-
-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathTypeHelper.cs
More file actions
324 lines (275 loc) · 12 KB
/
TypeHelper.cs
File metadata and controls
324 lines (275 loc) · 12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
using com.github.javaparser.ast.expr;
using com.github.javaparser.ast.type;
using JavaToCSharp.Expressions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Ast = com.github.javaparser.ast;
using Type = com.github.javaparser.ast.type.Type;
namespace JavaToCSharp;
public static class TypeHelper
{
private static readonly Dictionary<string, string> _typeNameConversions = new()
{
// Simple types
["boolean"] = "bool",
["Boolean"] = "bool",
["ICloseable"] = "IDisposable",
["Integer"] = "int",
["Long"] = "long",
["Float"] = "float",
["String"] = "string",
["Object"] = "object",
["AutoCloseable"] = "IDisposable",
// Generic types
["ArrayList"] = "List",
["List"] = "IList",
["Map"] = "Dictionary",
["Set"] = "HashSet",
["Iterator"] = "IEnumerator",
// Exceptions
["AlreadyClosedException"] = "ObjectDisposedException",
["Error"] = "Exception",
["IllegalArgumentException"] = "ArgumentException",
["IllegalStateException"] = "InvalidOperationException",
["UnsupportedOperationException"] = "NotSupportedException",
["RuntimeException"] = "Exception",
["AccessDeniedException"] = "UnauthorizedAccessException",
["AssertionError"] = "InvalidOperationException",
["NullPointerException"] = "NullReferenceException",
["UncheckedIOException"] = "IOException",
["EOFException"] = "EndOfStreamException",
["NoSuchFileException"] = "FileNotFoundException",
};
public static void AddOrUpdateTypeNameConversions(string key, string value)
{
_typeNameConversions[key] = value;
}
public static string ConvertTypeOf(Ast.nodeTypes.NodeWithType typedNode)
{
return ConvertType(typedNode.getType().toString());
}
public static string ConvertType(Type type)
{
return ConvertType(type.toString());
}
public static string ConvertType(string typeName)
=> TypeNameParser.ParseTypeName(typeName, s => _typeNameConversions.TryGetValue(s, out string? converted) ? converted : s);
public static TypeSyntax ConvertTypeSyntax(Type type, int arrayRank)
{
if (type is ArrayType arrayType)
{
if (arrayRank > 0 && arrayType.getArrayLevel() != arrayRank)
{
throw new ArgumentException("Given array rank does not match the array level of the type", nameof(arrayRank));
}
arrayRank = arrayType.getArrayLevel();
Type elementType;
while ((elementType = arrayType.getElementType()) is ArrayType nestedArrayType)
{
arrayType = nestedArrayType;
}
return ConvertTypeSyntax(elementType, arrayRank);
}
return arrayRank == 0
? SyntaxFactory.ParseTypeName(ConvertType(type))
: ConvertArrayTypeSyntax(type, arrayRank);
}
public static ArrayTypeSyntax ConvertArrayTypeSyntax(Type type, int arrayRank)
{
var rankSpecifiers = SyntaxFactory.ArrayRankSpecifier(
SyntaxFactory.SeparatedList<ExpressionSyntax>(
Enumerable.Repeat(SyntaxFactory.OmittedArraySizeExpression(), arrayRank)
));
return SyntaxFactory.ArrayType(ConvertTypeSyntax(type, 0))
.WithRankSpecifiers(SyntaxFactory.SingletonList(rankSpecifiers));
}
public static string Capitalize(string name)
{
var parts = name.Split('.');
var joined = string.Join(".", parts.Select(i =>
{
if (i.Length == 1)
return i.ToUpper();
else
return i[0].ToString().ToUpper() + i[1..];
}));
return joined;
}
public static string EscapeIdentifier(string name)
{
// @ (C# Reference): https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/verbatim
return name switch {
"string" or "ref" or "object" or "int" or "short" or "float" or "long" or "double" or "decimal" or "in" or
"out" or "byte" or "class" or "delegate" or "params" or "is" or "as" or "base" or "namespace" or "event" or
"lock" or "operator" or "override" => "@" + name,
_ => name,
};
}
public static string ReplaceCommonMethodNames(string name)
{
return name.ToLower() switch {
"hashcode" => "GetHashCode",
"getclass" => "GetType",
"close" => "Dispose",
_ => name,
};
}
public static TypeSyntax GetSyntaxFromType(ClassOrInterfaceType type)
{
string typeName = ConvertType(type.getNameAsString());
var typeArgs = type.getTypeArguments().FromOptional<Ast.NodeList>()?.ToList<Type>();
TypeSyntax typeSyntax;
if (typeArgs is { Count: > 0 })
{
typeSyntax = SyntaxFactory.GenericName(typeName)
.AddTypeArgumentListArguments(typeArgs.Select(t => SyntaxFactory.ParseTypeName(ConvertType(t))).ToArray());
}
else
{
typeSyntax = SyntaxFactory.ParseTypeName(typeName);
}
return typeSyntax;
}
public static ArgumentListSyntax GetSyntaxFromArguments(ConversionContext context, java.util.List args)
{
return SyntaxFactory.ArgumentList(GetSeparatedListFromArguments(context, args));
}
private static SeparatedSyntaxList<ArgumentSyntax> GetSeparatedListFromArguments(ConversionContext context, java.util.List args)
{
return GetSeparatedListFromArguments(context, args.OfType<Expression>());
}
private static SeparatedSyntaxList<ArgumentSyntax> GetSeparatedListFromArguments(ConversionContext context, IEnumerable<Expression> args)
{
var argSyntaxes = new List<ArgumentSyntax>();
foreach (var arg in args)
{
var argSyntax = ExpressionVisitor.VisitExpression(context, arg);
if (argSyntax is null)
{
continue;
}
argSyntaxes.Add(SyntaxFactory.Argument(argSyntax));
}
var separators = Enumerable.Repeat(SyntaxFactory.Token(SyntaxKind.CommaToken), argSyntaxes.Count - 1);
return SyntaxFactory.SeparatedList(argSyntaxes, separators);
}
/// <summary>
/// Returns the list of C# type parameter constraints that must be added to a class syntax
/// to convert the java bounded type parameters of a class declaration.
/// e.g. to convert <![CDATA[ <T extends Clazz<T>> ]]> into <![CDATA[ <T> where T : Clazz<T> ]]>
/// </summary>
public static IEnumerable<TypeParameterConstraintClauseSyntax> GetTypeParameterListConstraints(List<TypeParameter> typeParams)
{
var typeParameterConstraints = new List<TypeParameterConstraintClauseSyntax>();
foreach (TypeParameter typeParam in typeParams)
{
if (typeParam.getTypeBound().size() > 0)
{
var typeConstraintsSyntax = new SeparatedSyntaxList<TypeParameterConstraintSyntax>();
foreach (ClassOrInterfaceType bound in typeParam.getTypeBound())
{
typeConstraintsSyntax = typeConstraintsSyntax.Add(SyntaxFactory.TypeConstraint(SyntaxFactory.ParseTypeName(bound.asString())));
}
var typeIdentifier = SyntaxFactory.IdentifierName(typeParam.getName().asString());
var parameterConstraintClauseSyntax = SyntaxFactory.TypeParameterConstraintClause(typeIdentifier, typeConstraintsSyntax);
typeParameterConstraints.Add(parameterConstraintClauseSyntax);
}
}
return typeParameterConstraints;
}
/// <summary>
/// Transforms method calls into property and indexer accesses where appropriate.
/// </summary>
/// <param name="context">The conversion context.</param>
/// <param name="methodCallExpr">The <c>MethodCallExpr</c> to be transformed.</param>
/// <param name="transformedSyntax">The resulting transformed syntax.</param>
/// <returns><c>true</c> if the syntax was transformed, <c>false</c> otherwise</returns>
public static bool TryTransformMethodCall(ConversionContext context, MethodCallExpr methodCallExpr,
out ExpressionSyntax? transformedSyntax)
{
if (methodCallExpr.getScope().FromOptional<Expression>() is { } scope)
{
var methodName = methodCallExpr.getName();
var args = methodCallExpr.getArguments();
switch (methodName.getIdentifier())
{
case "length" when args.size() == 0:
{
var scopeSyntaxLength = ExpressionVisitor.VisitExpression(context, scope);
transformedSyntax = ReplaceMethodByProperty(scopeSyntaxLength, "Length");
return true;
}
case "size" when args.size() == 0:
{
var scopeSyntaxSize = ExpressionVisitor.VisitExpression(context, scope);
transformedSyntax = ReplaceMethodByProperty(scopeSyntaxSize, "Count");
return true;
}
case "get" when args.size() == 1:
{
var scopeSyntaxGet = ExpressionVisitor.VisitExpression(context, scope);
if (scopeSyntaxGet is null)
{
transformedSyntax = null;
return false;
}
transformedSyntax = ReplaceGetByIndexAccess(context, scopeSyntaxGet, args);
return true;
}
case "set" when args.size() == 2:
{
var scopeSyntaxSet = ExpressionVisitor.VisitExpression(context, scope);
if (scopeSyntaxSet is null)
{
transformedSyntax = null;
return false;
}
transformedSyntax = ReplaceSetByIndexAccess(context, scopeSyntaxSet, args);
return true;
}
}
}
transformedSyntax = null;
return false;
static MemberAccessExpressionSyntax? ReplaceMethodByProperty(ExpressionSyntax? scopeSyntax, string identifier)
{
if (scopeSyntax is null)
{
return null;
}
// Replace expr.Size() by expr.Count
return SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
scopeSyntax,
SyntaxFactory.IdentifierName(SyntaxFactory.Identifier(identifier)));
}
static ExpressionSyntax ReplaceGetByIndexAccess(ConversionContext context, ExpressionSyntax scopeSyntax,
java.util.List args)
{
// Replace expr.Get(i) by expr[i]
return SyntaxFactory.ElementAccessExpression(
scopeSyntax,
SyntaxFactory.BracketedArgumentList(GetSeparatedListFromArguments(context, args))
);
}
static ExpressionSyntax? ReplaceSetByIndexAccess(
ConversionContext context,
ExpressionSyntax scopeSyntax,
java.util.List args)
{
// Replace expr.Set(i,v) by expr[i] = v
var argsList = args.ToList<Expression>() ?? [];
var left = SyntaxFactory.ElementAccessExpression(
scopeSyntax,
SyntaxFactory.BracketedArgumentList(GetSeparatedListFromArguments(context, argsList.Take(1)))
).WithTrailingTrivia(SyntaxFactory.Whitespace(" "));
var right = ExpressionVisitor.VisitExpression(context, argsList[1])?.WithLeadingTrivia(SyntaxFactory.Whitespace(" "));
if (right is null)
{
return null;
}
return SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression, left, right);
}
}
}