Visitar URL original
Optimize do expression output (#17444) · babel/babel@220089e · GitHub
Skip to content

Commit 220089e

Browse files
authored
Optimize do expression output (#17444)
* add new test case * opt: conditionally apply the flatten transform Only apply the flatten transform when the do expression contains Break/Continue/Return. This enables us to optimize the output since we don't have to memoize intermediate results. * update test outputs * remove unreachable code variable declaration within for in/of can not have initializer. * update test case to cover spread element * add more test cases for early exit scenario * make node 6 happy * revert complex variable declaration removal
1 parent c8b155b commit 220089e

44 files changed

Lines changed: 533 additions & 553 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎packages/babel-plugin-proposal-destructuring-private/test/fixtures/assignment--es2015/completion-do-expression-babel-7/output.js‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,7 @@ _C = C;
55
var _x = {
66
_: void 0
77
};
8-
(() => {
8+
((_m, _m2) => {
99
var x;
10-
{
11-
var _m, _m2, _do;
12-
_do = (_m = _C, _m2 = babelHelpers.assertClassBrand(_C, _m, _x)._, x = _m2 === void 0 ? 2 : _m2, _m);
13-
}
14-
result = _do;
10+
result = (_m = _C, _m2 = babelHelpers.assertClassBrand(_C, _m, _x)._, x = _m2 === void 0 ? 2 : _m2, _m);
1511
})();

‎packages/babel-plugin-proposal-destructuring-private/test/fixtures/assignment--es2015/completion-do-expression/output.js‎

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,7 @@ _C = C;
55
var _x = {
66
_: void 0
77
};
8-
(() => {
8+
((_m, _m2) => {
99
var x;
10-
{
11-
var _do;
12-
var _m, _m2;
13-
_do = (_m = _C, _m2 = babelHelpers.assertClassBrand(_C, _m, _x)._, x = _m2 === void 0 ? 2 : _m2, _m);
14-
}
15-
result = _do;
10+
result = (_m = _C, _m2 = babelHelpers.assertClassBrand(_C, _m, _x)._, x = _m2 === void 0 ? 2 : _m2, _m);
1611
})();

‎packages/babel-plugin-proposal-destructuring-private/test/fixtures/assignment/completion-do-expression/output.js‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,8 @@ var result;
22
class C {
33
static #x;
44
static {
5+
var _m, _m2;
56
var x;
6-
{
7-
var _m, _m2, _do;
8-
_do = (_m = C, _m2 = _m.#x, x = _m2 === void 0 ? 2 : _m2, _m);
9-
}
10-
result = _do;
7+
result = (_m = C, _m2 = _m.#x, x = _m2 === void 0 ? 2 : _m2, _m);
118
}
129
}

‎packages/babel-plugin-proposal-do-expressions/src/index.ts‎

Lines changed: 33 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
import { declare } from "@babel/helper-plugin-utils";
22
import type { types as t, NodePath } from "@babel/core";
3-
import { wrapDoExpressionInIIFE } from "./utils.ts";
3+
import {
4+
wrapDoExpressionInIIFE,
5+
collectControlFlowStatements,
6+
} from "./utils.ts";
47

58
export default declare(api => {
69
api.assertVersion(REQUIRED_VERSION(7));
@@ -15,16 +18,39 @@ export default declare(api => {
1518
DoExpression: {
1619
exit(path) {
1720
if (path.node.async) {
18-
// Async do expressions are not yet supported
21+
// Async do expressions are handled by proposal-async-do-expressions
1922
return;
2023
}
21-
transformDoExpression(path);
24+
const controlFlowState = collectControlFlowStatements(path);
25+
if (
26+
controlFlowState.returnPath ||
27+
controlFlowState.break.size ||
28+
controlFlowState.continue.size
29+
) {
30+
transformDoExpressionWithControlFlowStatements(path);
31+
} else {
32+
const body = path.node.body.body;
33+
if (body.length) {
34+
path.replaceExpressionWithStatements(body);
35+
} else {
36+
path.replaceWith(path.scope.buildUndefinedNode());
37+
}
38+
}
2239
},
2340
},
2441
},
2542
};
2643

27-
function transformDoExpression(doExprPath: NodePath<t.DoExpression>) {
44+
/**
45+
* Transforms a do expression with control flow statements, e.g. break, continue, return.
46+
* To support these statements, we memoize top level expressions in the do block and then
47+
* unwrap the block.
48+
* @param doExprPath NodePath<t.DoExpression>
49+
* @returns
50+
*/
51+
function transformDoExpressionWithControlFlowStatements(
52+
doExprPath: NodePath<t.DoExpression>,
53+
) {
2854
const doAncestors = new WeakSet<t.Node>();
2955
let path: NodePath = doExprPath;
3056
while (path) {
@@ -176,6 +202,8 @@ export default declare(api => {
176202
if (left.isVariableDeclaration()) {
177203
const init = left.get("declarations")[0].get("init");
178204
if (init.node) {
205+
// Sloppy mode would allow:
206+
// for (var x = do { ... } in <iterator>);
179207
throw init.buildCodeFrameError(
180208
"Complex variable declaration in for-in with do expression is not currently supported",
181209
);
@@ -290,7 +318,7 @@ export default declare(api => {
290318
if (doAncestors.has(left.node)) {
291319
if (path.node.operator !== "=") {
292320
throw path.buildCodeFrameError(
293-
"Do expression inside complex assignment expression is not currently supported",
321+
"Do expression inside complex assignment expression is not currently supported.",
294322
);
295323
}
296324
const uid = path.scope.generateDeclaredUidIdentifier("do");
Lines changed: 72 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,82 @@
1-
import type { NodePath } from "@babel/core";
1+
import type { NodePath, Visitor, types as t } from "@babel/core";
2+
import { traverse } from "@babel/core";
3+
const mergeVisitors = traverse.visitors.merge;
24

35
// Wrap all do expressions in an IIFE.
46
// This doesn't work with control flow statements like break/continue/return.
57
// Only use this when the code is too hard to transform.
6-
export function wrapDoExpressionInIIFE(path: NodePath) {
7-
const state = {
8+
interface ControlFlowVisitorState {
9+
break: Set<string | null>;
10+
continue: Set<string | null>;
11+
returnPath: NodePath<t.ReturnStatement> | null;
12+
}
13+
14+
function throwError(path: NodePath) {
15+
throw path.buildCodeFrameError(
16+
"This control flow escape from do expression is not supported.",
17+
);
18+
}
19+
20+
const controlFlowVisitor: Visitor<ControlFlowVisitorState> = {
21+
FunctionParent(path) {
22+
path.skip();
23+
},
24+
"SwitchStatement|Loop"(_, state) {
25+
state.break.add(null);
26+
state.continue.add(null);
27+
},
28+
LabeledStatement(path, state) {
29+
const name = path.node.label.name;
30+
state.break.add(name);
31+
},
32+
BreakStatement(path, state) {
33+
if (!state.break.has(path.node.label?.name ?? null)) {
34+
throwError(path);
35+
}
36+
},
37+
ContinueStatement(path, state) {
38+
if (!state.continue.has(path.node.label?.name ?? null)) {
39+
throwError(path);
40+
}
41+
},
42+
ReturnStatement(path, state) {
43+
state.returnPath = path;
44+
},
45+
};
46+
47+
export function collectControlFlowStatements(path: NodePath) {
48+
const state: ControlFlowVisitorState = {
849
break: new Set<string | null>(),
950
continue: new Set<string | null>(),
10-
found: false,
51+
returnPath: null,
1152
};
12-
path.traverse({
13-
DoExpression(path) {
14-
const body = path.node.body.body;
15-
if (body.length) {
16-
path.replaceExpressionWithStatements(body);
17-
} else {
18-
path.replaceWith(path.scope.buildUndefinedNode());
19-
}
20-
},
21-
FunctionParent(path) {
22-
path.skip();
23-
},
24-
Loop() {
25-
state.break.add(null);
26-
state.continue.add(null);
27-
},
28-
LabeledStatement(path) {
29-
const name = path.node.label.name;
30-
state.break.add(name);
31-
},
32-
BreakStatement(path) {
33-
if (!state.break.has(path.node.label?.name ?? null)) {
34-
throwError(path);
35-
}
36-
},
37-
ContinueStatement(path) {
38-
if (!state.continue.has(path.node.label?.name ?? null)) {
39-
throwError(path);
40-
}
41-
},
42-
ReturnStatement(path) {
43-
throwError(path);
44-
},
45-
});
53+
path.traverse(controlFlowVisitor, state);
54+
return state;
55+
}
4656

47-
function throwError(path: NodePath) {
48-
throw path.buildCodeFrameError(
49-
"This control flow escape from do expression is not supported.",
50-
);
57+
export function wrapDoExpressionInIIFE(path: NodePath) {
58+
const state: ControlFlowVisitorState = {
59+
break: new Set<string | null>(),
60+
continue: new Set<string | null>(),
61+
returnPath: null,
62+
};
63+
path.traverse(
64+
mergeVisitors([
65+
{
66+
DoExpression(path) {
67+
const body = path.node.body.body;
68+
if (body.length) {
69+
path.replaceExpressionWithStatements(body);
70+
} else {
71+
path.replaceWith(path.scope.buildUndefinedNode());
72+
}
73+
},
74+
},
75+
controlFlowVisitor,
76+
]),
77+
state,
78+
);
79+
if (state.returnPath) {
80+
throwError(state.returnPath);
5181
}
5282
}
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
function recordEarlyExit(title, result) {
2+
switch (title) {
3+
case 'AssignmentExpression#Left#MemberExpression#ComputedKey': {
4+
result[do { return result; }] = 42;
5+
break;
6+
}
7+
8+
case 'AssignmentPattern#Left#ComputedKey': {
9+
const { [do { return result; }]: z = 42 } = result;
10+
result.push(z);
11+
break;
12+
}
13+
14+
case 'AssignmentPattern#Left#ComputedKey#WithoutInitializer': {
15+
const { [do { return result; }]: z } = result;
16+
result.push(z);
17+
break;
18+
}
19+
20+
case 'AssignmentPattern#Left#PatternInitializer': {
21+
const [ z = do { return result; } ] = result;
22+
result.push(z);
23+
break;
24+
}
25+
26+
case 'AssignmentPattern#Left#PatternInitializer#DoEmpty': {
27+
const [ z = do {} + do { return result; } ] = result;
28+
result.push(z);
29+
break;
30+
}
31+
32+
case 'AssignmentPattern#Left#PatternInitializer#WithHole': {
33+
const [ , z = do { return result; } ] = result;
34+
result.push(z);
35+
break;
36+
}
37+
38+
case 'AssignmentPattern#Left#PatternInitializer#WithIdentifier': {
39+
const [ x, z = do { return result; } ] = result;
40+
result.push(z);
41+
break;
42+
}
43+
44+
case 'AssignmentPattern#Left#PatternInitializer#WithRestElement': {
45+
const [ z = do { return result; }, ...x ] = result;
46+
result.push(z, ...x);
47+
break;
48+
}
49+
50+
case 'RestElement#Argument#PatternInitializer': {
51+
const [ ...[z = do { return result; }, ...x ] ] = result;
52+
result.push(z, ...x);
53+
break;
54+
}
55+
56+
case 'OptionalMemberExpression#ComputedKey': {
57+
result.push(result?.[do { return result; }]);
58+
break;
59+
}
60+
61+
case 'OptionalCallExpression#ComputedKey': {
62+
result.push(result?.[do { return result; }]());
63+
break;
64+
}
65+
66+
case 'UnaryExpression#Argument': {
67+
result.push(!result[do { return result; }]);
68+
break;
69+
}
70+
71+
case 'LogicalExpression#Left#operator||': {
72+
result[do { return result; }] || (result[0] = 42);
73+
break;
74+
}
75+
76+
case 'LogicalExpression#Left#operator&&': {
77+
result[undefined] = 42;
78+
result[do { return result; }] && (result[0] = 42);
79+
break;
80+
}
81+
82+
case 'LogicalExpression#Left#operator??': {
83+
result[do { return result; }] ?? (result[0] = 42);
84+
break;
85+
}
86+
87+
case 'ConditionalExpression#Test': {
88+
result[do { return result; }] ? (result[0] = 42) : (result[1] = 42);
89+
break;
90+
}
91+
92+
case 'ConditionalExpression#Alternate': {
93+
Object.keys(result).length > 0 ? (result[0] = 42) : (result[do { return result; }] = 42);
94+
break;
95+
}
96+
97+
case 'ConditionalExpression#Consequent': {
98+
Object.keys(result).length === 0 ? (result[do { return result; }] = 42) : (result[0] = 42);
99+
break;
100+
}
101+
102+
default:
103+
throw new Error(`Unsupported test title: ${title}`);
104+
}
105+
// This return should not be reached.
106+
return NaN;
107+
}
108+
109+
expect(recordEarlyExit('AssignmentExpression#Left#MemberExpression#ComputedKey', {})).toEqual({});
110+
// These cases are not supported.
111+
// expect(recordEarlyExit('AssignmentPattern#Left#ComputedKey', [])).toEqual([]);
112+
// expect(recordEarlyExit('AssignmentPattern#Left#ComputedKey#WithoutInitializer', [])).toEqual([]);
113+
expect(recordEarlyExit('AssignmentPattern#Left#PatternInitializer', [])).toEqual([]);
114+
expect(recordEarlyExit('AssignmentPattern#Left#PatternInitializer#DoEmpty', [])).toEqual([]);
115+
expect(recordEarlyExit('AssignmentPattern#Left#PatternInitializer#WithHole', [])).toEqual([]);
116+
expect(recordEarlyExit('AssignmentPattern#Left#PatternInitializer#WithIdentifier', [])).toEqual([]);
117+
expect(recordEarlyExit('AssignmentPattern#Left#PatternInitializer#WithRestElement', [])).toEqual([]);
118+
expect(recordEarlyExit('RestElement#Argument#PatternInitializer', [])).toEqual([]);
119+
expect(recordEarlyExit('OptionalCallExpression#ComputedKey', [])).toEqual([]);
120+
expect(recordEarlyExit('OptionalMemberExpression#ComputedKey', [])).toEqual([]);
121+
expect(recordEarlyExit('LogicalExpression#Left#operator||', {})).toEqual({});
122+
expect(recordEarlyExit('LogicalExpression#Left#operator&&', {})).toEqual({ undefined: 42 });
123+
expect(recordEarlyExit('LogicalExpression#Left#operator??', {})).toEqual({});
124+
expect(recordEarlyExit('UnaryExpression#Argument', [])).toEqual([]);
125+
expect(recordEarlyExit('ConditionalExpression#Test', [])).toEqual([]);
126+
expect(recordEarlyExit('ConditionalExpression#Alternate', {})).toEqual({});
127+
expect(recordEarlyExit('ConditionalExpression#Consequent', {})).toEqual({});

‎packages/babel-plugin-proposal-do-expressions/test/fixtures/do-expression-with-early-exit/call-expression/exec.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ function f1(a) {
66
function f2(a) {
77
(do { if (effects.push(1), false) return 0; ({ key: (arg) => effects.push(arg) }) })
88
[do { if (effects.push(2), a) return 1; 'key' }]
9-
(do { if (effects.push(3), false) return 2; 'arg' });
9+
(...do { if (effects.push(3), false) return [2]; ['arg'] });
1010
}
1111

1212
effects = [];

‎packages/babel-plugin-proposal-do-expressions/test/fixtures/do-expression-with-early-exit/call-expression/input.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,5 @@ function f1(a) {
66
function f2(a) {
77
(do { if (effects.push(1), false) return 0; ({ key: (arg) => effects.push(arg) }) })
88
[do { if (effects.push(2), a) return 1; 'key' }]
9-
(do { if (effects.push(3), false) return 2; 'arg' });
9+
(...do { if (effects.push(3), false) return [2]; ['arg'] });
1010
}

0 commit comments

Comments
 (0)