-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathflatten.ts
439 lines (370 loc) · 12.3 KB
/
flatten.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
import * as t from "@babel/types";
import { NodePath } from "@babel/traverse";
import {
ensureComputedExpression,
getFunctionName,
isDefiningIdentifier,
isModifiedIdentifier,
isStrictMode,
isVariableIdentifier,
prepend,
prependProgram,
} from "../utils/ast-utils";
import { PluginArg, PluginObject } from "./plugin";
import { computeProbabilityMap } from "../probability";
import { Order } from "../order";
import { NodeSymbol, PREDICTABLE, UNSAFE } from "../constants";
import {
computeFunctionLength,
isVariableFunctionIdentifier,
} from "../utils/function-utils";
import { ok } from "assert";
import { Scope } from "@babel/traverse";
import { NameGen } from "../utils/NameGen";
export default ({ Plugin }: PluginArg): PluginObject => {
const me = Plugin(Order.Flatten, {
changeData: {
functions: 0,
},
});
const isDebug = false;
function flattenFunction(fnPath: NodePath<t.Function>) {
// Skip if already processed
if (me.isSkipped(fnPath)) return;
// Don't apply to generator functions
if (fnPath.node.generator) return;
// Skip getter/setter methods
if (fnPath.isObjectMethod() || fnPath.isClassMethod()) {
if (fnPath.node.kind !== "method") return;
}
// Do not apply to arrow functions
if (t.isArrowFunctionExpression(fnPath.node)) return;
if (!t.isBlockStatement(fnPath.node.body)) return;
// Skip if marked as unsafe
if ((fnPath.node as NodeSymbol)[UNSAFE]) return;
var program = fnPath.findParent((p) =>
p.isProgram()
) as NodePath<t.Program>;
let functionName = getFunctionName(fnPath);
if (!t.isValidIdentifier(functionName, true)) {
functionName = "anonymous";
}
if (!computeProbabilityMap(me.options.flatten, functionName)) {
return;
}
const strictMode = fnPath.find((path) => isStrictMode(path));
if (strictMode === fnPath) return;
me.log("Transforming", functionName);
const flatObjectName = `${me.getPlaceholder()}_flat_object`;
const newFnName = `${me.getPlaceholder()}_flat_${functionName}`;
const nameGen = new NameGen(me.options.identifierGenerator);
function generateProp(originalName: string, type: string) {
var newPropertyName: string;
do {
newPropertyName = isDebug
? type + "_" + originalName
: nameGen.generate();
} while (allPropertyNames.has(newPropertyName));
allPropertyNames.add(newPropertyName);
return newPropertyName;
}
const standardProps = new Map<string, string>();
const setterPropsNeeded = new Set<string>();
const typeofProps = new Map<string, string>();
const functionCallProps = new Map<string, string>();
const allPropertyNames = new Set();
const identifierPaths: NodePath<t.Identifier>[] = [];
// Traverse function to identify variables to be replaced with flat object properties
fnPath.traverse({
Identifier: {
exit(identifierPath) {
if (!isVariableIdentifier(identifierPath)) return;
if (
identifierPath.isBindingIdentifier() &&
isDefiningIdentifier(identifierPath)
)
return;
if (isVariableFunctionIdentifier(identifierPath)) return;
if ((identifierPath.node as NodeSymbol)[UNSAFE]) return;
const identifierName = identifierPath.node.name;
if (identifierName === "arguments") return;
var binding = identifierPath.scope.getBinding(identifierName);
if (!binding) {
return;
}
var definedLocal = identifierPath.scope;
do {
if (definedLocal.hasOwnBinding(identifierName)) return;
if (definedLocal === fnPath.scope) break;
definedLocal = definedLocal.parent;
if (definedLocal === program.scope)
ok(functionName + ":" + identifierName);
} while (definedLocal);
var cursor: Scope = fnPath.scope.parent;
var isOutsideVariable = false;
do {
if (cursor.hasBinding(identifierName)) {
isOutsideVariable = true;
break;
}
cursor = cursor.parent;
} while (cursor);
if (!isOutsideVariable) {
return;
}
identifierPaths.push(identifierPath);
},
},
});
me.log(
`Function ${functionName}`,
"requires",
Array.from(new Set(identifierPaths.map((x) => x.node.name)))
);
for (var identifierPath of identifierPaths) {
const identifierName = identifierPath.node.name;
if (typeof identifierName !== "string") continue;
const isTypeof = identifierPath.parentPath.isUnaryExpression({
operator: "typeof",
});
const isFunctionCall =
identifierPath.parentPath.isCallExpression() &&
identifierPath.parentPath.node.callee === identifierPath.node;
if (isTypeof) {
var typeofProp = typeofProps.get(identifierName);
if (!typeofProp) {
typeofProp = generateProp(identifierName, "typeof");
typeofProps.set(identifierName, typeofProp);
}
ensureComputedExpression(identifierPath.parentPath);
identifierPath.parentPath
.replaceWith(
t.memberExpression(
t.identifier(flatObjectName),
t.stringLiteral(typeofProp),
true
)
)[0]
.skip();
} else if (isFunctionCall) {
let functionCallProp = functionCallProps.get(identifierName);
if (!functionCallProp) {
functionCallProp = generateProp(identifierName, "call");
functionCallProps.set(identifierName, functionCallProp);
}
ensureComputedExpression(identifierPath);
// Replace identifier with a reference to the flat object property
identifierPath
.replaceWith(
t.memberExpression(
t.identifier(flatObjectName),
t.stringLiteral(functionCallProp),
true
)
)[0]
.skip();
} else {
let standardProp = standardProps.get(identifierName);
if (!standardProp) {
standardProp = generateProp(identifierName, "standard");
standardProps.set(identifierName, standardProp);
}
if (!setterPropsNeeded.has(identifierName)) {
// Only provide 'set' method if the variable is modified
var isModification = isModifiedIdentifier(identifierPath);
if (isModification) {
setterPropsNeeded.add(identifierName);
}
}
ensureComputedExpression(identifierPath);
// Replace identifier with a reference to the flat object property
identifierPath
.replaceWith(
t.memberExpression(
t.identifier(flatObjectName),
t.stringLiteral(standardProp),
true
)
)[0]
.skip();
}
}
// for (const prop of [...typeofProps.keys(), ...functionCallProps.keys()]) {
// if (!standardProps.has(prop)) {
// standardProps.set(prop, generateProp());
// }
// }
const flatObjectProperties: t.ObjectMember[] = [];
for (var entry of standardProps) {
const [identifierName, objectProp] = entry;
flatObjectProperties.push(
me.skip(
t.objectMethod(
"get",
t.stringLiteral(objectProp),
[],
t.blockStatement([t.returnStatement(t.identifier(identifierName))]),
false,
false,
false
)
)
);
// Not all properties need a setter
if (setterPropsNeeded.has(identifierName)) {
var valueArgName = me.getPlaceholder() + "_value";
flatObjectProperties.push(
me.skip(
t.objectMethod(
"set",
t.stringLiteral(objectProp),
[t.identifier(valueArgName)],
t.blockStatement([
t.expressionStatement(
t.assignmentExpression(
"=",
t.identifier(identifierName),
t.identifier(valueArgName)
)
),
]),
false,
false,
false
)
)
);
}
}
for (const entry of typeofProps) {
const [identifierName, objectProp] = entry;
flatObjectProperties.push(
me.skip(
t.objectMethod(
"get",
t.stringLiteral(objectProp),
[],
t.blockStatement([
t.returnStatement(
t.unaryExpression("typeof", t.identifier(identifierName))
),
]),
false,
false,
false
)
)
);
}
for (const entry of functionCallProps) {
const [identifierName, objectProp] = entry;
flatObjectProperties.push(
me.skip(
t.objectMethod(
"method",
t.stringLiteral(objectProp),
[t.restElement(t.identifier("args"))],
t.blockStatement([
t.returnStatement(
t.callExpression(t.identifier(identifierName), [
t.spreadElement(t.identifier("args")),
])
),
]),
false,
false,
false
)
)
);
}
// Create the new flattened function
const flattenedFunctionDeclaration = t.functionDeclaration(
t.identifier(newFnName),
[t.arrayPattern([...fnPath.node.params]), t.identifier(flatObjectName)],
t.blockStatement([...[...fnPath.node.body.body]]),
false,
fnPath.node.async
);
// Create the flat object variable declaration
const flatObjectDeclaration = t.variableDeclaration("var", [
t.variableDeclarator(
t.identifier(flatObjectName),
t.objectExpression(flatObjectProperties)
),
]);
var argName = me.getPlaceholder() + "_args";
// Replace original function body with a call to the flattened function
fnPath.node.body = t.blockStatement([
flatObjectDeclaration,
t.returnStatement(
t.callExpression(t.identifier(newFnName), [
t.identifier(argName),
t.identifier(flatObjectName),
])
),
]);
const originalLength = computeFunctionLength(fnPath);
fnPath.node.params = [t.restElement(t.identifier(argName))];
// Ensure updated parameter gets registered in the function scope
fnPath.scope.crawl();
fnPath.skip();
// Add the new flattened function at the top level
var newPath = prependProgram(
program,
flattenedFunctionDeclaration
)[0] as NodePath<t.FunctionDeclaration>;
me.skip(newPath);
// Copy over all properties except the predictable flag
for (var symbol of Object.getOwnPropertySymbols(fnPath.node)) {
if (symbol !== PREDICTABLE) {
newPath.node[symbol] = fnPath.node[symbol];
}
}
// Old function is no longer predictable (rest element parameter)
(fnPath.node as NodeSymbol)[PREDICTABLE] = false;
// Old function is unsafe (uses arguments, this)
(fnPath.node as NodeSymbol)[UNSAFE] = true;
newPath.node[PREDICTABLE] = true;
// Carry over 'use strict' directive if not already present
if (strictMode) {
newPath.node.body.directives.push(
t.directive(t.directiveLiteral("use strict"))
);
// Non-simple parameter list conversion
prepend(
newPath,
t.variableDeclaration("var", [
t.variableDeclarator(
t.arrayPattern(newPath.node.params),
t.identifier("arguments")
),
])
);
newPath.node.params = [];
// Using 'arguments' is unsafe
(newPath.node as NodeSymbol)[UNSAFE] = true;
// Params changed and using 'arguments'
(newPath.node as NodeSymbol)[PREDICTABLE] = false;
}
// Ensure parameters are registered in the new function scope
newPath.scope.crawl();
newPath.skip();
me.skip(newPath);
// Set function length
me.setFunctionLength(fnPath, originalLength);
me.changeData.functions++;
}
return {
visitor: {
Function: {
exit(path: NodePath<t.Function>) {
flattenFunction(path);
},
},
Program(path) {
path.scope.crawl();
},
},
};
};