Skip to content

bundler: integrate React Compiler (Rust port) behind --react-compiler - #31785

Closed
robobun wants to merge 12 commits into
mainfrom
farm/7da26809/react-compiler-bundler
Closed

robobun wants to merge 12 commits into
mainfrom
farm/7da26809/react-compiler-bundler

Conversation

@robobun

@robobun robobun commented Jun 4, 2026 •

Copy link
Copy Markdown
Collaborator

Adds experimental React Compiler support to bun build — turn it on with one flag, no Babel plugin, no config files, nothing to install:

bun build ./app.tsx --react-compiler
await Bun.build({ entrypoints: ["./app.tsx"], reactCompiler: true });

This revives what #30519 attempted (closed — it depended on an oxc_react_compiler crate that doesn't exist), rebuilt on the real thing: the official Rust port of React Compiler from react/react#36173, whose PR description explicitly invites bundler integrations via its react_compiler_oxc adapter crate. Fixes #24356.

What it does

function Box({ label }) {
  const upper = label.toUpperCase();
  return <div>{upper}</div>;
}

compiles to the same output as babel-plugin-react-compiler:

import { c as _c } from "react/compiler-runtime";
function Box(t0) {
  const $ = _c(4);
  const { label } = t0;
  let t1;
  if ($[0] !== label) { t1 = label.toUpperCase(); $[0] = label; $[1] = t1; } else { t1 = $[1]; }
  ...
}

react/compiler-runtime ships with react ≥ 19, so the bundler resolves it from the app's existing react install. compilationMode: "infer" semantics (only components/hooks are compiled), "use no memo" honored, node_modules skipped, off by default.

How

  • Vendored dep (scripts/build/deps/react-compiler.ts): fetch-only dep pinned to the head of [compiler] Port React Compiler to Rust react/react#36173 (10 MB tarball), consumed as cargo path deps — the exact arrangement vendor/lolhtml already uses. One patch disables oxc_codegen's default sourcemap feature: the optional oxc_sourcemap declares crate-type = ["lib", "cdylib"], and the useless cdylib artifact fails to link under bun's static-relocation rustflags (same fix class as lolhtml's rlib-only patch).
  • src/react_compiler (bun_react_compiler): parses with oxc, runs the compiler, emits via oxc_codegen. The vendored AST converter still has 15 todo!() arms for exotic syntax (#field in obj, import x = require(...), export =, declare global, ...) — bun builds with panic = "abort", so a pre-scan visitor detects those constructs and falls back to the original source instead of aborting. Any parse error, semantic error, or compiler bailout also falls back — enabling the flag can never fail a build.
  • Bundler hook: ParseTask::run_with_source_code substitutes the compiled source right before Bun's parser runs, gated like react_fast_refresh. The flag plumbs through --react-compiler → BundlerOptions → BundleOptions and Bun.build({ reactCompiler }) → JSBundler::Config, mirroring react_fast_refresh at every site.
  • Fallout fix: the react crates pull serde_json into workspace subgraphs that never had it, and serde_json's impl PartialEq<Value> for u16/i32/... makes err.errno != E::EEXIST as _-style comparisons ambiguous (E0282). Fixed the nine latent sites (bun_install, node_fs incl. windows-cfg'd ones, win_watcher, dns options) to the canonical err.get_errno() == E::X idiom used everywhere else.

