Visitar URL original
Optimize do expression output by JLHwung · Pull Request #17444 · babel/babel · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,7 @@ _C = C;
var _x = {
_: void 0
};
(() => {
((_m, _m2) => {
var x;
{
var _m, _m2, _do;
_do = (_m = _C, _m2 = babelHelpers.assertClassBrand(_C, _m, _x)._, x = _m2 === void 0 ? 2 : _m2, _m);
}
result = _do;
result = (_m = _C, _m2 = babelHelpers.assertClassBrand(_C, _m, _x)._, x = _m2 === void 0 ? 2 : _m2, _m);
})();
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,7 @@ _C = C;
var _x = {
_: void 0
};
(() => {
((_m, _m2) => {
var x;
{
var _do;
var _m, _m2;
_do = (_m = _C, _m2 = babelHelpers.assertClassBrand(_C, _m, _x)._, x = _m2 === void 0 ? 2 : _m2, _m);
}
result = _do;
result = (_m = _C, _m2 = babelHelpers.assertClassBrand(_C, _m, _x)._, x = _m2 === void 0 ? 2 : _m2, _m);
})();
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@ var result;
class C {
static #x;
static {
var _m, _m2;
var x;
{
var _m, _m2, _do;
_do = (_m = C, _m2 = _m.#x, x = _m2 === void 0 ? 2 : _m2, _m);
}
result = _do;
result = (_m = C, _m2 = _m.#x, x = _m2 === void 0 ? 2 : _m2, _m);
}
}
38 changes: 33 additions & 5 deletions packages/babel-plugin-proposal-do-expressions/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { declare } from "@babel/helper-plugin-utils";
import type { types as t, NodePath } from "@babel/core";
import { wrapDoExpressionInIIFE } from "./utils.ts";
import {
wrapDoExpressionInIIFE,
collectControlFlowStatements,
} from "./utils.ts";

export default declare(api => {
api.assertVersion(REQUIRED_VERSION(7));
Expand All @@ -15,16 +18,39 @@ export default declare(api => {
DoExpression: {
exit(path) {
if (path.node.async) {
// Async do expressions are not yet supported
// Async do expressions are handled by proposal-async-do-expressions
return;
}
transformDoExpression(path);
const controlFlowState = collectControlFlowStatements(path);
if (
controlFlowState.returnPath ||
controlFlowState.break.size ||
controlFlowState.continue.size
) {
transformDoExpressionWithControlFlowStatements(path);
} else {
const body = path.node.body.body;
if (body.length) {
path.replaceExpressionWithStatements(body);
} else {
path.replaceWith(path.scope.buildUndefinedNode());
}
}
},
},
},
};

function transformDoExpression(doExprPath: NodePath<t.DoExpression>) {
/**
* Transforms a do expression with control flow statements, e.g. break, continue, return.
* To support these statements, we memoize top level expressions in the do block and then
* unwrap the block.
* @param doExprPath NodePath<t.DoExpression>
* @returns
*/
function transformDoExpressionWithControlFlowStatements(
doExprPath: NodePath<t.DoExpression>,
) {
const doAncestors = new WeakSet<t.Node>();
let path: NodePath = doExprPath;
while (path) {
Expand Down Expand Up @@ -176,6 +202,8 @@ export default declare(api => {
if (left.isVariableDeclaration()) {
const init = left.get("declarations")[0].get("init");
if (init.node) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This this PR add support for for (var i = 0 in {});?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch! I overlooked the sloppy mode, I will revert this part.

// Sloppy mode would allow:
// for (var x = do { ... } in <iterator>);
throw init.buildCodeFrameError(
"Complex variable declaration in for-in with do expression is not currently supported",
);
Expand Down Expand Up @@ -290,7 +318,7 @@ export default declare(api => {
if (doAncestors.has(left.node)) {
if (path.node.operator !== "=") {
throw path.buildCodeFrameError(
"Do expression inside complex assignment expression is not currently supported",
"Do expression inside complex assignment expression is not currently supported.",
);
}
const uid = path.scope.generateDeclaredUidIdentifier("do");
Expand Down
114 changes: 72 additions & 42 deletions packages/babel-plugin-proposal-do-expressions/src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,82 @@
import type { NodePath } from "@babel/core";
import type { NodePath, Visitor, types as t } from "@babel/core";
import { traverse } from "@babel/core";
const mergeVisitors = traverse.visitors.merge;

// Wrap all do expressions in an IIFE.
// This doesn't work with control flow statements like break/continue/return.
// Only use this when the code is too hard to transform.
export function wrapDoExpressionInIIFE(path: NodePath) {
const state = {
interface ControlFlowVisitorState {
break: Set<string | null>;
continue: Set<string | null>;
returnPath: NodePath<t.ReturnStatement> | null;
}

function throwError(path: NodePath) {
throw path.buildCodeFrameError(
"This control flow escape from do expression is not supported.",
);
}

const controlFlowVisitor: Visitor<ControlFlowVisitorState> = {
FunctionParent(path) {
path.skip();
},
"SwitchStatement|Loop"(_, state) {
state.break.add(null);
state.continue.add(null);
},
LabeledStatement(path, state) {
const name = path.node.label.name;
state.break.add(name);
},
BreakStatement(path, state) {
if (!state.break.has(path.node.label?.name ?? null)) {
throwError(path);
}
},
ContinueStatement(path, state) {
if (!state.continue.has(path.node.label?.name ?? null)) {
throwError(path);
}
},
ReturnStatement(path, state) {
state.returnPath = path;
},
};

export function collectControlFlowStatements(path: NodePath) {
const state: ControlFlowVisitorState = {
break: new Set<string | null>(),
continue: new Set<string | null>(),
found: false,
returnPath: null,
};
path.traverse({
DoExpression(path) {
const body = path.node.body.body;
if (body.length) {
path.replaceExpressionWithStatements(body);
} else {
path.replaceWith(path.scope.buildUndefinedNode());
}
},
FunctionParent(path) {
path.skip();
},
Loop() {
state.break.add(null);
state.continue.add(null);
},
LabeledStatement(path) {
const name = path.node.label.name;
state.break.add(name);
},
BreakStatement(path) {
if (!state.break.has(path.node.label?.name ?? null)) {
throwError(path);
}
},
ContinueStatement(path) {
if (!state.continue.has(path.node.label?.name ?? null)) {
throwError(path);
}
},
ReturnStatement(path) {
throwError(path);
},
});
path.traverse(controlFlowVisitor, state);
return state;
}

function throwError(path: NodePath) {
throw path.buildCodeFrameError(
"This control flow escape from do expression is not supported.",
);
export function wrapDoExpressionInIIFE(path: NodePath) {
const state: ControlFlowVisitorState = {
break: new Set<string | null>(),
continue: new Set<string | null>(),
returnPath: null,
};
path.traverse(
mergeVisitors([
{
DoExpression(path) {
const body = path.node.body.body;
if (body.length) {
path.replaceExpressionWithStatements(body);
} else {
path.replaceWith(path.scope.buildUndefinedNode());
}
},
},
controlFlowVisitor,
]),
state,
);
if (state.returnPath) {
throwError(state.returnPath);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
function recordEarlyExit(title, result) {
switch (title) {
case 'AssignmentExpression#Left#MemberExpression#ComputedKey': {
result[do { return result; }] = 42;
break;
}

case 'AssignmentPattern#Left#ComputedKey': {
const { [do { return result; }]: z = 42 } = result;
result.push(z);
break;
}

case 'AssignmentPattern#Left#ComputedKey#WithoutInitializer': {
const { [do { return result; }]: z } = result;
result.push(z);
break;
}

case 'AssignmentPattern#Left#PatternInitializer': {
const [ z = do { return result; } ] = result;
result.push(z);
break;
}

case 'AssignmentPattern#Left#PatternInitializer#DoEmpty': {
const [ z = do {} + do { return result; } ] = result;
result.push(z);
break;
}

case 'AssignmentPattern#Left#PatternInitializer#WithHole': {
const [ , z = do { return result; } ] = result;
result.push(z);
break;
}

case 'AssignmentPattern#Left#PatternInitializer#WithIdentifier': {
const [ x, z = do { return result; } ] = result;
result.push(z);
break;
}

case 'AssignmentPattern#Left#PatternInitializer#WithRestElement': {
const [ z = do { return result; }, ...x ] = result;
result.push(z, ...x);
break;
}

case 'RestElement#Argument#PatternInitializer': {
const [ ...[z = do { return result; }, ...x ] ] = result;
result.push(z, ...x);
break;
}

case 'OptionalMemberExpression#ComputedKey': {
result.push(result?.[do { return result; }]);
break;
}

case 'OptionalCallExpression#ComputedKey': {
result.push(result?.[do { return result; }]());
break;
}

case 'UnaryExpression#Argument': {
result.push(!result[do { return result; }]);
break;
}

case 'LogicalExpression#Left#operator||': {
result[do { return result; }] || (result[0] = 42);
break;
}

case 'LogicalExpression#Left#operator&&': {
result[undefined] = 42;
result[do { return result; }] && (result[0] = 42);
break;
}

case 'LogicalExpression#Left#operator??': {
result[do { return result; }] ?? (result[0] = 42);
break;
}

case 'ConditionalExpression#Test': {
result[do { return result; }] ? (result[0] = 42) : (result[1] = 42);
break;
}

case 'ConditionalExpression#Alternate': {
Object.keys(result).length > 0 ? (result[0] = 42) : (result[do { return result; }] = 42);
break;
}

case 'ConditionalExpression#Consequent': {
Object.keys(result).length === 0 ? (result[do { return result; }] = 42) : (result[0] = 42);
break;
}

default:
throw new Error(`Unsupported test title: ${title}`);
}
// This return should not be reached.
return NaN;
}

expect(recordEarlyExit('AssignmentExpression#Left#MemberExpression#ComputedKey', {})).toEqual({});
// These cases are not supported.
// expect(recordEarlyExit('AssignmentPattern#Left#ComputedKey', [])).toEqual([]);
// expect(recordEarlyExit('AssignmentPattern#Left#ComputedKey#WithoutInitializer', [])).toEqual([]);
expect(recordEarlyExit('AssignmentPattern#Left#PatternInitializer', [])).toEqual([]);
expect(recordEarlyExit('AssignmentPattern#Left#PatternInitializer#DoEmpty', [])).toEqual([]);
expect(recordEarlyExit('AssignmentPattern#Left#PatternInitializer#WithHole', [])).toEqual([]);
expect(recordEarlyExit('AssignmentPattern#Left#PatternInitializer#WithIdentifier', [])).toEqual([]);
expect(recordEarlyExit('AssignmentPattern#Left#PatternInitializer#WithRestElement', [])).toEqual([]);
expect(recordEarlyExit('RestElement#Argument#PatternInitializer', [])).toEqual([]);
expect(recordEarlyExit('OptionalCallExpression#ComputedKey', [])).toEqual([]);
expect(recordEarlyExit('OptionalMemberExpression#ComputedKey', [])).toEqual([]);
expect(recordEarlyExit('LogicalExpression#Left#operator||', {})).toEqual({});
expect(recordEarlyExit('LogicalExpression#Left#operator&&', {})).toEqual({ undefined: 42 });
expect(recordEarlyExit('LogicalExpression#Left#operator??', {})).toEqual({});
expect(recordEarlyExit('UnaryExpression#Argument', [])).toEqual([]);
expect(recordEarlyExit('ConditionalExpression#Test', [])).toEqual([]);
expect(recordEarlyExit('ConditionalExpression#Alternate', {})).toEqual({});
expect(recordEarlyExit('ConditionalExpression#Consequent', {})).toEqual({});
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ function f1(a) {
function f2(a) {
(do { if (effects.push(1), false) return 0; ({ key: (arg) => effects.push(arg) }) })
[do { if (effects.push(2), a) return 1; 'key' }]
(do { if (effects.push(3), false) return 2; 'arg' });
(...do { if (effects.push(3), false) return [2]; ['arg'] });
}

effects = [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ function f1(a) {
function f2(a) {
(do { if (effects.push(1), false) return 0; ({ key: (arg) => effects.push(arg) }) })
[do { if (effects.push(2), a) return 1; 'key' }]
(do { if (effects.push(3), false) return 2; 'arg' });
(...do { if (effects.push(3), false) return [2]; ['arg'] });
}
Loading