-
Notifications
You must be signed in to change notification settings - Fork 77
Expand file tree
/
Copy pathExpressionExtensions.cs
More file actions
423 lines (371 loc) · 17.4 KB
/
ExpressionExtensions.cs
File metadata and controls
423 lines (371 loc) · 17.4 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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using static Microsoft.JavaScript.NodeApi.DotNetHost.JSMarshaller;
namespace Microsoft.JavaScript.NodeApi.Generator;
/// <summary>
/// Extension method for generating C# code from expressions.
/// </summary>
internal static class ExpressionExtensions
{
/// <summary>
/// Converts a lambda expression to C# code.
/// </summary>
/// <remarks>
/// This supports just enough expression types to handle generating C# code for lambda
/// expressions constructed by <see cref="Microsoft.JavaScript.NodeApi.DotNetHost.JSMarsaler" />.
/// </remarks>
/// <exception cref="NotImplementedException">Thrown if expression includes a node type
/// for which C# conversion is not implemented.</exception>
public static string ToCS(this LambdaExpression expression)
=> ToCS(
expression,
path: expression.Name ?? string.Empty,
variables: null);
/// <summary>
/// Recursively traverses an expression tree and builds C# code from the expressions.
/// </summary>
/// <param name="expression">The current expression node.</param>
/// <param name="path">Tracks the path from the root to the current node, for use in error
/// messages.</param>
/// <param name="variables">Tracks which variables have been declared; enables declaring
/// variables on first assignment rather than at the beginning of the block.</param>
/// <returns>Generated C# code string.</returns>
private static string ToCS(
Expression expression,
string path,
HashSet<string>? variables)
{
path += "/" + expression?.NodeType.ToString() ?? string.Empty;
return expression switch
{
null => throw new ArgumentNullException(
nameof(expression), $"Missing expression at {path}"),
LambdaExpression lambda =>
// Format as either a method or a lambda depending on whether this node
// is inside a block (where variables have been defined).
(variables is null ? FormatType(lambda.ReturnType) + " " + lambda.Name + "(" +
string.Join(", ", lambda.Parameters.Select((p) => p.ToCS())) + ")\n" :
"(" + string.Join(", ", lambda.Parameters.Select((p) => p.ToCS())) + ") =>\n") +
ToCS(lambda.Body, path, [.. (variables ?? Enumerable.Empty<string>()).Union(
lambda.Parameters.Select((p) => p.Name!))]),
ParameterExpression parameter =>
(parameter.IsByRef && parameter.Name?.StartsWith(OutParameterPrefix) == true) ?
parameter.Name.Substring(OutParameterPrefix.Length) : parameter.Name ?? "_",
BlockExpression block => FormatBlock(block, path, variables),
ConstantExpression constant => constant.Type == typeof(Type) ?
$"typeof({FormatType((Type)constant.Value!)})" :
constant.Type == typeof(bool) ? constant.ToString().ToLowerInvariant() :
constant.ToString(),
DefaultExpression defaultExpression => "default",
UnaryExpression { NodeType: ExpressionType.TypeAs } cast =>
ToCS(cast.Operand, path, variables) + " as " + FormatType(cast.Type),
UnaryExpression { NodeType: ExpressionType.Convert } cast =>
"(" + FormatType(cast.Type) + ")" + WithParentheses(cast.Operand, path, variables),
BinaryExpression binary =>
ToCS(binary.Left, path, variables) +
binary.NodeType switch
{
ExpressionType.Assign => " = ",
ExpressionType.Equal => " == ",
ExpressionType.NotEqual => " == ",
ExpressionType.Coalesce => " ??\n",
_ => throw new NotImplementedException(
$"Binary operator not implemented: {binary.NodeType} at {path}")
} +
ToCS(binary.Right, path, variables),
ConditionalExpression conditional =>
// If type is void then it's an if/then(/else), otherwise it's a ternary expression.
conditional.Type == typeof(void)
? "if (" + ToCS(conditional.Test, path, variables) +
") { " + ToCS(conditional.IfTrue, path, variables) + "; }" +
(conditional.IfFalse is DefaultExpression ? string.Empty :
" else { " + ToCS(conditional.IfFalse, path, variables) + "; }")
: '(' + ToCS(conditional.Test, path, variables) + " ?\n" +
ToCS(conditional.IfTrue, path, variables) + " :\n" +
ToCS(conditional.IfFalse, path, variables) + ')',
MemberExpression { NodeType: ExpressionType.MemberAccess } member =>
member.Expression is ParameterExpression parameterExpression &&
parameterExpression.Name == "this" ? member.Member.Name :
(member.Expression != null ? WithParentheses(member.Expression, path, variables) :
member.Member.DeclaringType!.FullName) + "." + member.Member.Name,
MethodCallExpression { Method.Name: "op_Explicit" or "op_Implicit" } cast =>
"(" + FormatType(cast.Method.ReturnType) + ")" +
WithParentheses(cast.Arguments[0], path, variables),
MethodCallExpression { Method.Name: "get_Item" } index =>
WithParentheses(index.Object!, path, variables) +
"[" + ToCS(index.Arguments[0], path, variables) + "]",
MethodCallExpression { Method.IsSpecialName: true } call =>
call.Method.Name == "get_Item" && call.Arguments.Count >= 1 ?
WithParentheses(call.Object!, path, variables) +
FormatArgs(call.Arguments, path, variables, "[]") :
call.Method.Name == "set_Item" && call.Arguments.Count >= 2 ?
WithParentheses(call.Object!, path, variables) + FormatArgs(
call.Arguments.Take(call.Arguments.Count - 1), path, variables, "[]") +
" = " + ToCS(call.Arguments.Last(), path, variables) :
#if !STRING_AS_SPAN
call.Method.Name.StartsWith("get_") ?
(call.Method.IsStatic ?
FormatType(call.Method.DeclaringType!) +
"." + call.Method.Name.Substring(4):
WithParentheses(call.Object!, path, variables) +
"." + call.Method.Name.Substring(4)) :
call.Method.Name.StartsWith("set_") ?
(call.Method.IsStatic ?
FormatType(call.Method.DeclaringType!) +
"." + call.Method.Name.Substring(4) :
WithParentheses(call.Object!, path, variables) +
"." + call.Method.Name.Substring(4)) +
" = " + ToCS(call.Arguments.Single(), path, variables) :
#else
call.Method.Name.StartsWith("get_") ?
(call.Method.IsStatic ?
string.Concat(FormatType(call.Method.DeclaringType!),
".", call.Method.Name.AsSpan(4)) :
string.Concat(WithParentheses(call.Object!, path, variables),
".", call.Method.Name.AsSpan(4))) :
call.Method.Name.StartsWith("set_") ?
(call.Method.IsStatic ?
string.Concat(FormatType(call.Method.DeclaringType!),
".", call.Method.Name.AsSpan(4)) :
string.Concat(WithParentheses(call.Object!, path, variables),
".", call.Method.Name.AsSpan(4))) +
" = " + ToCS(call.Arguments.Single(), path, variables) :
#endif
throw new NotImplementedException("Special method not implemented: " + call.Method),
MethodCallExpression call =>
call.Method.IsStatic && call.Method.IsDefined(typeof(ExtensionAttribute), false)
? WithParentheses(call.Arguments.First(), path, variables) +
"." + call.Method.Name +
FormatArgs(call.Method, call.Arguments.Skip(1), path, variables) :
call.Method.IsStatic
? FormatType(call.Method.DeclaringType!) + "." + call.Method.Name +
FormatArgs(call.Method, call.Arguments, path, variables)
: WithParentheses(call.Object!, path, variables) + "." + call.Method.Name +
FormatArgs(call.Method, call.Arguments, path, variables),
IndexExpression { Object: not null, Arguments.Count: 1 } index =>
ToCS(index.Object, path, variables) +
"[" + ToCS(index.Arguments[0], path, variables) + "]",
InvocationExpression invocation =>
((LambdaExpression)invocation.Expression).Name +
FormatArgs(invocation.Arguments, path, variables),
NewExpression construction =>
"new " + FormatType(construction.Type) +
FormatArgs(construction.Arguments, path, variables),
NewArrayExpression { NodeType: ExpressionType.NewArrayBounds } newArray =>
newArray.Type.GetElementType()!.IsArray ?
"new " + FormatType(newArray.Type.GetElementType()!.GetElementType()!) +
"[" + ToCS(newArray.Expressions.Single(), path, variables) + "][]" :
"new " + FormatType(newArray.Type.GetElementType()!) +
"[" + ToCS(newArray.Expressions.Single(), path, variables) + "]",
NewArrayExpression { NodeType: ExpressionType.NewArrayInit } newArray =>
"new " + FormatType(newArray.Type.GetElementType()!) + "[] { " +
string.Join(", ", newArray.Expressions.Select((a) => ToCS(a, path, variables))) +
" }",
GotoExpression { Kind: GotoExpressionKind.Return } gotoExpression =>
"return " + ToCS(gotoExpression.Value!, path, variables),
LabelExpression label => label.DefaultValue != null ?
ToCS(label.DefaultValue, path, variables) : "???",
MemberInitExpression init => "new " + FormatType(init.Type) + "\n{\n" +
string.Concat(init.Bindings.Select((b) => b.Member.Name + " = " +
ToCS(((MemberAssignment)b).Expression, path, variables) + ",\n")) +
"}",
_ => throw new NotImplementedException(
"Expression type not implemented: " +
$"{expression.GetType().Name} ({expression.NodeType}) at {path}"),
};
}
private static string ToCS(this ParameterExpression parameter)
{
string prefix = string.Empty;
string type = FormatType(parameter.Type);
string name = parameter.Name ?? "_";
if (parameter.IsByRef)
{
if (name.StartsWith(OutParameterPrefix))
{
prefix = "out ";
name = name.Substring(OutParameterPrefix.Length);
}
else
{
prefix = "ref ";
}
}
return $"{prefix}{type} {name}";
}
private static string WithParentheses(
Expression expression,
string path,
HashSet<string>? variables)
{
string cs = ToCS(expression, path, variables);
if (cs.StartsWith('(') &&
(expression.NodeType == ExpressionType.TypeAs ||
expression.NodeType == ExpressionType.Convert ||
expression.NodeType == ExpressionType.Call ||
expression.NodeType == ExpressionType.MemberAccess ||
expression.NodeType == ExpressionType.Lambda))
{
// Wrap extra parentheses around casts when needed.
cs = $"({cs})";
}
return cs;
}
private static string FormatBlock(
BlockExpression block,
string path,
HashSet<string>? variables)
{
StringBuilder s = new();
s.Append("{\n");
variables ??= new HashSet<string>();
for (int i = 0; i < block.Expressions.Count; i++)
{
bool isReturn = i == block.Expressions.Count - 1 && block.Type != typeof(void);
string statement = FormatStatement(
block.Expressions[i], isReturn, path, ref variables);
s.Append(statement + '\n');
}
s.Append('}');
return s.ToString();
}
private static string FormatStatement(
Expression expression, bool isReturn, string path, ref HashSet<string> variables)
{
string s = string.Empty;
if (expression.NodeType == ExpressionType.Assign)
{
BinaryExpression assignment = (BinaryExpression)expression;
if (assignment.Left is ParameterExpression variable &&
!variables.Contains(variable.Name!))
{
variables = [.. variables.Union(new[] { variable.Name! })];
s += FormatType(variable.Type) + " " + s;
}
}
s += ToCS(expression, path, variables);
if (!s.EndsWith('}') ||
(expression.NodeType == ExpressionType.Assign &&
((BinaryExpression)expression).Right.NodeType == ExpressionType.MemberInit))
{
s += ';';
}
if (isReturn)
{
s = "return " + s;
}
return s;
}
internal static string FormatType(Type type)
{
if (string.IsNullOrEmpty(type.Name))
{
return "(anonymous)";
}
else if (type.IsGenericParameter)
{
return type.Name;
}
else if (type.IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return FormatType(type.GetGenericArguments()[0]) + "?";
}
string typeArgs = string.Join(", ", type.GenericTypeArguments.Select(FormatType));
if (type.IsNested)
{
if (type.GenericTypeArguments.Length == 0)
{
// Nested type may be generic with 0 type args if the declaring type is generic.
return $"{FormatType(type.DeclaringType!)}.{type.Name}";
}
else
{
return $"{FormatType(type.DeclaringType!)}.{type.Name}<{typeArgs}>";
}
}
else
{
string nsPrefix = type.Namespace != null ? type.Namespace + "." : string.Empty;
return $"{nsPrefix}{type.Name.Substring(0, type.Name.IndexOf('`'))}<{typeArgs}>";
}
}
else if (type.IsNested)
{
return $"{FormatType(type.DeclaringType!)}.{type.Name}";
}
else if (type.IsArray)
{
Type elementType = type.GetElementType()!;
return FormatType(elementType) + "[]";
}
else if (type.IsPrimitive)
{
switch (type.Name)
{
case nameof(Boolean): return "bool";
case nameof(SByte): return "sbyte";
case nameof(Byte): return "byte";
case nameof(Int16): return "short";
case nameof(UInt16): return "ushort";
case nameof(Int32): return "int";
case nameof(UInt32): return "uint";
case nameof(Int64): return "long";
case nameof(UInt64): return "ulong";
case nameof(IntPtr): return "nint";
case nameof(UIntPtr): return "nuint";
case nameof(Single): return "float";
case nameof(Double): return "double";
}
}
else if (type == typeof(string))
{
return "string";
}
else if (type == typeof(object))
{
return "object";
}
else if (type == typeof(void))
{
return "void";
}
return type.FullName!;
}
private static string FormatArgs(
MethodInfo method,
IEnumerable<Expression> arguments,
string path,
HashSet<string>? variables)
{
string genericPrefix = (method.IsGenericMethod
? "<" + string.Join(", ", method.GetGenericArguments().Select(FormatType)) + ">"
: string.Empty);
ParameterInfo[] parameters = method.GetParameters();
if (method.IsStatic && method.IsDefined(typeof(ExtensionAttribute), false))
{
parameters = parameters.Skip(1).ToArray();
}
string args = string.Join(", ", arguments.Zip(parameters, (a, p) =>
(p.IsOut ? (p.IsIn ? "ref " : "out ") : string.Empty) + ToCS(a, path, variables)));
return $"{genericPrefix}({args})";
}
private static string FormatArgs(
IEnumerable<Expression> arguments,
string path,
HashSet<string>? variables,
string brackets = "()")
{
char start = brackets[0];
char end = brackets[1];
return start + string.Join(", ", arguments.Select((a) => ToCS(a, path, variables))) + end;
}
}