/
rest.js
371 lines (319 loc) 路 10.7 KB
/
rest.js
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
import { template, types as t } from "@babel/core";
const buildRest = template(`
for (var LEN = ARGUMENTS.length,
ARRAY = new Array(ARRAY_LEN),
KEY = START;
KEY < LEN;
KEY++) {
ARRAY[ARRAY_KEY] = ARGUMENTS[KEY];
}
`);
const restIndex = template(`
(INDEX < OFFSET || ARGUMENTS.length <= INDEX) ? undefined : ARGUMENTS[INDEX]
`);
const restIndexImpure = template(`
REF = INDEX, (REF < OFFSET || ARGUMENTS.length <= REF) ? undefined : ARGUMENTS[REF]
`);
const restLength = template(`
ARGUMENTS.length <= OFFSET ? 0 : ARGUMENTS.length - OFFSET
`);
function referencesRest(path, state) {
if (path.node.name === state.name) {
// Check rest parameter is not shadowed by a binding in another scope.
return path.scope.bindingIdentifierEquals(state.name, state.outerBinding);
}
return false;
}
const memberExpressionOptimisationVisitor = {
Scope(path, state) {
// check if this scope has a local binding that will shadow the rest parameter
if (!path.scope.bindingIdentifierEquals(state.name, state.outerBinding)) {
path.skip();
}
},
Flow(path) {
// Do not skip TypeCastExpressions as the contain valid non flow code
if (path.isTypeCastExpression()) return;
// don't touch reference in type annotations
path.skip();
},
Function(path, state) {
// Detect whether any reference to rest is contained in nested functions to
// determine if deopt is necessary.
const oldNoOptimise = state.noOptimise;
state.noOptimise = true;
path.traverse(memberExpressionOptimisationVisitor, state);
state.noOptimise = oldNoOptimise;
// Skip because optimizing references to rest would refer to the `arguments`
// of the nested function.
path.skip();
},
ReferencedIdentifier(path, state) {
const { node } = path;
// we can't guarantee the purity of arguments
if (node.name === "arguments") {
state.deopted = true;
}
// is this a referenced identifier and is it referencing the rest parameter?
if (!referencesRest(path, state)) return;
if (state.noOptimise) {
state.deopted = true;
} else {
const { parentPath } = path;
// Is this identifier the right hand side of a default parameter?
if (parentPath.listKey === "params" && parentPath.key < state.offset) {
return;
}
// ex: `args[0]`
// ex: `args.whatever`
if (parentPath.isMemberExpression({ object: node })) {
const grandparentPath = parentPath.parentPath;
const argsOptEligible =
!state.deopted &&
!(
// ex: `args[0] = "whatever"`
(
(grandparentPath.isAssignmentExpression() &&
parentPath.node === grandparentPath.node.left) ||
// ex: `[args[0]] = ["whatever"]`
grandparentPath.isLVal() ||
// ex: `for (rest[0] in this)`
// ex: `for (rest[0] of this)`
grandparentPath.isForXStatement() ||
// ex: `++args[0]`
// ex: `args[0]--`
grandparentPath.isUpdateExpression() ||
// ex: `delete args[0]`
grandparentPath.isUnaryExpression({ operator: "delete" }) ||
// ex: `args[0]()`
// ex: `new args[0]()`
// ex: `new args[0]`
((grandparentPath.isCallExpression() ||
grandparentPath.isNewExpression()) &&
parentPath.node === grandparentPath.node.callee)
)
);
if (argsOptEligible) {
if (parentPath.node.computed) {
// if we know that this member expression is referencing a number then
// we can safely optimise it
if (parentPath.get("property").isBaseType("number")) {
state.candidates.push({ cause: "indexGetter", path });
return;
}
} else if (parentPath.node.property.name === "length") {
// args.length
state.candidates.push({ cause: "lengthGetter", path });
return;
}
}
}
// we can only do these optimizations if the rest variable would match
// the arguments exactly
// optimise single spread args in calls
// ex: fn(...args)
if (state.offset === 0 && parentPath.isSpreadElement()) {
const call = parentPath.parentPath;
if (call.isCallExpression() && call.node.arguments.length === 1) {
state.candidates.push({ cause: "argSpread", path });
return;
}
}
state.references.push(path);
}
},
/**
* Deopt on use of a binding identifier with the same name as our rest param.
*
* See https://github.com/babel/babel/issues/2091
*/
BindingIdentifier(path, state) {
if (referencesRest(path, state)) {
state.deopted = true;
}
},
};
function getParamsCount(node) {
let count = node.params.length;
// skip the first parameter if it is a TypeScript 'this parameter'
if (count > 0 && t.isIdentifier(node.params[0], { name: "this" })) {
count -= 1;
}
return count;
}
function hasRest(node) {
const length = node.params.length;
return length > 0 && t.isRestElement(node.params[length - 1]);
}
function optimiseIndexGetter(path, argsId, offset) {
const offsetLiteral = t.numericLiteral(offset);
let index;
if (t.isNumericLiteral(path.parent.property)) {
index = t.numericLiteral(path.parent.property.value + offset);
} else if (offset === 0) {
// Avoid unnecessary '+ 0'
index = path.parent.property;
} else {
index = t.binaryExpression(
"+",
path.parent.property,
t.cloneNode(offsetLiteral),
);
}
const { scope } = path;
if (!scope.isPure(index)) {
const temp = scope.generateUidIdentifierBasedOnNode(index);
scope.push({ id: temp, kind: "var" });
path.parentPath.replaceWith(
restIndexImpure({
ARGUMENTS: argsId,
OFFSET: offsetLiteral,
INDEX: index,
REF: t.cloneNode(temp),
}),
);
} else {
const parentPath = path.parentPath;
parentPath.replaceWith(
restIndex({
ARGUMENTS: argsId,
OFFSET: offsetLiteral,
INDEX: index,
}),
);
// See if we can statically evaluate the first test (i.e. index < offset)
// and optimize the AST accordingly.
const offsetTestPath = parentPath.get("test").get("left");
const valRes = offsetTestPath.evaluate();
if (valRes.confident) {
if (valRes.value === true) {
parentPath.replaceWith(parentPath.scope.buildUndefinedNode());
} else {
parentPath.get("test").replaceWith(parentPath.get("test").get("right"));
}
}
}
}
function optimiseLengthGetter(path, argsId, offset) {
if (offset) {
path.parentPath.replaceWith(
restLength({
ARGUMENTS: argsId,
OFFSET: t.numericLiteral(offset),
}),
);
} else {
path.replaceWith(argsId);
}
}
export default function convertFunctionRest(path) {
const { node, scope } = path;
if (!hasRest(node)) return false;
let rest = node.params.pop().argument;
const argsId = t.identifier("arguments");
if (t.isPattern(rest)) {
const pattern = rest;
rest = scope.generateUidIdentifier("ref");
const declar = t.variableDeclaration("let", [
t.variableDeclarator(pattern, rest),
]);
node.body.body.unshift(declar);
}
const paramsCount = getParamsCount(node);
// check and optimise for extremely common cases
const state = {
references: [],
offset: paramsCount,
argumentsNode: argsId,
outerBinding: scope.getBindingIdentifier(rest.name),
// candidate member expressions we could optimise if there are no other references
candidates: [],
// local rest binding name
name: rest.name,
/*
It may be possible to optimize the output code in certain ways, such as
not generating code to initialize an array (perhaps substituting direct
references to arguments[i] or arguments.length for reads of the
corresponding rest parameter property) or positioning the initialization
code so that it may not have to execute depending on runtime conditions.
This property tracks eligibility for optimization. "deopted" means give up
and don't perform optimization. For example, when any of rest's elements /
properties is assigned to at the top level, or referenced at all in a
nested function.
*/
deopted: false,
};
path.traverse(memberExpressionOptimisationVisitor, state);
// There are only "shorthand" references
if (!state.deopted && !state.references.length) {
for (const { path, cause } of (state.candidates: Array)) {
const clonedArgsId = t.cloneNode(argsId);
switch (cause) {
case "indexGetter":
optimiseIndexGetter(path, clonedArgsId, state.offset);
break;
case "lengthGetter":
optimiseLengthGetter(path, clonedArgsId, state.offset);
break;
default:
path.replaceWith(clonedArgsId);
}
}
return true;
}
Array.prototype.push.apply(
state.references,
state.candidates.map(({ path }) => path),
);
const start = t.numericLiteral(paramsCount);
const key = scope.generateUidIdentifier("key");
const len = scope.generateUidIdentifier("len");
let arrKey, arrLen;
if (paramsCount) {
// this method has additional params, so we need to subtract
// the index of the current argument position from the
// position in the array that we want to populate
arrKey = t.binaryExpression("-", t.cloneNode(key), t.cloneNode(start));
// we need to work out the size of the array that we're
// going to store all the rest parameters
//
// we need to add a check to avoid constructing the array
// with <0 if there are less arguments than params as it'll
// cause an error
arrLen = t.conditionalExpression(
t.binaryExpression(">", t.cloneNode(len), t.cloneNode(start)),
t.binaryExpression("-", t.cloneNode(len), t.cloneNode(start)),
t.numericLiteral(0),
);
} else {
arrKey = t.identifier(key.name);
arrLen = t.identifier(len.name);
}
const loop = buildRest({
ARGUMENTS: argsId,
ARRAY_KEY: arrKey,
ARRAY_LEN: arrLen,
START: start,
ARRAY: rest,
KEY: key,
LEN: len,
});
if (state.deopted) {
node.body.body.unshift(loop);
} else {
let target = path
.getEarliestCommonAncestorFrom(state.references)
.getStatementParent();
// don't perform the allocation inside a loop
target.findParent(path => {
if (path.isLoop()) {
target = path;
} else {
// Stop crawling up if this is a function.
return path.isFunction();
}
});
target.insertBefore(loop);
}
return true;
}