Skip to content

Commit

Permalink
Add support for labeled statements
Browse files Browse the repository at this point in the history
  • Loading branch information
lxsmnsyc committed Mar 8, 2023
1 parent 37c1d3c commit 4df469f
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 0 deletions.
15 changes: 15 additions & 0 deletions packages/forgetti/src/core/optimizer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1095,6 +1095,19 @@ export default class Optimizer {
this.scope.push(path.node);
}

optimizeLabeledStatement(
path: babel.NodePath<t.LabeledStatement>,
) {
const parent = this.scope;
const block = new OptimizerScope(this.ctx, path, parent);
this.scope = block;
this.optimizeStatement(path.get('body'));
this.scope = parent;
path.node.body = t.blockStatement(block.getStatements());
// this.optimizeStatement(path.get('body'));
this.scope.push(path.node);
}

optimizeStatement(
path: babel.NodePath<t.Statement>,
topBlock = false,
Expand All @@ -1119,6 +1132,8 @@ export default class Optimizer {
this.optimizeSwitchStatement(path);
} else if (isPathValid(path, t.isTryStatement)) {
this.optimizeTryStatement(path);
} else if (isPathValid(path, t.isLabeledStatement)) {
this.optimizeLabeledStatement(path);
} else {
this.scope.push(path.node);
}
Expand Down
20 changes: 20 additions & 0 deletions packages/forgetti/test/__snapshots__/statements.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,26 @@ function Example(props) {
}"
`;

exports[`statements > should optimize labeled statements 1`] = `
"import { useMemo as _useMemo } from \\"react\\";
function Example(props) {
let _c3 = _useMemo(() => new Array(2), []);
foo: {
let _c2 = _c3[0] ||= new Array(1);
{
let _c = _c2[0] ||= new Array(2);
let _v = _c[0] ||= console.log(\\"face\\");
_v;
break foo;
let _v2 = _c[1] ||= console.log(\\"this will not be executed\\");
_v2;
}
}
let _v3 = _c3[1] ||= console.log(\\"swap\\");
_v3;
}"
`;

exports[`statements > should optimize switch statements 1`] = `
"import { useMemo as _useMemo } from \\"react\\";
function Example(props) {
Expand Down
13 changes: 13 additions & 0 deletions packages/forgetti/test/statements.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,17 @@ describe('statements', () => {
`;
expect(await compile(code)).toMatchSnapshot();
});
it('should optimize labeled statements', async () => {
const code = `
function Example(props) {
foo: {
console.log("face");
break foo;
console.log("this will not be executed");
}
console.log("swap");
}
`;
expect(await compile(code)).toMatchSnapshot();
});
});

0 comments on commit 4df469f

Please sign in to comment.