forked from MapsterMapper/Mapster
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpressionEx.cs
More file actions
522 lines (451 loc) · 19.7 KB
/
ExpressionEx.cs
File metadata and controls
522 lines (451 loc) · 19.7 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
using Mapster.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
namespace Mapster.Utils
{
internal static class ExpressionEx
{
public static Expression Assign(Expression left, Expression right)
{
var middle = left.Type.IsReferenceAssignableFrom(right.Type)
? right
: Expression.Convert(right, left.Type);
return Expression.Assign(left, middle);
}
public static Expression PropertyOrFieldPath(Expression expr, string path)
{
Expression current = expr;
string[] props = path.Split('.');
for (int i = 0; i < props.Length; i++)
{
if (IsDictionaryKey(current, props[i], out Expression? next))
{
current = next;
continue;
}
if (IsPropertyOrField(current, props[i], out next))
{
current = next;
continue;
}
// For dynamically built types, it is possible to have periods in the property name.
// Rejoin an incrementing number of parts with periods to try and find a property match.
if (IsPropertyOrFieldPathWithPeriods(current, props, i, out next, out int combinationLength))
{
current = next;
i += combinationLength - 1;
continue;
}
throw new ArgumentException($"'{props[i]}' is not a member of type '{current.Type.FullName}'", nameof(path));
}
return current;
}
private static bool IsPropertyOrFieldPathWithPeriods(Expression expr, string[] path, int startIndex, out Expression? propExpr, out int combinationLength)
{
var remaining = path.Length - startIndex;
if (remaining < 2)
{
propExpr = null;
combinationLength = 0;
return false;
}
for (int count = 2; count <= remaining; count++)
{
string prop = string.Join(".", path, startIndex, count);
if (IsPropertyOrField(expr, prop, out propExpr))
{
combinationLength = count;
return true;
}
}
propExpr = null;
combinationLength = 0;
return false;
}
private static bool IsDictionaryKey(Expression expr, string prop, out Expression? propExpr)
{
var type = expr.Type;
var dictType = type.GetDictionaryType();
if (dictType?.GetGenericArguments()[0] != typeof(string))
{
propExpr = null;
return false;
}
var method = typeof(MapsterHelper).GetMethods()
.First(m => m.Name == nameof(MapsterHelper.GetValueOrDefault) && m.GetParameters()[0].ParameterType.Name == dictType.Name)
.MakeGenericMethod(dictType.GetGenericArguments());
propExpr = Expression.Call(method, expr.To(type), Expression.Constant(prop));
return true;
}
private static bool IsPropertyOrField(Expression expr, string prop, out Expression? propExpr)
{
Type type = expr.Type;
if (type.GetTypeInfo().IsInterface)
{
var allTypes = type.GetAllInterfaces();
var flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
var interfaceType = allTypes.FirstOrDefault(it => it.GetProperty(prop, flags) != null || it.GetField(prop, flags) != null);
if (interfaceType != null)
{
expr = Expression.Convert(expr, interfaceType);
type = expr.Type;
}
}
MemberInfo? propertyOrField = type
.GetMember(
prop,
MemberTypes.Field | MemberTypes.Property,
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy)
.FirstOrDefault();
propExpr = propertyOrField?.MemberType switch
{
MemberTypes.Property => Expression.Property(expr, (PropertyInfo)propertyOrField),
MemberTypes.Field => Expression.Field(expr, (FieldInfo)propertyOrField),
_ => null
};
return propExpr != null;
}
private static bool IsReferenceAssignableFrom(this Type destType, Type srcType)
{
if (destType == srcType)
return true;
if (!destType.GetTypeInfo().IsValueType && !srcType.GetTypeInfo().IsValueType && destType.GetTypeInfo().IsAssignableFrom(srcType.GetTypeInfo()))
return true;
return false;
}
public static Expression Not(Expression exp)
{
if (exp is UnaryExpression unary && unary.NodeType == ExpressionType.Not)
return unary.Operand;
return Expression.Not(exp);
}
public static Expression Apply(this LambdaExpression lambda, MapType mapType, params Expression[] exps)
{
return lambda.Apply(mapType != MapType.Projection, exps);
}
public static Expression Apply(this LambdaExpression lambda, ParameterExpression p1, ParameterExpression? p2 = null)
{
if (p2 == null)
return lambda.Apply(false, p1);
else
return lambda.Apply(false, p1, p2);
}
private static Expression Apply(this LambdaExpression lambda, bool allowInvoke, params Expression[] exps)
{
var replacer = new ParameterExpressionReplacer(lambda.Parameters, exps);
var result = replacer.Visit(lambda.Body);
if (!allowInvoke || !replacer.ReplaceCounts.Where((n, i) => n > 1 && exps[i].IsComplex()).Any())
return result!;
return Expression.Invoke(lambda, exps);
}
public static LambdaExpression TrimParameters(this LambdaExpression lambda, int skip = 0)
{
var replacer = new ParameterExpressionReplacer(lambda.Parameters, lambda.Parameters.ToArray<Expression>());
replacer.Visit(lambda.Body);
if (replacer.ReplaceCounts.Skip(skip).All(n => n > 0))
return lambda;
return Expression.Lambda(lambda.Body, lambda.Parameters.Where((_, i) => i < skip || replacer.ReplaceCounts[i] > 0));
}
public static Expression TrimConversion(this Expression exp, bool force = false)
{
while (exp.NodeType == ExpressionType.Convert || exp.NodeType == ExpressionType.ConvertChecked)
{
var unary = (UnaryExpression)exp;
if (force || unary.Type.IsReferenceAssignableFrom(unary.Operand.Type))
exp = unary.Operand;
else
break;
}
return exp;
}
public static Expression To(this Expression exp, Type type, bool force = false)
{
exp = exp.TrimConversion();
var sameType = force ? type == exp.Type : type.IsReferenceAssignableFrom(exp.Type);
return sameType ? exp : Expression.Convert(exp, type);
}
public static Delegate Compile(this LambdaExpression exp, CompileArgument arg)
{
try
{
return exp.Compile();
}
catch (Exception ex)
{
throw new CompileException(arg, ex)
{
Expression = exp,
};
}
}
public static Expression? CreateCountExpression(Expression source)
{
if (source.Type.IsArray)
{
return source.Type.GetArrayRank() == 1
? (Expression?) Expression.ArrayLength(source)
: Expression.Property(source, "Length");
}
else
{
var countProperty = GetCount(source.Type);
return countProperty != null
? Expression.Property(source, countProperty)
: null;
}
}
private static PropertyInfo? GetCount(Type type)
{
var c = type.GetProperty("Count");
if (c != null)
return c;
//for IList<>
var elementType = type.ExtractCollectionType();
var collection = typeof(ICollection<>).MakeGenericType(elementType);
return collection.IsAssignableFrom(type)
? collection.GetProperty("Count")
: null;
}
public static Expression ForLoop(Expression collection, ParameterExpression loopVar, params Expression[] loopContent)
{
var i = Expression.Variable(typeof(int), "i");
var len = Expression.Variable(typeof(int), "len");
Expression lenAssign;
Expression current;
if (collection.Type.IsArray && collection.Type.GetArrayRank() == 1)
{
current = Expression.ArrayIndex(collection, i);
lenAssign = Expression.Assign(len, Expression.ArrayLength(collection));
}
else if (collection.Type.GetDictionaryType() != null)
{
return ForEach(collection, loopVar, loopContent);
}
else
{
var indexer = (from p in collection.Type.GetDefaultMembers().OfType<PropertyInfo>()
let q = p.GetIndexParameters()
where q.Length == 1 && q[0].ParameterType == typeof(int)
select p).SingleOrDefault();
var count = GetCount(collection.Type);
//if indexer is not found, fallback to foreach
if (indexer == null || count == null)
return ForEach(collection, loopVar, loopContent);
current = Expression.Property(collection, indexer, i);
lenAssign = Expression.Assign(len, Expression.Property(collection, count));
}
var iAssign = Expression.Assign(i, Expression.Constant(0));
var breakLabel = Expression.Label("LoopBreak");
return Expression.Block(new[] { i, len },
iAssign,
lenAssign,
Expression.Loop(
Expression.IfThenElse(
Expression.LessThan(i, len),
Expression.Block(new[] { loopVar },
new[] { Expression.Assign(loopVar, current) }
.Concat(loopContent)
.Concat(new[] { Expression.PostIncrementAssign(i) })
),
Expression.Break(breakLabel)
),
breakLabel)
);
}
public static Expression ForEach(Expression collection, ParameterExpression loopVar, params Expression[] loopContent)
{
var elementType = loopVar.Type;
var enumerableType = typeof(IEnumerable<>).MakeGenericType(elementType);
var enumeratorType = typeof(IEnumerator<>).MakeGenericType(elementType);
var isGeneric = enumerableType.GetTypeInfo().IsAssignableFrom(collection.Type.GetTypeInfo());
if (!isGeneric)
{
enumerableType = typeof(IEnumerable);
enumeratorType = typeof(IEnumerator);
}
var enumeratorVar = Expression.Variable(enumeratorType, "enumerator");
var getEnumeratorCall = Expression.Call(collection, enumerableType.GetMethod("GetEnumerator")!);
var enumeratorAssign = Expression.Assign(enumeratorVar, getEnumeratorCall);
// The MoveNext method's actually on IEnumerator, not IEnumerator<T>
var moveNextCall = Expression.Call(enumeratorVar, typeof(IEnumerator).GetMethod("MoveNext")!);
var breakLabel = Expression.Label("LoopBreak");
Expression current = Expression.Property(enumeratorVar, "Current");
if (!isGeneric)
current = Expression.Convert(current, elementType);
return Expression.Block(new[] { enumeratorVar },
enumeratorAssign,
Expression.Loop(
Expression.IfThenElse(
moveNextCall,
Expression.Block(new[] { loopVar },
new[] { Assign(loopVar, current) }.Concat(loopContent)
),
Expression.Break(breakLabel)
),
breakLabel)
);
}
public static bool CanBeNull(this Expression exp)
{
if (!exp.Type.CanBeNull())
return false;
var visitor = new NullableExpressionVisitor();
visitor.Visit(exp);
return visitor.CanBeNull.GetValueOrDefault();
}
public static bool IsComplex(this Expression exp)
{
var visitor = new ComplexExpressionVisitor();
visitor.Visit(exp);
return visitor.IsComplex;
}
public static bool IsSingleValue(this Expression exp)
{
switch (exp.NodeType)
{
case ExpressionType.Constant:
case ExpressionType.Default:
case ExpressionType.Parameter:
return true;
default:
return false;
}
}
public static bool IsMultiLine(this LambdaExpression lambda)
{
var detector = new BlockExpressionDetector();
detector.Visit(lambda);
return detector.IsBlockExpression;
}
public static Expression NotNullReturn(this Expression exp, Expression value)
{
if (value.IsSingleValue() || !exp.CanBeNull())
return value;
var compareNull = Expression.Equal(exp, Expression.Constant(null, exp.Type));
return Expression.Condition(
compareNull,
value.Type.CreateDefault(),
value);
}
/// <summary>
/// Unpack Enum Nullable TSource value
/// </summary>
/// <param name="param"></param>
/// <returns></returns>
public static Expression NullableEnumExtractor(this Expression param)
{
var _SourceType = param.Type;
if (_SourceType.IsNullable())
{
var _genericType = param.Type.GetGenericArguments()[0];
if (_genericType.IsEnum)
{
var ExtractionExpression = Expression.Convert(param, typeof(object));
return ExtractionExpression;
}
return param;
}
return param;
}
public static Expression ApplyNullPropagation(this Expression getter)
{
var current = getter;
var result = getter;
while (current.NodeType == ExpressionType.MemberAccess)
{
var memEx = (MemberExpression) current;
var expr = memEx.Expression;
if (expr == null)
break;
if (expr.NodeType == ExpressionType.Parameter)
return result;
if (expr.CanBeNull())
{
var compareNull = Expression.Equal(expr, Expression.Constant(null, expr.Type));
if (!result.Type.CanBeNull())
result = Expression.Convert(result, typeof(Nullable<>).MakeGenericType(result.Type));
result = Expression.Condition(compareNull, result.Type.CreateDefault(), result);
}
current = expr;
}
return getter;
}
public static Expression ApplyNullPropagationFromCtor(this Expression getter, Expression adapt, CompileArgument arg)
{
Expression? condition = null;
var current = getter;
var checks = arg.Context.NullChecks
.Where(x=> !object.ReferenceEquals(x.arg,arg))
.Select(x=>x.param.Type);
while (current != null)
{
Expression? compareNull = null;
if (current.CanBeNull() && current is not ParameterExpression)
compareNull = Expression.NotEqual(current, Expression.Constant(null, current.Type));
else if (current.CanBeNull() && current is ParameterExpression
&& !checks.Contains(current.Type))
compareNull = Expression.NotEqual(current, Expression.Constant(null, current.Type));
if (compareNull != null)
{
if (condition == null)
condition = compareNull;
else
condition = Expression.AndAlso(compareNull, condition);
}
if (current is MemberExpression member)
current = member.Expression;
else
current = null;
}
if (condition == null)
return adapt;
return Expression.Condition(condition, adapt, adapt.Type.CreateDefault());
}
public static string? GetMemberPath(this LambdaExpression lambda, bool firstLevelOnly = false, bool noError = false)
{
var props = new List<string>();
var expr = lambda.Body.TrimConversion(true);
while (expr?.NodeType == ExpressionType.MemberAccess)
{
if (firstLevelOnly && props.Count > 0)
{
if (noError)
return null;
throw new ArgumentException("Only first level members are allowed (eg. obj => obj.Child)", nameof(lambda));
}
var memEx = (MemberExpression)expr;
props.Add(memEx.Member.Name);
expr = (Expression?)memEx.Expression;
}
if (props.Count == 0 || expr?.NodeType != ExpressionType.Parameter)
{
if (noError)
return null;
throw new ArgumentException("Allow only member access (eg. obj => obj.Child.Name)", nameof(lambda));
}
props.Reverse();
return string.Join(".", props);
}
public static bool IsIdentity(this LambdaExpression lambda)
{
var expr = lambda.Body.TrimConversion(true);
return lambda.Parameters.Count == 1 && lambda.Parameters[0] == expr;
}
internal static Expression GetNameConverterExpression(Func<string, string> converter)
{
if (converter == MapsterHelper.Identity)
return Expression.Field(null, typeof(MapsterHelper), nameof(MapsterHelper.Identity));
if (converter == MapsterHelper.PascalCase)
return Expression.Field(null, typeof(MapsterHelper), nameof(MapsterHelper.PascalCase));
if (converter == MapsterHelper.CamelCase)
return Expression.Field(null, typeof(MapsterHelper), nameof(MapsterHelper.CamelCase));
if (converter == MapsterHelper.LowerCase)
return Expression.Field(null, typeof(MapsterHelper), nameof(MapsterHelper.LowerCase));
return Expression.Constant(converter);
}
}
}