This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5k
/
Expression.cs
285 lines (257 loc) · 11.4 KB
/
Expression.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Linq.Expressions
{
/// <summary>
/// The base type for all nodes in Expression Trees.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
public abstract partial class Expression
{
private static readonly CacheDict<Type, MethodInfo> s_lambdaDelegateCache = new CacheDict<Type, MethodInfo>(40);
private static volatile CacheDict<Type, Func<Expression, string, bool, ReadOnlyCollection<ParameterExpression>, LambdaExpression>> s_lambdaFactories;
// For 4.0, many frequently used Expression nodes have had their memory
// footprint reduced by removing the Type and NodeType fields. This has
// large performance benefits to all users of Expression Trees.
//
// To support the 3.5 protected constructor, we store the fields that
// used to be here in a ConditionalWeakTable.
private class ExtensionInfo
{
public ExtensionInfo(ExpressionType nodeType, Type type)
{
NodeType = nodeType;
Type = type;
}
internal readonly ExpressionType NodeType;
internal readonly Type Type;
}
private static ConditionalWeakTable<Expression, ExtensionInfo> s_legacyCtorSupportTable;
/// <summary>
/// Constructs a new instance of <see cref="Expression"/>.
/// </summary>
/// <param name="nodeType">The <see ctype="ExpressionType"/> of the <see cref="Expression"/>.</param>
/// <param name="type">The <see cref="Type"/> of the <see cref="Expression"/>.</param>
[Obsolete("use a different constructor that does not take ExpressionType. Then override NodeType and Type properties to provide the values that would be specified to this constructor.")]
protected Expression(ExpressionType nodeType, Type type)
{
// Can't enforce anything that V1 didn't
if (s_legacyCtorSupportTable == null)
{
Interlocked.CompareExchange(
ref s_legacyCtorSupportTable,
new ConditionalWeakTable<Expression, ExtensionInfo>(),
comparand: null
);
}
s_legacyCtorSupportTable.Add(this, new ExtensionInfo(nodeType, type));
}
/// <summary>
/// Constructs a new instance of <see cref="Expression"/>.
/// </summary>
protected Expression()
{
}
/// <summary>
/// The <see cref="ExpressionType"/> of the <see cref="Expression"/>.
/// </summary>
public virtual ExpressionType NodeType
{
get
{
ExtensionInfo extInfo;
if (s_legacyCtorSupportTable != null && s_legacyCtorSupportTable.TryGetValue(this, out extInfo))
{
return extInfo.NodeType;
}
// the extension expression failed to override NodeType
throw Error.ExtensionNodeMustOverrideProperty("Expression.NodeType");
}
}
/// <summary>
/// The <see cref="Type"/> of the value represented by this <see cref="Expression"/>.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1721:PropertyNamesShouldNotMatchGetMethods")]
public virtual Type Type
{
get
{
ExtensionInfo extInfo;
if (s_legacyCtorSupportTable != null && s_legacyCtorSupportTable.TryGetValue(this, out extInfo))
{
return extInfo.Type;
}
// the extension expression failed to override Type
throw Error.ExtensionNodeMustOverrideProperty("Expression.Type");
}
}
/// <summary>
/// Indicates that the node can be reduced to a simpler node. If this
/// returns true, Reduce() can be called to produce the reduced form.
/// </summary>
public virtual bool CanReduce => false;
/// <summary>
/// Reduces this node to a simpler expression. If CanReduce returns
/// true, this should return a valid expression. This method is
/// allowed to return another node which itself must be reduced.
/// </summary>
/// <returns>The reduced expression.</returns>
public virtual Expression Reduce()
{
if (CanReduce) throw Error.ReducibleMustOverrideReduce();
return this;
}
/// <summary>
/// Reduces the node and then calls the <see cref="ExpressionVisitor.Visit(Expression)"/> method passing the reduced expression.
/// Throws an exception if the node isn't reducible.
/// </summary>
/// <param name="visitor">An instance of <see cref="ExpressionVisitor"/>.</param>
/// <returns>The expression being visited, or an expression which should replace it in the tree.</returns>
/// <remarks>
/// Override this method to provide logic to walk the node's children.
/// A typical implementation will call visitor.Visit on each of its
/// children, and if any of them change, should return a new copy of
/// itself with the modified children.
/// </remarks>
protected internal virtual Expression VisitChildren(ExpressionVisitor visitor)
{
if (!CanReduce) throw Error.MustBeReducible();
return visitor.Visit(ReduceAndCheck());
}
/// <summary>
/// Dispatches to the specific visit method for this node type. For
/// example, <see cref="MethodCallExpression"/> will call into
/// <see cref="ExpressionVisitor.VisitMethodCall"/>.
/// </summary>
/// <param name="visitor">The visitor to visit this node with.</param>
/// <returns>The result of visiting this node.</returns>
/// <remarks>
/// This default implementation for <see cref="ExpressionType.Extension"/>
/// nodes will call <see cref="ExpressionVisitor.VisitExtension"/>.
/// Override this method to call into a more specific method on a derived
/// visitor class of ExprressionVisitor. However, it should still
/// support unknown visitors by calling VisitExtension.
/// </remarks>
protected internal virtual Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitExtension(this);
}
/// <summary>
/// Reduces this node to a simpler expression. If CanReduce returns
/// true, this should return a valid expression. This method is
/// allowed to return another node which itself must be reduced.
/// </summary>
/// <returns>The reduced expression.</returns>
/// <remarks >
/// Unlike Reduce, this method checks that the reduced node satisfies
/// certain invariants.
/// </remarks>
public Expression ReduceAndCheck()
{
if (!CanReduce) throw Error.MustBeReducible();
Expression newNode = Reduce();
// 1. Reduction must return a new, non-null node
// 2. Reduction must return a new node whose result type can be assigned to the type of the original node
if (newNode == null || newNode == this) throw Error.MustReduceToDifferent();
if (!TypeUtils.AreReferenceAssignable(Type, newNode.Type)) throw Error.ReducedNotCompatible();
return newNode;
}
/// <summary>
/// Reduces the expression to a known node type (i.e. not an Extension node)
/// or simply returns the expression if it is already a known type.
/// </summary>
/// <returns>The reduced expression.</returns>
public Expression ReduceExtensions()
{
Expression node = this;
while (node.NodeType == ExpressionType.Extension)
{
node = node.ReduceAndCheck();
}
return node;
}
/// <summary>
/// Creates a <see cref="String"/> representation of the Expression.
/// </summary>
/// <returns>A <see cref="String"/> representation of the Expression.</returns>
public override string ToString()
{
return ExpressionStringBuilder.ExpressionToString(this);
}
/// <summary>
/// Creates a <see cref="String"/> representation of the Expression.
/// </summary>
/// <returns>A <see cref="String"/> representation of the Expression.</returns>
private string DebugView
{
// Note that this property is often accessed using reflection. As such it will have more dependencies than one
// might surmise from its being internal, and removing it requires greater caution than with other internal methods.
get
{
using (System.IO.StringWriter writer = new System.IO.StringWriter(CultureInfo.CurrentCulture))
{
DebugViewWriter.WriteTo(this, writer);
return writer.ToString();
}
}
}
private static void RequiresCanRead(IReadOnlyList<Expression> items, string paramName)
{
Debug.Assert(items != null);
// this is called a lot, avoid allocating an enumerator if we can...
for (int i = 0, n = items.Count; i < n; i++)
{
ExpressionUtils.RequiresCanRead(items[i], paramName, i);
}
}
private static void RequiresCanWrite(Expression expression, string paramName)
{
if (expression == null)
{
throw new ArgumentNullException(paramName);
}
switch (expression.NodeType)
{
case ExpressionType.Index:
PropertyInfo indexer = ((IndexExpression)expression).Indexer;
if (indexer == null || indexer.CanWrite)
{
return;
}
break;
case ExpressionType.MemberAccess:
MemberInfo member = ((MemberExpression)expression).Member;
PropertyInfo prop = member as PropertyInfo;
if (prop != null)
{
if(prop.CanWrite)
{
return;
}
}
else
{
Debug.Assert(member is FieldInfo);
FieldInfo field = (FieldInfo)member;
if (!(field.IsInitOnly || field.IsLiteral))
{
return;
}
}
break;
case ExpressionType.Parameter:
return;
}
throw Error.ExpressionMustBeWriteable(paramName);
}
}
}