Skip to content

Inline requires: Treat optional chains, logical assignments and defaults as branches when memoizing - #2280

Open
burrows99 wants to merge 1 commit into
react:mainfrom
burrows99:fix/memoized-inline-requires-conditional-refs
Open

burrows99 wants to merge 1 commit into
react:mainfrom
burrows99:fix/memoized-inline-requires-conditional-refs

Conversation

@burrows99

Copy link
Copy Markdown
Contributor

Summary

With unstable_memoizeInlineRequires, the inline-requires plugin rewrites the first reference to a module in a scope as (_m || (_m = require(...))) and later references in that scope as plain _m. isDirectlyEnclosedByBlock decides whether a reference always runs, but isBranch only knows if, ?:, &&/||/??, switch and loops. These can skip their operand too:

  • optional calls and members, including later links of the chain: cb?.(greet), cb?.[key], cb?.x.y(greet)
  • logical assignment: x ||= greet, x &&= greet, x ??= greet
  • default values: const {x = greet} = obj

When the first reference is inside one of these and gets skipped, the later references read undefined. The Hermes profile (unstable_transformProfile=hermes-stable) keeps ?. and ??=, so this app

import {greet} from 'greeter';

function welcome(name, onWelcome) {
  onWelcome?.(greet);
  return greet(name);
}

console.log(welcome('Metro'));

is bundled as

function welcome(name, onWelcome) {
  onWelcome?.((_greeter || (_greeter = require(_dependencyMap[0]))).greet);
  return (0, _greeter.greet)(name);
}

and throws TypeError: Cannot read properties of undefined (reading 'greet').

The fix adds these node types to isBranch, so a reference inside them never marks its scope as having loaded the module. A reference in the part that always runs (the callee of a?.(), the left of x ||= y) is now also treated as a branch. That is conservative, as for the left side of && today: it keeps the full (_m || (_m = require(...))) form.

flowchart TD
    A[First use of an import is in a skipped optional call] --> B{Later use in the same function}
    B -->|Before| C[Reads the memo variable while it is still undefined]
    B -->|After| D[Loads the module itself]
Loading

Changelog: [Fix] Memoized inline requires: a module first referenced in a skipped optional chain, logical assignment or default value is no longer undefined at later references

Test plan

Added memoizes a require whose first reference, in %s, is skipped to inline-requires-plugin-test.js: it transforms a module with memoizeCalls: true, runs it with vm, and checks that both an aliased (const foo = require(...)) and a destructured (const {a} = require(...)) module are loaded after a skipped first reference. Six cases: an optional call, an optional member, a later link of an optional chain, a logical assignment, a default value, and an optional call with a destructured require. All six fail on main and pass with this change.

yarn jest packages/metro-transform-plugins packages/metro-transform-worker
Tests:       251 passed, 251 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 dev server from this branch, a config with transform: {inlineRequires: true, unstable_memoizeInlineRequires: true}, and a local greeter package (exports.greet = name => 'Hello, ' + name):

$ curl -s "localhost:8091/index.bundle?platform=ios&dev=false&unstable_transformProfile=hermes-stable" -o bundle.js && node bundle.js
TypeError: Cannot read properties of undefined (reading 'greet')   # main
Hello, Metro                                                       # this branch

Narrated recording, before then after (sound on):

evidence.mp4

Edge cases and unchanged behaviour checked in the recording (the dev server from this branch):

  • a skipped format ??= greet (a formatter is passed) prints Hi Metro | Hello, Metro; on main it throws the same TypeError
  • the minified Hermes bundle prints Hello, Metro
  • unchanged: when the callback is passed (the optional call runs), it prints callback: Hello, you and Hello, Metro, as on main
  • unchanged: metro build with the default profile, which lowers ?. before inline requires runs, prints Hello, Metro, as on main

The optional member, later chain link and default value 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

…lts as branches when memoizing

With memoized inline requires, the first reference to a module in a scope
assigns the memo variable and later references in that scope read it
directly. A reference inside an optional call or member, the right-hand side
of `||=`, `&&=` or `??=`, or a default value may never be evaluated, so the
later references read `undefined`. Treat these like the other branches.
@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 23, 2026
@github-actions

Copy link
Copy Markdown

Metro review: Looks good

Risk: low · Commit: 7457d84 · 3 commands run, in a restricted sandbox after an automated safety assessment

With memoizeCalls, the PR makes isBranch treat optional calls and members, logical assignments (||=, &&=, ??=) and default values (AssignmentPattern) as branches. A first reference inside one of them that gets skipped no longer marks its scope as having loaded the module. The fix is correct and stays inside the predicate that already handles &&/||/?:. I checked it against the base on extra cases (&&=, ??=, parameter defaults, foo?.b as callee). It only gets more conservative and never emits a bare memo read before an assignment.

Findings

  • nit · Only ||= is tested, though &&= and ??= are handled too — packages/metro-transform-plugins/src/__tests__/inline-requires-plugin-test.js:13 · ff027a89

    The new isBranch clause covers ||=, &&= and ??=, but the test.each table only has x ||= foo.a. Two more rows would cover the other two operators: ['a nullish assignment', 'let x = 1; x ??= foo.a;'] and ['an and assignment', 'let x = 0; x &&= foo.a;']. Both fail on the base and pass with this change.

Verified
  • ✅ yarn jest --no-watchman packages/metro-transform-plugins/src/__tests__/inline-requires-plugin-test.js (head) — 83 tests pass, including the 6 new cases.
  • ✅ yarn jest --no-watchman packages/metro-transform-plugins/src/__tests__/review-extra-test.js (head) — The &&=, ??=, parameter default, do-while-after-break and optional-callee cases all produce correct output. A class instance field case failed on both head and base, so it predates this PR. The RN preset always lowers class properties before inline requires runs, so it isn't reachable there.
  • ✅ yarn jest --no-watchman packages/metro-transform-plugins/src/__tests__/review-extra-test.js (base) (failed as expected) — The &&= and ??= cases fail on the base, confirming the bug these operators cause.

Not run: No benchmark: the change adds a few node-type checks to the ancestor walk of each memoized reference, which doesn't plausibly change transform cost. I didn't reproduce the end-to-end dev server run with Hermes from the description. The unit tests and the base/head comparison cover the same behavior. I didn't run the typecheck or lint, since no Flow types change beyond node-type checks.

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

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