Skip to content

Commit 09a0693

Browse files
committed
C# 14 code cleanup
1 parent 63ee854 commit 09a0693

52 files changed

Lines changed: 325 additions & 383 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎JavaToCSharp.Tests/CommentTests.cs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
using Microsoft.CodeAnalysis.CSharp;
21
using Xunit.Abstractions;
32

43
namespace JavaToCSharp.Tests;

‎JavaToCSharp.Tests/JavaToCSharp.Tests.csproj‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
<Nullable>enable</Nullable>
77
<LangVersion>latest</LangVersion>
88
<ImplicitUsings>enable</ImplicitUsings>
9-
<WarningsAsErrors>nullable</WarningsAsErrors>
9+
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
1010
</PropertyGroup>
1111

1212
<ItemGroup>
@@ -21,7 +21,6 @@
2121
<PrivateAssets>all</PrivateAssets>
2222
</PackageReference>
2323
<PackageReference Include="IKVM" Version="8.15.0" />
24-
<PackageReference Include="IKVM" Version="8.14.0" />
2524
</ItemGroup>
2625

2726
<ItemGroup>

‎JavaToCSharp/CommentsHelper.cs‎

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
using Microsoft.CodeAnalysis;
1+
using System.Text.RegularExpressions;
2+
using Microsoft.CodeAnalysis;
23
using Microsoft.CodeAnalysis.CSharp;
34
using Microsoft.CodeAnalysis.CSharp.Syntax;
45

56
using JavaAst = com.github.javaparser.ast;
67
using JavaComments = com.github.javaparser.ast.comments;
78
using JavaParser = com.github.javaparser;
8-
using SysRegex = System.Text.RegularExpressions;
99

1010
namespace JavaToCSharp;
1111

