-
-
Notifications
You must be signed in to change notification settings - Fork 244
Expand file tree
/
Copy pathExpressionHelper.cs
More file actions
593 lines (489 loc) · 20.6 KB
/
ExpressionHelper.cs
File metadata and controls
593 lines (489 loc) · 20.6 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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq.Dynamic.Core.Validation;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Linq.Dynamic.Core.Parser;
internal class ExpressionHelper : IExpressionHelper
{
private static readonly Expression _nullExpression = Expression.Constant(null);
private readonly IConstantExpressionWrapper _constantExpressionWrapper = new ConstantExpressionWrapper();
private readonly ParsingConfig _parsingConfig;
internal ExpressionHelper(ParsingConfig parsingConfig)
{
_parsingConfig = Check.NotNull(parsingConfig);
}
public void WrapConstantExpression(ref Expression argument)
{
if (_parsingConfig.UseParameterizedNamesInDynamicQuery)
{
_constantExpressionWrapper.Wrap(ref argument);
}
}
public bool TryUnwrapAsValue<TValue>(Expression? expression, [NotNullWhen(true)] out TValue? value)
{
if (_parsingConfig.UseParameterizedNamesInDynamicQuery && _constantExpressionWrapper.TryUnwrapAsValue(expression as MemberExpression, out value))
{
return true;
}
value = default;
return false;
}
public bool TryUnwrapAsConstantExpression<TValue>(Expression? expression, [NotNullWhen(true)] out ConstantExpression? value)
{
if (_parsingConfig.UseParameterizedNamesInDynamicQuery && _constantExpressionWrapper.TryUnwrapAsConstantExpression<TValue>(expression as MemberExpression, out value))
{
return true;
}
value = null;
return false;
}
public bool TryUnwrapAsConstantExpression(Expression? expression, [NotNullWhen(true)] out ConstantExpression? value)
{
if (!_parsingConfig.UseParameterizedNamesInDynamicQuery || expression is not MemberExpression memberExpression)
{
value = null;
return false;
}
if
(
_constantExpressionWrapper.TryUnwrapAsConstantExpression<string>(memberExpression, out value) ||
_constantExpressionWrapper.TryUnwrapAsConstantExpression<int>(memberExpression, out value) ||
_constantExpressionWrapper.TryUnwrapAsConstantExpression<long>(memberExpression, out value) ||
_constantExpressionWrapper.TryUnwrapAsConstantExpression<short>(memberExpression, out value)
)
{
return true;
}
value = null;
return false;
}
public bool ConvertNumericTypeToBiggestCommonTypeForBinaryOperator(ref Expression left, ref Expression right)
{
if (left.Type == right.Type)
{
return true;
}
if (left.Type == typeof(ulong) || right.Type == typeof(ulong))
{
right = right.Type != typeof(ulong) ? Expression.Convert(right, typeof(ulong)) : right;
left = left.Type != typeof(ulong) ? Expression.Convert(left, typeof(ulong)) : left;
}
else if (left.Type == typeof(long) || right.Type == typeof(long))
{
right = right.Type != typeof(long) ? Expression.Convert(right, typeof(long)) : right;
left = left.Type != typeof(long) ? Expression.Convert(left, typeof(long)) : left;
}
else if (left.Type == typeof(uint) || right.Type == typeof(uint))
{
right = right.Type != typeof(uint) ? Expression.Convert(right, typeof(uint)) : right;
left = left.Type != typeof(uint) ? Expression.Convert(left, typeof(uint)) : left;
}
else if (left.Type == typeof(int) || right.Type == typeof(int))
{
right = right.Type != typeof(int) ? Expression.Convert(right, typeof(int)) : right;
left = left.Type != typeof(int) ? Expression.Convert(left, typeof(int)) : left;
}
else if (left.Type == typeof(ushort) || right.Type == typeof(ushort))
{
right = right.Type != typeof(ushort) ? Expression.Convert(right, typeof(ushort)) : right;
left = left.Type != typeof(ushort) ? Expression.Convert(left, typeof(ushort)) : left;
}
else if (left.Type == typeof(short) || right.Type == typeof(short))
{
right = right.Type != typeof(short) ? Expression.Convert(right, typeof(short)) : right;
left = left.Type != typeof(short) ? Expression.Convert(left, typeof(short)) : left;
}
else if (left.Type == typeof(byte) || right.Type == typeof(byte))
{
right = right.Type != typeof(byte) ? Expression.Convert(right, typeof(byte)) : right;
left = left.Type != typeof(byte) ? Expression.Convert(left, typeof(byte)) : left;
}
return false;
}
public Expression GenerateAdd(Expression left, Expression right)
{
return Expression.Add(left, right);
}
public Expression GenerateStringConcat(Expression left, Expression right)
{
return GenerateStaticMethodCall("Concat", left, right);
}
public Expression GenerateSubtract(Expression left, Expression right)
{
return Expression.Subtract(left, right);
}
public Expression GenerateEqual(Expression left, Expression right)
{
OptimizeForEqualityIfPossible(ref left, ref right);
TryConvertTypes(ref left, ref right);
WrapConstantExpressions(ref left, ref right);
return Expression.Equal(left, right);
}
public Expression GenerateNotEqual(Expression left, Expression right)
{
OptimizeForEqualityIfPossible(ref left, ref right);
TryConvertTypes(ref left, ref right);
WrapConstantExpressions(ref left, ref right);
return Expression.NotEqual(left, right);
}
public Expression GenerateGreaterThan(Expression left, Expression right)
{
TryConvertTypes(ref left, ref right);
if (left.Type == typeof(string))
{
return Expression.GreaterThan(GenerateStaticMethodCall(nameof(string.Compare), left, right), Expression.Constant(0));
}
if (left.Type.GetTypeInfo().IsEnum || right.Type.GetTypeInfo().IsEnum)
{
var leftPart = left.Type.GetTypeInfo().IsEnum ? Expression.Convert(left, Enum.GetUnderlyingType(left.Type)) : left;
var rightPart = right.Type.GetTypeInfo().IsEnum ? Expression.Convert(right, Enum.GetUnderlyingType(right.Type)) : right;
return Expression.GreaterThan(leftPart, rightPart);
}
WrapConstantExpressions(ref left, ref right);
return Expression.GreaterThan(left, right);
}
public Expression GenerateGreaterThanEqual(Expression left, Expression right)
{
TryConvertTypes(ref left, ref right);
if (left.Type == typeof(string))
{
return Expression.GreaterThanOrEqual(GenerateStaticMethodCall(nameof(string.Compare), left, right), Expression.Constant(0));
}
if (left.Type.GetTypeInfo().IsEnum || right.Type.GetTypeInfo().IsEnum)
{
return Expression.GreaterThanOrEqual(
left.Type.GetTypeInfo().IsEnum ? Expression.Convert(left, Enum.GetUnderlyingType(left.Type)) : left,
right.Type.GetTypeInfo().IsEnum ? Expression.Convert(right, Enum.GetUnderlyingType(right.Type)) : right
);
}
WrapConstantExpressions(ref left, ref right);
return Expression.GreaterThanOrEqual(left, right);
}
public Expression GenerateLessThan(Expression left, Expression right)
{
TryConvertTypes(ref left, ref right);
if (left.Type == typeof(string))
{
return Expression.LessThan(GenerateStaticMethodCall(nameof(string.Compare), left, right), Expression.Constant(0));
}
if (left.Type.GetTypeInfo().IsEnum || right.Type.GetTypeInfo().IsEnum)
{
return Expression.LessThan(
left.Type.GetTypeInfo().IsEnum ? Expression.Convert(left, Enum.GetUnderlyingType(left.Type)) : left,
right.Type.GetTypeInfo().IsEnum ? Expression.Convert(right, Enum.GetUnderlyingType(right.Type)) : right
);
}
WrapConstantExpressions(ref left, ref right);
return Expression.LessThan(left, right);
}
public Expression GenerateLessThanEqual(Expression left, Expression right)
{
TryConvertTypes(ref left, ref right);
if (left.Type == typeof(string))
{
return Expression.LessThanOrEqual(GenerateStaticMethodCall(nameof(string.Compare), left, right), Expression.Constant(0));
}
if (left.Type.GetTypeInfo().IsEnum || right.Type.GetTypeInfo().IsEnum)
{
return Expression.LessThanOrEqual(
left.Type.GetTypeInfo().IsEnum ? Expression.Convert(left, Enum.GetUnderlyingType(left.Type)) : left,
right.Type.GetTypeInfo().IsEnum ? Expression.Convert(right, Enum.GetUnderlyingType(right.Type)) : right
);
}
WrapConstantExpressions(ref left, ref right);
return Expression.LessThanOrEqual(left, right);
}
public void OptimizeForEqualityIfPossible(ref Expression left, ref Expression right)
{
// The goal here is to provide the way to convert some types from the string form in a way that is compatible with Linq to Entities.
// The Expression.Call(typeof(Guid).GetMethod("Parse"), right); does the job only for Linq to Object but Linq to Entities.
Type leftType = left.Type;
Type rightType = right.Type;
if (rightType == typeof(string) && right.NodeType == ExpressionType.Constant)
{
right = OptimizeStringForEqualityIfPossible((string?)((ConstantExpression)right).Value, leftType) ?? right;
}
if (leftType == typeof(string) && left.NodeType == ExpressionType.Constant)
{
left = OptimizeStringForEqualityIfPossible((string?)((ConstantExpression)left).Value, rightType) ?? left;
}
}
public Expression? OptimizeStringForEqualityIfPossible(string? text, Type type)
{
if (type == typeof(DateTime) && DateTime.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dateTime))
{
return Expression.Constant(dateTime, typeof(DateTime));
}
#if NET6_0_OR_GREATER
if (type == typeof(DateOnly) && DateOnly.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out var dateOnly))
{
return Expression.Constant(dateOnly, typeof(DateOnly));
}
if (type == typeof(TimeOnly) && TimeOnly.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.None, out var timeOnly))
{
return Expression.Constant(timeOnly, typeof(TimeOnly));
}
#endif
#if !NET35
if (type == typeof(Guid) && Guid.TryParse(text, out var guid))
{
return Expression.Constant(guid, typeof(Guid));
}
#else
try
{
return Expression.Constant(new Guid(text!));
}
catch
{
// Doing it in old fashion way when no TryParse interface was provided by .NET
}
#endif
return null;
}
public bool MemberExpressionIsDynamic(Expression expression)
{
#if NET35
return false;
#else
return expression is MemberExpression memberExpression && memberExpression.Member.GetCustomAttribute<DynamicAttribute>() != null;
#endif
}
public Expression ConvertToExpandoObjectAndCreateDynamicExpression(Expression expression, Type type, string propertyName)
{
#if !NET35 && !UAP10_0 && !NETSTANDARD1_3
return Expression.Dynamic(new DynamicGetMemberBinder(propertyName, _parsingConfig), type, expression);
#else
throw new NotSupportedException(Res.DynamicExpandoObjectIsNotSupported);
#endif
}
private void WrapConstantExpressions(ref Expression left, ref Expression right)
{
if (_parsingConfig.UseParameterizedNamesInDynamicQuery)
{
_constantExpressionWrapper.Wrap(ref left);
_constantExpressionWrapper.Wrap(ref right);
}
}
public bool TryGenerateAndAlsoNotNullExpression(Expression sourceExpression, bool addSelf, out Expression generatedExpression)
{
var expressions = CollectExpressions(addSelf, sourceExpression);
if (expressions.Count == 1 && expressions[0] is not MethodCallExpression)
{
generatedExpression = sourceExpression;
return false;
}
// Reverse the list
expressions.Reverse();
// Convert all expressions into '!= null' expressions (only if the type can be null)
var binaryExpressions = expressions
.Where(expression => TypeHelper.TypeCanBeNull(expression.Type))
.Select(expression => Expression.NotEqual(expression, _nullExpression))
.ToArray();
// Convert all binary expressions into `AndAlso(...)`
generatedExpression = binaryExpressions[0];
for (int i = 1; i < binaryExpressions.Length; i++)
{
generatedExpression = Expression.AndAlso(generatedExpression, binaryExpressions[i]);
}
return true;
}
public bool ExpressionQualifiesForNullPropagation(Expression? expression)
{
return expression is MemberExpression or ParameterExpression or MethodCallExpression or UnaryExpression;
}
public Expression GenerateDefaultExpression(Type type)
{
#if NET35
if (type.IsValueType)
{
return Expression.Constant(Activator.CreateInstance(type), type);
}
return Expression.Constant(null, type);
#else
return Expression.Default(type);
#endif
}
public Expression ConvertAnyArrayToObjectArray(Expression arrayExpression)
{
Check.NotNull(arrayExpression);
return Expression.Call(
null,
typeof(ExpressionHelper).GetMethod(nameof(ConvertIfIEnumerableHasValues), BindingFlags.Static | BindingFlags.NonPublic)!,
arrayExpression
);
}
/// <inheritdoc/>
public bool TryConvertTypes(ref Expression left, ref Expression right)
{
if (!_parsingConfig.ConvertObjectToSupportComparison || left.Type == right.Type || Constants.IsNull(left) || Constants.IsNull(right))
{
return false;
}
if (left.Type == typeof(object))
{
if (TryGetAsIndexerExpression(left, out var ce))
{
var rightTypeAsNullableType = TypeHelper.GetNullableType(right.Type);
right = Expression.Convert(right, rightTypeAsNullableType);
left = Expression.Condition(
ce.Test,
Expression.Convert(ce.IfTrue, rightTypeAsNullableType),
Expression.Convert(_nullExpression, rightTypeAsNullableType)
);
return true;
}
left = Expression.Condition(
Expression.Equal(left, _nullExpression),
GenerateDefaultExpression(right.Type),
Expression.Convert(left, right.Type)
);
}
else if (right.Type == typeof(object))
{
if (TryGetAsIndexerExpression(right, out var ce))
{
var leftTypeAsNullableType = TypeHelper.GetNullableType(left.Type);
left = Expression.Convert(left, leftTypeAsNullableType);
right = Expression.Condition(
ce.Test,
Expression.Convert(ce.IfTrue, leftTypeAsNullableType),
Expression.Convert(_nullExpression, leftTypeAsNullableType)
);
return true;
}
right = Expression.Condition(
Expression.Equal(right, _nullExpression),
GenerateDefaultExpression(left.Type),
Expression.Convert(right, left.Type)
);
}
return true;
}
private Expression? GetMemberExpression(Expression? expression)
{
if (ExpressionQualifiesForNullPropagation(expression))
{
return expression;
}
if (expression is LambdaExpression lambdaExpression)
{
if (lambdaExpression.Body is MemberExpression bodyAsMemberExpression)
{
return bodyAsMemberExpression;
}
if (lambdaExpression.Body is UnaryExpression bodyAsUnaryExpression)
{
return bodyAsUnaryExpression.Operand;
}
}
return null;
}
private List<Expression> CollectExpressions(bool addSelf, Expression sourceExpression)
{
var expression = GetMemberExpression(sourceExpression);
var list = new List<Expression>();
if (addSelf)
{
switch (expression)
{
case MemberExpression:
list.Add(sourceExpression);
break;
// ReSharper disable once RedundantEmptySwitchSection
default:
break;
}
}
bool expressionRecognized;
do
{
switch (expression)
{
case MemberExpression memberExpression:
expression = GetMemberExpression(memberExpression.Expression);
expressionRecognized = expression != null;
break;
case MethodCallExpression methodCallExpression:
expression = GetMethodCallExpression(methodCallExpression);
expressionRecognized = expression != null;
break;
case UnaryExpression unaryExpression:
expression = GetUnaryExpression(unaryExpression);
expressionRecognized = expression != null;
break;
default:
expressionRecognized = false;
break;
}
if (expressionRecognized && ExpressionQualifiesForNullPropagation(expression))
{
list.Add(expression!);
}
} while (expressionRecognized);
return list;
}
private static Expression GenerateStaticMethodCall(string methodName, Expression left, Expression right)
{
if (!TryGetStaticMethod(methodName, left, right, out var methodInfo))
{
throw new ArgumentException($"Method '{methodName}' not found on type '{left.Type}' or '{right.Type}'");
}
var parameters = methodInfo.GetParameters();
var parameterTypeLeft = parameters[0].ParameterType;
var parameterTypeRight = parameters[1].ParameterType;
if (parameterTypeLeft != left.Type && !Constants.IsNull(left))
{
left = Expression.Convert(left, parameterTypeLeft);
}
if (parameterTypeRight != right.Type && !Constants.IsNull(right))
{
right = Expression.Convert(right, parameterTypeRight);
}
return Expression.Call(null, methodInfo, left, right);
}
private static bool TryGetStaticMethod(string methodName, Expression left, Expression right, [NotNullWhen(true)] out MethodInfo? methodInfo)
{
methodInfo = left.Type.GetMethod(methodName, [left.Type, right.Type]) ?? right.Type.GetMethod(methodName, [left.Type, right.Type]);
return methodInfo != null;
}
private static Expression? GetMethodCallExpression(MethodCallExpression methodCallExpression)
{
if (methodCallExpression.Object != null)
{
// Something like: "np(FooValue.Zero().Length)"
return methodCallExpression.Object;
}
// Something like: "np(MyClasses.FirstOrDefault())"
return methodCallExpression.Arguments.FirstOrDefault();
}
private static Expression? GetUnaryExpression(UnaryExpression? unaryExpression)
{
return unaryExpression?.Operand;
}
private static object[] ConvertIfIEnumerableHasValues(IEnumerable? input)
{
// ReSharper disable once PossibleMultipleEnumeration
if (input != null && input.Cast<object>().Any())
{
// ReSharper disable once PossibleMultipleEnumeration
return input.Cast<object>().ToArray();
}
return [];
}
private static bool TryGetAsIndexerExpression(Expression expression, [NotNullWhen(true)] out ConditionalExpression? indexerExpresion)
{
indexerExpresion = expression as ConditionalExpression;
if (indexerExpresion == null)
{
return false;
}
return
indexerExpresion.IfTrue.ToString().Contains(DynamicClass.IndexerName) &&
indexerExpresion.Test.ToString().Contains("ContainsProperty");
}
}