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
|
// 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;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class VisitorTests
{
private class UsingExpression : Expression
{
public UsingExpression(Expression disposable, Expression body)
{
if (!typeof(IDisposable).IsAssignableFrom(disposable.Type))
{
throw new ArgumentException();
}
// Omit other exception handling as this is just an example for testing purposes.
Disposable = disposable;
Body = body;
}
private Expression Disposable { get; }
private Expression Body { get; }
public override bool CanReduce => true;
public override Expression Reduce()
{
if (Disposable.Type.GetTypeInfo().IsValueType)
{
return TryFinally(
Body,
Call(
Disposable,
typeof(IDisposable).GetMethod(nameof(IDisposable.Dispose))
)
);
}
return TryFinally(
Body,
IfThen(
ReferenceNotEqual(Disposable, Constant(null)),
Call(
Disposable,
typeof(IDisposable).GetMethod(nameof(IDisposable.Dispose))
)
)
);
}
public override Type Type => Body.Type;
public override ExpressionType NodeType => ExpressionType.Extension;
}
private class ForEachExpression : Expression
{
public ForEachExpression(ParameterExpression item, Expression enumerable, Expression body)
{
ItemVariable = item;
Enumerable = enumerable;
Body = body;
}
public ParameterExpression ItemVariable { get; }
public Expression Enumerable { get; }
public Expression Body { get; }
public override bool CanReduce => true;
public override Type Type => typeof(void);
public override ExpressionType NodeType => ExpressionType.Extension;
public override Expression Reduce()
{
var enType = typeof(IEnumerator<>).MakeGenericType(ItemVariable.Type);
var enumerator = Variable(enType);
var breakLabel = Label();
return Block(
new[] {ItemVariable, enumerator},
Assign(enumerator, Call(Enumerable, typeof(IEnumerable<>).MakeGenericType(ItemVariable.Type).GetMethod(nameof(IEnumerable.GetEnumerator)))),
new UsingExpression(
enumerator,
Loop(
Block(
IfThen(
IsFalse(
Call(enumerator, typeof(IEnumerator).GetMethod(nameof(IEnumerator.MoveNext)))
),
Break(breakLabel)
),
Assign(ItemVariable, Property(enumerator, enType.GetProperty(nameof(IEnumerator.Current)))),
Body
),
breakLabel
)
)
);
}
}
private class DefaultVisitor : ExpressionVisitor
{
}
private class ConstantRefreshingVisitor : ExpressionVisitor
{
protected override Expression VisitConstant(ConstantExpression node)
=> Expression.Constant(node.Value, node.Type);
}
private class ResultExpression : Expression
{
}
private class SourceExpression : Expression
{
protected override Expression Accept(ExpressionVisitor visitor) => new ResultExpression();
}
private class NullBecomingExpression : Expression
{
protected override Expression Accept(ExpressionVisitor visitor) => null;
}
private static string UpperCaseIfNotAlready(string value)
{
if (string.IsNullOrEmpty(value))
{
return value;
}
string upper = value.ToUpperInvariant();
return upper == value ? value : upper;
}
[Fact]
public void IsAbstract()
{
Assert.True(typeof(ExpressionVisitor).GetTypeInfo().IsAbstract);
}
[Fact]
public void VisitNullDefaultsToReturnNull()
{
Assert.Null(new DefaultVisitor().Visit(default(Expression)));
}
[Fact]
public void VisitExpressionDefaultsCallAccept()
{
Assert.IsType<ResultExpression>(new DefaultVisitor().Visit(new SourceExpression()));
}
[Fact]
public void VisitNullCollection()
{
Assert.Throws<ArgumentNullException>("nodes", () => new DefaultVisitor().Visit(default(ReadOnlyCollection<Expression>)));
}
[Fact]
public void VisitNullCollectionWithVisitorFunction()
{
Assert.Throws<ArgumentNullException>("nodes", () => ExpressionVisitor.Visit(null, (Expression i) => i));
}
[Fact]
public void VisitCollectionVisitorWithNullFunction()
{
Assert.Throws<ArgumentNullException>("elementVisitor", () => ExpressionVisitor.Visit(new List<Expression> { Expression.Empty() }.AsReadOnly(), null));
}
[Fact]
public void VisitAndConvertNullNode()
{
Assert.Null(new DefaultVisitor().VisitAndConvert(default(Expression), ""));
}
[Fact]
public void VisitAndConvertNullCollection()
{
Assert.Throws<ArgumentNullException>("nodes", () => new DefaultVisitor().VisitAndConvert(default(ReadOnlyCollection<Expression>), ""));
}
[Fact]
public void VisitCollectionReturnSameIfChildrenUnchanged()
{
var collection = new List<Expression> { Expression.Constant(0), Expression.Constant(2) }.AsReadOnly();
Assert.Same(collection, new DefaultVisitor().Visit(collection));
}
[Fact]
public void VisitCollectionDifferOnFirst()
{
string value = new string(new[] { 'a', 'b', 'c' });
var collection = new List<Expression> { Expression.Constant(value) }.AsReadOnly();
var visited = new ConstantRefreshingVisitor().Visit(collection);
Assert.NotSame(collection, visited);
Assert.NotSame(collection[0], visited[0]);
Assert.Same(value, ((ConstantExpression)visited[0]).Value);
}
[Fact]
public void VisitCollectionDifferOnLater()
{
string value = new string(new[] { 'a', 'b', 'c' });
var collection = new List<Expression> { Expression.Empty(), Expression.Constant(value) }.AsReadOnly();
var visited = new ConstantRefreshingVisitor().Visit(collection);
Assert.NotSame(collection, visited);
Assert.Same(collection[0], visited[0]);
Assert.NotSame(collection[1], visited[1]);
Assert.Same(value, ((ConstantExpression)visited[1]).Value);
}
[Fact]
public void VisitCollectionNullNodes()
{
var collection = new List<Expression> { null, null, null }.AsReadOnly();
Assert.Same(collection, new DefaultVisitor().Visit(collection));
}
[Fact]
public void VisitCollectionWithElementVisitorReturnSameIfChildrenUnchanged()
{
var collection = new List<string> { "ABC", "DEF" }.AsReadOnly();
Assert.Same(collection, ExpressionVisitor.Visit(collection, UpperCaseIfNotAlready));
}
[Fact]
public void VisitCollectionWithElementVisitorDifferOnFirst()
{
var collection = new List<string> { "abc" }.AsReadOnly();
var visited = ExpressionVisitor.Visit(collection, UpperCaseIfNotAlready);
Assert.NotSame(collection, visited);
Assert.NotSame(collection[0], visited[0]);
}
[Fact]
public void VisitCollectionWithElementVisitorDifferOnLater()
{
var collection = new List<string> { "ABC", "def", "GHI", "jkl" }.AsReadOnly();
var visited = ExpressionVisitor.Visit(collection, UpperCaseIfNotAlready);
Assert.NotSame(collection, visited);
Assert.Same(collection[0], visited[0]);
Assert.NotSame(collection[1], visited[1]);
Assert.Same(collection[2], visited[2]);
Assert.NotSame(collection[3], visited[3]);
}
[Fact]
public void VisitCollectionWithElementVisitorNullNodes()
{
var collection = new List<string> { null, null, null }.AsReadOnly();
Assert.Same(collection, ExpressionVisitor.Visit(collection, UpperCaseIfNotAlready));
}
[Fact]
public void VisitAndConvertReturnsSameIfVisitDoes()
{
var constant = Expression.Constant(0);
Assert.Same(constant, new DefaultVisitor().Visit(constant));
Assert.Same(constant, new DefaultVisitor().VisitAndConvert(constant, "foo"));
}
[Fact]
public void VisitAndConvertThrowsIfVisitReturnsNull()
{
string slug = "Won't be found by chance 3f8d0006-32f9-4622-9ff4-c88e95c9babc";
string errMsg = Assert.Throws<InvalidOperationException>(() => new DefaultVisitor().VisitAndConvert(new NullBecomingExpression(), slug)).Message;
Assert.Contains(slug, errMsg);
}
[Fact]
public void VisitAndConvertThrowsIfVisitChangesType()
{
string slug = "Won't be found by chance 5154E15C-A475-49B0-B596-8F822D7ACFC4";
string errMsg = Assert.Throws<InvalidOperationException>(() => new DefaultVisitor().VisitAndConvert(new SourceExpression(), slug)).Message;
Assert.Contains(slug, errMsg);
}
[Fact]
public void VisitAndConvertNullName()
{
new DefaultVisitor().VisitAndConvert(Expression.Constant(0), null);
Assert.Throws<InvalidOperationException>(() => new DefaultVisitor().VisitAndConvert(new SourceExpression(), null));
}
[Fact]
public void VisitAndConvertReturnsIfForcedToCommonBase()
{
Assert.IsNotType<SourceExpression>(new DefaultVisitor().VisitAndConvert<Expression>(new SourceExpression(), ""));
}
[Fact]
public void VisitAndConvertSameResultAsVisit()
{
var constant = Expression.Constant(0);
var visited = new ConstantRefreshingVisitor().VisitAndConvert(constant, "");
Assert.NotSame(constant, visited);
Assert.Equal(0, visited.Value);
}
[Fact]
public void ReduceChildrenCascades()
{
var intVar = Expression.Variable(typeof(int));
List<int> list = new List<int>();
var foreachExp = new ForEachExpression(
intVar,
Expression.Constant(Enumerable.Range(5, 4)),
Expression.Call(
Expression.Constant(list),
typeof(List<int>).GetMethod(nameof(List<int>.Insert)),
Expression.Constant(0),
intVar
)
);
// Check that not only has the visitor reduced the foreach into a block
// but the using within that block into a try…finally.
var reduced = new DefaultVisitor().Visit(foreachExp);
var block = (BlockExpression)reduced;
var tryExp = (TryExpression)block.Expressions[1];
var loop = (LoopExpression)tryExp.Body;
var innerBlock = (BlockExpression)loop.Body;
var call = (MethodCallExpression)innerBlock.Expressions.Last();
var instance = (ConstantExpression)call.Object;
Assert.Same(list, instance.Value);
}
}
}
|