This is an experimental, work-in-progress port of React Compiler to Rust. Key points: * Work-in-progress - we are sharing early, prior to testing internally at Meta, to get feedback from partners in parallel with continued development. * No builds available yet, you'll have to do some hacking if you want to try this. * All fixtures pass, no known gaps but there may be lurking bugs. * The architecture was heavily guided by humans (me, @josephsavona) but majority coded by AI. I was very hands-on in setting the architecture, the testing and verification strategy, incremental migration approach, etc. I also kept a close eye on the code and spent a decent amount of time going back and forth to get code quality to a decent level. * The public API is basically "Rust Babel AST" + Scope Info in, Rust Babel AST out. We use a Rust representation of the Babel AST as our "public API", as it were, and then each integration (Babel, OXC, SWC) converts to/from their native representation. For now integrations must also provide scope information - in the future React Compiler may compute bindings and references itself from the AST. * Internally, the Rust version uses the same architecture as the TypeScript version. The compiler converts from the AST into our own intermediate representation (HIR, short for High-level Intermediate Representation) which uses a control-flow graph (CFG) and single-static assignment (SSA). We go through the same series of passes, with the same overall algorithms. It's very much a pass-by-pass port. The main differences are in the data representation - using arena-like structures (and indices into these arenas) to work within Rust's borrowing system. * Early performance numbers are derived from AI and i haven't spent much time validating the benchmark setup, beyond the fact that the optimization opportunities it discovered made complete sense and the fixes were right. With that caveat, itt does appear that the Rust version is quite fast already: 3x faster when operating as a Babel plugin. The serialization cost is quite high, but the actual transformation logic is ~10x faster, so it's net faster. Native integrations (oxc, swc) should be even faster. * There are 3 integrations right now: an alternative Babel plugin (which will eventually get removed as we integrate into babel-plugin-react-compiler), and examples of what OXC and SWC integrations could look like (see react_compiler_oxc and react_compiler_swc crates). correctness: * all 1725 fixtures pass in snap when comparing the temporary rust version of the plugin with the main version. this compares generated code output as well as errors. * all fixtures also pass a full comparison of the per-pass compiler intermediate representation — the intermediate state (including log events and errors) are ~identical after every single pass (modulo some normalization of ids) * The OXC and SWC example integrations seem to be working well, though i haven't manually verified this to the same extent as i have the Babel integration. development: * `yarn snap --rust` is the primary test suite, testing that we error or compile as expected. It does not test the inner state of the compiler along the way, though, making it less suitable for finding subtle logic gaps btw the TS and Rust versions. It's also Babel based, making it less easy to test OXC and SWC integrations. * `compiler/scripts/test-e2e.sh` is an e2e test of all 3 variants (babel wrapper around Rust, OXC/SWC integrations) against the TS implementation. This does a partial comparison, focused on final output code only (doesn't test error details etc). Useful for getting the swc and oxc integrations closer to parity. * `compiler/script/test-rust-port.sh` does detailed testing of the internal compiler state after each pass, in addition to checking the final output code. This is the key script used to port the compiler, ensuring not just that the output was the same but that each pass was capturing all the same detail. This script can be pointed at *any* directory of JS files, which we expect to use for internal testing at Meta. ## For Partners We're excited to partner with teams to integrate the Rust version of React Compiler into other tools, like OXC and SWC. If you're interested in working with us on this, the best place to start is by taking a look at the react_compiler_swc and react_compiler_oxc crates. These give you an idea of the API shape that we're thinking of. Note that the conversion from any AST into our HIR is complex, and we can only maintain one version. Hence we've aligned on using a Babel-like AST as our public API. Another key point is that we don't yet implement our own scope analysis (since the TS version of the compiler relied on Babel's scope analysis), so for now we require that the scope data be serialized. It's a denormalized graph, and some metadata has to be stored to associate nodes with scopes. We're open to feedback about the AST and scope representation - we iterated a bit just to get things to work, but it can be more optimal. Key changes that we are considering: * Currently the compiler returns `Option<Program>`, which is `Some` if anything changed. This requires replacing the entire program. We plan to change this to return a series of patches to apply, in a form that is reasonably usable and efficient for all the integrations we care about (Babel, OXC, SWC, etc). * The Rust representation of the Babel AST is fine enough, but we could make it more optimal by doing arena allocation. We also plan to change the string representation to smol_str. * The scope representation, and association of data btw AST and scope, is very much a first pass approach that is good enough. We expect to implement our own scope resolution, though, so we hopefully won't need to iterate on the scope representation and can just throw it away. In terms of the shape of the integration, we anticipate that each integration would have the following: * Implementor repo (OXC, SWC, etc): lightweight code transform and lint pipeline integration that delegates to `crates/react_compiler_<name>` from our repo * Our repo: one crate per implementor, eg react_compiler_swc, react_compiler_oxc, where most of the logic lives. This setup lets us make changes to the integration layer easily within our repo. Feedback appreciated! --------- Co-authored-by: Joe Savona <[email protected]> Co-authored-by: Mike Vitousek <[email protected]> Co-authored-by: Mike Vitousek <[email protected]> Co-authored-by: lauren <[email protected]> Co-authored-by: lauren <[email protected]>
10 KiB
React Compiler Knowledge Base
This document contains knowledge about the React Compiler gathered during development sessions. It serves as a reference for understanding the codebase architecture and key concepts.
Project Structure
When modifying the compiler, you MUST read the documentation about that pass in compiler/packages/babel-plugin-react-compiler/docs/passes/ to learn more about the role of that pass within the compiler.
packages/babel-plugin-react-compiler/- Main compiler packagesrc/HIR/- High-level Intermediate Representation types and utilitiessrc/Inference/- Effect inference passes (aliasing, mutation, etc.)src/Validation/- Validation passes that check for errorssrc/Entrypoint/Pipeline.ts- Main compilation pipeline with pass orderingsrc/__tests__/fixtures/compiler/- Test fixtureserror.todo-*.js- Unsupported feature, correctly throws Todo error (graceful bailout)error.bug-*.js- Known bug, throws wrong error type or incorrect behavior*.expect.md- Expected output for each fixture
Running Tests
# Run all tests
yarn snap
# Run tests matching a pattern
# Example: yarn snap -p 'error.*'
yarn snap -p <pattern>
# Run a single fixture in debug mode. Use the path relative to the __tests__/fixtures/compiler directory
# For each step of compilation, outputs the step name and state of the compiled program
# Example: yarn snap -p simple.js -d
yarn snap -p <file-basename> -d
# Update fixture outputs (also works with -p)
yarn snap -u
Linting
# Run lint on the compiler source
yarn workspace babel-plugin-react-compiler lint
Formatting
# Run prettier on all files (from the react root directory, not compiler/)
yarn prettier-all
Compiling Arbitrary Files
Use yarn snap compile to compile any file (not just fixtures) with the React Compiler:
# Compile a file and see the output
yarn snap compile <path>
# Compile with debug logging to see the state after each compiler pass
# This is an alternative to `yarn snap -d -p <pattern>` when you don't have a fixture file yet
yarn snap compile --debug <path>
Minimizing Test Cases
Use yarn snap minimize to automatically reduce a failing test case to its minimal reproduction:
# Minimize a file that causes a compiler error
yarn snap minimize <path>
# Minimize and update the file in-place with the minimized version
yarn snap minimize --update <path>
Version Control
This repository uses Sapling (sl) for version control. Sapling is similar to Mercurial: there is not staging area, but new/deleted files must be explicitly added/removed.
# Check status
sl status
# Add new files, remove deleted files
sl addremove
# Commit all changes
sl commit -m "Your commit message"
# Commit with multi-line message using heredoc
sl commit -m "$(cat <<'EOF'
Summary line
Detailed description here
EOF
)"
Key Concepts
HIR (High-level Intermediate Representation)
The compiler converts source code to HIR for analysis. Key types in src/HIR/HIR.ts:
-
HIRFunction - A function being compiled
body.blocks- Map of BasicBlockscontext- Captured variables from outer scopeparams- Function parametersreturns- The function's return placealiasingEffects- Effects that describe the function's behavior when called
-
Instruction - A single operation
lvalue- The place being assigned tovalue- The instruction kind (CallExpression, FunctionExpression, LoadLocal, etc.)effects- Array of AliasingEffects for this instruction
-
Terminal - Block terminators (return, branch, etc.)
effects- Array of AliasingEffects
-
Place - A reference to a value
identifier.id- Unique IdentifierId
-
Phi nodes - Join points for values from different control flow paths
- Located at
block.phis phi.place- The result placephi.operands- Map of predecessor block to source place
- Located at
AliasingEffects System
Effects describe data flow and operations. Defined in src/Inference/AliasingEffects.ts:
Data Flow Effects:
Impure- Marks a place as containing an impure value (e.g., Date.now() result, ref.current)Capture a -> b- Value fromais captured intob(mutable capture)Alias a -> b-baliasesaImmutableCapture a -> b- Immutable capture (like Capture but read-only)Assign a -> b- Direct assignmentMaybeAlias a -> b- Possible aliasingCreateFrom a -> b- Created from source
Mutation Effects:
Mutate value- Value is mutatedMutateTransitive value- Value and transitive captures are mutatedMutateConditionally value- May mutateMutateTransitiveConditionally value- May mutate transitively
Other Effects:
Render place- Place is used in render context (JSX props, component return)Freeze place- Place is frozen (made immutable)Create place- New value createdCreateFunction- Function expression created, includescapturesarrayApply- Function application with receiver, function, args, and result
Hook Aliasing Signatures
Located in src/HIR/Globals.ts, hooks can define custom aliasing signatures to control how data flows through them.
Structure:
aliasing: {
receiver: '@receiver', // The hook function itself
params: ['@param0'], // Named positional parameters
rest: '@rest', // Rest parameters (or null)
returns: '@returns', // Return value
temporaries: [], // Temporary values during execution
effects: [ // Array of effects to apply when hook is called
{kind: 'Freeze', value: '@param0', reason: ValueReason.HookCaptured},
{kind: 'Assign', from: '@param0', into: '@returns'},
],
}
Common patterns:
-
RenderHookAliasing (useState, useContext, useMemo, useCallback):
- Freezes arguments (
Freeze @rest) - Marks arguments as render-time (
Render @rest) - Creates frozen return value
- Aliases arguments to return
- Freezes arguments (
-
EffectHookAliasing (useEffect, useLayoutEffect, useInsertionEffect):
- Freezes function and deps
- Creates internal effect object
- Captures function and deps into effect
- Returns undefined
-
Event handler hooks (useEffectEvent):
- Freezes callback (
Freeze @fn) - Aliases input to return (
Assign @fn -> @returns) - NO Render effect (callback not called during render)
- Freezes callback (
Example: useEffectEvent
const UseEffectEventHook = addHook(
DEFAULT_SHAPES,
{
positionalParams: [Effect.Freeze], // Takes one positional param
restParam: null,
returnType: {kind: 'Function', ...},
calleeEffect: Effect.Read,
hookKind: 'useEffectEvent',
returnValueKind: ValueKind.Frozen,
aliasing: {
receiver: '@receiver',
params: ['@fn'], // Name for the callback parameter
rest: null,
returns: '@returns',
temporaries: [],
effects: [
{kind: 'Freeze', value: '@fn', reason: ValueReason.HookCaptured},
{kind: 'Assign', from: '@fn', into: '@returns'},
// Note: NO Render effect - callback is not called during render
],
},
},
BuiltInUseEffectEventId,
);
// Add as both names for compatibility
['useEffectEvent', UseEffectEventHook],
['experimental_useEffectEvent', UseEffectEventHook],
Key insight: If a hook is missing an aliasing config, it falls back to DefaultNonmutatingHook which includes a Render effect on all arguments. This can cause false positives for hooks like useEffectEvent whose callbacks are not called during render.
Feature Flags
Feature flags are configured in src/HIR/Environment.ts, for example enableJsxOutlining. Test fixtures can override the active feature flags used for that fixture via a comment pragma on the first line of the fixture input, for example:
// enableJsxOutlining @enableNameAnonymousFunctions:false
...code...
Would enable the enableJsxOutlining feature and disable the enableNameAnonymousFunctions feature.
Rust Port (Active)
Work is tracked in compiler/docs/rust-port/ with numbered plan docs.
Rust crates live in compiler/crates/.
Before implementing from a plan:
- Run
git log --oneline --grep="<plan-name>"to see what's already done - Read the plan doc's Remaining Work / Status section
- Only implement what's actually remaining
After implementing:
- Update the plan doc's status
- Run
/compiler-verify - Ensure
compiler/scripts/test-babel-ast.shpasses
Debugging Tips
- Run
yarn snap -p <fixture>to see full HIR output with effects - Look for
@aliasingEffects=on FunctionExpressions - Look for
Impure,Render,Captureeffects on instructions - Check the pass ordering in Pipeline.ts to understand when effects are populated vs validated
Error Handling and Fault Tolerance
The compiler is fault-tolerant: it runs all passes and accumulates errors on the Environment rather than throwing on the first error. This lets users see all compilation errors at once.
Recording errors — Passes record errors via env.recordError(diagnostic). Errors are accumulated on Environment.#errors and checked at the end of the pipeline via env.hasErrors() / env.aggregateErrors().
tryRecord() wrapper — In Pipeline.ts, validation passes are wrapped in env.tryRecord(() => pass(hir)) which catches thrown CompilerErrors (non-invariant) and records them. Infrastructure/transformation passes are NOT wrapped in tryRecord() because later passes depend on their output being structurally valid.
Error categories:
CompilerError.throwTodo()— Unsupported but known pattern. Graceful bailout. Can be caught bytryRecord().CompilerError.invariant()— Truly unexpected/invalid state. Always throws immediately, never caught bytryRecord().- Non-
CompilerErrorexceptions — Always re-thrown.
Key files: Environment.ts (recordError, tryRecord, hasErrors, aggregateErrors), Pipeline.ts (pass orchestration), Program.ts (tryCompileFunction handles the Result).
Test fixtures: __tests__/fixtures/compiler/fault-tolerance/ contains multi-error fixtures verifying all errors are reported.