Repository navigation
React Compiler integration - #32504
Conversation
- ref-type slot allocation: useRef return type now {object: stable, current: mutable}
so .current reads keep their reactive slot through phi joins (reactive-ref,
reactive-ref-param, ref-type-convergence-with-phi-join)
- sequential-destructuring scope split: per-function error no longer aborts the
file (sequential-destructuring-* x2)
- method-call mutable-range sync: receiver property read Effect corrected
(method-call-scope-merge-mutable-range-sync)
- jsx lowering: tag/property Effect alignment with upstream
2 remain: destructuring-mixed-scope-and-local-variables-with-default (off-by-1
slot from default-value temp), tagged-template-in-hook (should bail, compiles).
Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
…1, 0 fail) resolve_identifier was falling through to VariableBinding::Global for every imported name because import_bindings had a setter but was never populated (namespace_alias is only set after scan_imports, which runs after the visit pass). This meant resolve_module_type was never reached, so shared-runtime types (graphql returnType=Primitive, useFragment noAlias=true) were ignored. Fixes the last two fixtures: - destructuring-mixed-scope-and-local-variables-with-default: graphql tagged template now typed Primitive → mayAllocate=false → no extra scope (9→8 slots) - tagged-template-in-hook: useFragment noAlias keeps the arg out of escapingValues → scope pruned → no runtime import Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
|
Updated 3:43 AM PT - Jun 20th, 2026
❌ @Jarred-Sumner, your commit dd8a936 has 1 failures in
Add 🧪 To try this PR locally: bunx bun-pr 32504That installs a local version of the PR into your bun-32504 --bun |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Found 1 issue this PR may fix:
🤖 Generated with Claude Code |
|
This PR may be a duplicate of:
🤖 Generated with Claude Code |
…obals - IndexMap/IndexSet → bun_collections::ArrayHashMap<_,_,AutoContext,AstAlloc> via src/react_compiler/collections.rs shim (drop-in; one use-line per module) - HIR Vec<T> → AstVec<T> (thread-local AstAlloc; no lifetime added) - hir/globals.rs base_globals: LazyLock<HashMap<String,_>> → comptime_string_map index (64 keys) into Box<[Global]> - indexmap dep removed; bun_react_compiler now has zero non-Bun deps 1261/0 fixtures, 3/3 snapshot, 10/10 cross-targets unchanged. Fixture suite 2.66s → 2.52s. Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
…61→1568 fixtures) Port upstream parseConfigPragmaForTests into program.rs::parse_fixture_pragmas. Reads all leading // @key / @key:value / @key(value) lines and applies them to EnvironmentConfig + ReactCompilerOptions before compilation. Runner: move handled keys from skip-list to HANDLED_PRAGMAS; add UNSUPPORTED_PRAGMAS for outputMode (lint/SSR meaningless for a bundler), dynamicGating (use-memo-if directive validation not ported), enableResetCacheOnSourceFileChanges (Bun has its own React Refresh). 5 new TODOs for genuine porting gaps: - validate_preserved_manual_memoization: missing inferred-dep-not-in-source check (3) - suppression.rs: implemented but not invoked from program.rs (1) - codegen slot off-by-one for invalid-set-state-in-effect-verbose-force-update (1) Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
…utMode/dynamicGating (1568→1605) Suppression detection moves into the lexer (one strings::contains per comment, gated on features.react_compiler) and propagates via a flag bit on G::Fn (8th flags::Function variant, still u8) / E::Arrow (4th bool, fits in existing padding). maybe_compile_* checks the bit and skips. No source re-scan, no per-comment allocation, no Host::all_comments. suppression.rs deleted. parse_fixture_pragmas (the // @EnableX test-only config parser) is now gated on ReactCompilerOptions::parse_test_pragmas (default false), set via Bun.build({reactCompilerParseTestPragmas: true}) by the fixture runner only. Production builds never read host.source(). Also: wire @outputMode (lint/ssr) and @dynamicGating; fix the invalid-set-state-in-effect-verbose-force-update slot count. Note: the lexer flag is monotonically sticky (no eslint-enable pairing), so a suppression marks every function after it in source order. Over-approximation of upstream's range-overlap check; compiling-skip is always safe. Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
A suppression inside a nested closure must reach the enclosing top-level component (which is what maybe_compile_function checks), but must not leak to that component's siblings. parse_fn_body already restores fn_or_arrow_data_parse, so is_top_level after it returns is the outer scope. Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
…05→1608) Second lexer bool has_react_hooks_block_suppression: a comment matching react-hooks/ + eslint-disable WITHOUT -next-line sets the sticky block flag (never cleared); with -next-line, only the consume-once _before flag is set. parse_fn checks (before || block); only _before is cleared at top-level exit. Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
…lint-gated validations (1607→1614, 0 todo) - CollectReactiveIdentifiers: port `isStableRefType` (useRef-only) instead of the wider `isStableType`, matching upstream CollectReactiveIdentifiers.ts. Fixes optional-chain-on-known-nonnull and one sibling. - parse_fixture_pragmas: default panicThreshold="all_errors" and validatePreserveExistingMemoizationGuarantees=false to match upstream parseConfigPragmaForTests + snap makePluginOptions. Under fixture mode, Invariant/Todo diagnostics still bail per-function (port-incomplete passes, not user-facing errors). Fix `validateExhaustiveEffectDependencies` pragma value parsing (kebab-case). - pipeline: gate validateNoSetStateInEffects / validateNoJSXInTryStatement / validateStaticComponents on outputMode==lint and drop their result, matching upstream `env.logErrors()` (logger-only, never fails compilation). - shared-runtime type provider: add typedCapture/typedCreateFrom/typedMutate aliasing signatures and the ReactCompilerKnownIncompatibleTest module. - infer_mutation_aliasing_effects: avoid redundant InferenceState clones in the worklist queue. - pipeline: add BUN_REACT_COMPILER_TIMING=1 per-pass timing. - fixtures harness: empty TODO map; guard against the "constructor" fixture name matching Object.prototype. Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
…allVec (868→556ms on a large React codebase) InferMutationAliasingEffects was 44% of React Compiler CPU. The state it clones per block per fixpoint iteration held HashSet<ValueReason> (12-variant enum, heap-allocated per AbstractValue) and HashSet<ValueId> per identifier. - ValueReason: EnumSetType → ValueReasonSet packs to u16 - AbstractValue: now Copy (kind + u16 reason = 4 bytes) - variables: HashMap<IdentifierId, SmallVec<[ValueId;4]>> (most are singletons) - merge_from(&mut self, other) -> bool: in-place, no new InferenceState - merge_abstract_values: kind | kind, reason | reason Large React codebase bench (~650 components): baseline 360ms → native 556ms (1.54×, was 2.51×) InferMutationAliasingEffects 1853ms → 509ms (−73%) total React Compiler CPU 4236ms → 2346ms (−45%) 1618 pass / 193 skip / 0 todo / 0 fail. Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
…12ms on a large React codebase) InferenceState.values: HashMap<ValueId,AbstractValue> → Vec<Option<AbstractValue>> indexed by pass-local ValueId (was process-global AtomicU32). Clone is memcpy. variables left as HashMap — IdentifierId is environment-wide, dense Vec regressed nested-function inference (519→649ms). resolve_identifier: refs in module_scope.generated (jsx/jsxDEV/Fragment/_c, minted by visit after collect_import_bindings) now return VariableBinding::Global instead of falling through to uninitialized. Fixes the "Expected value kind to be initialized ... Fragment$N" invariant on 44 fixtures that were false-passing. 3 fixtures added to TODO: they now emit one extra $[n]!==Fragment check because Bun lowers post-JSX-transform and sees Fragment as a tag dep (upstream's JsxFragment HIR has no tag). Semantically correct; not upstream-identical. InferMutationAliasingEffects 509→439ms; AnalyseFunctions 366→320ms. Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
…ps; Fragment→JsxTag::Fragment (512→484ms) Same HashMap<SmallId,_> → Vec<_> treatment for the next-hottest passes (InstructionId/BlockId/ScopeId are dense per-function u32s): InferReactivePlaces 232→87ms, EnterSSA 134→61ms, AnalyseFunctions 320→238ms variables in InferenceState: top-level fn uses dense Vec, nested fns keep HashMap (IdentifierId is environment-wide; dense Vec for nested fns regressed). lower_jsx_call: tag identifier resolving to jsx-runtime Fragment → JsxTag::Fragment (no place), matching upstream JsxFragment HIR. Removes the spurious $[n]!==Fragment dep check. Large React codebase bench (~650 components): baseline 391ms → native 484ms (1.24×, +93ms). Total React Compiler CPU 2346→2088ms. 1618 pass / 193 skip / 0 todo / 0 fail. Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
cc6e600 to
2887de7
Compare
|
Wonderful, thank you for working on this one. This has been the single biggest friction point in the stack |
…19→1395 KB)
8 passes (outline_jsx, name_anonymous_functions, validate_no_{set_state_in_effects,
derived_computations_in_effects,capitalized_calls,jsx_in_try_statement},
validate_static_components, compile_outlined_fn) plus parse_fixture_pragmas and
the BUN_REACT_COMPILER_TIMING accumulator are gated on
cfg(any(debug_assertions, feature="fixtures")) — they are only reachable via
test pragmas, which production builds never set. LTO strips them.
optimize_for_ssr stays in production: Bun.build({reactCompilerOutputMode: "ssr"})
now drops the compiler-runtime import, skips memoization, and runs the SSR
transform (e.g. useState(x) → const = x). Invalid values throw.
Large React codebase bench (~650 components): 457ms (1.35× baseline, +118ms).
react_compiler symbols 1519→1395 KB.
1614 pass / 193 skip / 0 fail.
Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
…f unchanged) [profile.release.package.bun_react_compiler] opt-level = "s" Large React codebase bench: 493ms (1.35× baseline) — within noise of 457ms. react_compiler symbols 1395→1098 KB (−21%). Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
…m (1098→1052 KB) - diagnostics: #[cold] cold_diagnostic/cold_todo/cold_invariant; ~150 call sites return Err(cold_*(...)) instead of inlining CompilerDiagnostic::new - hir/visitors: #[inline(never)] each_operand/each_lvalue/each_operand_mut; passes that only visit Places now share one 60-arm dispatch - collections: IdMap<K,V> stores keys as raw u32 (collapses K monomorphs for converted call sites; core HIR maps in hir/mod.rs still per-newtype) Large React codebase bench: 480ms (1.35× baseline). 1618 pass / 0 fail. react_compiler symbols 1098→1052 KB. Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
…based default Replace react_compiler: bool + react_compiler_ssr: bool with one ReactCompilerMode enum on Features/BundleOptions/TransformOptions. When reactCompiler: true and reactCompilerOutputMode is unspecified, the mode is derived from target at the options-construction site (js_bundle_completion_task.rs for Bun.build, build_command.rs for CLI): bun/node/macro/ssr → Ssr, browser → Client. pipeline.rs: gate add_memo_cache_import on Client so SSR output has no unused react/compiler-runtime import. expectBundled.ts: pass reactCompiler through to Bun.build for backend:"api". 6/6 snapshot tests (2 new for target defaults), 1614/0 fixtures. Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
Replaces the post-visit `maybe_compile_expr` walk and the `*mut G::Fn` threading with a Copy `PendingCompile` struct (args/flags/locs/binding) populated by `visit_func`/arrow-visit and consumed inside `visit_stmts` between its visit phase and its inline-mangle phase. The compiled body lands in the live `stmts` buffer so the existing mangle runs on it; new args/flags flow back via a single `CompileResult` field. No `unsafe`, no extra passes, non-RC path cost is one `is_some()` per top-level decl. Also: - emit `DeclareContext` at first-forward-reference index (not block top) so the mutable range no longer spans hooks and scopes are not flattened - treat `EBranchBoolean` as `Primitive::Boolean` in lowering - tighten react-hooks eslint-disable comment detection in the lexer - free `LinkerGraph.files.entry_bits` (`AutoBitSet::Dynamic`) on bundle teardown — leaked when entry points exceeded 64 - fixture test: normalize Glob paths to `/` for Windows - delete dead `mutate`/`VALUE_ID_SET_SPILLS`/`InferenceState.is_function_expression` [skip size check] Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
The trait default `transform_value` is the only impl and it returns Keep, so the Replace variant is never constructed and the 17 match arms that consume it are dead. Collapse `transform_value` to `Result<(), _>`. Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
Upstream lower() returns Err when builder.errors.hasAnyErrors() before builder.build(); the Bun port was only checking Invariant errors here and deferring the full has_errors() gate to the end of the pipeline. After the forward-reference hoist landed, functions that record a Todo error during lowering (throw inside try/catch, var declarations, etc.) no longer happen to fail EnterSSA, so they were running the full pass set — including InferMutationAliasingEffects on multi-thousand-instruction bodies — only to be discarded at the final has_errors() check. Widening the post-lowering gate to has_errors() restores the upstream bail point: 49 fewer functions reach run_hir_passes on a large React app build, InferMutationAliasingEffects aggregate time drops from ~695ms to ~484ms, and wall-clock for a 1k-component build drops from ~715ms to ~493ms with identical output (memo_cache_sentinel count unchanged). [skip size check] Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
Upstream Pipeline.ts calls .unwrap() on validateNoRefAccessInRender, validateNoSetStateInRender, validateNoImpureFunctionsInRender and validateNoFreezingKnownMutableFunctions, so a validation diagnostic throws out of runWithEnvironment at that point. The Bun ports of those passes record into env.errors and return unit, so a function that fails validation was continuing through InferReactivePlaces, the full reactive-scope pass set, and codegen before the end-of-pipeline has_errors() gate discarded it. Adding an explicit has_errors() gate at the upstream throw point skips those passes for ~70 functions on a 1k-component build with no change in which functions compile (memo_cache_sentinel count unchanged). [skip size check] Claude-Session: https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: ⛔ Files ignored due to path filters (2)
📒 Files selected for processing (298)
Disabled knowledge base sources:
WalkthroughThis PR adds Bun React Compiler configuration and documentation, wires parser and bundler support for React Compiler execution, introduces a new ChangesReact Compiler integration
Comment |
|
Follow-up for the three review findings is up at #32545. |
Follow-up to #32504, addressing the three review comments left on the merged PR. ## `reactCompilerOutputMode` no longer enables the compiler on its own `Bun.build({ reactCompiler: false, reactCompilerOutputMode: 'client' })` (or the equivalent with `'ssr'`, or with `reactCompiler` unset) previously ran the React Compiler pass anyway, because the `reactCompilerOutputMode` handler in `JSBundler.rs` unconditionally overwrote `this.react_compiler` with `Client`/`Ssr`. The output mode is now stored in a separate `Option<ReactCompilerMode>` field and only applied in `js_bundle_completion_task.rs` when `reactCompiler` is enabled, matching the documented behavior in `bun.d.ts`. The `react_compiler_output_mode_explicit` bool is no longer needed. Verified by `OutputModeIgnoredWhenCompilerDisabled-{Client,Ssr}`, which fail on `main` and pass here. `OutputModeExplicitSsrOverridesTarget` guards that an explicit `reactCompilerOutputMode` still overrides the target-derived default when the compiler is on. ## `import_record_indices` on the ReactCompiler part The `Part` pushed for the `react/compiler-runtime` import in `parse_entry.rs` left `import_record_indices` empty via `..Default::default()`, unlike every sibling synthetic-import part (JSX runtime, react-refresh, BunTest). It now collects each `SImport`'s `import_record_index` and sets the field. This turns out not to be observable today: `P::to_ast` runs `ImportScanner::scan` over every part and back-fills `import_record_indices` from the `SImport` statements (`p.rs:8392`), so the linker already sees the right edges. The change is kept for consistency with the other synthetic parts and as a guard should that back-fill ever change. `BundledCjsCompilerRuntimeSurvivesTreeShaking` covers the bundled-CJS-runtime + tree-shaking case end to end. ## Stale port paths in the sync tooling `scripts/sync-react-compiler.sh`, `src/react_compiler/DESIGN.md`, and `.claude/skills/sync-react-compiler.md` referenced `lowering/build_hir.rs` (now the `lowering/build_hir/` directory), plus `lowering/identifier_loc_index.rs`, `gating.rs`, and `suppression.rs`, none of which exist. The script's `port:` hints and the DESIGN.md layout table now point at where that logic actually lives (gating folded into `program.rs`; suppression detected in `js_parser/lexer.rs` and consumed in `program.rs`; identifier-loc index not needed because `Ref` provides binding identity). ## Tests ``` bun bd test test/bundler/transpiler/react-compiler.test.ts # 15 pass bun bd test test/bundler/transpiler/react-compiler-fixtures.test.ts # 1647 pass / 160 skip ``` Closes the review threads on #32504: r3447488111, r3447488114, r3447488115. --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
…its declaration (#42390) ### Problem - `bun build --react-compiler --target=browser` aborts on a component with a helper above a `let` that the helper reads and that is reassigned later: `panic: Expected identifier to be initialized` (`prune_non_escaping_scopes.rs:195`). With other helper bodies the compiler skips the function instead (`Invariant: [InferMutationAliasingEffects] Expected value kind to be initialized`), so it is not memoized. - The block hoisting pass (`src/react_compiler/lowering/build_hir/stmt.rs:158`) skipped every binding that `is_context_identifier`. `FindContextIdentifiers` marks a captured and reassigned local before lowering starts, so that local got no `DeclareContext HoistedLet`. The closure then captured a variable that no instruction had declared. ### Fix - Skip a binding only if it was already hoisted (`is_hoisted_identifier`), like `BuildHIR.ts` and the upstream Rust crate. - Correct because the HIR now has the `DeclareContext HoistedLet` that upstream prints in front of the closure. On 119 probe variants the outcome and every `_c(n)` size equal babel-plugin-react-compiler 1.0.0. Before: 41 abort, 50 skipped, 28 equal. - Verified: `test/bundler/transpiler/react-compiler.test.ts` (new `ClosureAboveReassignedLet`, SIGABRT on 1.4.2 and main). Also `react-compiler-fixtures.test.ts` (3293 pass). ### Background - A context variable is a local that a closure captures and that something reassigns. The compiler accesses it with `LoadContext` and `StoreContext` and declares it with `DeclareContext`. - A closure can name a `let` that is declared below it. Lowering emits `DeclareContext HoistedLet x` in front of the first statement that has such a closure, so every pass sees a declaration before the capture. `PruneHoistedContexts` removes it before codegen. - `FindContextIdentifiers` is the pass before lowering that finds those locals. <details><summary>Notes</summary> Repro (any directory, 1.4.2 and main 471b586): ```jsx // g.jsx export function List(p) { const renderRow = () => <Row items={items} />; let items = p.items; if (p.onlyActive) { items = items.filter((i) => i.active); } return <ul>{renderRow()}</ul>; } ``` ``` $ bun build --react-compiler --target=browser --external '*' g.jsx panic: Expected identifier to be initialized Crashed while visiting g.jsx ``` Frames: `CollectState::visit_operand` (`prune_non_escaping_scopes.rs:195`), `visit_value_for_memoization` (`:896`), `prune_non_escaping_scopes` (`:66`), `pipeline::run_hir_passes` (`pipeline.rs:622`). The operand is the context operand `items` of the `FunctionExpression`. It is in a reactive scope that is active at that instruction, and no earlier instruction has it as an lvalue, so it has no identifier node. The same cause with a self reference: `let render = () => <Row again={render} />; render = wrap(render);`. Upstream HIR for `g.jsx` (babel-plugin-react-compiler 1.0.0, `debugLogIRs`), first instructions: ``` [1] $2 = DeclareContext HoistedLet items$1 [2] $8 = Function @context[items$1] ... [3] $10 = StoreLocal Const renderRow$9 = $8 ... [6] $13 = StoreContext Let items$1 = $12 ``` `items` is a context identifier from `FindContextIdentifiers` there too (captured and reassigned), and upstream still hoists it. `BuildHIR.ts` has `if (builder.environment.isHoistedIdentifier(binding.identifier)) continue; // Already hoisted`, and `react_compiler_lowering/src/build_hir.rs` on facebook/react main has `is_hoisted_identifier(info.binding_id.0)`. The `is_context_identifier` check is in the port since #32504. Why only some helper bodies abort. Without the declaration, `InferMutationAliasingEffects` fails when the closure captures or aliases the variable (`items.length`, `[items]`, `foo(items)`, a bare `items`): the value kind of `items` is not initialized, and that invariant is already a per-function error. When the closure only reads or freezes it (a JSX attribute or child, a template literal, `items + 1`, `items ? 1 : 2`), inference passes and PruneNonEscapingScopes is the first pass that needs the declaration. That one is an `.expect()`. Probes. Matrix 1 is 104 files: helper as arrow or function declaration, 13 helper bodies, the `let` reassigned in an `if`, in a loop, in a plain statement, or never. Matrix 2 is 15 files: function declaration reassigned after a closure calls it, destructured `let`, `let` in a nested block, two closures, a closure that reassigns, a closure in a closure, `useEffect`, an object method, `for`, `switch`, `try`, the self reference. For each file I compared the compile event and the list of `_c(n)` sizes with babel-plugin-react-compiler 1.0.0. | | equal to upstream | skipped (invariant) | abort | | --- | --- | --- | --- | | main (debug build of 6a92015) | 28 | 50 | 41 | | this branch | 119 | 0 | 0 | One of the 119 is a function declaration that names itself in JSX and is reassigned. Upstream skips it with `Todo: [PruneHoistedContexts] Rewrite hoisted function references`. This branch reports the same error. Main aborts. The fixture `hoisting-reassigned-let-declaration.js` has this shape with a bare `() => x`. It passes before and after: the port reached the same output without the declaration. Relation to #42378. That PR turns the `.expect()` at `prune_non_escaping_scopes.rs:195` into a per-function error. The two are independent. With only #42378 these functions are skipped and not memoized. With only this PR they compile. What the test checks. It bundles four functions with `--target=browser` through the CLI and runs the output against a fake `react/compiler-runtime` whose `c` records every cache size. Each function returns the right value (the closure sees the reassigned value) and allocates the cache size that upstream emits: 4, 3, 4, 6. Each of the four aborts 1.4.2 on its own. On a build that has only #42378 the test also fails, with `[]` in place of each size. ssr mode (`--target=bun`) compiled these before and still does. Suites run with the debug build: `test/bundler/transpiler/react-compiler.test.ts` (46 pass), `test/bundler/transpiler/react-compiler-fixtures.test.ts` (3293 pass, 320 skip). `cargo clippy -p bun_react_compiler` and `cargo fmt --check` are clean. </details> <!-- robobun:evidence:begin --> --- **[human-review]** gate passed · iteration 0 · 2 files touched <details><summary>fails on main (without fix)</summary> ```console ASAN without fix: 1 FAILED $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/transpiler/react-compiler.test.ts bun test v1.4.3 (6a92015) test/bundler/transpiler/react-compiler.test.ts: (pass) bundler > react-compiler/SimpleComponent [813.34ms] (pass) bundler > react-compiler/ComponentWithHooks [324.73ms] (pass) bundler > react-compiler/ObjectPatternRestInProps [395.04ms] (pass) bundler > react-compiler/UnderscoreAndDollarComponentTags [301.18ms] (pass) bundler > react-compiler/OutputModeDefaultsByTarget-Browser [183.68ms] (pass) bundler > react-compiler/OutputModeDefaultsByTarget-Bun [144.15ms] (pass) bundler > react-compiler/FullstackHtmlImportCompilesClientGraphInClientMode [452.98ms] (pass) bundler > react-compiler/OutputModeExplicitSsrOverridesTarget [178.42ms] (pass) bundler > react-compiler/OutputModeIgnoredWhenCompilerDisabled-Client [142.44ms] (pass) bundler > react-compiler/OutputModeIgnoredWhenCompilerDisabled-Ssr [136.16ms] (pass) bundler > react-compiler/BundledReactPreservesImportRefs [423.84ms] (pass) bundler > react-compiler/BundledCjsCompilerRuntimeSurvivesTreeShaking [518.09ms] ( ... (truncated) release without fix: 1 failed, 1 skipped bun test v1.4.3-canary.1 (402e05b) test/bundler/transpiler/react-compiler.test.ts: (pass) bundler > react-compiler/SimpleComponent [39.44ms] (pass) bundler > react-compiler/ComponentWithHooks [19.94ms] (pass) bundler > react-compiler/ObjectPatternRestInProps [14.48ms] (pass) bundler > react-compiler/UnderscoreAndDollarComponentTags [15.89ms] (pass) bundler > react-compiler/OutputModeDefaultsByTarget-Browser [16.02ms] (pass) bundler > react-compiler/OutputModeDefaultsByTarget-Bun [8.57ms] (pass) bundler > react-compiler/FullstackHtmlImportCompilesClientGraphInClientMode [20.83ms] (pass) bundler > react-compiler/OutputModeExplicitSsrOverridesTarget [6.15ms] (pass) bundler > react-compiler/OutputModeIgnoredWhenCompilerDisabled-Client [7.18ms] (pass) bundler > react-compiler/OutputModeIgnoredWhenCompilerDisabled-Ssr [14.42ms] (pass) bundler > react-compiler/BundledReactPreservesImportRefs [15.26ms] (pass) bundler > react-compiler/BundledCjsCompilerRuntimeSurvivesTreeShaking [55.56ms] (pass) bundler > react-compiler/RequireStringPreservesImportRecord [27.79ms] (pass) bundler > react-compiler/BranchBooleanFeatureFlagPreservesDCE [15.03ms] (pass) bundler > react-compile ... (truncated) ``` </details> <details><summary>passes on PR (with fix)</summary> ```console ASAN with fix: all passed $ BUN_DEBUG_QUIET_LOGS=1 bun scripts/build.ts --profile=debug --quiet test "--reporter=junit" "--reporter-outfile=/tmp/pr_gate.xml" test/bundler/transpiler/react-compiler.test.ts bun test v1.4.3 (6a92015) test/bundler/transpiler/react-compiler.test.ts: (pass) bundler > react-compiler/SimpleComponent [806.81ms] (pass) bundler > react-compiler/ComponentWithHooks [296.53ms] (pass) bundler > react-compiler/ObjectPatternRestInProps [300.84ms] (pass) bundler > react-compiler/UnderscoreAndDollarComponentTags [365.91ms] (pass) bundler > react-compiler/OutputModeDefaultsByTarget-Browser [274.89ms] (pass) bundler > react-compiler/OutputModeDefaultsByTarget-Bun [140.96ms] (pass) bundler > react-compiler/FullstackHtmlImportCompilesClientGraphInClientMode [401.46ms] (pass) bundler > react-compiler/OutputModeExplicitSsrOverridesTarget [126.19ms] (pass) bundler > react-compiler/OutputModeIgnoredWhenCompilerDisabled-Client [130.72ms] (pass) bundler > react-compiler/OutputModeIgnoredWhenCompilerDisabled-Ssr [131.59ms] (pass) bundler > react-compiler/BundledReactPreservesImportRefs [317.37ms] (pass) bundler > react-compiler/BundledCjsCompilerRuntimeSurvivesTreeShaking [518.86ms] ( ... (truncated) release with fix: 1 skipped $ bun scripts/build.ts --profile=release [configured] bun-profile → bun (stripped) in 793ms (unchanged) ninja: Entering directory `/workspace/bun/build/release' [0/4] cargo bun_runtime → libbun_runtime.a �[1m�[92m Compiling�[0m bun_react_compiler v0.0.0 (/workspace/bun/src/react_compiler) �[1m�[92m Compiling�[0m bun_js_parser v0.0.0 (/workspace/bun/src/js_parser) �[1m�[92m Compiling�[0m bun_resolver v0.0.0 (/workspace/bun/src/resolver) �[1m�[92m Compiling�[0m bun_ini v0.0.0 (/workspace/bun/src/ini) �[1m�[92m Compiling�[0m bun_bundler v0.0.0 (/workspace/bun/src/bundler) �[1m�[92m Compiling�[0m bun_router v0.0.0 (/workspace/bun/src/router) �[1m�[92m Compiling�[0m bun_standalone_graph v0.0.0 (/workspace/bun/src/standalone_graph) �[1m�[92m Compiling�[0m bun_transpiler v0.0.0 (/workspace/bun/src/transpiler) �[1m�[92m Compiling�[0m bun_bunfig v0.0.0 (/workspace/bun/src/bunfig) �[1m�[92m Compiling�[0m bun_install v0.0.0 (/workspace/bun/src/install) �[1m�[92m Compiling�[0m bun_jsc v0.0.0 (/workspace/bun/src/jsc) �[1m�[92m Compiling�[0m bun_js_parser_jsc v0.0.0 (/workspace/bun/src/js_parser_jsc) �[1m�[92m Compiling�[0m bun_sys_jsc v0.0.0 (/works ... (truncated) ``` </details> <details><summary>diff hotspot</summary> ``` src/react_compiler/lowering/build_hir/stmt.rs | 5 +- test/bundler/transpiler/react-compiler.test.ts | 88 ++++++++++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) ``` </details> **gate history** · 1 passed · 0 rejected · iteration 0 <details><summary>evidence per changed file</summary> ``` file reads edits tests src/react_compiler/lowering/build_hir/stmt.rs 2 2 20 test/bundler/transpiler/react-compiler.test.ts 2 4 19 ``` </details> <!-- robobun:evidence:end -->
Integrates the upstream React Compiler as a built-in transform:
bun build --react-compiler/Bun.build({ reactCompiler: true }).What this does
Runs React's auto-memoization compiler on component and hook functions during the build, with no Babel/SWC/OXC in the loop. Bun's parser already produces a fully resolved AST; this lowers it directly into the compiler's HIR, runs the upstream HIR passes, and emits Bun AST nodes back from codegen — no intermediate AST is allocated.
Performance
On a large React codebase (~860 compiled components, ~1400 memo slots):
reactCompiler: false)reactCompiler: trueFull native
--compilebuild: 3.62 s vs 13.04 s with the Babel plugin (3.6×).Architecture
src/react_compiler/is a single crate (~62k LOC) that ports the upstreamfacebook/reactcompiler/crates/Rust workspace:hir/,ssa/,inference/,typeinference/,optimization/,validation/,reactive_scopes/,diagnostics/,utils/) — byte-for-byte upstreamsrc/, only import paths rewritten andserde/serde_jsonderives stripped. Hot-path data structures densified:HashMap<SmallId, _>→Vec<_>,HashSet<ValueReason>→EnumSet(u16), points-to sets →SmallVec<[_; 4]>. TheIndexMap/IndexSetAPI is shimmed over arena-backedbun_collections::ArrayHashMap.lowering/,codegen.rs,pipeline.rs,program.rs,imports.rs) — upstream's Babel-shapedreact_compiler_astreads/writes replaced withbun_astreads/writes via the type-mapping table insrc/react_compiler/DESIGN.md.The compile hook fires inside
visit_stmts(FnBody), between its visit phase and its inline-mangle phase. Candidate detection (S::Function/S::Local/S::ExportDefault/S::Exprand per-decl invisit_decls) records the bindingRefandmemo/forwardRefwrapper bit;visit_func/ arrow-visit copy the function's args/flags/locs into aCopyPendingCompilestruct; the hook callsmaybe_compile_pending, which constructs a stack-localG::Fnand runsmaybe_compile_node. The compiled body lands in the livestmtsbuffer so the existing mangle phase runs on it; new args/flags flow back via a singleCompileResultfield. No raw pointers, no extra pass; the non-RC path adds oneis_some()check per top-level decl.// eslint-disable react-hooks/*suppressions are detected by the lexer (one substring check per comment, gated on the feature flag) and propagated as a flag bit onG::Fn/E::Arrow; the compiler skips functions carrying it.Dependencies
No new crates in the production build.
serde/serde_json/serde_derive/serde-transcode/hmac-sha256/indexmapare not pulled in (upstream uses them for the napi JSON bridge and HMR hashing, neither of which Bun needs). Binary size: +~1.0 MB.Re-syncing against upstream
scripts/sync-react-compiler.shsparse-fetchesfacebook/reactand prints a per-file diff betweensrc/react_compiler/UPSTREAM_PORTEDand upstream tip, grouped into whole-crate ports (apply mechanically) and AST-boundary ports (re-port via the type-mapping table).--fixturesre-syncs the test corpus.Tests
test/bundler/transpiler/react-compiler.test.ts—itBundledsnapshot cases (simple component, component with hooks, non-component left untouched, eslint suppression, forward-ref sibling fn, self-referencing const arrow, branch-boolean DCE).test/bundler/transpiler/react-compiler-fixtures.test.ts— runs all 1,807 upstream fixtures via a singleBun.build()call (~2.7s wall). 1647 pass / 160 skip / 0 fail.@debugIR-dump fixtures (genuinely unrunnable in Bun).@enable*/@validate*/@compilationMode/@panicThreshold/@outputModepragmas are read intoEnvironmentConfig(test builds only; gated onreactCompilerParseTestPragmas: true).New
Bun.build()optionsreactCompiler?: boolean— enable the pass.reactCompilerOutputMode?: "client" | "ssr"—"ssr"skips the memo cache (default derived fromtarget).treeShaking?: boolean— bypass the always-on tree-shake (previously hardcodedtrueoutside Bake dev mode).reactCompilerParseTestPragmas?: boolean— test-only; enables// @enableXconfig pragmas.https://claude.ai/code/session_01FShraojuNHfmfS8q2DLDZb