Repository navigation
Conversation
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.
Metro review: Changes suggestedRisk: low · Commit: When constant folding removes a dead branch, the PR keeps a bare Findings
Verified
Not run: I didn't run 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)) && |
There was a problem hiding this comment.
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
Summary
When an
iftest folds to a constant,constantFoldingPluginremoves the dead branch, including anyvardeclared in it.varis hoisted to the enclosing function or program, so code outside the branch can still read or assign it. A package likeworks in a dev build (
overridesis{}), and without Metrooverrideswould just beundefinedin production. In a Metro production build the declaration is gone, soisEnabled()throwsReferenceError: 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 barevar name;for each at the top of the enclosing function or program (scope.push). Avarthat nothing outside the branch uses is still dropped, so the existingcan remode an if statement with a falsy constant testandif-else-branchestests 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]Changelog: [Fix] Keep
vardeclarations from a folded-away branch that are used outside it, instead of throwing a ReferenceError in production buildsTest 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 falsyif(including afor (var i ...)inside it), a truthyifwhoseelsedeclares two vars (one read, one assigned later), anelse if (false)branch, and a dead branch inside an exported function. Fails onmain(the declarations are gone anduse(a, i, b, d)/c = 3/return krefer to nothing); passes with this change.does not keep a var from a removed branch that is only used in a nested function there: avarinside a function expression in the dead branch is not hoisted out of it.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 localnode_modules/feature-flags, andconsole.log('newHeader enabled:', isEnabled('newHeader'))as the entry):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 unuseddevOnlyTimervar from the same dead branch is still removed (grep -c devOnlyTimer bundle.jsprints0); the dev build is unchanged. Theelse 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