Verification

  • test/bundler/bundler_react_compiler.test.ts — 8 tests, all executing their bundles against a stubbed react/compiler-runtime: memoization is asserted behaviorally (component called twice with same props → jsx factory invoked once, identical element returned), via CLI and Bun.build; off-by-default; "use no memo"; node_modules skip; TSX; custom hooks; and the #field in obj panic-guard (without the pre-scan that input aborts the process).
  • USE_SYSTEM_BUN=1 → 4 failures (the feature-dependent tests); bun bd test → 8 pass.
  • bun run rust:check-all → 10/10 targets green (the windows-cfg'd errno sites cross-checked).
  • Neighboring coverage re-run: bundler_jsx 33 pass, node/fs/cp 43 pass, install smoke (fresh + re-install over existing node_modules) OK, bun-types integration 12 pass.

Rework in progress: dropping oxc (maintainer direction)

Per review: oxc (parser/AST/allocator) must not enter bun. The vendored compiler core (HIR/SSA/inference/reactive-scopes codegen) is already oxc-free — oxc only entered via the upstream react_compiler_oxc adapter used for parse/semantic/emit. The replacement is a bun-native adapter, operating on bun's own types post-parse in ParseTask (single parse, no source round-trip):

  1. Input conversion (bun_ast → compiler's Babel-like AST + ScopeInfo): bun's parser already resolves references (EIdentifier.ref_ → Symbol) and retains the scope tree (Ast.module_scope children + members), so ScopeInfo (scopes/bindings/refNodeIdToBinding/nodeIdToScope) is a direct mapping — no re-analysis. Node IDs are assigned during conversion. Bun nodes carry only start offsets; ends come from the per-node close-token locs (close_paren_loc, close_brace_loc, close_tag_loc, …) plus token lengths.
  2. JSX: bun's visit pass lowers JSX to jsx()/jsxs()/createElement() calls before the bundler AST exists (ECall.was_jsx_element), but the compiler's compilationMode: "infer" detection requires JSX nodes. The converter reconstructs JSXElement from was_jsx_element calls (automatic + classic runtimes are both mechanical inversions), and the output direction re-lowers compiler-emitted JSX to calls reusing the file's existing jsx import refs.
  3. Output conversion (compiled Babel AST → bun_ast): span-reuse — compiled output copies input subtrees with their original ranges intact, so any output node whose range matches a recorded input node is replaced by the still-live original bun node; only compiler-synthesized nodes (memo cache ops, guards — a bounded grammar from codegen_reactive_function) are structurally converted. Any mismatch → bail, original AST used unchanged.
  4. Runtime import: react/compiler-runtime is injected post-parse following the react-fast-refresh recipe (add_import_record → namespace symbol → named_imports → S::Import in a new Part with declared_symbols/symbol_uses satisfied for the linker).
  5. This sheds oxc_parser/oxc_semantic/oxc_codegen and both allocators from the binary (~1.5 MB of the size delta — see below), and removes the UnsupportedSyntaxScan/use-directive/hashbang pre-scan concerns entirely — the transform sees bun's AST after bun's parse.

Draft until the adapter lands; option plumbing, vendor/build wiring, CI bootstrap, allowlists, and the behavioral test suite carry over unchanged.

Binary size

Measured with isolated probe binaries built with bun's exact release profile shape (fat LTO, codegen-units = 1, panic = "abort", stripped — what the CI size check measures):

configuration machine code added
full stack, default opt-level = 3 (original) 7.2 MB
full stack, opt-level = "z" on the closure 3.8 MB
+ regex crate removed (patch 0003) — this PR now 3.5 MB
compiler core only (no oxc, AST built directly) — post-rework floor 2.7 MB

Where the bytes go (symbol-level attribution of the opt-z probe):

  • ~930 KB — the compiler passes themselves: reactive-scope analysis/codegen (213 KB), type+effect inference (153 KB), AST→HIR/SSA lowering (146 KB), orchestration (143 KB), HIR (126 KB), validation (70 KB), optimization (62 KB), …. It is a ~120K-line optimizing compiler; this part is proportional to what it does.
  • ~500 KB — serde codegen for the Babel-AST JSON bridge. Upstream's API round-trips the AST through JSON by design: RawValue passthrough subtrees are deserialized inside the pipeline and CompileResult returns the compiled AST as a pre-serialized JSON string, so the full-AST Serialize/Deserialize monomorphizations are reachable no matter how the AST is built. A typed (non-JSON) result API is the one remaining structural cut (~0.3–0.5 MB) and is noted for the rework.
  • ~280 KB — oxc frontend (parser/semantic/codegen + its miette/textwrap diagnostics chain) — removed by the bun-native rework.
  • ~190 KB — the Babel-like AST types (constructors, visitors, Clone).
  • ~600 KB — std/alloc/hashbrown monomorphization (HashMap/BTreeMap/Vec/fmt instantiated for the compiler's types) plus ~280 KB of rodata tables/strings.

Size levers applied so far: per-package opt-level = "z" for the exact 66-package closure this PR adds to cargo tree (verified against main — nothing else in bun uses them; the compiler only runs as a build-time bundler transform, and the minsize attributes survive the fat-LTO link), the regex crate patched out (its one pattern is a literal prefix/suffix match; −275 KB), oxc_codegen's sourcemap feature off, sha2 forced soft. The Nehalem baseline-instruction scan passes under the new codegen.

For scale: the JS implementation (babel-plugin-react-compiler) is ~3 MB of dist JavaScript that additionally assumes Babel at runtime; the statically-linked Rust port landing at ~2.7–3.5 MB is the honest cost of shipping the compiler inside the binary with nothing to install.

Known limitations (experimental)

  • Sourcemaps for compiled files map to the compiled intermediate, not the original lines (same property as plugin-rewritten sources). The React PR plans a patch-based API that would fix this properly.
  • The compiler itself is labeled WIP upstream ("all 1725 fixtures pass, but there may be lurking bugs") — hence the flag is opt-in and marked experimental everywhere.
  • Pinned to a commit on the PR branch; bumping is a one-line change in scripts/build/deps/react-compiler.ts.

@robobun
robobun requested a review from alii as a code owner June 4, 2026 01:29
@mintlify

mintlify Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
bun 🟢 Ready View Preview Jun 4, 2026, 1:31 AM

💡 Tip: Enable Workflows to automatically generate PRs for you.

@coderabbitai

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

Bun adds an experimental React Compiler integration: vendored Rust compiler crate, workspace and build wiring, a pre-parse compilation pass in the bundler that calls the new compile_source API, config/CLI/API flags to enable it, docs, and tests.

Changes

React Compiler Integration

Layer / File(s) Summary
Build infrastructure & vendored dependency
Cargo.toml, patches/react-compiler/*, scripts/build/bun.ts, scripts/build/deps/index.ts, scripts/build/deps/react-compiler.ts, .github/workflows/*, scripts/rust-miri.ts
Adds workspace member/dependency for src/react_compiler, fetches a pinned react-compiler archive, applies patches (disable oxc_codegen sourcemap, baseline-safe deps), and wires vendor stamps into Rust build orchestration and CI steps.
bun_react_compiler crate
src/react_compiler/Cargo.toml, src/react_compiler/lib.rs
New Rust crate exposing CompileOptions and pub fn compile_source(source, path, options) -> Option<String> that parses with oxc, scans for unsupported syntax, runs the vendored transform, and emits compiled source or skips.
Bundler pre-parse compilation & options
src/bundler/ParseTask.rs, src/options_types/context.rs, src/bundler/options.rs, src/bundler/Cargo.toml
Parse worker conditionally UTF‑8 decodes and calls bun_react_compiler::compile_source for eligible JS/TS files when react_compiler is enabled; new react_compiler option added and threaded into per-worker options.
CLI and API binding
src/runtime/cli/Arguments.rs, src/runtime/cli/build_command.rs, src/runtime/api/JSBundler.rs, src/runtime/api/js_bundle_completion_task.rs
Adds --react-compiler CLI flag and BuildConfig.reactCompiler/js_bundler::Config.react_compiler; parsed flag is propagated into bundler/transpiler options.
Docs, types, tests, and test harness
docs/snippets/cli/build.mdx, packages/bun-types/bun.d.ts, test/bundler/bundler_react_compiler.test.ts, test/bundler/expectBundled.ts
Docs and TypeScript types document the experimental reactCompiler option; tests and test plumbing validate memoization behavior, "use no memo", node_modules skipping, unsupported-syntax bailout, TypeScript support, custom hooks, and both CLI/API backends.
Baseline allowlists, runtime errno fixes, and CI scripts
scripts/verify-baseline-static/*, src/install/hoisted_install.rs, src/runtime/node/*, src/runtime/node/win_watcher.rs, .github/workflows/*, scripts/rust-miri.ts, CLAUDE.md
Updates baseline allowlists for memchr symbols pulled in by the new crate, standardizes errno checks via get_errno(), and updates CI/Miri/Clippy preparation to clone/verify vendor/react-compiler.

Possibly related PRs

  • oven-sh/bun#30876: Related work touching scripts/rust-miri.ts and Miri setup for vendored dependencies.

Suggested reviewers

  • alii
🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: integrating React Compiler support into the bundler with a CLI flag.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description check ✅ Passed The PR description is comprehensive and well-structured, covering what the feature does, how it works, verification steps, and known limitations.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions github-actions Bot added the claude label Jun 4, 2026
@robobun

robobun commented Jun 4, 2026 •

Copy link
Copy Markdown
Collaborator Author
Updated 1:30 AM PT - Jun 15th, 2026

❌ @robobun, your commit 0566517 has 5 failures in Build #62367 (All Failures):


🧪   To try this PR locally:

bunx bun-pr 31785

That installs a local version of the PR into your bun-31785 executable, so you can run:

bun-31785 --bun

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/react_compiler/Cargo.toml`:
- Around line 13-20: The CI fails because src/react_compiler/Cargo.toml declares
local path deps react_compiler, react_compiler_oxc and react_compiler_hir that
aren’t fetched/created in the “configure-only + raw cargo” jobs; fix by either
(A) making the react-compiler vendor stamp available before cargo runs (invoke
the existing vendor bootstrap used by emitRust — e.g. run the script that
creates vendor/react-compiler or run the full scripts/build.ts step or add the
ninja target that produces the .ref/fetched tree) so the
../../vendor/react-compiler path exists when cargo resolves dependencies, or (B)
prevent these crates from being resolved in those jobs by gating/removing
bun_react_compiler from the workspace for the clippy/miri workflows (exclude the
workspace member or mark them optional) so cargo clippy / cargo miri don’t try
to resolve the local path deps; target the changes around the
workspace/Cargo.toml inclusion and the clippy.yml / miri.yml job steps that
currently run bun scripts/build.ts --configure-only and ninja -C build/...
clone-lolhtml.

In `@test/bundler/bundler_react_compiler.test.ts`:
- Around line 42-68: The test currently iterates backends with a for loop inside
describe("bundler")—replace that loop with a parameterized describe.each(["cli",
"api"]) so each backend is a named sub-suite; move the existing itBundled(...)
invocation (the test using react-compiler: true, files, run, onAfterBundle and
runtimeStubs) into the callback for describe.each and use the backend parameter
instead of the loop variable so the matrix follows the repo convention; keep the
itBundled call and its options (reactCompiler, files, run, onAfterBundle)
unchanged except for using the describe.each-provided backend value.

In `@test/bundler/expectBundled.ts`:
- Around line 204-205: Add explicit validation to reject reactCompiler when
ESBUILD is active: in the option validation/normalization logic that checks
ESBUILD (the same place that validates bytecode/dotenv/throw/allowUnresolved),
detect if options.reactCompiler === true && ESBUILD is enabled and throw or
return a clear error. Also ensure the CLI/API paths stop forwarding
reactCompiler under ESBUILD by removing it from the BuildConfig construction and
the ESBUILD_PATH branch for backend === "cli" (so reactCompiler is only ever
added when !ESBUILD). Update tests/assertions to expect a rejection when
reactCompiler:true is supplied with ESBUILD enabled.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 20553995-9c15-4a33-a22c-a2ace9115fc7

📥 Commits

Reviewing files that changed from the base of the PR and between 59ec626 and fb270b0.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (23)
  • Cargo.toml
  • docs/snippets/cli/build.mdx
  • packages/bun-types/bun.d.ts
  • patches/react-compiler/0001-codegen-no-sourcemap.patch
  • scripts/build/bun.ts
  • scripts/build/deps/index.ts
  • scripts/build/deps/react-compiler.ts
  • src/bundler/Cargo.toml
  • src/bundler/ParseTask.rs
  • src/bundler/options.rs
  • src/install/hoisted_install.rs
  • src/options_types/context.rs
  • src/react_compiler/Cargo.toml
  • src/react_compiler/lib.rs
  • src/runtime/api/JSBundler.rs
  • src/runtime/api/js_bundle_completion_task.rs
  • src/runtime/cli/Arguments.rs
  • src/runtime/cli/build_command.rs
  • src/runtime/dns_jsc/options_jsc.rs
  • src/runtime/node/node_fs.rs
  • src/runtime/node/win_watcher.rs
  • test/bundler/bundler_react_compiler.test.ts
  • test/bundler/expectBundled.ts

Comment thread src/react_compiler/Cargo.toml Resolved
Comment thread test/bundler/expectBundled.ts Resolved
Comment thread src/react_compiler/Cargo.toml Resolved
Comment thread src/bundler/ParseTask.rs Resolved
Comment thread Cargo.toml Resolved
Comment thread src/bundler/ParseTask.rs Resolved
Comment thread src/bundler/ParseTask.rs Resolved

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All the issues I flagged earlier look addressed and I didn't find anything new on d7d5e97 — but given the scope here (vendoring a WIP upstream PR, ~40 new transitive crates, bundler parse-path hook, new user-facing experimental flag), this one's worth a human sign-off on the overall approach.

Extended reasoning...

Overview

This PR integrates the experimental Rust port of React Compiler (react/react#36173) into bun build behind --react-compiler / Bun.build({ reactCompiler }). It spans 31 files: a new vendored fetch-only dep (scripts/build/deps/react-compiler.ts) pinned to a commit on an upstream PR branch, two patch files, a new workspace crate bun_react_compiler wrapping oxc + the vendored compiler, a source-rewrite hook in ParseTask::run_with_source_code, option plumbing through CLI/API/types/docs, CI workflow updates (clippy/miri), baseline-static allowlist additions, ~40 new transitive crates in Cargo.lock (the entire oxc family + react_compiler_* + their deps), an 8-test bundler suite, and nine "fallout" errno-comparison fixes in unrelated crates (node_fs, win_watcher, hoisted_install, dns_jsc) caused by serde_json's PartialEq<Value> impls newly entering those subgraphs.

Security risks

No direct auth/crypto/permission surface. The vendored dep is fetched from a third-party fork (josephsavona/react) at a pinned commit via the existing github-archive source kind, same trust model as vendor/lolhtml. The feature is opt-in and off by default; on bailout/error the original source is used unchanged. The main risk class is correctness of compiled output (the upstream code is explicitly labeled WIP with todo!() arms — guarded by a pre-scan visitor, with a test) rather than security. The errno-comparison rewrites are semantically equivalent to the originals.

Level of scrutiny

High — human review warranted. This is not a mechanical change: it's a product decision to ship an experimental feature built on an unreleased upstream PR, a build-system decision to add a second vendored Rust path-dep with patches, and a non-trivial bundler hot-path modification. The Cargo.lock growth alone (~570 added lines, full oxc parser/semantic/codegen stack) is a meaningful dependency-surface expansion that a maintainer should consciously accept.

Other factors

I left three rounds of inline findings on earlier revisions (CI vendor bootstrap missing for clippy/miri; use_directive and target_from_hashbang reading post-rewrite bytes; runtime source not excluded from the gate; doc drift in Cargo.toml/CLAUDE.md). The author addressed every one in 27cf0f6 / 3135acb / d7d5e97 and all threads are resolved. The bug-hunting system found nothing new on the current head. Test coverage is reasonable (8 behavioral tests including the panic-guard case), and the PR description documents verification across rust:check-all and neighboring suites. Nothing blocks merge from a correctness standpoint that I can see — the deferral is purely about scope and design sign-off, not outstanding issues.

Comment thread src/react_compiler/Cargo.toml Resolved

@Jarred-Sumner Jarred-Sumner left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Do not pull in oxc. Do not pull in their ast. or allocator.

Use bun's types only.

@robobun

robobun commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

Understood — reworking to drop oxc entirely and use bun's types only.

The vendored compiler core (HIR/SSA/inference/reactive-scopes codegen) is oxc-free; oxc only entered through the react_compiler_oxc adapter I used for parse/semantic analysis/emit. The rework replaces that adapter with a bun-native one:

  • Input: bun's own parser output — bun_ast plus the parser's symbol/scope data — converted to the compiler's Babel-like AST + ScopeInfo (the same contract react_compiler_oxc/react_compiler_swc implement upstream).
  • Output: compiled functions spliced back through bun's types, printed by bun's printer. No second parser, no source-text round-trip, and the UnsupportedSyntaxScan/UseDirective/hashbang concerns disappear because the transform runs on bun's AST after bun's parse.
  • Size: sheds oxc_parser/oxc_semantic/oxc_codegen and both allocators from the binary.

That adapter is a few thousand lines of careful two-way conversion (upstream's oxc input converter alone is ~3k lines), so I'm converting this to a draft while I do it properly rather than rushing it. The option plumbing, vendor/build wiring, CI bootstrap, allowlists, and tests all carry over unchanged.

@robobun
robobun marked this pull request as draft June 4, 2026 05:31

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All my earlier inline concerns have been addressed and the bug hunter found nothing new — deferring to a human for the design-level calls (the ~5–7 MB/target binary-size cost and vendoring an unmerged WIP upstream PR branch into the bundler hot path).

Extended reasoning...

Overview

This PR integrates the experimental Rust port of React Compiler into bun build behind a --react-compiler flag / Bun.build({ reactCompiler }) option. It spans 31 files: a new bun_react_compiler workspace crate that wraps oxc + the vendored react_compiler_* crates as a source-to-source pre-parse pass in ParseTask.rs; build/CI plumbing (scripts/build/deps/react-compiler.ts, scripts/build/bun.ts, clippy/miri workflows, rust-miri.ts, baseline allowlists, two vendor patches); option threading through BundlerOptions/BundleOptions/JSBundler::Config/CLI; a fallout fix replacing nine err.errno != E::X as _ comparisons with the canonical err.get_errno() == E::X idiom (because serde_json now enters those crates' subgraphs and makes the as _ form ambiguous); docs/types; and an 8-test bundler suite that behaviorally verifies memoization.

Security risks

Low. The new code path is opt-in, off by default, and only transforms first-party source (skips node_modules, the bundler runtime, and non-file namespaces). The vendored dep is fetched from a pinned commit via the existing github-archive mechanism (same as lolhtml). No auth/crypto/permission surfaces are touched; the errno comparison rewrites are semantically equivalent. The main robustness concern — todo!() arms in the vendored converter aborting the process under panic = "abort" — is mitigated by a conservative pre-scan visitor that bails out (returns None) on those constructs, and there's a test exercising that path.

Level of scrutiny

This warrants a human reviewer despite the clean bug-hunt. It is large, touches the bundler's per-file parse hot path, adds ~50 transitive crates (the full oxc parser/semantic/codegen stack plus 14 react_compiler_* crates) to every release build, and carries an acknowledged ~5–7 MB binary-size increase per target that was waved through with [skip size check]. It also vendors code pinned to a commit on an unmerged upstream PR branch that the author themselves describes as WIP with "lurking bugs" and 15 todo!() arms. Those are product/maintenance tradeoffs (binary size vs. zero-install convenience; shipping against an unmerged upstream) that a maintainer should sign off on, not a bot.

Other factors

I've already left four rounds of inline feedback on this PR (CI vendor bootstrap, use_directive/hashbang scan ordering vs. the rewrite, runtime-source gate, doc drift, and a transient musl LTO failure) — every one was addressed in 27cf0f6 / 3135acb / d7d5e97, and the musl failure was disproven by a green retry on byte-identical code. All threads are resolved. The errno fallout changes look correct and idiomatic. Test coverage is reasonable for an experimental flag (CLI+API memoization, off-by-default, "use no memo", node_modules skip, TSX, custom hooks, panic-guard bailout). Nothing remains that I'd flag as a bug; the open question is purely whether the cost/benefit of shipping this is acceptable, which is a maintainer call.

@robobun

robobun commented Jun 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

Status as of 05665171 (current head — rebased onto main e0acad31, plus timeoutScale harness fix):

Binary size — CI-measured on the real release binaries (builds 60330/60338): +2.59 MB on bun-linux-x64 (+1.88–2.84 MB across 15 targets), down from +6.31 MB (−59%). Levers: opt-level = "z" on the react-compiler-exclusive package closure (re-verified against the rebased main's cargo tree — still exactly 63 packages) and patch 0003 removing regex. Symbol-level breakdown in the PR body. Head carries [skip size check] as the size tool prescribes for intentional increases (soft-fail: the step runs and annotates informationally).

CI on 05665171 (build 62367): every build lane green — both aarch64 build-rust agents timed out at 35 min on first attempt (# Received cancellation signal) and passed in 8 min on auto-retry. All 8 bundler_react_compiler tests pass on every lane; the two previously-skipped bundler tests this PR restores (edgecase/AwsCdkLib, plugin/ResolveManySegfault) pass everywhere. The remaining red (init.test.ts CLAUDE.md snapshot, fetch-abort-slow-connect.test.ts, valkey/connection-failures.test.ts) is pre-existing on this main base — concurrent builds 62350/62355/62360 (other PRs on e0acad31) carry identical annotations. Nothing in this diff reaches those paths; the feature is opt-in and off by default. The diff is green; needs a maintainer.

This head also fixes a latent expectBundled harness bug: timeoutScale was declared on BundlerTestInput but never destructured, so itBundled's dry-run silently dropped any test that set it (both existing users were being skipped). The react-compiler tests use timeoutScale: 3 following those precedents since each spawned build runs the full compiler pipeline.

This PR remains a draft pending the oxc-removal rework described in the body (maintainer direction: bun's types only). Option plumbing, vendor/build wiring, CI bootstrap, allowlists, behavioral tests, size-profile overrides, and vendor patches all carry over; the react_compiler_oxc frontend gets replaced with a bun-native AST/scope adapter (~0.8 MB more off the binary; measured floor 2.7 MB probe-side).

robobun and others added 11 commits June 15, 2026 06:34
Adds experimental React Compiler support to the bundler, wired as a
source-to-source pre-parse pass in ParseTask. Enable with
`bun build --react-compiler` or `Bun.build({ reactCompiler: true })` —
no Babel plugin or extra installs; compiled output imports
react/compiler-runtime (ships with react >= 19).

The compiler is the Rust port from react/react#36173, vendored at a
pinned commit via the lolhtml-style fetch-only dep
(scripts/build/deps/react-compiler.ts) and compiled into libbun_rust.a
as path deps of the new bun_react_compiler crate. The wrapper parses
with oxc, pre-scans for syntax the vendored AST converter cannot handle
yet (its todo!() arms would abort under panic=abort), runs the compiler
with compilationMode: infer / panicThreshold: none semantics, and falls
back to the original source on any bailout. node_modules files are
skipped, "use no memo" is honored.

A patch disables oxc_codegen's default sourcemap feature: the optional
oxc_sourcemap dep declares crate-type cdylib, which fails to link under
bun's static-relocation rustflags (same class of fix as lolhtml's
rlib-only patch).

The react crates pull serde_json into workspace subgraphs that never
had it, and serde_json's impl PartialEq<Value> for {u16,i32,...} makes
`errno != E::EEXIST as _`-style comparisons ambiguous. Fixed the nine
latent sites (bun_install, node_fs, win_watcher, dns options) to the
canonical `err.get_errno() == E::X` idiom.
cargo clippy/miri run cargo directly after a ninja bootstrap that only
cloned vendor/lolhtml; with bun_react_compiler's path deps pointing into
vendor/react-compiler, cargo failed to load the workspace. Add the
auto-generated clone-react-compiler phony target to both workflows.

Also reject reactCompiler under expectBundled's esbuild backend, like
other bun-only options.
The client/server boundary decision must come from the original source
bytes, not from whatever the vendored emitter produces — even though it
currently preserves the directive prologue ahead of its injected
react/compiler-runtime import, that's a formatting detail of WIP vendored
code and not a contract.

Also teach scripts/rust-miri.ts to clone vendor/react-compiler alongside
vendor/lolhtml before invoking cargo on a fresh checkout.
windows-x64-baseline-verify-baseline disassembles the binary and rejects
instructions beyond Nehalem. The vendored compiler stack introduced three
sources, confirmed by scanning a target-cpu=nehalem build of the same
dependency graph with verify-baseline-static:

- regex's default perf-literal feature pulls aho-corasick, whose Teddy
  searcher compiles AVX/AVX2 kernels (16 symbols). The compiler's only
  pattern is the dynamic-gating directive matcher, so patch 0002 trims
  regex to features=["std"].
- sha2 emits a CPUID-dispatched SHA-NI block function; it only HMACs
  short gating strings, so the same patch forces the software path.
- oxc's line counting instantiates memchr's count_raw::find_avx2 — the
  same is_x86_feature_detected! dispatch as the ten memchr entries
  already allowlisted — so it joins them in both x64 allowlists.

After the patch the probe scan reports zero violations.
- Exclude source_index 0 (bun's embedded runtime.js) from the React
  Compiler gate, matching every other non-JSX-gated decision in
  run_with_source_code. The runtime has no components, so this was only
  wasted parse work, but runtime correctness shouldn't lean on the
  vendored crate's bailout contract.
- Read the auto-target hashbang from the original bytes, same reasoning
  as the use-directive scan: byte-prefix decisions must not depend on
  the vendored emitter's output formatting.
- Mention vendor/react-compiler in the workspace-exclude comment and
  CLAUDE.md's vendored-dependency list.
Vendoring React Compiler (14 crates) plus the oxc parser/semantic/codegen
stack it builds on adds ~5-7 MB per target. That is the cost of shipping
the compiler inside the binary — the feature's whole premise is zero
install, zero config. The increase is a one-time vendoring cost, not a
leak; the vendored tree is already trimmed (sourcemap feature off,
regex std-only, sha2 software path).
Previous run failed only on bunx.test.ts (github-tarball tests, CI
egress rate limiting) and napi.test.ts flake — no overlap with this
diff; all build, verify-baseline, clippy, and miri lanes are green.
The React Compiler dependency closure (66 packages: the vendored
react_compiler crates, the oxc frontend, and their serde/regex/unicode
closure) contributes ~7 MB of machine code to the stripped release
binary at the workspace default opt-level=3. This code only runs as a
build-time bundler transform, never on a hot runtime path, so trade
speed for size: per-package opt-level="z" overrides cut the closure's
contribution roughly in half (7.2 MB -> 3.8 MB in an isolated probe
built with the same profile shape: fat LTO, codegen-units=1,
panic=abort, stripped).

Every package in the list is used exclusively by the React Compiler
stack -- the list is exactly the set of packages the dependency added
to cargo tree relative to main, so no other part of Bun loses
optimization. The minsize/optsize function attributes survive the
fat-LTO link, and the Nehalem baseline-instruction scan still passes
under the new codegen (0 violations).
The compiler's only regex is the dynamic-gating directive pattern
`^use memo if\(([^\)]*)\)$` — a literal prefix/suffix match. Patch the
vendored crate to express it with strip_prefix/strip_suffix (behavioral
equivalence: the body must be `)`-free, everything else is literal) and
remove the regex dependency, which drops regex, regex-automata and
regex-syntax from the build graph entirely: ~275 KB of machine code and
tables in an isolated release-profile probe, on top of the opt-level=z
override (which also loses its three regex entries here).

Patch 0002 previously trimmed regex to std-only for the baseline builds;
that hunk is subsumed by removing the dependency, so 0002 now carries
only the sha2 force-soft hunk. The Nehalem baseline-instruction scan
still passes (0 violations).
CI size check on the previous head measured the React Compiler stack at
+2.59 MB on bun-linux-x64 (+1.88-2.84 MB across all 15 release targets),
down from +6.31 MB before the opt-level=z overrides and the vendored
regex removal -- a 59% reduction in the real fat-LTO binaries, slightly
better than the isolated probe predicted. Update the Cargo.toml profile
comment with the measured numbers.

The remaining delta is the feature itself (the compiler passes plus
upstream's serde AST bridge, breakdown in the PR description), so it
cannot fit the size check's 0.50 MB threshold; tag the commit as the
check prescribes for intentional increases.
@robobun
robobun force-pushed the farm/7da26809/react-compiler-bundler branch from 9f92059 to 089fae9 Compare June 15, 2026 06:41
…compiler tests

expectBundled destructures every known BundlerTestInput field and throws
on anything left in unknownProps. itBundled's registration-time dry-run
swallows that throw and returns without registering the test, so any
test that set timeoutScale was being silently dropped -- the two
existing users (edgecase/AwsCdkLib and plugin/ResolveManySegfault) never
ran under a release binary. Destructure it (unused in the body; it's
consumed by itBundled's test registration).

Give the react-compiler tests timeoutScale: 3 following those two
precedents: each test spawns a build that runs the full compiler
pipeline, so the 5s local-release default is too tight under the
residual pressure of a just-finished release build. CI sets its own
timeouts and ignores this.

[skip size check]
@Jarred-Sumner

Copy link
Copy Markdown
Collaborator

Closing in favor of #32504

This branch was successfully deployed

1 active deployment
staging - docs — 05665171 Deployed Jun 15, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support React Compiler w/ Bun's built-in bundler

2 participants