-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathMacroExpander.cs
225 lines (176 loc) · 8.18 KB
/
MacroExpander.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Semantics;
namespace Cometary.Macros
{
using Extensions;
/// <summary>
/// <see cref="CSharpSyntaxRewriter"/> that can expand macros.
/// </summary>
internal sealed class MacroExpander : CSharpSyntaxRewriter
{
private readonly SemanticModel semanticModel;
private readonly CancellationToken cancellationToken;
private readonly Dictionary<StatementSyntax, StatementSyntax> changes;
internal MacroExpander(CSharpSyntaxTree syntaxTree, CSharpCompilation compilation, CancellationToken cancellationToken)
{
this.cancellationToken = cancellationToken;
this.semanticModel = compilation.GetSemanticModel(syntaxTree, true);
this.changes = new Dictionary<StatementSyntax, StatementSyntax>();
}
public override SyntaxNode Visit(SyntaxNode node)
{
if (node is StatementSyntax stmt)
{
// Allow a Visit*Expression method to return a statement.
var result = stmt.Accept(this);
if (changes.TryGetValue(stmt, out StatementSyntax newStmt))
{
changes.Remove(stmt);
return newStmt;
}
return result;
}
return base.Visit(node);
}
public override SyntaxNode VisitMemberAccessExpression(MemberAccessExpressionSyntax node)
{
IOperation operation = semanticModel.GetOperation(node, cancellationToken);
if (operation == null || !operation.IsInvalid)
return base.VisitMemberAccessExpression(node);
// Expression is invalid, might be a late-bound object
IOperation expression = semanticModel.GetOperation(node.Expression, cancellationToken);
if (expression.IsInvalid)
return base.VisitMemberAccessExpression(node);
// Find out if it is a late-bound object...
INamedTypeSymbol type = expression.Type as INamedTypeSymbol;
if (type == null)
return base.VisitMemberAccessExpression(node);
// ... by finding its Bind method
object[] arguments = null;
bool IsValidBindMethod(MethodInfo mi)
{
if (!mi.IsStatic || mi.IsAbstract || mi.Name != "Bind")
return false;
if (!typeof(ExpressionSyntax).IsAssignableFrom(mi.ReturnType))
return false;
ParameterInfo[] parameters = mi.GetParameters();
object[] args = new object[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
Type paramType = parameters[i].ParameterType;
if (paramType.IsAssignableFrom(typeof(MemberAccessExpressionSyntax)))
args[i] = node;
else if (paramType == typeof(IOperation))
args[i] = expression;
else
return false;
}
arguments = args;
return true;
}
Type correspondingType = type.GetCorrespondingType();
if (correspondingType == null)
return base.VisitMemberAccessExpression(node);
MethodInfo bindMethod = correspondingType
.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)
.FirstOrDefault(IsValidBindMethod);
if (bindMethod == null)
return base.VisitMemberAccessExpression(node);
// We do have a binder!
// Call the method
try
{
ExpressionSyntax result = bindMethod.Invoke(null, arguments) as ExpressionSyntax;
return result == null
? SyntaxFactory.LiteralExpression(SyntaxKind.NullLiteralExpression)
: base.Visit(result);
}
catch (Exception e)
{
throw new DiagnosticException("Error thrown by binding method.", e, node.GetLocation());
}
}
public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax node)
{
IInvocationExpression invocation = semanticModel.GetOperation(node, cancellationToken) as IInvocationExpression;
if (invocation == null)
return base.VisitInvocationExpression(node);
bool IsMacroMethod(ISymbol methodSymbol, out string error)
{
foreach (var attr in methodSymbol.GetAttributes())
{
if (attr.AttributeClass.MetadataName != nameof(ExpandAttribute))
continue;
if (!methodSymbol.IsStatic)
error = "The target method must be static.";
else
error = null;
return true;
}
error = null;
return false;
}
// Check if it's a call to a macro method
var target = invocation.TargetMethod;
if (!IsMacroMethod(target, out string err))
return base.VisitInvocationExpression(node);
// Make sure it's valid
if (err != null)
throw new DiagnosticException($"Cannot call the specified method as a macro method: {err}.",
invocation.Syntax.GetLocation());
// It is a method, find it
MethodInfo method = target.GetCorrespondingMethod() as MethodInfo;
if (method == null)
throw new DiagnosticException("Cannot find corresponding method.", invocation.Syntax.GetLocation());
// Found it, make the arguments
ParameterInfo[] parameters = method.GetParameters();
object[] arguments = new object[parameters.Length];
for (int i = 0; i < arguments.Length; i++)
{
ParameterInfo param = parameters[i];
Type paramType = param.ParameterType;
if (param.HasDefaultValue)
arguments[i] = param.DefaultValue;
else
arguments[i] = paramType.GetTypeInfo().IsValueType
? Activator.CreateInstance(paramType)
: null;
}
// Set up the context
var statementSyntax = node.FirstAncestorOrSelf<StatementSyntax>();
var statementSymbol = new Lazy<IOperation>(() => semanticModel.GetOperation(statementSyntax, cancellationToken));
var callerSymbol = new Lazy<IMethodSymbol>(() => semanticModel.GetEnclosingSymbol(statementSyntax.SpanStart, cancellationToken) as IMethodSymbol);
var callerInfo = new Lazy<MethodInfo>(() => callerSymbol.Value?.GetCorrespondingMethod() as MethodInfo);
ExpressionSyntax expr;
StatementSyntax stmt;
using (CallBinder.EnterContext(invocation, statementSymbol, node, statementSyntax, method, target, callerInfo, callerSymbol))
{
// Invoke the method
try
{
method.Invoke(null, arguments);
}
catch (Exception e)
{
throw new DiagnosticException($"Exception thrown when expanding the '{method}' macro.", e, invocation.Syntax.GetLocation());
}
(expr, stmt) = CallBinder.Result;
}
// Edit the node accordingly
if (stmt != statementSyntax)
{
// Return the new statement
changes.Add(statementSyntax, stmt.WithTriviaFrom(statementSyntax).Accept(this) as StatementSyntax);
return node;
}
return base.Visit(expr == node ? expr : expr.WithTriviaFrom(node));
}
}
}