Skip to content

[compiler] Remove local CompilerError accumulators, emit directly to env.recordError()#571

Closed
everettbu wants to merge 11 commits into
mainfrom
pr35851
Closed

[compiler] Remove local CompilerError accumulators, emit directly to env.recordError()#571
everettbu wants to merge 11 commits into
mainfrom
pr35851

Conversation

@everettbu

Copy link
Copy Markdown

Mirror of facebook/react#35851
Original author: josephsavona


Removes unnecessary indirection in 17 compiler passes that previously
accumulated errors in a local CompilerError instance before flushing
them to env.recordErrors() at the end of each pass. Errors are now
emitted directly via env.recordError() as they're discovered.

For passes with recursive error-detection patterns (ValidateNoRefAccessInRender,
ValidateNoSetStateInRender), the internal accumulator is kept but flushed
via individual recordError() calls. For InferMutationAliasingRanges,
a shouldRecordErrors flag preserves the conditional suppression logic.
For TransformFire, the throw-based error propagation is replaced with
direct recording plus an early-exit check in Pipeline.ts.


Stack created with Sapling. Best reviewed with ReviewStack.

  • #35853
  • #35852
  • -> #35851
  • #35850
  • #35849
  • #35848
  • #35847
  • #35845
  • #35844
  • #35843
  • #35842
  • #35841
  • #35840

Add detailed plan for making the React Compiler fault-tolerant by
accumulating errors across all passes instead of stopping at the first
error. This enables reporting multiple compilation errors at once.
Add error accumulation methods to the Environment class:
- #errors field to accumulate CompilerErrors across passes
- recordError() to record a single diagnostic (throws if Invariant)
- recordErrors() to record all diagnostics from a CompilerError
- hasErrors() to check if any errors have been recorded
- aggregateErrors() to retrieve the accumulated CompilerError
- tryRecord() to wrap callbacks and catch CompilerErrors
…erance

- Change runWithEnvironment/run/compileFn to return Result<CodegenFunction, CompilerError>
- Wrap all pipeline passes in env.tryRecord() to catch and record CompilerErrors
- Record inference pass errors via env.recordErrors() instead of throwing
- Handle codegen Result explicitly, returning Err on failure
- Add final error check: return Err(env.aggregateErrors()) if any errors accumulated
- Update tryCompileFunction and retryCompileFunction in Program.ts to handle Result
- Keep lint-only passes using env.logErrors() (non-blocking)
- Update 52 test fixture expectations that now report additional errors

This is the core integration that enables fault tolerance: errors are caught,
recorded, and the pipeline continues to discover more errors.
…rs on env

Update 9 validation passes to record errors directly on fn.env instead of
returning Result<void, CompilerError>:
- validateHooksUsage
- validateNoCapitalizedCalls (also changed throwInvalidReact to recordError)
- validateUseMemo
- dropManualMemoization
- validateNoRefAccessInRender
- validateNoSetStateInRender
- validateNoImpureFunctionsInRender
- validateNoFreezingKnownMutableFunctions
- validateExhaustiveDependencies

Each pass now calls fn.env.recordErrors() instead of returning errors.asResult().
Pipeline.ts call sites updated to remove tryRecord() wrappers and .unwrap().
… tolerance

Update remaining validation passes to record errors on env:
- validateMemoizedEffectDependencies
- validatePreservedManualMemoization
- validateSourceLocations (added env parameter)
- validateContextVariableLValues (changed throwTodo to recordError)
- validateLocalsNotReassignedAfterRender (changed throw to recordError)
- validateNoDerivedComputationsInEffects (changed throw to recordError)

Update inference passes:
- inferMutationAliasingEffects: return void, errors on env
- inferMutationAliasingRanges: return Array<AliasingEffect> directly, errors on env

Update codegen:
- codegenFunction: return CodegenFunction directly, errors on env
- codegenReactiveFunction: same pattern

Update Pipeline.ts to call all passes directly without tryRecord/unwrap.
Also update AnalyseFunctions.ts which called inferMutationAliasingRanges.
Add test fixture demonstrating fault tolerance: the compiler now reports
both a mutation error and a ref access error in the same function, where
previously only one would be reported before bailing out.

Update plan doc to mark all phases as complete.
…ing throws

