/
SwitchExpression.cs
315 lines (287 loc) · 14.5 KB
/
SwitchExpression.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Reflection;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents a control expression that handles multiple selections by passing control to a <see cref="SwitchCase"/>.
/// </summary>
[DebuggerTypeProxy(typeof(SwitchExpressionProxy))]
public sealed class SwitchExpression : Expression
{
internal SwitchExpression(Type type, Expression switchValue, Expression? defaultBody, MethodInfo? comparison, ReadOnlyCollection<SwitchCase> cases)
{
Type = type;
SwitchValue = switchValue;
DefaultBody = defaultBody;
Comparison = comparison;
Cases = cases;
}
/// <summary>
/// Gets the static type of the expression that this <see cref="Expression"/> represents.
/// </summary>
/// <returns>The <see cref="System.Type"/> that represents the static type of the expression.</returns>
public sealed override Type Type { get; }
/// <summary>
/// Returns the node type of this Expression. Extension nodes should return
/// ExpressionType.Extension when overriding this method.
/// </summary>
/// <returns>The <see cref="ExpressionType"/> of the expression.</returns>
public sealed override ExpressionType NodeType => ExpressionType.Switch;
/// <summary>
/// Gets the test for the switch.
/// </summary>
public Expression SwitchValue { get; }
/// <summary>
/// Gets the collection of <see cref="SwitchCase"/> objects for the switch.
/// </summary>
public ReadOnlyCollection<SwitchCase> Cases { get; }
/// <summary>
/// Gets the test for the switch.
/// </summary>
public Expression? DefaultBody { get; }
/// <summary>
/// Gets the equality comparison method, if any.
/// </summary>
public MethodInfo? Comparison { get; }
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitSwitch(this);
}
internal bool IsLifted
{
get
{
if (SwitchValue.Type.IsNullableType())
{
return (Comparison == null) ||
!TypeUtils.AreEquivalent(SwitchValue.Type, Comparison.GetParametersCached()[0].ParameterType.GetNonRefType());
}
return false;
}
}
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="switchValue">The <see cref="SwitchValue"/> property of the result.</param>
/// <param name="cases">The <see cref="Cases"/> property of the result.</param>
/// <param name="defaultBody">The <see cref="DefaultBody"/> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public SwitchExpression Update(Expression switchValue, IEnumerable<SwitchCase>? cases, Expression? defaultBody)
{
if (switchValue == SwitchValue && defaultBody == DefaultBody && cases != null)
{
if (ExpressionUtils.SameElements(ref cases, Cases))
{
return this;
}
}
return Expression.Switch(Type, switchValue, defaultBody, Comparison, cases);
}
}
public partial class Expression
{
/// <summary>
/// Creates a <see cref="SwitchExpression"/>.
/// </summary>
/// <param name="switchValue">The value to be tested against each case.</param>
/// <param name="cases">The valid cases for this switch.</param>
/// <returns>The created <see cref="SwitchExpression"/>.</returns>
public static SwitchExpression Switch(Expression switchValue, params SwitchCase[]? cases)
{
return Switch(switchValue, null, null, (IEnumerable<SwitchCase>?)cases);
}
/// <summary>
/// Creates a <see cref="SwitchExpression"/>.
/// </summary>
/// <param name="switchValue">The value to be tested against each case.</param>
/// <param name="defaultBody">The result of the switch if no cases are matched.</param>
/// <param name="cases">The valid cases for this switch.</param>
/// <returns>The created <see cref="SwitchExpression"/>.</returns>
public static SwitchExpression Switch(Expression switchValue, Expression? defaultBody, params SwitchCase[]? cases)
{
return Switch(switchValue, defaultBody, null, (IEnumerable<SwitchCase>?)cases);
}
/// <summary>
/// Creates a <see cref="SwitchExpression"/>.
/// </summary>
/// <param name="switchValue">The value to be tested against each case.</param>
/// <param name="defaultBody">The result of the switch if no cases are matched.</param>
/// <param name="comparison">The equality comparison method to use.</param>
/// <param name="cases">The valid cases for this switch.</param>
/// <returns>The created <see cref="SwitchExpression"/>.</returns>
public static SwitchExpression Switch(Expression switchValue, Expression? defaultBody, MethodInfo? comparison, params SwitchCase[]? cases)
{
return Switch(switchValue, defaultBody, comparison, (IEnumerable<SwitchCase>?)cases);
}
/// <summary>
/// Creates a <see cref="SwitchExpression"/>.
/// </summary>
/// <param name="type">The result type of the switch.</param>
/// <param name="switchValue">The value to be tested against each case.</param>
/// <param name="defaultBody">The result of the switch if no cases are matched.</param>
/// <param name="comparison">The equality comparison method to use.</param>
/// <param name="cases">The valid cases for this switch.</param>
/// <returns>The created <see cref="SwitchExpression"/>.</returns>
public static SwitchExpression Switch(Type? type, Expression switchValue, Expression? defaultBody, MethodInfo? comparison, params SwitchCase[]? cases)
{
return Switch(type, switchValue, defaultBody, comparison, (IEnumerable<SwitchCase>?)cases);
}
/// <summary>
/// Creates a <see cref="SwitchExpression"/>.
/// </summary>
/// <param name="switchValue">The value to be tested against each case.</param>
/// <param name="defaultBody">The result of the switch if no cases are matched.</param>
/// <param name="comparison">The equality comparison method to use.</param>
/// <param name="cases">The valid cases for this switch.</param>
/// <returns>The created <see cref="SwitchExpression"/>.</returns>
public static SwitchExpression Switch(Expression switchValue, Expression? defaultBody, MethodInfo? comparison, IEnumerable<SwitchCase>? cases)
{
return Switch(null, switchValue, defaultBody, comparison, cases);
}
/// <summary>
/// Creates a <see cref="SwitchExpression"/>.
/// </summary>
/// <param name="type">The result type of the switch.</param>
/// <param name="switchValue">The value to be tested against each case.</param>
/// <param name="defaultBody">The result of the switch if no cases are matched.</param>
/// <param name="comparison">The equality comparison method to use.</param>
/// <param name="cases">The valid cases for this switch.</param>
/// <returns>The created <see cref="SwitchExpression"/>.</returns>
public static SwitchExpression Switch(Type? type, Expression switchValue, Expression? defaultBody, MethodInfo? comparison, IEnumerable<SwitchCase>? cases)
{
ExpressionUtils.RequiresCanRead(switchValue, nameof(switchValue));
if (switchValue.Type == typeof(void)) throw Error.ArgumentCannotBeOfTypeVoid(nameof(switchValue));
ReadOnlyCollection<SwitchCase> caseList = cases.ToReadOnly();
ContractUtils.RequiresNotNullItems(caseList, nameof(cases));
// Type of the result. Either provided, or it is type of the branches.
Type resultType;
if (type != null)
resultType = type;
else if (caseList.Count != 0)
resultType = caseList[0].Body.Type;
else if (defaultBody != null)
resultType = defaultBody.Type;
else
resultType = typeof(void);
bool customType = type != null;
if (comparison != null)
{
ValidateMethodInfo(comparison, nameof(comparison));
ParameterInfo[] pms = comparison.GetParametersCached();
if (pms.Length != 2)
{
throw Error.IncorrectNumberOfMethodCallArguments(comparison, nameof(comparison));
}
// Validate that the switch value's type matches the comparison method's
// left hand side parameter type.
ParameterInfo leftParam = pms[0];
bool liftedCall = false;
if (!ParameterIsAssignable(leftParam, switchValue.Type))
{
liftedCall = ParameterIsAssignable(leftParam, switchValue.Type.GetNonNullableType());
if (!liftedCall)
{
throw Error.SwitchValueTypeDoesNotMatchComparisonMethodParameter(switchValue.Type, leftParam.ParameterType);
}
}
ParameterInfo rightParam = pms[1];
foreach (SwitchCase c in caseList)
{
ArgumentNullException.ThrowIfNull(c, nameof(cases));
ValidateSwitchCaseType(c.Body, customType, resultType, nameof(cases));
for (int i = 0, n = c.TestValues.Count; i < n; i++)
{
// When a comparison method is provided, test values can have different type but have to
// be reference assignable to the right hand side parameter of the method.
Type rightOperandType = c.TestValues[i].Type;
if (liftedCall)
{
if (!rightOperandType.IsNullableType())
{
throw Error.TestValueTypeDoesNotMatchComparisonMethodParameter(rightOperandType, rightParam.ParameterType);
}
rightOperandType = rightOperandType.GetNonNullableType();
}
if (!ParameterIsAssignable(rightParam, rightOperandType))
{
throw Error.TestValueTypeDoesNotMatchComparisonMethodParameter(rightOperandType, rightParam.ParameterType);
}
}
}
// if we have a non-boolean user-defined equals, we don't want it.
if (comparison.ReturnType != typeof(bool))
{
throw Error.EqualityMustReturnBoolean(comparison, nameof(comparison));
}
}
else if (caseList.Count != 0)
{
// When comparison method is not present, all the test values must have
// the same type. Use the first test value's type as the baseline.
Expression firstTestValue = caseList[0].TestValues[0];
foreach (SwitchCase c in caseList)
{
ArgumentNullException.ThrowIfNull(c, nameof(cases));
ValidateSwitchCaseType(c.Body, customType, resultType, nameof(cases));
// When no comparison method is provided, require all test values to have the same type.
for (int i = 0, n = c.TestValues.Count; i < n; i++)
{
if (!TypeUtils.AreEquivalent(firstTestValue.Type, c.TestValues[i].Type))
{
throw Error.AllTestValuesMustHaveSameType(nameof(cases));
}
}
}
// Now we need to validate that switchValue.Type and testValueType
// make sense in an Equal node. Fortunately, Equal throws a
// reasonable error, so just call it.
BinaryExpression equal = Equal(switchValue, firstTestValue, false, comparison);
// Get the comparison function from equals node.
comparison = equal.Method;
}
if (defaultBody == null)
{
if (resultType != typeof(void)) throw Error.DefaultBodyMustBeSupplied(nameof(defaultBody));
}
else
{
ValidateSwitchCaseType(defaultBody, customType, resultType, nameof(defaultBody));
}
return new SwitchExpression(resultType, switchValue, defaultBody, comparison, caseList);
}
/// <summary>
/// If custom type is provided, all branches must be reference assignable to the result type.
/// If no custom type is provided, all branches must have the same type - resultType.
/// </summary>
private static void ValidateSwitchCaseType(Expression @case, bool customType, Type resultType, string parameterName)
{
if (customType)
{
if (resultType != typeof(void))
{
if (!TypeUtils.AreReferenceAssignable(resultType, @case.Type))
{
throw Error.ArgumentTypesMustMatch(parameterName);
}
}
}
else
{
if (!TypeUtils.AreEquivalent(resultType, @case.Type))
{
throw Error.AllCaseBodiesMustHaveSameType(parameterName);
}
}
}
}
}