/
conversion.ts
737 lines (643 loc) 路 20.2 KB
/
conversion.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
// This file contains methods that convert the path node into another node or some other type of data.
import {
arrowFunctionExpression,
assignmentExpression,
binaryExpression,
blockStatement,
callExpression,
conditionalExpression,
expressionStatement,
identifier,
isIdentifier,
jsxIdentifier,
logicalExpression,
LOGICAL_OPERATORS,
memberExpression,
metaProperty,
numericLiteral,
objectExpression,
restElement,
returnStatement,
sequenceExpression,
spreadElement,
stringLiteral,
super as _super,
thisExpression,
toExpression,
unaryExpression,
} from "@babel/types";
import type * as t from "@babel/types";
import environmentVisitor from "@babel/helper-environment-visitor";
import nameFunction from "@babel/helper-function-name";
import { merge as mergeVisitors } from "../visitors";
import type NodePath from "./index";
export function toComputedKey(this: NodePath) {
let key;
if (this.isMemberExpression()) {
key = this.node.property;
} else if (this.isProperty() || this.isMethod()) {
key = this.node.key;
} else {
throw new ReferenceError("todo");
}
// @ts-expect-error todo(flow->ts) computed does not exist in ClassPrivateProperty
if (!this.node.computed) {
if (isIdentifier(key)) key = stringLiteral(key.name);
}
return key;
}
export function ensureBlock(
this: NodePath<
t.Loop | t.WithStatement | t.Function | t.LabeledStatement | t.CatchClause
>,
) {
const body = this.get("body");
const bodyNode = body.node;
if (Array.isArray(body)) {
throw new Error("Can't convert array path to a block statement");
}
if (!bodyNode) {
throw new Error("Can't convert node without a body");
}
if (body.isBlockStatement()) {
return bodyNode;
}
const statements: Array<t.Statement> = [];
let stringPath = "body";
let key;
let listKey;
if (body.isStatement()) {
listKey = "body";
key = 0;
statements.push(body.node);
} else {
stringPath += ".body.0";
if (this.isFunction()) {
key = "argument";
statements.push(returnStatement(body.node as t.Expression));
} else {
key = "expression";
statements.push(expressionStatement(body.node as t.Expression));
}
}
this.node.body = blockStatement(statements);
const parentPath = this.get(stringPath) as NodePath;
body.setup(
parentPath,
listKey ? parentPath.node[listKey] : parentPath.node,
listKey,
key,
);
return this.node;
}
/**
* Keeping this for backward-compatibility. You should use arrowFunctionToExpression() for >=7.x.
*/
// TODO(Babel 8): Remove this
export function arrowFunctionToShadowed(this: NodePath) {
if (!this.isArrowFunctionExpression()) return;
this.arrowFunctionToExpression();
}
/**
* Given an arbitrary function, process its content as if it were an arrow function, moving references
* to "this", "arguments", "super", and such into the function's parent scope. This method is useful if
* you have wrapped some set of items in an IIFE or other function, but want "this", "arguments", and super"
* to continue behaving as expected.
*/
export function unwrapFunctionEnvironment(this: NodePath) {
if (
!this.isArrowFunctionExpression() &&
!this.isFunctionExpression() &&
!this.isFunctionDeclaration()
) {
throw this.buildCodeFrameError(
"Can only unwrap the environment of a function.",
);
}
hoistFunctionEnvironment(this);
}
/**
* Convert a given arrow function into a normal ES5 function expression.
*/
export function arrowFunctionToExpression(
this: NodePath,
{
allowInsertArrow = true,
/** @deprecated Use `noNewArrows` instead */
specCompliant = false,
// TODO(Babel 8): Consider defaulting to `false` for spec compliancy
noNewArrows = !specCompliant,
} = {},
) {
if (!this.isArrowFunctionExpression()) {
throw this.buildCodeFrameError(
"Cannot convert non-arrow function to a function expression.",
);
}
const { thisBinding, fnPath: fn } = hoistFunctionEnvironment(
this,
noNewArrows,
allowInsertArrow,
);
fn.ensureBlock();
fn.node.type = "FunctionExpression";
if (!noNewArrows) {
const checkBinding = thisBinding
? null
: fn.scope.generateUidIdentifier("arrowCheckId");
if (checkBinding) {
fn.parentPath.scope.push({
id: checkBinding,
init: objectExpression([]),
});
}
fn.get("body").unshiftContainer(
"body",
expressionStatement(
callExpression(this.hub.addHelper("newArrowCheck"), [
thisExpression(),
checkBinding
? identifier(checkBinding.name)
: identifier(thisBinding),
]),
),
);
fn.replaceWith(
callExpression(
memberExpression(
nameFunction(this, true) || fn.node,
identifier("bind"),
),
[checkBinding ? identifier(checkBinding.name) : thisExpression()],
),
);
}
}
const getSuperCallsVisitor = mergeVisitors<{
allSuperCalls: NodePath<t.CallExpression>[];
}>([
{
CallExpression(child, { allSuperCalls }) {
if (!child.get("callee").isSuper()) return;
allSuperCalls.push(child);
},
},
environmentVisitor,
]);
/**
* Given a function, traverse its contents, and if there are references to "this", "arguments", "super",
* or "new.target", ensure that these references reference the parent environment around this function.
*
* @returns `thisBinding`: the name of the injected reference to `this`; for example "_this"
* @returns `fnPath`: the new path to the function node. This is different from the fnPath
* parameter when the function node is wrapped in another node.
*/
function hoistFunctionEnvironment(
fnPath: NodePath<t.Function>,
// TODO(Babel 8): Consider defaulting to `false` for spec compliancy
noNewArrows = true,
allowInsertArrow = true,
): { thisBinding: string; fnPath: NodePath<t.Function> } {
let arrowParent;
let thisEnvFn = fnPath.findParent(p => {
if (p.isArrowFunctionExpression()) {
arrowParent ??= p;
return false;
}
return (
p.isFunction() ||
p.isProgram() ||
p.isClassProperty({ static: false }) ||
p.isClassPrivateProperty({ static: false })
);
});
const inConstructor = thisEnvFn.isClassMethod({ kind: "constructor" });
if (thisEnvFn.isClassProperty() || thisEnvFn.isClassPrivateProperty()) {
if (arrowParent) {
thisEnvFn = arrowParent;
} else if (allowInsertArrow) {
// It's safe to wrap this function in another and not hoist to the
// top level because the 'this' binding is constant in class
// properties (since 'super()' has already been called), so we don't
// need to capture/reassign it at the top level.
fnPath.replaceWith(
callExpression(
arrowFunctionExpression([], toExpression(fnPath.node)),
[],
),
);
thisEnvFn = fnPath.get("callee");
fnPath = thisEnvFn.get("body");
} else {
throw fnPath.buildCodeFrameError(
"Unable to transform arrow inside class property",
);
}
}
const { thisPaths, argumentsPaths, newTargetPaths, superProps, superCalls } =
getScopeInformation(fnPath);
// Convert all super() calls in the constructor, if super is used in an arrow.
if (inConstructor && superCalls.length > 0) {
if (!allowInsertArrow) {
throw superCalls[0].buildCodeFrameError(
"Unable to handle nested super() usage in arrow",
);
}
const allSuperCalls: NodePath<t.CallExpression>[] = [];
thisEnvFn.traverse(getSuperCallsVisitor, { allSuperCalls });
const superBinding = getSuperBinding(thisEnvFn);
allSuperCalls.forEach(superCall => {
const callee = identifier(superBinding);
callee.loc = superCall.node.callee.loc;
superCall.get("callee").replaceWith(callee);
});
}
// Convert all "arguments" references in the arrow to point at the alias.
if (argumentsPaths.length > 0) {
const argumentsBinding = getBinding(thisEnvFn, "arguments", () => {
const args = () => identifier("arguments");
if (thisEnvFn.scope.path.isProgram()) {
return conditionalExpression(
binaryExpression(
"===",
unaryExpression("typeof", args()),
stringLiteral("undefined"),
),
thisEnvFn.scope.buildUndefinedNode(),
args(),
);
} else {
return args();
}
});
argumentsPaths.forEach(argumentsChild => {
const argsRef = identifier(argumentsBinding);
argsRef.loc = argumentsChild.node.loc;
argumentsChild.replaceWith(argsRef);
});
}
// Convert all "new.target" references in the arrow to point at the alias.
if (newTargetPaths.length > 0) {
const newTargetBinding = getBinding(thisEnvFn, "newtarget", () =>
metaProperty(identifier("new"), identifier("target")),
);
newTargetPaths.forEach(targetChild => {
const targetRef = identifier(newTargetBinding);
targetRef.loc = targetChild.node.loc;
targetChild.replaceWith(targetRef);
});
}
// Convert all "super.prop" references to point at aliases.
if (superProps.length > 0) {
if (!allowInsertArrow) {
throw superProps[0].buildCodeFrameError(
"Unable to handle nested super.prop usage",
);
}
const flatSuperProps = superProps.reduce(
(acc, superProp) => acc.concat(standardizeSuperProperty(superProp)),
[],
);
flatSuperProps.forEach(superProp => {
const key = superProp.node.computed
? ""
: superProp.get("property").node.name;
const isAssignment = superProp.parentPath.isAssignmentExpression({
left: superProp.node,
});
const isCall = superProp.parentPath.isCallExpression({
callee: superProp.node,
});
const superBinding = getSuperPropBinding(thisEnvFn, isAssignment, key);
const args = [];
if (superProp.node.computed) {
args.push(superProp.get("property").node);
}
if (isAssignment) {
const value = superProp.parentPath.node.right;
args.push(value);
}
const call = callExpression(identifier(superBinding), args);
if (isCall) {
superProp.parentPath.unshiftContainer("arguments", thisExpression());
superProp.replaceWith(memberExpression(call, identifier("call")));
thisPaths.push(superProp.parentPath.get("arguments.0"));
} else if (isAssignment) {
// Replace not only the super.prop, but the whole assignment
superProp.parentPath.replaceWith(call);
} else {
superProp.replaceWith(call);
}
});
}
// Convert all "this" references in the arrow to point at the alias.
let thisBinding;
if (thisPaths.length > 0 || !noNewArrows) {
thisBinding = getThisBinding(thisEnvFn, inConstructor);
if (
noNewArrows ||
// In subclass constructors, still need to rewrite because "this" can't be bound in spec mode
// because it might not have been initialized yet.
(inConstructor && hasSuperClass(thisEnvFn))
) {
thisPaths.forEach(thisChild => {
const thisRef = thisChild.isJSX()
? jsxIdentifier(thisBinding)
: identifier(thisBinding);
thisRef.loc = thisChild.node.loc;
thisChild.replaceWith(thisRef);
});
if (!noNewArrows) thisBinding = null;
}
}
return { thisBinding, fnPath };
}
type LogicalOp = Parameters<typeof logicalExpression>[0];
type BinaryOp = Parameters<typeof binaryExpression>[0];
function isLogicalOp(op: string): op is LogicalOp {
return LOGICAL_OPERATORS.includes(op);
}
function standardizeSuperProperty(superProp: NodePath<t.MemberExpression>) {
if (
superProp.parentPath.isAssignmentExpression() &&
superProp.parentPath.node.operator !== "="
) {
const assignmentPath = superProp.parentPath;
const op = assignmentPath.node.operator.slice(0, -1) as
| LogicalOp
| BinaryOp;
const value = assignmentPath.node.right;
const isLogicalAssignment = isLogicalOp(op);
if (superProp.node.computed) {
// from: super[foo] **= 4;
// to: super[tmp = foo] = super[tmp] ** 4;
// from: super[foo] ??= 4;
// to: super[tmp = foo] ?? super[tmp] = 4;
const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
const object = superProp.node.object;
const property = superProp.node.property as t.Expression;
assignmentPath
.get("left")
.replaceWith(
memberExpression(
object,
assignmentExpression("=", tmp, property),
true /* computed */,
),
);
assignmentPath
.get("right")
.replaceWith(
rightExpression(
isLogicalAssignment ? "=" : op,
memberExpression(object, identifier(tmp.name), true /* computed */),
value,
),
);
} else {
// from: super.foo **= 4;
// to: super.foo = super.foo ** 4;
// from: super.foo ??= 4;
// to: super.foo ?? super.foo = 4;
const object = superProp.node.object;
const property = superProp.node.property as t.Identifier;
assignmentPath
.get("left")
.replaceWith(memberExpression(object, property));
assignmentPath
.get("right")
.replaceWith(
rightExpression(
isLogicalAssignment ? "=" : op,
memberExpression(object, identifier(property.name)),
value,
),
);
}
if (isLogicalAssignment) {
assignmentPath.replaceWith(
logicalExpression(
op,
assignmentPath.node.left as t.Expression,
assignmentPath.node.right as t.Expression,
),
);
} else {
assignmentPath.node.operator = "=";
}
return [
assignmentPath.get("left"),
assignmentPath.get("right").get("left"),
];
} else if (superProp.parentPath.isUpdateExpression()) {
const updateExpr = superProp.parentPath;
const tmp = superProp.scope.generateDeclaredUidIdentifier("tmp");
const computedKey = superProp.node.computed
? superProp.scope.generateDeclaredUidIdentifier("prop")
: null;
const parts: t.Expression[] = [
assignmentExpression(
"=",
tmp,
memberExpression(
superProp.node.object,
computedKey
? assignmentExpression(
"=",
computedKey,
superProp.node.property as t.Expression,
)
: superProp.node.property,
superProp.node.computed,
),
),
assignmentExpression(
"=",
memberExpression(
superProp.node.object,
computedKey ? identifier(computedKey.name) : superProp.node.property,
superProp.node.computed,
),
binaryExpression(
// map `++` to `+`, and `--` to `-`
superProp.parentPath.node.operator[0] as "+" | "-",
identifier(tmp.name),
numericLiteral(1),
),
),
];
if (!superProp.parentPath.node.prefix) {
parts.push(identifier(tmp.name));
}
updateExpr.replaceWith(sequenceExpression(parts));
const left = updateExpr.get("expressions.0.right");
const right = updateExpr.get("expressions.1.left");
return [left, right];
}
return [superProp];
function rightExpression(
op: BinaryOp | "=",
left: t.MemberExpression,
right: t.Expression,
) {
if (op === "=") {
return assignmentExpression("=", left, right);
} else {
return binaryExpression(op, left, right);
}
}
}
function hasSuperClass(thisEnvFn) {
return (
thisEnvFn.isClassMethod() &&
!!thisEnvFn.parentPath.parentPath.node.superClass
);
}
const assignSuperThisVisitor = mergeVisitors<{
supers: WeakSet<t.CallExpression>;
thisBinding: string;
}>([
{
CallExpression(child, { supers, thisBinding }) {
if (!child.get("callee").isSuper()) return;
if (supers.has(child.node)) return;
supers.add(child.node);
child.replaceWithMultiple([
child.node,
assignmentExpression("=", identifier(thisBinding), identifier("this")),
]);
},
},
environmentVisitor,
]);
// Create a binding that evaluates to the "this" of the given function.
function getThisBinding(thisEnvFn, inConstructor) {
return getBinding(thisEnvFn, "this", thisBinding => {
if (!inConstructor || !hasSuperClass(thisEnvFn)) return thisExpression();
thisEnvFn.traverse(assignSuperThisVisitor, {
supers: new WeakSet(),
thisBinding,
});
});
}
// Create a binding for a function that will call "super()" with arguments passed through.
function getSuperBinding(thisEnvFn) {
return getBinding(thisEnvFn, "supercall", () => {
const argsBinding = thisEnvFn.scope.generateUidIdentifier("args");
return arrowFunctionExpression(
[restElement(argsBinding)],
callExpression(_super(), [spreadElement(identifier(argsBinding.name))]),
);
});
}
// Create a binding for a function that will call "super.foo" or "super[foo]".
function getSuperPropBinding(thisEnvFn, isAssignment, propName) {
const op = isAssignment ? "set" : "get";
return getBinding(thisEnvFn, `superprop_${op}:${propName || ""}`, () => {
const argsList = [];
let fnBody;
if (propName) {
// () => super.foo
fnBody = memberExpression(_super(), identifier(propName));
} else {
const method = thisEnvFn.scope.generateUidIdentifier("prop");
// (method) => super[method]
argsList.unshift(method);
fnBody = memberExpression(
_super(),
identifier(method.name),
true /* computed */,
);
}
if (isAssignment) {
const valueIdent = thisEnvFn.scope.generateUidIdentifier("value");
argsList.push(valueIdent);
fnBody = assignmentExpression("=", fnBody, identifier(valueIdent.name));
}
return arrowFunctionExpression(argsList, fnBody);
});
}
function getBinding(thisEnvFn, key, init) {
const cacheKey = "binding:" + key;
let data = thisEnvFn.getData(cacheKey);
if (!data) {
const id = thisEnvFn.scope.generateUidIdentifier(key);
data = id.name;
thisEnvFn.setData(cacheKey, data);
thisEnvFn.scope.push({
id: id,
init: init(data),
});
}
return data;
}
const getScopeInformationVisitor = mergeVisitors<{
thisPaths: NodePath<t.ThisExpression | t.JSXIdentifier>[];
superCalls: NodePath<t.CallExpression>[];
superProps: NodePath<t.MemberExpression>[];
argumentsPaths: NodePath<t.Identifier | t.JSXIdentifier>[];
newTargetPaths: NodePath<t.MetaProperty>[];
}>([
{
ThisExpression(child, { thisPaths }) {
thisPaths.push(child);
},
JSXIdentifier(child, { thisPaths }) {
if (child.node.name !== "this") return;
if (
!child.parentPath.isJSXMemberExpression({ object: child.node }) &&
!child.parentPath.isJSXOpeningElement({ name: child.node })
) {
return;
}
thisPaths.push(child);
},
CallExpression(child, { superCalls }) {
if (child.get("callee").isSuper()) superCalls.push(child);
},
MemberExpression(child, { superProps }) {
if (child.get("object").isSuper()) superProps.push(child);
},
Identifier(child, { argumentsPaths }) {
if (!child.isReferencedIdentifier({ name: "arguments" })) return;
let curr = child.scope;
do {
if (curr.hasOwnBinding("arguments")) {
curr.rename("arguments");
return;
}
if (curr.path.isFunction() && !curr.path.isArrowFunctionExpression()) {
break;
}
} while ((curr = curr.parent));
argumentsPaths.push(child);
},
MetaProperty(child, { newTargetPaths }) {
if (!child.get("meta").isIdentifier({ name: "new" })) return;
if (!child.get("property").isIdentifier({ name: "target" })) return;
newTargetPaths.push(child);
},
},
environmentVisitor,
]);
function getScopeInformation(fnPath) {
const thisPaths = [];
const argumentsPaths = [];
const newTargetPaths = [];
const superProps = [];
const superCalls = [];
fnPath.traverse(getScopeInformationVisitor, {
thisPaths,
argumentsPaths,
newTargetPaths,
superProps,
superCalls,
});
return {
thisPaths,
argumentsPaths,
newTargetPaths,
superProps,
superCalls,
};
}