Skip to content

Commit 905cd5b

Browse files
authored
C# 14 and code style updates (#141)
- Uses C# 14 features like extension blocks, and some older C# features - Converts the sln to the new slnx format - Turns on warnings as errors for all projects - Uses GeneratedRegexAttribute where Regex was used - Misc code cleanup
1 parent 4e9013c commit 905cd5b

File tree

59 files changed

+456
-454
lines changed

Some content is hidden

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

59 files changed

+456
-454
lines changed

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: 2 additions & 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>
@@ -26,7 +26,7 @@
2626
<ItemGroup>
2727
<ProjectReference Include="..\JavaToCSharp\JavaToCSharp.csproj" />
2828
</ItemGroup>
29-
29+
3030
<ItemGroup>
3131
<IkvmReference Include="../Lib/javaparser-core-3.25.4.jar" />
3232
</ItemGroup>

JavaToCSharp.sln

Lines changed: 0 additions & 55 deletions
This file was deleted.

JavaToCSharp.slnx

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
<Solution>
2+
<Folder Name="/Lib/">
3+
<File Path="Lib/javaparser-core-3.25.4.jar" />
4+
</Folder>
5+
<Folder Name="/Solution Items/">
6+
<File Path=".editorconfig" />
7+
</Folder>
8+
<Project Path="JavaToCSharp.Tests/JavaToCSharp.Tests.csproj" />
9+
<Project Path="JavaToCSharp/JavaToCSharp.csproj" />
10+
<Project Path="JavaToCSharpCli/JavaToCSharpCli.csproj" />
11+
<Project Path="JavaToCSharpGui/JavaToCSharpGui.csproj" />
12+
</Solution>
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
22
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateStaticReadonly/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb" /&gt;</s:String>
3+
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/UserRules/=15b5b1f1_002D457c_002D4ca6_002Db278_002D5615aedc07d3/@EntryIndexedValue">&lt;Policy&gt;&lt;Descriptor Staticness="Static" AccessRightKinds="Private" Description="Static readonly fields (private)"&gt;&lt;ElementKinds&gt;&lt;Kind Name="READONLY_FIELD" /&gt;&lt;/ElementKinds&gt;&lt;/Descriptor&gt;&lt;Policy Inspect="True" WarnAboutPrefixesAndSuffixes="False" Prefix="_" Suffix="" Style="aaBb" /&gt;&lt;/Policy&gt;</s:String>
4+
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EPredefinedNamingRulesToUserRulesUpgrade/@EntryIndexedValue">True</s:Boolean>
35
<s:Boolean x:Key="/Default/UserDictionary/Words/=Avalonia/@EntryIndexedValue">True</s:Boolean>
46
<s:Boolean x:Key="/Default/UserDictionary/Words/=Cascadia/@EntryIndexedValue">True</s:Boolean>
57
<s:Boolean x:Key="/Default/UserDictionary/Words/=initializers/@EntryIndexedValue">True</s:Boolean>

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;

0 commit comments

Comments
 (0)