-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathTupleLiteralCSharpExpression.cs
331 lines (259 loc) · 15.1 KB
/
TupleLiteralCSharpExpression.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
// Prototyping extended expression trees for C#.
//
// bartde - May 2020
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Dynamic.Utils;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using static System.Dynamic.Utils.ContractUtils;
using static System.Dynamic.Utils.TypeUtils;
namespace Microsoft.CSharp.Expressions
{
using static Helpers;
/// <summary>
/// Represents a tuple literal.
/// </summary>
public sealed partial class TupleLiteralCSharpExpression : CSharpExpression
{
internal TupleLiteralCSharpExpression(Type type, ReadOnlyCollection<Expression> arguments, ReadOnlyCollection<string>? argumentNames)
{
Type = type;
Arguments = arguments;
ArgumentNames = argumentNames;
}
/// <summary>
/// Returns the node type of this <see cref="CSharpExpression" />. (Inherited from <see cref="CSharpExpression" />.)
/// </summary>
/// <returns>The <see cref="CSharpExpressionType"/> that represents this expression.</returns>
public sealed override CSharpExpressionType CSharpNodeType => CSharpExpressionType.TupleLiteral;
/// <summary>
/// Gets a collection of arguments used to construct the components of the tuple.
/// </summary>
public ReadOnlyCollection<Expression> Arguments { get; }
/// <summary>
/// Gets a collection of names of the components of the tuple, or <c>null</c> if no names were specified.
/// </summary>
public ReadOnlyCollection<string>? ArgumentNames { get; }
/// <summary>
/// Gets the type of the expression.
/// </summary>
public override Type Type { get; }
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
/// <param name="visitor">The visitor to visit this node with.</param>
/// <returns>The result of visiting this node.</returns>
protected internal override Expression Accept(CSharpExpressionVisitor visitor) => visitor.VisitTupleLiteral(this);
/// <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="arguments">The <see cref="Arguments" /> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public TupleLiteralCSharpExpression Update(IEnumerable<Expression> arguments)
{
if (SameElements(ref arguments!, Arguments))
{
return this;
}
return CSharpExpression.TupleLiteral(Type, arguments, ArgumentNames);
}
/// <summary>
/// Reduces the expression node to a simpler expression.
/// </summary>
/// <returns>The reduced expression.</returns>
public override Expression Reduce()
{
Stack<(ConstructorInfo ctor, MemberInfo[] members)> GetConstructorChain()
{
var res = new Stack<(ConstructorInfo ctor, MemberInfo[] members)>();
void Push(Type type)
{
var arity = type.GetGenericArguments().Length;
var ctor = type.GetConstructors().Single(ctor => ctor.GetParametersCached().Length == arity);
var members = new MemberInfo[arity];
for (int i = 0; i < arity; i++)
{
var member = type.GetField(TupleItemNames[i], BindingFlags.Public | BindingFlags.Instance);
Debug.Assert(member != null);
members[i] = member;
}
res.Push((ctor, members));
}
var current = Type;
Push(current);
while (current.GetGenericTypeDefinition() == MaxTupleType)
{
current = current.GetGenericArguments()[^1];
Push(current);
}
return res;
}
NewExpression CreateTuple(ConstructorInfo ctor, MemberInfo[] members, int firstArg, Expression? rest)
{
var n = members.Length;
var args = new Expression[n];
if (rest != null)
{
n--;
}
for (int i = 0; i < n; i++)
{
args[i] = Arguments[firstArg + i];
}
if (rest != null)
{
args[^1] = rest;
}
return Expression.New(ctor, args, members);
}
// E.g. Tuple`8<int, int, int, int, int, int, int, Tuple`3<int, int, int>>
// 1 2 3 4 5 6 7 8 9 10
var chain = GetConstructorChain();
var argIndex = Arguments.Count;
Expression? res = null;
Debug.Assert(chain.Count > 0);
do
{
var (ctor, members) = chain.Pop();
argIndex -= members.Length - (res != null ? 1 : 0);
res = CreateTuple(ctor, members, argIndex, rest: res);
}
while (chain.Count > 0);
return res;
}
private static readonly string[] TupleItemNames = { "Item1", "Item2", "Item3", "Item4", "Item5", "Item6", "Item7", "Rest" };
}
partial class CSharpExpression
{
/// <summary>
/// Creates a <see cref="TupleLiteralCSharpExpression" /> that represents a tuple literal.
/// </summary>
/// <param name="arguments">An array of one or more of <see cref="Expression" /> objects that represent the components of the tuple.</param>
/// <returns>A <see cref="TupleLiteralCSharpExpression" /> that has the <see cref="CSharpNodeType" /> property equal to <see cref="CSharpExpressionType.TupleLiteral" /> and the <see cref="TupleLiteralCSharpExpression.Arguments" /> and <see cref="TupleLiteralCSharpExpression.ArgumentNames" /> properties set to the specified values.</returns>
public static TupleLiteralCSharpExpression TupleLiteral(params Expression[] arguments) => TupleLiteral(arguments, argumentNames: null);
/// <summary>
/// Creates a <see cref="TupleLiteralCSharpExpression" /> that represents a tuple literal.
/// </summary>
/// <param name="arguments">An array of one or more of <see cref="Expression" /> objects that represent the components of the tuple.</param>
/// <returns>A <see cref="TupleLiteralCSharpExpression" /> that has the <see cref="CSharpNodeType" /> property equal to <see cref="CSharpExpressionType.TupleLiteral" /> and the <see cref="TupleLiteralCSharpExpression.Arguments" /> and <see cref="TupleLiteralCSharpExpression.ArgumentNames" /> properties set to the specified values.</returns>
public static TupleLiteralCSharpExpression TupleLiteral(IEnumerable<Expression> arguments) => TupleLiteral(arguments, argumentNames: null);
/// <summary>
/// Creates a <see cref="TupleLiteralCSharpExpression" /> that represents a tuple literal.
/// </summary>
/// <param name="arguments">An array of one or more of <see cref="Expression" /> objects that represent the components of the tuple.</param>
/// <param name="argumentNames">An array of names corresponding to the tuple components, or <c>null</c> if no names were specified.</param>
/// <returns>A <see cref="TupleLiteralCSharpExpression" /> that has the <see cref="CSharpNodeType" /> property equal to <see cref="CSharpExpressionType.TupleLiteral" /> and the <see cref="TupleLiteralCSharpExpression.Arguments" /> and <see cref="TupleLiteralCSharpExpression.ArgumentNames" /> properties set to the specified values.</returns>
public static TupleLiteralCSharpExpression TupleLiteral(IEnumerable<Expression> arguments, IEnumerable<string>? argumentNames)
{
var args = arguments.ToReadOnly();
RequiresNotEmpty(args, nameof(arguments));
var n = args.Count;
var types = new Type[n];
for (int i = 0; i < n; i++)
{
var arg = args[i];
RequiresNotNull(arg, nameof(arguments));
if (arg.Type == typeof(void))
throw Error.TupleComponentCannotBeVoid(nameof(arguments), i);
types[i] = arg.Type;
}
var type = MakeTupleType(types);
var argNames = argumentNames?.ToReadOnly();
if (argNames != null && argNames.Count != n)
throw Error.InvalidTupleArgumentNamesCount(type, nameof(argumentNames));
return new TupleLiteralCSharpExpression(type, args, argNames);
}
/// <summary>
/// Creates a <see cref="TupleLiteralCSharpExpression" /> that represents a tuple literal.
/// </summary>
/// <param name="type">The <see cref="Type" /> that represents the tuple type.</param>
/// <param name="arguments">An array of one or more of <see cref="Expression" /> objects that represent the components of the tuple.</param>
/// <returns>A <see cref="TupleLiteralCSharpExpression" /> that has the <see cref="CSharpNodeType" /> property equal to <see cref="CSharpExpressionType.TupleLiteral" /> and the <see cref="TupleLiteralCSharpExpression.Arguments" /> and <see cref="TupleLiteralCSharpExpression.ArgumentNames" /> properties set to the specified values.</returns>
public static TupleLiteralCSharpExpression TupleLiteral(Type type, params Expression[] arguments) => TupleLiteral(type, arguments, argumentNames: null);
/// <summary>
/// Creates a <see cref="TupleLiteralCSharpExpression" /> that represents a tuple literal.
/// </summary>
/// <param name="type">The <see cref="Type" /> that represents the tuple type.</param>
/// <param name="arguments">An array of one or more of <see cref="Expression" /> objects that represent the components of the tuple.</param>
/// <returns>A <see cref="TupleLiteralCSharpExpression" /> that has the <see cref="CSharpNodeType" /> property equal to <see cref="CSharpExpressionType.TupleLiteral" /> and the <see cref="TupleLiteralCSharpExpression.Arguments" /> and <see cref="TupleLiteralCSharpExpression.ArgumentNames" /> properties set to the specified values.</returns>
public static TupleLiteralCSharpExpression TupleLiteral(Type type, IEnumerable<Expression> arguments) => TupleLiteral(type, arguments, argumentNames: null);
/// <summary>
/// Creates a <see cref="TupleLiteralCSharpExpression" /> that represents a tuple literal.
/// </summary>
/// <param name="type">The <see cref="Type" /> that represents the tuple type.</param>
/// <param name="arguments">An array of one or more of <see cref="Expression" /> objects that represent the components of the tuple.</param>
/// <param name="argumentNames">An array of names corresponding to the tuple components, or <c>null</c> if no names were specified.</param>
/// <returns>A <see cref="TupleLiteralCSharpExpression" /> that has the <see cref="CSharpNodeType" /> property equal to <see cref="CSharpExpressionType.TupleLiteral" /> and the <see cref="TupleLiteralCSharpExpression.Arguments" /> and <see cref="TupleLiteralCSharpExpression.ArgumentNames" /> properties set to the specified values.</returns>
public static TupleLiteralCSharpExpression TupleLiteral(Type type, IEnumerable<Expression> arguments, IEnumerable<string>? argumentNames)
{
RequiresNotNull(type, nameof(type));
if (!IsTupleType(type))
throw Error.InvalidTupleType(type, nameof(type));
static List<ParameterInfo> GetTupleConstructorParameters(Type type, int n)
{
var res = new List<ParameterInfo>(n);
while (type != null)
{
var parameters = type.GetConstructors().Single().GetParameters();
var def = type.GetGenericTypeDefinition();
if (def == MaxTupleType)
{
for (int i = 0; i < parameters.Length - 1; i++)
{
res.Add(parameters[i]);
}
type = type.GetGenericArguments()[^1];
}
else
{
res.AddRange(parameters);
break;
}
}
return res;
}
#pragma warning disable CA1062 // Validate arguments of public methods. (See bug https://github.com/dotnet/roslyn-analyzers/issues/6163)
var args = arguments.ToReadOnly();
var n = args.Count;
#pragma warning restore CA1062 // Validate arguments of public methods
var parameters = GetTupleConstructorParameters(type, n);
if (parameters.Count != n)
throw Error.InvalidTupleArgumentCount(type, nameof(type));
for (int i = 0; i < n; i++)
{
//
// NB: With deconstructing assignment, a tuple literal can occur as an lhs. The checks below will
// only check assignability but will not enforce RequiresCanRead(args[i]) to avoid rejecting
// set-only properties. These will fail during a call to Reduce if the tuple literal is used
// as an rvalue.
//
var parameterType = parameters[i].ParameterType;
var argumentType = args[i].Type;
ValidateType(parameterType, nameof(type), i);
if (!AreReferenceAssignable(parameterType, argumentType))
throw Error.ExpressionTypeDoesNotMatchParameter(argumentType, parameterType, nameof(type), i);
}
var argNames = argumentNames?.ToReadOnly();
if (argNames != null && argNames.Count != n)
throw Error.InvalidTupleArgumentNamesCount(type, nameof(argumentNames));
return new TupleLiteralCSharpExpression(type, args, argNames);
}
}
partial class CSharpExpressionVisitor
{
/// <summary>
/// Visits the children of the <see cref="TupleLiteralCSharpExpression" />.
/// </summary>
/// <param name="node">The expression to visit.</param>
/// <returns>The modified expression, if it or any subexpression was modified; otherwise, returns the original expression.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", Justification = "Following the visitor pattern from System.Linq.Expressions.")]
protected internal virtual Expression VisitTupleLiteral(TupleLiteralCSharpExpression node) =>
node.Update(
Visit(node.Arguments)
);
}
}