Skip to content

Keep hoisted var declarations when folding away a branch - #2279

Open
burrows99 wants to merge 1 commit into
react:mainfrom
burrows99:fix/constant-folding-keep-hoisted-vars
Open

burrows99 wants to merge 1 commit into
react:mainfrom
burrows99:fix/constant-folding-keep-hoisted-vars

Conversation

@burrows99

Copy link
Copy Markdown
Contributor

Summary

When an if test folds to a constant, constantFoldingPlugin removes the dead branch, including any var declared in it. var is hoisted to the enclosing function or program, so code outside the branch can still read or assign it. A package like

if (process.env.NODE_ENV !== 'production') {
  var devOnlyTimer = Date.now();
  var overrides = {};
}

module.exports = function isEnabled(name) {
  return !!(overrides && overrides[name]);
};

works in a dev build (overrides is {}), and without Metro overrides would just be undefined in production. In a Metro production build the declaration is gone, so isEnabled() throws ReferenceError: overrides is not defined (and an assignment to such a name would create a global in sloppy code, or throw in strict code).

The fix: before removing a branch, collect the vars it declares (not those inside nested functions) that are referenced or assigned outside it and not declared anywhere else, and keep a bare var name; for each at the top of the enclosing function or program (scope.push). A var that nothing outside the branch uses is still dropped, so the existing can remode an if statement with a falsy constant test and if-else-branches tests are unchanged.

flowchart TD
    A[Production build folds a dev only if with a var] --> B{Var used outside the branch}
    B -->|Before| C[Declaration dropped so the app throws ReferenceError]
    B -->|After| D[Bare var kept so it reads undefined]
Loading

Changelog: [Fix] Keep var declarations from a folded-away branch that are used outside it, instead of throwing a ReferenceError in production builds

Test plan

Added two tests to constant-folding-plugin-test.js:

  • keeps the declaration of a var in a removed branch that is used elsewhere: a falsy if (including a for (var i ...) inside it), a truthy if whose else declares two vars (one read, one assigned later), an else if (false) branch, and a dead branch inside an exported function. Fails on main (the declarations are gone and use(a, i, b, d) / c = 3 / return k refer to nothing); passes with this change.
  • does not keep a var from a removed branch that is only used in a nested function there: a var inside a function expression in the dead branch is not hoisted out of it.
yarn jest packages/metro-transform-plugins packages/metro-transform-worker packages/metro/src/integration_tests
Tests:       350 passed, 350 total

yarn flow check  -> No errors!
eslint and prettier --check on the two changed files -> clean

I did not run the full yarn test.

End to end with the Metro CLI from this branch (metro build, the package above in a local node_modules/feature-flags, and console.log('newHeader enabled:', isEnabled('newHeader')) as the entry):

$ metro build index.js --dev false --minify false --out bundle.js && node bundle.js
ReferenceError: overrides is not defined     # main
newHeader enabled: false                     # this branch

Narrated recording, before then after (sound on):

evidence.mp4

Edge cases and unchanged behaviour checked in the recording (the CLI from this branch): the minified production build also prints newHeader enabled: false; the unused devOnlyTimer var from the same dead branch is still removed (grep -c devOnlyTimer bundle.js prints 0); the dev build is unchanged. The else if, for (var ...), assignment-only and nested-function cases are covered by the unit tests only.

AI assistance (Claude Code) was used to find this bug, write the change and run the checks above.

🤖 Generated with Claude Code

constantFoldingPlugin removes the dead branch of an `if` with a constant
test, including any `var` declared in it. `var` is hoisted, so code
outside the branch may still read or assign it: after
`if ("production" !== process.env.NODE_ENV) { var overrides = {}; }`,
`overrides && overrides[name]` evaluates to undefined in a dev build but
threw `ReferenceError: overrides is not defined` in a production build.

When a removed branch declares a `var` that is used outside it and not
declared anywhere else, keep a bare `var name;` at the top of the
enclosing function or program. Unused declarations are still dropped.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed. label Nov 22, 2026
@github-actions

Copy link
Copy Markdown

Metro review: Changes suggested

Risk: low · Commit: 1a3a8ed · 5 commands run, in a restricted sandbox after an automated safety assessment

When constant folding removes a dead branch, the PR keeps a bare var for each variable declared in that branch and used outside it. The approach is sound and the PR's tests pass. One common pattern still loses the declaration: the same var declared in two dead branches. The "declared elsewhere" check relies on binding data from before the first fold, so it treats the other dead branch's declarator as still live.

Findings

Verified
  • ✅ yarn jest --no-watchman packages/metro-transform-plugins — 201 tests pass on the PR head, including the two new tests
  • ✅ yarn jest --no-watchman packages/metro-transform-plugins/src/__tests__/review-probe-test.js (head) (failed as expected) — Two dead branches declaring the same var: output is use(a); with no declaration. Nested dead ifs, for-in, destructuring, static blocks and a live redeclaration are handled correctly.
  • ✅ yarn jest --no-watchman packages/metro-transform-plugins/src/__tests__/review-probe-test.js (base) — Base also drops a in these cases, as expected before the fix
  • ✅ Head with a dropped-branches list patched into the outside-declarator check, then yarn jest on the probe and constant-folding-plugin-test — 30/30 pass, and var a; is kept in both two-dead-branch cases. Reverted afterwards.
  • ❌ Head with the outside-declarator check removed entirely, then yarn jest constant-folding-plugin-test — Breaks the existing if-else-branches test (adds var a, a, b; and blocks constant inlining), so that clause is needed

Not run: I didn't run yarn typecheck or lint, since my edits were temporary and the PR's Flow annotations are unchanged by this review. I didn't reproduce the end-to-end metro build claim. The unit-level transform output covers the same code path. I didn't benchmark: the extra work runs only when a branch is folded away, and walks only that branch.

Automated review by Claude. Advisory only: it never approves or blocks, and a maintainer makes the call.

}
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

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Facebook bot. Authors need to sign the CLA before a PR can be reviewed.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant