Objlab
← News
Linguaggi e compilatori

Portare il compilatore React su Rust

Sintesi redazionale: URL dell'articolo: https://github.com/react/react/pull/36173 URL dei commenti: https://news.ycombinator.com/item?id=48473662 Punti: 49 # Commenti: 28. Fonte originale: https://github.com/react/react/pull/36173

<p># [compiler] Port React Compiler to Rust#36173</p><p>Merged</p><p>Merged</p><p>## Conversation</p><p>30 commits<br>March 21, 2026 11:17</p><p>added …s in reactive printer Add HirFunctionFormatter callback to reactive DebugPrinter so FunctionExpression and ObjectMethod values can print their inner HIR functions with full detail. Bridge debug_print.rs formatting into the reactive printer via format_hir_function_into.</p><p>Remove blank line output for unprinted outlined functions that caused Environment section misalignment. 1285/1717 fixtures now pass.</p><p>…unction value blocks Port the TS logic that converts StoreLocal to LoadLocal when the last instruction of a value block stores to an unnamed temporary. This fixes identifier/place mismatches in the reactive function output. 1459/1717 fixtures now pass.</p><p>In BuildReactiveFunction, for-loops should use the update block as the continue target when present, falling back to the test block. Matches TS terminal.update ?? terminal.test pattern.</p><p>BuildReactiveFunction is implemented with 1458/1717 fixtures passing (85%).</p><p>Major fixes to match the TypeScript BuildReactiveFunction behavior: - Add valueBlockResultToSequence for for/for-of/for-in init and for-of test values, which wraps value block results in SequenceExpressions with proper lvalue assignment - Fix for-of continue_block to use init (not test), matching TS scheduleLoop call - Add reachable() checks for if, switch, while, and label terminal fallthroughs - Add loopId checks for all loop types (do-while, while, for, for-of, for-in) to verify loop blocks aren&#x27;t already scheduled before traversal - Add alternate != fallthrough check for if terminals (matching TS branch semantics) - Fix switch case processing order to reverse (matching TS reverse-iterate-then-reverse) - Fix switch to skip already-scheduled cases instead of pushing None blocks - Fix value block catch-all to not propagate parent fallthrough (TS passes null) - Clean up dead code in value block catch-all Pass rate: 1635/1717 (95.2%). Remaining 82 failures are all earlier-pass issues.</p><p>Ported 15 reactive passes and visitor/transform infrastructure from TypeScript to Rust. Includes assertWellFormedBreakTargets, pruneUnusedLabels, assertScopeInstructionsWithinScopes, pruneNonEscapingScopes, pruneNonReactiveDependencies, pruneUnusedScopes, mergeReactiveScopesThatInvalidateTogether, pruneAlwaysInvalidatingScopes, propagateEarlyReturns, pruneUnusedLValues, promoteUsedTemporaries, extractScopeDeclarationsFromDestructuring, stabilizeBlockIds, renameVariables, and pruneHoistedContexts. 1603/1717 tests passing (93.4%).</p><p>…-port.ts The .replace(/\(generated\)/g, &#x27;(none)&#x27;) normalization was effectively a no-op: both TS and Rust event items go through the same formatLoc in the test harness, producing identical (generated) strings. The HIR debug printers output &quot;generated&quot; without parentheses, so the regex never matched HIR output either.</p><p>Reorder the 4 create_temporary_place_id calls in apply_early_return_to_scope to match the TypeScript allocation order (sentinelTemp first, then symbolTemp, forTemp, argTemp). The Rust port had them in a different order, causing IdentifierIds to be assigned differently and producing 33 test divergences in PropagateEarlyReturns output.</p><p>…S behavior In TypeScript, `buildReverseGraph` (Dominator.ts:237) calls `fn.env.nextBlockId` to create a synthetic exit node, which increments the block ID counter as a side-effect. The Rust port reads `env.next_block_id_counter` without incrementing. This causes block ID offsets: for a simple function, TS allocates 3 extra block IDs (one each from ValidateHooksUsage, ValidateNoSetStateInRender, and InferReactivePlaces) that Rust doesn&#x27;t, causing all subsequent block IDs to differ by 3. Fix by changing the 3 callers to use `env.next_block_id().0` instead of `env.next_block_id_counter`, consuming the ID to match TS behavior. This reduces block ID divergences from ~1505 to ~117 fixtures (remaining divergences are from recursive dominator calls within inner function validation).</p><p>…ew docs Aggregate top issues from ~95 per-file reviews into 20260321-summary.md. Key findings: ~55 panic!() calls that should be Err(...), type inference logic bugs, severely compressed validation passes, weakened SSA invariants, and JS semantics divergences in ConstantPropagation. Removes stale aggregated summary docs (SUMMARY.md, README.md, etc.) while keeping per-file reviews.</p><p>…re guidelines Corrected several recommendations that were inconsistent with rust-port-architecture.md: removed &quot;at minimum panic!()&quot; as acceptable for invariants (must be Err), marked tryRecord as unnecessary in Rust since Result handles the concern more cleanly, fixed incorrect claim that obj.class is invalid JS, and clarified that invariant violations must propagate via Err rather than accumulate on env.</p><p>…eps, names scope, unify shapes, phi/cycle errors Fix 5 bugs in InferTypes: - 2a: Resolve types for captured context variables in apply phase (FunctionExpression/ObjectMethod) - 2b: Resolve types for StartMemoize deps with NamedLocal kind - 2d: Merge unify/unify_with_shapes so shapes are always available for property resolution - 3a: Return Err(CompilerDiagnostic) for empty phi operands and cycle detection instead of silent return Also updated pipeline.rs to handle the new Result return type. Note: Bug 2c (shared names map) was already correct — inner functions use a fresh HashMap.</p><p>…on-null assertion Changed unwrap_or(0) to .expect() for unsealed_preds lookup. TS uses a non-null assertion (!) which maps to unwrap/panic per the architecture guide. Silently defaulting to 0 could produce incorrect SSA IDs.</p><p>…ThatInvalidateTogether Changed &#x27;while index &lt;= entry.to.saturating_sub(1)&#x27; to &#x27;while index &lt; entry.to&#x27; to match TS semantics. The old code would incorrectly process index 0 when entry.to was 0 (saturating_sub(1) returns 0, and 0 &lt;= 0 is true).</p><p>…and number formatting - Added &#x27;delete&#x27; and &#x27;await&#x27; to is_reserved_word (6a) - Changed integer overflow guard from n.abs() &lt; 1e20 to n.abs() &lt; (i64::MAX as f64) to prevent potential issues with large integers near the threshold (6c) - js_to_number already handles empty/whitespace strings correctly (6b was already fixed)</p><p>…ompilationMode and PanicThreshold Created CompilationMode (Infer/Annotation/All) and PanicThreshold (AllErrors/CriticalErrors/None) enums with serde support. Updated all string comparisons in program.rs to use enum pattern matching.</p><p>…al correspondence with TS</p><p>…reassigned for structural correspondence</p><p>…tch TS non-null assertion&quot; This reverts commite3c80a2.</p><p>…ms for CompilationMode and PanicThreshold&quot; This reverts commit88bf21f.</p><p>Mark completed items (2a-2d, 3a, 5b, 6a-6c, 7a-7c), note reverted items (5c plugin enums broke serde, 8b enter_ssa fallback was correct), and update remaining work items with findings from implementation.</p><p>… and consolidate pipeline error handling Converted all CompilerError.invariant() and CompilerError.throwTodo() panics to Err(CompilerDiagnostic) returns across 29 files, matching the architecture guide. Added From&lt;CompilerDiagnostic&gt; for CompilerError impl to enable clean ? propagation, replacing 17 verbose .map_err() blocks in pipeline.rs. Restored weakened SSA invariant checks in rewrite_instruction_kinds_based_on_reassignment.rs.</p><p>…flatten(), convert remaining assert! calls Replaced .ok().flatten() with ? in callers that return Result to properly propagate invariant errors from environment shape resolution. Converted 10 remaining assert!/assert_eq! calls in build_reactive_function.rs to Err(CompilerDiagnostic) returns. Simplified lower_expression&#x27;s function lowering to use .expect() since the error path is unreachable.</p><p>… Compiler Copies the full react_compiler_oxc crate. Includes OXC 0.121 AST conversion, reverse conversion, scope handling, prefilter, and diagnostics.</p><p>… Compiler Copies the full react_compiler_swc crate. Includes SWC AST conversion, reverse conversion, scope handling, prefilter, diagnostics, and integration tests.</p><p>Copies codegen_reactive_function.rs (~2800 lines) from the prior working branch. Converts ReactiveFunction tree back into Babel-compatible AST with memoization (useMemoCache) wired in. Includes pruneHoistedContexts fix for inner functions.</p><p>Connects codegen_reactive_function to the compilation pipeline: - Added codegen module and pub use to reactive_scopes lib.rs - Added react_compiler_ast dependency to reactive_scopes Cargo.toml - Updated pipeline.rs to call codegen_function after PruneHoistedContexts - Mapped codegen results (memo stats, outlined functions) to CodegenFunction - Fixed build_reactive_function calls to handle Result return type</p><p>Extend the Rust port test script to capture and compare the final JavaScript code produced by each compiler&#x27;s Babel plugin, in addition to the existing debug log entry comparison. The code is formatted with prettier before diffing. Results are reported separately with their own pass/fail counts and diff output.</p><p>Add react_compiler_e2e_cli binary crate for testing SWC and OXC frontends via stdin/stdout, codegen helpers (emit functions) to both react_compiler_swc and react_compiler_oxc, and a test-e2e.ts orchestrator that compares output from all 3 Rust frontends (Babel/NAPI, SWC, OXC) against the TS baseline.</p><p>**mvitousek**approved these changes</p><p>###<br>**<br>mvitousek<br>**<br>left a comment</p><p>**mvitousek**left a comment</p><p>Contributor</p><p>There was a problem hiding this comment.</p><p>Sending it! Fixing forward the lone surrogate issue</p><p>**mofeiZ**approved these changes</p><p>|<br>Can you publish the crates to the crates.io? |</p><p>|<br>+1 While Cargo supports git dependencies, crates that depend on git sources cannot themselves be published to crates.io. Projects like Oxc work around this by maintaining and publishing forked crates, so having the React team officially publish and version these crates would make adoption much easier. |</p><p>|<br>cool |</p><p>This was referenced Jun 10, 2026</p><p>4 tasks</p><p>kdy1<br>added a commit<br>to swc-project/swc<br>that referenced<br>this pull request<br>Jun 15, 2026</p><p>**Description:** Add experimental SWC support for the Rust React Compiler from react/react#36173. This adds the `swc_ecma_react_compiler` bridge, SWC &lt;-&gt; React Compiler AST/scope conversion, `.swcrc` `jsc.transform.reactCompiler` configuration, diagnostics forwarding, JS/WASM option types, and tests ported from the upstream SWC integration. **TODO:** - Wait for the React Compiler Rust crates to be published, then replace the temporary git dependencies with published crate versions. **Related issue:** - react/react#36173 --------- Co-authored-by: DongYun Kang &lt;kdy.1997.dev@gmail.com&gt;</p><p>robobun<br>added a commit<br>to oven-sh/bun<br>that referenced<br>this pull request<br>Jun 15, 2026</p><p>_(testo troncato)_</p>