Repository navigation
Conversation
|
Preview deployment for your docs. Learn more about Mintlify Previews.
💡 Tip: Enable Workflows to automatically generate PRs for you. |
WalkthroughBun 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. ChangesReact Compiler Integration
Possibly related PRs
Suggested reviewers
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
|
Updated 1:30 AM PT - Jun 15th, 2026
❌ @robobun, your commit 0566517 has 5 failures in
Add 🧪 To try this PR locally: bunx bun-pr 31785That installs a local version of the PR into your bun-31785 --bun |
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (1)
Cargo.lockis excluded by!**/*.lock
📒 Files selected for processing (23)
Cargo.tomldocs/snippets/cli/build.mdxpackages/bun-types/bun.d.tspatches/react-compiler/0001-codegen-no-sourcemap.patchscripts/build/bun.tsscripts/build/deps/index.tsscripts/build/deps/react-compiler.tssrc/bundler/Cargo.tomlsrc/bundler/ParseTask.rssrc/bundler/options.rssrc/install/hoisted_install.rssrc/options_types/context.rssrc/react_compiler/Cargo.tomlsrc/react_compiler/lib.rssrc/runtime/api/JSBundler.rssrc/runtime/api/js_bundle_completion_task.rssrc/runtime/cli/Arguments.rssrc/runtime/cli/build_command.rssrc/runtime/dns_jsc/options_jsc.rssrc/runtime/node/node_fs.rssrc/runtime/node/win_watcher.rstest/bundler/bundler_react_compiler.test.tstest/bundler/expectBundled.ts
There was a problem hiding this comment.
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.
Jarred-Sumner
left a comment
There was a problem hiding this comment.
Do not pull in oxc. Do not pull in their ast. or allocator.
Use bun's types only.
|
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
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. |
There was a problem hiding this comment.
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.
|
Status as of 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: CI on This head also fixes a latent 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 |
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.
9f92059 to
089fae9
Compare
…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]
2681f99 to
0566517
Compare
|
Closing in favor of #32504 |
Adds experimental React Compiler support to
bun build— turn it on with one flag, no Babel plugin, no config files, nothing to install:This revives what #30519 attempted (closed — it depended on an
oxc_react_compilercrate 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 itsreact_compiler_oxcadapter crate. Fixes #24356.What it does
compiles to the same output as
babel-plugin-react-compiler:react/compiler-runtimeships 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_modulesskipped, off by default.How
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 arrangementvendor/lolhtmlalready uses. One patch disablesoxc_codegen's defaultsourcemapfeature: the optionaloxc_sourcemapdeclarescrate-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 viaoxc_codegen. The vendored AST converter still has 15todo!()arms for exotic syntax (#field in obj,import x = require(...),export =,declare global, ...) — bun builds withpanic = "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.ParseTask::run_with_source_codesubstitutes the compiled source right before Bun's parser runs, gated likereact_fast_refresh. The flag plumbs through--react-compiler→BundlerOptions→BundleOptionsandBun.build({ reactCompiler })→JSBundler::Config, mirroringreact_fast_refreshat every site.serde_jsoninto workspace subgraphs that never had it, and serde_json'simpl PartialEq<Value> for u16/i32/...makeserr.errno != E::EEXIST as _-style comparisons ambiguous (E0282). Fixed the nine latent sites (bun_install,node_fsincl. windows-cfg'd ones,win_watcher, dns options) to the canonicalerr.get_errno() == E::Xidiom used everywhere else.Verification
test/bundler/bundler_react_compiler.test.ts— 8 tests, all executing their bundles against a stubbedreact/compiler-runtime: memoization is asserted behaviorally (component called twice with same props → jsx factory invoked once, identical element returned), via CLI andBun.build; off-by-default;"use no memo";node_modulesskip; TSX; custom hooks; and the#field in objpanic-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).bundler_jsx33 pass,node/fs/cp43 pass, install smoke (fresh + re-install over existingnode_modules) OK,bun-typesintegration 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_oxcadapter used for parse/semantic/emit. The replacement is a bun-native adapter, operating on bun's own types post-parse inParseTask(single parse, no source round-trip):bun_ast→ compiler's Babel-like AST +ScopeInfo): bun's parser already resolves references (EIdentifier.ref_→Symbol) and retains the scope tree (Ast.module_scopechildren + members), soScopeInfo(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.jsx()/jsxs()/createElement()calls before the bundler AST exists (ECall.was_jsx_element), but the compiler'scompilationMode: "infer"detection requires JSX nodes. The converter reconstructsJSXElementfromwas_jsx_elementcalls (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.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 fromcodegen_reactive_function) are structurally converted. Any mismatch → bail, original AST used unchanged.react/compiler-runtimeis injected post-parse following the react-fast-refresh recipe (add_import_record→ namespace symbol →named_imports→S::Importin a newPartwithdeclared_symbols/symbol_usessatisfied for the linker).oxc_parser/oxc_semantic/oxc_codegenand both allocators from the binary (~1.5 MB of the size delta — see below), and removes theUnsupportedSyntaxScan/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):opt-level = 3(original)opt-level = "z"on the closureWhere the bytes go (symbol-level attribution of the opt-z probe):
RawValuepassthrough subtrees are deserialized inside the pipeline andCompileResultreturns the compiled AST as a pre-serialized JSON string, so the full-ASTSerialize/Deserializemonomorphizations 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.Size levers applied so far: per-package
opt-level = "z"for the exact 66-package closure this PR adds tocargo tree(verified against main — nothing else in bun uses them; the compiler only runs as a build-time bundler transform, and theminsizeattributes 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)
scripts/build/deps/react-compiler.ts.