-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathea.ts
391 lines (342 loc) · 11 KB
/
ea.ts
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
/** Escape analysis */
// import { warn } from "console";
import { expr } from "cypress/types/jquery";
import {
Type,
Program,
FunDef,
Class,
ClosureDef,
Stmt,
Expr,
Destructure,
AssignTarget,
Location,
} from "./ast";
import * as BaseException from "./error";
/** The seperater used to flatten nested functions */
export const EA_NAMING_SEP = "_$";
/** This name is used to dereference, using a field_assign stmt or a lookup expr */
export const EA_DEREF_FIELD = "$deref";
/** This name is the type of a reference, expressed with a class type */
export const EA_REF_CLASS = "$ref";
const TRef: Type = { tag: "class", name: EA_REF_CLASS };
/** Field assign/lookup whose obj is an id of this name represents nonlocally mutable vars */
export const EA_NONLOCAL_OBJ = "$nl_ptr$";
export const EA_REF_SUFFIX = "_$ref";
type LocalEnv = {
name: string; // function name(without prefix)
prefix: string; // prefix is used to rename nested functions
varIds: string[]; // local variables & parameters
funIds: string[]; // nested functions defined (name without prefix)
parent: LocalEnv; // parent namespace, null for global
};
const globalLocalEnv: (fun_names: string[]) => LocalEnv = (fun_names: string[]) => ({
name: "global",
prefix: "",
varIds: [],
funIds: [],
parent: null,
});
/**
* Entry point of escape analysis.
* @param tAst Typed ast
* @returns Flattened ast with no nest functions
*/
export function ea(tAst: Program<[Type, Location]>): Program<[Type, Location]> {
return {
a: tAst.a,
funs: [],
inits: tAst.inits,
classes: tAst.classes,
stmts: tAst.stmts,
closures: [].concat(
...tAst.funs.map((f) => eaFunDef(f, globalLocalEnv(tAst.funs.map((f) => f.name)), true))
),
};
}
// TODO (closure group): ea for classes are not fully tested
export function eaClass(cl: Class<[Type, Location]>): Class<[Type, Location]> {
return {
a: cl.a,
name: cl.name,
fields: cl.fields,
methods: [].concat(
...cl.methods.map((f) => eaFunDef(f, globalLocalEnv(cl.methods.map((f) => f.name)), false))
),
};
}
/**
* Do escape analysis for a function and flatten it to an array of closures without
* nested functions.
* @param f The function definition to flatten
* @param prefix Prefix of current function's flatten name, expressed as python name
* @param parentEnv parent's (not ancestors') local environment
* @returns The first element should be the closure of `f`, followed by closure of its
* inner functions.
*/
export function eaFunDef(
f: FunDef<[Type, Location]>,
parentEnv: LocalEnv,
isGlobal: boolean
): ClosureDef<[Type, Location]>[] {
// create local variable environment
const localEnv: LocalEnv = {
name: f.name,
prefix: parentEnv.prefix + f.name + EA_NAMING_SEP,
varIds: [],
funIds: [],
parent: parentEnv,
};
f.parameters.forEach((p) => localEnv.varIds.push(p.name));
f.inits.forEach((i) => localEnv.varIds.push(i.name));
f.funs.forEach((nf) => localEnv.funIds.push(nf.name));
// recursively apply to inner functions
const innerClosures: ClosureDef<[Type, Location]>[] = [];
const nonlocalSet = new Set<string>();
const absFunIds = localEnv.funIds.map((n) => localEnv.prefix + n);
f.funs.forEach((f) => {
const cs = eaFunDef(f, localEnv, false);
innerClosures.push(...cs);
cs[0].nonlocals.forEach((v) => {
if (!localEnv.varIds.includes(v) && !absFunIds.includes(v)) {
nonlocalSet.add(v);
}
});
});
const processedBody = f.body.map((s) => eaStmt(s, localEnv, nonlocalSet));
const currClosure: ClosureDef<[Type, Location]> = {
a: f.a,
name: lookupId(f.name, localEnv).name,
parameters: f.parameters,
ret: f.ret,
nonlocals: [...nonlocalSet],
nested: f.funs.map((nf) => localEnv.prefix + nf.name),
inits: f.inits,
isGlobal: isGlobal,
body: processedBody,
};
return [currClosure].concat(innerClosures);
}
/**
* Do escape analysis for a statement.
*
* Notes for other groups to add cases: Generally, first call eaExpr for all expr
* component and call eaStmt for all stmt components. After that, reconstruct the
* ast. See assignment case if some name/identifier are used directly without id
* expression.
*
* @param nSet is used to keep track of nonlocal variables used in the curent
* function. Add used name/identifier to this set.
* @returns Converted statement
*/
function eaStmt(
stmt: Stmt<[Type, Location]>,
e: LocalEnv,
nSet: Set<string>
): Stmt<[Type, Location]> {
switch (stmt.tag) {
case "assignment":
const targets: AssignTarget<[Type, Location]>[] = stmt.destruct.targets.map((at) => {
if (at.ignore) return at; // do nothing for the ignore case
switch (at.target.tag) {
case "id":
const id = lookupId(at.target.name, e);
if (id.varScope == VarScope.GLOBAL) return at; // Globel names should keep the same
if (id.varScope == VarScope.NONLOCAL) nSet.add(id.name);
return {
...at,
target: {
a: at.target.a,
tag: "lookup",
obj: { a: [TRef, at.target.a[1]], tag: "id", name: at.target.name + EA_REF_SUFFIX },
field: EA_DEREF_FIELD,
},
};
case "lookup":
return { ...at, target: { ...at.target, obj: eaExpr(at.target.obj, e, nSet) } };
case "bracket-lookup": {
return {
...at,
target: {
...at.target,
obj: eaExpr(at.target.obj, e, nSet),
key: eaExpr(at.target.key, e, nSet),
},
};
}
}
});
const aVlaue = eaExpr(stmt.value, e, nSet);
const aDestruct: Destructure<[Type, Location]> = {
...stmt.destruct,
targets: targets,
};
// TODO (closure group): assume everything escapes by now
return { ...stmt, destruct: aDestruct, value: aVlaue };
case "return":
return { ...stmt, value: eaExpr(stmt.value, e, nSet) };
case "expr":
return { ...stmt, expr: eaExpr(stmt.expr, e, nSet) };
case "if":
return {
...stmt,
cond: eaExpr(stmt.cond, e, nSet),
thn: stmt.thn.map((s) => eaStmt(s, e, nSet)),
els: stmt.els.map((s) => eaStmt(s, e, nSet)),
};
case "while":
return {
...stmt,
cond: eaExpr(stmt.cond, e, nSet),
body: stmt.body.map((s) => eaStmt(s, e, nSet)),
};
case "pass":
return stmt;
case "continue":
return stmt;
case "break":
return stmt;
case "for":
return {
...stmt,
iterable: eaExpr(stmt.iterable, e, nSet),
body: stmt.body.map((b) => eaStmt(b, e, nSet)),
};
case "bracket-assign":
return {
...stmt,
obj: eaExpr(stmt.obj, e, nSet),
key: eaExpr(stmt.key, e, nSet),
value: eaExpr(stmt.value, e, nSet),
};
}
}
/**
* Do escape analysis for an expression.
*
* Notes for other groups to add cases: Generally, first call eaExpr for all expr
* component and call eaStmt for all stmt components. After that, reconstruct the
* ast. See id case if some name/identifier are used directly without id expression.
*
* @param nSet is used to keep track of nonlocal variables used in the curent
* function. Add used name/identifier to this set.
* @returns Converted expression
*/
function eaExpr(
expr: Expr<[Type, Location]>,
e: LocalEnv,
nSet: Set<string>
): Expr<[Type, Location]> {
switch (expr.tag) {
case "literal":
return expr;
case "binop":
return { ...expr, left: eaExpr(expr.left, e, nSet), right: eaExpr(expr.right, e, nSet) };
case "uniop":
return { ...expr, expr: eaExpr(expr.expr, e, nSet) };
case "builtin1":
return { ...expr, arg: eaExpr(expr.arg, e, nSet) };
case "builtin2":
return { ...expr, left: eaExpr(expr.left, e, nSet), right: eaExpr(expr.right, e, nSet) };
case "call":
return {
...expr,
arguments: expr.arguments.map((a) => eaExpr(a, e, nSet)),
};
case "id":
const idid = lookupId(expr.name, e);
if (idid.varScope != VarScope.GLOBAL) {
if (idid.varScope == VarScope.NONLOCAL) nSet.add(idid.name);
return {
a: expr.a,
tag: "lookup",
obj: { a: [TRef, expr.a[1]], tag: "id", name: idid.name + EA_REF_SUFFIX },
field: EA_DEREF_FIELD,
};
} else {
return { ...expr, name: idid.name };
}
case "lookup":
return { ...expr, obj: eaExpr(expr.obj, e, nSet) };
case "method-call":
return {
...expr,
obj: eaExpr(expr.obj, e, nSet),
arguments: expr.arguments.map((a) => eaExpr(a, e, nSet)),
};
case "construct":
return expr;
case "lambda":
throw new BaseException.InternalException(`ea not yet implemented!: ${expr.tag}`);
case "comprehension":
return {
...expr,
expr: eaExpr(expr.expr, e, nSet),
iter: eaExpr(expr.iter, e, nSet),
cond: expr.cond != undefined ? eaExpr(expr.cond, e, nSet) : expr.cond,
};
case "block":
return {
...expr,
block: expr.block.map((b) => eaStmt(b, e, nSet)),
expr: eaExpr(expr.expr, e, nSet),
};
case "call_expr":
return {
...expr,
name: eaExpr(expr.name, e, nSet),
arguments: expr.arguments.map((a) => eaExpr(a, e, nSet)),
};
case "list-expr":
return { ...expr, contents: expr.contents.map((c) => eaExpr(c, e, nSet)) };
case "tuple-expr":
return {
...expr,
contents: expr.contents.map((c) => eaExpr(c, e, nSet)),
};
case "slicing":
return {
...expr,
name: eaExpr(expr.name, e, nSet),
start: eaExpr(expr.start, e, nSet),
end: eaExpr(expr.end, e, nSet),
stride: eaExpr(expr.stride, e, nSet),
};
case "dict":
return {
...expr,
entries: expr.entries.map((keyvalue) => [
eaExpr(keyvalue[0], e, nSet),
eaExpr(keyvalue[1], e, nSet),
]),
};
case "bracket-lookup":
return {
...expr,
obj: eaExpr(expr.obj, e, nSet),
key: eaExpr(expr.key, e, nSet),
};
}
}
enum VarScope {
GLOBAL,
NONLOCAL,
LOCAL,
}
/**
* Lookup a name in the given space.
* @returns The scope if the identifier and a prefixed name if it is an function
*/
function lookupId(n: string, local: LocalEnv): { varScope: VarScope; name: string } {
// n is a local variable
if (local.varIds.includes(n)) return { varScope: VarScope.LOCAL, name: n };
// n is a child function
if (local.funIds.includes(n)) return { varScope: VarScope.LOCAL, name: local.prefix + n };
// n is a glocal variable
if (local.parent == null) return { varScope: VarScope.GLOBAL, name: n };
const nameInParent = lookupId(n, local.parent);
return nameInParent.varScope == VarScope.GLOBAL
? { varScope: VarScope.GLOBAL, name: nameInParent.name }
: { varScope: VarScope.NONLOCAL, name: nameInParent.name };
}