-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntroduceVariableReferences.cs
More file actions
404 lines (337 loc) · 16.6 KB
/
Copy pathIntroduceVariableReferences.cs
File metadata and controls
404 lines (337 loc) · 16.6 KB
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using JSIL.Ast;
using JSIL.Internal;
using Mono.Cecil;
namespace JSIL.Transforms {
public class IntroduceVariableReferences : JSAstVisitor {
public const bool Tracing = false;
public readonly HashSet<string> TransformedVariables = new HashSet<string>();
public readonly Dictionary<string, JSVariable> Variables;
public readonly JSILIdentifier JSIL;
public readonly IFunctionSource FunctionSource;
protected readonly HashSet<JSPassByReferenceExpression> ReferencesToTransform = new HashSet<JSPassByReferenceExpression>(
new ReferenceComparer<JSPassByReferenceExpression>()
);
protected readonly Dictionary<JSVariableDeclarationStatement, JSBlockStatement> Declarations = new Dictionary<JSVariableDeclarationStatement, JSBlockStatement>(
new ReferenceComparer<JSVariableDeclarationStatement>()
);
public IntroduceVariableReferences (JSILIdentifier jsil, Dictionary<string, JSVariable> variables, IFunctionSource functionSource) {
JSIL = jsil;
Variables = variables;
FunctionSource = functionSource;
}
public TypeSystem TypeSystem {
get {
return JSIL.TypeSystem;
}
}
protected bool MatchesConstructedReference (JSExpression lhs, JSVariable rhs) {
var jsv = lhs as JSVariable;
if ((jsv != null) && (jsv.Identifier == rhs.Identifier))
return true;
return false;
}
protected JSVariable GetReferentVariable (JSPassByReferenceExpression pbr) {
JSVariable referentVariable;
JSExpression referent;
if (!JSReferenceExpression.TryMaterialize(JSIL, pbr.Referent, out referent)) {
if (JSReferenceExpression.TryDereference(JSIL, pbr.Referent, out referent)) {
referentVariable = referent as JSVariable;
return referentVariable;
} else
return null;
}
referentVariable = referent as JSVariable;
return referentVariable;
}
protected JSVariable GetConstructedReference (JSPassByReferenceExpression pbr) {
JSVariable referentVariable;
JSExpression referent;
if (!JSReferenceExpression.TryMaterialize(JSIL, pbr.Referent, out referent)) {
// If the reference can be dereferenced, but cannot be materialized, it is
// a constructed reference.
if (JSReferenceExpression.TryDereference(JSIL, pbr.Referent, out referent)) {
referentVariable = referent as JSVariable;
// Ignore variables we previously transformed.
if ((referentVariable != null) && TransformedVariables.Contains(referentVariable.Identifier))
return null;
return referentVariable;
} else
return null;
}
referentVariable = referent as JSVariable;
if (referentVariable == null)
return null;
// Ignore variables we previously transformed.
if (TransformedVariables.Contains(referentVariable.Identifier))
return null;
// If the variable does not match the one in the dictionary, it is a constructed
// reference to a parameter.
var theVariable = Variables[referentVariable.Identifier];
if (!referentVariable.Equals(theVariable)) {
// If the parameter is a reference, we don't care about it.
if (theVariable.IsReference) {
// Unless it's the 'this' variable...
if (theVariable.IsThis) {
// But we handle that separately.
return referentVariable;
} else {
return null;
}
} else
return referentVariable;
}
return null;
}
protected void TransformParameterIntoReference (JSVariable parameter, JSBlockStatement block) {
var newParameter = new JSParameter("$" + parameter.Identifier, parameter.IdentifierType, parameter.Function);
var newVariable = new JSVariable(parameter.Identifier, new ByReferenceType(parameter.IdentifierType), parameter.Function);
var newDeclaration = new JSVariableDeclarationStatement(
new JSBinaryOperatorExpression(
JSOperator.Assignment,
// We have to use parameter here, not newVariable or newParameter, otherwise the resulting
// assignment looks like 'x.value = initializer' instead of 'x = initializer'
parameter,
JSIL.NewReference(newParameter),
newVariable.IdentifierType
)
);
if (Tracing)
Console.WriteLine(String.Format("Transformed {0} into {1}={2}", parameter, newVariable, newParameter));
Variables[newVariable.Identifier] = newVariable;
Variables.Add(newParameter.Identifier, newParameter);
var enclosingFunction = Stack.OfType<JSFunctionExpression>().First();
enclosingFunction.Body.Statements.Insert(0, newDeclaration);
var oldIndex = Array.IndexOf(enclosingFunction.Parameters, parameter);
enclosingFunction.Parameters[oldIndex] = newParameter;
}
protected void TransformVariableIntoReference (JSVariable variable, JSVariableDeclarationStatement statement, int declarationIndex, JSBlockStatement enclosingBlock) {
var oldDeclaration = statement.Declarations[declarationIndex];
var valueType = oldDeclaration.Right.GetActualType(JSIL.TypeSystem);
var newVariable = variable.Reference();
var enclosingFunction = Stack.OfType<JSFunctionExpression>().First();
JSExpression initialValue;
// If the declaration was in function scope originally we can hoist the initial value
// into our new variable declaration. If not, we need to initialize the ref variable
// to the default value for its type. It will get the correct value assigned later.
if (enclosingBlock == enclosingFunction.Body)
initialValue = oldDeclaration.Right;
else
initialValue = new JSDefaultValueLiteral(valueType);
var newDeclaration = new JSVariableDeclarationStatement(new JSBinaryOperatorExpression(
JSOperator.Assignment,
// We have to use a constructed ref to the variable here, otherwise
// the declaration will look like 'var x.value = foo'
new JSVariable(variable.Identifier, variable.IdentifierType, variable.Function),
JSIL.NewReference(initialValue),
newVariable.IdentifierType
));
if (Tracing)
Console.WriteLine(String.Format("Transformed {0} into {1} in {2}", variable, newVariable, statement));
// Insert the new declaration directly before the top-level block containing the original
// declaration. This ensures that if its initial value has a dependency on external state,
// the declaration will not precede the values it depends on.
// Note that for declarations that were hoisted out of inner blocks (conditionals, loops)
// it doesn't actually matter where the insert occurs, since we initialize with a default
// value in that case.
enclosingFunction.Body.InsertNearChildRecursive(
statement, newDeclaration, 0
);
// If the reference is being declared in function scope, it doesn't need a separate assignment
// for its initialization. Otherwise, we need to insert an assignment after the original variable
// declaration statement to ensure that the reference variable is initialized to the right value
// at the exact right point in the function's execution.
if (enclosingBlock != enclosingFunction.Body) {
var newAssignment = new JSExpressionStatement(
new JSBinaryOperatorExpression(
JSOperator.Assignment, newVariable, oldDeclaration.Right, valueType
)
);
var insertLocation = enclosingBlock.Statements.IndexOf(statement) + 1;
enclosingBlock.Statements.Insert(insertLocation, newAssignment);
}
Variables[variable.Identifier] = newVariable;
statement.Declarations.RemoveAt(declarationIndex);
TransformedVariables.Add(variable.Identifier);
}
public void VisitNode (JSPassByReferenceExpression pbr) {
if (GetConstructedReference(pbr) != null)
ReferencesToTransform.Add(pbr);
VisitChildren(pbr);
}
public void VisitNode (JSVariableDeclarationStatement vds) {
var parentBlock = (JSBlockStatement)ParentNode;
// FIXME: Is this right?
JSBlockStatement existing;
if (Declarations.TryGetValue(vds, out existing)) {
if (existing != parentBlock)
throw new InvalidDataException("Multiple parents for a single declaration statement");
} else {
Declarations.Add(vds, parentBlock);
}
VisitChildren(vds);
}
public void VisitNode (JSFunctionExpression fn) {
VisitChildren(fn);
foreach (var p in fn.Parameters) {
if (!p.IsReference)
continue;
var vrat = new VariableReferenceAccessTransformer(JSIL, p, FunctionSource);
vrat.Visit(fn);
}
/*
if (!fn.Method.Method.IsStatic) {
var vrat = new VariableReferenceAccessTransformer(JSIL, Variables["this"]);
vrat.Visit(fn);
}
*/
foreach (var r in ReferencesToTransform) {
var cr = GetConstructedReference(r);
if (cr == null) {
// We have already done the variable transform for this variable in the past.
continue;
}
// For 'ref this', we need to replace each individual expression, because we can't
// rename the this-variable.
if (cr.IsThis) {
var refThis = JSIL.NewReference(Variables["this"]);
fn.ReplaceChildRecursive(r, refThis);
continue;
}
var parameter = (from p in fn.Parameters
where p.Identifier == cr.Identifier
select p).FirstOrDefault();
if (parameter != null) {
TransformParameterIntoReference(parameter, fn.Body);
} else {
var declaration = (from kvp in Declarations
let vds = kvp.Key
from ivd in vds.Declarations.Select((vd, i) => new { vd = vd, i = i })
where MatchesConstructedReference(ivd.vd.Left, cr)
select new { vds = vds, vd = ivd.vd, i = ivd.i, block = kvp.Value }).FirstOrDefault();
if (declaration == null)
throw new InvalidOperationException(String.Format("Could not locate declaration for {0}", cr));
TransformVariableIntoReference(
(JSVariable)declaration.vd.Left,
declaration.vds,
declaration.i,
declaration.block
);
}
var vrat = new VariableReferenceAccessTransformer(JSIL, cr, FunctionSource);
vrat.Visit(fn);
}
}
}
public class VariableReferenceAccessTransformer : JSAstVisitor {
public readonly JSVariable Variable;
public readonly JSILIdentifier JSIL;
public readonly IFunctionSource FunctionSource;
public VariableReferenceAccessTransformer (JSILIdentifier jsil, JSVariable variable, IFunctionSource functionSource) {
JSIL = jsil;
Variable = variable;
FunctionSource = functionSource;
}
public TypeSystem TypeSystem {
get {
return JSIL.TypeSystem;
}
}
public void VisitNode (JSVariable variable) {
if (
(ParentNode is JSFunctionExpression) &&
(this.CurrentName == "FunctionSignature")
) {
VisitChildren(variable);
return;
}
if (
(variable.Identifier != Variable.Identifier) ||
// Don't transform if we're inside a read-through already
(ParentNode is JSReadThroughReferenceExpression) ||
(
// If we're inside a write-through and on the LHS, don't transform
(ParentNode is JSWriteThroughReferenceExpression) &&
(this.CurrentName == "Left")
)
) {
VisitChildren(variable);
return;
}
// If we're inside a pass-by-reference (ref x) then don't transform
if (
Stack.OfType<JSPassByReferenceExpression>().Any()
) {
VisitChildren(variable);
return;
}
var replacement = new JSReadThroughReferenceExpression(variable);
ParentNode.ReplaceChild(variable, replacement);
VisitReplacement(replacement);
}
public void VisitNode (JSUnaryOperatorExpression uoe) {
JSExpression expr;
if (!JSReferenceExpression.TryDereference(JSIL, uoe.Expression, out expr))
expr = uoe.Expression;
var eVar = expr as JSVariable;
var eChangeType = expr as JSChangeTypeExpression;
if (eChangeType != null)
eVar = eChangeType.Expression as JSVariable;
var type = uoe.Expression.GetActualType(TypeSystem);
if (
(eVar != null) &&
(eVar.Identifier == Variable.Identifier) &&
(uoe.Operator is JSUnaryMutationOperator)
) {
var newValue = DecomposeMutationOperators.DecomposeUnaryMutation(
uoe, () => TemporaryVariable.ForFunction(
Stack.Last() as JSFunctionExpression, type, FunctionSource
), type, TypeSystem
);
var replacement = new JSWriteThroughReferenceExpression(
Variable, newValue
);
ParentNode.ReplaceChild(uoe, replacement);
VisitReplacement(replacement);
} else {
VisitChildren(uoe);
}
}
public void VisitNode (JSBinaryOperatorExpression boe) {
JSExpression left;
if (!JSReferenceExpression.TryDereference(JSIL, boe.Left, out left))
left = boe.Left;
var leftVar = left as JSVariable;
var leftChangeType = left as JSChangeTypeExpression;
if (leftChangeType != null)
leftVar = leftChangeType.Expression as JSVariable;
if (
!(ParentNode is JSVariableDeclarationStatement) &&
(leftVar != null) &&
(leftVar.Identifier == Variable.Identifier) &&
(boe.Operator is JSAssignmentOperator)
) {
var replacement = new JSWriteThroughReferenceExpression(
Variable, boe.Right
);
ParentNode.ReplaceChild(boe, replacement);
VisitReplacement(replacement);
} else if (ParentNode is JSVariableDeclarationStatement) {
// Don't walk through the left-hand side of variable declarations.
VisitChildren(
boe,
(node, name) => name != "Left"
);
} else {
VisitChildren(boe);
}
}
public void VisitNode (JSWriteThroughReferenceExpression wtre) {
VisitChildren(wtre);
}
}
}