Skip to content
Open
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 @@ -128,6 +128,64 @@ describe('constant expressions', () => {
compare([constantFoldingPlugin], code, '');
});

test('keeps the declaration of a var in a removed branch that is used elsewhere', () => {
const code = `
if ('production' === 'development') {
var a = 1;
for (var i = 0; i < 3; i++) {}
}
if (true) {
f();
} else {
var b = 1, c = 2;
}
if (x) {
g();
} else if (false) {
var d;
}
export function h() {
if (false) {
var k = 1;
}
return k;
}
use(a, i, b, d);
c = 3;
`;

const expected = `
var a, i, b, c, d;
{
f();
}
if (x) {
g();
}
export function h() {
var k;
return k;
}
use(a, i, b, d);
c = 3;
`;

compare([constantFoldingPlugin], code, expected);
});

test('does not keep a var from a removed branch that is only used in a nested function there', () => {
const code = `
if (false) {
(function () {
var c;
});
}
use(c);
`;

compare([constantFoldingPlugin], code, 'use(c);');
});

test('does not fold non-literal void expressions', () => {
const code = `
void obj.prop;
Expand Down
47 changes: 47 additions & 0 deletions packages/metro-transform-plugins/src/constant-folding-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,53 @@ export default function constantFoldingPlugin(context: {
if (result.confident) {
state.stripped = true;

// `var`s are hoisted out of the branch that is dropped. Keep a bare
// declaration for those still used outside it, so they read as
// `undefined` instead of throwing a ReferenceError.
const dropped: NodePath<> = result.value
? // $FlowFixMe[incompatible-type]
path.get('alternate')
: // $FlowFixMe[incompatible-type]
path.get('consequent');
const hoisted = new Set<string>();
const outside = (p: NodePath<>) => !p.isDescendant(dropped);
const collect = (declaration: NodePath<>) => {
const {node} = declaration;
if (node?.type !== 'VariableDeclaration' || node.kind !== 'var') {
return;
}
for (const name of Object.keys(
declaration.getBindingIdentifiers(),
)) {
const binding = declaration.scope.getBinding(name);
// Declared elsewhere too (as a param or function, say).
if (binding?.kind !== 'var') {
continue;
}
const writes = [binding.path, ...binding.constantViolations];
if (
!writes.some(p => p.isVariableDeclarator() && outside(p)) &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

should fix · A var declared in two dead branches is still dropped

The check !writes.some(p => p.isVariableDeclarator() && outside(p)) skips hoisting when the binding has another declarator outside the current dead branch. Scope bindings aren't recomputed until the whole pass ends (clearScope()/crawl() in Program.exit). So a declarator that sat in an earlier dead branch, already removed in this pass, still shows up in binding.path/constantViolations and counts as "declared elsewhere".

Take two dead branches that redeclare the same name:

if (false) { var a = 1; }
if (false) { var a = 2; }
use(a);

The output is use(a); with no declaration, which is the same ReferenceError the PR sets out to fix. On the first fold, the second declarator counts as outside, so nothing is hoisted. On the second fold, the first declarator (already removed) counts as outside. The if (true) {} else { var a = 1; } form, repeated twice, loses a the same way. A file with several if (__DEV__) { var x = ... } blocks hits this.

Suggested fix: track the dead branches removed so far in the current pass. Then count a declarator as live only if it isn't inside any of them, e.g. droppedSoFar.every(d => !p.isDescendant(d)), with the list reset per traversal. Please add the two-dead-branches case to the new test.

Dropping the "declared elsewhere" clause altogether isn't a good alternative. It emits redundant var a; declarations next to live ones. It also breaks the existing can optimize if-else-branches with constant conditions test, because the extra declaration adds a constant violation that stops var b = a + 4 from folding.

Reproduced: I added a probe test at packages/metro-transform-plugins/src/__tests__/review-probe-test.js and ran it with yarn jest --no-watchman on the head. The two-dead-if case printed use(a); and the two-dead-else case printed {}\n{}\nuse(a);, both missing var a. The base gives the same output. Then I patched in a closure-level list of dropped branch paths and checked declarators against it. Both cases then printed var a; ..., the live-redeclaration cases were unchanged, and all 30 tests in the constant-folding and probe suites passed. Afterwards I reverted the patch. · id be5026ce

[...binding.referencePaths, ...writes].some(outside)
) {
hoisted.add(name);
}
}
};
if (dropped.node != null) {
collect(dropped);
dropped.traverse({
Function(p: NodePath<>) {
p.skip();
},
VariableDeclaration: collect,
});
}
const scope =
path.scope.getFunctionParent() ?? path.scope.getProgramParent();
for (const name of hoisted) {
scope.push({id: t.identifier(name)});
}

if (result.value || node.alternate) {
const valueIsTruthy = Boolean(result.value);
// $FlowFixMe[incompatible-type]
Expand Down