forked from DataObjects-NET/dataobjects-net
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathExpressionExtensions.cs
More file actions
314 lines (288 loc) · 13.5 KB
/
ExpressionExtensions.cs
File metadata and controls
314 lines (288 loc) · 13.5 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
// Copyright (C) 2009-2023 Xtensive LLC.
// This code is distributed under MIT license terms.
// See the License.txt file in the project root for more information.
// Created by: Alexis Kochetov
// Created: 2009.04.21
using System;
using System.Linq.Expressions;
using System.Reflection;
using Xtensive.Linq;
using Xtensive.Linq.SerializableExpressions;
using Xtensive.Linq.SerializableExpressions.Internals;
using System.Linq;
using Xtensive.Reflection;
using System.Collections.Concurrent;
namespace Xtensive.Core
{
/// <summary>
/// <see cref="Expression"/> related extension methods.
/// </summary>
public static class ExpressionExtensions
{
private readonly static ConcurrentDictionary<Type, ConstantExpression> StructDefaultConstantExpressions = new();
/// <summary>
/// Formats the <paramref name="expression"/>.
/// </summary>
/// <param name="expression">The expression to format.</param>
/// <param name="inCSharpNotation">If set to <see langword="true"/>,
/// the result will be returned in C# notation
/// (<see cref="ExpressionWriter"/> will be used).</param>
/// <returns>A string containing formatted expression.</returns>
public static string ToString(this Expression expression, bool inCSharpNotation)
{
if (!inCSharpNotation)
return expression.ToString();
return ExpressionWriter.Write(expression);
// // The old code
// string result = expression.ToString();
// result = Regex.Replace(result, @"value\([^)]+DisplayClass[^)]+\)\.", "");
// return result;
}
/// <summary>
/// Determines whether the specified expression is <see cref="ConstantExpression"/>
/// with <see langword="null" /> <see cref="ConstantExpression.Value"/>.
/// </summary>
/// <param name="expression">The expression.</param>
/// <returns>
/// <see langword="true" /> if the specified expression is null; otherwise, <see langword="false" />.
/// </returns>
public static bool IsNull(this Expression expression)
{
ArgumentNullException.ThrowIfNull(expression);
if (expression.NodeType==ExpressionType.Constant) {
var constantExpression = (ConstantExpression) expression;
return constantExpression.Value==null;
}
return false;
}
/// <summary>
/// Bind parameter expressions to <see cref="LambdaExpression"/>.
/// </summary>
/// <param name="lambdaExpression"><see cref="LambdaExpression"/> to bind parameters.</param>
/// <param name="parameters"><see cref="Expression"/>s to bind to <paramref name="lambdaExpression"/></param>
/// <returns>Body of <paramref name="lambdaExpression"/> with lambda's parameters replaced
/// with corresponding expression from <paramref name="parameters"/></returns>
/// <exception cref="InvalidOperationException">Something went wrong :(.</exception>
public static Expression BindParameters(this LambdaExpression lambdaExpression, params ReadOnlySpan<Expression> parameters)
{
var lambdaExpressionParameters = lambdaExpression.Parameters;
var lambdaExpressionParametersCount = lambdaExpressionParameters.Count;
if (lambdaExpressionParametersCount != parameters.Length)
throw new InvalidOperationException(String.Format(
Strings.ExUnableToBindParametersToLambdaXParametersCountIsIncorrect,
lambdaExpression.ToString(true)));
if (parameters.Length == 0)
return lambdaExpression;
using PooledArray<Expression> pooledConvertedParameters = new(parameters.Length);
var convertedParameters = pooledConvertedParameters.Array;
for (int i = 0; i < lambdaExpressionParametersCount; i++) {
var expressionParameter = lambdaExpressionParameters[i];
var parameter = parameters[i];
var parameterType = parameter.Type;
var expressionParameterType = expressionParameter.Type;
if (expressionParameterType.IsAssignableFrom(parameterType))
convertedParameters[i] = expressionParameterType == parameterType
? parameter
: Expression.Convert(parameter, expressionParameterType);
else
throw new InvalidOperationException(String.Format(
Strings.ExUnableToUseExpressionXAsXParameterOfLambdaXBecauseOfTypeMistmatch,
parameters[i].ToString(true), i, expressionParameter.ToString(true)));
}
return ExpressionReplacer.ReplaceAll(
lambdaExpression.Body, lambdaExpressionParameters, convertedParameters);
}
/// <summary>
/// Converts specified <see cref="Expression"/> to <see cref="SerializableExpression"/>.
/// </summary>
/// <param name="expression">The expression to convert.</param>
/// <returns>Serializable expression that represents <paramref name="expression"/>.</returns>
public static SerializableExpression ToSerializableExpression(this Expression expression)
{
return new ExpressionToSerializableExpressionConverter(expression).Convert();
}
/// <summary>
/// Converts specified <see cref="SerializableExpression"/> to <see cref="Expression"/>.
/// </summary>
/// <param name="expression">The expression to convert.</param>
/// <returns>Expression that represents given <see cref="SerializableExpression"/>.</returns>
public static Expression ToExpression(this SerializableExpression expression)
{
return new SerializableExpressionToExpressionConverter(expression).Convert();
}
/// <summary>
/// Converts <see cref="DefaultExpression"/> to <see cref="ConstantExpression"/>
/// with value of default value of type in the <paramref name="defaultExpression"/>.
/// </summary>
/// <param name="defaultExpression">The expression to convert.</param>
/// <returns>Result constant expression.</returns>
public static ConstantExpression ToConstantExpression(this DefaultExpression defaultExpression) =>
StructDefaultConstantExpressions.GetOrAdd(
defaultExpression.Type,
static (t, expr) => Expression.Constant(
t.IsValueType
? ((Func<object>) Expression.Lambda(Expression.Convert(expr, WellKnownTypes.Object)).Compile()).Invoke()
: null,
t),
defaultExpression);
/// <summary>
/// Gets return type of <see cref="LambdaExpression"/>.
/// This method is used to write code that is compilable on .NET 3.5,
/// which do not have corresponding property.
/// </summary>
/// <param name="lambda">Expression to get return type for.</param>
/// <returns>Return type of <paramref name="lambda"/>.</returns>
public static Type GetReturnType(this LambdaExpression lambda)
{
return lambda.Body.Type;
}
#region GetXxx methods
/// <summary>
/// Gets the <see cref="MemberInfo"/> from passed <paramref name="expression"/>.
/// </summary>
/// <param name="expression">The expression to analyze.</param>
/// <returns><see cref="MemberInfo"/> the expression references by its root <see cref="MemberExpression"/>.</returns>
/// <exception cref="ArgumentException">The root node of expression isn't of <see cref="MemberExpression"/> type.</exception>
public static MemberInfo GetMember(this Expression expression)
{
ArgumentNullException.ThrowIfNull(expression);
expression = expression.StripLambda().StripCasts();
var me = expression as MemberExpression;
if (me==null)
throw new ArgumentException(
string.Format(Strings.ExInvalidArgumentType, typeof (MemberExpression)), "expression");
return me.Member;
}
/// <summary>
/// Gets the <see cref="FieldInfo"/> from passed <paramref name="expression"/>.
/// </summary>
/// <param name="expression">The expression to analyze.</param>
/// <returns><see cref="MemberInfo"/> the expression references by its root <see cref="MemberExpression"/>.</returns>
/// <exception cref="ArgumentException">Expression must reference field.</exception>
public static FieldInfo GetField(this Expression expression)
{
var mi = GetMember(expression);
var fi = mi as FieldInfo;
if (fi==null)
throw new ArgumentException(
string.Format(Strings.ExExpression0MustReferenceField, expression.ToString(true)));
return fi;
}
/// <summary>
/// Gets the <see cref="PropertyInfo"/> from passed <paramref name="expression"/>.
/// </summary>
/// <param name="expression">The expression to analyze.</param>
/// <returns><see cref="MemberInfo"/> the expression references by its root <see cref="MemberExpression"/>.</returns>
/// <exception cref="ArgumentException">Expression must reference property.</exception>
public static PropertyInfo GetProperty(this Expression expression)
{
var mi = GetMember(expression);
var pi = mi as PropertyInfo;
if (pi==null)
throw new ArgumentException(
string.Format(Strings.ExExpression0MustReferenceProperty, expression.ToString(true)));
return pi;
}
/// <summary>
/// Gets the <see cref="MethodInfo"/> from passed <paramref name="expression"/>.
/// </summary>
/// <param name="expression">The expression to analyze.</param>
/// <returns><see cref="MethodInfo"/> the expression references by its root <see cref="MethodCallExpression"/>.</returns>
/// <exception cref="ArgumentException">Expression must reference event.</exception>
public static MethodInfo GetMethod(this Expression expression)
{
ArgumentNullException.ThrowIfNull(expression);
expression = expression.StripLambda().StripCasts();
var mce = expression as MethodCallExpression;
if (mce==null)
throw new ArgumentException(
string.Format(Strings.ExInvalidArgumentType, typeof (MethodCallExpression)), "expression");
return mce.Method;
}
/// <summary>
/// Gets the index <see cref="PropertyInfo"/> from passed <paramref name="expression"/>.
/// </summary>
/// <param name="expression">The expression to analyze.</param>
/// <returns><see cref="PropertyInfo"/> the expression references by its root <see cref="IndexExpression"/>.</returns>
/// <exception cref="ArgumentException">Expression must reference event.</exception>
public static PropertyInfo GetIndexer(this Expression expression)
{
ArgumentNullException.ThrowIfNull(expression);
expression = expression.StripLambda().StripCasts();
var ie = expression as IndexExpression;
if (ie==null)
throw new ArgumentException(
string.Format(Strings.ExInvalidArgumentType, typeof (IndexExpression)), "expression");
return ie.Indexer;
}
/// <summary>
/// Gets the <see cref="ConstructorInfo"/> from passed <paramref name="expression"/>.
/// </summary>
/// <param name="expression">The expression to analyze.</param>
/// <returns><see cref="ConstructorInfo"/> the expression references by its root <see cref="NewExpression"/>.</returns>
/// <exception cref="ArgumentException">Expression must reference event.</exception>
public static ConstructorInfo GetConstructor(this Expression expression)
{
ArgumentNullException.ThrowIfNull(expression);
expression = expression.StripLambda().StripCasts();
var ne = expression as NewExpression;
if (ne==null)
throw new ArgumentException(
string.Format(Strings.ExInvalidArgumentType, typeof (NewExpression)), "expression");
return ne.Constructor;
}
#endregion
#region StripXxx methods
/// <summary>
/// Strips <see cref="Expression.Quote"/> expressions.
/// </summary>
/// <param name="expression">The expression.</param>
public static LambdaExpression StripQuotes(this Expression expression)
{
while (expression.NodeType==ExpressionType.Quote)
expression = ((UnaryExpression) expression).Operand;
var lambda = expression as LambdaExpression;
if (lambda==null) {
if (!typeof (LambdaExpression).IsAssignableFrom(expression.Type))
throw new InvalidOperationException($"Unable to process expression '{expression}'");
var typeAs = Expression.TypeAs(expression, typeof (LambdaExpression));
return FastExpression.Lambda<Func<LambdaExpression>>(typeAs).CachingCompile()();
}
return lambda;
}
/// <summary>
/// Strips <see cref="ExpressionType.Convert"/> and <see cref="ExpressionType.TypeAs"/>.
/// </summary>
/// <param name="expression">The expression.</param>
public static Expression StripCasts(this Expression expression)
{
while (expression.NodeType is ExpressionType.Convert or ExpressionType.TypeAs) {
expression = ((UnaryExpression) expression).Operand;
}
return expression;
}
/// <summary>
/// Strips the lambda.
/// </summary>
/// <param name="expression">The expression.</param>
/// <returns></returns>
public static Expression StripLambda(this Expression expression)
{
if (expression.NodeType==ExpressionType.Lambda)
return ((LambdaExpression) expression).Body;
return expression;
}
/// <summary>
/// Strips the chain of <see cref="MemberExpression"/>s
/// </summary>
/// <param name="expression">Expression to process.</param>
/// <returns><paramref name="expression"/> with chain of <see cref="MemberExpression"/>s removed (if any).</returns>
public static Expression StripMemberAccessChain(this Expression expression)
{
while (expression.NodeType==ExpressionType.MemberAccess)
expression = ((MemberExpression) expression).Expression;
return expression;
}
#endregion
}
}