Remove `tryRecord()` from the compilation pipeline now that all passes record
errors directly via `env.recordError()` / `env.recordErrors()`. A single
catch-all try/catch in Program.ts provides the safety net for any pass that
incorrectly throws instead of recording.

Key changes:
- Remove all ~64 `env.tryRecord()` wrappers in Pipeline.ts
- Delete `tryRecord()` method from Environment.ts
- Add `CompileUnexpectedThrow` logger event so thrown errors are detectable
- Log `CompileUnexpectedThrow` in Program.ts catch-all for non-invariant throws
- Fail snap tests on `CompileUnexpectedThrow` to surface pass bugs in dev
- Convert throwTodo/throwDiagnostic calls in HIRBuilder (fbt, this),
  CodegenReactiveFunction (for-in/for-of), and BuildReactiveFunction to
  record errors or use invariants as appropriate
- Remove try/catch from BuildHIR's lower() since inner throws are now recorded
- CollectOptionalChainDependencies: return null instead of throwing on
  unsupported optional chain patterns (graceful optimization skip)
…env.recordError()

Removes unnecessary indirection in 17 compiler passes that previously
accumulated errors in a local `CompilerError` instance before flushing
them to `env.recordErrors()` at the end of each pass. Errors are now
emitted directly via `env.recordError()` as they're discovered.

For passes with recursive error-detection patterns (ValidateNoRefAccessInRender,
ValidateNoSetStateInRender), the internal accumulator is kept but flushed
via individual `recordError()` calls. For InferMutationAliasingRanges,
a `shouldRecordErrors` flag preserves the conditional suppression logic.
For TransformFire, the throw-based error propagation is replaced with
direct recording plus an early-exit check in Pipeline.ts.
@everettbu everettbu added CLA Signed React Core Team Opened by a member of the React Core Team labels Feb 21, 2026
@greptile-apps

greptile-apps Bot commented Feb 21, 2026

Copy link
Copy Markdown

Greptile Summary

This PR implements fault tolerance in the React Compiler by removing local CompilerError accumulators from 17 compiler passes and routing all errors through Environment.recordError(). The pipeline now runs all passes to completion and aggregates errors at the end, returning Result<CodegenFunction, CompilerError> instead of throwing on the first error encountered.

  • Adds recordError(), recordErrors(), hasErrors(), and aggregateErrors() to Environment, with invariant errors still thrown immediately
  • Changes lower() to always produce an HIRFunction (partial HIR on error), with best-effort handling for previously-unsupported constructs like var (treated as let), empty for-loop init/test, and expression-based for-loop init
  • Updates runWithEnvironment/compileFn to return Result and check env.hasErrors() at pipeline end
  • For passes with recursive error-detection patterns (ValidateNoRefAccessInRender, ValidateNoSetStateInRender), internal accumulators are kept but flushed via individual recordError() calls
  • InferMutationAliasingRanges uses a shouldRecordErrors flag to preserve the conditional suppression logic (only records when enableValidations && !isFunctionExpression)
  • Adds CompileUnexpectedThrow logger event and snap test detection for passes that incorrectly throw instead of recording errors
  • CollectOptionalChainDependencies now returns null instead of throwing for unsupported optional chain patterns, allowing previously-erroring fixtures to compile successfully
  • New test fixtures verify fault tolerance: multiple independent errors are reported together rather than stopping at the first

Confidence Score: 4/5

  • This PR is a well-structured refactor with comprehensive test coverage and no behavioral regressions in the happy path.
  • The changes are extensive (79 files) but follow a consistent, mechanical pattern: remove local error accumulator, record errors directly on Environment, simplify return types. The core infrastructure in Environment.ts is clean and correctly handles the invariant re-throw case. Test fixture updates confirm expected behavioral changes. The only minor concern is a style inconsistency in ValidateContextVariableLValues.ts (fn.env vs env parameter), which is harmless in practice.
  • BuildHIR.ts has the most complex changes (partial HIR construction for unsupported syntax), and InferMutationAliasingRanges.ts has the shouldRecordErrors conditional logic that should be verified against the original validation gating.

Important Files Changed

