1,147 matches across 25 files for func main lang:Markdown lang:Markdown
snippet_mode: grep · sorted by relevance
27### React Server Components
28
29▶- Add extra loop protection to React Server Functions (@sebmarkbage [#35351](https://github.com/facebook/react/pull/35351))
30
31## 19.2.2 (Dec 11, 2025)
· · ·
34
35- Move `react-server-dom-webpack/*.unbundled` to private `react-server-dom-unbundled` (@eps1lon [#35290](https://github.com/facebook/react/pull/35290))
36▶- Patch Promise cycles and toString on Server Functions (@sebmarkbage, @unstubbable [#35289](https://github.com/facebook/react/pull/35289), [#35345](https://github.com/facebook/react/pull/35345))
37
38## 19.2.1 (Dec 3, 2025)
· · ·
104- Preload `<img>` and `<link>` using hints before they're rendered (@sebmarkbage [#34604](https://github.com/facebook/react/pull/34604))
105- Log error if production elements are rendered during development (@eps1lon [#34189](https://github.com/facebook/react/pull/34189))
106▶- Fix a bug when returning a Temporary reference (e.g. a Client Reference) from Server Functions (@sebmarkbage [#34084](https://github.com/facebook/react/pull/34084), @denk0403 [#33761](https://github.com/facebook/react/pull/33761))
107- Pass line/column to `filterStackFrame` (@eps1lon [#33707](https://github.com/facebook/react/pull/33707))
108- Support Async Modules in Turbopack Server References (@lubieowoce [#34531](https://github.com/facebook/react/pull/34531))
· · ·
143### React Server Components
144
145▶- Add extra loop protection to React Server Functions (@sebmarkbage [#35351](https://github.com/facebook/react/pull/35351))
146
147## 19.1.3 (Dec 11, 2025)
· · ·
150
151- Move `react-server-dom-webpack/*.unbundled` to private `react-server-dom-unbundled` (@eps1lon [#35290](https://github.com/facebook/react/pull/35290))
152▶- Patch Promise cycles and toString on Server Functions (@sebmarkbage, @unstubbable [#35289](https://github.com/facebook/react/pull/35289), [#35345](https://github.com/facebook/react/pull/35345))
153
154## 19.1.2 (Dec 3, 2025)
+ 56 more matches in this file
1▶# [React](https://react.dev/) · [](https://github.com/facebook/react/blob/main/LICENSE) [](https://www.npmjs.com/package/react) [](https://github.com/facebook/react/actions/workflows/runtime_build_and_test.yml) [](https://github.com/facebook/react/actions/workflows/compiler_typescript.yml) [](https://legacy.reactjs.org/docs/how-to-contribute.html#your-first-pull-request)
2
3React is a JavaScript library for building user interfaces.
· · ·
46import { createRoot } from 'react-dom/client';
47
48▶function HelloMessage({ name }) {
49 return <div>Hello {name}</div>;
50}
· · ·
60## Contributing
61
62▶The main purpose of this repository is to continue evolving React core, making it faster and easier to use. Development of React happens in the open on GitHub, and we are grateful to the community for contributing bugfixes and improvements. Read below to learn how you can take part in improving React.
63
64### [Code of Conduct](https://code.fb.com/codeofconduct)
9
10- Follow patterns from `compiler/docs/rust-port/rust-port-architecture.md`
11▶- Use arenas + copyable IDs instead of shared references: `IdentifierId`, `ScopeId`, `FunctionId`, `TypeId`
12- Pass `env: &mut Environment` separately from `func: &mut HirFunction`
13- Use two-phase collect/apply when you can't mutate through stored references
· · ·
12▶- Pass `env: &mut Environment` separately from `func: &mut HirFunction`
13- Use two-phase collect/apply when you can't mutate through stored references
14- Run `bash compiler/scripts/test-babel-ast.sh` to test AST round-tripping
· · ·
19Before declaring work complete on a plan doc:
20- Re-read the original user prompt to ensure all requested steps are done
21▶- Check the plan doc for any "Remaining Work" items
22- Verify test-babel-ast.sh passes with the expected fixture count
23- Update the plan doc's status section
20| 2 | PruneMaybeThrows | hir | Validation: validateContextVariableLValues, validateUseMemo after |
21| 3 | DropManualMemoization | hir | Conditional |
22▶| 4 | InlineImmediatelyInvokedFunctionExpressions | hir | |
23| 5 | MergeConsecutiveBlocks | hir | |
24| 6 | SSA | hir | |
· · ·
27| 9 | InferTypes | hir | Validation: validateHooksUsage, validateNoCapitalizedCalls after (conditional) |
28| 10 | OptimizePropsMethodCalls | hir | |
29▶| 11 | AnalyseFunctions | hir | |
30| 12 | InferMutationAliasingEffects | hir | |
31| 13 | OptimizeForSSR | hir | Conditional: outputMode === 'ssr' |
· · ·
38| 20 | MemoizeFbtAndMacroOperandsInSameScope | hir | |
39| -- | outlineJSX | hir | Between #20 and #21, conditional: enableJsxOutlining, no log entry |
40▶| 21 | NameAnonymousFunctions | hir | Conditional |
41| 22 | OutlineFunctions | hir | Conditional |
42| 23 | AlignMethodCallScopes | hir | |
· · ·
41▶| 22 | OutlineFunctions | hir | Conditional |
42| 23 | AlignMethodCallScopes | hir | |
43| 24 | AlignObjectMethodScopes | hir | |
· · ·
49| 30 | FlattenScopesWithHooksOrUseHIR | hir | |
50| 31 | PropagateScopeDependenciesHIR | hir | |
51▶| 32 | BuildReactiveFunction | reactive | |
52| 33 | AssertWellFormedBreakTargets | debug | Validation |
53| 34 | PruneUnusedLabels | reactive | |
+ 12 more matches in this file
41## Step 2: Gather context
42
43▶Read the following files (all reads happen in main context):
44
451. **Architecture guide**: `compiler/docs/rust-port/rust-port-architecture.md`
· · ·
484. **Rust pipeline**: `compiler/crates/react_compiler/src/entrypoint/pipeline.rs`
495. **Rust HIR types**: Key type files in `compiler/crates/react_compiler_hir/src/` (especially `hir.rs`, `environment.rs`)
50▶6. **Rust reactive types**: For reactive passes, also read `compiler/crates/react_compiler_hir/src/reactive_function.rs`
517. **Target crate**: If the target crate already exists, read its `Cargo.toml`, `src/lib.rs`, and existing files to understand the current structure
52
34 `04-constantPropagation.md`, `05-deadCodeElimination.md`, `06-inferTypes.md`
35
36▶3. **Function & Effect Analysis** (passes 07-09):
37 `07-analyseFunctions.md`, `08-inferMutationAliasingEffects.md`, `09-inferMutationAliasingRanges.md`
38
· · ·
37▶ `07-analyseFunctions.md`, `08-inferMutationAliasingEffects.md`, `09-inferMutationAliasingRanges.md`
38
394. **Reactivity & Scope Variables** (passes 10-14):
· · ·
43 `15-alignReactiveScopesToBlockScopesHIR.md`, `16-mergeOverlappingReactiveScopesHIR.md`, `17-buildReactiveScopeTerminalsHIR.md`, `18-flattenReactiveLoopsHIR.md`, `19-flattenScopesWithHooksOrUseHIR.md`, `20-propagateScopeDependenciesHIR.md`
44
45▶6. **Reactive Function & Transforms** (passes 21-30):
46 `21-buildReactiveFunction.md`, `22-pruneUnusedLabels.md`, `23-pruneNonEscapingScopes.md`, `24-pruneNonReactiveDependencies.md`, `25-pruneUnusedScopes.md`, `26-mergeReactiveScopesThatInvalidateTogether.md`, `27-pruneAlwaysInvalidatingScopes.md`, `28-propagateEarlyReturns.md`, `29-promoteUsedTemporaries.md`, `30-renameVariables.md`
47
· · ·
46▶ `21-buildReactiveFunction.md`, `22-pruneUnusedLabels.md`, `23-pruneNonEscapingScopes.md`, `24-pruneNonReactiveDependencies.md`, `25-pruneUnusedScopes.md`, `26-mergeReactiveScopesThatInvalidateTogether.md`, `27-pruneAlwaysInvalidatingScopes.md`, `28-propagateEarlyReturns.md`, `29-promoteUsedTemporaries.md`, `30-renameVariables.md`
47
487. **Codegen & Optimization** (passes 31, 34-38):
· · ·
49▶ `31-codegenReactiveFunction.md`, `34-optimizePropsMethodCalls.md`, `35-optimizeForSSR.md`, `36-outlineJSX.md`, `37-outlineFunctions.md`, `38-memoizeFbtAndMacroOperandsInSameScope.md`
50
518. **Validation Passes** (passes 39-55):
+ 2 more matches in this file
7When 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.
8
9▶- `packages/babel-plugin-react-compiler/` - Main compiler package
10 - `src/HIR/` - High-level Intermediate Representation types and utilities
11 - `src/Inference/` - Effect inference passes (aliasing, mutation, etc.)
· · ·
12 - `src/Validation/` - Validation passes that check for errors
13▶ - `src/Entrypoint/Pipeline.ts` - Main compilation pipeline with pass ordering
14 - `src/__tests__/fixtures/compiler/` - Test fixtures
15 - `error.todo-*.js` - Unsupported feature, correctly throws Todo error (graceful bailout)
· · ·
104The compiler converts source code to HIR for analysis. Key types in `src/HIR/HIR.ts`:
105
106▶- **HIRFunction** - A function being compiled
107 - `body.blocks` - Map of BasicBlocks
108 - `context` - Captured variables from outer scope
· · ·
109▶ - `params` - Function parameters
110 - `returns` - The function's return place
111 - `aliasingEffects` - Effects that describe the function's behavior when called
· · ·
110▶ - `returns` - The function's return place
111 - `aliasingEffects` - Effects that describe the function's behavior when called
112
+ 14 more matches in this file
21snapshot at top.)
22
23▶The 15 remaining SWC e2e failures fall into three groups. Each line names the
24fixture and the failure mode; the group it sits in dictates the appropriate
25fix.
· · ·
26
27▶### Group A: Fixture maintenance, not Rust bugs
28
29SWC compiles code that TS rejects, or vice versa, in ways where Rust's
· · ·
39 emits a Todo bailout (`[hoisting] EnterSSA: Expected identifier to be
40 defined before being used`) that the Babel path does not.
41▶- `error.todo-repro-named-function-with-shadowed-local-same-name.js` —
42 Babel errors; SWC compiles.
43- `new-mutability/error.todo-repro-named-function-with-shadowed-local-same-name.js`
· · ·
43▶- `new-mutability/error.todo-repro-named-function-with-shadowed-local-same-name.js`
44 — same as above with the new mutation-aliasing model enabled.
45- `error.todo-rust-as-expression-assignment-target.tsx` — Babel errors;
· · ·
53
54- `use-no-forget-multiple-with-eslint-suppression.js` — spurious
55▶ `import { c as _c }` in the TS reference output. Fixed on `main` by
56 [react#36500](https://github.com/facebook/react/pull/36500) (merged).
57 Will pass automatically once `pr-36173` rebases onto `main`; until then
+ 6 more matches in this file
124| Crate | Purpose |
125|-------|---------|
126▶| `react_compiler` | Main entrypoint, pipeline orchestration |
127| `react_compiler_ast` | Babel AST types + serde |
128| `react_compiler_hir` | HIR types, environment, visitors |
· · ·
1681. **Parallel pass research**: Launch one agent per compiler pass to analyze TS implementation for port feasibility
1692. **Review agents**: Dedicated "Review Rust port changes" agents (14 invocations)
170▶3. **Fix-specific agents**: "Fix AnalyseFunctions failures" (4x), "Fix PruneMaybeThrows validation failures" (2x)
1714. **Worktree isolation**: 16 worktree entries for isolated implementation work
172
· · ·
189| `rust-port-orchestrator-log.md` | 135 | 104 | Running log of orchestrator progress |
190| `build_hir.rs` | 112 | 162 | Core HIR lowering from AST |
191▶| `program.rs` (entrypoint) | 103 | 173 | Main compilation entrypoint |
192| `rust-port-research.md` | 85 | 47+21 | Research & analysis document |
193| `test-rust-port.ts` | 77 | 90 | Primary test comparison script |
· · ·
222For large implementation tasks:
223```
224▶> Use a team of agents (opus) to implement the remainder of the items in <plan>. Make sure to thoroughly test, verify the implementation against the plan. Use /compiler-verify and /compiler-commit.
225```
226
· · ·
271---
272
273▶## 9. Current State & Remaining Work
274
275### Test Results (as of latest orchestrator log)
+ 3 more matches in this file
7This crate is the serialization boundary between the JS toolchain (Babel parser) and the Rust compiler. It must be a faithful 1:1 representation of Babel's AST output — not a simplified or custom IR.
8
9▶**Current status**: Complete (human reviewed). All 1714 compiler test fixtures round-trip successfully (0 failures). No `Unknown` catch-all variants remain. Scope types are defined separately in [rust-port-0002-scope-types.md](rust-port-0002-scope-types.md).
10
11---
· · ·
58### 1. Internally tagged via `"type"` field
59
60▶Babel AST nodes use a `"type"` field as the discriminant (e.g., `"type": "FunctionDeclaration"`). Serde's default externally-tagged enum format doesn't match this. Use **internally tagged** enums with `#[serde(tag = "type")]`:
61
62```rust
· · ·
107```rust
108#[derive(Debug, Clone, Serialize, Deserialize)]
109▶pub struct FunctionDeclaration {
110 #[serde(flatten)]
111 pub base: BaseNode,
· · ·
125### 3. Naming conventions
126
127▶- Rust struct/enum names: PascalCase matching the Babel type name exactly (e.g., `FunctionDeclaration`, `JSXElement`)
128- Rust field names: snake_case, with `#[serde(rename = "camelCase")]` for JSON mapping
129- Reserved words: `#[serde(rename = "async")]` on field `is_async: bool`, `#[serde(rename = "type")]` handled by internal tagging
· · ·
141| `field: T \| null` (required but nullable) | Present, may be `null` | `field: Option<T>` (no `skip_serializing_if` — always serialize) |
142
143▶**Critical subtlety**: Some fields like `FunctionDeclaration.id` are typed `id?: Identifier | null` and appear as `"id": null` in JSON (present but null), not absent. The round-trip test catches any mismatches here. When Babel serializes `null` for a field, we must also serialize `null` — not omit it. The round-trip test is the source of truth for which fields use which pattern.
144
145A `nullable_value` custom deserializer in `common.rs` handles the case where a field needs to distinguish "absent" from "explicitly null" (deserializing the latter as `Some(Value::Null)`):
+ 8 more matches in this file
51pub enum ScopeKind {
52 Program,
53▶ Function,
54 Block,
55 #[serde(rename = "for")]
· · ·
67 /// The scope this binding is declared in.
68 pub scope: ScopeId,
69▶ /// The type of the declaration AST node (e.g., "FunctionDeclaration",
70 /// "VariableDeclarator"). Used by the compiler to distinguish function
71 /// declarations from variable declarations during hoisting.
· · ·
70▶ /// "VariableDeclarator"). Used by the compiler to distinguish function
71 /// declarations from variable declarations during hoisting.
72 /// COMMENT: make this an enum similar to BindingKind
· · ·
86 /// Import bindings (import declarations).
87 Module,
88▶ /// Function declarations (hoisted).
89 Hoisted,
90 /// Other local bindings (class declarations, etc.).
· · ·
116Key differences from Babel's in-memory representation:
117- **Bindings are stored in a flat table** indexed by `BindingId`, not nested inside scope objects. Each `ScopeData` stores `HashMap<String, BindingId>` mapping names to binding IDs rather than containing full binding data inline.
118▶- **`declaration_type`** replaces Babel's `binding.path.isFunctionDeclaration()` / `binding.path.isVariableDeclarator()` checks. The compiler uses these to determine hoisting behavior — storing the declaration node type as a string avoids needing to cross-reference back into the AST.
119- **`ImportBindingData`** captures import source, kind, and imported name, covering all the import resolution the compiler does via `binding.path.isImportSpecifier()` etc.
120
+ 3 more matches in this file
8
9**Known issues — resolved:**
10▶- TS binary rewritten to call `compile()` directly (bypasses `transformFromAstSync` + `BabelPluginReactCompiler`). Individual pass functions aren't exported from dist, so logger-based capture is still used, but the Babel plugin orchestration layer is bypassed. (done)
11- `debug_error` renamed to `format_errors` (done). `CompilerError` type name kept as-is since `CompilerDiagnostic` already exists as a different type in the diagnostics crate.
12- Both TS and Rust now print `returnTypeAnnotation` in debug output. (done)
· · ·
15- All collection types migrated to `IndexMap`/`IndexSet` (done).
16
17▶**Known issues — remaining:**
18- Debug output format: TS and Rust debug printers produce different output formats. Both need to converge on Rust `Debug`-style nested format. This will be addressed when the Rust lowering is implemented and output comparison becomes possible.
19- TS debug printer collects identifiers/functions per-function; should print all from environment (matching Rust). Requires access to the Environment from TS, which is not currently exposed through the logger API.
· · ·
19▶- TS debug printer collects identifiers/functions per-function; should print all from environment (matching Rust). Requires access to the Environment from TS, which is not currently exposed through the logger API.
20- Rust binary config: `Environment::new()` needs matching config (`compilationMode: "all"`, `target: "19"`, etc.) — requires adding config support to the Rust Environment type.
21- Error format output between TS and Rust has not been validated for byte-identical output. Will be validated when lowering produces real output.
· · ·
83 bb0 (block):
84 [1] $0:T = LoadGlobal global:console
85▶- [2] $1:TFunction<BuiltInConsoleLog> = PropertyLoad $0.log
86+ [2] $1:T = PropertyLoad $0.log
87
· · ·
99### HIR Phase
100
101▶| Pass Name | Pipeline.ts Function |
102|-----------|---------------------|
103| `HIR` | `lower()` |
+ 35 more matches in this file
7The Rust port should be structurally as close to the TypeScript as possible: viewing the TS and Rust side by side, the logic should look, read, and feel similar while working naturally in Rust.
8
9▶**Current status**: M1-M13 fully implemented. All statement types, expression types, destructuring, function expressions, JSX, switch/try-catch, for-of/in, optional chaining, and recursive lowering are complete. No `todo!()` stubs remain. `cargo check` passes. Remaining work: test against fixtures and fix divergences from TypeScript output.
10
11**Known issues to fix:**
· · ·
12- All collection types must use `IndexMap`/`IndexSet` (from the `indexmap` crate), not `BTreeMap`/`BTreeSet`/`HashMap`/`HashSet`. This is critical for `HIR.blocks` where `BTreeMap` destroys RPO insertion ordering.
13▶- Functions `lower_function`, `lower_function_to_value`, `gather_captured_context`, `lower_object_property_key`, `lower_type` take `&Expression`. The AST crate uses `Expression` for keys and doesn't have standalone `Function`/`ObjectPropertyKey`/`TypeAnnotation` types, so `&Expression` is correct for the current AST structure. When these functions are implemented, they should pattern-match on the specific expression variants internally.
14- `VariableBinding::Identifier.binding_kind` is `String` — must be a `BindingKind` enum.
15- `HirBuilder` is missing `component_scope: ScopeId` field (needed for `gather_captured_context` in M9).
· · ·
33 Cargo.toml
34 src/
35▶ lib.rs # HIR types: HirFunction, BasicBlock, Instruction, Terminal, Place, etc.
36 environment.rs # Environment struct (arenas, counters, config)
37 react_compiler_diagnostics/
· · ·
57### 1. No NodePath — Work Directly with AST Structs + ScopeInfo
58
59▶The TypeScript `lower()` takes a `NodePath<t.Function>` and uses Babel's traversal API (`path.get()`, `path.scope.getBinding()`, etc.) extensively. The Rust port works with deserialized `react_compiler_ast` structs and the `ScopeInfo` from step 2.
60
61**TypeScript pattern:**
· · ·
62```typescript
63▶function lowerStatement(builder: HIRBuilder, stmtPath: NodePath<t.Statement>) {
64 switch (stmtPath.type) {
65 case 'IfStatement': {
+ 49 more matches in this file
5Create a new, minimal Babel plugin package (`babel-plugin-react-compiler-rust`) that serves as a thin JavaScript shim over the Rust compiler. The JS side does only three things:
6
7▶1. **Pre-filter**: Quick name-based scan for potential React functions (capitalized or hook-like names)
82. **Invoke Rust**: Serialize the Babel AST, scope info, and resolved options to JSON; call the Rust compiler via NAPI
93. **Apply result**: Replace the program AST with the Rust-returned AST and forward logger events
· · ·
10
11▶All complex logic — function detection, compilation mode decisions, directives, suppressions, gating rewrites, import insertion, outlined functions — lives in Rust. This ensures the logic is implemented once and reused across future OXC and SWC integrations.
12
13**Current status**: Implementation complete. All entrypoint logic ported to Rust: compile_program orchestration, shouldSkipCompilation, findFunctionsToCompile, getReactFunctionType/getComponentOrHookLike (with all name heuristics, callsHooksOrCreatesJsx, returnsNonNode, isValidComponentParams), directive parsing, suppression detection/filtering, ProgramContext (uid generation, import tracking), gating rewrites, import insertion. The actual per-function compilation (compileFn) returns a skip event pending full pipeline implementation.
· · ·
13▶**Current status**: Implementation complete. All entrypoint logic ported to Rust: compile_program orchestration, shouldSkipCompilation, findFunctionsToCompile, getReactFunctionType/getComponentOrHookLike (with all name heuristics, callsHooksOrCreatesJsx, returnsNonNode, isValidComponentParams), directive parsing, suppression detection/filtering, ProgramContext (uid generation, import tracking), gating rewrites, import insertion. The actual per-function compilation (compileFn) returns a skip event pending full pipeline implementation.
14
15**Prerequisites**: [rust-port-0001-babel-ast.md](rust-port-0001-babel-ast.md) (complete), [rust-port-0002-scope-types.md](rust-port-0002-scope-types.md) (complete), core compilation pipeline in Rust (in progress).
· · ·
42│ │ │ │
43│ │ - shouldSkipCompilation │ │
44▶│ │ - findFunctionsToCompile │ │
45│ │ (all compilation modes, directives, │ │
46│ │ forwardRef/memo, suppressions, etc.) │ │
· · ·
48│ │ - gating rewrites │ │
49│ │ - import insertion │ │
50▶│ │ - outlined function insertion │ │
51│ │ - panicThreshold handling │ │
52│ │ │ │
+ 50 more matches in this file
11| `identifiers: Vec<Identifier>` | `IdentifierId` | `Environment` | Shared `Identifier` object references across `Place` values |
12| `scopes: Vec<ReactiveScope>` | `ScopeId` | `Environment` | Shared `ReactiveScope` references across identifiers |
13▶| `functions: Vec<HIRFunction>` | `FunctionId` | `Environment` | Inline `HIRFunction` on `FunctionExpression`/`ObjectMethod` |
14| `types: Vec<Type>` | `TypeId` | `Environment` | Inline `Type` on `Identifier` |
15
· · ·
18## Instructions and EvaluationOrder
19
20▶- `HirFunction.instructions: Vec<Instruction>` — flat instruction table
21- `BasicBlock.instructions: Vec<InstructionId>` — indices into the table above
22- The old TypeScript `InstructionId` is renamed to `EvaluationOrder` — it represents evaluation order and appears on both instructions and terminals
· · ·
23▶- The new `InstructionId` is an index into `HirFunction.instructions`, giving passes a single copyable ID to reference any instruction
24
25## Place is Clone, MutableRange is on Identifier/Scope
· · ·
40```
41
42▶## Function Arena and FunctionId
43
44`FunctionExpression` and `ObjectMethod` instruction values store a `FunctionId` instead of an inline `HIRFunction`. Inner functions are accessed via the arena:
· · ·
44▶`FunctionExpression` and `ObjectMethod` instruction values store a `FunctionId` instead of an inline `HIRFunction`. Inner functions are accessed via the arena:
45
46```rust
+ 13 more matches in this file
4* Define a Scope type that encodes the tree of scope information, mapping to the information that babel represents in its own scope tree
5
6▶The main public API is roughly `compile(BabelAst, Scope) -> Option<BabelAst>` returning None if no changes, or Some with the updated ast.
7
8## Arenas
· · ·
16 * Table on Environment, stores actual ReactiveScope values
17 * `Identifier`, scope terminals, etc reference indirectly via `ScopeID`
18▶* `Function`:
19 * Table on Environment, stores the inner HirFunction values
20 * `InstructionValue::FunctionExpression` and `::ObjectMethod` reference indirectly via `FunctionId`
· · ·
19▶ * Table on Environment, stores the inner HirFunction values
20 * `InstructionValue::FunctionExpression` and `::ObjectMethod` reference indirectly via `FunctionId`
21* `Type`:
· · ·
20▶ * `InstructionValue::FunctionExpression` and `::ObjectMethod` reference indirectly via `FunctionId`
21* `Type`:
22 * Table on Environment, stores actual types
· · ·
28
29* Rename `InstructionId` to `EvaluationOrder` - this type is actually about representing the evaluation order, and is not even instruction-specific: it is also present on terminals.
30▶* `HirFunction` stores `instructions: Vec<InstructionId>`
31* `BasicBlock.instructions` becomes `Vec<InstructionId>`, indexing into the `HirFunction.instructions` vec
32
+ 7 more matches in this file
16InferTypes: complete
17OptimizePropsMethodCalls: complete
18▶AnalyseFunctions: complete (1649/1649)
19InferMutationAliasingEffects: complete (1643/1643)
20OptimizeForSSR: complete (5/5, conditional, outputMode === 'ssr')
· · ·
27MemoizeFbtAndMacroOperandsInSameScope: complete
28outlineJSX: complete (conditional on enableJsxOutlining)
29▶NameAnonymousFunctions: complete (2/2, conditional)
30OutlineFunctions: complete
31AlignMethodCallScopes: complete
· · ·
30▶OutlineFunctions: complete
31AlignMethodCallScopes: complete
32AlignObjectMethodScopes: complete
· · ·
38FlattenScopesWithHooksOrUseHIR: complete
39PropagateScopeDependenciesHIR: complete
40▶BuildReactiveFunction: complete
41AssertWellFormedBreakTargets: complete
42PruneUnusedLabels: complete
· · ·
66Program.ts logged directive as [object Object] instead of its string value.
67(2) Rust program.rs used inferred fn_name for CompileSuccess instead of
68▶codegen_fn.id, causing arrow functions to report names the TS compiler doesn't.
69Removed all code output normalization from test-e2e.ts — comparison now uses
70prettier only.
+ 125 more matches in this file
1▶# Rust Port: ReactiveFunction and Reactive Passes
2
3Current status: **Phase 2 In Progress** — Reactive types, crate skeleton, TS/Rust debug printers, and BuildReactiveFunction are implemented. 1458/1717 fixtures pass (85%). Remaining failures are mostly earlier-pass error propagation differences and a few loop scheduling edge cases.
· · ·
3▶Current status: **Phase 2 In Progress** — Reactive types, crate skeleton, TS/Rust debug printers, and BuildReactiveFunction are implemented. 1458/1717 fixtures pass (85%). Remaining failures are mostly earlier-pass error propagation differences and a few loop scheduling edge cases.
4
5## Overview
· · ·
6
7▶This document covers porting the reactive function representation and all passes from `BuildReactiveFunction` through `CodegenReactiveFunction` from TypeScript to Rust.
8
9The reactive function is a tree-structured IR derived from the HIR CFG. `BuildReactiveFunction` converts the flat CFG into a nested tree where control flow constructs (if/switch/loops/try) and reactive scopes are represented as nested blocks rather than block references. Subsequent passes prune, merge, and transform scopes, then codegen converts the tree to output AST.
· · ·
9▶The reactive function is a tree-structured IR derived from the HIR CFG. `BuildReactiveFunction` converts the flat CFG into a nested tree where control flow constructs (if/switch/loops/try) and reactive scopes are represented as nested blocks rather than block references. Subsequent passes prune, merge, and transform scopes, then codegen converts the tree to output AST.
10
11## 1. Rust Type Representation
· · ·
15All types derive `Debug, Clone`.
16
17▶### ReactiveFunction
18
19```rust
+ 60 more matches in this file
27 - [Phase 11: Scope Terminal Construction](#phase-11-scope-terminal-construction)
28 - [Phase 12: Scope Dependency Propagation](#phase-12-scope-dependency-propagation)
29▶ - [Phase 13: Reactive Function Construction](#phase-13-reactive-function-construction)
30 - [Phase 14: Reactive Function Transforms](#phase-14-reactive-function-transforms)
31 - [Phase 15: Codegen](#phase-15-codegen)
· · ·
30▶ - [Phase 14: Reactive Function Transforms](#phase-14-reactive-function-transforms)
31 - [Phase 15: Codegen](#phase-15-codegen)
32 - [Validation Passes](#validation-passes)
· · ·
39## Executive Summary
40
41▶Porting the React Compiler from TypeScript to Rust is **feasible and the Rust code can remain structurally very close to the TypeScript**. The compiler's algorithms are well-suited to Rust. The TypeScript implementation relies on patterns that conflict with Rust's ownership model, but all have clean, well-understood solutions using arenas and indirect references:
42
431. **Shared Identifier references**: Multiple `Place` objects reference the same `Identifier` object. **Solution**: Arena-allocated identifiers on `Environment`, referenced by copyable `IdentifierId` index.
· · ·
452. **Shared ReactiveScope references**: Multiple identifiers share the same `ReactiveScope` object (including its mutable range). **Solution**: Arena-allocated scopes on `Environment`, referenced by `ScopeId`.
46
47▶3. **Inner function storage**: `FunctionExpression`/`ObjectMethod` instructions store inner `HIRFunction` values inline. **Solution**: Arena-allocated functions on `Environment`, referenced by `FunctionId`.
48
494. **Type storage**: Types stored inline on identifiers. **Solution**: Arena-allocated types on `Environment`, referenced by `TypeId`.
· · ·
50
51▶5. **Instructions stored inline in blocks**: `BasicBlock.instructions` stores `Instruction` objects directly. **Solution**: Flat instruction table on `HIRFunction`, referenced by `InstructionId`. The existing `InstructionId` (evaluation order counter) is renamed to `EvaluationOrder` since it applies to both instructions and terminals.
52
536. **Environment as shared mutable singleton**: The `Environment` object is threaded through the entire compilation via `fn.env` and mutated by many passes. **Solution**: Remove `HIRFunction.env` and pass `env: &mut Environment` separately. Maintain existing fields (no sub-struct grouping) to allow precise sliced borrows via direct field access.
+ 171 more matches in this file
5
6## Purpose
7▶Converts a Babel AST function node into a High-level Intermediate Representation (HIR), which represents code as a control-flow graph (CFG) with basic blocks, instructions, and terminals. This is the first major transformation pass in the React Compiler pipeline, enabling precise expression-level memoization analysis.
8
9## Input Invariants
· · ·
10▶- Input must be a valid Babel `NodePath<t.Function>` (FunctionDeclaration, FunctionExpression, or ArrowFunctionExpression)
11- The function must be a component or hook (determined by the environment)
12- Babel scope analysis must be available for binding resolution
· · ·
11▶- The function must be a component or hook (determined by the environment)
12- Babel scope analysis must be available for binding resolution
13- An `Environment` instance must be provided with compiler configuration
· · ·
14▶- Optional `bindings` map for nested function lowering (recursive calls)
15- Optional `capturedRefs` map for context variables captured from outer scope
16
· · ·
17## Output Guarantees
18▶- Returns `Result<HIRFunction, CompilerError>` - either a successfully lowered function or compilation errors
19- The HIR function contains:
20 - A complete CFG with basic blocks (`body.blocks: Map<BlockId, BasicBlock>`)
+ 11 more matches in this file
10- The HIR must have blocks in reverse postorder (predecessors visited before successors, except for back-edges)
11- Block predecessor information (`block.preds`) must be populated correctly
12▶- The function's `context` array must be empty for the root function (outer function declarations)
13- Identifiers may be reused across multiple definitions/assignments (non-SSA form)
14
· · ·
17- All operand references use the SSA-renamed identifiers
18- Phi nodes are inserted at join points where values from different control flow paths converge
19▶- Function parameters are SSA-renamed
20- Nested functions (FunctionExpression, ObjectMethod) are recursively converted to SSA form
21- Context variables (captured from outer scopes) are handled specially and not redefined
· · ·
20▶- Nested functions (FunctionExpression, ObjectMethod) are recursively converted to SSA form
21- Context variables (captured from outer scopes) are handled specially and not redefined
22
· · ·
23## Algorithm
24▶The pass uses the Braun et al. algorithm ("Simple and Efficient Construction of Static Single Assignment Form") with adaptations for handling loops and nested functions.
25
26### Key Steps:
· · ·
271. **Block Traversal**: Iterate through blocks in order (assumed reverse postorder from previous passes)
28▶2. **Definition Tracking**: Maintain a per-block `defs` map from original identifiers to their SSA-renamed versions
293. **Renaming**:
30 - When a value is **defined** (lvalue), create a new SSA identifier with fresh `IdentifierId`
+ 6 more matches in this file
20- Unreachable blocks are removed and the CFG is minimized
21- Phi nodes with unreachable predecessor operands are pruned
22▶- Nested functions (`FunctionExpression`, `ObjectMethod`) are recursively processed
23
24## Algorithm
· · ·
63- **Division results**: Computed at compile time (may produce `NaN`, `Infinity`, etc.)
64- **LoadGlobal in phis**: Only propagated if all operands reference the same global name
65▶- **Nested functions**: Constants from outer scope are propagated into nested function expressions
66
67## TODOs
· · ·
72**Input:**
73```javascript
74▶function Component() {
75 let a = 1;
76
· · ·
95**After ConstantPropagation:**
96- `a === 1` evaluates to `true`
97▶- The `if (a === 1)` branch is eliminated, only consequent remains
98- `b` is known to be `true`
99- `if (b)` branch is eliminated, only consequent remains
· · ·
99▶- `if (b)` branch is eliminated, only consequent remains
100- `c` is known to be `'hello'`
101- All intermediate blocks are merged
+ 1 more matches in this file
5
6## Purpose
7▶Infers types for all identifiers in the HIR by generating type equations and solving them using unification. This pass annotates identifiers with concrete types (Primitive, Object, Function) based on the operations performed on them and the types of globals/hooks they interact with.
8
9## Input Invariants
· · ·
15- All identifier types are resolved from type variables (`Type`) to concrete types where possible
16- Phi nodes have their operand types unified to produce a single result type
17▶- Function return types are inferred from the unified types of all return statements
18- Property accesses on known objects/hooks resolve to the declared property types
19- Component props parameters are typed as `TObject<BuiltInProps>`
· · ·
251. **Constraint Generation (`generate`)**: Traverses all instructions and generates type equations:
26 - Primitives, literals, unary/binary operations -> `Primitive` type
27▶ - Hook/function calls -> Function type with fresh return type variable
28 - Property loads -> `Property` type that defers to object shape lookup
29 - Destructuring -> Property types for each extracted element
· · ·
37 - Property types are resolved by looking up the object's shape
38 - Phi types are resolved by finding a common type among operands (or falling back to `Phi` if incompatible)
39▶ - Function types are unified by unifying their return types
40 - Occurs check prevents infinite types (cycles in type references)
41
· · ·
44## Key Data Structures
45- **TypeVar** (`kind: 'Type'`): A type variable with a unique TypeId, used for unknowns
46▶- **Unifier**: Maintains a substitution map from TypeId to Type, with methods for unification and cycle detection
47- **TypeEquation**: A pair of types that should be equal, used as constraints
48- **PhiType** (`kind: 'Phi'`): Represents the join of multiple types from control flow merge points
+ 8 more matches in this file
1▶# analyseFunctions
2
3## File
· · ·
4▶`src/Inference/AnalyseFunctions.ts`
5
6## Purpose
· · ·
7▶Recursively analyzes all nested function expressions and object methods in a function to infer their aliasing effect signatures, which describe how the function affects its captured variables when invoked.
8
9## Input Invariants
· · ·
10- The HIR has been through SSA conversion and type inference
11▶- FunctionExpression and ObjectMethod instructions have an empty `aliasingEffects` array (`@aliasingEffects=[]`)
12- Context variables (captured variables from outer scope) exist on `fn.context` but do not have their effect populated
13
· · ·
14## Output Guarantees
15▶- Every FunctionExpression and ObjectMethod has its `aliasingEffects` array populated with the effects the function performs when called (mutations, captures, aliasing to return value, etc.)
16- Each context variable's `effect` property is set to either `Effect.Capture` (if the variable is captured or mutated by the inner function) or `Effect.Read` (if only read)
17- Context variable mutable ranges are reset to `{start: 0, end: 0}` and scopes are set to `null` to prepare for the outer function's subsequent `inferMutationAliasingRanges` pass
+ 24 more matches in this file
5
6## Purpose
7▶Infers the mutation and aliasing effects for all instructions and terminals in the HIR, making the effects of built-in instructions/functions as well as user-defined functions explicit. These effects form the basis for subsequent analysis to determine the mutable range of each value in the program and for validation against invalid code patterns like mutating frozen values.
8
9## Input Invariants
· · ·
10- HIR must be in SSA form (run after SSA pass)
11- Types must be inferred (run after InferTypes pass)
12▶- Functions must be analyzed (run after AnalyseFunctions pass) - this provides `aliasingEffects` on FunctionExpressions
13- Each instruction must have an lvalue (destination place)
14
· · ·
25 - Create initial `InferenceState` mapping identifiers to abstract values
26 - Initialize context variables as `ValueKind.Context`
27▶ - Initialize parameters as `ValueKind.Frozen` (for top-level components/hooks) or `ValueKind.Mutable` (for function expressions)
28
292. **Two-Phase Effect Processing**:
· · ·
46
47### InferenceState
48▶Maintains two maps:
49- `#values: Map<InstructionValue, AbstractValue>` - Maps allocation sites to their abstract kind
50- `#variables: Map<IdentifierId, Set<InstructionValue>>` - Maps identifiers to the set of values they may point to (set to handle phi joins)
· · ·
70```
71
72▶The `mergeValueKinds` function implements the lattice join:
73- `Frozen | Mutable -> MaybeFrozen`
74- `Context | Mutable -> Context`
+ 5 more matches in this file