[compiler] Phase 2+7: Wrap pipeline passes in tryRecord for fault tolerance (#35874)

- 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.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/35874).
* #35888
* #35884
* #35883
* #35882
* #35881
* #35880
* #35879
* #35878
* #35877
* #35876
* #35875
* __->__ #35874
This commit is contained in:
Joseph Savona
2026-02-23 15:26:28 -08:00
committed by GitHub
parent eca778cf8b
commit 426a394845
26 changed files with 634 additions and 90 deletions

View File

@@ -51,20 +51,20 @@ Add error accumulation to the `Environment` class so that any pass can record er
Change `runWithEnvironment` to run all passes and check for errors at the end instead of letting exceptions propagate.
- [ ] **2.1 Change `runWithEnvironment` return type** (`src/Entrypoint/Pipeline.ts`)
- [x] **2.1 Change `runWithEnvironment` return type** (`src/Entrypoint/Pipeline.ts`)
- Change return type from `CodegenFunction` to `Result<CodegenFunction, CompilerError>`
- At the end of the pipeline, check `env.hasErrors()`:
- If no errors: return `Ok(ast)`
- If errors: return `Err(env.aggregateErrors())`
- [ ] **2.2 Update `compileFn` to propagate the Result** (`src/Entrypoint/Pipeline.ts`)
- [x] **2.2 Update `compileFn` to propagate the Result** (`src/Entrypoint/Pipeline.ts`)
- Change `compileFn` return type from `CodegenFunction` to `Result<CodegenFunction, CompilerError>`
- Propagate the Result from `runWithEnvironment`
- [ ] **2.3 Update `run` to propagate the Result** (`src/Entrypoint/Pipeline.ts`)
- [x] **2.3 Update `run` to propagate the Result** (`src/Entrypoint/Pipeline.ts`)
- Same change for the internal `run` function
- [ ] **2.4 Update callers in Program.ts** (`src/Entrypoint/Program.ts`)
- [x] **2.4 Update callers in Program.ts** (`src/Entrypoint/Program.ts`)
- In `tryCompileFunction`, change from try/catch around `compileFn` to handling the `Result`:
- If `Ok(codegenFn)`: return the compiled function
- If `Err(compilerError)`: return `{kind: 'error', error: compilerError}`
@@ -248,31 +248,31 @@ The inference passes are the most critical to handle correctly because they prod
Walk through `runWithEnvironment` and wrap each pass call site. This is the integration work tying Phases 3-6 together.
- [ ] **7.1 Wrap `lower()` call** (line 163)
- [x] **7.1 Wrap `lower()` call** (line 163)
- Change from `lower(func, env).unwrap()` to `lower(func, env)` (direct return after Phase 3.1)
- [ ] **7.2 Wrap validation calls that use `.unwrap()`** (lines 169-303)
- [x] **7.2 Wrap validation calls that use `.unwrap()`** (lines 169-303)
- Remove `.unwrap()` from all validation calls after they're updated in Phase 4
- For validations guarded by `env.enableValidations`, keep the guard but remove the `.unwrap()`
- [ ] **7.3 Wrap inference calls** (lines 233-267)
- [x] **7.3 Wrap inference calls** (lines 233-267)
- After Phase 5, `inferMutationAliasingEffects` and `inferMutationAliasingRanges` record errors directly
- Remove the `mutabilityAliasingErrors` / `mutabilityAliasingRangeErrors` variables and their conditional throw logic
- [ ] **7.4 Wrap `env.logErrors()` calls** (lines 286-331)
- [x] **7.4 Wrap `env.logErrors()` calls** (lines 286-331)
- After Phase 4.13-4.16, these passes record on env directly
- Remove the `env.logErrors()` wrapper calls
- [ ] **7.5 Wrap codegen** (lines 575-578)
- [x] **7.5 Wrap codegen** (lines 575-578)
- After Phase 6.1, `codegenFunction` returns directly
- Remove the `.unwrap()`
- [ ] **7.6 Add final error check** (end of `runWithEnvironment`)
- [x] **7.6 Add final error check** (end of `runWithEnvironment`)
- After all passes complete, check `env.hasErrors()`
- If no errors: return `Ok(ast)`
- If errors: return `Err(env.aggregateErrors())`
- [ ] **7.7 Consider wrapping each pass in `env.tryRecord()`** as a safety net
- [x] **7.7 Consider wrapping each pass in `env.tryRecord()`** as a safety net
- Even after individual passes are updated, wrapping each pass call in `env.tryRecord()` provides defense-in-depth
- If a pass unexpectedly throws a CompilerError (e.g., from a code path we missed), it gets caught and recorded rather than aborting the pipeline
- Non-CompilerError exceptions and invariants still propagate immediately
@@ -318,3 +318,10 @@ Walk through `runWithEnvironment` and wrap each pass call site. This is the inte
- The `assertConsistentIdentifiers`, `assertTerminalSuccessorsExist`, `assertTerminalPredsExist`, `assertValidBlockNesting`, `assertValidMutableRanges`, `assertWellFormedBreakTargets`, `assertScopeInstructionsWithinScopes` assertion functions should continue to throw — they are invariant checks on internal data structure consistency
- The `panicThreshold` mechanism in Program.ts should continue to work — it now operates on the aggregated error from the Result rather than a caught exception, but the behavior is the same
## Key Learnings
* **Phase 2+7 (Pipeline tryRecord wrapping) was sufficient for basic fault tolerance.** Wrapping all passes in `env.tryRecord()` immediately enabled the compiler to continue past errors that previously threw. This caused 52 test fixtures to produce additional errors that were previously masked by the first error bailing out. For example, `error.todo-reassign-const` previously reported only "Support destructuring of context variables" but now also reports the immutability violation.
* **Lint-only passes (Pattern B: `env.logErrors()`) should not use `tryRecord()`/`recordError()`** because those errors are intentionally non-blocking. They are reported via the logger only and should not cause the pipeline to return `Err`. The `logErrors` pattern was kept for `validateNoDerivedComputationsInEffects_exp`, `validateNoSetStateInEffects`, `validateNoJSXInTryStatement`, and `validateStaticComponents`.
* **Inference passes that return `Result` with validation errors** (`inferMutationAliasingEffects`, `inferMutationAliasingRanges`) were changed to record errors via `env.recordErrors()` instead of throwing, allowing subsequent passes to proceed.
* **Value-producing passes** (`memoizeFbtAndMacroOperandsInSameScope`, `renameVariables`, `buildReactiveFunction`) need safe default values when wrapped in `tryRecord()` since the callback can't return values. We initialize with empty defaults (e.g., `new Set()`) before the `tryRecord()` call.

