Compare commits
41 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f706228d74 | ||
|
|
d6558f36e2 | ||
|
|
59d7c27087 | ||
|
|
9b2d8013ee | ||
|
|
e3e5d95cc4 | ||
|
|
426a394845 | ||
|
|
eca778cf8b | ||
|
|
0dbb43bc57 | ||
|
|
8b6b11f703 | ||
|
|
ab18f33d46 | ||
|
|
b16b768fbd | ||
|
|
2ba3065527 | ||
|
|
38cd020c1f | ||
|
|
f247ebaf44 | ||
|
|
3a2bee26d2 | ||
|
|
4842fbea02 | ||
|
|
61db53c179 | ||
|
|
4ac47537dd | ||
|
|
47d1ad1454 | ||
|
|
e8c6362678 | ||
|
|
03ca38e6e7 | ||
|
|
6066c782fe | ||
|
|
705055d7ac | ||
|
|
8374c2abf1 | ||
|
|
892c68605c | ||
|
|
cd515d7e22 | ||
|
|
78f5c504b7 | ||
|
|
e49335e961 | ||
|
|
57b79b0388 | ||
|
|
70890e7c58 | ||
|
|
f23aa1d9f5 | ||
|
|
49c3b270f9 | ||
|
|
c6bb26bf83 | ||
|
|
6a939d0b54 | ||
|
|
4c9d62d2b4 | ||
|
|
24f215ce8b | ||
|
|
eab523e2a9 | ||
|
|
272441a9ad | ||
|
|
b07aa7d643 | ||
|
|
2dd9b7cf76 | ||
|
|
65db1000b9 |
@@ -507,7 +507,6 @@ module.exports = {
|
||||
__IS_FIREFOX__: 'readonly',
|
||||
__IS_EDGE__: 'readonly',
|
||||
__IS_NATIVE__: 'readonly',
|
||||
__IS_INTERNAL_MCP_BUILD__: 'readonly',
|
||||
__IS_INTERNAL_VERSION__: 'readonly',
|
||||
chrome: 'readonly',
|
||||
},
|
||||
|
||||
@@ -29,6 +29,7 @@ jobs:
|
||||
- "7"
|
||||
- "8"
|
||||
- "9"
|
||||
- "10"
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
|
||||
@@ -215,12 +215,12 @@ const UseEffectEventHook = addHook(
|
||||
Feature flags are configured in `src/HIR/Environment.ts`, for example `enableJsxOutlining`. Test fixtures can override the active feature flags used for that fixture via a comment pragma on the first line of the fixture input, for example:
|
||||
|
||||
```javascript
|
||||
// enableJsxOutlining @enableChangeVariableCodegen:false
|
||||
// enableJsxOutlining @enableNameAnonymousFunctions:false
|
||||
|
||||
...code...
|
||||
```
|
||||
|
||||
Would enable the `enableJsxOutlining` feature and disable the `enableChangeVariableCodegen` feature.
|
||||
Would enable the `enableJsxOutlining` feature and disable the `enableNameAnonymousFunctions` feature.
|
||||
|
||||
## Debugging Tips
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
import { c as _c } from "react/compiler-runtime";
|
||||
export default function TestComponent(t0) {
|
||||
const $ = _c(2);
|
||||
const { x } = t0;
|
||||
let t1;
|
||||
if ($[0] !== x || true) {
|
||||
t1 = <Button>{x}</Button>;
|
||||
$[0] = x;
|
||||
$[1] = t1;
|
||||
} else {
|
||||
t1 = $[1];
|
||||
}
|
||||
return t1;
|
||||
}
|
||||
@@ -283,37 +283,6 @@ test('error is displayed when config has validation error', async ({page}) => {
|
||||
expect(output.replace(/\s+/g, ' ')).toContain('Unexpected compilationMode');
|
||||
});
|
||||
|
||||
test('disableMemoizationForDebugging flag works as expected', async ({
|
||||
page,
|
||||
}) => {
|
||||
const store: Store = {
|
||||
source: TEST_SOURCE,
|
||||
config: `import type { PluginOptions } from 'babel-plugin-react-compiler/dist';
|
||||
|
||||
({
|
||||
environment: {
|
||||
disableMemoizationForDebugging: true
|
||||
}
|
||||
} satisfies PluginOptions);`,
|
||||
showInternals: false,
|
||||
};
|
||||
const hash = encodeStore(store);
|
||||
await page.goto(`/#${hash}`, {waitUntil: 'networkidle'});
|
||||
await page.waitForFunction(isMonacoLoaded);
|
||||
await expandConfigs(page);
|
||||
await page.screenshot({
|
||||
fullPage: true,
|
||||
path: 'test-results/07-config-disableMemoizationForDebugging-flag.png',
|
||||
});
|
||||
|
||||
const text =
|
||||
(await page.locator('.monaco-editor-output').allInnerTexts()) ?? [];
|
||||
const output = await formatPrint(text);
|
||||
|
||||
expect(output).not.toEqual('');
|
||||
expect(output).toMatchSnapshot('disableMemoizationForDebugging-output.txt');
|
||||
});
|
||||
|
||||
test('error is displayed when source has syntax error', async ({page}) => {
|
||||
const syntaxErrorSource = `function TestComponent(props) {
|
||||
const oops = props.
|
||||
|
||||
331
compiler/fault-tolerance-overview.md
Normal file
331
compiler/fault-tolerance-overview.md
Normal file
@@ -0,0 +1,331 @@
|
||||
## React Compiler Fault Tolerance
|
||||
|
||||
Update React Compiler (@compiler/ directory) to always run all passes and return either the transformed code (if no error) or a list of one or more compilation errors.
|
||||
|
||||
## Background
|
||||
|
||||
Currently React Compiler runs through a series of passes in Pipeline.ts. If an error occurs in a pass the compiler will generally either throw the error in the pass where it occurs, or return a Result<_, CompilerError> which is then unwrapped in Pipeline.ts, throwing there. This means that a single error that triggers early can prevent later validation from running, meaning the user has to first fix one error in order to see another.
|
||||
|
||||
## New Approach
|
||||
|
||||
The compiler should always run all passes in the pipeline, up to and including CodegenReactiveFunction. During this process it should accumulate errors. If at the end of compilation there were no accumulated errors, return `Ok(generatedfunction)`. Else, return `Err(CompilerError)` with *all* the accumulated errors.
|
||||
|
||||
Note that some errors may continue to cause an eager bailout:
|
||||
* If an error is not an instanceof CompilerError, throw it as it occurs
|
||||
* If an error is a CompilerError invariant, throw it as it occurs since this represents a truly exceptional, unexpected case
|
||||
|
||||
## Detailed Design
|
||||
|
||||
* The Environment needs a way to record errors as compilation proceeds. This should generally store the error (and log, if a logger is configured), but should immediately throw if the error is an invariant (see above).
|
||||
* BuildHIR should always produce an HIR without error. For syntax forms that are unsupported (currently throwing a Todo error), we should instead construct record the todo error on the environment, and construct a partial HIR. The exact form of the partial HIR can be situation specific:
|
||||
* `var` is currently unsupported, but we could pretend it was `let`
|
||||
* `finally` blocks are unsupported, we could just prune them, or move the code after the try/catch (put the finally logic in the consequent)
|
||||
* This may mean updating the HIR to allow representing partial code
|
||||
* `eval()` can just be an Unsupported InstructionValue variant
|
||||
* All of the passes need to be updated to stop returning Result or CompilerError, and instead record their errors on the environment. They should always be able to proceed even in the presence of errors. For example, in InferMutationAliasingEffects if we discover that the code mutates a frozen value, we can record this as an error and then just pretend the mutation didn't happen - ie construct a scope as if the mutating code was not a mutation after all.
|
||||
* Finally, the end of the pipeline should check for errors and either turn `Ok(GeneratedFunction)` or `Err(aggregatedErrors)`. The code calling into the pipeline then needs to handle this appropriately.
|
||||
|
||||
## Detailed Plan
|
||||
|
||||
### Phase 1: Environment Error Accumulation Infrastructure
|
||||
|
||||
Add error accumulation to the `Environment` class so that any pass can record errors during compilation without halting.
|
||||
|
||||
- [x] **1.1 Add error accumulator to Environment** (`src/HIR/Environment.ts`)
|
||||
- Add a `#errors: CompilerError` field, initialized in the constructor
|
||||
- Add a `recordError(error: CompilerDiagnostic | CompilerErrorDetail)` method that:
|
||||
- If an Invariant-category detail, immediately throw it
|
||||
- Otherwise, push the diagnostic/detail onto `#errors` (and log via `this.logger` if configured)
|
||||
- Add a `recordErrors(error: CompilerError)` method that calls `recordError()` for each of the details on the given error.
|
||||
- Add a `hasErrors(): boolean` getter
|
||||
- Add a `aggregateErrors(): CompilerError` method that returns the accumulated error object
|
||||
- Consider whether `recordError` should accept the same options as `CompilerError.push()` for convenience (reason, description, severity, loc, etc.)
|
||||
|
||||
- [x] **1.2 Add a `tryRecord` helper on Environment** (`src/HIR/Environment.ts`)
|
||||
- Add a `tryRecord(fn: () => void): void` method that wraps a callback in try/catch:
|
||||
- If `fn` throws a `CompilerError` that is NOT an invariant, record it via `recordError`
|
||||
- If `fn` throws a non-CompilerError or a CompilerError invariant, re-throw
|
||||
- This helper is the migration path for passes that currently throw: wrap their call in `env.tryRecord(() => pass(hir))` so exceptions become recorded errors
|
||||
|
||||
### Phase 2: Update Pipeline.ts to Accumulate Errors
|
||||
|
||||
Change `runWithEnvironment` to run all passes and check for errors at the end instead of letting exceptions propagate.
|
||||
|
||||
- [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())`
|
||||
|
||||
- [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`
|
||||
|
||||
- [x] **2.3 Update `run` to propagate the Result** (`src/Entrypoint/Pipeline.ts`)
|
||||
- Same change for the internal `run` function
|
||||
|
||||
- [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}`
|
||||
- Keep the try/catch only for truly unexpected (non-CompilerError) exceptions and invariants
|
||||
- The existing `handleError`/`logError`/`panicThreshold` logic in `processFn` should continue to work unchanged since it already handles `CompilerError` instances
|
||||
|
||||
### Phase 3: Update BuildHIR (lower) to Always Produce HIR
|
||||
|
||||
Currently `lower()` returns `Result<HIRFunction, CompilerError>`. It already accumulates errors internally via `builder.errors`, but returns `Err` when errors exist. Change it to always return `Ok(hir)` while recording errors on the environment.
|
||||
|
||||
- [x] **3.1 Change `lower` to always return HIRFunction** (`src/HIR/BuildHIR.ts`)
|
||||
- Change return type from `Result<HIRFunction, CompilerError>` to `HIRFunction`
|
||||
- Instead of returning `Err(builder.errors)` at line 227-229, record errors on `env` via `env.recordErrors(builder.errors)` and return the (partial) HIR
|
||||
- Update the pipeline to call `lower(func, env)` directly instead of `lower(func, env).unwrap()`
|
||||
- Added try/catch around body lowering to catch thrown CompilerErrors (e.g., from `resolveBinding`) and record them
|
||||
|
||||
- [x] **3.2 Handle `var` declarations as `let`** (`src/HIR/BuildHIR.ts`, line ~855)
|
||||
- Record the Todo error, then treat `var` as `let` and continue lowering (instead of skipping the declaration)
|
||||
|
||||
- [x] **3.3 Handle `try/finally` by pruning `finally`** (`src/HIR/BuildHIR.ts`, lines ~1281-1296)
|
||||
- Already handled: `try` without `catch` pushes error and returns; `try` with `finally` pushes error and continues with `try/catch` portion only
|
||||
|
||||
- [x] **3.4 Handle `eval()` via UnsupportedNode** (`src/HIR/BuildHIR.ts`, line ~3568)
|
||||
- Already handled: records error via `builder.errors.push()` and continues
|
||||
|
||||
- [x] **3.5 Handle `with` statement via UnsupportedNode** (`src/HIR/BuildHIR.ts`, line ~1382)
|
||||
- Already handled: records error and emits `UnsupportedNode`
|
||||
|
||||
- [x] **3.6 Handle inline `class` declarations** (`src/HIR/BuildHIR.ts`, line ~1402)
|
||||
- Already handled: records error and emits `UnsupportedNode`
|
||||
|
||||
- [x] **3.7 Handle remaining Todo errors in expression lowering** (`src/HIR/BuildHIR.ts`)
|
||||
- Already handled: all ~60 error sites use `builder.errors.push()` to accumulate errors. The try/catch around body lowering provides a safety net for any that still throw.
|
||||
|
||||
- [x] **3.8 Handle `throw` inside `try/catch`** (`src/HIR/BuildHIR.ts`, line ~284)
|
||||
- Already handled: records error via `builder.errors.push()` and continues
|
||||
|
||||
- [x] **3.9 Handle `for` loops with missing test or expression init** (`src/HIR/BuildHIR.ts`, lines ~559, ~632)
|
||||
- For `for(;;)` (missing test): emit `true` as the test expression and add a branch terminal
|
||||
- For empty init (`for (; ...)`): add a placeholder instruction to avoid invariant about empty blocks
|
||||
- For expression init (`for (expr; ...)`): record error and lower the expression as best-effort
|
||||
- Changed `'unsupported'` terminal to `'goto'` terminal for non-variable init to maintain valid CFG structure
|
||||
|
||||
- [x] **3.10 Handle nested function lowering failures** (`src/HIR/BuildHIR.ts`, `lowerFunction` at line ~3504)
|
||||
- `lowerFunction()` now always returns `LoweredFunction` since `lower()` always returns `HIRFunction`
|
||||
- Errors from nested functions are recorded on the shared environment
|
||||
- Removed the `null` return case and the corresponding `UnsupportedNode` fallback in callers
|
||||
|
||||
- [x] **3.11 Handle unreachable functions in `build()`** (`src/HIR/HIRBuilder.ts`, `build()`)
|
||||
- Changed `CompilerError.throwTodo()` for unreachable code with hoisted declarations to `this.errors.push()` to allow HIR construction to complete
|
||||
|
||||
- [x] **3.12 Handle duplicate fbt tags** (`src/HIR/BuildHIR.ts`, line ~2279)
|
||||
- Changed `CompilerError.throwDiagnostic()` to `builder.errors.pushDiagnostic()` to record instead of throw
|
||||
|
||||
### Phase 4: Update Validation Passes
|
||||
|
||||
All validation passes need to record errors on the environment instead of returning `Result` or throwing. They should still detect the same problems, but the pipeline should continue after each one.
|
||||
|
||||
#### Pattern A passes (currently return `Result`, called with `.unwrap()`)
|
||||
|
||||
These passes already accumulate errors internally and return `Result<void, CompilerError>`. The change is: instead of returning the Result, record errors on `env` and return void. Remove the `.unwrap()` call in Pipeline.ts.
|
||||
|
||||
- [x] **4.1 `validateHooksUsage`** (`src/Validation/ValidateHooksUsage.ts`)
|
||||
- Change signature from `(fn: HIRFunction): Result<void, CompilerError>` to `(fn: HIRFunction): void`
|
||||
- Record errors on `fn.env` instead of returning `errors.asResult()`
|
||||
- Update Pipeline.ts call site (line 211): remove `.unwrap()`
|
||||
|
||||
- [x] **4.2 `validateNoCapitalizedCalls`** (`src/Validation/ValidateNoCapitalizedCalls.ts`)
|
||||
- Change signature to return void
|
||||
- Fix the hybrid pattern: the direct `CallExpression` path currently throws via `CompilerError.throwInvalidReact()` — change to record on env
|
||||
- The `MethodCall` path already accumulates — change to record on env
|
||||
- Update Pipeline.ts call site (line 214): remove `.unwrap()`
|
||||
|
||||
- [x] **4.3 `validateUseMemo`** (`src/Validation/ValidateUseMemo.ts`)
|
||||
- Change signature to return void
|
||||
- Record hard errors on env instead of returning `errors.asResult()`
|
||||
- The soft `voidMemoErrors` path already uses `env.logErrors()` — keep as-is or also record
|
||||
- Update Pipeline.ts call site (line 170): remove `.unwrap()`
|
||||
|
||||
- [x] **4.4 `dropManualMemoization`** (`src/Inference/DropManualMemoization.ts`)
|
||||
- Change signature to return void
|
||||
- Record errors on env instead of returning `errors.asResult()`
|
||||
- Update Pipeline.ts call site (line 178): remove `.unwrap()`
|
||||
|
||||
- [x] **4.5 `validateNoRefAccessInRender`** (`src/Validation/ValidateNoRefAccessInRender.ts`)
|
||||
- Change signature to return void
|
||||
- Record errors on env instead of returning Result
|
||||
- Update Pipeline.ts call site (line 275): remove `.unwrap()`
|
||||
|
||||
- [x] **4.6 `validateNoSetStateInRender`** (`src/Validation/ValidateNoSetStateInRender.ts`)
|
||||
- Change signature to return void
|
||||
- Record errors on env
|
||||
- Update Pipeline.ts call site (line 279): remove `.unwrap()`
|
||||
|
||||
- [x] **4.7 `validateNoImpureFunctionsInRender`** (`src/Validation/ValidateNoImpureFunctionsInRender.ts`)
|
||||
- Change signature to return void
|
||||
- Record errors on env
|
||||
- Update Pipeline.ts call site (line 300): remove `.unwrap()`
|
||||
|
||||
- [x] **4.8 `validateNoFreezingKnownMutableFunctions`** (`src/Validation/ValidateNoFreezingKnownMutableFunctions.ts`)
|
||||
- Change signature to return void
|
||||
- Record errors on env
|
||||
- Update Pipeline.ts call site (line 303): remove `.unwrap()`
|
||||
|
||||
- [x] **4.9 `validateExhaustiveDependencies`** (`src/Validation/ValidateExhaustiveDependencies.ts`)
|
||||
- Change signature to return void
|
||||
- Record errors on env
|
||||
- Update Pipeline.ts call site (line 315): remove `.unwrap()`
|
||||
|
||||
- [x] **4.10 `validateMemoizedEffectDependencies`** (`src/Validation/ValidateMemoizedEffectDependencies.ts`)
|
||||
- Change signature to return void (note: operates on `ReactiveFunction`)
|
||||
- Record errors on the function's env
|
||||
- Update Pipeline.ts call site (line 565): remove `.unwrap()`
|
||||
|
||||
- [x] **4.11 `validatePreservedManualMemoization`** (`src/Validation/ValidatePreservedManualMemoization.ts`)
|
||||
- Change signature to return void (note: operates on `ReactiveFunction`)
|
||||
- Record errors on the function's env
|
||||
- Update Pipeline.ts call site (line 572): remove `.unwrap()`
|
||||
|
||||
- [x] **4.12 `validateSourceLocations`** (`src/Validation/ValidateSourceLocations.ts`)
|
||||
- Change signature to return void
|
||||
- Record errors on env
|
||||
- Update Pipeline.ts call site (line 585): remove `.unwrap()`
|
||||
|
||||
#### Pattern B passes (currently use `env.logErrors()`)
|
||||
|
||||
These already use a soft-logging pattern and don't block compilation. They can be migrated to `env.recordError()` so all errors are aggregated in one place.
|
||||
|
||||
- [ ] **4.13 `validateNoDerivedComputationsInEffects_exp`** — change to record on env directly
|
||||
- [ ] **4.14 `validateNoSetStateInEffects`** — change to record on env directly
|
||||
- [ ] **4.15 `validateNoJSXInTryStatement`** — change to record on env directly
|
||||
- [ ] **4.16 `validateStaticComponents`** — change to record on env directly
|
||||
|
||||
#### Pattern D passes (currently throw directly, no Result)
|
||||
|
||||
These throw `CompilerError` directly (not via Result). They need the most work.
|
||||
|
||||
- [x] **4.17 `validateContextVariableLValues`** (`src/Validation/ValidateContextVariableLValues.ts`)
|
||||
- Currently throws via `CompilerError.throwTodo()` and `CompilerError.invariant()`
|
||||
- Change to record Todo errors on env and continue
|
||||
- Keep invariant throws (those indicate internal bugs)
|
||||
|
||||
- [x] **4.18 `validateLocalsNotReassignedAfterRender`** (`src/Validation/ValidateLocalsNotReassignedAfterRender.ts`)
|
||||
- Currently constructs a `CompilerError` and `throw`s it directly
|
||||
- Change to record errors on env
|
||||
|
||||
- [x] **4.19 `validateNoDerivedComputationsInEffects`** (`src/Validation/ValidateNoDerivedComputationsInEffects.ts`)
|
||||
- Currently throws directly
|
||||
- Change to record errors on env
|
||||
|
||||
### Phase 5: Update Inference Passes
|
||||
|
||||
The inference passes are the most critical to handle correctly because they produce side effects (populating effects on instructions, computing mutable ranges) that downstream passes depend on. They must continue producing valid (even if imprecise) output when errors are encountered.
|
||||
|
||||
- [x] **5.1 `inferMutationAliasingEffects`** (`src/Inference/InferMutationAliasingEffects.ts`)
|
||||
- Currently returns `Result<void, CompilerError>` — errors are about mutation of frozen/global values
|
||||
- Change to record errors on `fn.env` instead of accumulating internally
|
||||
- **Key recovery strategy**: When a mutation of a frozen value is detected, record the error but treat the operation as a non-mutating read. This way downstream passes see a consistent (if conservative) view
|
||||
- When a mutation of a global is detected, record the error but continue with the global unchanged
|
||||
- Update Pipeline.ts (lines 233-239): remove the conditional `.isErr()` / throw pattern
|
||||
|
||||
- [x] **5.2 `inferMutationAliasingRanges`** (`src/Inference/InferMutationAliasingRanges.ts`)
|
||||
- Currently returns `Result<Array<AliasingEffect>, CompilerError>`
|
||||
- This pass has a meaningful success value (the function's external aliasing effects)
|
||||
- Change to: always produce a best-effort effects array, record errors on env
|
||||
- When errors are encountered, produce conservative effects (e.g., assume no external mutation)
|
||||
- Update Pipeline.ts (lines 258-267): remove the conditional throw pattern, call directly
|
||||
|
||||
### Phase 6: Update Codegen
|
||||
|
||||
- [x] **6.1 `codegenFunction`** (`src/ReactiveScopes/CodegenReactiveFunction.ts`)
|
||||
- Currently returns `Result<CodegenFunction, CompilerError>`
|
||||
- Change to: always produce a `CodegenFunction`, record errors on env
|
||||
- If codegen encounters an error (e.g., an instruction it can't generate code for), it should:
|
||||
- Record the error
|
||||
- For `UnsupportedNode` values: pass through the original AST node (already works this way)
|
||||
- For other error cases: emit a placeholder or the original AST where possible
|
||||
- Update Pipeline.ts (line 575-578): remove `.unwrap()`
|
||||
|
||||
### Phase 7: Pipeline.ts Pass-by-Pass Migration
|
||||
|
||||
Walk through `runWithEnvironment` and wrap each pass call site. This is the integration work tying Phases 3-6 together.
|
||||
|
||||
- [x] **7.1 Wrap `lower()` call** (line 163)
|
||||
- Change from `lower(func, env).unwrap()` to `lower(func, env)` (direct return after Phase 3.1)
|
||||
|
||||
- [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()`
|
||||
|
||||
- [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
|
||||
|
||||
- [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
|
||||
|
||||
- [x] **7.5 Wrap codegen** (lines 575-578)
|
||||
- After Phase 6.1, `codegenFunction` returns directly
|
||||
- Remove the `.unwrap()`
|
||||
|
||||
- [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())`
|
||||
|
||||
- [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
|
||||
|
||||
### Phase 8: Testing
|
||||
|
||||
- [x] **8.1 Update existing `error.todo-*` fixture expectations**
|
||||
- Currently, fixtures with `error.todo-` prefix expect a single error and bailout
|
||||
- After fault tolerance, some of these may now produce multiple errors
|
||||
- Update the `.expect.md` files to reflect the new aggregated error output
|
||||
|
||||
- [x] **8.2 Add multi-error test fixtures**
|
||||
- Create test fixtures that contain multiple independent errors (e.g., both a `var` declaration and a mutation of a frozen value)
|
||||
- Verify that all errors are reported, not just the first one
|
||||
|
||||
- [x] **8.3 Add test for invariant-still-throws behavior**
|
||||
- Verify that `CompilerError.invariant()` failures still cause immediate abort
|
||||
- Verify that non-CompilerError exceptions still cause immediate abort
|
||||
|
||||
- [x] **8.4 Add test for partial HIR codegen**
|
||||
- Verify that when BuildHIR produces partial HIR (with `UnsupportedNode` values), later passes handle it gracefully and codegen produces the original AST for unsupported portions
|
||||
|
||||
- [x] **8.5 Verify error severity in aggregated output**
|
||||
- Test that the aggregated `CompilerError` correctly reports `hasErrors()` vs `hasWarning()` vs `hasHints()` based on the mix of accumulated diagnostics
|
||||
- Verify that `panicThreshold` behavior in Program.ts is correct for aggregated errors
|
||||
|
||||
- [x] **8.6 Run full test suite**
|
||||
- Run `yarn snap` and `yarn snap -u` to update all fixture expectations
|
||||
- Ensure no regressions in passing tests
|
||||
|
||||
### Implementation Notes
|
||||
|
||||
**Ordering**: Phases 1 → 2 → 3 → 4/5/6 (parallel) → 7 → 8. Phase 1 (Environment infrastructure) is the foundation. Phase 2 (Pipeline return type) sets up the contract. Phases 3-6 can be done incrementally — each pass can be migrated independently using `env.tryRecord()` as a transitional wrapper. Phase 7 is the integration. Phase 8 validates everything.
|
||||
|
||||
**Incremental migration path**: Rather than updating all passes at once, each pass can be individually migrated. During the transition:
|
||||
1. First add `env.tryRecord()` in Phase 7.7 around all pass calls in the pipeline — this immediately provides fault tolerance by catching any thrown CompilerError
|
||||
2. Then individually update passes (Phases 3-6) to record errors directly on env, which is cleaner but not required for the basic behavior
|
||||
3. This means the feature can be landed incrementally: Phase 1 + 2 + 7.7 gives basic fault tolerance, then individual passes can be refined over time
|
||||
|
||||
**What NOT to change**:
|
||||
- `CompilerError.invariant()` must continue to throw immediately — these represent internal bugs
|
||||
- Non-CompilerError exceptions must continue to throw — these are unexpected JS errors
|
||||
- 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.
|
||||
* **Phase 3 (BuildHIR) revealed that most error sites already used `builder.errors.push()` for accumulation.** The existing lowering code was designed to accumulate errors rather than throw. The main changes were: (1) changing `lower()` return type from `Result` to `HIRFunction`, (2) recording builder errors on env, (3) adding a try/catch around body lowering to catch thrown CompilerErrors from sub-calls like `resolveBinding()`, (4) treating `var` as `let` instead of skipping declarations, and (5) fixing ForStatement init/test handling to produce valid CFG structure.
|
||||
* **Partial HIR can trigger downstream invariants.** When lowering skips or partially handles constructs (e.g., unreachable hoisted functions, `var` declarations before the fix), downstream passes like `InferMutationAliasingEffects` may encounter uninitialized identifiers and throw invariants. This is acceptable since the function still correctly bails out of compilation, but error messages may be less specific. The fix for `var` (treating as `let`) demonstrates how to avoid this: continue lowering with a best-effort representation rather than skipping entirely.
|
||||
* **Errors accumulated on `env` are lost when an invariant propagates out of the pipeline.** Since invariant CompilerErrors always re-throw through `tryRecord()`, they exit the pipeline as exceptions. The caller only sees the invariant error, not any errors previously recorded on `env`. This is a design limitation that could be addressed by aggregating env errors with caught exceptions in `tryCompileFunction()`.
|
||||
* **Dedicated fault tolerance test fixtures** were added in `__tests__/fixtures/compiler/fault-tolerance/`. Each fixture combines two or more errors from different passes to verify the compiler reports all of them rather than short-circuiting on the first. Coverage includes: `var`+props mutation (BuildHIR→InferMutationAliasingEffects), `var`+ref access (BuildHIR→ValidateNoRefAccessInRender), `try/finally`+props mutation (BuildHIR→InferMutationAliasingEffects), `try/finally`+ref access (BuildHIR→ValidateNoRefAccessInRender), and a 3-error test combining try/finally+ref access+props mutation.
|
||||
|
||||
@@ -70,9 +70,6 @@ The `occursCheck` method prevents infinite types by detecting when a type variab
|
||||
- `DeclareContext` and `LoadContext` generate no type equations (intentionally untyped)
|
||||
- `StoreContext` with `Const` kind does propagate the rvalue type to enable ref inference through context variables
|
||||
|
||||
### Event Handler Inference
|
||||
When `enableInferEventHandlers` is enabled, JSX props starting with "on" (e.g., `onClick`) on built-in DOM elements (excluding web components with hyphens) are inferred as `Function<BuiltInEventHandlerId>`.
|
||||
|
||||
## TODOs
|
||||
1. **Hook vs Function type ambiguity**:
|
||||
> "TODO: callee could be a hook or a function, so this type equation isn't correct. We should change Hook to a subtype of Function or change unifier logic."
|
||||
|
||||
@@ -205,8 +205,6 @@ if ($[0] !== "source_hash_abc123") {
|
||||
}
|
||||
```
|
||||
|
||||
### Change Detection for Debugging
|
||||
When `enableChangeDetectionForDebugging` is configured, additional code is generated to detect when cached values unexpectedly change.
|
||||
|
||||
### Labeled Breaks
|
||||
Control flow with labeled breaks (for early returns or loop exits) uses `codegenLabel` to generate consistent label names:
|
||||
@@ -231,7 +229,6 @@ type CodegenFunction = {
|
||||
prunedMemoBlocks: number; // Scopes that were pruned
|
||||
prunedMemoValues: number; // Values in pruned scopes
|
||||
hasInferredEffect: boolean;
|
||||
hasFireRewrite: boolean;
|
||||
};
|
||||
```
|
||||
|
||||
|
||||
@@ -1,203 +0,0 @@
|
||||
# transformFire
|
||||
|
||||
## File
|
||||
`src/Transform/TransformFire.ts`
|
||||
|
||||
## Purpose
|
||||
This pass transforms `fire(fn())` calls inside `useEffect` lambdas into calls to a `useFire` hook that provides stable function references. The `fire()` function is a React API that allows effect callbacks to call functions with their current values while maintaining stable effect dependencies.
|
||||
|
||||
Without this transform, if an effect depends on a function that changes every render, the effect would re-run on every render. The `useFire` hook provides a stable wrapper that always calls the latest version of the function.
|
||||
|
||||
## Input Invariants
|
||||
- The `enableFire` feature flag must be enabled
|
||||
- `fire()` calls must only appear inside `useEffect` lambdas
|
||||
- Each `fire()` call must have exactly one argument (a function call expression)
|
||||
- The function being fired must be consistent across all `fire()` calls in the same effect
|
||||
|
||||
## Output Guarantees
|
||||
- All `fire(fn(...args))` calls are replaced with direct calls `fired_fn(...args)`
|
||||
- A `useFire(fn)` hook call is inserted before the `useEffect`
|
||||
- The fired function is stored in a temporary and captured by the effect
|
||||
- The original function `fn` is removed from the effect's captured context
|
||||
|
||||
## Algorithm
|
||||
|
||||
### Phase 1: Find Fire Calls
|
||||
```typescript
|
||||
function replaceFireFunctions(fn: HIRFunction, context: Context): void {
|
||||
// For each useEffect call instruction:
|
||||
// 1. Find all fire() calls in the effect lambda
|
||||
// 2. Validate they have proper arguments
|
||||
// 3. Track which functions are being fired
|
||||
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
for (const instr of block.instructions) {
|
||||
if (isUseEffectCall(instr)) {
|
||||
const lambda = getEffectLambda(instr);
|
||||
findAndReplaceFireCalls(lambda, fireFunctions);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 2: Insert useFire Hooks
|
||||
For each function being fired, insert a `useFire` call:
|
||||
```typescript
|
||||
// Before:
|
||||
useEffect(() => {
|
||||
fire(foo(props));
|
||||
}, [foo, props]);
|
||||
|
||||
// After:
|
||||
const t0 = useFire(foo);
|
||||
useEffect(() => {
|
||||
t0(props);
|
||||
}, [t0, props]);
|
||||
```
|
||||
|
||||
### Phase 3: Replace Fire Calls
|
||||
Transform `fire(fn(...args))` to `firedFn(...args)`:
|
||||
```typescript
|
||||
// The fire() wrapper is removed
|
||||
// The inner function call uses the useFire'd version
|
||||
fire(foo(x, y)) → t0(x, y) // where t0 = useFire(foo)
|
||||
```
|
||||
|
||||
### Phase 4: Validate No Remaining Fire Uses
|
||||
```typescript
|
||||
function ensureNoMoreFireUses(fn: HIRFunction, context: Context): void {
|
||||
// Ensure all fire() uses have been transformed
|
||||
// Report errors for any remaining fire() calls
|
||||
}
|
||||
```
|
||||
|
||||
## Edge Cases
|
||||
|
||||
### Fire Outside Effect
|
||||
`fire()` calls outside `useEffect` lambdas cause a validation error:
|
||||
```javascript
|
||||
// ERROR: fire() can only be used inside useEffect
|
||||
function Component() {
|
||||
fire(callback());
|
||||
}
|
||||
```
|
||||
|
||||
### Mixed Fire and Non-Fire Calls
|
||||
All calls to the same function must either all use `fire()` or none:
|
||||
```javascript
|
||||
// ERROR: Cannot mix fire() and non-fire calls
|
||||
useEffect(() => {
|
||||
fire(foo(x));
|
||||
foo(y); // Error: foo is used with and without fire()
|
||||
});
|
||||
```
|
||||
|
||||
### Multiple Arguments to Fire
|
||||
`fire()` accepts exactly one argument (the function call):
|
||||
```javascript
|
||||
// ERROR: fire() takes exactly one argument
|
||||
fire(foo, bar) // Invalid
|
||||
fire() // Invalid
|
||||
```
|
||||
|
||||
### Nested Effects
|
||||
Fire calls in nested effects are validated separately:
|
||||
```javascript
|
||||
useEffect(() => {
|
||||
useEffect(() => { // Error: nested effects not allowed
|
||||
fire(foo());
|
||||
});
|
||||
});
|
||||
```
|
||||
|
||||
### Deep Scope Handling
|
||||
The pass handles fire calls within deeply nested scopes inside effects:
|
||||
```javascript
|
||||
useEffect(() => {
|
||||
if (cond) {
|
||||
while (x) {
|
||||
fire(foo(x)); // Still transformed correctly
|
||||
}
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
## TODOs
|
||||
None in the source file.
|
||||
|
||||
## Example
|
||||
|
||||
### Fixture: `transform-fire/basic.js`
|
||||
|
||||
**Input:**
|
||||
```javascript
|
||||
// @enableFire
|
||||
function Component(props) {
|
||||
const foo = (props_0) => {
|
||||
console.log(props_0);
|
||||
};
|
||||
useEffect(() => {
|
||||
fire(foo(props));
|
||||
});
|
||||
return null;
|
||||
}
|
||||
```
|
||||
|
||||
**After TransformFire:**
|
||||
```
|
||||
bb0 (block):
|
||||
[1] $25 = Function @context[] ... // foo definition
|
||||
[2] StoreLocal Const foo$32 = $25
|
||||
[3] $45 = LoadGlobal import { useFire } from 'react/compiler-runtime'
|
||||
[4] $46 = LoadLocal foo$32
|
||||
[5] $47 = Call $45($46) // useFire(foo)
|
||||
[6] StoreLocal Const #t44$44 = $47
|
||||
[7] $34 = LoadGlobal(global) useEffect
|
||||
[8] $35 = Function @context[#t44$44, props$24] ...
|
||||
<<anonymous>>():
|
||||
[1] $37 = LoadLocal #t44$44 // Load the fired function
|
||||
[2] $38 = LoadLocal props$24
|
||||
[3] $39 = Call $37($38) // Call it directly (no fire wrapper)
|
||||
[4] Return Void
|
||||
[9] Call $34($35) // useEffect(lambda)
|
||||
[10] Return null
|
||||
```
|
||||
|
||||
**Generated Code:**
|
||||
```javascript
|
||||
import { useFire as _useFire } from "react/compiler-runtime";
|
||||
function Component(props) {
|
||||
const $ = _c(4);
|
||||
let t0;
|
||||
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
|
||||
t0 = (props_0) => {
|
||||
console.log(props_0);
|
||||
};
|
||||
$[0] = t0;
|
||||
} else {
|
||||
t0 = $[0];
|
||||
}
|
||||
const foo = t0;
|
||||
const t1 = _useFire(foo);
|
||||
let t2;
|
||||
if ($[1] !== props || $[2] !== t1) {
|
||||
t2 = () => {
|
||||
t1(props);
|
||||
};
|
||||
$[1] = props;
|
||||
$[2] = t1;
|
||||
$[3] = t2;
|
||||
} else {
|
||||
t2 = $[3];
|
||||
}
|
||||
useEffect(t2);
|
||||
return null;
|
||||
}
|
||||
```
|
||||
|
||||
Key observations:
|
||||
- `useFire` is imported from `react/compiler-runtime`
|
||||
- `fire(foo(props))` becomes `t1(props)` where `t1 = _useFire(foo)`
|
||||
- The effect now depends on `t1` (stable) and `props` (reactive)
|
||||
- The original `foo` function is memoized and passed to `useFire`
|
||||
@@ -1,174 +0,0 @@
|
||||
# lowerContextAccess
|
||||
|
||||
## File
|
||||
`src/Optimization/LowerContextAccess.ts`
|
||||
|
||||
## Purpose
|
||||
This pass optimizes `useContext` calls by generating selector functions that extract only the needed properties from the context. Instead of subscribing to the entire context object, components can subscribe to specific slices, enabling more granular re-rendering.
|
||||
|
||||
When a component destructures specific properties from a context, this pass transforms the `useContext` call to use a selector-based API that only triggers re-renders when the selected properties change.
|
||||
|
||||
## Input Invariants
|
||||
- The `lowerContextAccess` configuration must be set with:
|
||||
- `source`: The module to import the lowered context hook from
|
||||
- `importSpecifierName`: The name of the hook function
|
||||
- The function must use `useContext` with destructuring patterns
|
||||
- Only object destructuring patterns with identifier values are supported
|
||||
|
||||
## Output Guarantees
|
||||
- `useContext(Ctx)` calls with destructuring are replaced with selector calls
|
||||
- A selector function is generated that extracts the needed properties
|
||||
- The return type is changed from object to array for positional access
|
||||
- Unused original `useContext` calls are removed by dead code elimination
|
||||
|
||||
## Algorithm
|
||||
|
||||
### Phase 1: Collect Context Access Patterns
|
||||
```typescript
|
||||
function lowerContextAccess(fn: HIRFunction, config: ExternalFunction): void {
|
||||
const contextAccess: Map<IdentifierId, CallExpression> = new Map();
|
||||
const contextKeys: Map<IdentifierId, Array<string>> = new Map();
|
||||
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
for (const instr of block.instructions) {
|
||||
// Find useContext calls
|
||||
if (isUseContextCall(instr)) {
|
||||
contextAccess.set(instr.lvalue.identifier.id, instr.value);
|
||||
}
|
||||
|
||||
// Find destructuring patterns that access context results
|
||||
if (isDestructure(instr) && contextAccess.has(instr.value.value.id)) {
|
||||
const keys = extractPropertyKeys(instr.value.pattern);
|
||||
contextKeys.set(instr.value.value.id, keys);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Phase 2: Generate Selector Functions
|
||||
For each context access with known keys:
|
||||
```typescript
|
||||
// Original:
|
||||
const {foo, bar} = useContext(MyContext);
|
||||
|
||||
// Selector function generated:
|
||||
(ctx) => [ctx.foo, ctx.bar]
|
||||
```
|
||||
|
||||
### Phase 3: Transform Context Calls
|
||||
```typescript
|
||||
// Before:
|
||||
$0 = useContext(MyContext)
|
||||
{foo, bar} = $0
|
||||
|
||||
// After:
|
||||
$0 = useContext_withSelector(MyContext, (ctx) => [ctx.foo, ctx.bar])
|
||||
[foo, bar] = $0
|
||||
```
|
||||
|
||||
### Phase 4: Update Destructuring
|
||||
Change object destructuring to array destructuring to match selector return:
|
||||
```typescript
|
||||
// Before: { foo: foo$15, bar: bar$16 } = $14
|
||||
// After: [ foo$15, bar$16 ] = $14
|
||||
```
|
||||
|
||||
## Edge Cases
|
||||
|
||||
### Dynamic Property Access
|
||||
If context properties are accessed dynamically (not through destructuring), the optimization is skipped:
|
||||
```javascript
|
||||
const ctx = useContext(MyContext);
|
||||
const x = ctx[dynamicKey]; // Cannot optimize
|
||||
```
|
||||
|
||||
### Spread in Destructuring
|
||||
Spread patterns prevent optimization:
|
||||
```javascript
|
||||
const {foo, ...rest} = useContext(MyContext); // Cannot optimize
|
||||
```
|
||||
|
||||
### Non-Identifier Values
|
||||
Only simple identifier destructuring is supported:
|
||||
```javascript
|
||||
const {foo: bar} = useContext(MyContext); // Supported (rename)
|
||||
const {foo = defaultVal} = useContext(MyContext); // Not supported
|
||||
```
|
||||
|
||||
### Multiple Context Accesses
|
||||
Each `useContext` call is transformed independently:
|
||||
```javascript
|
||||
const {a} = useContext(CtxA); // Transformed
|
||||
const {b} = useContext(CtxB); // Transformed separately
|
||||
```
|
||||
|
||||
### Hook Guards
|
||||
When `enableEmitHookGuards` is enabled, the selector function includes proper hook guard annotations.
|
||||
|
||||
## TODOs
|
||||
None in the source file.
|
||||
|
||||
## Example
|
||||
|
||||
### Fixture: `lower-context-selector-simple.js`
|
||||
|
||||
**Input:**
|
||||
```javascript
|
||||
// @lowerContextAccess
|
||||
function App() {
|
||||
const {foo, bar} = useContext(MyContext);
|
||||
return <Bar foo={foo} bar={bar} />;
|
||||
}
|
||||
```
|
||||
|
||||
**After OptimizePropsMethodCalls (where lowering happens):**
|
||||
```
|
||||
bb0 (block):
|
||||
[1] $12 = LoadGlobal(global) useContext // Original (now unused)
|
||||
[2] $13 = LoadGlobal(global) MyContext
|
||||
[3] $22 = LoadGlobal import { useContext_withSelector } from 'react-compiler-runtime'
|
||||
[4] $36 = Function @context[]
|
||||
<<anonymous>>(#t23$30):
|
||||
[1] $31 = LoadLocal #t23$30
|
||||
[2] $32 = PropertyLoad $31.foo
|
||||
[3] $33 = LoadLocal #t23$30
|
||||
[4] $34 = PropertyLoad $33.bar
|
||||
[5] $35 = Array [$32, $34] // Return [foo, bar]
|
||||
[6] Return $35
|
||||
[5] $14 = Call $22($13, $36) // useContext_withSelector(MyContext, selector)
|
||||
[6] $17 = Destructure Const { foo: foo$15, bar: bar$16 } = $14
|
||||
...
|
||||
```
|
||||
|
||||
**Generated Code:**
|
||||
```javascript
|
||||
import { c as _c } from "react/compiler-runtime";
|
||||
import { useContext_withSelector } from "react-compiler-runtime";
|
||||
function App() {
|
||||
const $ = _c(2);
|
||||
let t0;
|
||||
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
|
||||
t0 = (ctx) => [ctx.foo, ctx.bar];
|
||||
$[0] = t0;
|
||||
} else {
|
||||
t0 = $[0];
|
||||
}
|
||||
const { foo, bar } = useContext_withSelector(MyContext, t0);
|
||||
let t1;
|
||||
if ($[1] === Symbol.for("react.memo_cache_sentinel")) {
|
||||
t1 = <Bar foo={foo} bar={bar} />;
|
||||
$[1] = t1;
|
||||
} else {
|
||||
t1 = $[1];
|
||||
}
|
||||
return t1;
|
||||
}
|
||||
```
|
||||
|
||||
Key observations:
|
||||
- `useContext` is replaced with `useContext_withSelector`
|
||||
- A selector function `(ctx) => [ctx.foo, ctx.bar]` is generated
|
||||
- The selector function is memoized (first cache slot)
|
||||
- Only `foo` and `bar` properties are extracted, enabling granular subscriptions
|
||||
- The selector return type changes from object to array
|
||||
@@ -49,13 +49,8 @@ const ALLOW_LIST = new Set([
|
||||
...(envConfig.validateNoCapitalizedCalls ?? []), // User-configured allowlist
|
||||
]);
|
||||
|
||||
const hookPattern = envConfig.hookPattern != null
|
||||
? new RegExp(envConfig.hookPattern)
|
||||
: null;
|
||||
|
||||
const isAllowed = (name: string): boolean => {
|
||||
return ALLOW_LIST.has(name) ||
|
||||
(hookPattern != null && hookPattern.test(name));
|
||||
return ALLOW_LIST.has(name);
|
||||
};
|
||||
```
|
||||
|
||||
@@ -137,13 +132,6 @@ Users can allowlist specific functions via configuration:
|
||||
validateNoCapitalizedCalls: ['MyUtility', 'SomeFactory']
|
||||
```
|
||||
|
||||
### Hook Patterns
|
||||
Functions matching the configured hook pattern are allowed even if capitalized:
|
||||
```typescript
|
||||
// With hookPattern: 'React\\$use.*'
|
||||
const x = React$useState(); // Allowed if it matches the hook pattern
|
||||
```
|
||||
|
||||
### Method Calls vs Function Calls
|
||||
Both direct function calls and method calls on objects are checked:
|
||||
```javascript
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
# validateMemoizedEffectDependencies
|
||||
|
||||
## File
|
||||
`src/Validation/ValidateMemoizedEffectDependencies.ts`
|
||||
|
||||
## Purpose
|
||||
Validates that all known effect dependencies (for `useEffect`, `useLayoutEffect`, and `useInsertionEffect`) are properly memoized. This prevents a common bug where unmemoized effect dependencies can cause infinite re-render loops or other unexpected behavior.
|
||||
|
||||
## Input Invariants
|
||||
- Operates on ReactiveFunction (post-reactive scope inference)
|
||||
- Reactive scopes have been assigned to values that need memoization
|
||||
- Must run after scope inference but before codegen
|
||||
|
||||
## Validation Rules
|
||||
This pass checks two conditions:
|
||||
|
||||
1. **Unmemoized dependencies with assigned scopes**: Disallows effect dependencies that should be memoized (have a reactive scope assigned) but where that reactive scope does not exist in the output. This catches cases where a reactive scope was pruned, such as when it spans a hook call.
|
||||
|
||||
2. **Mutable dependencies at effect call site**: Disallows effect dependencies whose mutable range encompasses the effect call. This catches values that the compiler knows may be mutated after the effect is set up.
|
||||
|
||||
When either condition is violated, the pass produces:
|
||||
```
|
||||
Compilation Skipped: React Compiler has skipped optimizing this component because
|
||||
the effect dependencies could not be memoized. Unmemoized effect dependencies can
|
||||
trigger an infinite loop or other unexpected behavior
|
||||
```
|
||||
|
||||
## Algorithm
|
||||
1. Traverse the reactive function using a visitor pattern
|
||||
2. Track all scopes that exist in the AST by adding them to a `Set<ScopeId>` during `visitScope`
|
||||
3. Only record a scope if its dependencies are also memoized (transitive memoization check)
|
||||
4. When visiting an instruction that is an effect hook call (`useEffect`, `useLayoutEffect`, `useInsertionEffect`) with at least 2 arguments (function + deps array):
|
||||
- Check if the dependency array is mutable at the call site using `isMutable()`
|
||||
- Check if the dependency array's scope exists using `isUnmemoized()`
|
||||
- If either check fails, push an error
|
||||
|
||||
### Key Helper Functions
|
||||
|
||||
**isEffectHook(identifier)**: Returns true if the identifier is `useEffect`, `useLayoutEffect`, or `useInsertionEffect`.
|
||||
|
||||
**isUnmemoized(operand, scopes)**: Returns true if the operand has a scope assigned (`operand.scope != null`) but that scope doesn't exist in the set of valid scopes.
|
||||
|
||||
## Edge Cases
|
||||
- Only validates effects with 2+ arguments (ignores effects without dependency arrays)
|
||||
- Transitive memoization: A scope is only considered valid if all its dependencies are also memoized
|
||||
- Merged scopes are tracked together with their primary scope
|
||||
|
||||
## TODOs
|
||||
From the source code:
|
||||
```typescript
|
||||
// TODO: isMutable is not safe to call here as it relies on identifier mutableRange
|
||||
// which is no longer valid at this point in the pipeline
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
### Fixture: `error.invalid-useEffect-dep-not-memoized.js`
|
||||
|
||||
**Input:**
|
||||
```javascript
|
||||
// @validateMemoizedEffectDependencies
|
||||
import {useEffect} from 'react';
|
||||
|
||||
function Component(props) {
|
||||
const data = {};
|
||||
useEffect(() => {
|
||||
console.log(props.value);
|
||||
}, [data]);
|
||||
mutate(data);
|
||||
return data;
|
||||
}
|
||||
```
|
||||
|
||||
**Error:**
|
||||
```
|
||||
Found 1 error:
|
||||
|
||||
Compilation Skipped: React Compiler has skipped optimizing this component because
|
||||
the effect dependencies could not be memoized. Unmemoized effect dependencies can
|
||||
trigger an infinite loop or other unexpected behavior
|
||||
|
||||
error.invalid-useEffect-dep-not-memoized.ts:6:2
|
||||
4 | function Component(props) {
|
||||
5 | const data = {};
|
||||
> 6 | useEffect(() => {
|
||||
| ^^^^^^^^^^^^^^^^^
|
||||
> 7 | console.log(props.value);
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
> 8 | }, [data]);
|
||||
| ^^^^^^^^^^^^^
|
||||
```
|
||||
|
||||
**Why it fails:** The `data` object is mutated after the `useEffect` call, which extends its mutable range past the effect. This means `data` cannot be safely memoized as an effect dependency because it might change after the effect is set up.
|
||||
@@ -25,7 +25,7 @@ This directory contains detailed documentation for each pass in the React Compil
|
||||
┌─────────────────────────────────────────────────────────────────────────────────────┐
|
||||
│ PHASE 2: OPTIMIZATION │
|
||||
│ │
|
||||
│ constantPropagation ──▶ deadCodeElimination ──▶ instructionReordering │
|
||||
│ constantPropagation ──▶ deadCodeElimination │
|
||||
│ │
|
||||
└─────────────────────────────────────────────────────────────────────────────────────┘
|
||||
│
|
||||
@@ -195,8 +195,6 @@ This directory contains detailed documentation for each pass in the React Compil
|
||||
|
||||
| # | Pass | File | Description |
|
||||
|---|------|------|-------------|
|
||||
| 32 | [transformFire](32-transformFire.md) | `Transform/TransformFire.ts` | Transform `fire()` calls in effects |
|
||||
| 33 | [lowerContextAccess](33-lowerContextAccess.md) | `Optimization/LowerContextAccess.ts` | Optimize context access with selectors |
|
||||
| 34 | [optimizePropsMethodCalls](34-optimizePropsMethodCalls.md) | `Optimization/OptimizePropsMethodCalls.ts` | Normalize props method calls |
|
||||
| 35 | [optimizeForSSR](35-optimizeForSSR.md) | `Optimization/OptimizeForSSR.ts` | SSR-specific optimizations |
|
||||
| 36 | [outlineJSX](36-outlineJSX.md) | `Optimization/OutlineJsx.ts` | Outline JSX to components |
|
||||
@@ -220,7 +218,6 @@ This directory contains detailed documentation for each pass in the React Compil
|
||||
| 49 | [validateNoRefAccessInRender](49-validateNoRefAccessInRender.md) | `Validation/ValidateNoRefAccessInRender.ts` | Ref access constraints |
|
||||
| 50 | [validateNoFreezingKnownMutableFunctions](50-validateNoFreezingKnownMutableFunctions.md) | `Validation/ValidateNoFreezingKnownMutableFunctions.ts` | Mutable function isolation |
|
||||
| 51 | [validateExhaustiveDependencies](51-validateExhaustiveDependencies.md) | `Validation/ValidateExhaustiveDependencies.ts` | Dependency array completeness |
|
||||
| 52 | [validateMemoizedEffectDependencies](52-validateMemoizedEffectDependencies.md) | `Validation/ValidateMemoizedEffectDependencies.ts` | Effect scope memoization |
|
||||
| 53 | [validatePreservedManualMemoization](53-validatePreservedManualMemoization.md) | `Validation/ValidatePreservedManualMemoization.ts` | Manual memo preservation |
|
||||
| 54 | [validateStaticComponents](54-validateStaticComponents.md) | `Validation/ValidateStaticComponents.ts` | Component identity stability |
|
||||
| 55 | [validateSourceLocations](55-validateSourceLocations.md) | `Validation/ValidateSourceLocations.ts` | Source location preservation |
|
||||
@@ -275,8 +272,6 @@ Many passes are controlled by feature flags in `Environment.ts`:
|
||||
|
||||
| Flag | Enables Pass |
|
||||
|------|--------------|
|
||||
| `enableFire` | transformFire |
|
||||
| `lowerContextAccess` | lowerContextAccess |
|
||||
| `enableJsxOutlining` | outlineJSX |
|
||||
| `enableFunctionOutlining` | outlineFunctions |
|
||||
| `validateNoSetStateInRender` | validateNoSetStateInRender |
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
injectReanimatedFlag,
|
||||
pipelineUsesReanimatedPlugin,
|
||||
} from '../Entrypoint/Reanimated';
|
||||
import validateNoUntransformedReferences from '../Entrypoint/ValidateNoUntransformedReferences';
|
||||
import {CompilerError} from '..';
|
||||
|
||||
const ENABLE_REACT_COMPILER_TIMINGS =
|
||||
@@ -64,19 +63,12 @@ export default function BabelPluginReactCompiler(
|
||||
},
|
||||
};
|
||||
}
|
||||
const result = compileProgram(prog, {
|
||||
compileProgram(prog, {
|
||||
opts,
|
||||
filename: pass.filename ?? null,
|
||||
comments: pass.file.ast.comments ?? [],
|
||||
code: pass.file.code,
|
||||
});
|
||||
validateNoUntransformedReferences(
|
||||
prog,
|
||||
pass.filename ?? null,
|
||||
opts.logger,
|
||||
opts.environment,
|
||||
result,
|
||||
);
|
||||
if (ENABLE_REACT_COMPILER_TIMINGS === true) {
|
||||
performance.mark(`${filename}:end`, {
|
||||
detail: 'BabelPlugin:Program:end',
|
||||
|
||||
@@ -565,15 +565,12 @@ function printCodeFrame(
|
||||
function printErrorSummary(category: ErrorCategory, message: string): string {
|
||||
let heading: string;
|
||||
switch (category) {
|
||||
case ErrorCategory.AutomaticEffectDependencies:
|
||||
case ErrorCategory.CapitalizedCalls:
|
||||
case ErrorCategory.Config:
|
||||
case ErrorCategory.EffectDerivationsOfState:
|
||||
case ErrorCategory.EffectSetState:
|
||||
case ErrorCategory.ErrorBoundaries:
|
||||
case ErrorCategory.Factories:
|
||||
case ErrorCategory.FBT:
|
||||
case ErrorCategory.Fire:
|
||||
case ErrorCategory.Gating:
|
||||
case ErrorCategory.Globals:
|
||||
case ErrorCategory.Hooks:
|
||||
@@ -637,10 +634,6 @@ export enum ErrorCategory {
|
||||
* Checking that useMemos always return a value
|
||||
*/
|
||||
VoidUseMemo = 'VoidUseMemo',
|
||||
/**
|
||||
* Checking for higher order functions acting as factories for components/hooks
|
||||
*/
|
||||
Factories = 'Factories',
|
||||
/**
|
||||
* Checks that manual memoization is preserved
|
||||
*/
|
||||
@@ -718,14 +711,6 @@ export enum ErrorCategory {
|
||||
* Suppressions
|
||||
*/
|
||||
Suppression = 'Suppression',
|
||||
/**
|
||||
* Issues with auto deps
|
||||
*/
|
||||
AutomaticEffectDependencies = 'AutomaticEffectDependencies',
|
||||
/**
|
||||
* Issues with `fire`
|
||||
*/
|
||||
Fire = 'Fire',
|
||||
/**
|
||||
* fbt-specific issues
|
||||
*/
|
||||
@@ -790,16 +775,6 @@ export function getRuleForCategory(category: ErrorCategory): LintRule {
|
||||
|
||||
function getRuleForCategoryImpl(category: ErrorCategory): LintRule {
|
||||
switch (category) {
|
||||
case ErrorCategory.AutomaticEffectDependencies: {
|
||||
return {
|
||||
category,
|
||||
severity: ErrorSeverity.Error,
|
||||
name: 'automatic-effect-dependencies',
|
||||
description:
|
||||
'Verifies that automatic effect dependencies are compiled if opted-in',
|
||||
preset: LintRulePreset.Off,
|
||||
};
|
||||
}
|
||||
case ErrorCategory.CapitalizedCalls: {
|
||||
return {
|
||||
category,
|
||||
@@ -870,17 +845,6 @@ function getRuleForCategoryImpl(category: ErrorCategory): LintRule {
|
||||
preset: LintRulePreset.Recommended,
|
||||
};
|
||||
}
|
||||
case ErrorCategory.Factories: {
|
||||
return {
|
||||
category,
|
||||
severity: ErrorSeverity.Error,
|
||||
name: 'component-hook-factories',
|
||||
description:
|
||||
'Validates against higher order functions defining nested components or hooks. ' +
|
||||
'Components and hooks should be defined at the module level',
|
||||
preset: LintRulePreset.Recommended,
|
||||
};
|
||||
}
|
||||
case ErrorCategory.FBT: {
|
||||
return {
|
||||
category,
|
||||
@@ -890,15 +854,6 @@ function getRuleForCategoryImpl(category: ErrorCategory): LintRule {
|
||||
preset: LintRulePreset.Off,
|
||||
};
|
||||
}
|
||||
case ErrorCategory.Fire: {
|
||||
return {
|
||||
category,
|
||||
severity: ErrorSeverity.Error,
|
||||
name: 'fire',
|
||||
description: 'Validates usage of `fire`',
|
||||
preset: LintRulePreset.Off,
|
||||
};
|
||||
}
|
||||
case ErrorCategory.Gating: {
|
||||
return {
|
||||
category,
|
||||
|
||||
@@ -19,7 +19,7 @@ import {getOrInsertWith} from '../Utils/utils';
|
||||
import {ExternalFunction, isHookName} from '../HIR/Environment';
|
||||
import {Err, Ok, Result} from '../Utils/Result';
|
||||
import {LoggerEvent, ParsedPluginOptions} from './Options';
|
||||
import {BabelFn, getReactCompilerRuntimeModule} from './Program';
|
||||
import {getReactCompilerRuntimeModule} from './Program';
|
||||
import {SuppressionRange} from './Suppression';
|
||||
|
||||
export function validateRestrictedImports(
|
||||
@@ -84,12 +84,6 @@ export class ProgramContext {
|
||||
// generated imports
|
||||
imports: Map<string, Map<string, NonLocalImportSpecifier>> = new Map();
|
||||
|
||||
/**
|
||||
* Metadata from compilation
|
||||
*/
|
||||
retryErrors: Array<{fn: BabelFn; error: CompilerError}> = [];
|
||||
inferredEffectLocations: Set<t.SourceLocation> = new Set();
|
||||
|
||||
constructor({
|
||||
program,
|
||||
suppressions,
|
||||
@@ -108,14 +102,7 @@ export class ProgramContext {
|
||||
}
|
||||
|
||||
isHookName(name: string): boolean {
|
||||
if (this.opts.environment.hookPattern == null) {
|
||||
return isHookName(name);
|
||||
} else {
|
||||
const match = new RegExp(this.opts.environment.hookPattern).exec(name);
|
||||
return (
|
||||
match != null && typeof match[1] === 'string' && isHookName(match[1])
|
||||
);
|
||||
}
|
||||
return isHookName(name);
|
||||
}
|
||||
|
||||
hasReference(name: string): boolean {
|
||||
|
||||
@@ -228,8 +228,6 @@ const CompilerOutputModeSchema = z.enum([
|
||||
'ssr',
|
||||
// Build optimized for the client, with auto memoization
|
||||
'client',
|
||||
// Build optimized for the client without auto memo
|
||||
'client-no-memo',
|
||||
// Lint mode, the output is unused but validations should run
|
||||
'lint',
|
||||
]);
|
||||
@@ -255,9 +253,7 @@ export type LoggerEvent =
|
||||
| CompileDiagnosticEvent
|
||||
| CompileSkipEvent
|
||||
| PipelineErrorEvent
|
||||
| TimingEvent
|
||||
| AutoDepsDecorationsEvent
|
||||
| AutoDepsEligibleEvent;
|
||||
| TimingEvent;
|
||||
|
||||
export type CompileErrorEvent = {
|
||||
kind: 'CompileError';
|
||||
@@ -294,17 +290,6 @@ export type TimingEvent = {
|
||||
kind: 'Timing';
|
||||
measurement: PerformanceMeasure;
|
||||
};
|
||||
export type AutoDepsDecorationsEvent = {
|
||||
kind: 'AutoDepsDecorations';
|
||||
fnLoc: t.SourceLocation;
|
||||
decorations: Array<t.SourceLocation>;
|
||||
};
|
||||
export type AutoDepsEligibleEvent = {
|
||||
kind: 'AutoDepsEligible';
|
||||
fnLoc: t.SourceLocation;
|
||||
depArrayLoc: t.SourceLocation;
|
||||
};
|
||||
|
||||
export type Logger = {
|
||||
logEvent: (filename: string | null, event: LoggerEvent) => void;
|
||||
debugLogIRs?: (value: CompilerPipelineValue) => void;
|
||||
|
||||
@@ -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,
|
||||
@@ -34,15 +37,12 @@ import {
|
||||
dropManualMemoization,
|
||||
inferReactivePlaces,
|
||||
inlineImmediatelyInvokedFunctionExpressions,
|
||||
inferEffectDependencies,
|
||||
} from '../Inference';
|
||||
import {
|
||||
constantPropagation,
|
||||
deadCodeElimination,
|
||||
pruneMaybeThrows,
|
||||
inlineJsxTransform,
|
||||
} from '../Optimization';
|
||||
import {instructionReordering} from '../Optimization/InstructionReordering';
|
||||
import {
|
||||
CodegenFunction,
|
||||
alignObjectMethodScopes,
|
||||
@@ -69,7 +69,6 @@ import {alignReactiveScopesToBlockScopesHIR} from '../ReactiveScopes/AlignReacti
|
||||
import {flattenReactiveLoopsHIR} from '../ReactiveScopes/FlattenReactiveLoopsHIR';
|
||||
import {flattenScopesWithHooksOrUseHIR} from '../ReactiveScopes/FlattenScopesWithHooksOrUseHIR';
|
||||
import {pruneAlwaysInvalidatingScopes} from '../ReactiveScopes/PruneAlwaysInvalidatingScopes';
|
||||
import pruneInitializationDependencies from '../ReactiveScopes/PruneInitializationDependencies';
|
||||
import {stabilizeBlockIds} from '../ReactiveScopes/StabilizeBlockIds';
|
||||
import {
|
||||
eliminateRedundantPhi,
|
||||
@@ -80,7 +79,6 @@ import {inferTypes} from '../TypeInference';
|
||||
import {
|
||||
validateContextVariableLValues,
|
||||
validateHooksUsage,
|
||||
validateMemoizedEffectDependencies,
|
||||
validateNoCapitalizedCalls,
|
||||
validateNoRefAccessInRender,
|
||||
validateNoSetStateInRender,
|
||||
@@ -89,14 +87,11 @@ import {
|
||||
} from '../Validation';
|
||||
import {validateLocalsNotReassignedAfterRender} from '../Validation/ValidateLocalsNotReassignedAfterRender';
|
||||
import {outlineFunctions} from '../Optimization/OutlineFunctions';
|
||||
import {lowerContextAccess} from '../Optimization/LowerContextAccess';
|
||||
import {validateNoSetStateInEffects} from '../Validation/ValidateNoSetStateInEffects';
|
||||
import {validateNoJSXInTryStatement} from '../Validation/ValidateNoJSXInTryStatement';
|
||||
import {propagateScopeDependenciesHIR} from '../HIR/PropagateScopeDependenciesHIR';
|
||||
import {outlineJSX} from '../Optimization/OutlineJsx';
|
||||
import {optimizePropsMethodCalls} from '../Optimization/OptimizePropsMethodCalls';
|
||||
import {transformFire} from '../Transform';
|
||||
import {validateNoImpureFunctionsInRender} from '../Validation/ValidateNoImpureFunctionsInRender';
|
||||
import {validateStaticComponents} from '../Validation/ValidateStaticComponents';
|
||||
import {validateNoFreezingKnownMutableFunctions} from '../Validation/ValidateNoFreezingKnownMutableFunctions';
|
||||
import {inferMutationAliasingEffects} from '../Inference/InferMutationAliasingEffects';
|
||||
@@ -125,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,
|
||||
@@ -156,26 +151,21 @@ function runWithEnvironment(
|
||||
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
|
||||
>,
|
||||
env: Environment,
|
||||
): CodegenFunction {
|
||||
): Result<CodegenFunction, CompilerError> {
|
||||
const log = (value: CompilerPipelineValue): void => {
|
||||
env.logger?.debugLogIRs?.(value);
|
||||
};
|
||||
const hir = lower(func, env).unwrap();
|
||||
const hir = lower(func, env);
|
||||
log({kind: 'hir', name: 'HIR', value: hir});
|
||||
|
||||
pruneMaybeThrows(hir);
|
||||
log({kind: 'hir', name: 'PruneMaybeThrows', value: hir});
|
||||
|
||||
validateContextVariableLValues(hir);
|
||||
validateUseMemo(hir).unwrap();
|
||||
validateUseMemo(hir);
|
||||
|
||||
if (
|
||||
env.enableDropManualMemoization &&
|
||||
!env.config.enablePreserveExistingManualUseMemo &&
|
||||
!env.config.disableMemoizationForDebugging &&
|
||||
!env.config.enableChangeDetectionForDebugging
|
||||
) {
|
||||
dropManualMemoization(hir).unwrap();
|
||||
if (env.enableDropManualMemoization) {
|
||||
dropManualMemoization(hir);
|
||||
log({kind: 'hir', name: 'DropManualMemoization', value: hir});
|
||||
}
|
||||
|
||||
@@ -208,35 +198,21 @@ function runWithEnvironment(
|
||||
|
||||
if (env.enableValidations) {
|
||||
if (env.config.validateHooksUsage) {
|
||||
validateHooksUsage(hir).unwrap();
|
||||
validateHooksUsage(hir);
|
||||
}
|
||||
if (env.config.validateNoCapitalizedCalls) {
|
||||
validateNoCapitalizedCalls(hir).unwrap();
|
||||
validateNoCapitalizedCalls(hir);
|
||||
}
|
||||
}
|
||||
|
||||
if (env.config.enableFire) {
|
||||
transformFire(hir);
|
||||
log({kind: 'hir', name: 'TransformFire', value: hir});
|
||||
}
|
||||
|
||||
if (env.config.lowerContextAccess) {
|
||||
lowerContextAccess(hir, env.config.lowerContextAccess);
|
||||
}
|
||||
|
||||
optimizePropsMethodCalls(hir);
|
||||
log({kind: 'hir', name: 'OptimizePropsMethodCalls', value: hir});
|
||||
|
||||
analyseFunctions(hir);
|
||||
log({kind: 'hir', name: 'AnalyseFunctions', value: hir});
|
||||
|
||||
const mutabilityAliasingErrors = inferMutationAliasingEffects(hir);
|
||||
inferMutationAliasingEffects(hir);
|
||||
log({kind: 'hir', name: 'InferMutationAliasingEffects', value: hir});
|
||||
if (env.enableValidations) {
|
||||
if (mutabilityAliasingErrors.isErr()) {
|
||||
throw mutabilityAliasingErrors.unwrapErr();
|
||||
}
|
||||
}
|
||||
|
||||
if (env.outputMode === 'ssr') {
|
||||
optimizeForSSR(hir);
|
||||
@@ -246,23 +222,14 @@ function runWithEnvironment(
|
||||
// Note: Has to come after infer reference effects because "dead" code may still affect inference
|
||||
deadCodeElimination(hir);
|
||||
log({kind: 'hir', name: 'DeadCodeElimination', value: hir});
|
||||
|
||||
if (env.config.enableInstructionReordering) {
|
||||
instructionReordering(hir);
|
||||
log({kind: 'hir', name: 'InstructionReordering', value: hir});
|
||||
}
|
||||
|
||||
pruneMaybeThrows(hir);
|
||||
log({kind: 'hir', name: 'PruneMaybeThrows', value: hir});
|
||||
|
||||
const mutabilityAliasingRangeErrors = inferMutationAliasingRanges(hir, {
|
||||
inferMutationAliasingRanges(hir, {
|
||||
isFunctionExpression: false,
|
||||
});
|
||||
log({kind: 'hir', name: 'InferMutationAliasingRanges', value: hir});
|
||||
if (env.enableValidations) {
|
||||
if (mutabilityAliasingRangeErrors.isErr()) {
|
||||
throw mutabilityAliasingRangeErrors.unwrapErr();
|
||||
}
|
||||
validateLocalsNotReassignedAfterRender(hir);
|
||||
}
|
||||
|
||||
@@ -272,11 +239,11 @@ function runWithEnvironment(
|
||||
}
|
||||
|
||||
if (env.config.validateRefAccessDuringRender) {
|
||||
validateNoRefAccessInRender(hir).unwrap();
|
||||
validateNoRefAccessInRender(hir);
|
||||
}
|
||||
|
||||
if (env.config.validateNoSetStateInRender) {
|
||||
validateNoSetStateInRender(hir).unwrap();
|
||||
validateNoSetStateInRender(hir);
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -296,11 +263,9 @@ function runWithEnvironment(
|
||||
env.logErrors(validateNoJSXInTryStatement(hir));
|
||||
}
|
||||
|
||||
if (env.config.validateNoImpureFunctionsInRender) {
|
||||
validateNoImpureFunctionsInRender(hir).unwrap();
|
||||
}
|
||||
|
||||
validateNoFreezingKnownMutableFunctions(hir).unwrap();
|
||||
env.tryRecord(() => {
|
||||
validateNoFreezingKnownMutableFunctions(hir);
|
||||
});
|
||||
}
|
||||
|
||||
inferReactivePlaces(hir);
|
||||
@@ -312,7 +277,7 @@ function runWithEnvironment(
|
||||
env.config.validateExhaustiveEffectDependencies
|
||||
) {
|
||||
// NOTE: this relies on reactivity inference running first
|
||||
validateExhaustiveDependencies(hir).unwrap();
|
||||
validateExhaustiveDependencies(hir);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -341,7 +306,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',
|
||||
@@ -433,25 +399,8 @@ function runWithEnvironment(
|
||||
value: hir,
|
||||
});
|
||||
|
||||
if (env.config.inferEffectDependencies) {
|
||||
inferEffectDependencies(hir);
|
||||
log({
|
||||
kind: 'hir',
|
||||
name: 'InferEffectDependencies',
|
||||
value: hir,
|
||||
});
|
||||
}
|
||||
|
||||
if (env.config.inlineJsxTransform) {
|
||||
inlineJsxTransform(hir, env.config.inlineJsxTransform);
|
||||
log({
|
||||
kind: 'hir',
|
||||
name: 'inlineJsxTransform',
|
||||
value: hir,
|
||||
});
|
||||
}
|
||||
|
||||
const reactiveFunction = buildReactiveFunction(hir);
|
||||
let reactiveFunction!: ReactiveFunction;
|
||||
reactiveFunction = buildReactiveFunction(hir);
|
||||
log({
|
||||
kind: 'reactive',
|
||||
name: 'BuildReactiveFunction',
|
||||
@@ -503,15 +452,6 @@ function runWithEnvironment(
|
||||
value: reactiveFunction,
|
||||
});
|
||||
|
||||
if (env.config.enableChangeDetectionForDebugging != null) {
|
||||
pruneInitializationDependencies(reactiveFunction);
|
||||
log({
|
||||
kind: 'reactive',
|
||||
name: 'PruneInitializationDependencies',
|
||||
value: reactiveFunction,
|
||||
});
|
||||
}
|
||||
|
||||
propagateEarlyReturns(reactiveFunction);
|
||||
log({
|
||||
kind: 'reactive',
|
||||
@@ -547,7 +487,8 @@ function runWithEnvironment(
|
||||
value: reactiveFunction,
|
||||
});
|
||||
|
||||
const uniqueIdentifiers = renameVariables(reactiveFunction);
|
||||
let uniqueIdentifiers: Set<string> = new Set();
|
||||
uniqueIdentifiers = renameVariables(reactiveFunction);
|
||||
log({
|
||||
kind: 'reactive',
|
||||
name: 'RenameVariables',
|
||||
@@ -561,28 +502,24 @@ function runWithEnvironment(
|
||||
value: reactiveFunction,
|
||||
});
|
||||
|
||||
if (env.config.validateMemoizedEffectDependencies) {
|
||||
validateMemoizedEffectDependencies(reactiveFunction).unwrap();
|
||||
}
|
||||
|
||||
if (
|
||||
env.config.enablePreserveExistingMemoizationGuarantees ||
|
||||
env.config.validatePreserveExistingMemoizationGuarantees
|
||||
) {
|
||||
validatePreservedManualMemoization(reactiveFunction).unwrap();
|
||||
validatePreservedManualMemoization(reactiveFunction);
|
||||
}
|
||||
|
||||
const ast = codegenFunction(reactiveFunction, {
|
||||
uniqueIdentifiers,
|
||||
fbtOperands,
|
||||
}).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();
|
||||
validateSourceLocations(func, ast, env);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -594,7 +531,10 @@ function runWithEnvironment(
|
||||
throw new Error('unexpected error');
|
||||
}
|
||||
|
||||
return ast;
|
||||
if (env.hasErrors()) {
|
||||
return Err(env.aggregateErrors());
|
||||
}
|
||||
return Ok(ast);
|
||||
}
|
||||
|
||||
export function compileFn(
|
||||
@@ -608,7 +548,7 @@ export function compileFn(
|
||||
logger: Logger | null,
|
||||
filename: string | null,
|
||||
code: string | null,
|
||||
): CodegenFunction {
|
||||
): Result<CodegenFunction, CompilerError> {
|
||||
return run(
|
||||
func,
|
||||
config,
|
||||
|
||||
@@ -350,10 +350,6 @@ function isFilePartOfSources(
|
||||
return false;
|
||||
}
|
||||
|
||||
export type CompileProgramMetadata = {
|
||||
retryErrors: Array<{fn: BabelFn; error: CompilerError}>;
|
||||
inferredEffectLocations: Set<t.SourceLocation>;
|
||||
};
|
||||
/**
|
||||
* Main entrypoint for React Compiler.
|
||||
*
|
||||
@@ -364,7 +360,7 @@ export type CompileProgramMetadata = {
|
||||
export function compileProgram(
|
||||
program: NodePath<t.Program>,
|
||||
pass: CompilerPass,
|
||||
): CompileProgramMetadata | null {
|
||||
): void {
|
||||
/**
|
||||
* This is directly invoked by the react-compiler babel plugin, so exceptions
|
||||
* thrown by this function will fail the babel build.
|
||||
@@ -377,7 +373,7 @@ export function compileProgram(
|
||||
* the outlined functions.
|
||||
*/
|
||||
if (shouldSkipCompilation(program, pass)) {
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
const restrictedImportsErr = validateRestrictedImports(
|
||||
program,
|
||||
@@ -385,7 +381,7 @@ export function compileProgram(
|
||||
);
|
||||
if (restrictedImportsErr) {
|
||||
handleError(restrictedImportsErr, pass, null);
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
/*
|
||||
* Record lint errors and critical errors as depending on Forget's config,
|
||||
@@ -479,16 +475,11 @@ export function compileProgram(
|
||||
);
|
||||
handleError(error, programContext, null);
|
||||
}
|
||||
return null;
|
||||
return;
|
||||
}
|
||||
|
||||
// Insert React Compiler generated functions into the Babel AST
|
||||
applyCompiledFunctions(program, compiledFns, pass, programContext);
|
||||
|
||||
return {
|
||||
retryErrors: programContext.retryErrors,
|
||||
inferredEffectLocations: programContext.inferredEffectLocations,
|
||||
};
|
||||
}
|
||||
|
||||
type CompileSource = {
|
||||
@@ -518,10 +509,6 @@ function findFunctionsToCompile(
|
||||
|
||||
const fnType = getReactFunctionType(fn, pass);
|
||||
|
||||
if (pass.opts.environment.validateNoDynamicallyCreatedComponentsOrHooks) {
|
||||
validateNoDynamicallyCreatedComponentsOrHooks(fn, pass, programContext);
|
||||
}
|
||||
|
||||
if (fnType === null || programContext.alreadyCompiled.has(fn.node)) {
|
||||
return;
|
||||
}
|
||||
@@ -633,15 +620,7 @@ function processFn(
|
||||
} else {
|
||||
handleError(compileResult.error, programContext, fn.node.loc ?? null);
|
||||
}
|
||||
if (outputMode === 'client') {
|
||||
const retryResult = retryCompileFunction(fn, fnType, programContext);
|
||||
if (retryResult == null) {
|
||||
return null;
|
||||
}
|
||||
compiledFn = retryResult;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
} else {
|
||||
compiledFn = compileResult.compiledFn;
|
||||
}
|
||||
@@ -678,16 +657,6 @@ function processFn(
|
||||
if (programContext.hasModuleScopeOptOut) {
|
||||
return null;
|
||||
} else if (programContext.opts.outputMode === 'lint') {
|
||||
/**
|
||||
* inferEffectDependencies + noEmit is currently only used for linting. In
|
||||
* this mode, add source locations for where the compiler *can* infer effect
|
||||
* dependencies.
|
||||
*/
|
||||
for (const loc of compiledFn.inferredEffectLocations) {
|
||||
if (loc !== GeneratedSource) {
|
||||
programContext.inferredEffectLocations.add(loc);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
} else if (
|
||||
programContext.opts.compilationMode === 'annotation' &&
|
||||
@@ -728,67 +697,23 @@ function tryCompileFunction(
|
||||
}
|
||||
|
||||
try {
|
||||
return {
|
||||
kind: 'compile',
|
||||
compiledFn: compileFn(
|
||||
fn,
|
||||
programContext.opts.environment,
|
||||
fnType,
|
||||
outputMode,
|
||||
programContext,
|
||||
programContext.opts.logger,
|
||||
programContext.filename,
|
||||
programContext.code,
|
||||
),
|
||||
};
|
||||
} catch (err) {
|
||||
return {kind: 'error', error: err};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* If non-memo feature flags are enabled, retry compilation with a more minimal
|
||||
* feature set.
|
||||
*
|
||||
* @returns a CodegenFunction if retry was successful
|
||||
*/
|
||||
function retryCompileFunction(
|
||||
fn: BabelFn,
|
||||
fnType: ReactFunctionType,
|
||||
programContext: ProgramContext,
|
||||
): CodegenFunction | null {
|
||||
const environment = programContext.opts.environment;
|
||||
if (
|
||||
!(environment.enableFire || environment.inferEffectDependencies != null)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Note that function suppressions are not checked in the retry pipeline, as
|
||||
* they only affect auto-memoization features.
|
||||
*/
|
||||
try {
|
||||
const retryResult = compileFn(
|
||||
const result = compileFn(
|
||||
fn,
|
||||
environment,
|
||||
programContext.opts.environment,
|
||||
fnType,
|
||||
'client-no-memo',
|
||||
outputMode,
|
||||
programContext,
|
||||
programContext.opts.logger,
|
||||
programContext.filename,
|
||||
programContext.code,
|
||||
);
|
||||
|
||||
if (!retryResult.hasFireRewrite && !retryResult.hasInferredEffect) {
|
||||
return null;
|
||||
if (result.isOk()) {
|
||||
return {kind: 'compile', compiledFn: result.unwrap()};
|
||||
} else {
|
||||
return {kind: 'error', error: result.unwrapErr()};
|
||||
}
|
||||
return retryResult;
|
||||
} catch (err) {
|
||||
// TODO: we might want to log error here, but this will also result in duplicate logging
|
||||
if (err instanceof CompilerError) {
|
||||
programContext.retryErrors.push({fn, error: err});
|
||||
}
|
||||
return null;
|
||||
return {kind: 'error', error: err};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -876,84 +801,17 @@ function shouldSkipCompilation(
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that Components/Hooks are always defined at module level. This prevents scope reference
|
||||
* errors that occur when the compiler attempts to optimize the nested component/hook while its
|
||||
* parent function remains uncompiled.
|
||||
*/
|
||||
function validateNoDynamicallyCreatedComponentsOrHooks(
|
||||
fn: BabelFn,
|
||||
pass: CompilerPass,
|
||||
programContext: ProgramContext,
|
||||
): void {
|
||||
const parentNameExpr = getFunctionName(fn);
|
||||
const parentName =
|
||||
parentNameExpr !== null && parentNameExpr.isIdentifier()
|
||||
? parentNameExpr.node.name
|
||||
: '<anonymous>';
|
||||
|
||||
const validateNestedFunction = (
|
||||
nestedFn: NodePath<
|
||||
t.FunctionDeclaration | t.FunctionExpression | t.ArrowFunctionExpression
|
||||
>,
|
||||
): void => {
|
||||
if (
|
||||
nestedFn.node === fn.node ||
|
||||
programContext.alreadyCompiled.has(nestedFn.node)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (nestedFn.scope.getProgramParent() !== nestedFn.scope.parent) {
|
||||
const nestedFnType = getReactFunctionType(nestedFn as BabelFn, pass);
|
||||
const nestedFnNameExpr = getFunctionName(nestedFn as BabelFn);
|
||||
const nestedName =
|
||||
nestedFnNameExpr !== null && nestedFnNameExpr.isIdentifier()
|
||||
? nestedFnNameExpr.node.name
|
||||
: '<anonymous>';
|
||||
if (nestedFnType === 'Component' || nestedFnType === 'Hook') {
|
||||
CompilerError.throwDiagnostic({
|
||||
category: ErrorCategory.Factories,
|
||||
reason: `Components and hooks cannot be created dynamically`,
|
||||
description: `The function \`${nestedName}\` appears to be a React ${nestedFnType.toLowerCase()}, but it's defined inside \`${parentName}\`. Components and Hooks should always be declared at module scope`,
|
||||
details: [
|
||||
{
|
||||
kind: 'error',
|
||||
message: 'this function dynamically created a component/hook',
|
||||
loc: parentNameExpr?.node.loc ?? fn.node.loc ?? null,
|
||||
},
|
||||
{
|
||||
kind: 'error',
|
||||
message: 'the component is created here',
|
||||
loc: nestedFnNameExpr?.node.loc ?? nestedFn.node.loc ?? null,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
nestedFn.skip();
|
||||
};
|
||||
|
||||
fn.traverse({
|
||||
FunctionDeclaration: validateNestedFunction,
|
||||
FunctionExpression: validateNestedFunction,
|
||||
ArrowFunctionExpression: validateNestedFunction,
|
||||
});
|
||||
}
|
||||
|
||||
function getReactFunctionType(
|
||||
fn: BabelFn,
|
||||
pass: CompilerPass,
|
||||
): ReactFunctionType | null {
|
||||
const hookPattern = pass.opts.environment.hookPattern;
|
||||
if (fn.node.body.type === 'BlockStatement') {
|
||||
const optInDirectives = tryFindDirectiveEnablingMemoization(
|
||||
fn.node.body.directives,
|
||||
pass.opts,
|
||||
);
|
||||
if (optInDirectives.unwrapOr(null) != null) {
|
||||
return getComponentOrHookLike(fn, hookPattern) ?? 'Other';
|
||||
return getComponentOrHookLike(fn) ?? 'Other';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -974,13 +832,13 @@ function getReactFunctionType(
|
||||
}
|
||||
case 'infer': {
|
||||
// Check if this is a component or hook-like function
|
||||
return componentSyntaxType ?? getComponentOrHookLike(fn, hookPattern);
|
||||
return componentSyntaxType ?? getComponentOrHookLike(fn);
|
||||
}
|
||||
case 'syntax': {
|
||||
return componentSyntaxType;
|
||||
}
|
||||
case 'all': {
|
||||
return getComponentOrHookLike(fn, hookPattern) ?? 'Other';
|
||||
return getComponentOrHookLike(fn) ?? 'Other';
|
||||
}
|
||||
default: {
|
||||
assertExhaustive(
|
||||
@@ -1022,10 +880,7 @@ function hasMemoCacheFunctionImport(
|
||||
return hasUseMemoCache;
|
||||
}
|
||||
|
||||
function isHookName(s: string, hookPattern: string | null): boolean {
|
||||
if (hookPattern !== null) {
|
||||
return new RegExp(hookPattern).test(s);
|
||||
}
|
||||
function isHookName(s: string): boolean {
|
||||
return /^use[A-Z0-9]/.test(s);
|
||||
}
|
||||
|
||||
@@ -1034,16 +889,13 @@ function isHookName(s: string, hookPattern: string | null): boolean {
|
||||
* containing a hook name.
|
||||
*/
|
||||
|
||||
function isHook(
|
||||
path: NodePath<t.Expression | t.PrivateName>,
|
||||
hookPattern: string | null,
|
||||
): boolean {
|
||||
function isHook(path: NodePath<t.Expression | t.PrivateName>): boolean {
|
||||
if (path.isIdentifier()) {
|
||||
return isHookName(path.node.name, hookPattern);
|
||||
return isHookName(path.node.name);
|
||||
} else if (
|
||||
path.isMemberExpression() &&
|
||||
!path.node.computed &&
|
||||
isHook(path.get('property'), hookPattern)
|
||||
isHook(path.get('property'))
|
||||
) {
|
||||
const obj = path.get('object').node;
|
||||
const isPascalCaseNameSpace = /^[A-Z].*/;
|
||||
@@ -1184,19 +1036,18 @@ function getComponentOrHookLike(
|
||||
node: NodePath<
|
||||
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
|
||||
>,
|
||||
hookPattern: string | null,
|
||||
): ReactFunctionType | null {
|
||||
const functionName = getFunctionName(node);
|
||||
// Check if the name is component or hook like:
|
||||
if (functionName !== null && isComponentName(functionName)) {
|
||||
let isComponent =
|
||||
callsHooksOrCreatesJsx(node, hookPattern) &&
|
||||
callsHooksOrCreatesJsx(node) &&
|
||||
isValidComponentParams(node.get('params')) &&
|
||||
!returnsNonNode(node);
|
||||
return isComponent ? 'Component' : null;
|
||||
} else if (functionName !== null && isHook(functionName, hookPattern)) {
|
||||
} else if (functionName !== null && isHook(functionName)) {
|
||||
// Hooks have hook invocations or JSX, but can take any # of arguments
|
||||
return callsHooksOrCreatesJsx(node, hookPattern) ? 'Hook' : null;
|
||||
return callsHooksOrCreatesJsx(node) ? 'Hook' : null;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -1206,7 +1057,7 @@ function getComponentOrHookLike(
|
||||
if (node.isFunctionExpression() || node.isArrowFunctionExpression()) {
|
||||
if (isForwardRefCallback(node) || isMemoCallback(node)) {
|
||||
// As an added check we also look for hook invocations or JSX
|
||||
return callsHooksOrCreatesJsx(node, hookPattern) ? 'Component' : null;
|
||||
return callsHooksOrCreatesJsx(node) ? 'Component' : null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
@@ -1232,7 +1083,6 @@ function callsHooksOrCreatesJsx(
|
||||
node: NodePath<
|
||||
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
|
||||
>,
|
||||
hookPattern: string | null,
|
||||
): boolean {
|
||||
let invokesHooks = false;
|
||||
let createsJsx = false;
|
||||
@@ -1243,7 +1093,7 @@ function callsHooksOrCreatesJsx(
|
||||
},
|
||||
CallExpression(call) {
|
||||
const callee = call.get('callee');
|
||||
if (callee.isExpression() && isHook(callee, hookPattern)) {
|
||||
if (callee.isExpression() && isHook(callee)) {
|
||||
invokesHooks = true;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,327 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {NodePath} from '@babel/core';
|
||||
import * as t from '@babel/types';
|
||||
|
||||
import {CompilerError, EnvironmentConfig, Logger} from '..';
|
||||
import {getOrInsertWith} from '../Utils/utils';
|
||||
import {Environment, GeneratedSource} from '../HIR';
|
||||
import {DEFAULT_EXPORT} from '../HIR/Environment';
|
||||
import {CompileProgramMetadata} from './Program';
|
||||
import {
|
||||
CompilerDiagnostic,
|
||||
CompilerDiagnosticOptions,
|
||||
ErrorCategory,
|
||||
} from '../CompilerError';
|
||||
|
||||
function throwInvalidReact(
|
||||
options: CompilerDiagnosticOptions,
|
||||
{logger, filename}: TraversalState,
|
||||
): never {
|
||||
logger?.logEvent(filename, {
|
||||
kind: 'CompileError',
|
||||
fnLoc: null,
|
||||
detail: new CompilerDiagnostic(options),
|
||||
});
|
||||
CompilerError.throwDiagnostic(options);
|
||||
}
|
||||
|
||||
function isAutodepsSigil(
|
||||
arg: NodePath<t.ArgumentPlaceholder | t.SpreadElement | t.Expression>,
|
||||
): boolean {
|
||||
// Check for AUTODEPS identifier imported from React
|
||||
if (arg.isIdentifier() && arg.node.name === 'AUTODEPS') {
|
||||
const binding = arg.scope.getBinding(arg.node.name);
|
||||
if (binding && binding.path.isImportSpecifier()) {
|
||||
const importSpecifier = binding.path.node as t.ImportSpecifier;
|
||||
if (importSpecifier.imported.type === 'Identifier') {
|
||||
return (importSpecifier.imported as t.Identifier).name === 'AUTODEPS';
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check for React.AUTODEPS member expression
|
||||
if (arg.isMemberExpression() && !arg.node.computed) {
|
||||
const object = arg.get('object');
|
||||
const property = arg.get('property');
|
||||
|
||||
if (
|
||||
object.isIdentifier() &&
|
||||
object.node.name === 'React' &&
|
||||
property.isIdentifier() &&
|
||||
property.node.name === 'AUTODEPS'
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
function assertValidEffectImportReference(
|
||||
autodepsIndex: number,
|
||||
paths: Array<NodePath<t.Node>>,
|
||||
context: TraversalState,
|
||||
): void {
|
||||
for (const path of paths) {
|
||||
const parent = path.parentPath;
|
||||
if (parent != null && parent.isCallExpression()) {
|
||||
const args = parent.get('arguments');
|
||||
const maybeCalleeLoc = path.node.loc;
|
||||
const hasInferredEffect =
|
||||
maybeCalleeLoc != null &&
|
||||
context.inferredEffectLocations.has(maybeCalleeLoc);
|
||||
/**
|
||||
* Error on effect calls that still have AUTODEPS in their args
|
||||
*/
|
||||
const hasAutodepsArg = args.some(isAutodepsSigil);
|
||||
if (hasAutodepsArg && !hasInferredEffect) {
|
||||
const maybeErrorDiagnostic = matchCompilerDiagnostic(
|
||||
path,
|
||||
context.transformErrors,
|
||||
);
|
||||
/**
|
||||
* Note that we cannot easily check the type of the first argument here,
|
||||
* as it may have already been transformed by the compiler (and not
|
||||
* memoized).
|
||||
*/
|
||||
throwInvalidReact(
|
||||
{
|
||||
category: ErrorCategory.AutomaticEffectDependencies,
|
||||
reason:
|
||||
'Cannot infer dependencies of this effect. This will break your build!',
|
||||
description:
|
||||
'To resolve, either pass a dependency array or fix reported compiler bailout diagnostics' +
|
||||
(maybeErrorDiagnostic ? ` ${maybeErrorDiagnostic}` : ''),
|
||||
details: [
|
||||
{
|
||||
kind: 'error',
|
||||
message: 'Cannot infer dependencies',
|
||||
loc: parent.node.loc ?? GeneratedSource,
|
||||
},
|
||||
],
|
||||
},
|
||||
context,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function assertValidFireImportReference(
|
||||
paths: Array<NodePath<t.Node>>,
|
||||
context: TraversalState,
|
||||
): void {
|
||||
if (paths.length > 0) {
|
||||
const maybeErrorDiagnostic = matchCompilerDiagnostic(
|
||||
paths[0],
|
||||
context.transformErrors,
|
||||
);
|
||||
throwInvalidReact(
|
||||
{
|
||||
category: ErrorCategory.Fire,
|
||||
reason: '[Fire] Untransformed reference to compiler-required feature.',
|
||||
description:
|
||||
'Either remove this `fire` call or ensure it is successfully transformed by the compiler' +
|
||||
(maybeErrorDiagnostic != null ? ` ${maybeErrorDiagnostic}` : ''),
|
||||
details: [
|
||||
{
|
||||
kind: 'error',
|
||||
message: 'Untransformed `fire` call',
|
||||
loc: paths[0].node.loc ?? GeneratedSource,
|
||||
},
|
||||
],
|
||||
},
|
||||
context,
|
||||
);
|
||||
}
|
||||
}
|
||||
export default function validateNoUntransformedReferences(
|
||||
path: NodePath<t.Program>,
|
||||
filename: string | null,
|
||||
logger: Logger | null,
|
||||
env: EnvironmentConfig,
|
||||
compileResult: CompileProgramMetadata | null,
|
||||
): void {
|
||||
const moduleLoadChecks = new Map<
|
||||
string,
|
||||
Map<string, CheckInvalidReferenceFn>
|
||||
>();
|
||||
if (env.enableFire) {
|
||||
/**
|
||||
* Error on any untransformed references to `fire` (e.g. including non-call
|
||||
* expressions)
|
||||
*/
|
||||
for (const module of Environment.knownReactModules) {
|
||||
const react = getOrInsertWith(moduleLoadChecks, module, () => new Map());
|
||||
react.set('fire', assertValidFireImportReference);
|
||||
}
|
||||
}
|
||||
if (env.inferEffectDependencies) {
|
||||
for (const {
|
||||
function: {source, importSpecifierName},
|
||||
autodepsIndex,
|
||||
} of env.inferEffectDependencies) {
|
||||
const module = getOrInsertWith(moduleLoadChecks, source, () => new Map());
|
||||
module.set(
|
||||
importSpecifierName,
|
||||
assertValidEffectImportReference.bind(null, autodepsIndex),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (moduleLoadChecks.size > 0) {
|
||||
transformProgram(path, moduleLoadChecks, filename, logger, compileResult);
|
||||
}
|
||||
}
|
||||
|
||||
type TraversalState = {
|
||||
shouldInvalidateScopes: boolean;
|
||||
program: NodePath<t.Program>;
|
||||
logger: Logger | null;
|
||||
filename: string | null;
|
||||
transformErrors: Array<{fn: NodePath<t.Node>; error: CompilerError}>;
|
||||
inferredEffectLocations: Set<t.SourceLocation>;
|
||||
};
|
||||
type CheckInvalidReferenceFn = (
|
||||
paths: Array<NodePath<t.Node>>,
|
||||
context: TraversalState,
|
||||
) => void;
|
||||
|
||||
function validateImportSpecifier(
|
||||
specifier: NodePath<t.ImportSpecifier>,
|
||||
importSpecifierChecks: Map<string, CheckInvalidReferenceFn>,
|
||||
state: TraversalState,
|
||||
): void {
|
||||
const imported = specifier.get('imported');
|
||||
const specifierName: string =
|
||||
imported.node.type === 'Identifier'
|
||||
? imported.node.name
|
||||
: imported.node.value;
|
||||
const checkFn = importSpecifierChecks.get(specifierName);
|
||||
if (checkFn == null) {
|
||||
return;
|
||||
}
|
||||
if (state.shouldInvalidateScopes) {
|
||||
state.shouldInvalidateScopes = false;
|
||||
state.program.scope.crawl();
|
||||
}
|
||||
|
||||
const local = specifier.get('local');
|
||||
const binding = local.scope.getBinding(local.node.name);
|
||||
CompilerError.invariant(binding != null, {
|
||||
reason: 'Expected binding to be found for import specifier',
|
||||
loc: local.node.loc ?? GeneratedSource,
|
||||
});
|
||||
checkFn(binding.referencePaths, state);
|
||||
}
|
||||
|
||||
function validateNamespacedImport(
|
||||
specifier: NodePath<t.ImportNamespaceSpecifier | t.ImportDefaultSpecifier>,
|
||||
importSpecifierChecks: Map<string, CheckInvalidReferenceFn>,
|
||||
state: TraversalState,
|
||||
): void {
|
||||
if (state.shouldInvalidateScopes) {
|
||||
state.shouldInvalidateScopes = false;
|
||||
state.program.scope.crawl();
|
||||
}
|
||||
const local = specifier.get('local');
|
||||
const binding = local.scope.getBinding(local.node.name);
|
||||
const defaultCheckFn = importSpecifierChecks.get(DEFAULT_EXPORT);
|
||||
|
||||
CompilerError.invariant(binding != null, {
|
||||
reason: 'Expected binding to be found for import specifier',
|
||||
loc: local.node.loc ?? GeneratedSource,
|
||||
});
|
||||
const filteredReferences = new Map<
|
||||
CheckInvalidReferenceFn,
|
||||
Array<NodePath<t.Node>>
|
||||
>();
|
||||
for (const reference of binding.referencePaths) {
|
||||
if (defaultCheckFn != null) {
|
||||
getOrInsertWith(filteredReferences, defaultCheckFn, () => []).push(
|
||||
reference,
|
||||
);
|
||||
}
|
||||
const parent = reference.parentPath;
|
||||
if (
|
||||
parent != null &&
|
||||
parent.isMemberExpression() &&
|
||||
parent.get('object') === reference
|
||||
) {
|
||||
if (parent.node.computed || parent.node.property.type !== 'Identifier') {
|
||||
continue;
|
||||
}
|
||||
const checkFn = importSpecifierChecks.get(parent.node.property.name);
|
||||
if (checkFn != null) {
|
||||
getOrInsertWith(filteredReferences, checkFn, () => []).push(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const [checkFn, references] of filteredReferences) {
|
||||
checkFn(references, state);
|
||||
}
|
||||
}
|
||||
function transformProgram(
|
||||
path: NodePath<t.Program>,
|
||||
|
||||
moduleLoadChecks: Map<string, Map<string, CheckInvalidReferenceFn>>,
|
||||
filename: string | null,
|
||||
logger: Logger | null,
|
||||
compileResult: CompileProgramMetadata | null,
|
||||
): void {
|
||||
const traversalState: TraversalState = {
|
||||
shouldInvalidateScopes: true,
|
||||
program: path,
|
||||
filename,
|
||||
logger,
|
||||
transformErrors: compileResult?.retryErrors ?? [],
|
||||
inferredEffectLocations:
|
||||
compileResult?.inferredEffectLocations ?? new Set(),
|
||||
};
|
||||
path.traverse({
|
||||
ImportDeclaration(path: NodePath<t.ImportDeclaration>) {
|
||||
const importSpecifierChecks = moduleLoadChecks.get(
|
||||
path.node.source.value,
|
||||
);
|
||||
if (importSpecifierChecks == null) {
|
||||
return;
|
||||
}
|
||||
const specifiers = path.get('specifiers');
|
||||
for (const specifier of specifiers) {
|
||||
if (specifier.isImportSpecifier()) {
|
||||
validateImportSpecifier(
|
||||
specifier,
|
||||
importSpecifierChecks,
|
||||
traversalState,
|
||||
);
|
||||
} else {
|
||||
validateNamespacedImport(
|
||||
specifier as NodePath<
|
||||
t.ImportNamespaceSpecifier | t.ImportDefaultSpecifier
|
||||
>,
|
||||
importSpecifierChecks,
|
||||
traversalState,
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function matchCompilerDiagnostic(
|
||||
badReference: NodePath<t.Node>,
|
||||
transformErrors: Array<{fn: NodePath<t.Node>; error: CompilerError}>,
|
||||
): string | null {
|
||||
for (const {fn, error} of transformErrors) {
|
||||
if (fn.isAncestor(badReference)) {
|
||||
return error.toString();
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
CompilerSuggestionOperation,
|
||||
ErrorCategory,
|
||||
} from '../CompilerError';
|
||||
import {Err, Ok, Result} from '../Utils/Result';
|
||||
import {assertExhaustive, hasNode} from '../Utils/utils';
|
||||
import {Environment} from './Environment';
|
||||
import {
|
||||
@@ -75,7 +74,7 @@ export function lower(
|
||||
// Bindings captured from the outer function, in case lower() is called recursively (for lambdas)
|
||||
bindings: Bindings | null = null,
|
||||
capturedRefs: Map<t.Identifier, SourceLocation> = new Map(),
|
||||
): Result<HIRFunction, CompilerError> {
|
||||
): HIRFunction {
|
||||
const builder = new HIRBuilder(env, {
|
||||
bindings,
|
||||
context: capturedRefs,
|
||||
@@ -186,32 +185,51 @@ export function lower(
|
||||
|
||||
let directives: Array<string> = [];
|
||||
const body = func.get('body');
|
||||
if (body.isExpression()) {
|
||||
const fallthrough = builder.reserve('block');
|
||||
const terminal: ReturnTerminal = {
|
||||
kind: 'return',
|
||||
returnVariant: 'Implicit',
|
||||
loc: GeneratedSource,
|
||||
value: lowerExpressionToTemporary(builder, body),
|
||||
id: makeInstructionId(0),
|
||||
effects: null,
|
||||
};
|
||||
builder.terminateWithContinuation(terminal, fallthrough);
|
||||
} else if (body.isBlockStatement()) {
|
||||
lowerStatement(builder, body);
|
||||
directives = body.get('directives').map(d => d.node.value.value);
|
||||
} else {
|
||||
builder.errors.pushDiagnostic(
|
||||
CompilerDiagnostic.create({
|
||||
category: ErrorCategory.Syntax,
|
||||
reason: `Unexpected function body kind`,
|
||||
description: `Expected function body to be an expression or a block statement, got \`${body.type}\``,
|
||||
}).withDetails({
|
||||
kind: 'error',
|
||||
loc: body.node.loc ?? null,
|
||||
message: 'Expected a block statement or expression',
|
||||
}),
|
||||
);
|
||||
try {
|
||||
if (body.isExpression()) {
|
||||
const fallthrough = builder.reserve('block');
|
||||
const terminal: ReturnTerminal = {
|
||||
kind: 'return',
|
||||
returnVariant: 'Implicit',
|
||||
loc: GeneratedSource,
|
||||
value: lowerExpressionToTemporary(builder, body),
|
||||
id: makeInstructionId(0),
|
||||
effects: null,
|
||||
};
|
||||
builder.terminateWithContinuation(terminal, fallthrough);
|
||||
} else if (body.isBlockStatement()) {
|
||||
lowerStatement(builder, body);
|
||||
directives = body.get('directives').map(d => d.node.value.value);
|
||||
} else {
|
||||
builder.errors.pushDiagnostic(
|
||||
CompilerDiagnostic.create({
|
||||
category: ErrorCategory.Syntax,
|
||||
reason: `Unexpected function body kind`,
|
||||
description: `Expected function body to be an expression or a block statement, got \`${body.type}\``,
|
||||
}).withDetails({
|
||||
kind: 'error',
|
||||
loc: body.node.loc ?? null,
|
||||
message: 'Expected a block statement or expression',
|
||||
}),
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof CompilerError) {
|
||||
// Re-throw invariant errors immediately
|
||||
for (const detail of err.details) {
|
||||
if (
|
||||
(detail instanceof CompilerDiagnostic
|
||||
? detail.category
|
||||
: detail.category) === ErrorCategory.Invariant
|
||||
) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
// Record non-invariant errors and continue to produce partial HIR
|
||||
builder.errors.merge(err);
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
let validatedId: HIRFunction['id'] = null;
|
||||
@@ -224,10 +242,6 @@ export function lower(
|
||||
}
|
||||
}
|
||||
|
||||
if (builder.errors.hasAnyErrors()) {
|
||||
return Err(builder.errors);
|
||||
}
|
||||
|
||||
builder.terminate(
|
||||
{
|
||||
kind: 'return',
|
||||
@@ -244,23 +258,29 @@ export function lower(
|
||||
null,
|
||||
);
|
||||
|
||||
return Ok({
|
||||
const hirBody = builder.build();
|
||||
|
||||
// Record all accumulated errors (including any from build()) on env
|
||||
if (builder.errors.hasAnyErrors()) {
|
||||
env.recordErrors(builder.errors);
|
||||
}
|
||||
|
||||
return {
|
||||
id: validatedId,
|
||||
nameHint: null,
|
||||
params,
|
||||
fnType: bindings == null ? env.fnType : 'Other',
|
||||
returnTypeAnnotation: null, // TODO: extract the actual return type node if present
|
||||
returns: createTemporaryPlace(env, func.node.loc ?? GeneratedSource),
|
||||
body: builder.build(),
|
||||
body: hirBody,
|
||||
context,
|
||||
generator: func.node.generator === true,
|
||||
async: func.node.async === true,
|
||||
loc: func.node.loc ?? GeneratedSource,
|
||||
env,
|
||||
effects: null,
|
||||
aliasingEffects: null,
|
||||
directives,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
// Helper to lower a statement
|
||||
@@ -555,6 +575,24 @@ function lowerStatement(
|
||||
|
||||
const initBlock = builder.enter('loop', _blockId => {
|
||||
const init = stmt.get('init');
|
||||
if (init.node == null) {
|
||||
/*
|
||||
* No init expression (e.g., `for (; ...)`), add a placeholder to avoid
|
||||
* invariant about empty blocks
|
||||
*/
|
||||
lowerValueToTemporary(builder, {
|
||||
kind: 'Primitive',
|
||||
value: undefined,
|
||||
loc: stmt.node.loc ?? GeneratedSource,
|
||||
});
|
||||
return {
|
||||
kind: 'goto',
|
||||
block: testBlock.id,
|
||||
variant: GotoVariant.Break,
|
||||
id: makeInstructionId(0),
|
||||
loc: stmt.node.loc ?? GeneratedSource,
|
||||
};
|
||||
}
|
||||
if (!init.isVariableDeclaration()) {
|
||||
builder.errors.push({
|
||||
reason:
|
||||
@@ -563,8 +601,14 @@ function lowerStatement(
|
||||
loc: stmt.node.loc ?? null,
|
||||
suggestions: null,
|
||||
});
|
||||
// Lower the init expression as best-effort and continue
|
||||
if (init.isExpression()) {
|
||||
lowerExpressionToTemporary(builder, init as NodePath<t.Expression>);
|
||||
}
|
||||
return {
|
||||
kind: 'unsupported',
|
||||
kind: 'goto',
|
||||
block: testBlock.id,
|
||||
variant: GotoVariant.Break,
|
||||
id: makeInstructionId(0),
|
||||
loc: init.node?.loc ?? GeneratedSource,
|
||||
};
|
||||
@@ -635,6 +679,23 @@ function lowerStatement(
|
||||
loc: stmt.node.loc ?? null,
|
||||
suggestions: null,
|
||||
});
|
||||
// Treat `for(;;)` as `while(true)` to keep the builder state consistent
|
||||
builder.terminateWithContinuation(
|
||||
{
|
||||
kind: 'branch',
|
||||
test: lowerValueToTemporary(builder, {
|
||||
kind: 'Primitive',
|
||||
value: true,
|
||||
loc: stmt.node.loc ?? GeneratedSource,
|
||||
}),
|
||||
consequent: bodyBlock,
|
||||
alternate: continuationBlock.id,
|
||||
fallthrough: continuationBlock.id,
|
||||
id: makeInstructionId(0),
|
||||
loc: stmt.node.loc ?? GeneratedSource,
|
||||
},
|
||||
continuationBlock,
|
||||
);
|
||||
} else {
|
||||
builder.terminateWithContinuation(
|
||||
{
|
||||
@@ -858,10 +919,12 @@ function lowerStatement(
|
||||
loc: stmt.node.loc ?? null,
|
||||
suggestions: null,
|
||||
});
|
||||
return;
|
||||
// Treat `var` as `let` so references to the variable don't break
|
||||
}
|
||||
const kind =
|
||||
nodeKind === 'let' ? InstructionKind.Let : InstructionKind.Const;
|
||||
nodeKind === 'let' || nodeKind === 'var'
|
||||
? InstructionKind.Let
|
||||
: InstructionKind.Const;
|
||||
for (const declaration of stmt.get('declarations')) {
|
||||
const id = declaration.get('id');
|
||||
const init = declaration.get('init');
|
||||
@@ -1494,9 +1557,6 @@ function lowerObjectMethod(
|
||||
): InstructionValue {
|
||||
const loc = property.node.loc ?? GeneratedSource;
|
||||
const loweredFunc = lowerFunction(builder, property);
|
||||
if (!loweredFunc) {
|
||||
return {kind: 'UnsupportedNode', node: property.node, loc: loc};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'ObjectMethod',
|
||||
@@ -2276,18 +2336,20 @@ function lowerExpression(
|
||||
});
|
||||
for (const [name, locations] of Object.entries(fbtLocations)) {
|
||||
if (locations.length > 1) {
|
||||
CompilerError.throwDiagnostic({
|
||||
category: ErrorCategory.Todo,
|
||||
reason: 'Support duplicate fbt tags',
|
||||
description: `Support \`<${tagName}>\` tags with multiple \`<${tagName}:${name}>\` values`,
|
||||
details: locations.map(loc => {
|
||||
return {
|
||||
kind: 'error',
|
||||
message: `Multiple \`<${tagName}:${name}>\` tags found`,
|
||||
loc,
|
||||
};
|
||||
builder.errors.pushDiagnostic(
|
||||
new CompilerDiagnostic({
|
||||
category: ErrorCategory.Todo,
|
||||
reason: 'Support duplicate fbt tags',
|
||||
description: `Support \`<${tagName}>\` tags with multiple \`<${tagName}:${name}>\` values`,
|
||||
details: locations.map(loc => {
|
||||
return {
|
||||
kind: 'error' as const,
|
||||
message: `Multiple \`<${tagName}:${name}>\` tags found`,
|
||||
loc,
|
||||
};
|
||||
}),
|
||||
}),
|
||||
});
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3468,9 +3530,6 @@ function lowerFunctionToValue(
|
||||
const exprNode = expr.node;
|
||||
const exprLoc = exprNode.loc ?? GeneratedSource;
|
||||
const loweredFunc = lowerFunction(builder, expr);
|
||||
if (!loweredFunc) {
|
||||
return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
|
||||
}
|
||||
return {
|
||||
kind: 'FunctionExpression',
|
||||
name: loweredFunc.func.id,
|
||||
@@ -3489,7 +3548,7 @@ function lowerFunction(
|
||||
| t.FunctionDeclaration
|
||||
| t.ObjectMethod
|
||||
>,
|
||||
): LoweredFunction | null {
|
||||
): LoweredFunction {
|
||||
const componentScope: Scope = builder.environment.parentFunction.scope;
|
||||
const capturedContext = gatherCapturedContext(expr, componentScope);
|
||||
|
||||
@@ -3501,19 +3560,12 @@ function lowerFunction(
|
||||
* This isn't a problem in practice because use Babel's scope analysis to
|
||||
* identify the correct references.
|
||||
*/
|
||||
const lowering = lower(
|
||||
const loweredFunc = lower(
|
||||
expr,
|
||||
builder.environment,
|
||||
builder.bindings,
|
||||
new Map([...builder.context, ...capturedContext]),
|
||||
);
|
||||
let loweredFunc: HIRFunction;
|
||||
if (lowering.isErr()) {
|
||||
const functionErrors = lowering.unwrapErr();
|
||||
builder.errors.merge(functionErrors);
|
||||
return null;
|
||||
}
|
||||
loweredFunc = lowering.unwrap();
|
||||
return {
|
||||
func: loweredFunc,
|
||||
};
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
PropertyLiteral,
|
||||
ReactiveScopeDependency,
|
||||
ScopeId,
|
||||
SourceLocation,
|
||||
TInstruction,
|
||||
} from './HIR';
|
||||
|
||||
@@ -123,9 +124,7 @@ export function collectHoistablePropertyLoads(
|
||||
hoistableFromOptionals,
|
||||
registry,
|
||||
nestedFnImmutableContext: null,
|
||||
assumedInvokedFns: fn.env.config.enableTreatFunctionDepsAsConditional
|
||||
? new Set()
|
||||
: getAssumedInvokedFunctions(fn),
|
||||
assumedInvokedFns: getAssumedInvokedFunctions(fn),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -141,9 +140,7 @@ export function collectHoistablePropertyLoadsInInnerFn(
|
||||
hoistableFromOptionals,
|
||||
registry: new PropertyPathRegistry(),
|
||||
nestedFnImmutableContext: null,
|
||||
assumedInvokedFns: fn.env.config.enableTreatFunctionDepsAsConditional
|
||||
? new Set()
|
||||
: getAssumedInvokedFunctions(fn),
|
||||
assumedInvokedFns: getAssumedInvokedFunctions(fn),
|
||||
};
|
||||
const nestedFnImmutableContext = new Set(
|
||||
fn.context
|
||||
@@ -244,6 +241,7 @@ class PropertyPathRegistry {
|
||||
getOrCreateIdentifier(
|
||||
identifier: Identifier,
|
||||
reactive: boolean,
|
||||
loc: SourceLocation,
|
||||
): PropertyPathNode {
|
||||
/**
|
||||
* Reads from a statically scoped variable are always safe in JS,
|
||||
@@ -260,6 +258,7 @@ class PropertyPathRegistry {
|
||||
identifier,
|
||||
reactive,
|
||||
path: [],
|
||||
loc,
|
||||
},
|
||||
hasOptional: false,
|
||||
parent: null,
|
||||
@@ -290,6 +289,7 @@ class PropertyPathRegistry {
|
||||
identifier: parent.fullPath.identifier,
|
||||
reactive: parent.fullPath.reactive,
|
||||
path: parent.fullPath.path.concat(entry),
|
||||
loc: entry.loc,
|
||||
},
|
||||
hasOptional: parent.hasOptional || entry.optional,
|
||||
};
|
||||
@@ -304,7 +304,7 @@ class PropertyPathRegistry {
|
||||
* so all subpaths of a PropertyLoad should already exist
|
||||
* (e.g. a.b is added before a.b.c),
|
||||
*/
|
||||
let currNode = this.getOrCreateIdentifier(n.identifier, n.reactive);
|
||||
let currNode = this.getOrCreateIdentifier(n.identifier, n.reactive, n.loc);
|
||||
if (n.path.length === 0) {
|
||||
return currNode;
|
||||
}
|
||||
@@ -323,20 +323,21 @@ class PropertyPathRegistry {
|
||||
}
|
||||
|
||||
function getMaybeNonNullInInstruction(
|
||||
instr: InstructionValue,
|
||||
value: InstructionValue,
|
||||
context: CollectHoistablePropertyLoadsContext,
|
||||
): PropertyPathNode | null {
|
||||
let path: ReactiveScopeDependency | null = null;
|
||||
if (instr.kind === 'PropertyLoad') {
|
||||
path = context.temporaries.get(instr.object.identifier.id) ?? {
|
||||
identifier: instr.object.identifier,
|
||||
reactive: instr.object.reactive,
|
||||
if (value.kind === 'PropertyLoad') {
|
||||
path = context.temporaries.get(value.object.identifier.id) ?? {
|
||||
identifier: value.object.identifier,
|
||||
reactive: value.object.reactive,
|
||||
path: [],
|
||||
loc: value.loc,
|
||||
};
|
||||
} else if (instr.kind === 'Destructure') {
|
||||
path = context.temporaries.get(instr.value.identifier.id) ?? null;
|
||||
} else if (instr.kind === 'ComputedLoad') {
|
||||
path = context.temporaries.get(instr.object.identifier.id) ?? null;
|
||||
} else if (value.kind === 'Destructure') {
|
||||
path = context.temporaries.get(value.value.identifier.id) ?? null;
|
||||
} else if (value.kind === 'ComputedLoad') {
|
||||
path = context.temporaries.get(value.object.identifier.id) ?? null;
|
||||
}
|
||||
return path != null ? context.registry.getOrCreateProperty(path) : null;
|
||||
}
|
||||
@@ -393,7 +394,11 @@ function collectNonNullsInBlocks(
|
||||
) {
|
||||
const identifier = fn.params[0].identifier;
|
||||
knownNonNullIdentifiers.add(
|
||||
context.registry.getOrCreateIdentifier(identifier, true),
|
||||
context.registry.getOrCreateIdentifier(
|
||||
identifier,
|
||||
true,
|
||||
fn.params[0].loc,
|
||||
),
|
||||
);
|
||||
}
|
||||
const nodes = new Map<
|
||||
@@ -468,6 +473,7 @@ function collectNonNullsInBlocks(
|
||||
identifier: dep.root.value.identifier,
|
||||
path: dep.path.slice(0, i),
|
||||
reactive: dep.root.value.reactive,
|
||||
loc: dep.loc,
|
||||
});
|
||||
assumedNonNullObjects.add(depNode);
|
||||
}
|
||||
@@ -654,17 +660,23 @@ function reduceMaybeOptionalChains(
|
||||
changed = false;
|
||||
|
||||
for (const original of optionalChainNodes) {
|
||||
let {identifier, path: origPath, reactive} = original.fullPath;
|
||||
let {
|
||||
identifier,
|
||||
path: origPath,
|
||||
reactive,
|
||||
loc: origLoc,
|
||||
} = original.fullPath;
|
||||
let currNode: PropertyPathNode = registry.getOrCreateIdentifier(
|
||||
identifier,
|
||||
reactive,
|
||||
origLoc,
|
||||
);
|
||||
for (let i = 0; i < origPath.length; i++) {
|
||||
const entry = origPath[i];
|
||||
// If the base is known to be non-null, replace with a non-optional load
|
||||
const nextEntry: DependencyPathEntry =
|
||||
entry.optional && nodes.has(currNode)
|
||||
? {property: entry.property, optional: false}
|
||||
? {property: entry.property, optional: false, loc: entry.loc}
|
||||
: entry;
|
||||
currNode = PropertyPathRegistry.getOrCreatePropertyEntry(
|
||||
currNode,
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {CompilerError} from '..';
|
||||
import {CompilerError, SourceLocation} from '..';
|
||||
import {assertNonNull} from './CollectHoistablePropertyLoads';
|
||||
import {
|
||||
BlockId,
|
||||
@@ -169,6 +169,7 @@ function matchOptionalTestBlock(
|
||||
propertyId: IdentifierId;
|
||||
storeLocalInstr: Instruction;
|
||||
consequentGoto: BlockId;
|
||||
propertyLoadLoc: SourceLocation;
|
||||
} | null {
|
||||
const consequentBlock = assertNonNull(blocks.get(terminal.consequent));
|
||||
if (
|
||||
@@ -221,6 +222,7 @@ function matchOptionalTestBlock(
|
||||
propertyId: propertyLoad.lvalue.identifier.id,
|
||||
storeLocalInstr,
|
||||
consequentGoto: consequentBlock.terminal.block,
|
||||
propertyLoadLoc: propertyLoad.loc,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
@@ -275,7 +277,11 @@ function traverseOptionalBlock(
|
||||
instrVal.kind === 'PropertyLoad' &&
|
||||
instrVal.object.identifier.id === prevInstr.lvalue.identifier.id
|
||||
) {
|
||||
path.push({property: instrVal.property, optional: false});
|
||||
path.push({
|
||||
property: instrVal.property,
|
||||
optional: false,
|
||||
loc: instrVal.loc,
|
||||
});
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
@@ -292,6 +298,7 @@ function traverseOptionalBlock(
|
||||
identifier: maybeTest.instructions[0].value.place.identifier,
|
||||
reactive: maybeTest.instructions[0].value.place.reactive,
|
||||
path,
|
||||
loc: maybeTest.instructions[0].value.place.loc,
|
||||
};
|
||||
test = maybeTest.terminal;
|
||||
} else if (maybeTest.terminal.kind === 'optional') {
|
||||
@@ -390,7 +397,7 @@ function traverseOptionalBlock(
|
||||
loc: optional.terminal.loc,
|
||||
},
|
||||
);
|
||||
const load = {
|
||||
const load: ReactiveScopeDependency = {
|
||||
identifier: baseObject.identifier,
|
||||
reactive: baseObject.reactive,
|
||||
path: [
|
||||
@@ -398,8 +405,10 @@ function traverseOptionalBlock(
|
||||
{
|
||||
property: matchConsequentResult.property,
|
||||
optional: optional.terminal.optional,
|
||||
loc: matchConsequentResult.propertyLoadLoc,
|
||||
},
|
||||
],
|
||||
loc: matchConsequentResult.propertyLoadLoc,
|
||||
};
|
||||
context.processedInstrsInOptional.add(matchConsequentResult.storeLocalInstr);
|
||||
context.processedInstrsInOptional.add(test);
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
Identifier,
|
||||
PropertyLiteral,
|
||||
ReactiveScopeDependency,
|
||||
SourceLocation,
|
||||
} from '../HIR';
|
||||
import {printIdentifier} from '../HIR/PrintHIR';
|
||||
|
||||
@@ -36,12 +37,13 @@ export class ReactiveScopeDependencyTreeHIR {
|
||||
* duplicates when traversing the CFG.
|
||||
*/
|
||||
constructor(hoistableObjects: Iterable<ReactiveScopeDependency>) {
|
||||
for (const {path, identifier, reactive} of hoistableObjects) {
|
||||
for (const {path, identifier, reactive, loc} of hoistableObjects) {
|
||||
let currNode = ReactiveScopeDependencyTreeHIR.#getOrCreateRoot(
|
||||
identifier,
|
||||
reactive,
|
||||
this.#hoistableObjects,
|
||||
path.length > 0 && path[0].optional ? 'Optional' : 'NonNull',
|
||||
loc,
|
||||
);
|
||||
|
||||
for (let i = 0; i < path.length; i++) {
|
||||
@@ -62,6 +64,7 @@ export class ReactiveScopeDependencyTreeHIR {
|
||||
nextNode = {
|
||||
properties: new Map(),
|
||||
accessType,
|
||||
loc: path[i].loc,
|
||||
};
|
||||
currNode.properties.set(path[i].property, nextNode);
|
||||
}
|
||||
@@ -75,6 +78,7 @@ export class ReactiveScopeDependencyTreeHIR {
|
||||
reactive: boolean,
|
||||
roots: Map<Identifier, TreeNode<T> & {reactive: boolean}>,
|
||||
defaultAccessType: T,
|
||||
loc: SourceLocation,
|
||||
): TreeNode<T> {
|
||||
// roots can always be accessed unconditionally in JS
|
||||
let rootNode = roots.get(identifier);
|
||||
@@ -84,6 +88,7 @@ export class ReactiveScopeDependencyTreeHIR {
|
||||
properties: new Map(),
|
||||
reactive,
|
||||
accessType: defaultAccessType,
|
||||
loc,
|
||||
};
|
||||
roots.set(identifier, rootNode);
|
||||
} else {
|
||||
@@ -102,12 +107,13 @@ export class ReactiveScopeDependencyTreeHIR {
|
||||
* safe-to-evaluate subpath
|
||||
*/
|
||||
addDependency(dep: ReactiveScopeDependency): void {
|
||||
const {identifier, reactive, path} = dep;
|
||||
const {identifier, reactive, path, loc} = dep;
|
||||
let depCursor = ReactiveScopeDependencyTreeHIR.#getOrCreateRoot(
|
||||
identifier,
|
||||
reactive,
|
||||
this.#deps,
|
||||
PropertyAccessType.UnconditionalAccess,
|
||||
loc,
|
||||
);
|
||||
/**
|
||||
* hoistableCursor is null if depCursor is not an object we can hoist
|
||||
@@ -153,6 +159,7 @@ export class ReactiveScopeDependencyTreeHIR {
|
||||
depCursor,
|
||||
entry.property,
|
||||
accessType,
|
||||
entry.loc,
|
||||
);
|
||||
} else if (
|
||||
hoistableCursor != null &&
|
||||
@@ -163,6 +170,7 @@ export class ReactiveScopeDependencyTreeHIR {
|
||||
depCursor,
|
||||
entry.property,
|
||||
PropertyAccessType.UnconditionalAccess,
|
||||
entry.loc,
|
||||
);
|
||||
} else {
|
||||
/**
|
||||
@@ -306,6 +314,7 @@ function merge(
|
||||
type TreeNode<T extends string> = {
|
||||
properties: Map<PropertyLiteral, TreeNode<T>>;
|
||||
accessType: T;
|
||||
loc: SourceLocation;
|
||||
};
|
||||
type HoistableNode = TreeNode<'Optional' | 'NonNull'>;
|
||||
type DependencyNode = TreeNode<PropertyAccessType>;
|
||||
@@ -323,7 +332,7 @@ function collectMinimalDependenciesInSubtree(
|
||||
results: Set<ReactiveScopeDependency>,
|
||||
): void {
|
||||
if (isDependency(node.accessType)) {
|
||||
results.add({identifier: rootIdentifier, reactive, path});
|
||||
results.add({identifier: rootIdentifier, reactive, path, loc: node.loc});
|
||||
} else {
|
||||
for (const [childName, childNode] of node.properties) {
|
||||
collectMinimalDependenciesInSubtree(
|
||||
@@ -335,6 +344,7 @@ function collectMinimalDependenciesInSubtree(
|
||||
{
|
||||
property: childName,
|
||||
optional: isOptional(childNode.accessType),
|
||||
loc: childNode.loc,
|
||||
},
|
||||
],
|
||||
results,
|
||||
@@ -362,12 +372,14 @@ function makeOrMergeProperty(
|
||||
node: DependencyNode,
|
||||
property: PropertyLiteral,
|
||||
accessType: PropertyAccessType,
|
||||
loc: SourceLocation,
|
||||
): DependencyNode {
|
||||
let child = node.properties.get(property);
|
||||
if (child == null) {
|
||||
child = {
|
||||
properties: new Map(),
|
||||
accessType,
|
||||
loc,
|
||||
};
|
||||
node.properties.set(property, child);
|
||||
} else {
|
||||
|
||||
@@ -8,7 +8,12 @@
|
||||
import * as t from '@babel/types';
|
||||
import {ZodError, z} from 'zod/v4';
|
||||
import {fromZodError} from 'zod-validation-error/v4';
|
||||
import {CompilerError} from '../CompilerError';
|
||||
import {
|
||||
CompilerDiagnostic,
|
||||
CompilerError,
|
||||
CompilerErrorDetail,
|
||||
ErrorCategory,
|
||||
} from '../CompilerError';
|
||||
import {CompilerOutputMode, Logger, ProgramContext} from '../Entrypoint';
|
||||
import {Err, Ok, Result} from '../Utils/Result';
|
||||
import {
|
||||
@@ -54,14 +59,6 @@ import {FlowTypeEnv} from '../Flood/Types';
|
||||
import {defaultModuleTypeProvider} from './DefaultModuleTypeProvider';
|
||||
import {assertExhaustive} from '../Utils/utils';
|
||||
|
||||
export const ReactElementSymbolSchema = z.object({
|
||||
elementSymbol: z.union([
|
||||
z.literal('react.element'),
|
||||
z.literal('react.transitional.element'),
|
||||
]),
|
||||
globalDevVar: z.string(),
|
||||
});
|
||||
|
||||
export const ExternalFunctionSchema = z.object({
|
||||
// Source for the imported module that exports the `importSpecifierName` functions
|
||||
source: z.string(),
|
||||
@@ -82,8 +79,6 @@ export const InstrumentationSchema = z
|
||||
);
|
||||
|
||||
export type ExternalFunction = z.infer<typeof ExternalFunctionSchema>;
|
||||
export const USE_FIRE_FUNCTION_NAME = 'useFire';
|
||||
export const EMIT_FREEZE_GLOBAL_GATING = '__DEV__';
|
||||
|
||||
export const MacroSchema = z.string();
|
||||
|
||||
@@ -236,24 +231,9 @@ export const EnvironmentConfigSchema = z.object({
|
||||
.enum(['off', 'all', 'missing-only', 'extra-only'])
|
||||
.default('off'),
|
||||
|
||||
/**
|
||||
* When this is true, rather than pruning existing manual memoization but ensuring or validating
|
||||
* that the memoized values remain memoized, the compiler will simply not prune existing calls to
|
||||
* useMemo/useCallback.
|
||||
*/
|
||||
enablePreserveExistingManualUseMemo: z.boolean().default(false),
|
||||
|
||||
// 🌲
|
||||
enableForest: z.boolean().default(false),
|
||||
|
||||
/**
|
||||
* Enable use of type annotations in the source to drive type inference. By default
|
||||
* Forget attemps to infer types using only information that is guaranteed correct
|
||||
* given the source, and does not trust user-supplied type annotations. This mode
|
||||
* enables trusting user type annotations.
|
||||
*/
|
||||
enableUseTypeAnnotations: z.boolean().default(false),
|
||||
|
||||
/**
|
||||
* Allows specifying a function that can populate HIR with type information from
|
||||
* Flow
|
||||
@@ -268,53 +248,8 @@ export const EnvironmentConfigSchema = z.object({
|
||||
*/
|
||||
enableOptionalDependencies: z.boolean().default(true),
|
||||
|
||||
enableFire: z.boolean().default(false),
|
||||
|
||||
enableNameAnonymousFunctions: z.boolean().default(false),
|
||||
|
||||
/**
|
||||
* Enables inference and auto-insertion of effect dependencies. Takes in an array of
|
||||
* configurable module and import pairs to allow for user-land experimentation. For example,
|
||||
* [
|
||||
* {
|
||||
* module: 'react',
|
||||
* imported: 'useEffect',
|
||||
* autodepsIndex: 1,
|
||||
* },{
|
||||
* module: 'MyExperimentalEffectHooks',
|
||||
* imported: 'useExperimentalEffect',
|
||||
* autodepsIndex: 2,
|
||||
* },
|
||||
* ]
|
||||
* would insert dependencies for calls of `useEffect` imported from `react` and calls of
|
||||
* useExperimentalEffect` from `MyExperimentalEffectHooks`.
|
||||
*
|
||||
* `autodepsIndex` tells the compiler which index we expect the AUTODEPS to appear in.
|
||||
* With the configuration above, we'd insert dependencies for `useEffect` if it has two
|
||||
* arguments, and the second is AUTODEPS.
|
||||
*
|
||||
* Still experimental.
|
||||
*/
|
||||
inferEffectDependencies: z
|
||||
.nullable(
|
||||
z.array(
|
||||
z.object({
|
||||
function: ExternalFunctionSchema,
|
||||
autodepsIndex: z.number().min(1, 'autodepsIndex must be > 0'),
|
||||
}),
|
||||
),
|
||||
)
|
||||
.default(null),
|
||||
|
||||
/**
|
||||
* Enables inlining ReactElement object literals in place of JSX
|
||||
* An alternative to the standard JSX transform which replaces JSX with React's jsxProd() runtime
|
||||
* Currently a prod-only optimization, requiring Fast JSX dependencies
|
||||
*
|
||||
* The symbol configuration is set for backwards compatability with pre-React 19 transforms
|
||||
*/
|
||||
inlineJsxTransform: ReactElementSymbolSchema.nullable().default(null),
|
||||
|
||||
/*
|
||||
* Enable validation of hooks to partially check that the component honors the rules of hooks.
|
||||
* When disabled, the component is assumed to follow the rules (though the Babel plugin looks
|
||||
@@ -366,16 +301,6 @@ export const EnvironmentConfigSchema = z.object({
|
||||
*/
|
||||
validateStaticComponents: z.boolean().default(false),
|
||||
|
||||
/**
|
||||
* Validates that the dependencies of all effect hooks are memoized. This helps ensure
|
||||
* that Forget does not introduce infinite renders caused by a dependency changing,
|
||||
* triggering an effect, which triggers re-rendering, which causes a dependency to change,
|
||||
* triggering the effect, etc.
|
||||
*
|
||||
* Covers useEffect, useLayoutEffect, useInsertionEffect.
|
||||
*/
|
||||
validateMemoizedEffectDependencies: z.boolean().default(false),
|
||||
|
||||
/**
|
||||
* Validates that there are no capitalized calls other than those allowed by the allowlist.
|
||||
* Calls to capitalized functions are often functions that used to be components and may
|
||||
@@ -422,38 +347,8 @@ export const EnvironmentConfigSchema = z.object({
|
||||
* then this flag will assume that `x` is not subusequently modified.
|
||||
*/
|
||||
enableTransitivelyFreezeFunctionExpressions: z.boolean().default(true),
|
||||
|
||||
/*
|
||||
* Enables codegen mutability debugging. This emits a dev-mode only to log mutations
|
||||
* to values that Forget assumes are immutable (for Forget compiled code).
|
||||
* For example:
|
||||
* emitFreeze: {
|
||||
* source: 'ReactForgetRuntime',
|
||||
* importSpecifierName: 'makeReadOnly',
|
||||
* }
|
||||
*
|
||||
* produces:
|
||||
* import {makeReadOnly} from 'ReactForgetRuntime';
|
||||
*
|
||||
* function Component(props) {
|
||||
* if (c_0) {
|
||||
* // ...
|
||||
* $[0] = __DEV__ ? makeReadOnly(x) : x;
|
||||
* } else {
|
||||
* x = $[0];
|
||||
* }
|
||||
* }
|
||||
*/
|
||||
enableEmitFreeze: ExternalFunctionSchema.nullable().default(null),
|
||||
|
||||
enableEmitHookGuards: ExternalFunctionSchema.nullable().default(null),
|
||||
|
||||
/**
|
||||
* Enable instruction reordering. See InstructionReordering.ts for the details
|
||||
* of the approach.
|
||||
*/
|
||||
enableInstructionReordering: z.boolean().default(false),
|
||||
|
||||
/**
|
||||
* Enables function outlinining, where anonymous functions that do not close over
|
||||
* local variables can be extracted into top-level helper functions.
|
||||
@@ -535,80 +430,12 @@ export const EnvironmentConfigSchema = z.object({
|
||||
// Enable validation of mutable ranges
|
||||
assertValidMutableRanges: z.boolean().default(false),
|
||||
|
||||
/*
|
||||
* Enable emitting "change variables" which store the result of whether a particular
|
||||
* reactive scope dependency has changed since the scope was last executed.
|
||||
*
|
||||
* Ex:
|
||||
* ```
|
||||
* const c_0 = $[0] !== input; // change variable
|
||||
* let output;
|
||||
* if (c_0) ...
|
||||
* ```
|
||||
*
|
||||
* Defaults to false, where the comparison is inlined:
|
||||
*
|
||||
* ```
|
||||
* let output;
|
||||
* if ($[0] !== input) ...
|
||||
* ```
|
||||
*/
|
||||
enableChangeVariableCodegen: z.boolean().default(false),
|
||||
|
||||
/**
|
||||
* Enable emitting comments that explain Forget's output, and which
|
||||
* values are being checked and which values produced by each memo block.
|
||||
*
|
||||
* Intended for use in demo purposes (incl playground)
|
||||
*/
|
||||
enableMemoizationComments: z.boolean().default(false),
|
||||
|
||||
/**
|
||||
* [TESTING ONLY] Throw an unknown exception during compilation to
|
||||
* simulate unexpected exceptions e.g. errors from babel functions.
|
||||
*/
|
||||
throwUnknownException__testonly: z.boolean().default(false),
|
||||
|
||||
/**
|
||||
* Enables deps of a function epxression to be treated as conditional. This
|
||||
* makes sure we don't load a dep when it's a property (to check if it has
|
||||
* changed) and instead check the receiver.
|
||||
*
|
||||
* This makes sure we don't end up throwing when the reciver is null. Consider
|
||||
* this code:
|
||||
*
|
||||
* ```
|
||||
* function getLength() {
|
||||
* return props.bar.length;
|
||||
* }
|
||||
* ```
|
||||
*
|
||||
* It's only safe to memoize `getLength` against props, not props.bar, as
|
||||
* props.bar could be null when this `getLength` function is created.
|
||||
*
|
||||
* This does cause the memoization to now be coarse grained, which is
|
||||
* non-ideal.
|
||||
*/
|
||||
enableTreatFunctionDepsAsConditional: z.boolean().default(false),
|
||||
|
||||
/**
|
||||
* When true, always act as though the dependencies of a memoized value
|
||||
* have changed. This makes the compiler not actually perform any optimizations,
|
||||
* but is useful for debugging. Implicitly also sets
|
||||
* @enablePreserveExistingManualUseMemo, because otherwise memoization in the
|
||||
* original source will be disabled as well.
|
||||
*/
|
||||
disableMemoizationForDebugging: z.boolean().default(false),
|
||||
|
||||
/**
|
||||
* When true, rather using memoized values, the compiler will always re-compute
|
||||
* values, and then use a heuristic to compare the memoized value to the newly
|
||||
* computed one. This detects cases where rules of react violations may cause the
|
||||
* compiled code to behave differently than the original.
|
||||
*/
|
||||
enableChangeDetectionForDebugging:
|
||||
ExternalFunctionSchema.nullable().default(null),
|
||||
|
||||
/**
|
||||
* The react native re-animated library uses custom Babel transforms that
|
||||
* requires the calls to library API remain unmodified.
|
||||
@@ -619,19 +446,6 @@ export const EnvironmentConfigSchema = z.object({
|
||||
*/
|
||||
enableCustomTypeDefinitionForReanimated: z.boolean().default(false),
|
||||
|
||||
/**
|
||||
* If specified, this value is used as a pattern for determing which global values should be
|
||||
* treated as hooks. The pattern should have a single capture group, which will be used as
|
||||
* the hook name for the purposes of resolving hook definitions (for builtin hooks)_.
|
||||
*
|
||||
* For example, by default `React$useState` would not be treated as a hook. By specifying
|
||||
* `hookPattern: 'React$(\w+)'`, the compiler will treat this value equivalently to `useState()`.
|
||||
*
|
||||
* This setting is intended for cases where Forget is compiling code that has been prebundled
|
||||
* and identifiers have been changed.
|
||||
*/
|
||||
hookPattern: z.string().nullable().default(null),
|
||||
|
||||
/**
|
||||
* If enabled, this will treat objects named as `ref` or if their names end with the substring `Ref`,
|
||||
* and contain a property named `current`, as React refs.
|
||||
@@ -656,28 +470,6 @@ export const EnvironmentConfigSchema = z.object({
|
||||
*/
|
||||
enableTreatSetIdentifiersAsStateSetters: z.boolean().default(false),
|
||||
|
||||
/*
|
||||
* If specified a value, the compiler lowers any calls to `useContext` to use
|
||||
* this value as the callee.
|
||||
*
|
||||
* A selector function is compiled and passed as an argument along with the
|
||||
* context to this function call.
|
||||
*
|
||||
* The compiler automatically figures out the keys by looking for the immediate
|
||||
* destructuring of the return value from the useContext call. In the future,
|
||||
* this can be extended to different kinds of context access like property
|
||||
* loads and accesses over multiple statements as well.
|
||||
*
|
||||
* ```
|
||||
* // input
|
||||
* const {foo, bar} = useContext(MyContext);
|
||||
*
|
||||
* // output
|
||||
* const {foo, bar} = useCompiledContext(MyContext, (c) => [c.foo, c.bar]);
|
||||
* ```
|
||||
*/
|
||||
lowerContextAccess: ExternalFunctionSchema.nullable().default(null),
|
||||
|
||||
/**
|
||||
* If enabled, will validate useMemos that don't return any values:
|
||||
*
|
||||
@@ -689,13 +481,6 @@ export const EnvironmentConfigSchema = z.object({
|
||||
*/
|
||||
validateNoVoidUseMemo: z.boolean().default(true),
|
||||
|
||||
/**
|
||||
* Validates that Components/Hooks are always defined at module level. This prevents scope
|
||||
* reference errors that occur when the compiler attempts to optimize the nested component/hook
|
||||
* while its parent function remains uncompiled.
|
||||
*/
|
||||
validateNoDynamicallyCreatedComponentsOrHooks: z.boolean().default(false),
|
||||
|
||||
/**
|
||||
* When enabled, allows setState calls in effects based on valid patterns involving refs:
|
||||
* - Allow setState where the value being set is derived from a ref. This is useful where
|
||||
@@ -717,15 +502,6 @@ export const EnvironmentConfigSchema = z.object({
|
||||
* 3. Force update / external sync - should use useSyncExternalStore
|
||||
*/
|
||||
enableVerboseNoSetStateInEffect: z.boolean().default(false),
|
||||
|
||||
/**
|
||||
* Enables inference of event handler types for JSX props on built-in DOM elements.
|
||||
* When enabled, functions passed to event handler props (props starting with "on")
|
||||
* on primitive JSX tags are inferred to have the BuiltinEventHandlerId type, which
|
||||
* allows ref access within those functions since DOM event handlers are guaranteed
|
||||
* by React to only execute in response to events, not during render.
|
||||
*/
|
||||
enableInferEventHandlers: z.boolean().default(false),
|
||||
});
|
||||
|
||||
export type EnvironmentConfig = z.infer<typeof EnvironmentConfigSchema>;
|
||||
@@ -767,9 +543,6 @@ export class Environment {
|
||||
fnType: ReactFunctionType;
|
||||
outputMode: CompilerOutputMode;
|
||||
programContext: ProgramContext;
|
||||
hasFireRewrite: boolean;
|
||||
hasInferredEffect: boolean;
|
||||
inferredEffectLocations: Set<SourceLocation> = new Set();
|
||||
|
||||
#contextIdentifiers: Set<t.Identifier>;
|
||||
#hoistedIdentifiers: Set<t.Identifier>;
|
||||
@@ -777,6 +550,12 @@ export class Environment {
|
||||
|
||||
#flowTypeEnvironment: FlowTypeEnv | null;
|
||||
|
||||
/**
|
||||
* Accumulated compilation errors. Passes record errors here instead of
|
||||
* throwing, so the pipeline can continue and report all errors at once.
|
||||
*/
|
||||
#errors: CompilerError = new CompilerError();
|
||||
|
||||
constructor(
|
||||
scope: BabelScope,
|
||||
fnType: ReactFunctionType,
|
||||
@@ -799,20 +578,6 @@ export class Environment {
|
||||
this.programContext = programContext;
|
||||
this.#shapes = new Map(DEFAULT_SHAPES);
|
||||
this.#globals = new Map(DEFAULT_GLOBALS);
|
||||
this.hasFireRewrite = false;
|
||||
this.hasInferredEffect = false;
|
||||
|
||||
if (
|
||||
config.disableMemoizationForDebugging &&
|
||||
config.enableChangeDetectionForDebugging != null
|
||||
) {
|
||||
CompilerError.throwInvalidConfig({
|
||||
reason: `Invalid environment config: the 'disableMemoizationForDebugging' and 'enableChangeDetectionForDebugging' options cannot be used together`,
|
||||
description: null,
|
||||
loc: null,
|
||||
suggestions: null,
|
||||
});
|
||||
}
|
||||
|
||||
for (const [hookName, hook] of this.config.customHooks) {
|
||||
CompilerError.invariant(!this.#globals.has(hookName), {
|
||||
@@ -875,9 +640,6 @@ export class Environment {
|
||||
case 'ssr': {
|
||||
return true;
|
||||
}
|
||||
case 'client-no-memo': {
|
||||
return false;
|
||||
}
|
||||
default: {
|
||||
assertExhaustive(
|
||||
this.outputMode,
|
||||
@@ -894,8 +656,7 @@ export class Environment {
|
||||
// linting also enables memoization so that we can check if manual memoization is preserved
|
||||
return true;
|
||||
}
|
||||
case 'ssr':
|
||||
case 'client-no-memo': {
|
||||
case 'ssr': {
|
||||
return false;
|
||||
}
|
||||
default: {
|
||||
@@ -914,9 +675,6 @@ export class Environment {
|
||||
case 'ssr': {
|
||||
return true;
|
||||
}
|
||||
case 'client-no-memo': {
|
||||
return false;
|
||||
}
|
||||
default: {
|
||||
assertExhaustive(
|
||||
this.outputMode,
|
||||
@@ -955,6 +713,75 @@ export class Environment {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Record a single diagnostic or error detail on this environment.
|
||||
* If the error is an Invariant, it is immediately thrown since invariants
|
||||
* represent internal bugs that cannot be recovered from.
|
||||
* Otherwise, the error is accumulated and optionally logged.
|
||||
*/
|
||||
recordError(error: CompilerDiagnostic | CompilerErrorDetail): void {
|
||||
if (error.category === ErrorCategory.Invariant) {
|
||||
const compilerError = new CompilerError();
|
||||
if (error instanceof CompilerDiagnostic) {
|
||||
compilerError.pushDiagnostic(error);
|
||||
} else {
|
||||
compilerError.pushErrorDetail(error);
|
||||
}
|
||||
throw compilerError;
|
||||
}
|
||||
if (error instanceof CompilerDiagnostic) {
|
||||
this.#errors.pushDiagnostic(error);
|
||||
} else {
|
||||
this.#errors.pushErrorDetail(error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Record all diagnostics from a CompilerError onto this environment.
|
||||
*/
|
||||
recordErrors(error: CompilerError): void {
|
||||
for (const detail of error.details) {
|
||||
this.recordError(detail);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if any errors have been recorded during compilation.
|
||||
*/
|
||||
hasErrors(): boolean {
|
||||
return this.#errors.hasAnyErrors();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the accumulated CompilerError containing all recorded diagnostics.
|
||||
*/
|
||||
aggregateErrors(): CompilerError {
|
||||
return this.#errors;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps a callback in try/catch: if the callback throws a CompilerError
|
||||
* that is NOT an invariant, the error is recorded and execution continues.
|
||||
* Non-CompilerError exceptions and invariants are re-thrown.
|
||||
*/
|
||||
tryRecord(fn: () => void): void {
|
||||
try {
|
||||
fn();
|
||||
} catch (err) {
|
||||
if (err instanceof CompilerError) {
|
||||
// Check if any detail is an invariant — if so, re-throw
|
||||
for (const detail of err.details) {
|
||||
if (detail.category === ErrorCategory.Invariant) {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
this.recordErrors(err);
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
isContextIdentifier(node: t.Identifier): boolean {
|
||||
return this.#contextIdentifiers.has(node);
|
||||
}
|
||||
@@ -1029,18 +856,6 @@ export class Environment {
|
||||
binding: NonLocalBinding,
|
||||
loc: SourceLocation,
|
||||
): Global | null {
|
||||
if (this.config.hookPattern != null) {
|
||||
const match = new RegExp(this.config.hookPattern).exec(binding.name);
|
||||
if (
|
||||
match != null &&
|
||||
typeof match[1] === 'string' &&
|
||||
isHookName(match[1])
|
||||
) {
|
||||
const resolvedName = match[1];
|
||||
return this.#globals.get(resolvedName) ?? this.#getCustomHookType();
|
||||
}
|
||||
}
|
||||
|
||||
switch (binding.kind) {
|
||||
case 'ModuleLocal': {
|
||||
// don't resolve module locals
|
||||
|
||||
@@ -9,9 +9,6 @@ import {Effect, ValueKind, ValueReason} from './HIR';
|
||||
import {
|
||||
BUILTIN_SHAPES,
|
||||
BuiltInArrayId,
|
||||
BuiltInAutodepsId,
|
||||
BuiltInFireFunctionId,
|
||||
BuiltInFireId,
|
||||
BuiltInMapId,
|
||||
BuiltInMixedReadonlyId,
|
||||
BuiltInObjectId,
|
||||
@@ -846,26 +843,6 @@ const REACT_APIS: Array<[string, BuiltInType]> = [
|
||||
BuiltInUseOperatorId,
|
||||
),
|
||||
],
|
||||
[
|
||||
'fire',
|
||||
addFunction(
|
||||
DEFAULT_SHAPES,
|
||||
[],
|
||||
{
|
||||
positionalParams: [],
|
||||
restParam: null,
|
||||
returnType: {
|
||||
kind: 'Function',
|
||||
return: {kind: 'Poly'},
|
||||
shapeId: BuiltInFireFunctionId,
|
||||
isConstructor: false,
|
||||
},
|
||||
calleeEffect: Effect.Read,
|
||||
returnValueKind: ValueKind.Frozen,
|
||||
},
|
||||
BuiltInFireId,
|
||||
),
|
||||
],
|
||||
[
|
||||
'useEffectEvent',
|
||||
addHook(
|
||||
@@ -887,7 +864,6 @@ const REACT_APIS: Array<[string, BuiltInType]> = [
|
||||
BuiltInUseEffectEventId,
|
||||
),
|
||||
],
|
||||
['AUTODEPS', addObject(DEFAULT_SHAPES, BuiltInAutodepsId, [])],
|
||||
];
|
||||
|
||||
TYPED_GLOBALS.push(
|
||||
|
||||
@@ -1639,6 +1639,7 @@ export function makePropertyLiteral(value: string | number): PropertyLiteral {
|
||||
export type DependencyPathEntry = {
|
||||
property: PropertyLiteral;
|
||||
optional: boolean;
|
||||
loc: SourceLocation;
|
||||
};
|
||||
export type DependencyPath = Array<DependencyPathEntry>;
|
||||
export type ReactiveScopeDependency = {
|
||||
@@ -1656,6 +1657,7 @@ export type ReactiveScopeDependency = {
|
||||
*/
|
||||
reactive: boolean;
|
||||
path: DependencyPath;
|
||||
loc: SourceLocation;
|
||||
};
|
||||
|
||||
export function areEqualPaths(a: DependencyPath, b: DependencyPath): boolean {
|
||||
@@ -1886,12 +1888,6 @@ export function isDispatcherType(id: Identifier): boolean {
|
||||
return id.type.kind === 'Function' && id.type.shapeId === 'BuiltInDispatch';
|
||||
}
|
||||
|
||||
export function isFireFunctionType(id: Identifier): boolean {
|
||||
return (
|
||||
id.type.kind === 'Function' && id.type.shapeId === 'BuiltInFireFunction'
|
||||
);
|
||||
}
|
||||
|
||||
export function isEffectEventFunctionType(id: Identifier): boolean {
|
||||
return (
|
||||
id.type.kind === 'Function' &&
|
||||
|
||||
@@ -381,11 +381,12 @@ export default class HIRBuilder {
|
||||
instr => instr.value.kind === 'FunctionExpression',
|
||||
)
|
||||
) {
|
||||
CompilerError.throwTodo({
|
||||
this.errors.push({
|
||||
reason: `Support functions with unreachable code that may contain hoisted declarations`,
|
||||
loc: block.instructions[0]?.loc ?? block.terminal.loc,
|
||||
description: null,
|
||||
suggestions: null,
|
||||
category: ErrorCategory.Todo,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -383,12 +383,8 @@ export const BuiltInUseTransitionId = 'BuiltInUseTransition';
|
||||
export const BuiltInUseOptimisticId = 'BuiltInUseOptimistic';
|
||||
export const BuiltInSetOptimisticId = 'BuiltInSetOptimistic';
|
||||
export const BuiltInStartTransitionId = 'BuiltInStartTransition';
|
||||
export const BuiltInFireId = 'BuiltInFire';
|
||||
export const BuiltInFireFunctionId = 'BuiltInFireFunction';
|
||||
export const BuiltInUseEffectEventId = 'BuiltInUseEffectEvent';
|
||||
export const BuiltInEffectEventId = 'BuiltInEffectEventFunction';
|
||||
export const BuiltInAutodepsId = 'BuiltInAutoDepsId';
|
||||
export const BuiltInEventHandlerId = 'BuiltInEventHandlerId';
|
||||
|
||||
// See getReanimatedModuleType() in Globals.ts — this is part of supporting Reanimated's ref-like types
|
||||
export const ReanimatedSharedValueId = 'ReanimatedSharedValueId';
|
||||
@@ -1249,19 +1245,6 @@ addFunction(
|
||||
BuiltInEffectEventId,
|
||||
);
|
||||
|
||||
addFunction(
|
||||
BUILTIN_SHAPES,
|
||||
[],
|
||||
{
|
||||
positionalParams: [],
|
||||
restParam: Effect.ConditionallyMutate,
|
||||
returnType: {kind: 'Poly'},
|
||||
calleeEffect: Effect.ConditionallyMutate,
|
||||
returnValueKind: ValueKind.Mutable,
|
||||
},
|
||||
BuiltInEventHandlerId,
|
||||
);
|
||||
|
||||
/**
|
||||
* MixedReadOnly =
|
||||
* | primitive
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
ObjectMethod,
|
||||
PropertyLiteral,
|
||||
convertHoistedLValueKind,
|
||||
SourceLocation,
|
||||
} from './HIR';
|
||||
import {
|
||||
collectHoistablePropertyLoads,
|
||||
@@ -298,6 +299,7 @@ function collectTemporariesSidemapImpl(
|
||||
value.object,
|
||||
value.property,
|
||||
false,
|
||||
value.loc,
|
||||
temporaries,
|
||||
);
|
||||
temporaries.set(lvalue.identifier.id, property);
|
||||
@@ -318,6 +320,7 @@ function collectTemporariesSidemapImpl(
|
||||
identifier: value.place.identifier,
|
||||
reactive: value.place.reactive,
|
||||
path: [],
|
||||
loc: value.loc,
|
||||
});
|
||||
}
|
||||
} else if (
|
||||
@@ -339,6 +342,7 @@ function getProperty(
|
||||
object: Place,
|
||||
propertyName: PropertyLiteral,
|
||||
optional: boolean,
|
||||
loc: SourceLocation,
|
||||
temporaries: ReadonlyMap<IdentifierId, ReactiveScopeDependency>,
|
||||
): ReactiveScopeDependency {
|
||||
/*
|
||||
@@ -371,13 +375,18 @@ function getProperty(
|
||||
property = {
|
||||
identifier: object.identifier,
|
||||
reactive: object.reactive,
|
||||
path: [{property: propertyName, optional}],
|
||||
path: [{property: propertyName, optional, loc}],
|
||||
loc,
|
||||
};
|
||||
} else {
|
||||
property = {
|
||||
identifier: resolvedDependency.identifier,
|
||||
reactive: resolvedDependency.reactive,
|
||||
path: [...resolvedDependency.path, {property: propertyName, optional}],
|
||||
path: [
|
||||
...resolvedDependency.path,
|
||||
{property: propertyName, optional, loc},
|
||||
],
|
||||
loc,
|
||||
};
|
||||
}
|
||||
return property;
|
||||
@@ -537,6 +546,7 @@ export class DependencyCollectionContext {
|
||||
identifier: place.identifier,
|
||||
reactive: place.reactive,
|
||||
path: [],
|
||||
loc: place.loc,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -545,11 +555,13 @@ export class DependencyCollectionContext {
|
||||
object: Place,
|
||||
property: PropertyLiteral,
|
||||
optional: boolean,
|
||||
loc: SourceLocation,
|
||||
): void {
|
||||
const nextDependency = getProperty(
|
||||
object,
|
||||
property,
|
||||
optional,
|
||||
loc,
|
||||
this.#temporaries,
|
||||
);
|
||||
this.visitDependency(nextDependency);
|
||||
@@ -602,6 +614,7 @@ export class DependencyCollectionContext {
|
||||
identifier: maybeDependency.identifier,
|
||||
reactive: maybeDependency.reactive,
|
||||
path: [],
|
||||
loc: maybeDependency.loc,
|
||||
};
|
||||
}
|
||||
if (this.#checkValidDependency(maybeDependency)) {
|
||||
@@ -626,6 +639,7 @@ export class DependencyCollectionContext {
|
||||
identifier: place.identifier,
|
||||
reactive: place.reactive,
|
||||
path: [],
|
||||
loc: place.loc,
|
||||
})
|
||||
) {
|
||||
currentScope.reassignments.add(place.identifier);
|
||||
@@ -679,7 +693,7 @@ export function handleInstruction(
|
||||
return;
|
||||
}
|
||||
if (value.kind === 'PropertyLoad') {
|
||||
context.visitProperty(value.object, value.property, false);
|
||||
context.visitProperty(value.object, value.property, false, value.loc);
|
||||
} else if (value.kind === 'StoreLocal') {
|
||||
context.visitOperand(value.value);
|
||||
if (value.lvalue.kind === InstructionKind.Reassign) {
|
||||
|
||||
@@ -54,7 +54,7 @@ function lowerWithMutationAliasing(fn: HIRFunction): void {
|
||||
deadCodeElimination(fn);
|
||||
const functionEffects = inferMutationAliasingRanges(fn, {
|
||||
isFunctionExpression: true,
|
||||
}).unwrap();
|
||||
});
|
||||
rewriteInstructionKindsBasedOnReassignment(fn);
|
||||
inferReactiveScopeVariables(fn);
|
||||
fn.aliasingEffects = functionEffects;
|
||||
|
||||
@@ -31,7 +31,6 @@ import {
|
||||
makeInstructionId,
|
||||
} from '../HIR';
|
||||
import {createTemporaryPlace, markInstructionIds} from '../HIR/HIRBuilder';
|
||||
import {Result} from '../Utils/Result';
|
||||
|
||||
type ManualMemoCallee = {
|
||||
kind: 'useMemo' | 'useCallback';
|
||||
@@ -74,7 +73,10 @@ export function collectMaybeMemoDependencies(
|
||||
return {
|
||||
root: object.root,
|
||||
// TODO: determine if the access is optional
|
||||
path: [...object.path, {property: value.property, optional}],
|
||||
path: [
|
||||
...object.path,
|
||||
{property: value.property, optional, loc: value.loc},
|
||||
],
|
||||
loc: value.loc,
|
||||
};
|
||||
}
|
||||
@@ -386,9 +388,7 @@ function extractManualMemoizationArgs(
|
||||
* This pass also validates that useMemo callbacks return a value (not void), ensuring that useMemo
|
||||
* is only used for memoizing values and not for running arbitrary side effects.
|
||||
*/
|
||||
export function dropManualMemoization(
|
||||
func: HIRFunction,
|
||||
): Result<void, CompilerError> {
|
||||
export function dropManualMemoization(func: HIRFunction): void {
|
||||
const errors = new CompilerError();
|
||||
const isValidationEnabled =
|
||||
func.env.config.validatePreserveExistingMemoizationGuarantees ||
|
||||
@@ -550,7 +550,9 @@ export function dropManualMemoization(
|
||||
}
|
||||
}
|
||||
|
||||
return errors.asResult();
|
||||
if (errors.hasAnyErrors()) {
|
||||
func.env.recordErrors(errors);
|
||||
}
|
||||
}
|
||||
|
||||
function findOptionalPlaces(fn: HIRFunction): Set<IdentifierId> {
|
||||
|
||||
@@ -1,675 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import * as t from '@babel/types';
|
||||
import {CompilerError, SourceLocation} from '..';
|
||||
import {
|
||||
ArrayExpression,
|
||||
Effect,
|
||||
FunctionExpression,
|
||||
GeneratedSource,
|
||||
HIRFunction,
|
||||
IdentifierId,
|
||||
Instruction,
|
||||
makeInstructionId,
|
||||
TInstruction,
|
||||
InstructionId,
|
||||
ScopeId,
|
||||
ReactiveScopeDependency,
|
||||
Place,
|
||||
ReactiveScope,
|
||||
ReactiveScopeDependencies,
|
||||
Terminal,
|
||||
isUseRefType,
|
||||
isSetStateType,
|
||||
isFireFunctionType,
|
||||
makeScopeId,
|
||||
HIR,
|
||||
BasicBlock,
|
||||
BlockId,
|
||||
isEffectEventFunctionType,
|
||||
} from '../HIR';
|
||||
import {collectHoistablePropertyLoadsInInnerFn} from '../HIR/CollectHoistablePropertyLoads';
|
||||
import {collectOptionalChainSidemap} from '../HIR/CollectOptionalChainDependencies';
|
||||
import {ReactiveScopeDependencyTreeHIR} from '../HIR/DeriveMinimalDependenciesHIR';
|
||||
import {DEFAULT_EXPORT} from '../HIR/Environment';
|
||||
import {
|
||||
createTemporaryPlace,
|
||||
fixScopeAndIdentifierRanges,
|
||||
markInstructionIds,
|
||||
markPredecessors,
|
||||
reversePostorderBlocks,
|
||||
} from '../HIR/HIRBuilder';
|
||||
import {
|
||||
collectTemporariesSidemap,
|
||||
DependencyCollectionContext,
|
||||
handleInstruction,
|
||||
} from '../HIR/PropagateScopeDependenciesHIR';
|
||||
import {buildDependencyInstructions} from '../HIR/ScopeDependencyUtils';
|
||||
import {
|
||||
eachInstructionOperand,
|
||||
eachTerminalOperand,
|
||||
terminalFallthrough,
|
||||
} from '../HIR/visitors';
|
||||
import {empty} from '../Utils/Stack';
|
||||
import {getOrInsertWith} from '../Utils/utils';
|
||||
import {deadCodeElimination} from '../Optimization';
|
||||
import {BuiltInAutodepsId} from '../HIR/ObjectShape';
|
||||
|
||||
/**
|
||||
* Infers reactive dependencies captured by useEffect lambdas and adds them as
|
||||
* a second argument to the useEffect call if no dependency array is provided.
|
||||
*/
|
||||
export function inferEffectDependencies(fn: HIRFunction): void {
|
||||
const fnExpressions = new Map<
|
||||
IdentifierId,
|
||||
TInstruction<FunctionExpression>
|
||||
>();
|
||||
|
||||
const autodepFnConfigs = new Map<string, Map<string, number>>();
|
||||
for (const effectTarget of fn.env.config.inferEffectDependencies!) {
|
||||
const moduleTargets = getOrInsertWith(
|
||||
autodepFnConfigs,
|
||||
effectTarget.function.source,
|
||||
() => new Map<string, number>(),
|
||||
);
|
||||
moduleTargets.set(
|
||||
effectTarget.function.importSpecifierName,
|
||||
effectTarget.autodepsIndex,
|
||||
);
|
||||
}
|
||||
const autodepFnLoads = new Map<IdentifierId, number>();
|
||||
const autodepModuleLoads = new Map<IdentifierId, Map<string, number>>();
|
||||
|
||||
const scopeInfos = new Map<ScopeId, ReactiveScopeDependencies>();
|
||||
|
||||
const loadGlobals = new Set<IdentifierId>();
|
||||
|
||||
/**
|
||||
* When inserting LoadLocals, we need to retain the reactivity of the base
|
||||
* identifier, as later passes e.g. PruneNonReactiveDeps take the reactivity of
|
||||
* a base identifier as the "maximal" reactivity of all its references.
|
||||
* Concretely,
|
||||
* reactive(Identifier i) = Union_{reference of i}(reactive(reference))
|
||||
*/
|
||||
const reactiveIds = inferReactiveIdentifiers(fn);
|
||||
const rewriteBlocks: Array<BasicBlock> = [];
|
||||
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
if (block.terminal.kind === 'scope') {
|
||||
const scopeBlock = fn.body.blocks.get(block.terminal.block)!;
|
||||
if (
|
||||
scopeBlock.instructions.length === 1 &&
|
||||
scopeBlock.terminal.kind === 'goto' &&
|
||||
scopeBlock.terminal.block === block.terminal.fallthrough
|
||||
) {
|
||||
scopeInfos.set(
|
||||
block.terminal.scope.id,
|
||||
block.terminal.scope.dependencies,
|
||||
);
|
||||
}
|
||||
}
|
||||
const rewriteInstrs: Array<SpliceInfo> = [];
|
||||
for (const instr of block.instructions) {
|
||||
const {value, lvalue} = instr;
|
||||
if (value.kind === 'FunctionExpression') {
|
||||
fnExpressions.set(
|
||||
lvalue.identifier.id,
|
||||
instr as TInstruction<FunctionExpression>,
|
||||
);
|
||||
} else if (value.kind === 'PropertyLoad') {
|
||||
if (
|
||||
typeof value.property === 'string' &&
|
||||
autodepModuleLoads.has(value.object.identifier.id)
|
||||
) {
|
||||
const moduleTargets = autodepModuleLoads.get(
|
||||
value.object.identifier.id,
|
||||
)!;
|
||||
const propertyName = value.property;
|
||||
const numRequiredArgs = moduleTargets.get(propertyName);
|
||||
if (numRequiredArgs != null) {
|
||||
autodepFnLoads.set(lvalue.identifier.id, numRequiredArgs);
|
||||
}
|
||||
}
|
||||
} else if (value.kind === 'LoadGlobal') {
|
||||
loadGlobals.add(lvalue.identifier.id);
|
||||
/*
|
||||
* TODO: Handle properties on default exports, like
|
||||
* import React from 'react';
|
||||
* React.useEffect(...);
|
||||
*/
|
||||
if (value.binding.kind === 'ImportNamespace') {
|
||||
const moduleTargets = autodepFnConfigs.get(value.binding.module);
|
||||
if (moduleTargets != null) {
|
||||
autodepModuleLoads.set(lvalue.identifier.id, moduleTargets);
|
||||
}
|
||||
}
|
||||
if (
|
||||
value.binding.kind === 'ImportSpecifier' ||
|
||||
value.binding.kind === 'ImportDefault'
|
||||
) {
|
||||
const moduleTargets = autodepFnConfigs.get(value.binding.module);
|
||||
if (moduleTargets != null) {
|
||||
const importSpecifierName =
|
||||
value.binding.kind === 'ImportSpecifier'
|
||||
? value.binding.imported
|
||||
: DEFAULT_EXPORT;
|
||||
const numRequiredArgs = moduleTargets.get(importSpecifierName);
|
||||
if (numRequiredArgs != null) {
|
||||
autodepFnLoads.set(lvalue.identifier.id, numRequiredArgs);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
value.kind === 'CallExpression' ||
|
||||
value.kind === 'MethodCall'
|
||||
) {
|
||||
const callee =
|
||||
value.kind === 'CallExpression' ? value.callee : value.property;
|
||||
|
||||
const autodepsArgIndex = value.args.findIndex(
|
||||
arg =>
|
||||
arg.kind === 'Identifier' &&
|
||||
arg.identifier.type.kind === 'Object' &&
|
||||
arg.identifier.type.shapeId === BuiltInAutodepsId,
|
||||
);
|
||||
const autodepsArgExpectedIndex = autodepFnLoads.get(
|
||||
callee.identifier.id,
|
||||
);
|
||||
|
||||
if (
|
||||
value.args.length > 0 &&
|
||||
autodepsArgExpectedIndex != null &&
|
||||
autodepsArgIndex === autodepsArgExpectedIndex &&
|
||||
autodepFnLoads.has(callee.identifier.id) &&
|
||||
value.args[0].kind === 'Identifier'
|
||||
) {
|
||||
// We have a useEffect call with no deps array, so we need to infer the deps
|
||||
const effectDeps: Array<Place> = [];
|
||||
const deps: ArrayExpression = {
|
||||
kind: 'ArrayExpression',
|
||||
elements: effectDeps,
|
||||
loc: GeneratedSource,
|
||||
};
|
||||
const depsPlace = createTemporaryPlace(fn.env, GeneratedSource);
|
||||
depsPlace.effect = Effect.Read;
|
||||
|
||||
const fnExpr = fnExpressions.get(value.args[0].identifier.id);
|
||||
if (fnExpr != null) {
|
||||
// We have a function expression, so we can infer its dependencies
|
||||
const scopeInfo =
|
||||
fnExpr.lvalue.identifier.scope != null
|
||||
? scopeInfos.get(fnExpr.lvalue.identifier.scope.id)
|
||||
: null;
|
||||
let minimalDeps: Set<ReactiveScopeDependency>;
|
||||
if (scopeInfo != null) {
|
||||
minimalDeps = new Set(scopeInfo);
|
||||
} else {
|
||||
minimalDeps = inferMinimalDependencies(fnExpr);
|
||||
}
|
||||
/**
|
||||
* Step 1: push dependencies to the effect deps array
|
||||
*
|
||||
* Note that it's invalid to prune all non-reactive deps in this pass, see
|
||||
* the `infer-effect-deps/pruned-nonreactive-obj` fixture for an
|
||||
* explanation.
|
||||
*/
|
||||
|
||||
const usedDeps = [];
|
||||
for (const maybeDep of minimalDeps) {
|
||||
if (
|
||||
((isUseRefType(maybeDep.identifier) ||
|
||||
isSetStateType(maybeDep.identifier)) &&
|
||||
!reactiveIds.has(maybeDep.identifier.id)) ||
|
||||
isFireFunctionType(maybeDep.identifier) ||
|
||||
isEffectEventFunctionType(maybeDep.identifier)
|
||||
) {
|
||||
// exclude non-reactive hook results, which will never be in a memo block
|
||||
continue;
|
||||
}
|
||||
|
||||
const dep = truncateDepAtCurrent(maybeDep);
|
||||
const {place, value, exitBlockId} = buildDependencyInstructions(
|
||||
dep,
|
||||
fn.env,
|
||||
);
|
||||
rewriteInstrs.push({
|
||||
kind: 'block',
|
||||
location: instr.id,
|
||||
value,
|
||||
exitBlockId: exitBlockId,
|
||||
});
|
||||
effectDeps.push(place);
|
||||
usedDeps.push(dep);
|
||||
}
|
||||
|
||||
// For LSP autodeps feature.
|
||||
const decorations: Array<t.SourceLocation> = [];
|
||||
for (const loc of collectDepUsages(usedDeps, fnExpr.value)) {
|
||||
if (typeof loc === 'symbol') {
|
||||
continue;
|
||||
}
|
||||
decorations.push(loc);
|
||||
}
|
||||
if (typeof value.loc !== 'symbol') {
|
||||
fn.env.logger?.logEvent(fn.env.filename, {
|
||||
kind: 'AutoDepsDecorations',
|
||||
fnLoc: value.loc,
|
||||
decorations,
|
||||
});
|
||||
}
|
||||
|
||||
// Step 2: push the inferred deps array as an argument of the useEffect
|
||||
rewriteInstrs.push({
|
||||
kind: 'instr',
|
||||
location: instr.id,
|
||||
value: {
|
||||
id: makeInstructionId(0),
|
||||
loc: GeneratedSource,
|
||||
lvalue: {...depsPlace, effect: Effect.Mutate},
|
||||
value: deps,
|
||||
effects: null,
|
||||
},
|
||||
});
|
||||
value.args[autodepsArgIndex] = {
|
||||
...depsPlace,
|
||||
effect: Effect.Freeze,
|
||||
};
|
||||
fn.env.inferredEffectLocations.add(callee.loc);
|
||||
} else if (loadGlobals.has(value.args[0].identifier.id)) {
|
||||
// Global functions have no reactive dependencies, so we can insert an empty array
|
||||
rewriteInstrs.push({
|
||||
kind: 'instr',
|
||||
location: instr.id,
|
||||
value: {
|
||||
id: makeInstructionId(0),
|
||||
loc: GeneratedSource,
|
||||
lvalue: {...depsPlace, effect: Effect.Mutate},
|
||||
value: deps,
|
||||
effects: null,
|
||||
},
|
||||
});
|
||||
value.args[autodepsArgIndex] = {
|
||||
...depsPlace,
|
||||
effect: Effect.Freeze,
|
||||
};
|
||||
fn.env.inferredEffectLocations.add(callee.loc);
|
||||
}
|
||||
} else if (
|
||||
value.args.length >= 2 &&
|
||||
value.args.length - 1 === autodepFnLoads.get(callee.identifier.id) &&
|
||||
value.args[0] != null &&
|
||||
value.args[0].kind === 'Identifier'
|
||||
) {
|
||||
const penultimateArg = value.args[value.args.length - 2];
|
||||
const depArrayArg = value.args[value.args.length - 1];
|
||||
if (
|
||||
depArrayArg.kind !== 'Spread' &&
|
||||
penultimateArg.kind !== 'Spread' &&
|
||||
typeof depArrayArg.loc !== 'symbol' &&
|
||||
typeof penultimateArg.loc !== 'symbol' &&
|
||||
typeof value.loc !== 'symbol'
|
||||
) {
|
||||
fn.env.logger?.logEvent(fn.env.filename, {
|
||||
kind: 'AutoDepsEligible',
|
||||
fnLoc: value.loc,
|
||||
depArrayLoc: {
|
||||
...depArrayArg.loc,
|
||||
start: penultimateArg.loc.end,
|
||||
end: depArrayArg.loc.end,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
rewriteSplices(block, rewriteInstrs, rewriteBlocks);
|
||||
}
|
||||
|
||||
if (rewriteBlocks.length > 0) {
|
||||
for (const block of rewriteBlocks) {
|
||||
fn.body.blocks.set(block.id, block);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fixup the HIR to restore RPO, ensure correct predecessors, and renumber
|
||||
* instructions.
|
||||
*/
|
||||
reversePostorderBlocks(fn.body);
|
||||
markPredecessors(fn.body);
|
||||
// Renumber instructions and fix scope ranges
|
||||
markInstructionIds(fn.body);
|
||||
fixScopeAndIdentifierRanges(fn.body);
|
||||
deadCodeElimination(fn);
|
||||
|
||||
fn.env.hasInferredEffect = true;
|
||||
}
|
||||
}
|
||||
|
||||
function truncateDepAtCurrent(
|
||||
dep: ReactiveScopeDependency,
|
||||
): ReactiveScopeDependency {
|
||||
const idx = dep.path.findIndex(path => path.property === 'current');
|
||||
if (idx === -1) {
|
||||
return dep;
|
||||
} else {
|
||||
return {...dep, path: dep.path.slice(0, idx)};
|
||||
}
|
||||
}
|
||||
|
||||
type SpliceInfo =
|
||||
| {kind: 'instr'; location: InstructionId; value: Instruction}
|
||||
| {
|
||||
kind: 'block';
|
||||
location: InstructionId;
|
||||
value: HIR;
|
||||
exitBlockId: BlockId;
|
||||
};
|
||||
|
||||
function rewriteSplices(
|
||||
originalBlock: BasicBlock,
|
||||
splices: Array<SpliceInfo>,
|
||||
rewriteBlocks: Array<BasicBlock>,
|
||||
): void {
|
||||
if (splices.length === 0) {
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Splice instructions or value blocks into the original block.
|
||||
* --- original block ---
|
||||
* bb_original
|
||||
* instr1
|
||||
* ...
|
||||
* instr2 <-- splice location
|
||||
* instr3
|
||||
* ...
|
||||
* <original terminal>
|
||||
*
|
||||
* If there is more than one block in the splice, this means that we're
|
||||
* splicing in a set of value-blocks of the following structure:
|
||||
* --- blocks we're splicing in ---
|
||||
* bb_entry:
|
||||
* instrEntry
|
||||
* ...
|
||||
* <splice terminal> fallthrough=bb_exit
|
||||
*
|
||||
* bb1(value):
|
||||
* ...
|
||||
*
|
||||
* bb_exit:
|
||||
* instrExit
|
||||
* ...
|
||||
* <synthetic terminal>
|
||||
*
|
||||
*
|
||||
* --- rewritten blocks ---
|
||||
* bb_original
|
||||
* instr1
|
||||
* ... (original instructions)
|
||||
* instr2
|
||||
* instrEntry
|
||||
* ... (spliced instructions)
|
||||
* <splice terminal> fallthrough=bb_exit
|
||||
*
|
||||
* bb1(value):
|
||||
* ...
|
||||
*
|
||||
* bb_exit:
|
||||
* instrExit
|
||||
* ... (spliced instructions)
|
||||
* instr3
|
||||
* ... (original instructions)
|
||||
* <original terminal>
|
||||
*/
|
||||
const originalInstrs = originalBlock.instructions;
|
||||
let currBlock: BasicBlock = {...originalBlock, instructions: []};
|
||||
rewriteBlocks.push(currBlock);
|
||||
|
||||
let cursor = 0;
|
||||
|
||||
for (const rewrite of splices) {
|
||||
while (originalInstrs[cursor].id < rewrite.location) {
|
||||
CompilerError.invariant(
|
||||
originalInstrs[cursor].id < originalInstrs[cursor + 1].id,
|
||||
{
|
||||
reason:
|
||||
'[InferEffectDependencies] Internal invariant broken: expected block instructions to be sorted',
|
||||
loc: originalInstrs[cursor].loc,
|
||||
},
|
||||
);
|
||||
currBlock.instructions.push(originalInstrs[cursor]);
|
||||
cursor++;
|
||||
}
|
||||
CompilerError.invariant(originalInstrs[cursor].id === rewrite.location, {
|
||||
reason:
|
||||
'[InferEffectDependencies] Internal invariant broken: splice location not found',
|
||||
loc: originalInstrs[cursor].loc,
|
||||
});
|
||||
|
||||
if (rewrite.kind === 'instr') {
|
||||
currBlock.instructions.push(rewrite.value);
|
||||
} else if (rewrite.kind === 'block') {
|
||||
const {entry, blocks} = rewrite.value;
|
||||
const entryBlock = blocks.get(entry)!;
|
||||
// splice in all instructions from the entry block
|
||||
currBlock.instructions.push(...entryBlock.instructions);
|
||||
if (blocks.size > 1) {
|
||||
/**
|
||||
* We're splicing in a set of value-blocks, which means we need
|
||||
* to push new blocks and update terminals.
|
||||
*/
|
||||
CompilerError.invariant(
|
||||
terminalFallthrough(entryBlock.terminal) === rewrite.exitBlockId,
|
||||
{
|
||||
reason:
|
||||
'[InferEffectDependencies] Internal invariant broken: expected entry block to have a fallthrough',
|
||||
loc: entryBlock.terminal.loc,
|
||||
},
|
||||
);
|
||||
const originalTerminal = currBlock.terminal;
|
||||
currBlock.terminal = entryBlock.terminal;
|
||||
|
||||
for (const [id, block] of blocks) {
|
||||
if (id === entry) {
|
||||
continue;
|
||||
}
|
||||
if (id === rewrite.exitBlockId) {
|
||||
block.terminal = originalTerminal;
|
||||
currBlock = block;
|
||||
}
|
||||
rewriteBlocks.push(block);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
currBlock.instructions.push(...originalInstrs.slice(cursor));
|
||||
}
|
||||
|
||||
function inferReactiveIdentifiers(fn: HIRFunction): Set<IdentifierId> {
|
||||
const reactiveIds: Set<IdentifierId> = new Set();
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
for (const instr of block.instructions) {
|
||||
/**
|
||||
* No need to traverse into nested functions as
|
||||
* 1. their effects are recorded in `LoweredFunction.dependencies`
|
||||
* 2. we don't mark `reactive` in these anyways
|
||||
*/
|
||||
for (const place of eachInstructionOperand(instr)) {
|
||||
if (place.reactive) {
|
||||
reactiveIds.add(place.identifier.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const place of eachTerminalOperand(block.terminal)) {
|
||||
if (place.reactive) {
|
||||
reactiveIds.add(place.identifier.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
return reactiveIds;
|
||||
}
|
||||
|
||||
function collectDepUsages(
|
||||
deps: Array<ReactiveScopeDependency>,
|
||||
fnExpr: FunctionExpression,
|
||||
): Array<SourceLocation> {
|
||||
const identifiers: Map<IdentifierId, ReactiveScopeDependency> = new Map();
|
||||
const loadedDeps: Set<IdentifierId> = new Set();
|
||||
const sourceLocations = [];
|
||||
for (const dep of deps) {
|
||||
identifiers.set(dep.identifier.id, dep);
|
||||
}
|
||||
|
||||
for (const [, block] of fnExpr.loweredFunc.func.body.blocks) {
|
||||
for (const instr of block.instructions) {
|
||||
if (
|
||||
instr.value.kind === 'LoadLocal' &&
|
||||
identifiers.has(instr.value.place.identifier.id)
|
||||
) {
|
||||
loadedDeps.add(instr.lvalue.identifier.id);
|
||||
}
|
||||
for (const place of eachInstructionOperand(instr)) {
|
||||
if (loadedDeps.has(place.identifier.id)) {
|
||||
// TODO(@jbrown215): handle member exprs!!
|
||||
sourceLocations.push(place.identifier.loc);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sourceLocations;
|
||||
}
|
||||
|
||||
function inferMinimalDependencies(
|
||||
fnInstr: TInstruction<FunctionExpression>,
|
||||
): Set<ReactiveScopeDependency> {
|
||||
const fn = fnInstr.value.loweredFunc.func;
|
||||
|
||||
const temporaries = collectTemporariesSidemap(fn, new Set());
|
||||
const {
|
||||
hoistableObjects,
|
||||
processedInstrsInOptional,
|
||||
temporariesReadInOptional,
|
||||
} = collectOptionalChainSidemap(fn);
|
||||
|
||||
const hoistablePropertyLoads = collectHoistablePropertyLoadsInInnerFn(
|
||||
fnInstr,
|
||||
temporaries,
|
||||
hoistableObjects,
|
||||
);
|
||||
const hoistableToFnEntry = hoistablePropertyLoads.get(fn.body.entry);
|
||||
CompilerError.invariant(hoistableToFnEntry != null, {
|
||||
reason:
|
||||
'[InferEffectDependencies] Internal invariant broken: missing entry block',
|
||||
loc: fnInstr.loc,
|
||||
});
|
||||
|
||||
const dependencies = inferDependencies(
|
||||
fnInstr,
|
||||
new Map([...temporaries, ...temporariesReadInOptional]),
|
||||
processedInstrsInOptional,
|
||||
);
|
||||
|
||||
const tree = new ReactiveScopeDependencyTreeHIR(
|
||||
[...hoistableToFnEntry.assumedNonNullObjects].map(o => o.fullPath),
|
||||
);
|
||||
for (const dep of dependencies) {
|
||||
tree.addDependency({...dep});
|
||||
}
|
||||
|
||||
return tree.deriveMinimalDependencies();
|
||||
}
|
||||
|
||||
function inferDependencies(
|
||||
fnInstr: TInstruction<FunctionExpression>,
|
||||
temporaries: ReadonlyMap<IdentifierId, ReactiveScopeDependency>,
|
||||
processedInstrsInOptional: ReadonlySet<Instruction | Terminal>,
|
||||
): Set<ReactiveScopeDependency> {
|
||||
const fn = fnInstr.value.loweredFunc.func;
|
||||
const context = new DependencyCollectionContext(
|
||||
new Set(),
|
||||
temporaries,
|
||||
processedInstrsInOptional,
|
||||
);
|
||||
for (const dep of fn.context) {
|
||||
context.declare(dep.identifier, {
|
||||
id: makeInstructionId(0),
|
||||
scope: empty(),
|
||||
});
|
||||
}
|
||||
const placeholderScope: ReactiveScope = {
|
||||
id: makeScopeId(0),
|
||||
range: {
|
||||
start: fnInstr.id,
|
||||
end: makeInstructionId(fnInstr.id + 1),
|
||||
},
|
||||
dependencies: new Set(),
|
||||
reassignments: new Set(),
|
||||
declarations: new Map(),
|
||||
earlyReturnValue: null,
|
||||
merged: new Set(),
|
||||
loc: GeneratedSource,
|
||||
};
|
||||
context.enterScope(placeholderScope);
|
||||
inferDependenciesInFn(fn, context, temporaries);
|
||||
context.exitScope(placeholderScope, false);
|
||||
const resultUnfiltered = context.deps.get(placeholderScope);
|
||||
CompilerError.invariant(resultUnfiltered != null, {
|
||||
reason:
|
||||
'[InferEffectDependencies] Internal invariant broken: missing scope dependencies',
|
||||
loc: fn.loc,
|
||||
});
|
||||
|
||||
const fnContext = new Set(fn.context.map(dep => dep.identifier.id));
|
||||
const result = new Set<ReactiveScopeDependency>();
|
||||
for (const dep of resultUnfiltered) {
|
||||
if (fnContext.has(dep.identifier.id)) {
|
||||
result.add(dep);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
function inferDependenciesInFn(
|
||||
fn: HIRFunction,
|
||||
context: DependencyCollectionContext,
|
||||
temporaries: ReadonlyMap<IdentifierId, ReactiveScopeDependency>,
|
||||
): void {
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
// Record referenced optional chains in phis
|
||||
for (const phi of block.phis) {
|
||||
for (const operand of phi.operands) {
|
||||
const maybeOptionalChain = temporaries.get(operand[1].identifier.id);
|
||||
if (maybeOptionalChain) {
|
||||
context.visitDependency(maybeOptionalChain);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const instr of block.instructions) {
|
||||
if (
|
||||
instr.value.kind === 'FunctionExpression' ||
|
||||
instr.value.kind === 'ObjectMethod'
|
||||
) {
|
||||
context.declare(instr.lvalue.identifier, {
|
||||
id: instr.id,
|
||||
scope: context.currentScope,
|
||||
});
|
||||
/**
|
||||
* Recursively visit the inner function to extract dependencies
|
||||
*/
|
||||
const innerFn = instr.value.loweredFunc.func;
|
||||
context.enterInnerFn(instr as TInstruction<FunctionExpression>, () => {
|
||||
inferDependenciesInFn(innerFn, context, temporaries);
|
||||
});
|
||||
} else {
|
||||
handleInstruction(instr, context);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,7 @@ import {
|
||||
eachTerminalOperand,
|
||||
eachTerminalSuccessor,
|
||||
} from '../HIR/visitors';
|
||||
import {Ok, Result} from '../Utils/Result';
|
||||
|
||||
import {
|
||||
assertExhaustive,
|
||||
getOrInsertDefault,
|
||||
@@ -100,7 +100,7 @@ export function inferMutationAliasingEffects(
|
||||
{isFunctionExpression}: {isFunctionExpression: boolean} = {
|
||||
isFunctionExpression: false,
|
||||
},
|
||||
): Result<void, CompilerError> {
|
||||
): void {
|
||||
const initialState = InferenceState.empty(fn.env, isFunctionExpression);
|
||||
|
||||
// Map of blocks to the last (merged) incoming state that was processed
|
||||
@@ -220,7 +220,7 @@ export function inferMutationAliasingEffects(
|
||||
}
|
||||
}
|
||||
}
|
||||
return Ok(undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
function findHoistedContextDeclarations(
|
||||
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
eachTerminalOperand,
|
||||
} from '../HIR/visitors';
|
||||
import {assertExhaustive, getOrInsertWith} from '../Utils/utils';
|
||||
import {Err, Ok, Result} from '../Utils/Result';
|
||||
|
||||
import {AliasingEffect, MutationReason} from './AliasingEffects';
|
||||
|
||||
/**
|
||||
@@ -74,7 +74,7 @@ import {AliasingEffect, MutationReason} from './AliasingEffects';
|
||||
export function inferMutationAliasingRanges(
|
||||
fn: HIRFunction,
|
||||
{isFunctionExpression}: {isFunctionExpression: boolean},
|
||||
): Result<Array<AliasingEffect>, CompilerError> {
|
||||
): Array<AliasingEffect> {
|
||||
// The set of externally-visible effects
|
||||
const functionEffects: Array<AliasingEffect> = [];
|
||||
|
||||
@@ -547,10 +547,14 @@ export function inferMutationAliasingRanges(
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.hasAnyErrors() && !isFunctionExpression) {
|
||||
return Err(errors);
|
||||
if (
|
||||
errors.hasAnyErrors() &&
|
||||
!isFunctionExpression &&
|
||||
fn.env.enableValidations
|
||||
) {
|
||||
fn.env.recordErrors(errors);
|
||||
}
|
||||
return Ok(functionEffects);
|
||||
return functionEffects;
|
||||
}
|
||||
|
||||
function appendFunctionErrors(errors: CompilerError, fn: HIRFunction): void {
|
||||
|
||||
@@ -9,4 +9,3 @@ export {default as analyseFunctions} from './AnalyseFunctions';
|
||||
export {dropManualMemoization} from './DropManualMemoization';
|
||||
export {inferReactivePlaces} from './InferReactivePlaces';
|
||||
export {inlineImmediatelyInvokedFunctionExpressions} from './InlineImmediatelyInvokedFunctionExpressions';
|
||||
export {inferEffectDependencies} from './InferEffectDependencies';
|
||||
|
||||
@@ -1,790 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {
|
||||
BasicBlock,
|
||||
BlockId,
|
||||
BuiltinTag,
|
||||
DeclarationId,
|
||||
Effect,
|
||||
forkTemporaryIdentifier,
|
||||
GotoTerminal,
|
||||
GotoVariant,
|
||||
HIRFunction,
|
||||
Identifier,
|
||||
IfTerminal,
|
||||
Instruction,
|
||||
InstructionKind,
|
||||
JsxAttribute,
|
||||
makeInstructionId,
|
||||
makePropertyLiteral,
|
||||
ObjectProperty,
|
||||
Phi,
|
||||
Place,
|
||||
promoteTemporary,
|
||||
SpreadPattern,
|
||||
} from '../HIR';
|
||||
import {
|
||||
createTemporaryPlace,
|
||||
fixScopeAndIdentifierRanges,
|
||||
markInstructionIds,
|
||||
markPredecessors,
|
||||
reversePostorderBlocks,
|
||||
} from '../HIR/HIRBuilder';
|
||||
import {CompilerError, EnvironmentConfig} from '..';
|
||||
import {
|
||||
mapInstructionLValues,
|
||||
mapInstructionOperands,
|
||||
mapInstructionValueOperands,
|
||||
mapTerminalOperands,
|
||||
} from '../HIR/visitors';
|
||||
import {ErrorCategory} from '../CompilerError';
|
||||
|
||||
type InlinedJsxDeclarationMap = Map<
|
||||
DeclarationId,
|
||||
{identifier: Identifier; blockIdsToIgnore: Set<BlockId>}
|
||||
>;
|
||||
|
||||
/**
|
||||
* A prod-only, RN optimization to replace JSX with inlined ReactElement object literals
|
||||
*
|
||||
* Example:
|
||||
* <>foo</>
|
||||
* _______________
|
||||
* let t1;
|
||||
* if (__DEV__) {
|
||||
* t1 = <>foo</>
|
||||
* } else {
|
||||
* t1 = {...}
|
||||
* }
|
||||
*
|
||||
*/
|
||||
export function inlineJsxTransform(
|
||||
fn: HIRFunction,
|
||||
inlineJsxTransformConfig: NonNullable<
|
||||
EnvironmentConfig['inlineJsxTransform']
|
||||
>,
|
||||
): void {
|
||||
const inlinedJsxDeclarations: InlinedJsxDeclarationMap = new Map();
|
||||
/**
|
||||
* Step 1: Codegen the conditional and ReactElement object literal
|
||||
*/
|
||||
for (const [_, currentBlock] of [...fn.body.blocks]) {
|
||||
let fallthroughBlockInstructions: Array<Instruction> | null = null;
|
||||
const instructionCount = currentBlock.instructions.length;
|
||||
for (let i = 0; i < instructionCount; i++) {
|
||||
const instr = currentBlock.instructions[i]!;
|
||||
// TODO: Support value blocks
|
||||
if (currentBlock.kind === 'value') {
|
||||
fn.env.logger?.logEvent(fn.env.filename, {
|
||||
kind: 'CompileDiagnostic',
|
||||
fnLoc: null,
|
||||
detail: {
|
||||
category: ErrorCategory.Todo,
|
||||
reason: 'JSX Inlining is not supported on value blocks',
|
||||
loc: instr.loc,
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
switch (instr.value.kind) {
|
||||
case 'JsxExpression':
|
||||
case 'JsxFragment': {
|
||||
/**
|
||||
* Split into blocks for new IfTerminal:
|
||||
* current, then, else, fallthrough
|
||||
*/
|
||||
const currentBlockInstructions = currentBlock.instructions.slice(
|
||||
0,
|
||||
i,
|
||||
);
|
||||
const thenBlockInstructions = currentBlock.instructions.slice(
|
||||
i,
|
||||
i + 1,
|
||||
);
|
||||
const elseBlockInstructions: Array<Instruction> = [];
|
||||
fallthroughBlockInstructions ??= currentBlock.instructions.slice(
|
||||
i + 1,
|
||||
);
|
||||
|
||||
const fallthroughBlockId = fn.env.nextBlockId;
|
||||
const fallthroughBlock: BasicBlock = {
|
||||
kind: currentBlock.kind,
|
||||
id: fallthroughBlockId,
|
||||
instructions: fallthroughBlockInstructions,
|
||||
terminal: currentBlock.terminal,
|
||||
preds: new Set(),
|
||||
phis: new Set(),
|
||||
};
|
||||
|
||||
/**
|
||||
* Complete current block
|
||||
* - Add instruction for variable declaration
|
||||
* - Add instruction for LoadGlobal used by conditional
|
||||
* - End block with a new IfTerminal
|
||||
*/
|
||||
const varPlace = createTemporaryPlace(fn.env, instr.value.loc);
|
||||
promoteTemporary(varPlace.identifier);
|
||||
const varLValuePlace = createTemporaryPlace(fn.env, instr.value.loc);
|
||||
const thenVarPlace = {
|
||||
...varPlace,
|
||||
identifier: forkTemporaryIdentifier(
|
||||
fn.env.nextIdentifierId,
|
||||
varPlace.identifier,
|
||||
),
|
||||
};
|
||||
const elseVarPlace = {
|
||||
...varPlace,
|
||||
identifier: forkTemporaryIdentifier(
|
||||
fn.env.nextIdentifierId,
|
||||
varPlace.identifier,
|
||||
),
|
||||
};
|
||||
const varInstruction: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
lvalue: {...varLValuePlace},
|
||||
value: {
|
||||
kind: 'DeclareLocal',
|
||||
lvalue: {place: {...varPlace}, kind: InstructionKind.Let},
|
||||
type: null,
|
||||
loc: instr.value.loc,
|
||||
},
|
||||
effects: null,
|
||||
loc: instr.loc,
|
||||
};
|
||||
currentBlockInstructions.push(varInstruction);
|
||||
|
||||
const devGlobalPlace = createTemporaryPlace(fn.env, instr.value.loc);
|
||||
const devGlobalInstruction: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
lvalue: {...devGlobalPlace, effect: Effect.Mutate},
|
||||
value: {
|
||||
kind: 'LoadGlobal',
|
||||
binding: {
|
||||
kind: 'Global',
|
||||
name: inlineJsxTransformConfig.globalDevVar,
|
||||
},
|
||||
loc: instr.value.loc,
|
||||
},
|
||||
effects: null,
|
||||
loc: instr.loc,
|
||||
};
|
||||
currentBlockInstructions.push(devGlobalInstruction);
|
||||
const thenBlockId = fn.env.nextBlockId;
|
||||
const elseBlockId = fn.env.nextBlockId;
|
||||
const ifTerminal: IfTerminal = {
|
||||
kind: 'if',
|
||||
test: {...devGlobalPlace, effect: Effect.Read},
|
||||
consequent: thenBlockId,
|
||||
alternate: elseBlockId,
|
||||
fallthrough: fallthroughBlockId,
|
||||
loc: instr.loc,
|
||||
id: makeInstructionId(0),
|
||||
};
|
||||
currentBlock.instructions = currentBlockInstructions;
|
||||
currentBlock.terminal = ifTerminal;
|
||||
|
||||
/**
|
||||
* Set up then block where we put the original JSX return
|
||||
*/
|
||||
const thenBlock: BasicBlock = {
|
||||
id: thenBlockId,
|
||||
instructions: thenBlockInstructions,
|
||||
kind: 'block',
|
||||
phis: new Set(),
|
||||
preds: new Set(),
|
||||
terminal: {
|
||||
kind: 'goto',
|
||||
block: fallthroughBlockId,
|
||||
variant: GotoVariant.Break,
|
||||
id: makeInstructionId(0),
|
||||
loc: instr.loc,
|
||||
},
|
||||
};
|
||||
fn.body.blocks.set(thenBlockId, thenBlock);
|
||||
|
||||
const resassignElsePlace = createTemporaryPlace(
|
||||
fn.env,
|
||||
instr.value.loc,
|
||||
);
|
||||
const reassignElseInstruction: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
lvalue: {...resassignElsePlace},
|
||||
value: {
|
||||
kind: 'StoreLocal',
|
||||
lvalue: {
|
||||
place: elseVarPlace,
|
||||
kind: InstructionKind.Reassign,
|
||||
},
|
||||
value: {...instr.lvalue},
|
||||
type: null,
|
||||
loc: instr.value.loc,
|
||||
},
|
||||
effects: null,
|
||||
loc: instr.loc,
|
||||
};
|
||||
thenBlockInstructions.push(reassignElseInstruction);
|
||||
|
||||
/**
|
||||
* Set up else block where we add new codegen
|
||||
*/
|
||||
const elseBlockTerminal: GotoTerminal = {
|
||||
kind: 'goto',
|
||||
block: fallthroughBlockId,
|
||||
variant: GotoVariant.Break,
|
||||
id: makeInstructionId(0),
|
||||
loc: instr.loc,
|
||||
};
|
||||
const elseBlock: BasicBlock = {
|
||||
id: elseBlockId,
|
||||
instructions: elseBlockInstructions,
|
||||
kind: 'block',
|
||||
phis: new Set(),
|
||||
preds: new Set(),
|
||||
terminal: elseBlockTerminal,
|
||||
};
|
||||
fn.body.blocks.set(elseBlockId, elseBlock);
|
||||
|
||||
/**
|
||||
* ReactElement object literal codegen
|
||||
*/
|
||||
const {refProperty, keyProperty, propsProperty} =
|
||||
createPropsProperties(
|
||||
fn,
|
||||
instr,
|
||||
elseBlockInstructions,
|
||||
instr.value.kind === 'JsxExpression' ? instr.value.props : [],
|
||||
instr.value.children,
|
||||
);
|
||||
const reactElementInstructionPlace = createTemporaryPlace(
|
||||
fn.env,
|
||||
instr.value.loc,
|
||||
);
|
||||
const reactElementInstruction: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
lvalue: {...reactElementInstructionPlace, effect: Effect.Store},
|
||||
value: {
|
||||
kind: 'ObjectExpression',
|
||||
properties: [
|
||||
createSymbolProperty(
|
||||
fn,
|
||||
instr,
|
||||
elseBlockInstructions,
|
||||
'$$typeof',
|
||||
inlineJsxTransformConfig.elementSymbol,
|
||||
),
|
||||
instr.value.kind === 'JsxExpression'
|
||||
? createTagProperty(
|
||||
fn,
|
||||
instr,
|
||||
elseBlockInstructions,
|
||||
instr.value.tag,
|
||||
)
|
||||
: createSymbolProperty(
|
||||
fn,
|
||||
instr,
|
||||
elseBlockInstructions,
|
||||
'type',
|
||||
'react.fragment',
|
||||
),
|
||||
refProperty,
|
||||
keyProperty,
|
||||
propsProperty,
|
||||
],
|
||||
loc: instr.value.loc,
|
||||
},
|
||||
effects: null,
|
||||
loc: instr.loc,
|
||||
};
|
||||
elseBlockInstructions.push(reactElementInstruction);
|
||||
|
||||
const reassignConditionalInstruction: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
lvalue: {...createTemporaryPlace(fn.env, instr.value.loc)},
|
||||
value: {
|
||||
kind: 'StoreLocal',
|
||||
lvalue: {
|
||||
place: {...elseVarPlace},
|
||||
kind: InstructionKind.Reassign,
|
||||
},
|
||||
value: {...reactElementInstruction.lvalue},
|
||||
type: null,
|
||||
loc: instr.value.loc,
|
||||
},
|
||||
effects: null,
|
||||
loc: instr.loc,
|
||||
};
|
||||
elseBlockInstructions.push(reassignConditionalInstruction);
|
||||
|
||||
/**
|
||||
* Create phis to reassign the var
|
||||
*/
|
||||
const operands: Map<BlockId, Place> = new Map();
|
||||
operands.set(thenBlockId, {
|
||||
...elseVarPlace,
|
||||
});
|
||||
operands.set(elseBlockId, {
|
||||
...thenVarPlace,
|
||||
});
|
||||
|
||||
const phiIdentifier = forkTemporaryIdentifier(
|
||||
fn.env.nextIdentifierId,
|
||||
varPlace.identifier,
|
||||
);
|
||||
const phiPlace = {
|
||||
...createTemporaryPlace(fn.env, instr.value.loc),
|
||||
identifier: phiIdentifier,
|
||||
};
|
||||
const phis: Set<Phi> = new Set([
|
||||
{
|
||||
kind: 'Phi',
|
||||
operands,
|
||||
place: phiPlace,
|
||||
},
|
||||
]);
|
||||
fallthroughBlock.phis = phis;
|
||||
fn.body.blocks.set(fallthroughBlockId, fallthroughBlock);
|
||||
|
||||
/**
|
||||
* Track this JSX instruction so we can replace references in step 2
|
||||
*/
|
||||
inlinedJsxDeclarations.set(instr.lvalue.identifier.declarationId, {
|
||||
identifier: phiIdentifier,
|
||||
blockIdsToIgnore: new Set([thenBlockId, elseBlockId]),
|
||||
});
|
||||
break;
|
||||
}
|
||||
case 'FunctionExpression':
|
||||
case 'ObjectMethod': {
|
||||
inlineJsxTransform(
|
||||
instr.value.loweredFunc.func,
|
||||
inlineJsxTransformConfig,
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 2: Replace declarations with new phi values
|
||||
*/
|
||||
for (const [blockId, block] of fn.body.blocks) {
|
||||
for (const instr of block.instructions) {
|
||||
mapInstructionOperands(instr, place =>
|
||||
handlePlace(place, blockId, inlinedJsxDeclarations),
|
||||
);
|
||||
|
||||
mapInstructionLValues(instr, lvalue =>
|
||||
handlelValue(lvalue, blockId, inlinedJsxDeclarations),
|
||||
);
|
||||
|
||||
mapInstructionValueOperands(instr.value, place =>
|
||||
handlePlace(place, blockId, inlinedJsxDeclarations),
|
||||
);
|
||||
}
|
||||
|
||||
mapTerminalOperands(block.terminal, place =>
|
||||
handlePlace(place, blockId, inlinedJsxDeclarations),
|
||||
);
|
||||
|
||||
if (block.terminal.kind === 'scope') {
|
||||
const scope = block.terminal.scope;
|
||||
for (const dep of scope.dependencies) {
|
||||
dep.identifier = handleIdentifier(
|
||||
dep.identifier,
|
||||
inlinedJsxDeclarations,
|
||||
);
|
||||
}
|
||||
|
||||
for (const [origId, decl] of [...scope.declarations]) {
|
||||
const newDecl = handleIdentifier(
|
||||
decl.identifier,
|
||||
inlinedJsxDeclarations,
|
||||
);
|
||||
if (newDecl.id !== origId) {
|
||||
scope.declarations.delete(origId);
|
||||
scope.declarations.set(decl.identifier.id, {
|
||||
identifier: newDecl,
|
||||
scope: decl.scope,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Step 3: Fixup the HIR
|
||||
* Restore RPO, ensure correct predecessors, renumber instructions, fix scope and ranges.
|
||||
*/
|
||||
reversePostorderBlocks(fn.body);
|
||||
markPredecessors(fn.body);
|
||||
markInstructionIds(fn.body);
|
||||
fixScopeAndIdentifierRanges(fn.body);
|
||||
}
|
||||
|
||||
function createSymbolProperty(
|
||||
fn: HIRFunction,
|
||||
instr: Instruction,
|
||||
nextInstructions: Array<Instruction>,
|
||||
propertyName: string,
|
||||
symbolName: string,
|
||||
): ObjectProperty {
|
||||
const symbolPlace = createTemporaryPlace(fn.env, instr.value.loc);
|
||||
const symbolInstruction: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
lvalue: {...symbolPlace, effect: Effect.Mutate},
|
||||
value: {
|
||||
kind: 'LoadGlobal',
|
||||
binding: {kind: 'Global', name: 'Symbol'},
|
||||
loc: instr.value.loc,
|
||||
},
|
||||
effects: null,
|
||||
loc: instr.loc,
|
||||
};
|
||||
nextInstructions.push(symbolInstruction);
|
||||
|
||||
const symbolForPlace = createTemporaryPlace(fn.env, instr.value.loc);
|
||||
const symbolForInstruction: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
lvalue: {...symbolForPlace, effect: Effect.Read},
|
||||
value: {
|
||||
kind: 'PropertyLoad',
|
||||
object: {...symbolInstruction.lvalue},
|
||||
property: makePropertyLiteral('for'),
|
||||
loc: instr.value.loc,
|
||||
},
|
||||
effects: null,
|
||||
loc: instr.loc,
|
||||
};
|
||||
nextInstructions.push(symbolForInstruction);
|
||||
|
||||
const symbolValuePlace = createTemporaryPlace(fn.env, instr.value.loc);
|
||||
const symbolValueInstruction: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
lvalue: {...symbolValuePlace, effect: Effect.Mutate},
|
||||
value: {
|
||||
kind: 'Primitive',
|
||||
value: symbolName,
|
||||
loc: instr.value.loc,
|
||||
},
|
||||
effects: null,
|
||||
loc: instr.loc,
|
||||
};
|
||||
nextInstructions.push(symbolValueInstruction);
|
||||
|
||||
const $$typeofPlace = createTemporaryPlace(fn.env, instr.value.loc);
|
||||
const $$typeofInstruction: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
lvalue: {...$$typeofPlace, effect: Effect.Mutate},
|
||||
value: {
|
||||
kind: 'MethodCall',
|
||||
receiver: symbolInstruction.lvalue,
|
||||
property: symbolForInstruction.lvalue,
|
||||
args: [symbolValueInstruction.lvalue],
|
||||
loc: instr.value.loc,
|
||||
},
|
||||
effects: null,
|
||||
loc: instr.loc,
|
||||
};
|
||||
const $$typeofProperty: ObjectProperty = {
|
||||
kind: 'ObjectProperty',
|
||||
key: {name: propertyName, kind: 'string'},
|
||||
type: 'property',
|
||||
place: {...$$typeofPlace, effect: Effect.Capture},
|
||||
};
|
||||
nextInstructions.push($$typeofInstruction);
|
||||
return $$typeofProperty;
|
||||
}
|
||||
|
||||
function createTagProperty(
|
||||
fn: HIRFunction,
|
||||
instr: Instruction,
|
||||
nextInstructions: Array<Instruction>,
|
||||
componentTag: BuiltinTag | Place,
|
||||
): ObjectProperty {
|
||||
let tagProperty: ObjectProperty;
|
||||
switch (componentTag.kind) {
|
||||
case 'BuiltinTag': {
|
||||
const tagPropertyPlace = createTemporaryPlace(fn.env, instr.value.loc);
|
||||
const tagInstruction: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
lvalue: {...tagPropertyPlace, effect: Effect.Mutate},
|
||||
value: {
|
||||
kind: 'Primitive',
|
||||
value: componentTag.name,
|
||||
loc: instr.value.loc,
|
||||
},
|
||||
effects: null,
|
||||
loc: instr.loc,
|
||||
};
|
||||
tagProperty = {
|
||||
kind: 'ObjectProperty',
|
||||
key: {name: 'type', kind: 'string'},
|
||||
type: 'property',
|
||||
place: {...tagPropertyPlace, effect: Effect.Capture},
|
||||
};
|
||||
nextInstructions.push(tagInstruction);
|
||||
break;
|
||||
}
|
||||
case 'Identifier': {
|
||||
tagProperty = {
|
||||
kind: 'ObjectProperty',
|
||||
key: {name: 'type', kind: 'string'},
|
||||
type: 'property',
|
||||
place: {...componentTag, effect: Effect.Capture},
|
||||
};
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return tagProperty;
|
||||
}
|
||||
|
||||
function createPropsProperties(
|
||||
fn: HIRFunction,
|
||||
instr: Instruction,
|
||||
nextInstructions: Array<Instruction>,
|
||||
propAttributes: Array<JsxAttribute>,
|
||||
children: Array<Place> | null,
|
||||
): {
|
||||
refProperty: ObjectProperty;
|
||||
keyProperty: ObjectProperty;
|
||||
propsProperty: ObjectProperty;
|
||||
} {
|
||||
let refProperty: ObjectProperty | undefined;
|
||||
let keyProperty: ObjectProperty | undefined;
|
||||
const props: Array<ObjectProperty | SpreadPattern> = [];
|
||||
const jsxAttributesWithoutKey = propAttributes.filter(
|
||||
p => p.kind === 'JsxAttribute' && p.name !== 'key',
|
||||
);
|
||||
const jsxSpreadAttributes = propAttributes.filter(
|
||||
p => p.kind === 'JsxSpreadAttribute',
|
||||
);
|
||||
const spreadPropsOnly =
|
||||
jsxAttributesWithoutKey.length === 0 && jsxSpreadAttributes.length === 1;
|
||||
propAttributes.forEach(prop => {
|
||||
switch (prop.kind) {
|
||||
case 'JsxAttribute': {
|
||||
switch (prop.name) {
|
||||
case 'key': {
|
||||
keyProperty = {
|
||||
kind: 'ObjectProperty',
|
||||
key: {name: 'key', kind: 'string'},
|
||||
type: 'property',
|
||||
place: {...prop.place},
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 'ref': {
|
||||
/**
|
||||
* In the current JSX implementation, ref is both
|
||||
* a property on the element and a property on props.
|
||||
*/
|
||||
refProperty = {
|
||||
kind: 'ObjectProperty',
|
||||
key: {name: 'ref', kind: 'string'},
|
||||
type: 'property',
|
||||
place: {...prop.place},
|
||||
};
|
||||
const refPropProperty: ObjectProperty = {
|
||||
kind: 'ObjectProperty',
|
||||
key: {name: 'ref', kind: 'string'},
|
||||
type: 'property',
|
||||
place: {...prop.place},
|
||||
};
|
||||
props.push(refPropProperty);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
const attributeProperty: ObjectProperty = {
|
||||
kind: 'ObjectProperty',
|
||||
key: {name: prop.name, kind: 'string'},
|
||||
type: 'property',
|
||||
place: {...prop.place},
|
||||
};
|
||||
props.push(attributeProperty);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'JsxSpreadAttribute': {
|
||||
props.push({
|
||||
kind: 'Spread',
|
||||
place: {...prop.argument},
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const propsPropertyPlace = createTemporaryPlace(fn.env, instr.value.loc);
|
||||
if (children) {
|
||||
let childrenPropProperty: ObjectProperty;
|
||||
if (children.length === 1) {
|
||||
childrenPropProperty = {
|
||||
kind: 'ObjectProperty',
|
||||
key: {name: 'children', kind: 'string'},
|
||||
type: 'property',
|
||||
place: {...children[0], effect: Effect.Capture},
|
||||
};
|
||||
} else {
|
||||
const childrenPropPropertyPlace = createTemporaryPlace(
|
||||
fn.env,
|
||||
instr.value.loc,
|
||||
);
|
||||
|
||||
const childrenPropInstruction: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
lvalue: {...childrenPropPropertyPlace, effect: Effect.Mutate},
|
||||
value: {
|
||||
kind: 'ArrayExpression',
|
||||
elements: [...children],
|
||||
loc: instr.value.loc,
|
||||
},
|
||||
effects: null,
|
||||
loc: instr.loc,
|
||||
};
|
||||
nextInstructions.push(childrenPropInstruction);
|
||||
childrenPropProperty = {
|
||||
kind: 'ObjectProperty',
|
||||
key: {name: 'children', kind: 'string'},
|
||||
type: 'property',
|
||||
place: {...childrenPropPropertyPlace, effect: Effect.Capture},
|
||||
};
|
||||
}
|
||||
props.push(childrenPropProperty);
|
||||
}
|
||||
|
||||
if (refProperty == null) {
|
||||
const refPropertyPlace = createTemporaryPlace(fn.env, instr.value.loc);
|
||||
const refInstruction: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
lvalue: {...refPropertyPlace, effect: Effect.Mutate},
|
||||
value: {
|
||||
kind: 'Primitive',
|
||||
value: null,
|
||||
loc: instr.value.loc,
|
||||
},
|
||||
effects: null,
|
||||
loc: instr.loc,
|
||||
};
|
||||
refProperty = {
|
||||
kind: 'ObjectProperty',
|
||||
key: {name: 'ref', kind: 'string'},
|
||||
type: 'property',
|
||||
place: {...refPropertyPlace, effect: Effect.Capture},
|
||||
};
|
||||
nextInstructions.push(refInstruction);
|
||||
}
|
||||
|
||||
if (keyProperty == null) {
|
||||
const keyPropertyPlace = createTemporaryPlace(fn.env, instr.value.loc);
|
||||
const keyInstruction: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
lvalue: {...keyPropertyPlace, effect: Effect.Mutate},
|
||||
value: {
|
||||
kind: 'Primitive',
|
||||
value: null,
|
||||
loc: instr.value.loc,
|
||||
},
|
||||
effects: null,
|
||||
loc: instr.loc,
|
||||
};
|
||||
keyProperty = {
|
||||
kind: 'ObjectProperty',
|
||||
key: {name: 'key', kind: 'string'},
|
||||
type: 'property',
|
||||
place: {...keyPropertyPlace, effect: Effect.Capture},
|
||||
};
|
||||
nextInstructions.push(keyInstruction);
|
||||
}
|
||||
|
||||
let propsProperty: ObjectProperty;
|
||||
if (spreadPropsOnly) {
|
||||
const spreadProp = jsxSpreadAttributes[0];
|
||||
CompilerError.invariant(spreadProp.kind === 'JsxSpreadAttribute', {
|
||||
reason: 'Spread prop attribute must be of kind JSXSpreadAttribute',
|
||||
loc: instr.loc,
|
||||
});
|
||||
propsProperty = {
|
||||
kind: 'ObjectProperty',
|
||||
key: {name: 'props', kind: 'string'},
|
||||
type: 'property',
|
||||
place: {...spreadProp.argument, effect: Effect.Mutate},
|
||||
};
|
||||
} else {
|
||||
const propsInstruction: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
lvalue: {...propsPropertyPlace, effect: Effect.Mutate},
|
||||
value: {
|
||||
kind: 'ObjectExpression',
|
||||
properties: props,
|
||||
loc: instr.value.loc,
|
||||
},
|
||||
effects: null,
|
||||
loc: instr.loc,
|
||||
};
|
||||
propsProperty = {
|
||||
kind: 'ObjectProperty',
|
||||
key: {name: 'props', kind: 'string'},
|
||||
type: 'property',
|
||||
place: {...propsPropertyPlace, effect: Effect.Capture},
|
||||
};
|
||||
nextInstructions.push(propsInstruction);
|
||||
}
|
||||
|
||||
return {refProperty, keyProperty, propsProperty};
|
||||
}
|
||||
|
||||
function handlePlace(
|
||||
place: Place,
|
||||
blockId: BlockId,
|
||||
inlinedJsxDeclarations: InlinedJsxDeclarationMap,
|
||||
): Place {
|
||||
const inlinedJsxDeclaration = inlinedJsxDeclarations.get(
|
||||
place.identifier.declarationId,
|
||||
);
|
||||
if (
|
||||
inlinedJsxDeclaration == null ||
|
||||
inlinedJsxDeclaration.blockIdsToIgnore.has(blockId)
|
||||
) {
|
||||
return place;
|
||||
}
|
||||
|
||||
return {...place, identifier: inlinedJsxDeclaration.identifier};
|
||||
}
|
||||
|
||||
function handlelValue(
|
||||
lvalue: Place,
|
||||
blockId: BlockId,
|
||||
inlinedJsxDeclarations: InlinedJsxDeclarationMap,
|
||||
): Place {
|
||||
const inlinedJsxDeclaration = inlinedJsxDeclarations.get(
|
||||
lvalue.identifier.declarationId,
|
||||
);
|
||||
if (
|
||||
inlinedJsxDeclaration == null ||
|
||||
inlinedJsxDeclaration.blockIdsToIgnore.has(blockId)
|
||||
) {
|
||||
return lvalue;
|
||||
}
|
||||
|
||||
return {...lvalue, identifier: inlinedJsxDeclaration.identifier};
|
||||
}
|
||||
|
||||
function handleIdentifier(
|
||||
identifier: Identifier,
|
||||
inlinedJsxDeclarations: InlinedJsxDeclarationMap,
|
||||
): Identifier {
|
||||
const inlinedJsxDeclaration = inlinedJsxDeclarations.get(
|
||||
identifier.declarationId,
|
||||
);
|
||||
return inlinedJsxDeclaration == null
|
||||
? identifier
|
||||
: inlinedJsxDeclaration.identifier;
|
||||
}
|
||||
@@ -1,503 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {CompilerError} from '..';
|
||||
import {
|
||||
BasicBlock,
|
||||
Environment,
|
||||
GeneratedSource,
|
||||
HIRFunction,
|
||||
IdentifierId,
|
||||
Instruction,
|
||||
InstructionId,
|
||||
Place,
|
||||
isExpressionBlockKind,
|
||||
makeInstructionId,
|
||||
markInstructionIds,
|
||||
} from '../HIR';
|
||||
import {printInstruction} from '../HIR/PrintHIR';
|
||||
import {
|
||||
eachInstructionLValue,
|
||||
eachInstructionValueLValue,
|
||||
eachInstructionValueOperand,
|
||||
eachTerminalOperand,
|
||||
} from '../HIR/visitors';
|
||||
import {getOrInsertWith} from '../Utils/utils';
|
||||
|
||||
/**
|
||||
* This pass implements conservative instruction reordering to move instructions closer to
|
||||
* to where their produced values are consumed. The goal is to group instructions in a way that
|
||||
* is more optimal for future optimizations. Notably, MergeReactiveScopesThatAlwaysInvalidateTogether
|
||||
* can only merge two candidate scopes if there are no intervenining instructions that are used by
|
||||
* some later code: instruction reordering can move those intervening instructions later in many cases,
|
||||
* thereby allowing more scopes to merge together.
|
||||
*
|
||||
* The high-level approach is to build a dependency graph where nodes correspond either to
|
||||
* instructions OR to a particular lvalue assignment of another instruction. So
|
||||
* `Destructure [x, y] = z` creates 3 nodes: one for the instruction, and one each for x and y.
|
||||
* The lvalue nodes depend on the instruction node that assigns them.
|
||||
*
|
||||
* Dependency edges are added for all the lvalues and rvalues of each instruction, so for example
|
||||
* the node for `t$2 = CallExpression t$0 ( t$1 )` will take dependencies on the nodes for t$0 and t$1.
|
||||
*
|
||||
* Individual instructions are grouped into two categories:
|
||||
* - "Reorderable" instructions include a safe set of instructions that we know are fine to reorder.
|
||||
* This includes JSX elements/fragments/text, primitives, template literals, and globals.
|
||||
* These instructions are never emitted until they are referenced, and can even be moved across
|
||||
* basic blocks until they are used.
|
||||
* - All other instructions are non-reorderable, and take an explicit dependency on the last such
|
||||
* non-reorderable instruction in their block. This largely ensures that mutations are serialized,
|
||||
* since all potentially mutating instructions are in this category.
|
||||
*
|
||||
* The only remaining mutation not handled by the above is variable reassignment. To ensure that all
|
||||
* reads/writes of a variable access the correct version, all references (lvalues and rvalues) to
|
||||
* each named variable are serialized. Thus `x = 1; y = x; x = 2; z = x` will establish a chain
|
||||
* of dependencies and retain the correct ordering.
|
||||
*
|
||||
* The algorithm proceeds one basic block at a time, first building up the dependnecy graph and then
|
||||
* reordering.
|
||||
*
|
||||
* The reordering weights nodes according to their transitive dependencies, and whether a particular node
|
||||
* needs memoization or not. Larger dependencies go first, followed by smaller dependencies, which in
|
||||
* testing seems to allow scopes to merge more effectively. Over time we can likely continue to improve
|
||||
* the reordering heuristic.
|
||||
*
|
||||
* An obvious area for improvement is to allow reordering of LoadLocals that occur after the last write
|
||||
* of the named variable. We can add this in a follow-up.
|
||||
*/
|
||||
export function instructionReordering(fn: HIRFunction): void {
|
||||
// Shared nodes are emitted when they are first used
|
||||
const shared: Nodes = new Map();
|
||||
const references = findReferencedRangeOfTemporaries(fn);
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
reorderBlock(fn.env, block, shared, references);
|
||||
}
|
||||
CompilerError.invariant(shared.size === 0, {
|
||||
reason: `InstructionReordering: expected all reorderable nodes to have been emitted`,
|
||||
loc:
|
||||
[...shared.values()]
|
||||
.map(node => node.instruction?.loc)
|
||||
.filter(loc => loc != null)[0] ?? GeneratedSource,
|
||||
});
|
||||
markInstructionIds(fn.body);
|
||||
}
|
||||
|
||||
const DEBUG = false;
|
||||
|
||||
type Nodes = Map<IdentifierId, Node>;
|
||||
type Node = {
|
||||
instruction: Instruction | null;
|
||||
dependencies: Set<IdentifierId>;
|
||||
reorderability: Reorderability;
|
||||
depth: number | null;
|
||||
};
|
||||
|
||||
// Inclusive start and end
|
||||
type References = {
|
||||
singleUseIdentifiers: SingleUseIdentifiers;
|
||||
lastAssignments: LastAssignments;
|
||||
};
|
||||
type LastAssignments = Map<string, InstructionId>;
|
||||
type SingleUseIdentifiers = Set<IdentifierId>;
|
||||
enum ReferenceKind {
|
||||
Read,
|
||||
Write,
|
||||
}
|
||||
function findReferencedRangeOfTemporaries(fn: HIRFunction): References {
|
||||
const singleUseIdentifiers = new Map<IdentifierId, number>();
|
||||
const lastAssignments: LastAssignments = new Map();
|
||||
function reference(
|
||||
instr: InstructionId,
|
||||
place: Place,
|
||||
kind: ReferenceKind,
|
||||
): void {
|
||||
if (
|
||||
place.identifier.name !== null &&
|
||||
place.identifier.name.kind === 'named'
|
||||
) {
|
||||
if (kind === ReferenceKind.Write) {
|
||||
const name = place.identifier.name.value;
|
||||
const previous = lastAssignments.get(name);
|
||||
if (previous === undefined) {
|
||||
lastAssignments.set(name, instr);
|
||||
} else {
|
||||
lastAssignments.set(
|
||||
name,
|
||||
makeInstructionId(Math.max(previous, instr)),
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
} else if (kind === ReferenceKind.Read) {
|
||||
const previousCount = singleUseIdentifiers.get(place.identifier.id) ?? 0;
|
||||
singleUseIdentifiers.set(place.identifier.id, previousCount + 1);
|
||||
}
|
||||
}
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
for (const instr of block.instructions) {
|
||||
for (const operand of eachInstructionValueLValue(instr.value)) {
|
||||
reference(instr.id, operand, ReferenceKind.Read);
|
||||
}
|
||||
for (const lvalue of eachInstructionLValue(instr)) {
|
||||
reference(instr.id, lvalue, ReferenceKind.Write);
|
||||
}
|
||||
}
|
||||
for (const operand of eachTerminalOperand(block.terminal)) {
|
||||
reference(block.terminal.id, operand, ReferenceKind.Read);
|
||||
}
|
||||
}
|
||||
return {
|
||||
singleUseIdentifiers: new Set(
|
||||
[...singleUseIdentifiers]
|
||||
.filter(([, count]) => count === 1)
|
||||
.map(([id]) => id),
|
||||
),
|
||||
lastAssignments,
|
||||
};
|
||||
}
|
||||
|
||||
function reorderBlock(
|
||||
env: Environment,
|
||||
block: BasicBlock,
|
||||
shared: Nodes,
|
||||
references: References,
|
||||
): void {
|
||||
const locals: Nodes = new Map();
|
||||
const named: Map<string, IdentifierId> = new Map();
|
||||
let previous: IdentifierId | null = null;
|
||||
for (const instr of block.instructions) {
|
||||
const {lvalue, value} = instr;
|
||||
// Get or create a node for this lvalue
|
||||
const reorderability = getReorderability(instr, references);
|
||||
const node = getOrInsertWith(
|
||||
locals,
|
||||
lvalue.identifier.id,
|
||||
() =>
|
||||
({
|
||||
instruction: instr,
|
||||
dependencies: new Set(),
|
||||
reorderability,
|
||||
depth: null,
|
||||
}) as Node,
|
||||
);
|
||||
/**
|
||||
* Ensure non-reoderable instructions have their order retained by
|
||||
* adding explicit dependencies to the previous such instruction.
|
||||
*/
|
||||
if (reorderability === Reorderability.Nonreorderable) {
|
||||
if (previous !== null) {
|
||||
node.dependencies.add(previous);
|
||||
}
|
||||
previous = lvalue.identifier.id;
|
||||
}
|
||||
/**
|
||||
* Establish dependencies on operands
|
||||
*/
|
||||
for (const operand of eachInstructionValueOperand(value)) {
|
||||
const {name, id} = operand.identifier;
|
||||
if (name !== null && name.kind === 'named') {
|
||||
// Serialize all accesses to named variables
|
||||
const previous = named.get(name.value);
|
||||
if (previous !== undefined) {
|
||||
node.dependencies.add(previous);
|
||||
}
|
||||
named.set(name.value, lvalue.identifier.id);
|
||||
} else if (locals.has(id) || shared.has(id)) {
|
||||
node.dependencies.add(id);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Establish nodes for lvalues, with dependencies on the node
|
||||
* for the instruction itself. This ensures that any consumers
|
||||
* of the lvalue will take a dependency through to the original
|
||||
* instruction.
|
||||
*/
|
||||
for (const lvalueOperand of eachInstructionValueLValue(value)) {
|
||||
const lvalueNode = getOrInsertWith(
|
||||
locals,
|
||||
lvalueOperand.identifier.id,
|
||||
() =>
|
||||
({
|
||||
instruction: null,
|
||||
dependencies: new Set(),
|
||||
depth: null,
|
||||
}) as Node,
|
||||
);
|
||||
lvalueNode.dependencies.add(lvalue.identifier.id);
|
||||
const name = lvalueOperand.identifier.name;
|
||||
if (name !== null && name.kind === 'named') {
|
||||
const previous = named.get(name.value);
|
||||
if (previous !== undefined) {
|
||||
node.dependencies.add(previous);
|
||||
}
|
||||
named.set(name.value, lvalue.identifier.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const nextInstructions: Array<Instruction> = [];
|
||||
const seen = new Set<IdentifierId>();
|
||||
|
||||
DEBUG && console.log(`bb${block.id}`);
|
||||
|
||||
/**
|
||||
* The ideal order for emitting instructions may change the final instruction,
|
||||
* but value blocks have special semantics for the final instruction of a block -
|
||||
* that's the expression's value!. So we choose between a less optimal strategy
|
||||
* for value blocks which preserves the final instruction order OR a more optimal
|
||||
* ordering for statement-y blocks.
|
||||
*/
|
||||
if (isExpressionBlockKind(block.kind)) {
|
||||
// First emit everything that can't be reordered
|
||||
if (previous !== null) {
|
||||
DEBUG && console.log(`(last non-reorderable instruction)`);
|
||||
DEBUG && print(env, locals, shared, seen, previous);
|
||||
emit(env, locals, shared, nextInstructions, previous);
|
||||
}
|
||||
/*
|
||||
* For "value" blocks the final instruction represents its value, so we have to be
|
||||
* careful to not change the ordering. Emit the last instruction explicitly.
|
||||
* Any non-reorderable instructions will get emitted first, and any unused
|
||||
* reorderable instructions can be deferred to the shared node list.
|
||||
*/
|
||||
if (block.instructions.length !== 0) {
|
||||
DEBUG && console.log(`(block value)`);
|
||||
DEBUG &&
|
||||
print(
|
||||
env,
|
||||
locals,
|
||||
shared,
|
||||
seen,
|
||||
block.instructions.at(-1)!.lvalue.identifier.id,
|
||||
);
|
||||
emit(
|
||||
env,
|
||||
locals,
|
||||
shared,
|
||||
nextInstructions,
|
||||
block.instructions.at(-1)!.lvalue.identifier.id,
|
||||
);
|
||||
}
|
||||
/*
|
||||
* Then emit the dependencies of the terminal operand. In many cases they will have
|
||||
* already been emitted in the previous step and this is a no-op.
|
||||
* TODO: sort the dependencies based on weight, like we do for other nodes. Not a big
|
||||
* deal though since most terminals have a single operand
|
||||
*/
|
||||
for (const operand of eachTerminalOperand(block.terminal)) {
|
||||
DEBUG && console.log(`(terminal operand)`);
|
||||
DEBUG && print(env, locals, shared, seen, operand.identifier.id);
|
||||
emit(env, locals, shared, nextInstructions, operand.identifier.id);
|
||||
}
|
||||
// Anything not emitted yet is globally reorderable
|
||||
for (const [id, node] of locals) {
|
||||
if (node.instruction == null) {
|
||||
continue;
|
||||
}
|
||||
CompilerError.invariant(
|
||||
node.reorderability === Reorderability.Reorderable,
|
||||
{
|
||||
reason: `Expected all remaining instructions to be reorderable`,
|
||||
description:
|
||||
node.instruction != null
|
||||
? `Instruction [${node.instruction.id}] was not emitted yet but is not reorderable`
|
||||
: `Lvalue $${id} was not emitted yet but is not reorderable`,
|
||||
loc: node.instruction?.loc ?? block.terminal.loc,
|
||||
},
|
||||
);
|
||||
|
||||
DEBUG && console.log(`save shared: $${id}`);
|
||||
shared.set(id, node);
|
||||
}
|
||||
} else {
|
||||
/**
|
||||
* If this is not a value block, then the order within the block doesn't matter
|
||||
* and we can optimize more. The observation is that blocks often have instructions
|
||||
* such as:
|
||||
*
|
||||
* ```
|
||||
* t$0 = nonreorderable
|
||||
* t$1 = nonreorderable <-- this gets in the way of merging t$0 and t$2
|
||||
* t$2 = reorderable deps[ t$0 ]
|
||||
* return t$2
|
||||
* ```
|
||||
*
|
||||
* Ie where there is some pair of nonreorderable+reorderable values, with some intervening
|
||||
* also non-reorderable instruction. If we emit all non-reorderable instructions first,
|
||||
* then we'll keep the original order. But reordering instructions doesn't just mean moving
|
||||
* them later: we can also move them _earlier_. By starting from terminal operands we
|
||||
* end up emitting:
|
||||
*
|
||||
* ```
|
||||
* t$0 = nonreorderable // dep of t$2
|
||||
* t$2 = reorderable deps[ t$0 ]
|
||||
* t$1 = nonreorderable <-- not in the way of merging anymore!
|
||||
* return t$2
|
||||
* ```
|
||||
*
|
||||
* Ie all nonreorderable transitive deps of the terminal operands will get emitted first,
|
||||
* but we'll be able to intersperse the depending reorderable instructions in between
|
||||
* them in a way that works better with scope merging.
|
||||
*/
|
||||
for (const operand of eachTerminalOperand(block.terminal)) {
|
||||
DEBUG && console.log(`(terminal operand)`);
|
||||
DEBUG && print(env, locals, shared, seen, operand.identifier.id);
|
||||
emit(env, locals, shared, nextInstructions, operand.identifier.id);
|
||||
}
|
||||
// Anything not emitted yet is globally reorderable
|
||||
for (const id of Array.from(locals.keys()).reverse()) {
|
||||
const node = locals.get(id);
|
||||
if (node === undefined) {
|
||||
continue;
|
||||
}
|
||||
if (node.reorderability === Reorderability.Reorderable) {
|
||||
DEBUG && console.log(`save shared: $${id}`);
|
||||
shared.set(id, node);
|
||||
} else {
|
||||
DEBUG && console.log('leftover');
|
||||
DEBUG && print(env, locals, shared, seen, id);
|
||||
emit(env, locals, shared, nextInstructions, id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
block.instructions = nextInstructions;
|
||||
DEBUG && console.log();
|
||||
}
|
||||
|
||||
function getDepth(env: Environment, nodes: Nodes, id: IdentifierId): number {
|
||||
const node = nodes.get(id)!;
|
||||
if (node == null) {
|
||||
return 0;
|
||||
}
|
||||
if (node.depth != null) {
|
||||
return node.depth;
|
||||
}
|
||||
node.depth = 0; // in case of cycles
|
||||
let depth = node.reorderability === Reorderability.Reorderable ? 1 : 10;
|
||||
for (const dep of node.dependencies) {
|
||||
depth += getDepth(env, nodes, dep);
|
||||
}
|
||||
node.depth = depth;
|
||||
return depth;
|
||||
}
|
||||
|
||||
function print(
|
||||
env: Environment,
|
||||
locals: Nodes,
|
||||
shared: Nodes,
|
||||
seen: Set<IdentifierId>,
|
||||
id: IdentifierId,
|
||||
depth: number = 0,
|
||||
): void {
|
||||
if (seen.has(id)) {
|
||||
DEBUG && console.log(`${'| '.repeat(depth)}$${id} <skipped>`);
|
||||
return;
|
||||
}
|
||||
seen.add(id);
|
||||
const node = locals.get(id) ?? shared.get(id);
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
const deps = [...node.dependencies];
|
||||
deps.sort((a, b) => {
|
||||
const aDepth = getDepth(env, locals, a);
|
||||
const bDepth = getDepth(env, locals, b);
|
||||
return bDepth - aDepth;
|
||||
});
|
||||
for (const dep of deps) {
|
||||
print(env, locals, shared, seen, dep, depth + 1);
|
||||
}
|
||||
DEBUG &&
|
||||
console.log(
|
||||
`${'| '.repeat(depth)}$${id} ${printNode(node)} deps=[${deps
|
||||
.map(x => `$${x}`)
|
||||
.join(', ')}] depth=${node.depth}`,
|
||||
);
|
||||
}
|
||||
|
||||
function printNode(node: Node): string {
|
||||
const {instruction} = node;
|
||||
if (instruction === null) {
|
||||
return '<lvalue-only>';
|
||||
}
|
||||
switch (instruction.value.kind) {
|
||||
case 'FunctionExpression':
|
||||
case 'ObjectMethod': {
|
||||
return `[${instruction.id}] ${instruction.value.kind}`;
|
||||
}
|
||||
default: {
|
||||
return printInstruction(instruction);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function emit(
|
||||
env: Environment,
|
||||
locals: Nodes,
|
||||
shared: Nodes,
|
||||
instructions: Array<Instruction>,
|
||||
id: IdentifierId,
|
||||
): void {
|
||||
const node = locals.get(id) ?? shared.get(id);
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
locals.delete(id);
|
||||
shared.delete(id);
|
||||
const deps = [...node.dependencies];
|
||||
deps.sort((a, b) => {
|
||||
const aDepth = getDepth(env, locals, a);
|
||||
const bDepth = getDepth(env, locals, b);
|
||||
return bDepth - aDepth;
|
||||
});
|
||||
for (const dep of deps) {
|
||||
emit(env, locals, shared, instructions, dep);
|
||||
}
|
||||
if (node.instruction !== null) {
|
||||
instructions.push(node.instruction);
|
||||
}
|
||||
}
|
||||
|
||||
enum Reorderability {
|
||||
Reorderable,
|
||||
Nonreorderable,
|
||||
}
|
||||
function getReorderability(
|
||||
instr: Instruction,
|
||||
references: References,
|
||||
): Reorderability {
|
||||
switch (instr.value.kind) {
|
||||
case 'JsxExpression':
|
||||
case 'JsxFragment':
|
||||
case 'JSXText':
|
||||
case 'LoadGlobal':
|
||||
case 'Primitive':
|
||||
case 'TemplateLiteral':
|
||||
case 'BinaryExpression':
|
||||
case 'UnaryExpression': {
|
||||
return Reorderability.Reorderable;
|
||||
}
|
||||
case 'LoadLocal': {
|
||||
const name = instr.value.place.identifier.name;
|
||||
if (name !== null && name.kind === 'named') {
|
||||
const lastAssignment = references.lastAssignments.get(name.value);
|
||||
if (
|
||||
lastAssignment !== undefined &&
|
||||
lastAssignment < instr.id &&
|
||||
references.singleUseIdentifiers.has(instr.lvalue.identifier.id)
|
||||
) {
|
||||
return Reorderability.Reorderable;
|
||||
}
|
||||
}
|
||||
return Reorderability.Nonreorderable;
|
||||
}
|
||||
default: {
|
||||
return Reorderability.Nonreorderable;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,308 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {
|
||||
ArrayExpression,
|
||||
BasicBlock,
|
||||
CallExpression,
|
||||
Destructure,
|
||||
Environment,
|
||||
ExternalFunction,
|
||||
GeneratedSource,
|
||||
HIRFunction,
|
||||
IdentifierId,
|
||||
Instruction,
|
||||
LoadGlobal,
|
||||
LoadLocal,
|
||||
NonLocalImportSpecifier,
|
||||
Place,
|
||||
PropertyLoad,
|
||||
isUseContextHookType,
|
||||
makeBlockId,
|
||||
makeInstructionId,
|
||||
makePropertyLiteral,
|
||||
markInstructionIds,
|
||||
promoteTemporary,
|
||||
reversePostorderBlocks,
|
||||
} from '../HIR';
|
||||
import {createTemporaryPlace} from '../HIR/HIRBuilder';
|
||||
import {enterSSA} from '../SSA';
|
||||
import {inferTypes} from '../TypeInference';
|
||||
|
||||
export function lowerContextAccess(
|
||||
fn: HIRFunction,
|
||||
loweredContextCalleeConfig: ExternalFunction,
|
||||
): void {
|
||||
const contextAccess: Map<IdentifierId, CallExpression> = new Map();
|
||||
const contextKeys: Map<IdentifierId, Array<string>> = new Map();
|
||||
|
||||
// collect context access and keys
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
for (const instr of block.instructions) {
|
||||
const {value, lvalue} = instr;
|
||||
|
||||
if (
|
||||
value.kind === 'CallExpression' &&
|
||||
isUseContextHookType(value.callee.identifier)
|
||||
) {
|
||||
contextAccess.set(lvalue.identifier.id, value);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (value.kind !== 'Destructure') {
|
||||
continue;
|
||||
}
|
||||
|
||||
const destructureId = value.value.identifier.id;
|
||||
if (!contextAccess.has(destructureId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const keys = getContextKeys(value);
|
||||
if (keys === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (contextKeys.has(destructureId)) {
|
||||
/*
|
||||
* TODO(gsn): Add support for accessing context over multiple
|
||||
* statements.
|
||||
*/
|
||||
return;
|
||||
} else {
|
||||
contextKeys.set(destructureId, keys);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let importLoweredContextCallee: NonLocalImportSpecifier | null = null;
|
||||
|
||||
if (contextAccess.size > 0 && contextKeys.size > 0) {
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
let nextInstructions: Array<Instruction> | null = null;
|
||||
|
||||
for (let i = 0; i < block.instructions.length; i++) {
|
||||
const instr = block.instructions[i];
|
||||
const {lvalue, value} = instr;
|
||||
if (
|
||||
value.kind === 'CallExpression' &&
|
||||
isUseContextHookType(value.callee.identifier) &&
|
||||
contextKeys.has(lvalue.identifier.id)
|
||||
) {
|
||||
importLoweredContextCallee ??=
|
||||
fn.env.programContext.addImportSpecifier(
|
||||
loweredContextCalleeConfig,
|
||||
);
|
||||
const loweredContextCalleeInstr = emitLoadLoweredContextCallee(
|
||||
fn.env,
|
||||
importLoweredContextCallee,
|
||||
);
|
||||
|
||||
if (nextInstructions === null) {
|
||||
nextInstructions = block.instructions.slice(0, i);
|
||||
}
|
||||
nextInstructions.push(loweredContextCalleeInstr);
|
||||
|
||||
const keys = contextKeys.get(lvalue.identifier.id)!;
|
||||
const selectorFnInstr = emitSelectorFn(fn.env, keys);
|
||||
nextInstructions.push(selectorFnInstr);
|
||||
|
||||
const lowerContextCallId = loweredContextCalleeInstr.lvalue;
|
||||
value.callee = lowerContextCallId;
|
||||
|
||||
const selectorFn = selectorFnInstr.lvalue;
|
||||
value.args.push(selectorFn);
|
||||
}
|
||||
|
||||
if (nextInstructions) {
|
||||
nextInstructions.push(instr);
|
||||
}
|
||||
}
|
||||
if (nextInstructions) {
|
||||
block.instructions = nextInstructions;
|
||||
}
|
||||
}
|
||||
markInstructionIds(fn.body);
|
||||
inferTypes(fn);
|
||||
}
|
||||
}
|
||||
|
||||
function emitLoadLoweredContextCallee(
|
||||
env: Environment,
|
||||
importedLowerContextCallee: NonLocalImportSpecifier,
|
||||
): Instruction {
|
||||
const loadGlobal: LoadGlobal = {
|
||||
kind: 'LoadGlobal',
|
||||
binding: {...importedLowerContextCallee},
|
||||
loc: GeneratedSource,
|
||||
};
|
||||
|
||||
return {
|
||||
id: makeInstructionId(0),
|
||||
loc: GeneratedSource,
|
||||
lvalue: createTemporaryPlace(env, GeneratedSource),
|
||||
effects: null,
|
||||
value: loadGlobal,
|
||||
};
|
||||
}
|
||||
|
||||
function getContextKeys(value: Destructure): Array<string> | null {
|
||||
const keys = [];
|
||||
const pattern = value.lvalue.pattern;
|
||||
|
||||
switch (pattern.kind) {
|
||||
case 'ArrayPattern': {
|
||||
return null;
|
||||
}
|
||||
|
||||
case 'ObjectPattern': {
|
||||
for (const place of pattern.properties) {
|
||||
if (
|
||||
place.kind !== 'ObjectProperty' ||
|
||||
place.type !== 'property' ||
|
||||
place.key.kind !== 'identifier' ||
|
||||
place.place.identifier.name === null ||
|
||||
place.place.identifier.name.kind !== 'named'
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
keys.push(place.key.name);
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function emitPropertyLoad(
|
||||
env: Environment,
|
||||
obj: Place,
|
||||
property: string,
|
||||
): {instructions: Array<Instruction>; element: Place} {
|
||||
const loadObj: LoadLocal = {
|
||||
kind: 'LoadLocal',
|
||||
place: obj,
|
||||
loc: GeneratedSource,
|
||||
};
|
||||
const object: Place = createTemporaryPlace(env, GeneratedSource);
|
||||
const loadLocalInstr: Instruction = {
|
||||
lvalue: object,
|
||||
value: loadObj,
|
||||
id: makeInstructionId(0),
|
||||
effects: null,
|
||||
loc: GeneratedSource,
|
||||
};
|
||||
|
||||
const loadProp: PropertyLoad = {
|
||||
kind: 'PropertyLoad',
|
||||
object,
|
||||
property: makePropertyLiteral(property),
|
||||
loc: GeneratedSource,
|
||||
};
|
||||
const element: Place = createTemporaryPlace(env, GeneratedSource);
|
||||
const loadPropInstr: Instruction = {
|
||||
lvalue: element,
|
||||
value: loadProp,
|
||||
id: makeInstructionId(0),
|
||||
effects: null,
|
||||
loc: GeneratedSource,
|
||||
};
|
||||
return {
|
||||
instructions: [loadLocalInstr, loadPropInstr],
|
||||
element: element,
|
||||
};
|
||||
}
|
||||
|
||||
function emitSelectorFn(env: Environment, keys: Array<string>): Instruction {
|
||||
const obj: Place = createTemporaryPlace(env, GeneratedSource);
|
||||
promoteTemporary(obj.identifier);
|
||||
const instr: Array<Instruction> = [];
|
||||
const elements = [];
|
||||
for (const key of keys) {
|
||||
const {instructions, element: prop} = emitPropertyLoad(env, obj, key);
|
||||
instr.push(...instructions);
|
||||
elements.push(prop);
|
||||
}
|
||||
|
||||
const arrayInstr = emitArrayInstr(elements, env);
|
||||
instr.push(arrayInstr);
|
||||
|
||||
const block: BasicBlock = {
|
||||
kind: 'block',
|
||||
id: makeBlockId(0),
|
||||
instructions: instr,
|
||||
terminal: {
|
||||
id: makeInstructionId(0),
|
||||
kind: 'return',
|
||||
returnVariant: 'Explicit',
|
||||
loc: GeneratedSource,
|
||||
value: arrayInstr.lvalue,
|
||||
effects: null,
|
||||
},
|
||||
preds: new Set(),
|
||||
phis: new Set(),
|
||||
};
|
||||
|
||||
const fn: HIRFunction = {
|
||||
loc: GeneratedSource,
|
||||
id: null,
|
||||
nameHint: null,
|
||||
fnType: 'Other',
|
||||
env,
|
||||
params: [obj],
|
||||
returnTypeAnnotation: null,
|
||||
returns: createTemporaryPlace(env, GeneratedSource),
|
||||
context: [],
|
||||
body: {
|
||||
entry: block.id,
|
||||
blocks: new Map([[block.id, block]]),
|
||||
},
|
||||
generator: false,
|
||||
async: false,
|
||||
directives: [],
|
||||
aliasingEffects: [],
|
||||
};
|
||||
|
||||
reversePostorderBlocks(fn.body);
|
||||
markInstructionIds(fn.body);
|
||||
enterSSA(fn);
|
||||
inferTypes(fn);
|
||||
|
||||
const fnInstr: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
value: {
|
||||
kind: 'FunctionExpression',
|
||||
name: null,
|
||||
nameHint: null,
|
||||
loweredFunc: {
|
||||
func: fn,
|
||||
},
|
||||
type: 'ArrowFunctionExpression',
|
||||
loc: GeneratedSource,
|
||||
},
|
||||
lvalue: createTemporaryPlace(env, GeneratedSource),
|
||||
effects: null,
|
||||
loc: GeneratedSource,
|
||||
};
|
||||
return fnInstr;
|
||||
}
|
||||
|
||||
function emitArrayInstr(elements: Array<Place>, env: Environment): Instruction {
|
||||
const array: ArrayExpression = {
|
||||
kind: 'ArrayExpression',
|
||||
elements,
|
||||
loc: GeneratedSource,
|
||||
};
|
||||
const arrayLvalue: Place = createTemporaryPlace(env, GeneratedSource);
|
||||
const arrayInstr: Instruction = {
|
||||
id: makeInstructionId(0),
|
||||
value: array,
|
||||
lvalue: arrayLvalue,
|
||||
effects: null,
|
||||
loc: GeneratedSource,
|
||||
};
|
||||
return arrayInstr;
|
||||
}
|
||||
@@ -8,4 +8,3 @@
|
||||
export {constantPropagation} from './ConstantPropagation';
|
||||
export {deadCodeElimination} from './DeadCodeElimination';
|
||||
export {pruneMaybeThrows} from './PruneMaybeThrows';
|
||||
export {inlineJsxTransform} from './InlineJsxTransform';
|
||||
|
||||
@@ -46,13 +46,13 @@ import {
|
||||
} from '../HIR/HIR';
|
||||
import {printIdentifier, printInstruction, printPlace} from '../HIR/PrintHIR';
|
||||
import {eachPatternOperand} from '../HIR/visitors';
|
||||
import {Err, Ok, Result} from '../Utils/Result';
|
||||
|
||||
import {GuardKind} from '../Utils/RuntimeDiagnosticConstants';
|
||||
import {assertExhaustive} from '../Utils/utils';
|
||||
import {buildReactiveFunction} from './BuildReactiveFunction';
|
||||
import {SINGLE_CHILD_FBT_TAGS} from './MemoizeFbtAndMacroOperandsInSameScope';
|
||||
import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
|
||||
import {EMIT_FREEZE_GLOBAL_GATING, ReactFunctionType} from '../HIR/Environment';
|
||||
import {ReactFunctionType} from '../HIR/Environment';
|
||||
import {ProgramContext} from '../Entrypoint';
|
||||
|
||||
export const MEMO_CACHE_SENTINEL = 'react.memo_cache_sentinel';
|
||||
@@ -100,17 +100,6 @@ export type CodegenFunction = {
|
||||
fn: CodegenFunction;
|
||||
type: ReactFunctionType | null;
|
||||
}>;
|
||||
|
||||
/**
|
||||
* This is true if the compiler has compiled inferred effect dependencies
|
||||
*/
|
||||
hasInferredEffect: boolean;
|
||||
inferredEffectLocations: Set<SourceLocation>;
|
||||
|
||||
/**
|
||||
* This is true if the compiler has compiled a fire to a useFire call
|
||||
*/
|
||||
hasFireRewrite: boolean;
|
||||
};
|
||||
|
||||
export function codegenFunction(
|
||||
@@ -122,7 +111,7 @@ export function codegenFunction(
|
||||
uniqueIdentifiers: Set<string>;
|
||||
fbtOperands: Set<IdentifierId>;
|
||||
},
|
||||
): Result<CodegenFunction, CompilerError> {
|
||||
): CodegenFunction {
|
||||
const cx = new Context(
|
||||
fn.env,
|
||||
fn.id ?? '[[ anonymous ]]',
|
||||
@@ -152,11 +141,7 @@ export function codegenFunction(
|
||||
};
|
||||
}
|
||||
|
||||
const compileResult = codegenReactiveFunction(cx, fn);
|
||||
if (compileResult.isErr()) {
|
||||
return compileResult;
|
||||
}
|
||||
const compiled = compileResult.unwrap();
|
||||
const compiled = codegenReactiveFunction(cx, fn);
|
||||
|
||||
const hookGuard = fn.env.config.enableEmitHookGuards;
|
||||
if (hookGuard != null && fn.env.outputMode === 'client') {
|
||||
@@ -284,7 +269,7 @@ export function codegenFunction(
|
||||
emitInstrumentForget.globalGating,
|
||||
);
|
||||
if (assertResult.isErr()) {
|
||||
return assertResult;
|
||||
fn.env.recordErrors(assertResult.unwrapErr());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -334,20 +319,17 @@ export function codegenFunction(
|
||||
),
|
||||
reactiveFunction,
|
||||
);
|
||||
if (codegen.isErr()) {
|
||||
return codegen;
|
||||
}
|
||||
outlined.push({fn: codegen.unwrap(), type});
|
||||
outlined.push({fn: codegen, type});
|
||||
}
|
||||
compiled.outlined = outlined;
|
||||
|
||||
return compileResult;
|
||||
return compiled;
|
||||
}
|
||||
|
||||
function codegenReactiveFunction(
|
||||
cx: Context,
|
||||
fn: ReactiveFunction,
|
||||
): Result<CodegenFunction, CompilerError> {
|
||||
): CodegenFunction {
|
||||
for (const param of fn.params) {
|
||||
const place = param.kind === 'Identifier' ? param : param.place;
|
||||
cx.temp.set(place.identifier.declarationId, null);
|
||||
@@ -366,13 +348,13 @@ function codegenReactiveFunction(
|
||||
}
|
||||
|
||||
if (cx.errors.hasAnyErrors()) {
|
||||
return Err(cx.errors);
|
||||
fn.env.recordErrors(cx.errors);
|
||||
}
|
||||
|
||||
const countMemoBlockVisitor = new CountMemoBlockVisitor(fn.env);
|
||||
visitReactiveFunction(fn, countMemoBlockVisitor, undefined);
|
||||
|
||||
return Ok({
|
||||
return {
|
||||
type: 'CodegenFunction',
|
||||
loc: fn.loc,
|
||||
id: fn.id !== null ? t.identifier(fn.id) : null,
|
||||
@@ -387,10 +369,7 @@ function codegenReactiveFunction(
|
||||
prunedMemoBlocks: countMemoBlockVisitor.prunedMemoBlocks,
|
||||
prunedMemoValues: countMemoBlockVisitor.prunedMemoValues,
|
||||
outlined: [],
|
||||
hasFireRewrite: fn.env.hasFireRewrite,
|
||||
hasInferredEffect: fn.env.hasInferredEffect,
|
||||
inferredEffectLocations: fn.env.inferredEffectLocations,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
class CountMemoBlockVisitor extends ReactiveFunctionVisitor<void> {
|
||||
@@ -574,30 +553,6 @@ function codegenBlockNoReset(
|
||||
return t.blockStatement(statements);
|
||||
}
|
||||
|
||||
function wrapCacheDep(cx: Context, value: t.Expression): t.Expression {
|
||||
if (
|
||||
cx.env.config.enableEmitFreeze != null &&
|
||||
cx.env.outputMode === 'client'
|
||||
) {
|
||||
const emitFreezeIdentifier = cx.env.programContext.addImportSpecifier(
|
||||
cx.env.config.enableEmitFreeze,
|
||||
).name;
|
||||
cx.env.programContext
|
||||
.assertGlobalBinding(EMIT_FREEZE_GLOBAL_GATING, cx.env.scope)
|
||||
.unwrap();
|
||||
return t.conditionalExpression(
|
||||
t.identifier(EMIT_FREEZE_GLOBAL_GATING),
|
||||
t.callExpression(t.identifier(emitFreezeIdentifier), [
|
||||
value,
|
||||
t.stringLiteral(cx.fnName),
|
||||
]),
|
||||
value,
|
||||
);
|
||||
} else {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function codegenReactiveScope(
|
||||
cx: Context,
|
||||
statements: Array<t.Statement>,
|
||||
@@ -612,12 +567,9 @@ function codegenReactiveScope(
|
||||
value: t.Expression;
|
||||
}> = [];
|
||||
const changeExpressions: Array<t.Expression> = [];
|
||||
const changeExpressionComments: Array<string> = [];
|
||||
const outputComments: Array<string> = [];
|
||||
|
||||
for (const dep of [...scope.dependencies].sort(compareScopeDependency)) {
|
||||
const index = cx.nextCacheIndex;
|
||||
changeExpressionComments.push(printDependencyComment(dep));
|
||||
const comparison = t.binaryExpression(
|
||||
'!==',
|
||||
t.memberExpression(
|
||||
@@ -627,18 +579,7 @@ function codegenReactiveScope(
|
||||
),
|
||||
codegenDependency(cx, dep),
|
||||
);
|
||||
|
||||
if (cx.env.config.enableChangeVariableCodegen) {
|
||||
const changeIdentifier = t.identifier(cx.synthesizeName(`c_${index}`));
|
||||
statements.push(
|
||||
t.variableDeclaration('const', [
|
||||
t.variableDeclarator(changeIdentifier, comparison),
|
||||
]),
|
||||
);
|
||||
changeExpressions.push(changeIdentifier);
|
||||
} else {
|
||||
changeExpressions.push(comparison);
|
||||
}
|
||||
changeExpressions.push(comparison);
|
||||
/*
|
||||
* Adding directly to cacheStoreStatements rather than cacheLoads, because there
|
||||
* is no corresponding cacheLoadStatement for dependencies
|
||||
@@ -676,13 +617,12 @@ function codegenReactiveScope(
|
||||
});
|
||||
|
||||
const name = convertIdentifier(identifier);
|
||||
outputComments.push(name.name);
|
||||
if (!cx.hasDeclared(identifier)) {
|
||||
statements.push(
|
||||
t.variableDeclaration('let', [createVariableDeclarator(name, null)]),
|
||||
);
|
||||
}
|
||||
cacheLoads.push({name, index, value: wrapCacheDep(cx, name)});
|
||||
cacheLoads.push({name, index, value: name});
|
||||
cx.declare(identifier);
|
||||
}
|
||||
for (const reassignment of scope.reassignments) {
|
||||
@@ -691,8 +631,7 @@ function codegenReactiveScope(
|
||||
firstOutputIndex = index;
|
||||
}
|
||||
const name = convertIdentifier(reassignment);
|
||||
outputComments.push(name.name);
|
||||
cacheLoads.push({name, index, value: wrapCacheDep(cx, name)});
|
||||
cacheLoads.push({name, index, value: name});
|
||||
}
|
||||
|
||||
let testCondition = (changeExpressions as Array<t.Expression>).reduce(
|
||||
@@ -724,187 +663,44 @@ function codegenReactiveScope(
|
||||
);
|
||||
}
|
||||
|
||||
if (cx.env.config.disableMemoizationForDebugging) {
|
||||
CompilerError.invariant(
|
||||
cx.env.config.enableChangeDetectionForDebugging == null,
|
||||
{
|
||||
reason: `Expected to not have both change detection enabled and memoization disabled`,
|
||||
description: `Incompatible config options`,
|
||||
loc: GeneratedSource,
|
||||
},
|
||||
);
|
||||
testCondition = t.logicalExpression(
|
||||
'||',
|
||||
testCondition,
|
||||
t.booleanLiteral(true),
|
||||
);
|
||||
}
|
||||
let computationBlock = codegenBlock(cx, block);
|
||||
|
||||
let memoStatement;
|
||||
const detectionFunction = cx.env.config.enableChangeDetectionForDebugging;
|
||||
if (detectionFunction != null && changeExpressions.length > 0) {
|
||||
const loc =
|
||||
typeof scope.loc === 'symbol'
|
||||
? 'unknown location'
|
||||
: `(${scope.loc.start.line}:${scope.loc.end.line})`;
|
||||
const importedDetectionFunctionIdentifier =
|
||||
cx.env.programContext.addImportSpecifier(detectionFunction).name;
|
||||
const cacheLoadOldValueStatements: Array<t.Statement> = [];
|
||||
const changeDetectionStatements: Array<t.Statement> = [];
|
||||
const idempotenceDetectionStatements: Array<t.Statement> = [];
|
||||
|
||||
for (const {name, index, value} of cacheLoads) {
|
||||
const loadName = cx.synthesizeName(`old$${name.name}`);
|
||||
const slot = t.memberExpression(
|
||||
t.identifier(cx.synthesizeName('$')),
|
||||
t.numericLiteral(index),
|
||||
true,
|
||||
);
|
||||
cacheStoreStatements.push(
|
||||
t.expressionStatement(t.assignmentExpression('=', slot, value)),
|
||||
);
|
||||
cacheLoadOldValueStatements.push(
|
||||
t.variableDeclaration('let', [
|
||||
t.variableDeclarator(t.identifier(loadName), slot),
|
||||
]),
|
||||
);
|
||||
changeDetectionStatements.push(
|
||||
t.expressionStatement(
|
||||
t.callExpression(t.identifier(importedDetectionFunctionIdentifier), [
|
||||
t.identifier(loadName),
|
||||
t.cloneNode(name, true),
|
||||
t.stringLiteral(name.name),
|
||||
t.stringLiteral(cx.fnName),
|
||||
t.stringLiteral('cached'),
|
||||
t.stringLiteral(loc),
|
||||
]),
|
||||
for (const {name, index, value} of cacheLoads) {
|
||||
cacheStoreStatements.push(
|
||||
t.expressionStatement(
|
||||
t.assignmentExpression(
|
||||
'=',
|
||||
t.memberExpression(
|
||||
t.identifier(cx.synthesizeName('$')),
|
||||
t.numericLiteral(index),
|
||||
true,
|
||||
),
|
||||
value,
|
||||
),
|
||||
);
|
||||
idempotenceDetectionStatements.push(
|
||||
t.expressionStatement(
|
||||
t.callExpression(t.identifier(importedDetectionFunctionIdentifier), [
|
||||
t.cloneNode(slot, true),
|
||||
t.cloneNode(name, true),
|
||||
t.stringLiteral(name.name),
|
||||
t.stringLiteral(cx.fnName),
|
||||
t.stringLiteral('recomputed'),
|
||||
t.stringLiteral(loc),
|
||||
]),
|
||||
),
|
||||
);
|
||||
idempotenceDetectionStatements.push(
|
||||
t.expressionStatement(t.assignmentExpression('=', name, slot)),
|
||||
);
|
||||
}
|
||||
const condition = cx.synthesizeName('condition');
|
||||
const recomputationBlock = t.cloneNode(computationBlock, true);
|
||||
memoStatement = t.blockStatement([
|
||||
...computationBlock.body,
|
||||
t.variableDeclaration('let', [
|
||||
t.variableDeclarator(t.identifier(condition), testCondition),
|
||||
]),
|
||||
t.ifStatement(
|
||||
t.unaryExpression('!', t.identifier(condition)),
|
||||
t.blockStatement([
|
||||
...cacheLoadOldValueStatements,
|
||||
...changeDetectionStatements,
|
||||
]),
|
||||
),
|
||||
...cacheStoreStatements,
|
||||
t.ifStatement(
|
||||
t.identifier(condition),
|
||||
t.blockStatement([
|
||||
...recomputationBlock.body,
|
||||
...idempotenceDetectionStatements,
|
||||
]),
|
||||
),
|
||||
]);
|
||||
} else {
|
||||
for (const {name, index, value} of cacheLoads) {
|
||||
cacheStoreStatements.push(
|
||||
t.expressionStatement(
|
||||
t.assignmentExpression(
|
||||
'=',
|
||||
t.memberExpression(
|
||||
t.identifier(cx.synthesizeName('$')),
|
||||
t.numericLiteral(index),
|
||||
true,
|
||||
),
|
||||
value,
|
||||
);
|
||||
cacheLoadStatements.push(
|
||||
t.expressionStatement(
|
||||
t.assignmentExpression(
|
||||
'=',
|
||||
name,
|
||||
t.memberExpression(
|
||||
t.identifier(cx.synthesizeName('$')),
|
||||
t.numericLiteral(index),
|
||||
true,
|
||||
),
|
||||
),
|
||||
);
|
||||
cacheLoadStatements.push(
|
||||
t.expressionStatement(
|
||||
t.assignmentExpression(
|
||||
'=',
|
||||
name,
|
||||
t.memberExpression(
|
||||
t.identifier(cx.synthesizeName('$')),
|
||||
t.numericLiteral(index),
|
||||
true,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
computationBlock.body.push(...cacheStoreStatements);
|
||||
memoStatement = t.ifStatement(
|
||||
testCondition,
|
||||
computationBlock,
|
||||
t.blockStatement(cacheLoadStatements),
|
||||
),
|
||||
);
|
||||
}
|
||||
computationBlock.body.push(...cacheStoreStatements);
|
||||
memoStatement = t.ifStatement(
|
||||
testCondition,
|
||||
computationBlock,
|
||||
t.blockStatement(cacheLoadStatements),
|
||||
);
|
||||
|
||||
if (cx.env.config.enableMemoizationComments) {
|
||||
if (changeExpressionComments.length) {
|
||||
t.addComment(
|
||||
memoStatement,
|
||||
'leading',
|
||||
` check if ${printDelimitedCommentList(
|
||||
changeExpressionComments,
|
||||
'or',
|
||||
)} changed`,
|
||||
true,
|
||||
);
|
||||
t.addComment(
|
||||
memoStatement,
|
||||
'leading',
|
||||
` "useMemo" for ${printDelimitedCommentList(outputComments, 'and')}:`,
|
||||
true,
|
||||
);
|
||||
} else {
|
||||
t.addComment(
|
||||
memoStatement,
|
||||
'leading',
|
||||
' cache value with no dependencies',
|
||||
true,
|
||||
);
|
||||
t.addComment(
|
||||
memoStatement,
|
||||
'leading',
|
||||
` "useMemo" for ${printDelimitedCommentList(outputComments, 'and')}:`,
|
||||
true,
|
||||
);
|
||||
}
|
||||
if (computationBlock.body.length > 0) {
|
||||
t.addComment(
|
||||
computationBlock.body[0]!,
|
||||
'leading',
|
||||
` Inputs changed, recompute`,
|
||||
true,
|
||||
);
|
||||
}
|
||||
if (cacheLoadStatements.length > 0) {
|
||||
t.addComment(
|
||||
cacheLoadStatements[0]!,
|
||||
'leading',
|
||||
` Inputs did not change, use cached value`,
|
||||
true,
|
||||
);
|
||||
}
|
||||
}
|
||||
statements.push(memoStatement);
|
||||
|
||||
const earlyReturnValue = scope.earlyReturnValue;
|
||||
@@ -1431,41 +1227,6 @@ function codegenForInit(
|
||||
}
|
||||
}
|
||||
|
||||
function printDependencyComment(dependency: ReactiveScopeDependency): string {
|
||||
const identifier = convertIdentifier(dependency.identifier);
|
||||
let name = identifier.name;
|
||||
if (dependency.path !== null) {
|
||||
for (const path of dependency.path) {
|
||||
name += `.${path.property}`;
|
||||
}
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
function printDelimitedCommentList(
|
||||
items: Array<string>,
|
||||
finalCompletion: string,
|
||||
): string {
|
||||
if (items.length === 2) {
|
||||
return items.join(` ${finalCompletion} `);
|
||||
} else if (items.length <= 1) {
|
||||
return items.join('');
|
||||
}
|
||||
|
||||
let output = [];
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i]!;
|
||||
if (i < items.length - 2) {
|
||||
output.push(`${item}, `);
|
||||
} else if (i === items.length - 2) {
|
||||
output.push(`${item}, ${finalCompletion} `);
|
||||
} else {
|
||||
output.push(item);
|
||||
}
|
||||
}
|
||||
return output.join('');
|
||||
}
|
||||
|
||||
function codegenDependency(
|
||||
cx: Context,
|
||||
dependency: ReactiveScopeDependency,
|
||||
@@ -1897,7 +1658,7 @@ function codegenInstructionValue(
|
||||
cx.temp,
|
||||
),
|
||||
reactiveFunction,
|
||||
).unwrap();
|
||||
);
|
||||
|
||||
/*
|
||||
* ObjectMethod builder must be backwards compatible with older versions of babel.
|
||||
@@ -2096,7 +1857,7 @@ function codegenInstructionValue(
|
||||
cx.temp,
|
||||
),
|
||||
reactiveFunction,
|
||||
).unwrap();
|
||||
);
|
||||
|
||||
if (instrValue.type === 'ArrowFunctionExpression') {
|
||||
let body: t.BlockStatement | t.Expression = fn.body;
|
||||
|
||||
@@ -470,6 +470,7 @@ function canMergeScopes(
|
||||
identifier: declaration.identifier,
|
||||
reactive: true,
|
||||
path: [],
|
||||
loc: GeneratedSource,
|
||||
})),
|
||||
),
|
||||
next.scope.dependencies,
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
printIdentifier,
|
||||
printInstructionValue,
|
||||
printPlace,
|
||||
printSourceLocation,
|
||||
printType,
|
||||
} from '../HIR/PrintHIR';
|
||||
import {assertExhaustive} from '../Utils/utils';
|
||||
@@ -114,7 +115,7 @@ export function printDependency(dependency: ReactiveScopeDependency): string {
|
||||
const identifier =
|
||||
printIdentifier(dependency.identifier) +
|
||||
printType(dependency.identifier.type);
|
||||
return `${identifier}${dependency.path.map(token => `${token.optional ? '?.' : '.'}${token.property}`).join('')}`;
|
||||
return `${identifier}${dependency.path.map(token => `${token.optional ? '?.' : '.'}${token.property}`).join('')}_${printSourceLocation(dependency.loc)}`;
|
||||
}
|
||||
|
||||
export function printReactiveInstructions(
|
||||
|
||||
@@ -1,294 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {CompilerError} from '../CompilerError';
|
||||
import {
|
||||
Environment,
|
||||
Identifier,
|
||||
IdentifierId,
|
||||
InstructionId,
|
||||
Place,
|
||||
PropertyLiteral,
|
||||
ReactiveBlock,
|
||||
ReactiveFunction,
|
||||
ReactiveInstruction,
|
||||
ReactiveScopeBlock,
|
||||
ReactiveTerminalStatement,
|
||||
getHookKind,
|
||||
isUseRefType,
|
||||
isUseStateType,
|
||||
} from '../HIR';
|
||||
import {eachCallArgument, eachInstructionLValue} from '../HIR/visitors';
|
||||
import DisjointSet from '../Utils/DisjointSet';
|
||||
import {assertExhaustive} from '../Utils/utils';
|
||||
import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
|
||||
|
||||
/**
|
||||
* This pass is built based on the observation by @jbrown215 that arguments
|
||||
* to useState and useRef are only used the first time a component is rendered.
|
||||
* Any subsequent times, the arguments will be evaluated but ignored. In this pass,
|
||||
* we use this fact to improve the output of the compiler by not recomputing values that
|
||||
* are only used as arguments (or inputs to arguments to) useState and useRef.
|
||||
*
|
||||
* This pass isn't yet stress-tested so it's not enabled by default. It's only enabled
|
||||
* to support certain debug modes that detect non-idempotent code, since non-idempotent
|
||||
* code can "safely" be used if its only passed to useState and useRef. We plan to rewrite
|
||||
* this pass in HIR and enable it as an optimization in the future.
|
||||
*
|
||||
* Algorithm:
|
||||
* We take two passes over the reactive function AST. In the first pass, we gather
|
||||
* aliases and build relationships between property accesses--the key thing we need
|
||||
* to do here is to find that, e.g., $0.x and $1 refer to the same value if
|
||||
* $1 = PropertyLoad $0.x.
|
||||
*
|
||||
* In the second pass, we traverse the AST in reverse order and track how each place
|
||||
* is used. If a place is read from in any Terminal, we mark the place as "Update", meaning
|
||||
* it is used whenever the component is updated/re-rendered. If a place is read from in
|
||||
* a useState or useRef hook call, we mark it as "Create", since it is only used when the
|
||||
* component is created. In other instructions, we propagate the inferred place for the
|
||||
* instructions lvalues onto any other instructions that are read.
|
||||
*
|
||||
* Whenever we finish this reverse pass over a reactive block, we can look at the blocks
|
||||
* dependencies and see whether the dependencies are used in an "Update" context or only
|
||||
* in a "Create" context. If a dependency is create-only, then we can remove that dependency
|
||||
* from the block.
|
||||
*/
|
||||
|
||||
type CreateUpdate = 'Create' | 'Update' | 'Unknown';
|
||||
|
||||
type KindMap = Map<IdentifierId, CreateUpdate>;
|
||||
|
||||
class Visitor extends ReactiveFunctionVisitor<CreateUpdate> {
|
||||
map: KindMap = new Map();
|
||||
aliases: DisjointSet<IdentifierId>;
|
||||
paths: Map<IdentifierId, Map<PropertyLiteral, IdentifierId>>;
|
||||
env: Environment;
|
||||
|
||||
constructor(
|
||||
env: Environment,
|
||||
aliases: DisjointSet<IdentifierId>,
|
||||
paths: Map<IdentifierId, Map<PropertyLiteral, IdentifierId>>,
|
||||
) {
|
||||
super();
|
||||
this.aliases = aliases;
|
||||
this.paths = paths;
|
||||
this.env = env;
|
||||
}
|
||||
|
||||
join(values: Array<CreateUpdate>): CreateUpdate {
|
||||
function join2(l: CreateUpdate, r: CreateUpdate): CreateUpdate {
|
||||
if (l === 'Update' || r === 'Update') {
|
||||
return 'Update';
|
||||
} else if (l === 'Create' || r === 'Create') {
|
||||
return 'Create';
|
||||
} else if (l === 'Unknown' || r === 'Unknown') {
|
||||
return 'Unknown';
|
||||
}
|
||||
assertExhaustive(r, `Unhandled variable kind ${r}`);
|
||||
}
|
||||
return values.reduce(join2, 'Unknown');
|
||||
}
|
||||
|
||||
isCreateOnlyHook(id: Identifier): boolean {
|
||||
return isUseStateType(id) || isUseRefType(id);
|
||||
}
|
||||
|
||||
override visitPlace(
|
||||
_: InstructionId,
|
||||
place: Place,
|
||||
state: CreateUpdate,
|
||||
): void {
|
||||
this.map.set(
|
||||
place.identifier.id,
|
||||
this.join([state, this.map.get(place.identifier.id) ?? 'Unknown']),
|
||||
);
|
||||
}
|
||||
|
||||
override visitBlock(block: ReactiveBlock, state: CreateUpdate): void {
|
||||
super.visitBlock([...block].reverse(), state);
|
||||
}
|
||||
|
||||
override visitInstruction(instruction: ReactiveInstruction): void {
|
||||
const state = this.join(
|
||||
[...eachInstructionLValue(instruction)].map(
|
||||
operand => this.map.get(operand.identifier.id) ?? 'Unknown',
|
||||
),
|
||||
);
|
||||
|
||||
const visitCallOrMethodNonArgs = (): void => {
|
||||
switch (instruction.value.kind) {
|
||||
case 'CallExpression': {
|
||||
this.visitPlace(instruction.id, instruction.value.callee, state);
|
||||
break;
|
||||
}
|
||||
case 'MethodCall': {
|
||||
this.visitPlace(instruction.id, instruction.value.property, state);
|
||||
this.visitPlace(instruction.id, instruction.value.receiver, state);
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const isHook = (): boolean => {
|
||||
let callee = null;
|
||||
switch (instruction.value.kind) {
|
||||
case 'CallExpression': {
|
||||
callee = instruction.value.callee.identifier;
|
||||
break;
|
||||
}
|
||||
case 'MethodCall': {
|
||||
callee = instruction.value.property.identifier;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return callee != null && getHookKind(this.env, callee) != null;
|
||||
};
|
||||
|
||||
switch (instruction.value.kind) {
|
||||
case 'CallExpression':
|
||||
case 'MethodCall': {
|
||||
if (
|
||||
instruction.lvalue &&
|
||||
this.isCreateOnlyHook(instruction.lvalue.identifier)
|
||||
) {
|
||||
[...eachCallArgument(instruction.value.args)].forEach(operand =>
|
||||
this.visitPlace(instruction.id, operand, 'Create'),
|
||||
);
|
||||
visitCallOrMethodNonArgs();
|
||||
} else {
|
||||
this.traverseInstruction(instruction, isHook() ? 'Update' : state);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
this.traverseInstruction(instruction, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override visitScope(scope: ReactiveScopeBlock): void {
|
||||
const state = this.join(
|
||||
[
|
||||
...scope.scope.declarations.keys(),
|
||||
...[...scope.scope.reassignments.values()].map(ident => ident.id),
|
||||
].map(id => this.map.get(id) ?? 'Unknown'),
|
||||
);
|
||||
super.visitScope(scope, state);
|
||||
[...scope.scope.dependencies].forEach(ident => {
|
||||
let target: undefined | IdentifierId =
|
||||
this.aliases.find(ident.identifier.id) ?? ident.identifier.id;
|
||||
ident.path.forEach(token => {
|
||||
target &&= this.paths.get(target)?.get(token.property);
|
||||
});
|
||||
if (target && this.map.get(target) === 'Create') {
|
||||
scope.scope.dependencies.delete(ident);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
override visitTerminal(
|
||||
stmt: ReactiveTerminalStatement,
|
||||
state: CreateUpdate,
|
||||
): void {
|
||||
CompilerError.invariant(state !== 'Create', {
|
||||
reason: "Visiting a terminal statement with state 'Create'",
|
||||
loc: stmt.terminal.loc,
|
||||
});
|
||||
super.visitTerminal(stmt, state);
|
||||
}
|
||||
|
||||
override visitReactiveFunctionValue(
|
||||
_id: InstructionId,
|
||||
_dependencies: Array<Place>,
|
||||
fn: ReactiveFunction,
|
||||
state: CreateUpdate,
|
||||
): void {
|
||||
visitReactiveFunction(fn, this, state);
|
||||
}
|
||||
}
|
||||
|
||||
export default function pruneInitializationDependencies(
|
||||
fn: ReactiveFunction,
|
||||
): void {
|
||||
const [aliases, paths] = getAliases(fn);
|
||||
visitReactiveFunction(fn, new Visitor(fn.env, aliases, paths), 'Update');
|
||||
}
|
||||
|
||||
function update(
|
||||
map: Map<IdentifierId, Map<PropertyLiteral, IdentifierId>>,
|
||||
key: IdentifierId,
|
||||
path: PropertyLiteral,
|
||||
value: IdentifierId,
|
||||
): void {
|
||||
const inner = map.get(key) ?? new Map();
|
||||
inner.set(path, value);
|
||||
map.set(key, inner);
|
||||
}
|
||||
|
||||
class AliasVisitor extends ReactiveFunctionVisitor {
|
||||
scopeIdentifiers: DisjointSet<IdentifierId> = new DisjointSet<IdentifierId>();
|
||||
scopePaths: Map<IdentifierId, Map<PropertyLiteral, IdentifierId>> = new Map();
|
||||
|
||||
override visitInstruction(instr: ReactiveInstruction): void {
|
||||
if (
|
||||
instr.value.kind === 'StoreLocal' ||
|
||||
instr.value.kind === 'StoreContext'
|
||||
) {
|
||||
this.scopeIdentifiers.union([
|
||||
instr.value.lvalue.place.identifier.id,
|
||||
instr.value.value.identifier.id,
|
||||
]);
|
||||
} else if (
|
||||
instr.value.kind === 'LoadLocal' ||
|
||||
instr.value.kind === 'LoadContext'
|
||||
) {
|
||||
instr.lvalue &&
|
||||
this.scopeIdentifiers.union([
|
||||
instr.lvalue.identifier.id,
|
||||
instr.value.place.identifier.id,
|
||||
]);
|
||||
} else if (instr.value.kind === 'PropertyLoad') {
|
||||
instr.lvalue &&
|
||||
update(
|
||||
this.scopePaths,
|
||||
instr.value.object.identifier.id,
|
||||
instr.value.property,
|
||||
instr.lvalue.identifier.id,
|
||||
);
|
||||
} else if (instr.value.kind === 'PropertyStore') {
|
||||
update(
|
||||
this.scopePaths,
|
||||
instr.value.object.identifier.id,
|
||||
instr.value.property,
|
||||
instr.value.value.identifier.id,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getAliases(
|
||||
fn: ReactiveFunction,
|
||||
): [
|
||||
DisjointSet<IdentifierId>,
|
||||
Map<IdentifierId, Map<PropertyLiteral, IdentifierId>>,
|
||||
] {
|
||||
const visitor = new AliasVisitor();
|
||||
visitReactiveFunction(fn, visitor, null);
|
||||
let disjoint = visitor.scopeIdentifiers;
|
||||
let scopePaths = new Map<IdentifierId, Map<PropertyLiteral, IdentifierId>>();
|
||||
for (const [key, value] of visitor.scopePaths) {
|
||||
for (const [path, id] of value) {
|
||||
update(
|
||||
scopePaths,
|
||||
disjoint.find(key) ?? key,
|
||||
path,
|
||||
disjoint.find(id) ?? id,
|
||||
);
|
||||
}
|
||||
}
|
||||
return [disjoint, scopePaths];
|
||||
}
|
||||
@@ -1,739 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {CompilerError, CompilerErrorDetailOptions, SourceLocation} from '..';
|
||||
import {
|
||||
ArrayExpression,
|
||||
CallExpression,
|
||||
Effect,
|
||||
Environment,
|
||||
FunctionExpression,
|
||||
GeneratedSource,
|
||||
HIRFunction,
|
||||
Identifier,
|
||||
IdentifierId,
|
||||
Instruction,
|
||||
InstructionId,
|
||||
InstructionKind,
|
||||
InstructionValue,
|
||||
isUseEffectHookType,
|
||||
LoadLocal,
|
||||
makeInstructionId,
|
||||
NonLocalImportSpecifier,
|
||||
Place,
|
||||
promoteTemporary,
|
||||
} from '../HIR';
|
||||
import {createTemporaryPlace, markInstructionIds} from '../HIR/HIRBuilder';
|
||||
import {getOrInsertWith} from '../Utils/utils';
|
||||
import {
|
||||
BuiltInFireFunctionId,
|
||||
BuiltInFireId,
|
||||
DefaultNonmutatingHook,
|
||||
} from '../HIR/ObjectShape';
|
||||
import {eachInstructionOperand} from '../HIR/visitors';
|
||||
import {printSourceLocationLine} from '../HIR/PrintHIR';
|
||||
import {USE_FIRE_FUNCTION_NAME} from '../HIR/Environment';
|
||||
import {ErrorCategory} from '../CompilerError';
|
||||
|
||||
/*
|
||||
* TODO(jmbrown):
|
||||
* - traverse object methods
|
||||
* - method calls
|
||||
* - React.useEffect calls
|
||||
*/
|
||||
|
||||
const CANNOT_COMPILE_FIRE = 'Cannot compile `fire`';
|
||||
|
||||
export function transformFire(fn: HIRFunction): void {
|
||||
const context = new Context(fn.env);
|
||||
replaceFireFunctions(fn, context);
|
||||
if (!context.hasErrors()) {
|
||||
ensureNoMoreFireUses(fn, context);
|
||||
}
|
||||
context.throwIfErrorsFound();
|
||||
}
|
||||
|
||||
function replaceFireFunctions(fn: HIRFunction, context: Context): void {
|
||||
let importedUseFire: NonLocalImportSpecifier | null = null;
|
||||
let hasRewrite = false;
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
const rewriteInstrs = new Map<InstructionId, Array<Instruction>>();
|
||||
const deleteInstrs = new Set<InstructionId>();
|
||||
for (const instr of block.instructions) {
|
||||
const {value, lvalue} = instr;
|
||||
if (
|
||||
value.kind === 'CallExpression' &&
|
||||
isUseEffectHookType(value.callee.identifier) &&
|
||||
value.args.length > 0 &&
|
||||
value.args[0].kind === 'Identifier'
|
||||
) {
|
||||
const lambda = context.getFunctionExpression(
|
||||
value.args[0].identifier.id,
|
||||
);
|
||||
if (lambda != null) {
|
||||
const capturedCallees =
|
||||
visitFunctionExpressionAndPropagateFireDependencies(
|
||||
lambda,
|
||||
context,
|
||||
true,
|
||||
);
|
||||
|
||||
// Add useFire calls for all fire calls in found in the lambda
|
||||
const newInstrs = [];
|
||||
for (const [
|
||||
fireCalleePlace,
|
||||
fireCalleeInfo,
|
||||
] of capturedCallees.entries()) {
|
||||
if (!context.hasCalleeWithInsertedFire(fireCalleePlace)) {
|
||||
context.addCalleeWithInsertedFire(fireCalleePlace);
|
||||
|
||||
importedUseFire ??= fn.env.programContext.addImportSpecifier({
|
||||
source: fn.env.programContext.reactRuntimeModule,
|
||||
importSpecifierName: USE_FIRE_FUNCTION_NAME,
|
||||
});
|
||||
const loadUseFireInstr = makeLoadUseFireInstruction(
|
||||
fn.env,
|
||||
importedUseFire,
|
||||
);
|
||||
const loadFireCalleeInstr = makeLoadFireCalleeInstruction(
|
||||
fn.env,
|
||||
fireCalleeInfo.capturedCalleeIdentifier,
|
||||
);
|
||||
const callUseFireInstr = makeCallUseFireInstruction(
|
||||
fn.env,
|
||||
loadUseFireInstr.lvalue,
|
||||
loadFireCalleeInstr.lvalue,
|
||||
);
|
||||
const storeUseFireInstr = makeStoreUseFireInstruction(
|
||||
fn.env,
|
||||
callUseFireInstr.lvalue,
|
||||
fireCalleeInfo.fireFunctionBinding,
|
||||
);
|
||||
newInstrs.push(
|
||||
loadUseFireInstr,
|
||||
loadFireCalleeInstr,
|
||||
callUseFireInstr,
|
||||
storeUseFireInstr,
|
||||
);
|
||||
|
||||
// We insert all of these instructions before the useEffect is loaded
|
||||
const loadUseEffectInstrId = context.getLoadGlobalInstrId(
|
||||
value.callee.identifier.id,
|
||||
);
|
||||
if (loadUseEffectInstrId == null) {
|
||||
context.pushError({
|
||||
loc: value.loc,
|
||||
description: null,
|
||||
category: ErrorCategory.Invariant,
|
||||
reason: '[InsertFire] No LoadGlobal found for useEffect call',
|
||||
suggestions: null,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
rewriteInstrs.set(loadUseEffectInstrId, newInstrs);
|
||||
}
|
||||
}
|
||||
ensureNoRemainingCalleeCaptures(
|
||||
lambda.loweredFunc.func,
|
||||
context,
|
||||
capturedCallees,
|
||||
);
|
||||
|
||||
if (
|
||||
value.args.length > 1 &&
|
||||
value.args[1] != null &&
|
||||
value.args[1].kind === 'Identifier'
|
||||
) {
|
||||
const depArray = value.args[1];
|
||||
const depArrayExpression = context.getArrayExpression(
|
||||
depArray.identifier.id,
|
||||
);
|
||||
if (depArrayExpression != null) {
|
||||
for (const dependency of depArrayExpression.elements) {
|
||||
if (dependency.kind === 'Identifier') {
|
||||
const loadOfDependency = context.getLoadLocalInstr(
|
||||
dependency.identifier.id,
|
||||
);
|
||||
if (loadOfDependency != null) {
|
||||
const replacedDepArrayItem = capturedCallees.get(
|
||||
loadOfDependency.place.identifier.id,
|
||||
);
|
||||
if (replacedDepArrayItem != null) {
|
||||
loadOfDependency.place =
|
||||
replacedDepArrayItem.fireFunctionBinding;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
context.pushError({
|
||||
loc: value.args[1].loc,
|
||||
description:
|
||||
'You must use an array literal for an effect dependency array when that effect uses `fire()`',
|
||||
category: ErrorCategory.Fire,
|
||||
reason: CANNOT_COMPILE_FIRE,
|
||||
suggestions: null,
|
||||
});
|
||||
}
|
||||
} else if (value.args.length > 1 && value.args[1].kind === 'Spread') {
|
||||
context.pushError({
|
||||
loc: value.args[1].place.loc,
|
||||
description:
|
||||
'You must use an array literal for an effect dependency array when that effect uses `fire()`',
|
||||
category: ErrorCategory.Fire,
|
||||
reason: CANNOT_COMPILE_FIRE,
|
||||
suggestions: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (
|
||||
value.kind === 'CallExpression' &&
|
||||
value.callee.identifier.type.kind === 'Function' &&
|
||||
value.callee.identifier.type.shapeId === BuiltInFireId &&
|
||||
context.inUseEffectLambda()
|
||||
) {
|
||||
/*
|
||||
* We found a fire(callExpr()) call. We remove the `fire()` call and replace the callExpr()
|
||||
* with a freshly generated fire function binding. We'll insert the useFire call before the
|
||||
* useEffect call, which happens in the CallExpression (useEffect) case above.
|
||||
*/
|
||||
|
||||
/*
|
||||
* We only allow fire to be called with a CallExpression: `fire(f())`
|
||||
* TODO: add support for method calls: `fire(this.method())`
|
||||
*/
|
||||
if (value.args.length === 1 && value.args[0].kind === 'Identifier') {
|
||||
const callExpr = context.getCallExpression(
|
||||
value.args[0].identifier.id,
|
||||
);
|
||||
|
||||
if (callExpr != null) {
|
||||
const calleeId = callExpr.callee.identifier.id;
|
||||
const loadLocal = context.getLoadLocalInstr(calleeId);
|
||||
if (loadLocal == null) {
|
||||
context.pushError({
|
||||
loc: value.loc,
|
||||
description: null,
|
||||
category: ErrorCategory.Invariant,
|
||||
reason:
|
||||
'[InsertFire] No loadLocal found for fire call argument',
|
||||
suggestions: null,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
const fireFunctionBinding =
|
||||
context.getOrGenerateFireFunctionBinding(
|
||||
loadLocal.place,
|
||||
value.loc,
|
||||
);
|
||||
|
||||
loadLocal.place = {...fireFunctionBinding};
|
||||
|
||||
// Delete the fire call expression
|
||||
deleteInstrs.add(instr.id);
|
||||
} else {
|
||||
context.pushError({
|
||||
loc: value.loc,
|
||||
description:
|
||||
'`fire()` can only receive a function call such as `fire(fn(a,b)). Method calls and other expressions are not allowed',
|
||||
category: ErrorCategory.Fire,
|
||||
reason: CANNOT_COMPILE_FIRE,
|
||||
suggestions: null,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
let description: string =
|
||||
'fire() can only take in a single call expression as an argument';
|
||||
if (value.args.length === 0) {
|
||||
description += ' but received none';
|
||||
} else if (value.args.length > 1) {
|
||||
description += ' but received multiple arguments';
|
||||
} else if (value.args[0].kind === 'Spread') {
|
||||
description += ' but received a spread argument';
|
||||
}
|
||||
context.pushError({
|
||||
loc: value.loc,
|
||||
description,
|
||||
category: ErrorCategory.Fire,
|
||||
reason: CANNOT_COMPILE_FIRE,
|
||||
suggestions: null,
|
||||
});
|
||||
}
|
||||
} else if (value.kind === 'CallExpression') {
|
||||
context.addCallExpression(lvalue.identifier.id, value);
|
||||
} else if (
|
||||
value.kind === 'FunctionExpression' &&
|
||||
context.inUseEffectLambda()
|
||||
) {
|
||||
visitFunctionExpressionAndPropagateFireDependencies(
|
||||
value,
|
||||
context,
|
||||
false,
|
||||
);
|
||||
} else if (value.kind === 'FunctionExpression') {
|
||||
context.addFunctionExpression(lvalue.identifier.id, value);
|
||||
} else if (value.kind === 'LoadLocal') {
|
||||
context.addLoadLocalInstr(lvalue.identifier.id, value);
|
||||
} else if (
|
||||
value.kind === 'LoadGlobal' &&
|
||||
value.binding.kind === 'ImportSpecifier' &&
|
||||
value.binding.module === 'react' &&
|
||||
value.binding.imported === 'fire' &&
|
||||
context.inUseEffectLambda()
|
||||
) {
|
||||
deleteInstrs.add(instr.id);
|
||||
} else if (value.kind === 'LoadGlobal') {
|
||||
context.addLoadGlobalInstrId(lvalue.identifier.id, instr.id);
|
||||
} else if (value.kind === 'ArrayExpression') {
|
||||
context.addArrayExpression(lvalue.identifier.id, value);
|
||||
}
|
||||
}
|
||||
block.instructions = rewriteInstructions(rewriteInstrs, block.instructions);
|
||||
block.instructions = deleteInstructions(deleteInstrs, block.instructions);
|
||||
|
||||
if (rewriteInstrs.size > 0 || deleteInstrs.size > 0) {
|
||||
hasRewrite = true;
|
||||
fn.env.hasFireRewrite = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (hasRewrite) {
|
||||
markInstructionIds(fn.body);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Traverses a function expression to find fire calls fire(foo()) and replaces them with
|
||||
* fireFoo().
|
||||
*
|
||||
* When a function captures a fire call we need to update its context to reflect the newly created
|
||||
* fire function bindings and update the LoadLocals referenced by the function's dependencies.
|
||||
*
|
||||
* @param isUseEffect is necessary so we can keep track of when we should additionally insert
|
||||
* useFire hooks calls.
|
||||
*/
|
||||
function visitFunctionExpressionAndPropagateFireDependencies(
|
||||
fnExpr: FunctionExpression,
|
||||
context: Context,
|
||||
enteringUseEffect: boolean,
|
||||
): FireCalleesToFireFunctionBinding {
|
||||
let withScope = enteringUseEffect
|
||||
? context.withUseEffectLambdaScope.bind(context)
|
||||
: context.withFunctionScope.bind(context);
|
||||
|
||||
const calleesCapturedByFnExpression = withScope(() =>
|
||||
replaceFireFunctions(fnExpr.loweredFunc.func, context),
|
||||
);
|
||||
|
||||
// For each replaced callee, update the context of the function expression to track it
|
||||
for (
|
||||
let contextIdx = 0;
|
||||
contextIdx < fnExpr.loweredFunc.func.context.length;
|
||||
contextIdx++
|
||||
) {
|
||||
const contextItem = fnExpr.loweredFunc.func.context[contextIdx];
|
||||
const replacedCallee = calleesCapturedByFnExpression.get(
|
||||
contextItem.identifier.id,
|
||||
);
|
||||
if (replacedCallee != null) {
|
||||
fnExpr.loweredFunc.func.context[contextIdx] = {
|
||||
...replacedCallee.fireFunctionBinding,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
context.mergeCalleesFromInnerScope(calleesCapturedByFnExpression);
|
||||
|
||||
return calleesCapturedByFnExpression;
|
||||
}
|
||||
|
||||
/*
|
||||
* eachInstructionOperand is not sufficient for our cases because:
|
||||
* 1. fire is a global, which will not appear
|
||||
* 2. The HIR may be malformed, so can't rely on function deps and must
|
||||
* traverse the whole function.
|
||||
*/
|
||||
function* eachReachablePlace(fn: HIRFunction): Iterable<Place> {
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
for (const instr of block.instructions) {
|
||||
if (
|
||||
instr.value.kind === 'FunctionExpression' ||
|
||||
instr.value.kind === 'ObjectMethod'
|
||||
) {
|
||||
yield* eachReachablePlace(instr.value.loweredFunc.func);
|
||||
} else {
|
||||
yield* eachInstructionOperand(instr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function ensureNoRemainingCalleeCaptures(
|
||||
fn: HIRFunction,
|
||||
context: Context,
|
||||
capturedCallees: FireCalleesToFireFunctionBinding,
|
||||
): void {
|
||||
for (const place of eachReachablePlace(fn)) {
|
||||
const calleeInfo = capturedCallees.get(place.identifier.id);
|
||||
if (calleeInfo != null) {
|
||||
const calleeName =
|
||||
calleeInfo.capturedCalleeIdentifier.name?.kind === 'named'
|
||||
? calleeInfo.capturedCalleeIdentifier.name.value
|
||||
: '<unknown>';
|
||||
context.pushError({
|
||||
loc: place.loc,
|
||||
description: `All uses of ${calleeName} must be either used with a fire() call in \
|
||||
this effect or not used with a fire() call at all. ${calleeName} was used with fire() on line \
|
||||
${printSourceLocationLine(calleeInfo.fireLoc)} in this effect`,
|
||||
category: ErrorCategory.Fire,
|
||||
reason: CANNOT_COMPILE_FIRE,
|
||||
suggestions: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function ensureNoMoreFireUses(fn: HIRFunction, context: Context): void {
|
||||
for (const place of eachReachablePlace(fn)) {
|
||||
if (
|
||||
place.identifier.type.kind === 'Function' &&
|
||||
place.identifier.type.shapeId === BuiltInFireId
|
||||
) {
|
||||
context.pushError({
|
||||
loc: place.identifier.loc,
|
||||
description: 'Cannot use `fire` outside of a useEffect function',
|
||||
category: ErrorCategory.Fire,
|
||||
reason: CANNOT_COMPILE_FIRE,
|
||||
suggestions: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function makeLoadUseFireInstruction(
|
||||
env: Environment,
|
||||
importedLoadUseFire: NonLocalImportSpecifier,
|
||||
): Instruction {
|
||||
const useFirePlace = createTemporaryPlace(env, GeneratedSource);
|
||||
useFirePlace.effect = Effect.Read;
|
||||
useFirePlace.identifier.type = DefaultNonmutatingHook;
|
||||
const instrValue: InstructionValue = {
|
||||
kind: 'LoadGlobal',
|
||||
binding: {...importedLoadUseFire},
|
||||
loc: GeneratedSource,
|
||||
};
|
||||
return {
|
||||
id: makeInstructionId(0),
|
||||
value: instrValue,
|
||||
lvalue: {...useFirePlace},
|
||||
loc: GeneratedSource,
|
||||
effects: null,
|
||||
};
|
||||
}
|
||||
|
||||
function makeLoadFireCalleeInstruction(
|
||||
env: Environment,
|
||||
fireCalleeIdentifier: Identifier,
|
||||
): Instruction {
|
||||
const loadedFireCallee = createTemporaryPlace(env, GeneratedSource);
|
||||
const fireCallee: Place = {
|
||||
kind: 'Identifier',
|
||||
identifier: fireCalleeIdentifier,
|
||||
reactive: false,
|
||||
effect: Effect.Unknown,
|
||||
loc: fireCalleeIdentifier.loc,
|
||||
};
|
||||
return {
|
||||
id: makeInstructionId(0),
|
||||
value: {
|
||||
kind: 'LoadLocal',
|
||||
loc: GeneratedSource,
|
||||
place: {...fireCallee},
|
||||
},
|
||||
lvalue: {...loadedFireCallee},
|
||||
loc: GeneratedSource,
|
||||
effects: null,
|
||||
};
|
||||
}
|
||||
|
||||
function makeCallUseFireInstruction(
|
||||
env: Environment,
|
||||
useFirePlace: Place,
|
||||
argPlace: Place,
|
||||
): Instruction {
|
||||
const useFireCallResultPlace = createTemporaryPlace(env, GeneratedSource);
|
||||
useFireCallResultPlace.effect = Effect.Read;
|
||||
|
||||
const useFireCall: CallExpression = {
|
||||
kind: 'CallExpression',
|
||||
callee: {...useFirePlace},
|
||||
args: [argPlace],
|
||||
loc: GeneratedSource,
|
||||
};
|
||||
|
||||
return {
|
||||
id: makeInstructionId(0),
|
||||
value: useFireCall,
|
||||
lvalue: {...useFireCallResultPlace},
|
||||
loc: GeneratedSource,
|
||||
effects: null,
|
||||
};
|
||||
}
|
||||
|
||||
function makeStoreUseFireInstruction(
|
||||
env: Environment,
|
||||
useFireCallResultPlace: Place,
|
||||
fireFunctionBindingPlace: Place,
|
||||
): Instruction {
|
||||
promoteTemporary(fireFunctionBindingPlace.identifier);
|
||||
|
||||
const fireFunctionBindingLValuePlace = createTemporaryPlace(
|
||||
env,
|
||||
GeneratedSource,
|
||||
);
|
||||
return {
|
||||
id: makeInstructionId(0),
|
||||
value: {
|
||||
kind: 'StoreLocal',
|
||||
lvalue: {
|
||||
kind: InstructionKind.Const,
|
||||
place: {...fireFunctionBindingPlace},
|
||||
},
|
||||
value: {...useFireCallResultPlace},
|
||||
type: null,
|
||||
loc: GeneratedSource,
|
||||
},
|
||||
lvalue: fireFunctionBindingLValuePlace,
|
||||
loc: GeneratedSource,
|
||||
effects: null,
|
||||
};
|
||||
}
|
||||
|
||||
type FireCalleesToFireFunctionBinding = Map<
|
||||
IdentifierId,
|
||||
{
|
||||
fireFunctionBinding: Place;
|
||||
capturedCalleeIdentifier: Identifier;
|
||||
fireLoc: SourceLocation;
|
||||
}
|
||||
>;
|
||||
|
||||
class Context {
|
||||
#env: Environment;
|
||||
|
||||
#errors: CompilerError = new CompilerError();
|
||||
|
||||
/*
|
||||
* Used to look up the call expression passed to a `fire(callExpr())`. Gives back
|
||||
* the `callExpr()`.
|
||||
*/
|
||||
#callExpressions = new Map<IdentifierId, CallExpression>();
|
||||
|
||||
/*
|
||||
* We keep track of function expressions so that we can traverse them when
|
||||
* we encounter a lambda passed to a useEffect call
|
||||
*/
|
||||
#functionExpressions = new Map<IdentifierId, FunctionExpression>();
|
||||
|
||||
/*
|
||||
* Mapping from lvalue ids to the LoadLocal for it. Allows us to replace dependency LoadLocals.
|
||||
*/
|
||||
#loadLocals = new Map<IdentifierId, LoadLocal>();
|
||||
|
||||
/*
|
||||
* Maps all of the fire callees found in a component/hook to the generated fire function places
|
||||
* we create for them. Allows us to reuse already-inserted useFire results
|
||||
*/
|
||||
#fireCalleesToFireFunctions: Map<IdentifierId, Place> = new Map();
|
||||
|
||||
/*
|
||||
* The callees for which we have already created fire bindings. Used to skip inserting a new
|
||||
* useFire call for a fire callee if one has already been created.
|
||||
*/
|
||||
#calleesWithInsertedFire = new Set<IdentifierId>();
|
||||
|
||||
/*
|
||||
* A mapping from fire callees to the created fire function bindings that are reachable from this
|
||||
* scope.
|
||||
*
|
||||
* We additionally keep track of the captured callee identifier so that we can properly reference
|
||||
* it in the place where we LoadLocal the callee as an argument to useFire.
|
||||
*/
|
||||
#capturedCalleeIdentifierIds: FireCalleesToFireFunctionBinding = new Map();
|
||||
|
||||
/*
|
||||
* We only transform fire calls if we're syntactically within a useEffect lambda (for now)
|
||||
*/
|
||||
#inUseEffectLambda = false;
|
||||
|
||||
/*
|
||||
* Mapping from useEffect callee identifier ids to the instruction id of the
|
||||
* load global instruction for the useEffect call. We use this to insert the
|
||||
* useFire calls before the useEffect call
|
||||
*/
|
||||
#loadGlobalInstructionIds = new Map<IdentifierId, InstructionId>();
|
||||
|
||||
constructor(env: Environment) {
|
||||
this.#env = env;
|
||||
}
|
||||
|
||||
/*
|
||||
* We keep track of array expressions so we can rewrite dependency arrays passed to useEffect
|
||||
* to use the fire functions
|
||||
*/
|
||||
#arrayExpressions = new Map<IdentifierId, ArrayExpression>();
|
||||
|
||||
pushError(error: CompilerErrorDetailOptions): void {
|
||||
this.#errors.push(error);
|
||||
}
|
||||
|
||||
withFunctionScope(fn: () => void): FireCalleesToFireFunctionBinding {
|
||||
fn();
|
||||
return this.#capturedCalleeIdentifierIds;
|
||||
}
|
||||
|
||||
withUseEffectLambdaScope(fn: () => void): FireCalleesToFireFunctionBinding {
|
||||
const capturedCalleeIdentifierIds = this.#capturedCalleeIdentifierIds;
|
||||
const inUseEffectLambda = this.#inUseEffectLambda;
|
||||
|
||||
this.#capturedCalleeIdentifierIds = new Map();
|
||||
this.#inUseEffectLambda = true;
|
||||
|
||||
const resultCapturedCalleeIdentifierIds = this.withFunctionScope(fn);
|
||||
|
||||
this.#capturedCalleeIdentifierIds = capturedCalleeIdentifierIds;
|
||||
this.#inUseEffectLambda = inUseEffectLambda;
|
||||
|
||||
return resultCapturedCalleeIdentifierIds;
|
||||
}
|
||||
|
||||
addCallExpression(id: IdentifierId, callExpr: CallExpression): void {
|
||||
this.#callExpressions.set(id, callExpr);
|
||||
}
|
||||
|
||||
getCallExpression(id: IdentifierId): CallExpression | undefined {
|
||||
return this.#callExpressions.get(id);
|
||||
}
|
||||
|
||||
addLoadLocalInstr(id: IdentifierId, loadLocal: LoadLocal): void {
|
||||
this.#loadLocals.set(id, loadLocal);
|
||||
}
|
||||
|
||||
getLoadLocalInstr(id: IdentifierId): LoadLocal | undefined {
|
||||
return this.#loadLocals.get(id);
|
||||
}
|
||||
getOrGenerateFireFunctionBinding(
|
||||
callee: Place,
|
||||
fireLoc: SourceLocation,
|
||||
): Place {
|
||||
const fireFunctionBinding = getOrInsertWith(
|
||||
this.#fireCalleesToFireFunctions,
|
||||
callee.identifier.id,
|
||||
() => createTemporaryPlace(this.#env, GeneratedSource),
|
||||
);
|
||||
|
||||
fireFunctionBinding.identifier.type = {
|
||||
kind: 'Function',
|
||||
shapeId: BuiltInFireFunctionId,
|
||||
return: {kind: 'Poly'},
|
||||
isConstructor: false,
|
||||
};
|
||||
|
||||
this.#capturedCalleeIdentifierIds.set(callee.identifier.id, {
|
||||
fireFunctionBinding,
|
||||
capturedCalleeIdentifier: callee.identifier,
|
||||
fireLoc,
|
||||
});
|
||||
|
||||
return fireFunctionBinding;
|
||||
}
|
||||
|
||||
mergeCalleesFromInnerScope(
|
||||
innerCallees: FireCalleesToFireFunctionBinding,
|
||||
): void {
|
||||
for (const [id, calleeInfo] of innerCallees.entries()) {
|
||||
this.#capturedCalleeIdentifierIds.set(id, calleeInfo);
|
||||
}
|
||||
}
|
||||
|
||||
addCalleeWithInsertedFire(id: IdentifierId): void {
|
||||
this.#calleesWithInsertedFire.add(id);
|
||||
}
|
||||
|
||||
hasCalleeWithInsertedFire(id: IdentifierId): boolean {
|
||||
return this.#calleesWithInsertedFire.has(id);
|
||||
}
|
||||
|
||||
inUseEffectLambda(): boolean {
|
||||
return this.#inUseEffectLambda;
|
||||
}
|
||||
|
||||
addFunctionExpression(id: IdentifierId, fn: FunctionExpression): void {
|
||||
this.#functionExpressions.set(id, fn);
|
||||
}
|
||||
|
||||
getFunctionExpression(id: IdentifierId): FunctionExpression | undefined {
|
||||
return this.#functionExpressions.get(id);
|
||||
}
|
||||
|
||||
addLoadGlobalInstrId(id: IdentifierId, instrId: InstructionId): void {
|
||||
this.#loadGlobalInstructionIds.set(id, instrId);
|
||||
}
|
||||
|
||||
getLoadGlobalInstrId(id: IdentifierId): InstructionId | undefined {
|
||||
return this.#loadGlobalInstructionIds.get(id);
|
||||
}
|
||||
|
||||
addArrayExpression(id: IdentifierId, array: ArrayExpression): void {
|
||||
this.#arrayExpressions.set(id, array);
|
||||
}
|
||||
|
||||
getArrayExpression(id: IdentifierId): ArrayExpression | undefined {
|
||||
return this.#arrayExpressions.get(id);
|
||||
}
|
||||
|
||||
hasErrors(): boolean {
|
||||
return this.#errors.hasAnyErrors();
|
||||
}
|
||||
|
||||
throwIfErrorsFound(): void {
|
||||
if (this.hasErrors()) throw this.#errors;
|
||||
}
|
||||
}
|
||||
|
||||
function deleteInstructions(
|
||||
deleteInstrs: Set<InstructionId>,
|
||||
instructions: Array<Instruction>,
|
||||
): Array<Instruction> {
|
||||
if (deleteInstrs.size > 0) {
|
||||
const newInstrs = instructions.filter(instr => !deleteInstrs.has(instr.id));
|
||||
return newInstrs;
|
||||
}
|
||||
return instructions;
|
||||
}
|
||||
|
||||
function rewriteInstructions(
|
||||
rewriteInstrs: Map<InstructionId, Array<Instruction>>,
|
||||
instructions: Array<Instruction>,
|
||||
): Array<Instruction> {
|
||||
if (rewriteInstrs.size > 0) {
|
||||
const newInstrs = [];
|
||||
for (const instr of instructions) {
|
||||
const newInstrsAtId = rewriteInstrs.get(instr.id);
|
||||
if (newInstrsAtId != null) {
|
||||
newInstrs.push(...newInstrsAtId, instr);
|
||||
} else {
|
||||
newInstrs.push(instr);
|
||||
}
|
||||
}
|
||||
|
||||
return newInstrs;
|
||||
}
|
||||
|
||||
return instructions;
|
||||
}
|
||||
@@ -4,5 +4,3 @@
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
export {transformFire} from './TransformFire';
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
import * as t from '@babel/types';
|
||||
import {CompilerError} from '../CompilerError';
|
||||
import {Environment} from '../HIR';
|
||||
import {lowerType} from '../HIR/BuildHIR';
|
||||
import {
|
||||
GeneratedSource,
|
||||
HIRFunction,
|
||||
@@ -26,7 +25,6 @@ import {
|
||||
} from '../HIR/HIR';
|
||||
import {
|
||||
BuiltInArrayId,
|
||||
BuiltInEventHandlerId,
|
||||
BuiltInFunctionId,
|
||||
BuiltInJsxId,
|
||||
BuiltInMixedReadonlyId,
|
||||
@@ -223,22 +221,11 @@ function* generateInstructionTypes(
|
||||
}
|
||||
|
||||
case 'StoreLocal': {
|
||||
if (env.config.enableUseTypeAnnotations) {
|
||||
yield equation(
|
||||
value.lvalue.place.identifier.type,
|
||||
value.value.identifier.type,
|
||||
);
|
||||
const valueType =
|
||||
value.type === null ? makeType() : lowerType(value.type);
|
||||
yield equation(valueType, value.lvalue.place.identifier.type);
|
||||
yield equation(left, valueType);
|
||||
} else {
|
||||
yield equation(left, value.value.identifier.type);
|
||||
yield equation(
|
||||
value.lvalue.place.identifier.type,
|
||||
value.value.identifier.type,
|
||||
);
|
||||
}
|
||||
yield equation(left, value.value.identifier.type);
|
||||
yield equation(
|
||||
value.lvalue.place.identifier.type,
|
||||
value.value.identifier.type,
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -422,12 +409,7 @@ function* generateInstructionTypes(
|
||||
}
|
||||
|
||||
case 'TypeCastExpression': {
|
||||
if (env.config.enableUseTypeAnnotations) {
|
||||
yield equation(value.type, value.value.identifier.type);
|
||||
yield equation(left, value.type);
|
||||
} else {
|
||||
yield equation(left, value.value.identifier.type);
|
||||
}
|
||||
yield equation(left, value.value.identifier.type);
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -473,41 +455,6 @@ function* generateInstructionTypes(
|
||||
}
|
||||
}
|
||||
}
|
||||
if (env.config.enableInferEventHandlers) {
|
||||
if (
|
||||
value.kind === 'JsxExpression' &&
|
||||
value.tag.kind === 'BuiltinTag' &&
|
||||
!value.tag.name.includes('-')
|
||||
) {
|
||||
/*
|
||||
* Infer event handler types for built-in DOM elements.
|
||||
* Props starting with "on" (e.g., onClick, onSubmit) on primitive tags
|
||||
* are inferred as event handlers. This allows functions with ref access
|
||||
* to be passed to these props, since DOM event handlers are guaranteed
|
||||
* by React to only execute in response to events, never during render.
|
||||
*
|
||||
* We exclude tags with hyphens to avoid web components (custom elements),
|
||||
* which are required by the HTML spec to contain a hyphen. Web components
|
||||
* may call event handler props during their lifecycle methods (e.g.,
|
||||
* connectedCallback), which would be unsafe for ref access.
|
||||
*/
|
||||
for (const prop of value.props) {
|
||||
if (
|
||||
prop.kind === 'JsxAttribute' &&
|
||||
prop.name.startsWith('on') &&
|
||||
prop.name.length > 2 &&
|
||||
prop.name[2] === prop.name[2].toUpperCase()
|
||||
) {
|
||||
yield equation(prop.place.identifier.type, {
|
||||
kind: 'Function',
|
||||
shapeId: BuiltInEventHandlerId,
|
||||
return: makeType(),
|
||||
isConstructor: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
yield equation(left, {kind: 'Object', shapeId: BuiltInJsxId});
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -39,14 +39,6 @@ function tryParseTestPragmaValue(val: string): Result<unknown, unknown> {
|
||||
|
||||
const testComplexConfigDefaults: PartialEnvironmentConfig = {
|
||||
validateNoCapitalizedCalls: [],
|
||||
enableChangeDetectionForDebugging: {
|
||||
source: 'react-compiler-runtime',
|
||||
importSpecifierName: '$structuralCheck',
|
||||
},
|
||||
enableEmitFreeze: {
|
||||
source: 'react-compiler-runtime',
|
||||
importSpecifierName: 'makeReadOnly',
|
||||
},
|
||||
enableEmitInstrumentForget: {
|
||||
fn: {
|
||||
source: 'react-compiler-runtime',
|
||||
@@ -62,37 +54,6 @@ const testComplexConfigDefaults: PartialEnvironmentConfig = {
|
||||
source: 'react-compiler-runtime',
|
||||
importSpecifierName: '$dispatcherGuard',
|
||||
},
|
||||
inlineJsxTransform: {
|
||||
elementSymbol: 'react.transitional.element',
|
||||
globalDevVar: 'DEV',
|
||||
},
|
||||
lowerContextAccess: {
|
||||
source: 'react-compiler-runtime',
|
||||
importSpecifierName: 'useContext_withSelector',
|
||||
},
|
||||
inferEffectDependencies: [
|
||||
{
|
||||
function: {
|
||||
source: 'react',
|
||||
importSpecifierName: 'useEffect',
|
||||
},
|
||||
autodepsIndex: 1,
|
||||
},
|
||||
{
|
||||
function: {
|
||||
source: 'shared-runtime',
|
||||
importSpecifierName: 'useSpecialEffect',
|
||||
},
|
||||
autodepsIndex: 2,
|
||||
},
|
||||
{
|
||||
function: {
|
||||
source: 'useEffectWrapper',
|
||||
importSpecifierName: 'default',
|
||||
},
|
||||
autodepsIndex: 1,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function* splitPragma(
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {CompilerError} from '..';
|
||||
import {CompilerDiagnostic, CompilerError} from '..';
|
||||
import {ErrorCategory} from '../CompilerError';
|
||||
import {Environment} from '../HIR/Environment';
|
||||
import {HIRFunction, IdentifierId, Place} from '../HIR';
|
||||
import {printPlace} from '../HIR/PrintHIR';
|
||||
import {eachInstructionValueLValue, eachPatternOperand} from '../HIR/visitors';
|
||||
@@ -17,12 +19,13 @@ import {eachInstructionValueLValue, eachPatternOperand} from '../HIR/visitors';
|
||||
*/
|
||||
export function validateContextVariableLValues(fn: HIRFunction): void {
|
||||
const identifierKinds: IdentifierKinds = new Map();
|
||||
validateContextVariableLValuesImpl(fn, identifierKinds);
|
||||
validateContextVariableLValuesImpl(fn, identifierKinds, fn.env);
|
||||
}
|
||||
|
||||
function validateContextVariableLValuesImpl(
|
||||
fn: HIRFunction,
|
||||
identifierKinds: IdentifierKinds,
|
||||
env: Environment,
|
||||
): void {
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
for (const instr of block.instructions) {
|
||||
@@ -30,30 +33,30 @@ function validateContextVariableLValuesImpl(
|
||||
switch (value.kind) {
|
||||
case 'DeclareContext':
|
||||
case 'StoreContext': {
|
||||
visit(identifierKinds, value.lvalue.place, 'context');
|
||||
visit(identifierKinds, value.lvalue.place, 'context', env);
|
||||
break;
|
||||
}
|
||||
case 'LoadContext': {
|
||||
visit(identifierKinds, value.place, 'context');
|
||||
visit(identifierKinds, value.place, 'context', env);
|
||||
break;
|
||||
}
|
||||
case 'StoreLocal':
|
||||
case 'DeclareLocal': {
|
||||
visit(identifierKinds, value.lvalue.place, 'local');
|
||||
visit(identifierKinds, value.lvalue.place, 'local', env);
|
||||
break;
|
||||
}
|
||||
case 'LoadLocal': {
|
||||
visit(identifierKinds, value.place, 'local');
|
||||
visit(identifierKinds, value.place, 'local', env);
|
||||
break;
|
||||
}
|
||||
case 'PostfixUpdate':
|
||||
case 'PrefixUpdate': {
|
||||
visit(identifierKinds, value.lvalue, 'local');
|
||||
visit(identifierKinds, value.lvalue, 'local', env);
|
||||
break;
|
||||
}
|
||||
case 'Destructure': {
|
||||
for (const lvalue of eachPatternOperand(value.lvalue.pattern)) {
|
||||
visit(identifierKinds, lvalue, 'destructure');
|
||||
visit(identifierKinds, lvalue, 'destructure', env);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -62,18 +65,24 @@ function validateContextVariableLValuesImpl(
|
||||
validateContextVariableLValuesImpl(
|
||||
value.loweredFunc.func,
|
||||
identifierKinds,
|
||||
env,
|
||||
);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
for (const _ of eachInstructionValueLValue(value)) {
|
||||
CompilerError.throwTodo({
|
||||
reason:
|
||||
'ValidateContextVariableLValues: unhandled instruction variant',
|
||||
loc: value.loc,
|
||||
description: `Handle '${value.kind} lvalues`,
|
||||
suggestions: null,
|
||||
});
|
||||
fn.env.recordError(
|
||||
CompilerDiagnostic.create({
|
||||
category: ErrorCategory.Todo,
|
||||
reason:
|
||||
'ValidateContextVariableLValues: unhandled instruction variant',
|
||||
description: `Handle '${value.kind} lvalues`,
|
||||
}).withDetails({
|
||||
kind: 'error',
|
||||
loc: value.loc,
|
||||
message: null,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -90,6 +99,7 @@ function visit(
|
||||
identifiers: IdentifierKinds,
|
||||
place: Place,
|
||||
kind: 'local' | 'context' | 'destructure',
|
||||
env: Environment,
|
||||
): void {
|
||||
const prev = identifiers.get(place.identifier.id);
|
||||
if (prev !== undefined) {
|
||||
@@ -97,12 +107,18 @@ function visit(
|
||||
const isContext = kind === 'context';
|
||||
if (wasContext !== isContext) {
|
||||
if (prev.kind === 'destructure' || kind === 'destructure') {
|
||||
CompilerError.throwTodo({
|
||||
reason: `Support destructuring of context variables`,
|
||||
loc: kind === 'destructure' ? place.loc : prev.place.loc,
|
||||
description: null,
|
||||
suggestions: null,
|
||||
});
|
||||
env.recordError(
|
||||
CompilerDiagnostic.create({
|
||||
category: ErrorCategory.Todo,
|
||||
reason: `Support destructuring of context variables`,
|
||||
description: null,
|
||||
}).withDetails({
|
||||
kind: 'error',
|
||||
loc: kind === 'destructure' ? place.loc : prev.place.loc,
|
||||
message: null,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
CompilerError.invariant(false, {
|
||||
|
||||
@@ -29,6 +29,9 @@ import {
|
||||
isStableType,
|
||||
isSubPath,
|
||||
isSubPathIgnoringOptionals,
|
||||
isUseEffectHookType,
|
||||
isUseInsertionEffectHookType,
|
||||
isUseLayoutEffectHookType,
|
||||
isUseRefType,
|
||||
LoadGlobal,
|
||||
ManualMemoDependency,
|
||||
@@ -41,9 +44,7 @@ import {
|
||||
eachInstructionValueOperand,
|
||||
eachTerminalOperand,
|
||||
} from '../HIR/visitors';
|
||||
import {Result} from '../Utils/Result';
|
||||
import {retainWhere} from '../Utils/utils';
|
||||
import {isEffectHook} from './ValidateMemoizedEffectDependencies';
|
||||
|
||||
const DEBUG = false;
|
||||
|
||||
@@ -86,9 +87,7 @@ const DEBUG = false;
|
||||
* When we go to compute the dependencies, we then think that the user's manual dep
|
||||
* logic is part of what the memo computation logic.
|
||||
*/
|
||||
export function validateExhaustiveDependencies(
|
||||
fn: HIRFunction,
|
||||
): Result<void, CompilerError> {
|
||||
export function validateExhaustiveDependencies(fn: HIRFunction): void {
|
||||
const env = fn.env;
|
||||
const reactive = collectReactiveIdentifiersHIR(fn);
|
||||
|
||||
@@ -215,7 +214,9 @@ export function validateExhaustiveDependencies(
|
||||
},
|
||||
false, // isFunctionExpression
|
||||
);
|
||||
return error.asResult();
|
||||
if (error.hasAnyErrors()) {
|
||||
fn.env.recordErrors(error);
|
||||
}
|
||||
}
|
||||
|
||||
function validateDependencies(
|
||||
@@ -756,6 +757,7 @@ function collectDependencies(
|
||||
{
|
||||
optional,
|
||||
property: value.property,
|
||||
loc: value.loc,
|
||||
},
|
||||
],
|
||||
loc: value.loc,
|
||||
@@ -1110,3 +1112,11 @@ function createDiagnostic(
|
||||
suggestions: suggestion != null ? [suggestion] : null,
|
||||
});
|
||||
}
|
||||
|
||||
export function isEffectHook(identifier: Identifier): boolean {
|
||||
return (
|
||||
isUseEffectHookType(identifier) ||
|
||||
isUseLayoutEffectHookType(identifier) ||
|
||||
isUseInsertionEffectHookType(identifier)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ import {
|
||||
eachTerminalOperand,
|
||||
} from '../HIR/visitors';
|
||||
import {assertExhaustive} from '../Utils/utils';
|
||||
import {Result} from '../Utils/Result';
|
||||
|
||||
/**
|
||||
* Represents the possible kinds of value which may be stored at a given Place during
|
||||
@@ -88,9 +87,7 @@ function joinKinds(a: Kind, b: Kind): Kind {
|
||||
* may not appear as the callee of a conditional call.
|
||||
* See the note for Kind.PotentialHook for sources of potential hooks
|
||||
*/
|
||||
export function validateHooksUsage(
|
||||
fn: HIRFunction,
|
||||
): Result<void, CompilerError> {
|
||||
export function validateHooksUsage(fn: HIRFunction): void {
|
||||
const unconditionalBlocks = computeUnconditionalBlocks(fn);
|
||||
|
||||
const errors = new CompilerError();
|
||||
@@ -426,7 +423,9 @@ export function validateHooksUsage(
|
||||
for (const [, error] of errorsByPlace) {
|
||||
errors.pushErrorDetail(error);
|
||||
}
|
||||
return errors.asResult();
|
||||
if (errors.hasAnyErrors()) {
|
||||
fn.env.recordErrors(errors);
|
||||
}
|
||||
}
|
||||
|
||||
function visitFunctionExpression(errors: CompilerError, fn: HIRFunction): void {
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
import {CompilerDiagnostic, CompilerError, Effect} from '..';
|
||||
import {ErrorCategory} from '../CompilerError';
|
||||
import {Environment} from '../HIR/Environment';
|
||||
import {HIRFunction, IdentifierId, Place} from '../HIR';
|
||||
import {
|
||||
eachInstructionLValue,
|
||||
@@ -27,15 +28,15 @@ export function validateLocalsNotReassignedAfterRender(fn: HIRFunction): void {
|
||||
contextVariables,
|
||||
false,
|
||||
false,
|
||||
fn.env,
|
||||
);
|
||||
if (reassignment !== null) {
|
||||
const errors = new CompilerError();
|
||||
const variable =
|
||||
reassignment.identifier.name != null &&
|
||||
reassignment.identifier.name.kind === 'named'
|
||||
? `\`${reassignment.identifier.name.value}\``
|
||||
: 'variable';
|
||||
errors.pushDiagnostic(
|
||||
fn.env.recordError(
|
||||
CompilerDiagnostic.create({
|
||||
category: ErrorCategory.Immutability,
|
||||
reason: 'Cannot reassign variable after render completes',
|
||||
@@ -46,7 +47,6 @@ export function validateLocalsNotReassignedAfterRender(fn: HIRFunction): void {
|
||||
message: `Cannot reassign ${variable} after render completes`,
|
||||
}),
|
||||
);
|
||||
throw errors;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -55,6 +55,7 @@ function getContextReassignment(
|
||||
contextVariables: Set<IdentifierId>,
|
||||
isFunctionExpression: boolean,
|
||||
isAsync: boolean,
|
||||
env: Environment,
|
||||
): Place | null {
|
||||
const reassigningFunctions = new Map<IdentifierId, Place>();
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
@@ -68,6 +69,7 @@ function getContextReassignment(
|
||||
contextVariables,
|
||||
true,
|
||||
isAsync || value.loweredFunc.func.async,
|
||||
env,
|
||||
);
|
||||
if (reassignment === null) {
|
||||
// If the function itself doesn't reassign, does one of its dependencies?
|
||||
@@ -84,13 +86,12 @@ function getContextReassignment(
|
||||
// if the function or its depends reassign, propagate that fact on the lvalue
|
||||
if (reassignment !== null) {
|
||||
if (isAsync || value.loweredFunc.func.async) {
|
||||
const errors = new CompilerError();
|
||||
const variable =
|
||||
reassignment.identifier.name !== null &&
|
||||
reassignment.identifier.name.kind === 'named'
|
||||
? `\`${reassignment.identifier.name.value}\``
|
||||
: 'variable';
|
||||
errors.pushDiagnostic(
|
||||
env.recordError(
|
||||
CompilerDiagnostic.create({
|
||||
category: ErrorCategory.Immutability,
|
||||
reason: 'Cannot reassign variable in async function',
|
||||
@@ -102,7 +103,7 @@ function getContextReassignment(
|
||||
message: `Cannot reassign ${variable}`,
|
||||
}),
|
||||
);
|
||||
throw errors;
|
||||
return null;
|
||||
}
|
||||
reassigningFunctions.set(lvalue.identifier.id, reassignment);
|
||||
}
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) Meta Platforms, Inc. and affiliates.
|
||||
*
|
||||
* This source code is licensed under the MIT license found in the
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {CompilerError} from '..';
|
||||
import {ErrorCategory} from '../CompilerError';
|
||||
import {
|
||||
Identifier,
|
||||
Instruction,
|
||||
ReactiveFunction,
|
||||
ReactiveInstruction,
|
||||
ReactiveScopeBlock,
|
||||
ScopeId,
|
||||
isUseEffectHookType,
|
||||
isUseInsertionEffectHookType,
|
||||
isUseLayoutEffectHookType,
|
||||
} from '../HIR';
|
||||
import {isMutable} from '../ReactiveScopes/InferReactiveScopeVariables';
|
||||
import {
|
||||
ReactiveFunctionVisitor,
|
||||
visitReactiveFunction,
|
||||
} from '../ReactiveScopes/visitors';
|
||||
import {Result} from '../Utils/Result';
|
||||
|
||||
/**
|
||||
* Validates that all known effect dependencies are memoized. The algorithm checks two things:
|
||||
* - Disallow effect dependencies that should be memoized (have a reactive scope assigned) but
|
||||
* where that reactive scope does not exist. This checks for cases where a reactive scope was
|
||||
* pruned for some reason, such as spanning a hook.
|
||||
* - Disallow effect dependencies whose a mutable range that encompasses the effect call.
|
||||
*
|
||||
* This latter check corresponds to any values which Forget knows may be mutable and may be mutated
|
||||
* after the effect. Note that it's possible Forget may miss not memoize a value for some other reason,
|
||||
* but in general this is a bug. The only reason Forget would _choose_ to skip memoization of an
|
||||
* effect dependency is because it's mutated later.
|
||||
*
|
||||
* Example:
|
||||
*
|
||||
* ```javascript
|
||||
* const object = {}; // mutable range starts here...
|
||||
*
|
||||
* useEffect(() => {
|
||||
* console.log('hello');
|
||||
* }, [object]); // the dependency array picks up the mutable range of its mutable contents
|
||||
*
|
||||
* mutate(object); // ... mutable range ends here after this mutation
|
||||
* ```
|
||||
*/
|
||||
export function validateMemoizedEffectDependencies(
|
||||
fn: ReactiveFunction,
|
||||
): Result<void, CompilerError> {
|
||||
const errors = new CompilerError();
|
||||
visitReactiveFunction(fn, new Visitor(), errors);
|
||||
return errors.asResult();
|
||||
}
|
||||
|
||||
class Visitor extends ReactiveFunctionVisitor<CompilerError> {
|
||||
scopes: Set<ScopeId> = new Set();
|
||||
|
||||
override visitScope(
|
||||
scopeBlock: ReactiveScopeBlock,
|
||||
state: CompilerError,
|
||||
): void {
|
||||
this.traverseScope(scopeBlock, state);
|
||||
|
||||
/*
|
||||
* Record scopes that exist in the AST so we can later check to see if
|
||||
* effect dependencies which should be memoized (have a scope assigned)
|
||||
* actually are memoized (that scope exists).
|
||||
* However, we only record scopes if *their* dependencies are also
|
||||
* memoized, allowing a transitive memoization check.
|
||||
*/
|
||||
let areDependenciesMemoized = true;
|
||||
for (const dep of scopeBlock.scope.dependencies) {
|
||||
if (isUnmemoized(dep.identifier, this.scopes)) {
|
||||
areDependenciesMemoized = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (areDependenciesMemoized) {
|
||||
this.scopes.add(scopeBlock.scope.id);
|
||||
for (const id of scopeBlock.scope.merged) {
|
||||
this.scopes.add(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override visitInstruction(
|
||||
instruction: ReactiveInstruction,
|
||||
state: CompilerError,
|
||||
): void {
|
||||
this.traverseInstruction(instruction, state);
|
||||
if (
|
||||
instruction.value.kind === 'CallExpression' &&
|
||||
isEffectHook(instruction.value.callee.identifier) &&
|
||||
instruction.value.args.length >= 2
|
||||
) {
|
||||
const deps = instruction.value.args[1]!;
|
||||
if (
|
||||
deps.kind === 'Identifier' &&
|
||||
/*
|
||||
* TODO: isMutable is not safe to call here as it relies on identifier mutableRange which is no longer valid at this point
|
||||
* in the pipeline
|
||||
*/
|
||||
(isMutable(instruction as Instruction, deps) ||
|
||||
isUnmemoized(deps.identifier, this.scopes))
|
||||
) {
|
||||
state.push({
|
||||
category: ErrorCategory.EffectDependencies,
|
||||
reason:
|
||||
'React Compiler has skipped optimizing this component because the effect dependencies could not be memoized. Unmemoized effect dependencies can trigger an infinite loop or other unexpected behavior',
|
||||
description: null,
|
||||
loc: typeof instruction.loc !== 'symbol' ? instruction.loc : null,
|
||||
suggestions: null,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function isUnmemoized(operand: Identifier, scopes: Set<ScopeId>): boolean {
|
||||
return operand.scope != null && !scopes.has(operand.scope.id);
|
||||
}
|
||||
|
||||
export function isEffectHook(identifier: Identifier): boolean {
|
||||
return (
|
||||
isUseEffectHookType(identifier) ||
|
||||
isUseLayoutEffectHookType(identifier) ||
|
||||
isUseInsertionEffectHookType(identifier)
|
||||
);
|
||||
}
|
||||
@@ -5,30 +5,19 @@
|
||||
* LICENSE file in the root directory of this source tree.
|
||||
*/
|
||||
|
||||
import {CompilerError, EnvironmentConfig} from '..';
|
||||
import {CompilerError, CompilerErrorDetail, EnvironmentConfig} from '..';
|
||||
import {ErrorCategory} from '../CompilerError';
|
||||
import {HIRFunction, IdentifierId} from '../HIR';
|
||||
import {DEFAULT_GLOBALS} from '../HIR/Globals';
|
||||
import {Result} from '../Utils/Result';
|
||||
|
||||
export function validateNoCapitalizedCalls(
|
||||
fn: HIRFunction,
|
||||
): Result<void, CompilerError> {
|
||||
export function validateNoCapitalizedCalls(fn: HIRFunction): void {
|
||||
const envConfig: EnvironmentConfig = fn.env.config;
|
||||
const ALLOW_LIST = new Set([
|
||||
...DEFAULT_GLOBALS.keys(),
|
||||
...(envConfig.validateNoCapitalizedCalls ?? []),
|
||||
]);
|
||||
/*
|
||||
* The hook pattern may allow uppercase names, like React$useState, so we need to be sure that we
|
||||
* do not error in those cases
|
||||
*/
|
||||
const hookPattern =
|
||||
envConfig.hookPattern != null ? new RegExp(envConfig.hookPattern) : null;
|
||||
const isAllowed = (name: string): boolean => {
|
||||
return (
|
||||
ALLOW_LIST.has(name) || (hookPattern != null && hookPattern.test(name))
|
||||
);
|
||||
return ALLOW_LIST.has(name);
|
||||
};
|
||||
|
||||
const errors = new CompilerError();
|
||||
@@ -56,13 +45,16 @@ export function validateNoCapitalizedCalls(
|
||||
const calleeIdentifier = value.callee.identifier.id;
|
||||
const calleeName = capitalLoadGlobals.get(calleeIdentifier);
|
||||
if (calleeName != null) {
|
||||
CompilerError.throwInvalidReact({
|
||||
category: ErrorCategory.CapitalizedCalls,
|
||||
reason,
|
||||
description: `${calleeName} may be a component`,
|
||||
loc: value.loc,
|
||||
suggestions: null,
|
||||
});
|
||||
fn.env.recordError(
|
||||
new CompilerErrorDetail({
|
||||
category: ErrorCategory.CapitalizedCalls,
|
||||
reason,
|
||||
description: `${calleeName} may be a component`,
|
||||
loc: value.loc,
|
||||
suggestions: null,
|
||||
}),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -93,5 +85,7 @@ export function validateNoCapitalizedCalls(
|
||||
}
|
||||
}
|
||||
}
|
||||
return errors.asResult();
|
||||
if (errors.hasAnyErrors()) {
|
||||
fn.env.recordErrors(errors);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,8 +97,8 @@ export function validateNoDerivedComputationsInEffects(fn: HIRFunction): void {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (errors.hasAnyErrors()) {
|
||||
throw errors;
|
||||
for (const detail of errors.details) {
|
||||
fn.env.recordError(detail);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
eachTerminalOperand,
|
||||
} from '../HIR/visitors';
|
||||
import {AliasingEffect} from '../Inference/AliasingEffects';
|
||||
import {Result} from '../Utils/Result';
|
||||
|
||||
/**
|
||||
* Validates that functions with known mutations (ie due to types) cannot be passed
|
||||
@@ -43,9 +42,7 @@ import {Result} from '../Utils/Result';
|
||||
* This pass detects functions with *known* mutations (Store or Mutate, not ConditionallyMutate)
|
||||
* that are passed where a frozen value is expected and rejects them.
|
||||
*/
|
||||
export function validateNoFreezingKnownMutableFunctions(
|
||||
fn: HIRFunction,
|
||||
): Result<void, CompilerError> {
|
||||
export function validateNoFreezingKnownMutableFunctions(fn: HIRFunction): void {
|
||||
const errors = new CompilerError();
|
||||
const contextMutationEffects: Map<
|
||||
IdentifierId,
|
||||
@@ -162,5 +159,7 @@ export function validateNoFreezingKnownMutableFunctions(
|
||||
visitOperand(operand);
|
||||
}
|
||||
}
|
||||
return errors.asResult();
|
||||
if (errors.hasAnyErrors()) {
|
||||
fn.env.recordErrors(errors);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,7 +9,6 @@ import {CompilerDiagnostic, CompilerError} from '..';
|
||||
import {ErrorCategory} from '../CompilerError';
|
||||
import {HIRFunction} from '../HIR';
|
||||
import {getFunctionCallSignature} from '../Inference/InferMutationAliasingEffects';
|
||||
import {Result} from '../Utils/Result';
|
||||
|
||||
/**
|
||||
* Checks that known-impure functions are not called during render. Examples of invalid functions to
|
||||
@@ -20,9 +19,7 @@ import {Result} from '../Utils/Result';
|
||||
* this in several of our validation passes and should unify those analyses into a reusable helper
|
||||
* and use it here.
|
||||
*/
|
||||
export function validateNoImpureFunctionsInRender(
|
||||
fn: HIRFunction,
|
||||
): Result<void, CompilerError> {
|
||||
export function validateNoImpureFunctionsInRender(fn: HIRFunction): void {
|
||||
const errors = new CompilerError();
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
for (const instr of block.instructions) {
|
||||
@@ -55,5 +52,7 @@ export function validateNoImpureFunctionsInRender(
|
||||
}
|
||||
}
|
||||
}
|
||||
return errors.asResult();
|
||||
if (errors.hasAnyErrors()) {
|
||||
fn.env.recordErrors(errors);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,21 +15,18 @@ import {
|
||||
GeneratedSource,
|
||||
HIRFunction,
|
||||
IdentifierId,
|
||||
Identifier,
|
||||
Place,
|
||||
SourceLocation,
|
||||
getHookKindForType,
|
||||
isRefValueType,
|
||||
isUseRefType,
|
||||
} from '../HIR';
|
||||
import {BuiltInEventHandlerId} from '../HIR/ObjectShape';
|
||||
import {
|
||||
eachInstructionOperand,
|
||||
eachInstructionValueOperand,
|
||||
eachPatternOperand,
|
||||
eachTerminalOperand,
|
||||
} from '../HIR/visitors';
|
||||
import {Err, Ok, Result} from '../Utils/Result';
|
||||
import {retainWhere} from '../Utils/utils';
|
||||
|
||||
/**
|
||||
@@ -122,12 +119,14 @@ class Env {
|
||||
}
|
||||
}
|
||||
|
||||
export function validateNoRefAccessInRender(
|
||||
fn: HIRFunction,
|
||||
): Result<void, CompilerError> {
|
||||
export function validateNoRefAccessInRender(fn: HIRFunction): void {
|
||||
const env = new Env();
|
||||
collectTemporariesSidemap(fn, env);
|
||||
return validateNoRefAccessInRenderImpl(fn, env).map(_ => undefined);
|
||||
const errors = new CompilerError();
|
||||
validateNoRefAccessInRenderImpl(fn, env, errors);
|
||||
if (errors.hasAnyErrors()) {
|
||||
fn.env.recordErrors(errors);
|
||||
}
|
||||
}
|
||||
|
||||
function collectTemporariesSidemap(fn: HIRFunction, env: Env): void {
|
||||
@@ -178,11 +177,6 @@ function refTypeOfType(place: Place): RefAccessType {
|
||||
}
|
||||
}
|
||||
|
||||
function isEventHandlerType(identifier: Identifier): boolean {
|
||||
const type = identifier.type;
|
||||
return type.kind === 'Function' && type.shapeId === BuiltInEventHandlerId;
|
||||
}
|
||||
|
||||
function tyEqual(a: RefAccessType, b: RefAccessType): boolean {
|
||||
if (a.kind !== b.kind) {
|
||||
return false;
|
||||
@@ -312,7 +306,8 @@ function joinRefAccessTypes(...types: Array<RefAccessType>): RefAccessType {
|
||||
function validateNoRefAccessInRenderImpl(
|
||||
fn: HIRFunction,
|
||||
env: Env,
|
||||
): Result<RefAccessType, CompilerError> {
|
||||
errors: CompilerError,
|
||||
): RefAccessType {
|
||||
let returnValues: Array<undefined | RefAccessType> = [];
|
||||
let place;
|
||||
for (const param of fn.params) {
|
||||
@@ -343,7 +338,6 @@ function validateNoRefAccessInRenderImpl(
|
||||
env.resetChanged();
|
||||
returnValues = [];
|
||||
const safeBlocks: Array<{block: BlockId; ref: RefId}> = [];
|
||||
const errors = new CompilerError();
|
||||
for (const [, block] of fn.body.blocks) {
|
||||
retainWhere(safeBlocks, entry => entry.block !== block.id);
|
||||
for (const phi of block.phis) {
|
||||
@@ -439,13 +433,15 @@ function validateNoRefAccessInRenderImpl(
|
||||
case 'FunctionExpression': {
|
||||
let returnType: RefAccessType = {kind: 'None'};
|
||||
let readRefEffect = false;
|
||||
const innerErrors = new CompilerError();
|
||||
const result = validateNoRefAccessInRenderImpl(
|
||||
instr.value.loweredFunc.func,
|
||||
env,
|
||||
innerErrors,
|
||||
);
|
||||
if (result.isOk()) {
|
||||
returnType = result.unwrap();
|
||||
} else if (result.isErr()) {
|
||||
if (!innerErrors.hasAnyErrors()) {
|
||||
returnType = result;
|
||||
} else {
|
||||
readRefEffect = true;
|
||||
}
|
||||
env.set(instr.lvalue.identifier.id, {
|
||||
@@ -491,9 +487,6 @@ function validateNoRefAccessInRenderImpl(
|
||||
*/
|
||||
if (!didError) {
|
||||
const isRefLValue = isUseRefType(instr.lvalue.identifier);
|
||||
const isEventHandlerLValue = isEventHandlerType(
|
||||
instr.lvalue.identifier,
|
||||
);
|
||||
for (const operand of eachInstructionValueOperand(instr.value)) {
|
||||
/**
|
||||
* By default we check that function call operands are not refs,
|
||||
@@ -501,7 +494,6 @@ function validateNoRefAccessInRenderImpl(
|
||||
*/
|
||||
if (
|
||||
isRefLValue ||
|
||||
isEventHandlerLValue ||
|
||||
(hookKind != null &&
|
||||
hookKind !== 'useState' &&
|
||||
hookKind !== 'useReducer')
|
||||
@@ -509,8 +501,7 @@ function validateNoRefAccessInRenderImpl(
|
||||
/**
|
||||
* Allow passing refs or ref-accessing functions when:
|
||||
* 1. lvalue is a ref (mergeRefs pattern: `mergeRefs(ref1, ref2)`)
|
||||
* 2. lvalue is an event handler (DOM events execute outside render)
|
||||
* 3. calling hooks (independently validated for ref safety)
|
||||
* 2. calling hooks (independently validated for ref safety)
|
||||
*/
|
||||
validateNoDirectRefValueAccess(errors, operand, env);
|
||||
} else if (interpolatedAsJsx.has(instr.lvalue.identifier.id)) {
|
||||
@@ -741,7 +732,7 @@ function validateNoRefAccessInRenderImpl(
|
||||
}
|
||||
|
||||
if (errors.hasAnyErrors()) {
|
||||
return Err(errors);
|
||||
return {kind: 'None'};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -750,10 +741,8 @@ function validateNoRefAccessInRenderImpl(
|
||||
loc: GeneratedSource,
|
||||
});
|
||||
|
||||
return Ok(
|
||||
joinRefAccessTypes(
|
||||
...returnValues.filter((env): env is RefAccessType => env !== undefined),
|
||||
),
|
||||
return joinRefAccessTypes(
|
||||
...returnValues.filter((env): env is RefAccessType => env !== undefined),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
import {HIRFunction, IdentifierId, isSetStateType} from '../HIR';
|
||||
import {computeUnconditionalBlocks} from '../HIR/ComputeUnconditionalBlocks';
|
||||
import {eachInstructionValueOperand} from '../HIR/visitors';
|
||||
import {Result} from '../Utils/Result';
|
||||
|
||||
/**
|
||||
* Validates that the given function does not have an infinite update loop
|
||||
@@ -43,17 +42,21 @@ import {Result} from '../Utils/Result';
|
||||
* y();
|
||||
* ```
|
||||
*/
|
||||
export function validateNoSetStateInRender(
|
||||
fn: HIRFunction,
|
||||
): Result<void, CompilerError> {
|
||||
export function validateNoSetStateInRender(fn: HIRFunction): void {
|
||||
const unconditionalSetStateFunctions: Set<IdentifierId> = new Set();
|
||||
return validateNoSetStateInRenderImpl(fn, unconditionalSetStateFunctions);
|
||||
const errors = validateNoSetStateInRenderImpl(
|
||||
fn,
|
||||
unconditionalSetStateFunctions,
|
||||
);
|
||||
if (errors.hasAnyErrors()) {
|
||||
fn.env.recordErrors(errors);
|
||||
}
|
||||
}
|
||||
|
||||
function validateNoSetStateInRenderImpl(
|
||||
fn: HIRFunction,
|
||||
unconditionalSetStateFunctions: Set<IdentifierId>,
|
||||
): Result<void, CompilerError> {
|
||||
): CompilerError {
|
||||
const unconditionalBlocks = computeUnconditionalBlocks(fn);
|
||||
let activeManualMemoId: number | null = null;
|
||||
const errors = new CompilerError();
|
||||
@@ -92,7 +95,7 @@ function validateNoSetStateInRenderImpl(
|
||||
validateNoSetStateInRenderImpl(
|
||||
instr.value.loweredFunc.func,
|
||||
unconditionalSetStateFunctions,
|
||||
).isErr()
|
||||
).hasAnyErrors()
|
||||
) {
|
||||
// This function expression unconditionally calls a setState
|
||||
unconditionalSetStateFunctions.add(instr.lvalue.identifier.id);
|
||||
@@ -183,5 +186,5 @@ function validateNoSetStateInRenderImpl(
|
||||
}
|
||||
}
|
||||
|
||||
return errors.asResult();
|
||||
return errors;
|
||||
}
|
||||
|
||||
@@ -37,7 +37,6 @@ import {
|
||||
ReactiveFunctionVisitor,
|
||||
visitReactiveFunction,
|
||||
} from '../ReactiveScopes/visitors';
|
||||
import {Result} from '../Utils/Result';
|
||||
import {getOrInsertDefault} from '../Utils/utils';
|
||||
|
||||
/**
|
||||
@@ -47,15 +46,15 @@ import {getOrInsertDefault} from '../Utils/utils';
|
||||
* This can occur if a value's mutable range somehow extended to include a hook and
|
||||
* was pruned.
|
||||
*/
|
||||
export function validatePreservedManualMemoization(
|
||||
fn: ReactiveFunction,
|
||||
): Result<void, CompilerError> {
|
||||
export function validatePreservedManualMemoization(fn: ReactiveFunction): void {
|
||||
const state = {
|
||||
errors: new CompilerError(),
|
||||
manualMemoState: null,
|
||||
};
|
||||
visitReactiveFunction(fn, new Visitor(), state);
|
||||
return state.errors.asResult();
|
||||
for (const detail of state.errors.details) {
|
||||
fn.env.recordError(detail);
|
||||
}
|
||||
}
|
||||
|
||||
const DEBUG = false;
|
||||
|
||||
@@ -9,7 +9,7 @@ import {NodePath} from '@babel/traverse';
|
||||
import * as t from '@babel/types';
|
||||
import {CompilerDiagnostic, CompilerError, ErrorCategory} from '..';
|
||||
import {CodegenFunction} from '../ReactiveScopes';
|
||||
import {Result} from '../Utils/Result';
|
||||
import {Environment} from '../HIR/Environment';
|
||||
|
||||
/**
|
||||
* IMPORTANT: This validation is only intended for use in unit tests.
|
||||
@@ -123,7 +123,8 @@ export function validateSourceLocations(
|
||||
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
|
||||
>,
|
||||
generatedAst: CodegenFunction,
|
||||
): Result<void, CompilerError> {
|
||||
env: Environment,
|
||||
): void {
|
||||
const errors = new CompilerError();
|
||||
|
||||
/*
|
||||
@@ -309,5 +310,7 @@ export function validateSourceLocations(
|
||||
}
|
||||
}
|
||||
|
||||
return errors.asResult();
|
||||
for (const detail of errors.details) {
|
||||
env.recordError(detail);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,9 +20,8 @@ import {
|
||||
eachInstructionValueOperand,
|
||||
eachTerminalOperand,
|
||||
} from '../HIR/visitors';
|
||||
import {Result} from '../Utils/Result';
|
||||
|
||||
export function validateUseMemo(fn: HIRFunction): Result<void, CompilerError> {
|
||||
export function validateUseMemo(fn: HIRFunction): void {
|
||||
const errors = new CompilerError();
|
||||
const voidMemoErrors = new CompilerError();
|
||||
const useMemos = new Set<IdentifierId>();
|
||||
@@ -177,7 +176,9 @@ export function validateUseMemo(fn: HIRFunction): Result<void, CompilerError> {
|
||||
}
|
||||
}
|
||||
fn.env.logErrors(voidMemoErrors.asResult());
|
||||
return errors.asResult();
|
||||
if (errors.hasAnyErrors()) {
|
||||
fn.env.recordErrors(errors);
|
||||
}
|
||||
}
|
||||
|
||||
function validateNoContextVariableAssignment(
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
|
||||
export {validateContextVariableLValues} from './ValidateContextVariableLValues';
|
||||
export {validateHooksUsage} from './ValidateHooksUsage';
|
||||
export {validateMemoizedEffectDependencies} from './ValidateMemoizedEffectDependencies';
|
||||
export {validateNoCapitalizedCalls} from './ValidateNoCapitalizedCalls';
|
||||
export {validateNoRefAccessInRender} from './ValidateNoRefAccessInRender';
|
||||
export {validateNoSetStateInRender} from './ValidateNoSetStateInRender';
|
||||
|
||||
@@ -24,24 +24,6 @@ describe('parseConfigPragma()', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('effect autodeps config must have at least 1 required argument', () => {
|
||||
expect(() => {
|
||||
validateEnvironmentConfig({
|
||||
inferEffectDependencies: [
|
||||
{
|
||||
function: {
|
||||
source: 'react',
|
||||
importSpecifierName: 'useEffect',
|
||||
},
|
||||
autodepsIndex: 0,
|
||||
},
|
||||
],
|
||||
} as any);
|
||||
}).toThrowErrorMatchingInlineSnapshot(
|
||||
`"Error: Could not validate environment config. Update React Compiler config to fix the error. Validation error: AutodepsIndex must be > 0 at "inferEffectDependencies[0].autodepsIndex"."`,
|
||||
);
|
||||
});
|
||||
|
||||
it('can parse stringy enums', () => {
|
||||
const stringyHook = {
|
||||
effectKind: 'freeze',
|
||||
|
||||
@@ -1,148 +0,0 @@
|
||||
|
||||
## Input
|
||||
|
||||
```javascript
|
||||
// @enableInferEventHandlers
|
||||
import {useRef} from 'react';
|
||||
|
||||
// Simulates react-hook-form's handleSubmit
|
||||
function handleSubmit<T>(callback: (data: T) => void | Promise<void>) {
|
||||
return (event: any) => {
|
||||
event.preventDefault();
|
||||
callback({} as T);
|
||||
};
|
||||
}
|
||||
|
||||
// Simulates an upload function
|
||||
async function upload(file: any): Promise<{blob: {url: string}}> {
|
||||
return {blob: {url: 'https://example.com/file.jpg'}};
|
||||
}
|
||||
|
||||
interface SignatureRef {
|
||||
toFile(): any;
|
||||
}
|
||||
|
||||
function Component() {
|
||||
const ref = useRef<SignatureRef>(null);
|
||||
|
||||
const onSubmit = async (value: any) => {
|
||||
// This should be allowed: accessing ref.current in an async event handler
|
||||
// that's wrapped and passed to onSubmit prop
|
||||
let sigUrl: string;
|
||||
if (value.hasSignature) {
|
||||
const {blob} = await upload(ref.current?.toFile());
|
||||
sigUrl = blob?.url || '';
|
||||
} else {
|
||||
sigUrl = value.signature;
|
||||
}
|
||||
console.log('Signature URL:', sigUrl);
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<input type="text" name="signature" />
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export const FIXTURE_ENTRYPOINT = {
|
||||
fn: Component,
|
||||
params: [{}],
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
## Code
|
||||
|
||||
```javascript
|
||||
import { c as _c } from "react/compiler-runtime"; // @enableInferEventHandlers
|
||||
import { useRef } from "react";
|
||||
|
||||
// Simulates react-hook-form's handleSubmit
|
||||
function handleSubmit(callback) {
|
||||
const $ = _c(2);
|
||||
let t0;
|
||||
if ($[0] !== callback) {
|
||||
t0 = (event) => {
|
||||
event.preventDefault();
|
||||
callback({} as T);
|
||||
};
|
||||
$[0] = callback;
|
||||
$[1] = t0;
|
||||
} else {
|
||||
t0 = $[1];
|
||||
}
|
||||
return t0;
|
||||
}
|
||||
|
||||
// Simulates an upload function
|
||||
async function upload(file) {
|
||||
const $ = _c(1);
|
||||
let t0;
|
||||
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
|
||||
t0 = { blob: { url: "https://example.com/file.jpg" } };
|
||||
$[0] = t0;
|
||||
} else {
|
||||
t0 = $[0];
|
||||
}
|
||||
return t0;
|
||||
}
|
||||
|
||||
interface SignatureRef {
|
||||
toFile(): any;
|
||||
}
|
||||
|
||||
function Component() {
|
||||
const $ = _c(4);
|
||||
const ref = useRef(null);
|
||||
|
||||
const onSubmit = async (value) => {
|
||||
let sigUrl;
|
||||
if (value.hasSignature) {
|
||||
const { blob } = await upload(ref.current?.toFile());
|
||||
sigUrl = blob?.url || "";
|
||||
} else {
|
||||
sigUrl = value.signature;
|
||||
}
|
||||
|
||||
console.log("Signature URL:", sigUrl);
|
||||
};
|
||||
|
||||
const t0 = handleSubmit(onSubmit);
|
||||
let t1;
|
||||
let t2;
|
||||
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
|
||||
t1 = <input type="text" name="signature" />;
|
||||
t2 = <button type="submit">Submit</button>;
|
||||
$[0] = t1;
|
||||
$[1] = t2;
|
||||
} else {
|
||||
t1 = $[0];
|
||||
t2 = $[1];
|
||||
}
|
||||
let t3;
|
||||
if ($[2] !== t0) {
|
||||
t3 = (
|
||||
<form onSubmit={t0}>
|
||||
{t1}
|
||||
{t2}
|
||||
</form>
|
||||
);
|
||||
$[2] = t0;
|
||||
$[3] = t3;
|
||||
} else {
|
||||
t3 = $[3];
|
||||
}
|
||||
return t3;
|
||||
}
|
||||
|
||||
export const FIXTURE_ENTRYPOINT = {
|
||||
fn: Component,
|
||||
params: [{}],
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
### Eval output
|
||||
(kind: ok) <form><input type="text" name="signature"><button type="submit">Submit</button></form>
|
||||
@@ -1,48 +0,0 @@
|
||||
// @enableInferEventHandlers
|
||||
import {useRef} from 'react';
|
||||
|
||||
// Simulates react-hook-form's handleSubmit
|
||||
function handleSubmit<T>(callback: (data: T) => void | Promise<void>) {
|
||||
return (event: any) => {
|
||||
event.preventDefault();
|
||||
callback({} as T);
|
||||
};
|
||||
}
|
||||
|
||||
// Simulates an upload function
|
||||
async function upload(file: any): Promise<{blob: {url: string}}> {
|
||||
return {blob: {url: 'https://example.com/file.jpg'}};
|
||||
}
|
||||
|
||||
interface SignatureRef {
|
||||
toFile(): any;
|
||||
}
|
||||
|
||||
function Component() {
|
||||
const ref = useRef<SignatureRef>(null);
|
||||
|
||||
const onSubmit = async (value: any) => {
|
||||
// This should be allowed: accessing ref.current in an async event handler
|
||||
// that's wrapped and passed to onSubmit prop
|
||||
let sigUrl: string;
|
||||
if (value.hasSignature) {
|
||||
const {blob} = await upload(ref.current?.toFile());
|
||||
sigUrl = blob?.url || '';
|
||||
} else {
|
||||
sigUrl = value.signature;
|
||||
}
|
||||
console.log('Signature URL:', sigUrl);
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<input type="text" name="signature" />
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
|
||||
export const FIXTURE_ENTRYPOINT = {
|
||||
fn: Component,
|
||||
params: [{}],
|
||||
};
|
||||
@@ -1,100 +0,0 @@
|
||||
|
||||
## Input
|
||||
|
||||
```javascript
|
||||
// @enableInferEventHandlers
|
||||
import {useRef} from 'react';
|
||||
|
||||
// Simulates react-hook-form's handleSubmit or similar event handler wrappers
|
||||
function handleSubmit<T>(callback: (data: T) => void) {
|
||||
return (event: any) => {
|
||||
event.preventDefault();
|
||||
callback({} as T);
|
||||
};
|
||||
}
|
||||
|
||||
function Component() {
|
||||
const ref = useRef<HTMLInputElement>(null);
|
||||
|
||||
const onSubmit = (data: any) => {
|
||||
// This should be allowed: accessing ref.current in an event handler
|
||||
// that's wrapped by handleSubmit and passed to onSubmit prop
|
||||
if (ref.current !== null) {
|
||||
console.log(ref.current.value);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<input ref={ref} />
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const FIXTURE_ENTRYPOINT = {
|
||||
fn: Component,
|
||||
params: [{}],
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
## Code
|
||||
|
||||
```javascript
|
||||
import { c as _c } from "react/compiler-runtime"; // @enableInferEventHandlers
|
||||
import { useRef } from "react";
|
||||
|
||||
// Simulates react-hook-form's handleSubmit or similar event handler wrappers
|
||||
function handleSubmit(callback) {
|
||||
const $ = _c(2);
|
||||
let t0;
|
||||
if ($[0] !== callback) {
|
||||
t0 = (event) => {
|
||||
event.preventDefault();
|
||||
callback({} as T);
|
||||
};
|
||||
$[0] = callback;
|
||||
$[1] = t0;
|
||||
} else {
|
||||
t0 = $[1];
|
||||
}
|
||||
return t0;
|
||||
}
|
||||
|
||||
function Component() {
|
||||
const $ = _c(1);
|
||||
const ref = useRef(null);
|
||||
let t0;
|
||||
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
|
||||
const onSubmit = (data) => {
|
||||
if (ref.current !== null) {
|
||||
console.log(ref.current.value);
|
||||
}
|
||||
};
|
||||
t0 = (
|
||||
<>
|
||||
<input ref={ref} />
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
$[0] = t0;
|
||||
} else {
|
||||
t0 = $[0];
|
||||
}
|
||||
return t0;
|
||||
}
|
||||
|
||||
export const FIXTURE_ENTRYPOINT = {
|
||||
fn: Component,
|
||||
params: [{}],
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
### Eval output
|
||||
(kind: ok) <input><form><button type="submit">Submit</button></form>
|
||||
@@ -1,36 +0,0 @@
|
||||
// @enableInferEventHandlers
|
||||
import {useRef} from 'react';
|
||||
|
||||
// Simulates react-hook-form's handleSubmit or similar event handler wrappers
|
||||
function handleSubmit<T>(callback: (data: T) => void) {
|
||||
return (event: any) => {
|
||||
event.preventDefault();
|
||||
callback({} as T);
|
||||
};
|
||||
}
|
||||
|
||||
function Component() {
|
||||
const ref = useRef<HTMLInputElement>(null);
|
||||
|
||||
const onSubmit = (data: any) => {
|
||||
// This should be allowed: accessing ref.current in an event handler
|
||||
// that's wrapped by handleSubmit and passed to onSubmit prop
|
||||
if (ref.current !== null) {
|
||||
console.log(ref.current.value);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<input ref={ref} />
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
<button type="submit">Submit</button>
|
||||
</form>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export const FIXTURE_ENTRYPOINT = {
|
||||
fn: Component,
|
||||
params: [{}],
|
||||
};
|
||||
@@ -1,53 +0,0 @@
|
||||
|
||||
## Input
|
||||
|
||||
```javascript
|
||||
// @validateNoCapitalizedCalls @hookPattern:".*\b(use[^$]+)$"
|
||||
import * as React from 'react';
|
||||
const React$useState = React.useState;
|
||||
const THIS_IS_A_CONSTANT = () => {};
|
||||
function Component() {
|
||||
const b = Boolean(true); // OK
|
||||
const n = Number(3); // OK
|
||||
const s = String('foo'); // OK
|
||||
const [state, setState] = React$useState(0); // OK
|
||||
const [state2, setState2] = React.useState(1); // OK
|
||||
const constant = THIS_IS_A_CONSTANT(); // OK
|
||||
return 3;
|
||||
}
|
||||
|
||||
export const FIXTURE_ENTRYPOINT = {
|
||||
fn: Component,
|
||||
params: [],
|
||||
isComponent: true,
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
## Code
|
||||
|
||||
```javascript
|
||||
// @validateNoCapitalizedCalls @hookPattern:".*\b(use[^$]+)$"
|
||||
import * as React from "react";
|
||||
const React$useState = React.useState;
|
||||
const THIS_IS_A_CONSTANT = () => {};
|
||||
function Component() {
|
||||
Boolean(true);
|
||||
Number(3);
|
||||
String("foo");
|
||||
React$useState(0);
|
||||
React.useState(1);
|
||||
THIS_IS_A_CONSTANT();
|
||||
return 3;
|
||||
}
|
||||
|
||||
export const FIXTURE_ENTRYPOINT = {
|
||||
fn: Component,
|
||||
params: [],
|
||||
isComponent: true,
|
||||
};
|
||||
|
||||
```
|
||||
|
||||
### Eval output
|
||||
(kind: ok) 3
|
||||
@@ -1,19 +0,0 @@
|
||||
// @validateNoCapitalizedCalls @hookPattern:".*\b(use[^$]+)$"
|
||||
import * as React from 'react';
|
||||
const React$useState = React.useState;
|
||||
const THIS_IS_A_CONSTANT = () => {};
|
||||
function Component() {
|
||||
const b = Boolean(true); // OK
|
||||
const n = Number(3); // OK
|
||||
const s = String('foo'); // OK
|
||||
const [state, setState] = React$useState(0); // OK
|
||||
const [state2, setState2] = React.useState(1); // OK
|
||||
const constant = THIS_IS_A_CONSTANT(); // OK
|
||||
return 3;
|
||||
}
|
||||
|
||||
export const FIXTURE_ENTRYPOINT = {
|
||||
fn: Component,
|
||||
params: [],
|
||||
isComponent: true,
|
||||
};
|
||||
@@ -1,49 +0,0 @@
|
||||
|
||||
## Input
|
||||
|
||||
```javascript
|
||||
// @enableChangeDetectionForDebugging
|
||||
function Component(props) {
|
||||
let x = null;
|
||||
if (props.cond) {
|
||||
x = [];
|
||||
x.push(props.value);
|
||||
}
|
||||
return x;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Code
|
||||
|
||||
```javascript
|
||||
import { $structuralCheck } from "react-compiler-runtime";
|
||||
import { c as _c } from "react/compiler-runtime"; // @enableChangeDetectionForDebugging
|
||||
function Component(props) {
|
||||
const $ = _c(2);
|
||||
let x = null;
|
||||
if (props.cond) {
|
||||
{
|
||||
x = [];
|
||||
x.push(props.value);
|
||||
let condition = $[0] !== props.value;
|
||||
if (!condition) {
|
||||
let old$x = $[1];
|
||||
$structuralCheck(old$x, x, "x", "Component", "cached", "(3:6)");
|
||||
}
|
||||
$[0] = props.value;
|
||||
$[1] = x;
|
||||
if (condition) {
|
||||
x = [];
|
||||
x.push(props.value);
|
||||
$structuralCheck($[1], x, "x", "Component", "recomputed", "(3:6)");
|
||||
x = $[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return x;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
// @enableChangeDetectionForDebugging
|
||||
function Component(props) {
|
||||
let x = null;
|
||||
if (props.cond) {
|
||||
x = [];
|
||||
x.push(props.value);
|
||||
}
|
||||
return x;
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
|
||||
## Input
|
||||
|
||||
```javascript
|
||||
// @enableEmitFreeze @enableEmitInstrumentForget
|
||||
|
||||
function useFoo(props) {
|
||||
return foo(props.x);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Code
|
||||
|
||||
```javascript
|
||||
import {
|
||||
makeReadOnly,
|
||||
shouldInstrument,
|
||||
useRenderCounter,
|
||||
} from "react-compiler-runtime";
|
||||
import { c as _c } from "react/compiler-runtime"; // @enableEmitFreeze @enableEmitInstrumentForget
|
||||
|
||||
function useFoo(props) {
|
||||
if (DEV && shouldInstrument)
|
||||
useRenderCounter("useFoo", "/codegen-emit-imports-same-source.ts");
|
||||
const $ = _c(2);
|
||||
let t0;
|
||||
if ($[0] !== props.x) {
|
||||
t0 = foo(props.x);
|
||||
$[0] = props.x;
|
||||
$[1] = __DEV__ ? makeReadOnly(t0, "useFoo") : t0;
|
||||
} else {
|
||||
t0 = $[1];
|
||||
}
|
||||
return t0;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
// @enableEmitFreeze @enableEmitInstrumentForget
|
||||
|
||||
function useFoo(props) {
|
||||
return foo(props.x);
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
|
||||
## Input
|
||||
|
||||
```javascript
|
||||
// @enableEmitFreeze true
|
||||
|
||||
function MyComponentName(props) {
|
||||
let x = {};
|
||||
foo(x, props.a);
|
||||
foo(x, props.b);
|
||||
|
||||
let y = [];
|
||||
y.push(x);
|
||||
return y;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Code
|
||||
|
||||
```javascript
|
||||
import { makeReadOnly } from "react-compiler-runtime";
|
||||
import { c as _c } from "react/compiler-runtime"; // @enableEmitFreeze true
|
||||
|
||||
function MyComponentName(props) {
|
||||
const $ = _c(3);
|
||||
let y;
|
||||
if ($[0] !== props.a || $[1] !== props.b) {
|
||||
const x = {};
|
||||
foo(x, props.a);
|
||||
foo(x, props.b);
|
||||
y = [];
|
||||
y.push(x);
|
||||
$[0] = props.a;
|
||||
$[1] = props.b;
|
||||
$[2] = __DEV__ ? makeReadOnly(y, "MyComponentName") : y;
|
||||
} else {
|
||||
y = $[2];
|
||||
}
|
||||
return y;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
// @enableEmitFreeze true
|
||||
|
||||
function MyComponentName(props) {
|
||||
let x = {};
|
||||
foo(x, props.a);
|
||||
foo(x, props.b);
|
||||
|
||||
let y = [];
|
||||
y.push(x);
|
||||
return y;
|
||||
}
|
||||
@@ -24,18 +24,9 @@ function useThing(fn) {
|
||||
```
|
||||
Found 1 error:
|
||||
|
||||
Compilation Skipped: `this` is not supported syntax
|
||||
Invariant: [HIRBuilder] Unexpected null block
|
||||
|
||||
React Compiler does not support compiling functions that use `this`.
|
||||
|
||||
error.reserved-words.ts:8:28
|
||||
6 |
|
||||
7 | if (ref.current === null) {
|
||||
> 8 | ref.current = function (this: unknown, ...args) {
|
||||
| ^^^^^^^^^^^^^ `this` was used here
|
||||
9 | return fnRef.current.call(this, ...args);
|
||||
10 | };
|
||||
11 | }
|
||||
expected block 0 to exist.
|
||||
```
|
||||
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
|
||||
## Input
|
||||
|
||||
```javascript
|
||||
// @enableEmitFreeze @instrumentForget
|
||||
|
||||
let makeReadOnly = 'conflicting identifier';
|
||||
function useFoo(props) {
|
||||
return foo(props.x);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Code
|
||||
|
||||
```javascript
|
||||
import { makeReadOnly as _makeReadOnly } from "react-compiler-runtime";
|
||||
import { c as _c } from "react/compiler-runtime"; // @enableEmitFreeze @instrumentForget
|
||||
|
||||
let makeReadOnly = "conflicting identifier";
|
||||
function useFoo(props) {
|
||||
const $ = _c(2);
|
||||
let t0;
|
||||
if ($[0] !== props.x) {
|
||||
t0 = foo(props.x);
|
||||
$[0] = props.x;
|
||||
$[1] = __DEV__ ? _makeReadOnly(t0, "useFoo") : t0;
|
||||
} else {
|
||||
t0 = $[1];
|
||||
}
|
||||
return t0;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Eval output
|
||||
(kind: exception) Fixture not implemented
|
||||
@@ -1,6 +0,0 @@
|
||||
// @enableEmitFreeze @instrumentForget
|
||||
|
||||
let makeReadOnly = 'conflicting identifier';
|
||||
function useFoo(props) {
|
||||
return foo(props.x);
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
|
||||
## Input
|
||||
|
||||
```javascript
|
||||
// @enableEmitFreeze @instrumentForget
|
||||
function useFoo(props) {
|
||||
return foo(props.x, __DEV__);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
## Code
|
||||
|
||||
```javascript
|
||||
import { makeReadOnly } from "react-compiler-runtime";
|
||||
import { c as _c } from "react/compiler-runtime"; // @enableEmitFreeze @instrumentForget
|
||||
function useFoo(props) {
|
||||
const $ = _c(2);
|
||||
let t0;
|
||||
if ($[0] !== props.x) {
|
||||
t0 = foo(props.x, __DEV__);
|
||||
$[0] = props.x;
|
||||
$[1] = __DEV__ ? makeReadOnly(t0, "useFoo") : t0;
|
||||
} else {
|
||||
t0 = $[1];
|
||||
}
|
||||
return t0;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
### Eval output
|
||||
(kind: exception) Fixture not implemented
|
||||
@@ -1,4 +0,0 @@
|
||||
// @enableEmitFreeze @instrumentForget
|
||||
function useFoo(props) {
|
||||
return foo(props.x, __DEV__);
|
||||
}
|
||||
@@ -17,16 +17,17 @@ function Component(props) {
|
||||
```
|
||||
Found 1 error:
|
||||
|
||||
Todo: (BuildHIR::lowerAssignment) Handle computed properties in ObjectPattern
|
||||
Invariant: [InferMutationAliasingEffects] Expected value kind to be initialized
|
||||
|
||||
error._todo.computed-lval-in-destructure.ts:3:9
|
||||
1 | function Component(props) {
|
||||
2 | const computedKey = props.key;
|
||||
> 3 | const {[computedKey]: x} = props.val;
|
||||
| ^^^^^^^^^^^^^^^^ (BuildHIR::lowerAssignment) Handle computed properties in ObjectPattern
|
||||
<unknown> x$8.
|
||||
|
||||
error._todo.computed-lval-in-destructure.ts:5:9
|
||||
3 | const {[computedKey]: x} = props.val;
|
||||
4 |
|
||||
5 | return x;
|
||||
> 5 | return x;
|
||||
| ^ this is uninitialized
|
||||
6 | }
|
||||
7 |
|
||||
```
|
||||
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
|
||||
## Input
|
||||
|
||||
```javascript
|
||||
// @enableEmitFreeze @instrumentForget
|
||||
function useFoo(props) {
|
||||
const __DEV__ = 'conflicting global';
|
||||
console.log(__DEV__);
|
||||
return foo(props.x);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
## Error
|
||||
|
||||
```
|
||||
Found 1 error:
|
||||
|
||||
Todo: Encountered conflicting global in generated program
|
||||
|
||||
Conflict from local binding __DEV__.
|
||||
|
||||
error.emit-freeze-conflicting-global.ts:3:8
|
||||
1 | // @enableEmitFreeze @instrumentForget
|
||||
2 | function useFoo(props) {
|
||||
> 3 | const __DEV__ = 'conflicting global';
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Encountered conflicting global in generated program
|
||||
4 | console.log(__DEV__);
|
||||
5 | return foo(props.x);
|
||||
6 | }
|
||||
```
|
||||
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
// @enableEmitFreeze @instrumentForget
|
||||
function useFoo(props) {
|
||||
const __DEV__ = 'conflicting global';
|
||||
console.log(__DEV__);
|
||||
return foo(props.x);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
|
||||
## Input
|
||||
|
||||
```javascript
|
||||
// @validateRefAccessDuringRender
|
||||
/**
|
||||
* This fixture tests fault tolerance: the compiler should report
|
||||
* multiple independent errors rather than stopping at the first one.
|
||||
*
|
||||
* Error 1: Ref access during render (ref.current)
|
||||
* Error 2: Mutation of frozen value (props)
|
||||
*/
|
||||
function Component(props) {
|
||||
const ref = useRef(null);
|
||||
|
||||
// Error: reading ref during render
|
||||
const value = ref.current;
|
||||
|
||||
// Error: mutating frozen value (props, which is frozen after hook call)
|
||||
props.items = [];
|
||||
|
||||
return <div>{value}</div>;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
## Error
|
||||
|
||||
```
|
||||
Found 2 errors:
|
||||
|
||||
Error: This value cannot be modified
|
||||
|
||||
Modifying component props or hook arguments is not allowed. Consider using a local variable instead.
|
||||
|
||||
error.fault-tolerance-reports-multiple-errors.ts:16:2
|
||||
14 |
|
||||
15 | // Error: mutating frozen value (props, which is frozen after hook call)
|
||||
> 16 | props.items = [];
|
||||
| ^^^^^ value cannot be modified
|
||||
17 |
|
||||
18 | return <div>{value}</div>;
|
||||
19 | }
|
||||
|
||||
Error: Cannot access refs during render
|
||||
|
||||
React refs are values that are not needed for rendering. Refs should only be accessed outside of render, such as in event handlers or effects. Accessing a ref value (the `current` property) during render can cause your component not to update as expected (https://react.dev/reference/react/useRef).
|
||||
|
||||
error.fault-tolerance-reports-multiple-errors.ts:13:16
|
||||
11 |
|
||||
12 | // Error: reading ref during render
|
||||
> 13 | const value = ref.current;
|
||||
| ^^^^^^^^^^^ Cannot access ref value during render
|
||||
14 |
|
||||
15 | // Error: mutating frozen value (props, which is frozen after hook call)
|
||||
16 | props.items = [];
|
||||
```
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// @validateRefAccessDuringRender
|
||||
/**
|
||||
* This fixture tests fault tolerance: the compiler should report
|
||||
* multiple independent errors rather than stopping at the first one.
|
||||
*
|
||||
* Error 1: Ref access during render (ref.current)
|
||||
* Error 2: Mutation of frozen value (props)
|
||||
*/
|
||||
function Component(props) {
|
||||
const ref = useRef(null);
|
||||
|
||||
// Error: reading ref during render
|
||||
const value = ref.current;
|
||||
|
||||
// Error: mutating frozen value (props, which is frozen after hook call)
|
||||
props.items = [];
|
||||
|
||||
return <div>{value}</div>;
|
||||
}
|
||||
@@ -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;
|
||||
```
|
||||
|
||||
|
||||
@@ -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 |
|
||||
```
|
||||
|
||||
|
||||
@@ -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]`
|
||||
```
|
||||
|
||||
|
||||
@@ -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 | }
|
||||
```
|
||||
|
||||
|
||||
@@ -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 |
|
||||
```
|
||||
|
||||
|
||||
@@ -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 => {
|
||||
```
|
||||
|
||||
|
||||
@@ -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 => {
|
||||
```
|
||||
|
||||
|
||||
@@ -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 => {
|
||||
```
|
||||
|
||||
|
||||
@@ -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]`
|
||||
```
|
||||
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
|
||||
## Input
|
||||
|
||||
```javascript
|
||||
// @validateMemoizedEffectDependencies
|
||||
function Component(props) {
|
||||
// Items cannot be memoized bc its mutation spans a hook call
|
||||
const items = [props.value];
|
||||
const [state, _setState] = useState(null);
|
||||
mutate(items);
|
||||
|
||||
// Items is no longer mutable here, but it hasn't been memoized
|
||||
useEffect(() => {
|
||||
console.log(items);
|
||||
}, [items]);
|
||||
|
||||
return [items, state];
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
## Error
|
||||
|
||||
```
|
||||
Found 1 error:
|
||||
|
||||
Compilation Skipped: React Compiler has skipped optimizing this component because the effect dependencies could not be memoized. Unmemoized effect dependencies can trigger an infinite loop or other unexpected behavior
|
||||
|
||||
error.invalid-useEffect-dep-not-memoized-bc-range-overlaps-hook.ts:9:2
|
||||
7 |
|
||||
8 | // Items is no longer mutable here, but it hasn't been memoized
|
||||
> 9 | useEffect(() => {
|
||||
| ^^^^^^^^^^^^^^^^^
|
||||
> 10 | console.log(items);
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^
|
||||
> 11 | }, [items]);
|
||||
| ^^^^^^^^^^^^^^ React Compiler has skipped optimizing this component because the effect dependencies could not be memoized. Unmemoized effect dependencies can trigger an infinite loop or other unexpected behavior
|
||||
12 |
|
||||
13 | return [items, state];
|
||||
14 | }
|
||||
```
|
||||
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
// @validateMemoizedEffectDependencies
|
||||
function Component(props) {
|
||||
// Items cannot be memoized bc its mutation spans a hook call
|
||||
const items = [props.value];
|
||||
const [state, _setState] = useState(null);
|
||||
mutate(items);
|
||||
|
||||
// Items is no longer mutable here, but it hasn't been memoized
|
||||
useEffect(() => {
|
||||
console.log(items);
|
||||
}, [items]);
|
||||
|
||||
return [items, state];
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
|
||||
## Input
|
||||
|
||||
```javascript
|
||||
// @validateMemoizedEffectDependencies
|
||||
import {useEffect} from 'react';
|
||||
|
||||
function Component(props) {
|
||||
const data = {};
|
||||
useEffect(() => {
|
||||
console.log(props.value);
|
||||
}, [data]);
|
||||
mutate(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
## Error
|
||||
|
||||
```
|
||||
Found 1 error:
|
||||
|
||||
Compilation Skipped: React Compiler has skipped optimizing this component because the effect dependencies could not be memoized. Unmemoized effect dependencies can trigger an infinite loop or other unexpected behavior
|
||||
|
||||
error.invalid-useEffect-dep-not-memoized.ts:6:2
|
||||
4 | function Component(props) {
|
||||
5 | const data = {};
|
||||
> 6 | useEffect(() => {
|
||||
| ^^^^^^^^^^^^^^^^^
|
||||
> 7 | console.log(props.value);
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
> 8 | }, [data]);
|
||||
| ^^^^^^^^^^^^^ React Compiler has skipped optimizing this component because the effect dependencies could not be memoized. Unmemoized effect dependencies can trigger an infinite loop or other unexpected behavior
|
||||
9 | mutate(data);
|
||||
10 | return data;
|
||||
11 | }
|
||||
```
|
||||
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
// @validateMemoizedEffectDependencies
|
||||
import {useEffect} from 'react';
|
||||
|
||||
function Component(props) {
|
||||
const data = {};
|
||||
useEffect(() => {
|
||||
console.log(props.value);
|
||||
}, [data]);
|
||||
mutate(data);
|
||||
return data;
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
|
||||
## Input
|
||||
|
||||
```javascript
|
||||
// @validateMemoizedEffectDependencies
|
||||
import {useInsertionEffect} from 'react';
|
||||
|
||||
function Component(props) {
|
||||
const data = {};
|
||||
useInsertionEffect(() => {
|
||||
console.log(props.value);
|
||||
}, [data]);
|
||||
mutate(data);
|
||||
return data;
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
|
||||
## Error
|
||||
|
||||
```
|
||||
Found 1 error:
|
||||
|
||||
Compilation Skipped: React Compiler has skipped optimizing this component because the effect dependencies could not be memoized. Unmemoized effect dependencies can trigger an infinite loop or other unexpected behavior
|
||||
|
||||
error.invalid-useInsertionEffect-dep-not-memoized.ts:6:2
|
||||
4 | function Component(props) {
|
||||
5 | const data = {};
|
||||
> 6 | useInsertionEffect(() => {
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
> 7 | console.log(props.value);
|
||||
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||
> 8 | }, [data]);
|
||||
| ^^^^^^^^^^^^^ React Compiler has skipped optimizing this component because the effect dependencies could not be memoized. Unmemoized effect dependencies can trigger an infinite loop or other unexpected behavior
|
||||
9 | mutate(data);
|
||||
10 | return data;
|
||||
11 | }
|
||||
```
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user