12-
public static class CommentsHelper
12+
public static partial class CommentsHelper
1313
{
1414
private enum CommentPosition
1515
{
@@ -18,8 +18,8 @@ private enum CommentPosition
1818
}
1919

2020
// Regex: Optional *, capture optional @par, capture optional text (keep leading whitespaces, trim end).
21-
private static readonly SysRegex.Regex _analyzeDocString =
22-
new(@"^(\s*\*)?(\s*(?<param>@[a-z]+))?\s?(?<text>.*?)\s*$", SysRegex.RegexOptions.Compiled);
21+
[GeneratedRegex(@"^(\s*\*)?(\s*(?<param>@[a-z]+))?\s?(?<text>.*?)\s*$", RegexOptions.Compiled)]
22+
private static partial Regex AnalyzeDocStringRegex { get; }
2323

2424
private static readonly Dictionary<string, string> _knownTagsDict = new()
2525
{
@@ -142,9 +142,14 @@ private static (SyntaxKind kind, string? pre, string? post) GetCommentInfo(
142142
private static List<(JavaComments.Comment c, CommentPosition pos)> GatherComments(JavaAst.Node? node)
143143
{
144144
var result = new List<(JavaComments.Comment c, CommentPosition pos)>();
145-
if (node == null) return result;
145+
146+
if (node is null)
147+
{
148+
return result;
149+
}
146150

147151
var parentNode = node.getParentNode().FromOptional<JavaAst.Node>();
152+
148153
if (parentNode is null)
149154
{
150155
if (node.getComment().FromOptional<JavaComments.Comment>() is { } comment)
@@ -155,6 +160,7 @@ private static (SyntaxKind kind, string? pre, string? post) GetCommentInfo(
155160
else
156161
{
157162
var unsortedComments = parentNode.getAllContainedComments();
163+
158164
if (unsortedComments.size() != 0)
159165
{
160166
var comments = unsortedComments.OfType<JavaComments.Comment>()
@@ -163,7 +169,7 @@ private static (SyntaxKind kind, string? pre, string? post) GetCommentInfo(
163169
.ToList();
164170

165171
// Find leading comments
166-
var nodeBegin = node.getBegin().FromOptional<JavaParser.Position>()
172+
var nodeBegin = node.getBegin().FromOptional<JavaParser.Position>()
167173
?? throw new InvalidOperationException("Node did not have a begin position");
168174
var previousSibling = GetPreviousSibling(parentNode, nodeBegin);
169175
int previousPos = previousSibling?.getEnd().FromOptional<JavaParser.Position>()?.line ?? 0;
@@ -173,7 +179,7 @@ private static (SyntaxKind kind, string? pre, string? post) GetCommentInfo(
173179
// Find trailing comments.
174180
// We consider only comments either appearing on the same line or, if no sibling nodes follow,
175181
// then also comments on the succeeding lines (because otherwise they belong to the next sibling).
176-
var nodeEnd = node.getEnd().FromOptional<JavaParser.Position>()
182+
var nodeEnd = node.getEnd().FromOptional<JavaParser.Position>()
177183
?? throw new InvalidOperationException("Node did not have an end position");
178184

179185
var trailingComments = HasNextSibling(parentNode, nodeEnd)
@@ -191,7 +197,7 @@ private static (SyntaxKind kind, string? pre, string? post) GetCommentInfo(
191197
comments.Where(c =>
192198
{
193199
var commentBegin = c.getBegin().FromOptional<JavaParser.Position>();
194-
return commentBegin != null && (commentBegin.line == nodeEnd.line && commentBegin.column > nodeEnd.column || commentBegin.line > nodeEnd.line);
200+
return commentBegin is not null && (commentBegin.line == nodeEnd.line && commentBegin.column > nodeEnd.column || commentBegin.line > nodeEnd.line);
195201
})
196202
.Select(c => (c, CommentPosition.Trailing));
197203

@@ -200,7 +206,7 @@ private static (SyntaxKind kind, string? pre, string? post) GetCommentInfo(
200206
.Where(c =>
201207
{
202208
var commentBegin = c.getBegin().FromOptional<JavaParser.Position>();
203-
return commentBegin != null && commentBegin.line == nodeEnd.line && commentBegin.column > nodeEnd.column;
209+
return commentBegin is not null && commentBegin.line == nodeEnd.line && commentBegin.column > nodeEnd.column;
204210
})
205211
.Select(c => (c, CommentPosition.Trailing));
206212

@@ -212,7 +218,7 @@ private static bool HasNextSibling(JavaAst.Node parentNode, JavaParser.Position
212218
.Any(sibling =>
213219
{
214220
var siblingBegin = sibling.getBegin().FromOptional<JavaParser.Position>();
215-
return siblingBegin != null && (siblingBegin.line > nodeEnd.line || siblingBegin.line == nodeEnd.line && siblingBegin.column > nodeEnd.column);
221+
return siblingBegin is not null && (siblingBegin.line > nodeEnd.line || siblingBegin.line == nodeEnd.line && siblingBegin.column > nodeEnd.column);
216222
});
217223
}
218224

@@ -222,7 +228,7 @@ private static bool HasNextSibling(JavaAst.Node parentNode, JavaParser.Position
222228
{
223229
var commentBegin = c.getBegin().FromOptional<JavaParser.Position>();
224230
var commentEnd = c.getEnd().FromOptional<JavaParser.Position>();
225-
return commentBegin != null && commentEnd != null && commentBegin.line > previousPos && (commentEnd.line < nodeBegin.line || commentEnd.line == nodeBegin.line && commentEnd.column < nodeBegin.column);
231+
return commentBegin is not null && commentEnd is not null && commentBegin.line > previousPos && (commentEnd.line < nodeBegin.line || commentEnd.line == nodeBegin.line && commentEnd.column < nodeBegin.column);
226232
})
227233
.Select(c => (c, CommentPosition.Leading));
228234
}
@@ -236,7 +242,7 @@ private static bool HasNextSibling(JavaAst.Node parentNode, JavaParser.Position
236242
.LastOrDefault(sibling =>
237243
{
238244
var siblingEnd = sibling.getEnd().FromOptional<JavaParser.Position>();
239-
return siblingEnd != null && (siblingEnd.line < nodeBegin.line || siblingEnd.line == nodeBegin.line && siblingEnd.column < nodeBegin.column);
245+
return siblingEnd is not null && (siblingEnd.line < nodeBegin.line || siblingEnd.line == nodeBegin.line && siblingEnd.column < nodeBegin.column);
240246
});
241247
}
242248

@@ -252,7 +258,7 @@ public static IEnumerable<SyntaxTrivia> ConvertToComment(IEnumerable<JavaAst.Nod
252258
var outputs = new List<string>();
253259
foreach (var code in codes)
254260
{
255-
string[] input = code.ToString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);
261+
string[] input = code.ToString().Split([Environment.NewLine], StringSplitOptions.None);
256262
outputs.AddRange(input);
257263
}
258264

@@ -277,14 +283,14 @@ public static IEnumerable<SyntaxTrivia> ConvertToComment(IEnumerable<JavaAst.Nod
277283

278284
private static IEnumerable<SyntaxTrivia> ConvertDocComment(JavaComments.Comment comment, string? post)
279285
{
280-
string[] input = comment.getContent().Split(new[] { Environment.NewLine }, StringSplitOptions.None);
286+
string[] input = comment.getContent().Split([Environment.NewLine], StringSplitOptions.None);
281287
var output = new List<string>();
282288
var remarks = new List<string>(); // For Java tags unknown in C#
283289
var currentOutput = output;
284290
string? tag = null;
285291
foreach (string inputLine in input)
286292
{
287-
var match = _analyzeDocString.Match(inputLine);
293+
var match = AnalyzeDocStringRegex.Match(inputLine);
288294
if (match.Success)
289295
{
290296
string paramName = match.Groups["param"].Value;
@@ -304,7 +310,7 @@ private static IEnumerable<SyntaxTrivia> ConvertDocComment(JavaComments.Comment
304310
remarks.Add(paramName + text);
305311
tag = "remarks";
306312
}
307-
else if (tag == null)
313+
else if (tag is null)
308314
{
309315
tag = "summary";
310316
OpenSection(output, tag, text);
@@ -358,14 +364,14 @@ private static void CloseSection(IList<string> output, string? tag)
358364
}
359365
else
360366
{
361-
output[output.Count - 1] += xmlEndTag;
367+
output[^1] += xmlEndTag;
362368
}
363369
}
364370
}
365371

366372
private static void TrimTrailingEmptyLines(IList<string> lines)
367373
{
368-
while (lines.Count > 0 && lines[lines.Count - 1].Trim() == "")
374+
while (lines.Count > 0 && lines[^1].Trim() == "")
369375
{
370376
lines.RemoveAt(lines.Count - 1);
371377
}
@@ -468,7 +474,7 @@ private static SyntaxNode AdjustBlockCommentIndentation(SyntaxNode node)
468474
if (t.IsKind(SyntaxKind.MultiLineCommentTrivia))
469475
{
470476
int indentation = GetIndentation(leading, i) + 1; // Add one to align stars.
471-
string[] lines = t.ToFullString().Split(new[] { Environment.NewLine }, StringSplitOptions.None);
477+
string[] lines = t.ToFullString().Split([Environment.NewLine], StringSplitOptions.None);
472478
string indentString = new(' ', indentation);
473479
for (int l = 1; l < lines.Length; l++)
474480
{

‎JavaToCSharp/ConversionContext.cs‎

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,14 @@
1-
using System.Collections.Generic;
2-
using Microsoft.CodeAnalysis.CSharp.Syntax;
1+
using Microsoft.CodeAnalysis.CSharp.Syntax;
32

43
namespace JavaToCSharp;
54

6-
public class ConversionContext
5+
public class ConversionContext(JavaConversionOptions options)
76
{
8-
public ConversionContext(JavaConversionOptions options)
9-
{
10-
PendingAnonymousTypes = new Queue<ClassDeclarationSyntax>();
11-
UsedAnonymousTypeNames = new HashSet<string>();
12-
Options = options;
13-
}
7+
public Queue<ClassDeclarationSyntax> PendingAnonymousTypes { get; } = new();
148

15-
public Queue<ClassDeclarationSyntax> PendingAnonymousTypes { get; }
9+
public ISet<string> UsedAnonymousTypeNames { get; } = new HashSet<string>();
1610

17-
public ISet<string> UsedAnonymousTypeNames { get; }
18-
19-
public JavaConversionOptions Options { get; }
11+
public JavaConversionOptions Options { get; } = options;
2012

2113
public string? RootTypeName { get; set; }
2214

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,6 @@
1-
using System;
1+
namespace JavaToCSharp;
22

3-
namespace JavaToCSharp;
4-
5-
public sealed class ConversionStateChangedEventArgs : EventArgs
3+
public sealed class ConversionStateChangedEventArgs(ConversionState newState) : EventArgs
64
{
7-
public ConversionStateChangedEventArgs(ConversionState newState)
8-
{
9-
NewState = newState;
10-
}
11-
12-
public ConversionState NewState { get; }
5+
public ConversionState NewState { get; } = newState;
136
}
Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,8 @@
1-
using System;
1+
namespace JavaToCSharp;
22

3-
namespace JavaToCSharp;
4-
5-
public class ConversionWarningEventArgs : EventArgs
3+
public class ConversionWarningEventArgs(string message, int javaLineNumber) : EventArgs
64
{
7-
public ConversionWarningEventArgs(string message, int javaLineNumber)
8-
{
9-
Message = message;
10-
JavaLineNumber = javaLineNumber;
11-
}
12-
13-
public string Message { get; }
5+
public string Message { get; } = message;
146

15-
public int JavaLineNumber { get; }
7+
public int JavaLineNumber { get; } = javaLineNumber;
168
}

‎JavaToCSharp/Declarations/AnnotationDeclarationVisitor.cs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using com.github.javaparser;
1+
using com.github.javaparser;
42
using com.github.javaparser.ast.body;
53
using com.github.javaparser.ast.type;
64
using Microsoft.CodeAnalysis.CSharp.Syntax;

‎JavaToCSharp/Declarations/BodyDeclarationVisitor.cs‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using System;
2-
using System.Collections.Generic;
3-
using com.github.javaparser.ast.body;
1+
using com.github.javaparser.ast.body;
42
using com.github.javaparser.ast.type;
53
using Microsoft.CodeAnalysis.CSharp.Syntax;
64
using Range = com.github.javaparser.Range;

‎JavaToCSharp/Declarations/ClassOrInterfaceDeclarationVisitor.cs‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
1-
using System.Collections.Generic;
2-
using System.Linq;
3-
using com.github.javaparser.ast;
1+
using com.github.javaparser.ast;
42
using com.github.javaparser.ast.body;
53
using com.github.javaparser.ast.expr;
64
using com.github.javaparser.ast.type;
@@ -71,7 +69,7 @@ public static InterfaceDeclarationSyntax VisitInterfaceDeclaration(ConversionCon
7169

7270
var extends = interfaceDecl.getExtendedTypes().ToList<ClassOrInterfaceType>();
7371

74-
if (extends != null)
72+
if (extends is not null)
7573
{
7674
foreach (var extend in extends)
7775
{
@@ -81,7 +79,7 @@ public static InterfaceDeclarationSyntax VisitInterfaceDeclaration(ConversionCon
8179

8280
var implements = interfaceDecl.getImplementedTypes().ToList<ClassOrInterfaceType>();
8381

84-
if (implements != null)
82+
if (implements is not null)
8583
{
8684
foreach (var implement in implements)
8785
{
@@ -98,7 +96,7 @@ public static InterfaceDeclarationSyntax VisitInterfaceDeclaration(ConversionCon
9896
var syntax = VisitBodyDeclarationForInterface(context, classSyntax, member);
9997
var memberWithComments = syntax?.WithJavaComments(context, member);
10098

101-
if (memberWithComments != null)
99+
if (memberWithComments is not null)
102100
{
103101
classSyntax = classSyntax.AddMembers(memberWithComments);
104102
}
@@ -144,14 +142,14 @@ public static ClassDeclarationSyntax VisitClassDeclaration(ConversionContext con
144142
if (mods.Contains(Modifier.Keyword.FINAL))
145143
classSyntax = classSyntax.AddModifiers(SyntaxFactory.Token(SyntaxKind.SealedKeyword));
146144

147-
var extends = classDecl.getExtendedTypes().ToList<ClassOrInterfaceType>() ?? new List<ClassOrInterfaceType>();
145+
var extends = classDecl.getExtendedTypes().ToList<ClassOrInterfaceType>() ?? [];
148146

149147
foreach (var extend in extends)
150148
{
151149
classSyntax = classSyntax.AddBaseListTypes(SyntaxFactory.SimpleBaseType(TypeHelper.GetSyntaxFromType(extend)));
152150
}
153151

154-
var implements = classDecl.getImplementedTypes().ToList<ClassOrInterfaceType>() ?? new List<ClassOrInterfaceType>();
152+
var implements = classDecl.getImplementedTypes().ToList<ClassOrInterfaceType>() ?? [];
155153

156154
foreach (var implement in implements)
157155
{
@@ -184,7 +182,7 @@ public static ClassDeclarationSyntax VisitClassDeclaration(ConversionContext con
184182
var syntax = VisitBodyDeclarationForClass(context, classSyntax, member, extends, implements);
185183
var withJavaComments = syntax?.WithJavaComments(context, member);
186184

187-
if (withJavaComments != null)
185+
if (withJavaComments is not null)
188186
{
189187
classSyntax = classSyntax.AddMembers(withJavaComments);
190188
}

‎JavaToCSharp/Declarations/ConstructorDeclarationVisitor.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ public class ConstructorDeclarationVisitor : BodyDeclarationVisitor<ConstructorD
7272
ArgumentListSyntax? argsSyntax = null;
7373

7474
var initArgs = ctorInvStmt.getArguments();
75-
if (initArgs != null && initArgs.size() > 0)
75+
if (initArgs is not null && initArgs.size() > 0)
7676
{
7777
argsSyntax = TypeHelper.GetSyntaxFromArguments(context, initArgs);
7878
}

0 commit comments

Comments
 (0)