Skip to content

Keep side effects in sequence operands when folding constants - #2278

Merged
robhogan merged 1 commit into
react:mainfrom
burrows99:fix/constant-folding-sequence-side-effects
Nov 22, 2026
Merged

robhogan merged 1 commit into
react:mainfrom
burrows99:fix/constant-folding-sequence-side-effects

Conversation

@burrows99

Copy link
Copy Markdown
Contributor

Summary

constantFoldingPlugin folds an if/ternary/logical test when Babel can evaluate it. Babel evaluates a sequence expression to its last operand, and the plugin's side-effect check only looked for calls and assignments. So a test like (n++, false) counted as the constant false, and the n++ was dropped with the dead branch.

Minifiers produce exactly this shape: they join a statement into the following if test. A prebuilt package with

var n=0;module.exports=function(){if(n++,"production"!==process.env.NODE_ENV)console.warn("dev only");return n};

becomes if (n++, false) once Metro inlines NODE_ENV in a production build, and the whole if was removed, so the counter never moved. Dev builds were fine.

The fix marks update (++/--), delete, new, await, yield and tagged template expressions as unsafe to fold, next to the existing CallExpression / AssignmentExpression / OptionalCallExpression entries. A sequence whose leading operands have no side effects ((0, false)) still folds. The unsafe callback's parameter type is widened to NodePath<> so it accepts the new node types.

flowchart TD
    A[Minified test n++ then a NODE_ENV check] --> B{Production build folds the test}
    B -->|Before| C[Branch and n++ removed so the app prints 0 0 0]
    B -->|After| D[Test kept so the app prints 1 2 3]
Loading

Changelog: [Fix] Keep side effects such as i++ in the leading operands of a sequence when folding constants in production builds

Test plan

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

  • does not drop side effects from the leading operands of a sequence: if ((i++, false)), (delete o.x, true) ? 1 : 2, (new Foo(), null) || 3, (--j, 1) + 2, (tag`x`, 0) || 4, and await / yield in an if test are all left alone. It fails on main (every one of them is folded and the side effect is gone) and passes with this change.
  • folds a sequence whose leading operands have no side effects: (0, 'production' !== 'production') ? 1 : 2 still becomes 2.
yarn jest packages/metro-transform-plugins packages/metro-transform-worker
Tests:       245 passed, 245 total
Snapshots:   70 passed, 70 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, a local node_modules/counter-lib holding the minified line above, and console.log(nextId(), nextId(), nextId()) as the entry):

$ metro build index.js --dev false --out bundle.js && node bundle.js
0 0 0     # main
1 2 3     # 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): an unminified production build (--minify false) also prints 1 2 3; the minified production bundle still has no dev only code in it (grep -c prints 0, the minifier removes the dead branch); a dev build is unchanged (warns three times, prints 1 2 3). The other side-effect kinds (delete, new, --, tagged templates, await, yield) are covered by the unit test only.

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

🤖 Generated with Claude Code

Babel evaluates a sequence expression to its last operand, so
constantFoldingPlugin treated a test like `(n++, false)` as a constant and
dropped `n++`. Minifiers join statements into an `if` test this way, so
`if(n++,"production"!==process.env.NODE_ENV)` in a prebuilt package lost
its increment in production builds. Treat update, delete, new, await,
yield and tagged template expressions as unsafe to fold, like calls and
assignments already are.
@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: Looks good

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

The constant-folding plugin's side-effect check now also stops folding on update, delete, new, await, yield and tagged template expressions. Before, Babel's evaluate read a sequence as its last operand, so a test like (i++, false) got folded and the i++ was lost. The fix is small and covered by tests, and it also fixes the same loss in the unary/binary folding path: on base, !(i++, 1) became false and typeof (i++, 1) became "number". Each non-delete operator gets an unsafe entry, matching how the existing call and assignment entries are written.

Findings

Verified
  • ✅ yarn jest --no-watchman packages/metro-transform-plugins packages/metro-transform-worker — 246 tests and 70 snapshots pass at head.
  • ✅ yarn jest --no-watchman (the PR's constant-folding-plugin-test.js copied into the base checkout) (failed as expected) — Without the fix, 'does not drop side effects from the leading operands of a sequence' fails; the other 28 tests pass.
  • ✅ yarn jest --no-watchman packages/metro-transform-plugins/src/__tests__/review-probe-test.js (head and base) — Compared head and base output on 15 inputs. Head now keeps update, unary-wrapped, ?? and void sequence cases that base folded. Member access, template literal and in operands are still folded in both.
  • ✅ yarn typecheck — No errors.
  • ✅ yarn eslint on the two changed files

Not run: No benchmark: the change adds a few visitor keys to a traversal of each folded test expression, which already ran, so per-file cost barely changes. I didn't reproduce the end-to-end metro build demo from the description; the unit tests and the head/base probe cover the same transform. No Windows run, because the logic doesn't depend on the platform.

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

* resulting in the expression call being skipped.
*/
OptionalCallExpression: unsafe,
// Babel evaluates a sequence to its last operand, so side effects in

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit · Property access in a leading sequence operand is still dropped

The check is a deny-list, so some leading operands that can still have effects are folded away. The closest to real minifier output is a member access: if ((o.x, false)) { a(); } still becomes nothing. That drops a getter call, or the TypeError thrown when o is nullish. (`${o}`, false) (which calls toString) and ("x" in p, false) (which runs a Proxy trap) are dropped too. This isn't new in this PR, and these cases are rarer than n++. If you want the sequence case closed off fully, check that the leading operands are pure, for example path.get('expressions').slice(0, -1).every(p => p.scope.isPure(p.node)) in a SequenceExpression entry. That is an allow-list, so it handles cases nobody thought to list. Otherwise, the comment could say which cases the list deliberately leaves out.

Reproduced: A probe test (packages/metro-transform-plugins/src/__tests__/review-probe-test.js, run in both checkouts) printed the plugin's output. Head and base both reduce if ((o.x, false)) { a(); }, if ((`${o}`, false)) { a(); } and if (("x" in p, false)) { a(); } to empty output. Head keeps (i++, false), !(i++, 1), typeof (i++, 1) and (i++, 1) ?? 2, all of which base folded. · id 0b01608a

@robhogan

Copy link
Copy Markdown
Collaborator

This is the first time I've seen an AI-narrated screen recording in a PR!

This is good stuff though - nice and tight diff, readable description, proven testing. Thanks!

@robhogan
robhogan merged commit 572f800 into react:main Nov 22, 2026
16 checks passed
@burrows99
burrows99 deleted the fix/constant-folding-sequence-side-effects branch November 22, 2026 20:01
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.

2 participants