View File

@@ -9,8 +9,11 @@ import {NodePath} from '@babel/traverse';
import * as t from '@babel/types';
import prettyFormat from 'pretty-format';
import {CompilerOutputMode, Logger, ProgramContext} from '.';
import {CompilerError} from '../CompilerError';
import {Err, Ok, Result} from '../Utils/Result';
import {
HIRFunction,
IdentifierId,
ReactiveFunction,
assertConsistentIdentifiers,
assertTerminalPredsExist,
@@ -89,7 +92,6 @@ import {validateNoJSXInTryStatement} from '../Validation/ValidateNoJSXInTryState
import {propagateScopeDependenciesHIR} from '../HIR/PropagateScopeDependenciesHIR';
import {outlineJSX} from '../Optimization/OutlineJsx';
import {optimizePropsMethodCalls} from '../Optimization/OptimizePropsMethodCalls';
import {validateNoImpureFunctionsInRender} from '../Validation/ValidateNoImpureFunctionsInRender';
import {validateStaticComponents} from '../Validation/ValidateStaticComponents';
import {validateNoFreezingKnownMutableFunctions} from '../Validation/ValidateNoFreezingKnownMutableFunctions';
import {inferMutationAliasingEffects} from '../Inference/InferMutationAliasingEffects';
@@ -118,7 +120,7 @@ function run(
logger: Logger | null,
filename: string | null,
code: string | null,
): CodegenFunction {
): Result<CodegenFunction, CompilerError> {
const contextIdentifiers = findContextIdentifiers(func);
const env = new Environment(
func.scope,
@@ -149,7 +151,7 @@ function runWithEnvironment(
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
>,
env: Environment,
): CodegenFunction {
): Result<CodegenFunction, CompilerError> {
const log = (value: CompilerPipelineValue): void => {
env.logger?.debugLogIRs?.(value);
};
@@ -159,11 +161,17 @@ function runWithEnvironment(
pruneMaybeThrows(hir);
log({kind: 'hir', name: 'PruneMaybeThrows', value: hir});
validateContextVariableLValues(hir);
validateUseMemo(hir).unwrap();
env.tryRecord(() => {
validateContextVariableLValues(hir);
});
env.tryRecord(() => {
validateUseMemo(hir).unwrap();
});
if (env.enableDropManualMemoization) {
dropManualMemoization(hir).unwrap();
env.tryRecord(() => {
dropManualMemoization(hir).unwrap();
});
log({kind: 'hir', name: 'DropManualMemoization', value: hir});
}
@@ -196,10 +204,14 @@ function runWithEnvironment(
if (env.enableValidations) {
if (env.config.validateHooksUsage) {
validateHooksUsage(hir).unwrap();
env.tryRecord(() => {
validateHooksUsage(hir).unwrap();
});
}
if (env.config.validateNoCapitalizedCalls) {
validateNoCapitalizedCalls(hir).unwrap();
env.tryRecord(() => {
validateNoCapitalizedCalls(hir).unwrap();
});
}
}
@@ -213,7 +225,7 @@ function runWithEnvironment(
log({kind: 'hir', name: 'InferMutationAliasingEffects', value: hir});
if (env.enableValidations) {
if (mutabilityAliasingErrors.isErr()) {
throw mutabilityAliasingErrors.unwrapErr();
env.recordErrors(mutabilityAliasingErrors.unwrapErr());
}
}
@@ -234,9 +246,11 @@ function runWithEnvironment(
log({kind: 'hir', name: 'InferMutationAliasingRanges', value: hir});
if (env.enableValidations) {
if (mutabilityAliasingRangeErrors.isErr()) {
throw mutabilityAliasingRangeErrors.unwrapErr();
env.recordErrors(mutabilityAliasingRangeErrors.unwrapErr());
}
validateLocalsNotReassignedAfterRender(hir);
env.tryRecord(() => {
validateLocalsNotReassignedAfterRender(hir);
});
}
if (env.enableValidations) {
@@ -245,11 +259,15 @@ function runWithEnvironment(
}
if (env.config.validateRefAccessDuringRender) {
validateNoRefAccessInRender(hir).unwrap();
env.tryRecord(() => {
validateNoRefAccessInRender(hir).unwrap();
});
}
if (env.config.validateNoSetStateInRender) {
validateNoSetStateInRender(hir).unwrap();
env.tryRecord(() => {
validateNoSetStateInRender(hir).unwrap();
});
}
if (
@@ -258,7 +276,9 @@ function runWithEnvironment(
) {
env.logErrors(validateNoDerivedComputationsInEffects_exp(hir));
} else if (env.config.validateNoDerivedComputationsInEffects) {
validateNoDerivedComputationsInEffects(hir);
env.tryRecord(() => {
validateNoDerivedComputationsInEffects(hir);
});
}
if (env.config.validateNoSetStateInEffects && env.outputMode === 'lint') {
@@ -269,11 +289,9 @@ function runWithEnvironment(
env.logErrors(validateNoJSXInTryStatement(hir));
}
if (env.config.validateNoImpureFunctionsInRender) {
validateNoImpureFunctionsInRender(hir).unwrap();
}
validateNoFreezingKnownMutableFunctions(hir).unwrap();
env.tryRecord(() => {
validateNoFreezingKnownMutableFunctions(hir).unwrap();
});
}
inferReactivePlaces(hir);
@@ -285,7 +303,9 @@ function runWithEnvironment(
env.config.validateExhaustiveEffectDependencies
) {
// NOTE: this relies on reactivity inference running first
validateExhaustiveDependencies(hir).unwrap();
env.tryRecord(() => {
validateExhaustiveDependencies(hir).unwrap();
});
}
}
@@ -314,7 +334,8 @@ function runWithEnvironment(
log({kind: 'hir', name: 'InferReactiveScopeVariables', value: hir});
}
const fbtOperands = memoizeFbtAndMacroOperandsInSameScope(hir);
let fbtOperands: Set<IdentifierId> = new Set();
fbtOperands = memoizeFbtAndMacroOperandsInSameScope(hir);
log({
kind: 'hir',
name: 'MemoizeFbtAndMacroOperandsInSameScope',
@@ -406,7 +427,8 @@ function runWithEnvironment(
value: hir,
});
const reactiveFunction = buildReactiveFunction(hir);
let reactiveFunction!: ReactiveFunction;
reactiveFunction = buildReactiveFunction(hir);
log({
kind: 'reactive',
name: 'BuildReactiveFunction',
@@ -493,7 +515,8 @@ function runWithEnvironment(
value: reactiveFunction,
});
const uniqueIdentifiers = renameVariables(reactiveFunction);
let uniqueIdentifiers: Set<string> = new Set();
uniqueIdentifiers = renameVariables(reactiveFunction);
log({
kind: 'reactive',
name: 'RenameVariables',
@@ -511,20 +534,29 @@ function runWithEnvironment(
env.config.enablePreserveExistingMemoizationGuarantees ||
env.config.validatePreserveExistingMemoizationGuarantees
) {
validatePreservedManualMemoization(reactiveFunction).unwrap();
env.tryRecord(() => {
validatePreservedManualMemoization(reactiveFunction).unwrap();
});
}
const ast = codegenFunction(reactiveFunction, {
const codegenResult = codegenFunction(reactiveFunction, {
uniqueIdentifiers,
fbtOperands,
}).unwrap();
});
if (codegenResult.isErr()) {
env.recordErrors(codegenResult.unwrapErr());
return Err(env.aggregateErrors());
}
const ast = codegenResult.unwrap();
log({kind: 'ast', name: 'Codegen', value: ast});
for (const outlined of ast.outlined) {
log({kind: 'ast', name: 'Codegen (outlined)', value: outlined.fn});
}
if (env.config.validateSourceLocations) {
validateSourceLocations(func, ast).unwrap();
env.tryRecord(() => {
validateSourceLocations(func, ast).unwrap();
});
}
/**
@@ -536,7 +568,10 @@ function runWithEnvironment(
throw new Error('unexpected error');
}
return ast;
if (env.hasErrors()) {
return Err(env.aggregateErrors());
}
return Ok(ast);
}
export function compileFn(
@@ -550,7 +585,7 @@ export function compileFn(
logger: Logger | null,
filename: string | null,
code: string | null,
): CodegenFunction {
): Result<CodegenFunction, CompilerError> {
return run(
func,
config,

View File

@@ -697,19 +697,21 @@ function tryCompileFunction(
}
try {
return {
kind: 'compile',
compiledFn: compileFn(
fn,
programContext.opts.environment,
fnType,
outputMode,
programContext,
programContext.opts.logger,
programContext.filename,
programContext.code,
),
};
const result = compileFn(
fn,
programContext.opts.environment,
fnType,
outputMode,
programContext,
programContext.opts.logger,
programContext.filename,
programContext.code,
);
if (result.isOk()) {
return {kind: 'compile', compiledFn: result.unwrap()};
} else {
return {kind: 'error', error: result.unwrapErr()};
}
} catch (err) {
return {kind: 'error', error: err};
}

View File

@@ -29,7 +29,7 @@ export const FIXTURE_ENTRYPOINT = {
## Error
```
Found 1 error:
Found 2 errors:
Error: This value cannot be modified
@@ -43,6 +43,32 @@ error.hook-call-freezes-captured-memberexpr.ts:13:2
14 | return <Stringify x={x} cb={cb} />;
15 | }
16 |
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `x` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
error.hook-call-freezes-captured-memberexpr.ts:9:25
7 | * After this custom hook call, it's no longer valid to mutate x.
8 | */
> 9 | const cb = useIdentity(() => {
| ^^^^^^^
> 10 | x.value++;
| ^^^^^^^^^^^^^^
> 11 | });
| ^^^^ This function may (indirectly) reassign or modify `x` after render
12 |
13 | x.value += count;
14 | return <Stringify x={x} cb={cb} />;
error.hook-call-freezes-captured-memberexpr.ts:10:4
8 | */
9 | const cb = useIdentity(() => {
> 10 | x.value++;
| ^ This modifies `x`
11 | });
12 |
13 | x.value += count;
```

View File

@@ -15,7 +15,7 @@ function component(a, b) {
## Error
```
Found 1 error:
Found 3 errors:
Error: useMemo() callbacks may not be async or generator functions
@@ -32,6 +32,37 @@ error.invalid-ReactUseMemo-async-callback.ts:2:24
5 | return x;
6 | }
7 |
Error: Found missing memoization dependencies
Missing dependencies can cause a value to update less often than it should, resulting in stale UI.
error.invalid-ReactUseMemo-async-callback.ts:3:10
1 | function component(a, b) {
2 | let x = React.useMemo(async () => {
> 3 | await a;
| ^ Missing dependency `a`
4 | }, []);
5 | return x;
6 | }
Inferred dependencies: `[a]`
Compilation Skipped: Existing memoization could not be preserved
React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected. The inferred dependency was `a`, but the source dependencies were []. Inferred dependency not present in source.
error.invalid-ReactUseMemo-async-callback.ts:2:24
1 | function component(a, b) {
> 2 | let x = React.useMemo(async () => {
| ^^^^^^^^^^^^^
> 3 | await a;
| ^^^^^^^^^^^^
> 4 | }, []);
| ^^^^ Could not preserve existing manual memoization
5 | return x;
6 | }
7 |
```

View File

@@ -22,7 +22,7 @@ function Component({item, cond}) {
## Error
```
Found 2 errors:
Found 3 errors:
Error: Calling setState from useMemo may trigger an infinite loop
@@ -49,6 +49,39 @@ error.invalid-conditional-setState-in-useMemo.ts:8:6
9 | }
10 | }, [cond, key, init]);
11 |
Error: Found missing/extra memoization dependencies
Missing dependencies can cause a value to update less often than it should, resulting in stale UI. Extra dependencies can cause a value to update more often than it should, resulting in performance problems such as excessive renders or effects firing too often.
error.invalid-conditional-setState-in-useMemo.ts:7:18
5 | useMemo(() => {
6 | if (cond) {
> 7 | setPrevItem(item);
| ^^^^ Missing dependency `item`
8 | setState(0);
9 | }
10 | }, [cond, key, init]);
error.invalid-conditional-setState-in-useMemo.ts:10:12
8 | setState(0);
9 | }
> 10 | }, [cond, key, init]);
| ^^^ Unnecessary dependency `key`. Values declared outside of a component/hook should not be listed as dependencies as the component will not re-render if they change
11 |
12 | return state;
13 | }
error.invalid-conditional-setState-in-useMemo.ts:10:17
8 | setState(0);
9 | }
> 10 | }, [cond, key, init]);
| ^^^^ Unnecessary dependency `init`. Values declared outside of a component/hook should not be listed as dependencies as the component will not re-render if they change
11 |
12 | return state;
13 | }
Inferred dependencies: `[cond, item]`
```

View File

@@ -16,7 +16,7 @@ function useInvalidMutation(options) {
## Error
```
Found 1 error:
Found 2 errors:
Error: This value cannot be modified
@@ -30,6 +30,27 @@ error.invalid-mutation-in-closure.ts:4:4
5 | }
6 | return test;
7 | }
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `options` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
error.invalid-mutation-in-closure.ts:6:9
4 | options.foo = 'bar';
5 | }
> 6 | return test;
| ^^^^ This function may (indirectly) reassign or modify `options` after render
7 | }
8 |
error.invalid-mutation-in-closure.ts:4:4
2 | function test() {
3 | foo(options.foo); // error should not point on this line
> 4 | options.foo = 'bar';
| ^^^^^^^ This modifies `options`
5 | }
6 | return test;
7 | }
```

View File

@@ -15,7 +15,7 @@ function useFoo() {
## Error
```
Found 1 error:
Found 2 errors:
Error: Cannot reassign variable after render completes
@@ -29,6 +29,31 @@ error.invalid-reassign-local-in-hook-return-value.ts:4:4
5 | };
6 | }
7 |
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `x` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
error.invalid-reassign-local-in-hook-return-value.ts:3:9
1 | function useFoo() {
2 | let x = 0;
> 3 | return value => {
| ^^^^^^^^^^
> 4 | x = value;
| ^^^^^^^^^^^^^^
> 5 | };
| ^^^^ This function may (indirectly) reassign or modify `x` after render
6 | }
7 |
error.invalid-reassign-local-in-hook-return-value.ts:4:4
2 | let x = 0;
3 | return value => {
> 4 | x = value;
| ^ This modifies `x`
5 | };
6 | }
7 |
```

View File

@@ -47,7 +47,7 @@ function Component() {
## Error
```
Found 1 error:
Found 2 errors:
Error: Cannot reassign variable after render completes
@@ -61,6 +61,32 @@ error.invalid-reassign-local-variable-in-effect.ts:7:4
8 | };
9 |
10 | const onMount = newValue => {
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `local` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
error.invalid-reassign-local-variable-in-effect.ts:33:12
31 | };
32 |
> 33 | useEffect(() => {
| ^^^^^^^
> 34 | onMount();
| ^^^^^^^^^^^^^^
> 35 | }, [onMount]);
| ^^^^ This function may (indirectly) reassign or modify `local` after render
36 |
37 | return 'ok';
38 | }
error.invalid-reassign-local-variable-in-effect.ts:7:4
5 |
6 | const reassignLocal = newValue => {
> 7 | local = newValue;
| ^^^^^ This modifies `local`
8 | };
9 |
10 | const onMount = newValue => {
```

View File

@@ -48,7 +48,7 @@ function Component() {
## Error
```
Found 1 error:
Found 2 errors:
Error: Cannot reassign variable after render completes
@@ -62,6 +62,32 @@ error.invalid-reassign-local-variable-in-hook-argument.ts:8:4
9 | };
10 |
11 | const callback = newValue => {
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `local` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
error.invalid-reassign-local-variable-in-hook-argument.ts:34:14
32 | };
33 |
> 34 | useIdentity(() => {
| ^^^^^^^
> 35 | callback();
| ^^^^^^^^^^^^^^^
> 36 | });
| ^^^^ This function may (indirectly) reassign or modify `local` after render
37 |
38 | return 'ok';
39 | }
error.invalid-reassign-local-variable-in-hook-argument.ts:8:4
6 |
7 | const reassignLocal = newValue => {
> 8 | local = newValue;
| ^^^^^ This modifies `local`
9 | };
10 |
11 | const callback = newValue => {
```

View File

@@ -41,7 +41,7 @@ function Component() {
## Error
```
Found 1 error:
Found 2 errors:
Error: Cannot reassign variable after render completes
@@ -55,6 +55,27 @@ error.invalid-reassign-local-variable-in-jsx-callback.ts:5:4
6 | };
7 |
8 | const onClick = newValue => {
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `local` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
error.invalid-reassign-local-variable-in-jsx-callback.ts:31:26
29 | };
30 |
> 31 | return <button onClick={onClick}>Submit</button>;
| ^^^^^^^ This function may (indirectly) reassign or modify `local` after render
32 | }
33 |
error.invalid-reassign-local-variable-in-jsx-callback.ts:5:4
3 |
4 | const reassignLocal = newValue => {
> 5 | local = newValue;
| ^^^^^ This modifies `local`
6 | };
7 |
8 | const onClick = newValue => {
```

View File

@@ -26,7 +26,7 @@ function useKeyedState({key, init}) {
## Error
```
Found 1 error:
Found 3 errors:
Error: Calling setState from useMemo may trigger an infinite loop
@@ -40,6 +40,61 @@ error.invalid-setState-in-useMemo-indirect-useCallback.ts:13:4
14 | }, [key, init]);
15 |
16 | return state;
Error: Found missing memoization dependencies
Missing dependencies can cause a value to update less often than it should, resulting in stale UI.
error.invalid-setState-in-useMemo-indirect-useCallback.ts:9:13
7 | const fn = useCallback(() => {
8 | setPrevKey(key);
> 9 | setState(init);
| ^^^^ Missing dependency `init`
10 | });
11 |
12 | useMemo(() => {
error.invalid-setState-in-useMemo-indirect-useCallback.ts:8:15
6 |
7 | const fn = useCallback(() => {
> 8 | setPrevKey(key);
| ^^^ Missing dependency `key`
9 | setState(init);
10 | });
11 |
Error: Found missing/extra memoization dependencies
Missing dependencies can cause a value to update less often than it should, resulting in stale UI. Extra dependencies can cause a value to update more often than it should, resulting in performance problems such as excessive renders or effects firing too often.
error.invalid-setState-in-useMemo-indirect-useCallback.ts:13:4
11 |
12 | useMemo(() => {
> 13 | fn();
| ^^ Missing dependency `fn`
14 | }, [key, init]);
15 |
16 | return state;
error.invalid-setState-in-useMemo-indirect-useCallback.ts:14:6
12 | useMemo(() => {
13 | fn();
> 14 | }, [key, init]);
| ^^^ Unnecessary dependency `key`
15 |
16 | return state;
17 | }
error.invalid-setState-in-useMemo-indirect-useCallback.ts:14:11
12 | useMemo(() => {
13 | fn();
> 14 | }, [key, init]);
| ^^^^ Unnecessary dependency `init`
15 |
16 | return state;
17 | }
Inferred dependencies: `[fn]`
```

View File

@@ -15,7 +15,7 @@ function component(a, b) {
## Error
```
Found 1 error:
Found 3 errors:
Error: useMemo() callbacks may not be async or generator functions
@@ -32,6 +32,37 @@ error.invalid-useMemo-async-callback.ts:2:18
5 | return x;
6 | }
7 |
Error: Found missing memoization dependencies
Missing dependencies can cause a value to update less often than it should, resulting in stale UI.
error.invalid-useMemo-async-callback.ts:3:10
1 | function component(a, b) {
2 | let x = useMemo(async () => {
> 3 | await a;
| ^ Missing dependency `a`
4 | }, []);
5 | return x;
6 | }
Inferred dependencies: `[a]`
Compilation Skipped: Existing memoization could not be preserved
React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected. The inferred dependency was `a`, but the source dependencies were []. Inferred dependency not present in source.
error.invalid-useMemo-async-callback.ts:2:18
1 | function component(a, b) {
> 2 | let x = useMemo(async () => {
| ^^^^^^^^^^^^^
> 3 | await a;
| ^^^^^^^^^^^^
> 4 | }, []);
| ^^^^ Could not preserve existing manual memoization
5 | return x;
6 | }
7 |
```

View File

@@ -13,7 +13,7 @@ function component(a, b) {
## Error
```
Found 1 error:
Found 3 errors:
Error: useMemo() callbacks may not accept parameters
@@ -26,6 +26,32 @@ error.invalid-useMemo-callback-args.ts:2:18
3 | return x;
4 | }
5 |
Error: Found missing memoization dependencies
Missing dependencies can cause a value to update less often than it should, resulting in stale UI.
error.invalid-useMemo-callback-args.ts:2:23
1 | function component(a, b) {
> 2 | let x = useMemo(c => a, []);
| ^ Missing dependency `a`
3 | return x;
4 | }
5 |
Inferred dependencies: `[a]`
Compilation Skipped: Existing memoization could not be preserved
React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected. The inferred dependency was `a`, but the source dependencies were []. Inferred dependency not present in source.
error.invalid-useMemo-callback-args.ts:2:18
1 | function component(a, b) {
> 2 | let x = useMemo(c => a, []);
| ^^^^^^ Could not preserve existing manual memoization
3 | return x;
4 | }
5 |
```

View File

@@ -32,7 +32,7 @@ export const FIXTURE_ENTRYPOINT = {
## Error
```
Found 1 error:
Found 2 errors:
Error: Cannot reassign variable after render completes
@@ -46,6 +46,28 @@ error.mutable-range-shared-inner-outer-function.ts:8:6
9 | b = [];
10 | } else {
11 | a = {};
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `a` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
error.mutable-range-shared-inner-outer-function.ts:17:23
15 | b.push(false);
16 | };
> 17 | return <div onClick={f} />;
| ^ This function may (indirectly) reassign or modify `a` after render
18 | }
19 |
20 | export const FIXTURE_ENTRYPOINT = {
error.mutable-range-shared-inner-outer-function.ts:8:6
6 | const f = () => {
7 | if (cond) {
> 8 | a = {};
| ^ This modifies `a`
9 | b = [];
10 | } else {
11 | a = {};
```

View File

@@ -29,7 +29,7 @@ function useHook(parentRef) {
## Error
```
Found 1 error:
Found 2 errors:
Error: This value cannot be modified
@@ -43,6 +43,27 @@ error.todo-allow-assigning-to-inferred-ref-prop-in-callback.ts:15:8
16 | }
17 | }
18 | };
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `parentRef` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
error.todo-allow-assigning-to-inferred-ref-prop-in-callback.ts:19:9
17 | }
18 | };
> 19 | return handler;
| ^^^^^^^ This function may (indirectly) reassign or modify `parentRef` after render
20 | }
21 |
error.todo-allow-assigning-to-inferred-ref-prop-in-callback.ts:15:8
13 | } else {
14 | // So this assignment fails since we don't know its a ref
> 15 | parentRef.current = instance;
| ^^^^^^^^^ This modifies `parentRef`
16 | }
17 | }
18 | };
```

View File

@@ -17,7 +17,7 @@ function Component() {
## Error
```
Found 1 error:
Found 2 errors:
Error: Cannot reassign variable after render completes
@@ -31,6 +31,27 @@ error.todo-function-expression-references-later-variable-declaration.ts:3:4
4 | };
5 | let onClick;
6 |
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `onClick` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
error.todo-function-expression-references-later-variable-declaration.ts:7:23
5 | let onClick;
6 |
> 7 | return <div onClick={callback} />;
| ^^^^^^^^ This function may (indirectly) reassign or modify `onClick` after render
8 | }
9 |
error.todo-function-expression-references-later-variable-declaration.ts:3:4
1 | function Component() {
2 | let callback = () => {
> 3 | onClick = () => {};
| ^^^^^^^ This modifies `onClick`
4 | };
5 | let onClick;
6 |
```

View File

@@ -21,7 +21,7 @@ function Component({foo}) {
## Error
```
Found 1 error:
Found 2 errors:
Todo: Support destructuring of context variables
@@ -33,6 +33,19 @@ error.todo-reassign-const.ts:3:20
4 | let bar = foo.bar;
5 | return (
6 | <Stringify
Error: This value cannot be modified
Modifying component props or hook arguments is not allowed. Consider using a local variable instead.
error.todo-reassign-const.ts:8:8
6 | <Stringify
7 | handler={() => {
> 8 | foo = true;
| ^^^ `foo` cannot be modified
9 | }}
10 | />
11 | );
```

View File

@@ -51,7 +51,7 @@ function Component({x, y, z}) {
## Error
```
Found 4 errors:
Found 6 errors:
Error: Found missing/extra memoization dependencies
@@ -157,6 +157,48 @@ error.invalid-exhaustive-deps.ts:37:13
40 | }, []);
Inferred dependencies: `[ref]`
Compilation Skipped: Existing memoization could not be preserved
React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected. The inferred dependency was `x.y.z.a.b`, but the source dependencies were [x?.y.z.a?.b.z]. Inferred different dependency than source.
error.invalid-exhaustive-deps.ts:14:20
12 | // ok, not our job to type check nullability
13 | }, [x.y.z.a]);
> 14 | const c = useMemo(() => {
| ^^^^^^^
> 15 | return x?.y.z.a?.b;
| ^^^^^^^^^^^^^^^^^^^^^^^
> 16 | // error: too precise
| ^^^^^^^^^^^^^^^^^^^^^^^
> 17 | }, [x?.y.z.a?.b.z]);
| ^^^^ Could not preserve existing manual memoization
18 | const d = useMemo(() => {
19 | return x?.y?.[(console.log(y), z?.b)];
20 | // ok
Compilation Skipped: Existing memoization could not be preserved
React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected. The inferred dependency was `ref`, but the source dependencies were []. Inferred dependency not present in source.
error.invalid-exhaustive-deps.ts:35:21
33 | const ref2 = useRef(null);
34 | const ref = z ? ref1 : ref2;
> 35 | const cb = useMemo(() => {
| ^^^^^^^
> 36 | return () => {
| ^^^^^^^^^^^^^^^^^^
> 37 | return ref.current;
| ^^^^^^^^^^^^^^^^^^
> 38 | };
| ^^^^^^^^^^^^^^^^^^
> 39 | // error: ref is a stable type but reactive
| ^^^^^^^^^^^^^^^^^^
> 40 | }, []);
| ^^^^ Could not preserve existing manual memoization
41 | return <Stringify results={[a, b, c, d, e, f, cb]} />;
42 | }
43 |
```

View File

@@ -22,7 +22,7 @@ function useHook() {
## Error
```
Found 1 error:
Found 2 errors:
Error: Found missing memoization dependencies
@@ -38,6 +38,19 @@ error.invalid-missing-nonreactive-dep-unmemoized.ts:11:31
14 |
Inferred dependencies: `[object]`
Compilation Skipped: Existing memoization could not be preserved
React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected. The inferred dependency was `object`, but the source dependencies were []. Inferred dependency not present in source.
error.invalid-missing-nonreactive-dep-unmemoized.ts:11:24
9 | useIdentity();
10 | object.x = 0;
> 11 | const array = useMemo(() => [object], []);
| ^^^^^^^^^^^^^^ Could not preserve existing manual memoization
12 | return array;
13 | }
14 |
```

View File

@@ -42,7 +42,7 @@ function Component() {
## Error
```
Found 1 error:
Found 2 errors:
Error: Cannot reassign variable after render completes
@@ -56,6 +56,27 @@ error.invalid-reassign-local-variable-in-jsx-callback.ts:6:4
7 | };
8 |
9 | const onClick = newValue => {
Error: Cannot modify local variables after render completes
This argument is a function which may reassign or mutate `local` after render, which can cause inconsistent behavior on subsequent renders. Consider using state instead.
error.invalid-reassign-local-variable-in-jsx-callback.ts:32:26
30 | };
31 |
> 32 | return <button onClick={onClick}>Submit</button>;
| ^^^^^^^ This function may (indirectly) reassign or modify `local` after render
33 | }
34 |
error.invalid-reassign-local-variable-in-jsx-callback.ts:6:4
4 |
5 | const reassignLocal = newValue => {
> 6 | local = newValue;
| ^^^^^ This modifies `local`
7 | };
8 |
9 | const onClick = newValue => {
```

View File

@@ -31,7 +31,7 @@ function Component({content, refetch}) {
## Error
```
Found 1 error:
Found 2 errors:
Error: Cannot access variable before it is declared
@@ -52,6 +52,18 @@ Error: Cannot access variable before it is declared
20 |
21 | return <Foo data={data} onSubmit={onSubmit} />;
22 | }
Error: Found missing memoization dependencies
Missing dependencies can cause a value to update less often than it should, resulting in stale UI.
9 | // TDZ violation!
10 | const onRefetch = useCallback(() => {
> 11 | refetch(data);
| ^^^^ Missing dependency `data`
12 | }, [refetch]);
13 |
14 | // The context variable gets frozen here since it's passed to a hook
```

View File

@@ -30,7 +30,7 @@ function useFoo(input1) {
## Error
```
Found 1 error:
Found 2 errors:
Error: Found missing memoization dependencies
@@ -46,6 +46,23 @@ error.useMemo-unrelated-mutation-in-depslist.ts:18:14
21 | }
Inferred dependencies: `[x, y]`
Compilation Skipped: Existing memoization could not be preserved
React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected. The inferred dependency was `input1`, but the source dependencies were [y]. Inferred different dependency than source.
error.useMemo-unrelated-mutation-in-depslist.ts:16:27
14 | const x = {};
15 | const y = [input1];
> 16 | const memoized = useMemo(() => {
| ^^^^^^^
> 17 | return [y];
| ^^^^^^^^^^^^^^^
> 18 | }, [(mutate(x), y)]);
| ^^^^ Could not preserve existing manual memoization
19 |
20 | return [x, memoized];
21 | }
```

View File

@@ -16,29 +16,24 @@ function Component(props) {
## Error
```
Found 2 errors:
Found 1 error:
Error: Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)
Invariant: Unexpected empty block with `goto` terminal
error.invalid-hook-for.ts:4:9
2 | let i = 0;
3 | for (let x = 0; useHook(x) < 10; useHook(i), x++) {
> 4 | i += useHook(x);
| ^^^^^^^ Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)
5 | }
6 | return i;
7 | }
Block bb5 is empty.
Error: Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)
error.invalid-hook-for.ts:3:35
error.invalid-hook-for.ts:3:2
1 | function Component(props) {
2 | let i = 0;
> 3 | for (let x = 0; useHook(x) < 10; useHook(i), x++) {
| ^^^^^^^ Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)
4 | i += useHook(x);
5 | }
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> 4 | i += useHook(x);
| ^^^^^^^^^^^^^^^^^^^^
> 5 | }
| ^^^^ Unexpected empty block with `goto` terminal
6 | return i;
7 | }
8 |
```

View File

@@ -25,6 +25,7 @@ export const FIXTURE_ENTRYPOINT = {
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { useRef } from "react";
const useControllableState = (options) => {};

View File

@@ -57,7 +57,6 @@ testRule('plugin-recommended', TestRecommendedRules, {
],
invalid: [
{
// TODO: actually return multiple diagnostics in this case
name: 'Multiple diagnostic kinds from the same function are surfaced',
code: normalizeIndent`
import Child from './Child';
@@ -70,6 +69,7 @@ testRule('plugin-recommended', TestRecommendedRules, {
`,
errors: [
makeTestCaseError('Hooks must always be called in a consistent order'),
makeTestCaseError('Capitalized functions are reserved for components'),
],
},
{
@@ -128,6 +128,7 @@ testRule('plugin-recommended', TestRecommendedRules, {
makeTestCaseError(
'Calling setState from useMemo may trigger an infinite loop',
),
makeTestCaseError('Found extra memoization dependencies'),
],
},
],