-
Notifications
You must be signed in to change notification settings - Fork 85
/
ExpressionCleaner.cs
410 lines (321 loc) · 14.7 KB
/
ExpressionCleaner.cs
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
namespace Signum.Utilities.ExpressionTrees;
/// <summary>
/// Implementation of SimpleExpressionVisitor that does the replacement
/// * MethodExpanderAttribute
/// * MemberXXXExpression static field
/// * ExpressionExtensions.Evaluate method
///
/// It also simplifies and skip evaluating short circuited subexpresions
/// Evaluates constant subexpressions
/// </summary>
public class ExpressionCleaner : ExpressionVisitor
{
Func<Expression, Expression> partialEval;
bool shortCircuit;
public ExpressionCleaner(Func<Expression, Expression> partialEval, bool shortCircuit)
{
this.partialEval = partialEval;
this.shortCircuit = shortCircuit;
}
public static Expression? Clean(Expression? expr)
{
return Clean(expr, ExpressionEvaluator.PartialEval, true);
}
public static Expression? Clean(Expression? expr, Func<Expression, Expression> partialEval, bool shortCircuit)
{
ExpressionCleaner ee = new ExpressionCleaner(partialEval, shortCircuit);
var result = ee.Visit(expr);
if (result == null)
return null;
return partialEval(result);
}
protected override Expression VisitInvocation(InvocationExpression iv)
{
if (iv.Expression is LambdaExpression)
return Visit(ExpressionReplacer.Replace(iv));
else
return base.VisitInvocation(iv); //Just calling a delegate in the projector
}
protected override Expression VisitMethodCall(MethodCallExpression m)
{
MethodCallExpression expr = (MethodCallExpression)base.VisitMethodCall(m);
Expression? binded = BindMethodExpression(expr, false);
if (binded != null)
return Visit(binded);
return expr;
}
public static Expression? BindMethodExpression(MethodCallExpression m, bool allowPolymorphics)
{
if (m.Method.DeclaringType == typeof(ExpressionExtensions) && m.Method.Name == "Evaluate")
{
LambdaExpression lambda = (LambdaExpression)ExpressionEvaluator.Eval(m.Arguments[0])!;
return Expression.Invoke(lambda, m.Arguments.Skip(1).ToArray());
}
if (m.Method.HasAttributeInherit<PolymorphicExpansionAttribute>() && !allowPolymorphics)
return null;
MethodExpanderAttribute? attribute = m.Method.GetCustomAttribute<MethodExpanderAttribute>();
if (attribute != null)
{
if (attribute.ExpanderType.IsGenericTypeDefinition)
{
if (!typeof(GenericMethodExpander).IsAssignableFrom(attribute.ExpanderType))
throw new InvalidOperationException("Expansion failed, '{0}' does not implement IMethodExpander or GenericMethodExpander".FormatWith(attribute.ExpanderType.TypeName()));
Expression[] args = m.Object == null ? m.Arguments.ToArray() : m.Arguments.PreAnd(m.Object).ToArray();
var type = attribute.ExpanderType.MakeGenericType(m.Method.GetGenericArguments());
GenericMethodExpander expander = (GenericMethodExpander)Activator.CreateInstance(type)!;
return Expression.Invoke(expander.GenericLambdaExpression, args);
}
else
{
if(!typeof(IMethodExpander).IsAssignableFrom(attribute.ExpanderType))
throw new InvalidOperationException("Expansion failed, '{0}' does not implement IMethodExpander or GenericMethodExpander".FormatWith(attribute.ExpanderType.TypeName()));
IMethodExpander expander = (IMethodExpander)Activator.CreateInstance(attribute.ExpanderType)!;
Expression exp = expander.Expand(
m.Object,
m.Arguments.ToArray(),
m.Method);
return exp;
}
}
LambdaExpression? lambdaExpression = GetFieldExpansion(m.Object?.Type, m.Method);
if (lambdaExpression != null)
{
Expression[] args = m.Object == null ? m.Arguments.ToArray() : m.Arguments.PreAnd(m.Object).ToArray();
return Expression.Invoke(lambdaExpression, args);
}
return null;
}
protected override Expression VisitMember(MemberExpression m)
{
MemberExpression exp = (MemberExpression)base.VisitMember(m);
Expression? binded = BindMemberExpression(exp, false);
if (binded != null)
return Visit(binded);
return exp;
}
public static Expression? BindMemberExpression(MemberExpression m, bool allowPolymorphics)
{
PropertyInfo? pi = m.Member as PropertyInfo;
if (pi == null)
return null;
if (pi.HasAttributeInherit<PolymorphicExpansionAttribute>() && !allowPolymorphics)
return null;
LambdaExpression? lambda = GetFieldExpansion(m.Expression?.Type, pi);
if (lambda == null)
return null;
if (m.Expression == null)
return lambda.Body;
else
return Expression.Invoke(lambda, m.Expression);
}
public static bool HasExpansions(Type type, MemberInfo mi)
{
return GetFieldExpansion(type, mi) != null || mi is MethodInfo && mi.HasAttribute<MethodExpanderAttribute>();
}
public static LambdaExpression? GetFieldExpansion(Type? decType, MemberInfo mi)
{
if (decType == null || decType == mi.DeclaringType || IsStatic(mi))
return GetExpansion(mi);
else
{
for (MemberInfo? m = GetMember(decType, mi); m != null; m = BaseMember(m))
{
var result = GetExpansion(m);
if (result != null)
return result;
}
return null;
}
}
static bool IsStatic(MemberInfo mi)
{
if (mi is MethodInfo mti)
return mti.IsStatic;
if (mi is PropertyInfo pi)
return (pi.GetGetMethod() ?? pi.GetSetMethod())!.IsStatic;
return false;
}
static LambdaExpression? GetExpansion(MemberInfo mi)
{
ExpressionFieldAttribute? efa = mi.GetCustomAttribute<ExpressionFieldAttribute>();
if (efa == null)
return null;
if (efa.Name == "auto")
throw new InvalidOperationException($"The {nameof(ExpressionFieldAttribute)} for {mi.DeclaringType!.TypeName()}.{mi.MemberName()} has the default value 'auto'.\r\nMaybe Signum.MSBuildTask is not running in assemby {mi.DeclaringType!.Assembly.GetName().Name}?");
Type type = mi.DeclaringType!;
FieldInfo? fi = type.GetField(efa.Name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
if (fi == null)
throw new InvalidOperationException("Expression field '{0}' not found on '{1}'".FormatWith(efa.Name, type.TypeName()));
var obj = fi.GetValue(null);
if (obj == null)
throw new InvalidOperationException("Expression field '{0}' is null".FormatWith(efa.Name));
if (!(obj is LambdaExpression result))
throw new InvalidOperationException("Expression field '{0}' does not contain a lambda expression".FormatWith(efa.Name, type.TypeName()));
return result;
}
static readonly BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
static MemberInfo? GetMember(Type decType, MemberInfo mi)
{
if (mi is MethodInfo)
{
Type[] types = ((MethodInfo)mi).GetParameters().Select(a => a.ParameterType).ToArray();
var result = decType.GetMethod(mi.Name, flags, null, types, null);
if (result != null)
return result;
if (mi.DeclaringType!.IsInterface)
return decType.GetMethod(mi.DeclaringType.FullName + "." + mi.Name, flags, null, types, null);
return null;
}
if (mi is PropertyInfo pi)
{
Type[] types = pi.GetIndexParameters().Select(a => a.ParameterType).ToArray();
var result = decType.GetProperty(mi.Name, flags, null, pi.PropertyType, types, null) ;
if (result != null)
return result;
if(mi.DeclaringType!.IsInterface)
return decType.GetProperty(mi.DeclaringType.FullName + "." + mi.Name, flags, null, pi.PropertyType, types, null);
return null;
}
throw new InvalidOperationException("Invalid Member type");
}
static MemberInfo? BaseMember(MemberInfo mi)
{
MemberInfo? result;
if (mi is MethodInfo mti)
result = mti.GetBaseDefinition();
else if (mi is PropertyInfo pi)
result = pi.GetBaseDefinition();
else
throw new InvalidOperationException("Invalid Member type");
if (result == mi)
return null;
return result;
}
#region Simplifier
bool GetBool(Expression exp)
{
return (bool)((ConstantExpression)exp).Value!;
}
protected override Expression VisitBinary(BinaryExpression b)
{
if (!shortCircuit)
return base.VisitBinary(b);
if (b.NodeType == ExpressionType.Coalesce)
{
Expression left = partialEval(this.Visit(b.Left));
if (left.NodeType == ExpressionType.Constant)
{
var ce = (ConstantExpression)left;
if (ce.Value == null)
return Visit(b.Right);
if (ce.Type.IsNullable())
return Expression.Constant(ce.Value, ce.Type.UnNullify());
else
return ce;
}
Expression right = this.Visit(b.Right);
Expression? conversion = this.Visit(b.Conversion);
return Expression.Coalesce(left, right, conversion as LambdaExpression);
}
if (b.Type != typeof(bool))
return base.VisitBinary(b);
if (b.NodeType == ExpressionType.And || b.NodeType == ExpressionType.AndAlso)
{
Expression left = partialEval(this.Visit(b.Left));
if (left.NodeType == ExpressionType.Constant)
return GetBool(left) ? Visit(b.Right) : Expression.Constant(false);
Expression right = partialEval(this.Visit(b.Right));
if (right.NodeType == ExpressionType.Constant)
return GetBool(right) ? left : Expression.Constant(false);
return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method);
}
else if (b.NodeType == ExpressionType.Or || b.NodeType == ExpressionType.OrElse)
{
Expression left = partialEval(this.Visit(b.Left));
if (left.NodeType == ExpressionType.Constant)
return GetBool(left) ? Expression.Constant(true) : Visit(b.Right);
Expression right = partialEval(this.Visit(b.Right));
if (right.NodeType == ExpressionType.Constant)
return GetBool(right) ? Expression.Constant(true) : left;
return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method);
}
// rel == 'a' is compiled as (int)rel == 123
if(b.NodeType == ExpressionType.Equal ||
b.NodeType == ExpressionType.NotEqual)
{
{
if (IsConvertCharToInt(b.Left) is Expression l &&
IsConvertCharToIntOrConstant(b.Right) is Expression r)
return Expression.MakeBinary(b.NodeType, Visit(l), Visit(r));
}
{
if (IsConvertCharToIntOrConstant(b.Left) is Expression l &&
IsConvertCharToInt(b.Right) is Expression r)
return Expression.MakeBinary(b.NodeType, Visit(l), Visit(r));
}
}
if (b.Left.Type != typeof(bool))
return base.VisitBinary(b);
if (b.NodeType == ExpressionType.Equal)
{
Expression left = partialEval(this.Visit(b.Left));
if (left.NodeType == ExpressionType.Constant)
return GetBool(left) ? Visit(b.Right) : Visit(Expression.Not(b.Right));
Expression right = partialEval(this.Visit(b.Right));
if (right.NodeType == ExpressionType.Constant)
return GetBool(right) ? left : Expression.Not(left);
return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method);
}
else if (b.NodeType == ExpressionType.NotEqual)
{
Expression left = partialEval(this.Visit(b.Left));
if (left.NodeType == ExpressionType.Constant)
return GetBool(left) ? Visit(Expression.Not(b.Right)) : Visit(b.Right);
Expression right = partialEval(this.Visit(b.Right));
if (right.NodeType == ExpressionType.Constant)
return GetBool(right) ? Expression.Not(left) : left;
return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method);
}
return base.VisitBinary(b);
}
static Expression? IsConvertCharToInt(Expression exp)
{
if (exp is UnaryExpression ue && ue.NodeType == ExpressionType.Convert && ue.Operand.Type == typeof(char))
{
return ue.Operand;
}
return null;
}
static Expression? IsConvertCharToIntOrConstant(Expression exp)
{
var result = IsConvertCharToInt(exp);
if (result != null)
return result;
if (exp is ConstantExpression ceInt && ceInt.Type == typeof(int))
return Expression.Constant((char)(int)ceInt.Value!, typeof(char));
if (exp is ConstantExpression ceChar && ceChar.Type == typeof(char))
return ceChar;
return null;
}
protected override Expression VisitConditional(ConditionalExpression c)
{
if (!shortCircuit)
return base.VisitConditional(c);
Expression test = partialEval(this.Visit(c.Test));
if (test.NodeType == ExpressionType.Constant)
{
if (GetBool(test))
return this.Visit(c.IfTrue);
else
return this.Visit(c.IfFalse);
}
Expression ifTrue = this.Visit(c.IfTrue);
Expression ifFalse = this.Visit(c.IfFalse);
if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse)
{
return Expression.Condition(test, ifTrue, ifFalse);
}
return c;
}
#endregion
}