Filename Overview
compiler/packages/babel-plugin-react-compiler/src/HIR/Environment.ts Adds core error accumulation infrastructure: #errors field, recordError() (with Invariant re-throw), recordErrors(), hasErrors(), aggregateErrors(). Clean, well-designed API.
compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Pipeline.ts Changes runWithEnvironment/compileFn to return Result<CodegenFunction, CompilerError>. Removes .unwrap() calls on passes, checks env.hasErrors() at end of pipeline. Minor whitespace changes (blank lines).
compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Program.ts Updates tryCompileFunction to handle Result from compileFn. Adds detection of unexpected throws (non-invariant CompilerErrors) via new CompileUnexpectedThrow event.
compiler/packages/babel-plugin-react-compiler/src/HIR/BuildHIR.ts Major refactor: lower() now always returns HIRFunction instead of Result. All builder.errors.push() calls replaced with builder.recordError(). Adds fault-tolerant handling for var (treats as let), empty for-init/test, and expression-based for-init. Removes effects field from return (not in type).
compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts Removes local errors: CompilerError accumulator, adds recordError() method that delegates to env.recordError(). resolveBinding and build() now record errors instead of throwing.
compiler/packages/babel-plugin-react-compiler/src/HIR/CollectOptionalChainDependencies.ts Changes throwTodo to return null for unexpected terminal kinds in optional chain fallthrough, enabling the pipeline to continue gracefully.
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/BuildReactiveFunction.ts Changes throwTodo to CompilerError.invariant for non-branch test blocks, reflecting that this case should now be unreachable after earlier pipeline changes.
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/CodegenReactiveFunction.ts Removes local errors accumulator from Context and codegenReactiveFunction. All throwTodo calls replaced with cx.recordError() + early returns. codegenFunction returns CodegenFunction directly instead of Result.
compiler/packages/babel-plugin-react-compiler/src/Inference/InferMutationAliasingRanges.ts Replaces local error accumulation with shouldRecordErrors flag that correctly preserves conditional suppression logic (!isFunctionExpression && env.enableValidations). Passes `Environment
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateContextVariableLValues.ts Converts from throw-based to record-based error reporting. Passes Environment through recursive calls. Minor inconsistency: uses fn.env in default case instead of the env parameter (harmless since they're the same object).
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateNoRefAccessInRender.ts Keeps internal CompilerError accumulator for recursive analysis, but flushes to fn.env.recordError() at the top level. Inner function expressions use separate innerErrors for detection (consistent with original behavior).
compiler/packages/snap/src/compiler.ts Adds detection of CompileUnexpectedThrow events in test runner, failing tests when passes throw instead of recording errors.

Last reviewed commit: ac48dcd

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

79 files reviewed, 1 comment

Edit Code Review Agent Settings | Greptile

description: `Handle '${value.kind} lvalues`,
suggestions: null,
});
fn.env.recordError(

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Inconsistent use of fn.env vs env parameter

In the default branch, fn.env.recordError(...) is used directly, while the rest of the function consistently uses the env parameter (which is threaded through for recursive calls into inner function expressions). These happen to be the same Environment instance in practice (inner HIRFunction objects share the same env), so this is not a bug, but for consistency with the rest of the function, consider using env here instead of fn.env.

Suggested change
fn.env.recordError(
env.recordError(

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Prompt To Fix With AI
This is a comment left during a code review.
Path: compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateContextVariableLValues.ts
Line: 74

Comment:
**Inconsistent use of `fn.env` vs `env` parameter**

In the `default` branch, `fn.env.recordError(...)` is used directly, while the rest of the function consistently uses the `env` parameter (which is threaded through for recursive calls into inner function expressions). These happen to be the same `Environment` instance in practice (inner `HIRFunction` objects share the same env), so this is not a bug, but for consistency with the rest of the function, consider using `env` here instead of `fn.env`.

```suggestion
            env.recordError(
```

<sub>Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!</sub>

How can I resolve this? If you propose a fix, please make it concise.

@everettbu

Copy link
Copy Markdown
Author

Upstream PR was closed or merged. Code is synced via branch mirror.

@everettbu everettbu closed this Feb 23, 2026
@everettbu
everettbu deleted the pr35851 branch February 23, 2026 17:34
@everettbu
everettbu restored the pr35851 branch February 23, 2026 18:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed React Core Team Opened by a member of the React Core Team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants