My favorites | Sign in
Project Home Downloads Issues Source
Checkout   Browse   Changes    
 
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
// Copyright 2005-2009 Gallio Project - http://www.gallio.org/
// Portions Copyright 2000-2004 Jonathan de Halleux
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace Gallio.Common.Linq
{
/// <summary>
/// Instuments an <see cref="Expression{T}" /> to intercept intermediate results
/// from each sub-expression.
/// </summary>
public abstract class ExpressionInstrumentor
{
private static readonly MethodInfo interceptVoidMethod =
typeof(ExpressionInstrumentor).GetMethod("InterceptVoid", BindingFlags.NonPublic | BindingFlags.Instance);
private static readonly MethodInfo interceptNonVoidMethod =
typeof(ExpressionInstrumentor).GetMethod("InterceptNonVoid", BindingFlags.NonPublic | BindingFlags.Instance);

/// <summary>
/// Compiles an expression to introduce trace points.
/// </summary>
/// <typeparam name="T">The expression type.</typeparam>
/// <param name="expr">The expression tree.</param>
/// <returns>The compiled delegate representing expression.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="expr"/> is null.</exception>
public T Compile<T>(Expression<T> expr)
{
return Rewrite(expr).Compile();
}

/// <summary>
/// Rewrites an expression tree to introduce trace points.
/// </summary>
/// <typeparam name="T">The expression type.</typeparam>
/// <param name="expr">The expression tree.</param>
/// <returns>The compiled delegate representing expression.</returns>
/// <exception cref="ArgumentNullException">Thrown if <paramref name="expr"/> is null.</exception>
public Expression<T> Rewrite<T>(Expression<T> expr)
{
if (expr == null)
throw new ArgumentNullException("expr");

return Expression.Lambda<T>(
new Rewriter(this).RewriteExpression(expr.Body),
expr.Parameters);
}

/// <summary>
/// Evaluates a sub-expression and collects trace information.
/// </summary>
/// <typeparam name="T">The return type of the sub-expression.</typeparam>
/// <param name="expr">The sub-expression to evaluate.</param>
/// <param name="continuation">The continuation that evaluates the sub-expression.</param>
/// <returns>The result of the evaluation.</returns>
[DebuggerHidden, DebuggerStepThrough]
protected virtual T Intercept<T>(Expression expr, System.Func<T> continuation)
{
return continuation();
}

[DebuggerHidden, DebuggerStepThrough]
private void InterceptVoid(Expression expr, System.Action continuation)
{
Intercept(expr, continuation.AsUnitFunc());
}

[DebuggerHidden, DebuggerStepThrough]
private T InterceptNonVoid<T>(Expression expr, System.Func<T> continuation)
{
return Intercept(expr, continuation);
}

private sealed class Rewriter : ExpressionVisitor<Expression>
{
private readonly ExpressionInstrumentor instrumentor;

public Rewriter(ExpressionInstrumentor instrumentor)
{
this.instrumentor = instrumentor;
}

public Expression RewriteExpression(Expression expr)
{
if (expr == null)
return null;

Expression rewrittenExpr = Visit(expr);
Type exprType = expr.Type;

Debug.Assert(rewrittenExpr.NodeType == expr.NodeType, String.Format(
"The rewritten expression node type '{0}' should equal the original expression node type '{1}'.", rewrittenExpr.NodeType, expr.NodeType));
Debug.Assert(rewrittenExpr.Type == exprType, String.Format(
"The rewritten expression type '{0}' should equal the original expression type '{1}'.", rewrittenExpr.Type, exprType));

if (exprType == typeof(void))
{
return Expression.Call(
Expression.Constant(instrumentor),
interceptVoidMethod,
Expression.Constant(expr),
Expression.Lambda(
typeof(System.Action),
rewrittenExpr));
}
else
{
// Note: This is a tricky little hack.
// Expression nodes for NewArrayInit or NewArrayBounds have a type which is
// not a sized array. You can see this because the type will print like
// "Int32[*]" instead of "Int32[]". It turns out that you get a
// VerificationException when calling a generic function specialized to a
// rank-1 rather than sized array type. So here we detect the case and
// ensure that we use a sized array. Not sure if there will be any deeper
// consequences... -- Jeff.
if (exprType.IsArray && exprType.GetArrayRank() == 1)
exprType = exprType.GetElementType().MakeArrayType();

return Expression.Call(
Expression.Constant(instrumentor),
interceptNonVoidMethod.MakeGenericMethod(exprType),
Expression.Constant(expr),
Expression.Lambda(
typeof(System.Func<>).MakeGenericType(exprType),
rewrittenExpr));
}
}

protected override Expression VisitBinary(BinaryExpression expr)
{
return Expression.MakeBinary(
expr.NodeType,
RewriteExpression(expr.Left),
RewriteExpression(expr.Right),
expr.IsLiftedToNull,
expr.Method,
expr.Conversion);
}

protected override Expression VisitUnary(UnaryExpression expr)
{
if (expr.NodeType == ExpressionType.Quote)
return expr;
if (expr.NodeType == ExpressionType.UnaryPlus)
return Expression.UnaryPlus(RewriteExpression(expr.Operand), expr.Method);

return Expression.MakeUnary(
expr.NodeType,
RewriteExpression(expr.Operand),
expr.Type,
expr.Method);
}

protected override Expression VisitMethodCall(MethodCallExpression expr)
{
return Expression.Call(
RewriteExpression(expr.Object),
expr.Method,
RewriteExpressions(expr.Arguments));
}

protected override Expression VisitConditional(ConditionalExpression expr)
{
return Expression.Condition(
RewriteExpression(expr.Test),
RewriteExpression(expr.IfTrue),
RewriteExpression(expr.IfFalse));
}

protected override Expression VisitInvocation(InvocationExpression expr)
{
return Expression.Invoke(
RewriteExpression(expr.Expression),
RewriteExpressions(expr.Arguments));
}

protected override Expression VisitListInit(ListInitExpression expr)
{
return Expression.ListInit(
expr.NewExpression,
RewriteInitializers(expr.Initializers));
}

protected override Expression VisitMember(MemberExpression expr)
{
return Expression.MakeMemberAccess(
RewriteExpression(expr.Expression),
expr.Member);
}

protected override Expression VisitMemberInit(MemberInitExpression expr)
{
return Expression.MemberInit(expr.NewExpression,
RewriteBindings(expr.Bindings));
}

protected override Expression VisitNew(NewExpression expr)
{
// Note: We get an ArgumentException when Members is null and we use the
// full specification of the New expression.
if (expr.Members == null)
return Expression.New(
expr.Constructor,
RewriteExpressions(expr.Arguments));

return Expression.New(
expr.Constructor,
RewriteExpressions(expr.Arguments),
expr.Members);
}

protected override Expression VisitNewArray(NewArrayExpression expr)
{
if (expr.NodeType == ExpressionType.NewArrayInit)
{
return Expression.NewArrayInit(
expr.Type.GetElementType(),
RewriteExpressions(expr.Expressions));
}

return Expression.NewArrayBounds(
expr.Type.GetElementType(),
RewriteExpressions(expr.Expressions));
}

protected override Expression VisitTypeBinary(TypeBinaryExpression expr)
{
return Expression.TypeIs(
RewriteExpression(expr.Expression),
expr.TypeOperand);
}

protected override Expression VisitAny(Expression expr)
{
return expr;
}

private IEnumerable<MemberBinding> RewriteBindings(IEnumerable<MemberBinding> bindings)
{
foreach (MemberBinding binding in bindings)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
yield return Expression.Bind(binding.Member, RewriteExpression(((MemberAssignment)binding).Expression));
break;
case MemberBindingType.ListBinding:
yield return Expression.ListBind(binding.Member, RewriteInitializers(((MemberListBinding)binding).Initializers));
break;
case MemberBindingType.MemberBinding:
yield return Expression.MemberBind(binding.Member, RewriteBindings(((MemberMemberBinding)binding).Bindings));
break;
}
}
}

private IEnumerable<ElementInit> RewriteInitializers(IEnumerable<ElementInit> inits)
{
foreach (ElementInit init in inits)
yield return Expression.ElementInit(init.AddMethod, RewriteExpressions(init.Arguments));
}

private IEnumerable<Expression> RewriteExpressions(IEnumerable<Expression> exprs)
{
return from e in exprs select RewriteExpression(e);
}
}
}
}

Change log

r2362 by jeff.brown on Nov 18, 2009   Diff
Creating tag for v3.1 Update 2
Go to: 
Project members, sign in to write a code review

Older revisions

r2012 by jeff.brown on Jul 20, 2009   Diff
Create a release branch for v3.1.
r1997 by yann.trevin on Jul 15, 2009   Diff
Added some rules to the XML doc
verification scripts (mostly to detect
empty elements)
Fixed a plethora of bugs and typos in
the XML doc.
r1764 by jeff.brown on May 8, 2009   Diff
Refactored Gallio namespaces to reduce
coupling across tiers motivated by a
little poking around with NDepend.
Gathered common data types and
utilities into a new Common namespace
...
All revisions of this file

File info

Size: 12359 bytes, 285 lines
Powered by Google Project Hosting