[compiler] Fix for edge cases of mutation of potentially frozen values (#33984)

Fixes two related cases of mutation of potentially frozen values.

The first is method calls on frozen values. Previously, we modeled
unknown function calls as potentially aliasing their receiver+args into
the return value. If the receiver or argument were known to be frozen,
then we would downgrade the `Alias` effect into an `ImmutableCapture`.
However, within a function expression it's possible to call a function
using a frozen value as an argument (that gets `Alias`-ed into the
return) but where we don't have the context locally to know that the
value is frozen.

This results in cases like this:

```js
const frozen = useContext(...);
useEffect(() => {
  frozen.method().property = true;
  ^^^^^^^^^^^^^^^^^^^^^^^^ cannot mutate frozen value
}, [...]);
```

Within the function we would infer:

```
t0 = MethodCall ...
  Create t0 = mutable
  Alias t0 <- frozen
t1 = PropertyStore ...
  Mutate t0
```

And then transitively infer the function expression as having a `Mutate
'frozen'` effect, which when evaluated against the outer context
(`frozen` is frozen) is an error.

The fix is to model unknown function calls as _maybe_ aliasing their
receiver/args in the return, and then considering mutations of a
maybe-aliased value to only be a conditional mutation of the source:


```
t0 = MethodCall ...
  Create t0 = mutable
  MaybeAlias t0 <- frozen // maybe alias now
t1 = PropertyStore ...
  Mutate t0
```

Then, the `Mutate t0` turns into a `MutateConditional 'frozen'`, which
just gets ignored when we process the outer context.

The second, related fix is for known mutation of phis that may be a
frozen value. The previous inference model correctly recorded these as
errors, the new model does not. We now correctly report a validation
error for this case in the new model.

---
[//]: # (BEGIN SAPLING FOOTER)
Stack created with [Sapling](https://sapling-scm.com). Best reviewed
with [ReviewStack](https://reviewstack.dev/facebook/react/pull/33984).
* #33993
* #33991
* __->__ #33984
This commit is contained in:
Joseph Savona 2025-07-25 10:07:24 -07:00 committed by GitHub
parent b2c30493ce
commit 12483a119b
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
17 changed files with 483 additions and 106 deletions

View File

@ -943,7 +943,10 @@ export function printAliasingEffect(effect: AliasingEffect): string {
return `Assign ${printPlaceForAliasEffect(effect.into)} = ${printPlaceForAliasEffect(effect.from)}`;
}
case 'Alias': {
return `Alias ${printPlaceForAliasEffect(effect.into)} = ${printPlaceForAliasEffect(effect.from)}`;
return `Alias ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`;
}
case 'MaybeAlias': {
return `MaybeAlias ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`;
}
case 'Capture': {
return `Capture ${printPlaceForAliasEffect(effect.into)} <- ${printPlaceForAliasEffect(effect.from)}`;

View File

@ -90,6 +90,23 @@ export type AliasingEffect =
* c could be mutating a.
*/
| {kind: 'Alias'; from: Place; into: Place}
/**
* Indicates the potential for information flow from `from` to `into`. This is used for a specific
* case: functions with unknown signatures. If the compiler sees a call such as `foo(x)`, it has to
* consider several possibilities (which may depend on the arguments):
* - foo(x) returns a new mutable value that does not capture any information from x.
* - foo(x) returns a new mutable value that *does* capture information from x.
* - foo(x) returns x itself, ie foo is the identity function
*
* The same is true of functions that take multiple arguments: `cond(a, b, c)` could conditionally
* return b or c depending on the value of a.
*
* To represent this case, MaybeAlias represents the fact that an aliasing relationship could exist.
* Any mutations that flow through this relationship automatically become conditional.
*/
| {kind: 'MaybeAlias'; from: Place; into: Place}
/**
* Records direct assignment: `into = from`.
*/
@ -183,7 +200,8 @@ export function hashEffect(effect: AliasingEffect): string {
case 'ImmutableCapture':
case 'Assign':
case 'Alias':
case 'Capture': {
case 'Capture':
case 'MaybeAlias': {
return [
effect.kind,
effect.from.identifier.id,

View File

@ -85,7 +85,8 @@ function lowerWithMutationAliasing(fn: HIRFunction): void {
case 'Assign':
case 'Alias':
case 'Capture':
case 'CreateFrom': {
case 'CreateFrom':
case 'MaybeAlias': {
capturedOrMutated.add(effect.from.identifier.id);
break;
}

View File

@ -691,6 +691,7 @@ function applyEffect(
}
break;
}
case 'MaybeAlias':
case 'Alias':
case 'Capture': {
CompilerError.invariant(
@ -955,7 +956,7 @@ function applyEffect(
context,
state,
// OK: recording information flow
{kind: 'Alias', from: operand, into: effect.into},
{kind: 'MaybeAlias', from: operand, into: effect.into},
initialized,
effects,
);
@ -1323,7 +1324,7 @@ class InferenceState {
return 'mutate-global';
}
case ValueKind.MaybeFrozen: {
return 'none';
return 'mutate-frozen';
}
default: {
assertExhaustive(kind, `Unexpected kind ${kind}`);
@ -2376,6 +2377,7 @@ function computeEffectsForSignature(
// Apply substitutions
for (const effect of signature.effects) {
switch (effect.kind) {
case 'MaybeAlias':
case 'Assign':
case 'ImmutableCapture':
case 'Alias':

View File

@ -160,6 +160,8 @@ export function inferMutationAliasingRanges(
state.assign(index++, effect.from, effect.into);
} else if (effect.kind === 'Alias') {
state.assign(index++, effect.from, effect.into);
} else if (effect.kind === 'MaybeAlias') {
state.maybeAlias(index++, effect.from, effect.into);
} else if (effect.kind === 'Capture') {
state.capture(index++, effect.from, effect.into);
} else if (
@ -346,7 +348,8 @@ export function inferMutationAliasingRanges(
case 'Assign':
case 'Alias':
case 'Capture':
case 'CreateFrom': {
case 'CreateFrom':
case 'MaybeAlias': {
const isMutatedOrReassigned =
effect.into.identifier.mutableRange.end > instr.id;
if (isMutatedOrReassigned) {
@ -567,7 +570,12 @@ type Node = {
createdFrom: Map<Identifier, number>;
captures: Map<Identifier, number>;
aliases: Map<Identifier, number>;
edges: Array<{index: number; node: Identifier; kind: 'capture' | 'alias'}>;
maybeAliases: Map<Identifier, number>;
edges: Array<{
index: number;
node: Identifier;
kind: 'capture' | 'alias' | 'maybeAlias';
}>;
transitive: {kind: MutationKind; loc: SourceLocation} | null;
local: {kind: MutationKind; loc: SourceLocation} | null;
lastMutated: number;
@ -585,6 +593,7 @@ class AliasingState {
createdFrom: new Map(),
captures: new Map(),
aliases: new Map(),
maybeAliases: new Map(),
edges: [],
transitive: null,
local: null,
@ -630,6 +639,18 @@ class AliasingState {
}
}
maybeAlias(index: number, from: Place, into: Place): void {
const fromNode = this.nodes.get(from.identifier);
const toNode = this.nodes.get(into.identifier);
if (fromNode == null || toNode == null) {
return;
}
fromNode.edges.push({index, node: into.identifier, kind: 'maybeAlias'});
if (!toNode.maybeAliases.has(from.identifier)) {
toNode.maybeAliases.set(from.identifier, index);
}
}
render(index: number, start: Identifier, errors: CompilerError): void {
const seen = new Set<Identifier>();
const queue: Array<Identifier> = [start];
@ -673,22 +694,24 @@ class AliasingState {
// Null is used for simulated mutations
end: InstructionId | null,
transitive: boolean,
kind: MutationKind,
startKind: MutationKind,
loc: SourceLocation,
errors: CompilerError,
): void {
const seen = new Set<Identifier>();
const seen = new Map<Identifier, MutationKind>();
const queue: Array<{
place: Identifier;
transitive: boolean;
direction: 'backwards' | 'forwards';
}> = [{place: start, transitive, direction: 'backwards'}];
kind: MutationKind;
}> = [{place: start, transitive, direction: 'backwards', kind: startKind}];
while (queue.length !== 0) {
const {place: current, transitive, direction} = queue.pop()!;
if (seen.has(current)) {
const {place: current, transitive, direction, kind} = queue.pop()!;
const previousKind = seen.get(current);
if (previousKind != null && previousKind >= kind) {
continue;
}
seen.add(current);
seen.set(current, kind);
const node = this.nodes.get(current);
if (node == null) {
continue;
@ -724,13 +747,18 @@ class AliasingState {
if (edge.index >= index) {
break;
}
queue.push({place: edge.node, transitive, direction: 'forwards'});
queue.push({place: edge.node, transitive, direction: 'forwards', kind});
}
for (const [alias, when] of node.createdFrom) {
if (when >= index) {
continue;
}
queue.push({place: alias, transitive: true, direction: 'backwards'});
queue.push({
place: alias,
transitive: true,
direction: 'backwards',
kind,
});
}
if (direction === 'backwards' || node.value.kind !== 'Phi') {
/**
@ -747,7 +775,25 @@ class AliasingState {
if (when >= index) {
continue;
}
queue.push({place: alias, transitive, direction: 'backwards'});
queue.push({place: alias, transitive, direction: 'backwards', kind});
}
/**
* MaybeAlias indicates potential data flow from unknown function calls,
* so we downgrade mutations through these aliases to consider them
* conditional. This means we'll consider them for mutation *range*
* purposes but not report validation errors for mutations, since
* we aren't sure that the `from` value could actually be aliased.
*/
for (const [alias, when] of node.maybeAliases) {
if (when >= index) {
continue;
}
queue.push({
place: alias,
transitive,
direction: 'backwards',
kind: MutationKind.Conditional,
});
}
}
/**
@ -758,7 +804,12 @@ class AliasingState {
if (when >= index) {
continue;
}
queue.push({place: capture, transitive, direction: 'backwards'});
queue.push({
place: capture,
transitive,
direction: 'backwards',
kind,
});
}
}
}

View File

@ -153,6 +153,10 @@ This is somewhat the inverse of `Capture`. The `CreateFrom` effect describes tha
Describes immutable data flow from one value to another. This is not currently used for anything, but is intended to eventually power a more sophisticated escape analysis.
### MaybeAlias
Describes potential data flow that the compiler knows may occur behind a function call, but cannot be sure about. For example, `foo(x)` _may_ be the identity function and return `x`, or `cond(a, b, c)` may conditionally return `b` or `c` depending on the value of `a`, but those functions could just as easily return new mutable values and not capture any information from their arguments. MaybeAlias represents that we have to consider the potential for data flow when deciding mutable ranges, but should be conservative about reporting errors. For example, `foo(someFrozenValue).property = true` should not error since we don't know for certain that foo returns its input.
### State-Changing Effects
The following effects describe state changes to specific values, not data flow. In many cases, JavaScript semantics will involve a combination of both data-flow effects *and* state-change effects. For example, `object.property = value` has data flow (`Capture object <- value`) and mutation (`Mutate object`).
@ -347,6 +351,17 @@ a.b = b; // capture
mutate(a); // can transitively mutate b
```
### MaybeAlias makes mutation conditional
Because we don't know for certain that the aliasing occurs, we consider the mutation conditional against the source.
```
MaybeAlias a <- b
Mutate a
=>
MutateConditional b
```
### Freeze Does Not Freeze the Value
Freeze does not freeze the value itself:

View File

@ -0,0 +1,39 @@
## Input
```javascript
import {useHook} from 'shared-runtime';
function Component(props) {
const frozen = useHook();
let x;
if (props.cond) {
x = frozen;
} else {
x = {};
}
x.property = true;
}
```
## Error
```
Found 1 error:
Error: This value cannot be modified
Modifying a value returned from a hook is not allowed. Consider moving the modification into the hook where the value is constructed.
error.invalid-mutate-phi-which-could-be-frozen.ts:11:2
9 | x = {};
10 | }
> 11 | x.property = true;
| ^ value cannot be modified
12 | }
13 |
```

View File

@ -0,0 +1,12 @@
import {useHook} from 'shared-runtime';
function Component(props) {
const frozen = useHook();
let x;
if (props.cond) {
x = frozen;
} else {
x = {};
}
x.property = true;
}

View File

@ -0,0 +1,61 @@
## Input
```javascript
import {Stringify, useIdentity} from 'shared-runtime';
function Component() {
const data = useIdentity(
new Map([
[0, 'value0'],
[1, 'value1'],
])
);
const items = [];
// NOTE: `i` is a context variable because it's reassigned and also referenced
// within a closure, the `onClick` handler of each item
// TODO: for loops create a unique environment on each iteration, which means
// that if the iteration variable is only updated in the updater, the variable
// is effectively const within the body and the "update" acts more like
// a re-initialization than a reassignment.
// Until we model this "new environment" semantic, we allow this case to error
for (let i = MIN; i <= MAX; i += INCREMENT) {
items.push(
<Stringify key={i} onClick={() => data.get(i)} shouldInvokeFns={true} />
);
}
return <>{items}</>;
}
const MIN = 0;
const MAX = 3;
const INCREMENT = 1;
export const FIXTURE_ENTRYPOINT = {
params: [],
fn: Component,
};
```
## Error
```
Found 1 error:
Error: This value cannot be modified
Modifying a value used previously in JSX is not allowed. Consider moving the modification before the JSX.
error.todo-for-loop-with-context-variable-iterator.ts:18:30
16 | // a re-initialization than a reassignment.
17 | // Until we model this "new environment" semantic, we allow this case to error
> 18 | for (let i = MIN; i <= MAX; i += INCREMENT) {
| ^ `i` cannot be modified
19 | items.push(
20 | <Stringify key={i} onClick={() => data.get(i)} shouldInvokeFns={true} />
21 | );
```

View File

@ -10,6 +10,11 @@ function Component() {
const items = [];
// NOTE: `i` is a context variable because it's reassigned and also referenced
// within a closure, the `onClick` handler of each item
// TODO: for loops create a unique environment on each iteration, which means
// that if the iteration variable is only updated in the updater, the variable
// is effectively const within the body and the "update" acts more like
// a re-initialization than a reassignment.
// Until we model this "new environment" semantic, we allow this case to error
for (let i = MIN; i <= MAX; i += INCREMENT) {
items.push(
<Stringify key={i} onClick={() => data.get(i)} shouldInvokeFns={true} />

View File

@ -1,89 +0,0 @@
## Input
```javascript
import {Stringify, useIdentity} from 'shared-runtime';
function Component() {
const data = useIdentity(
new Map([
[0, 'value0'],
[1, 'value1'],
])
);
const items = [];
// NOTE: `i` is a context variable because it's reassigned and also referenced
// within a closure, the `onClick` handler of each item
for (let i = MIN; i <= MAX; i += INCREMENT) {
items.push(
<Stringify key={i} onClick={() => data.get(i)} shouldInvokeFns={true} />
);
}
return <>{items}</>;
}
const MIN = 0;
const MAX = 3;
const INCREMENT = 1;
export const FIXTURE_ENTRYPOINT = {
params: [],
fn: Component,
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { Stringify, useIdentity } from "shared-runtime";
function Component() {
const $ = _c(3);
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = new Map([
[0, "value0"],
[1, "value1"],
]);
$[0] = t0;
} else {
t0 = $[0];
}
const data = useIdentity(t0);
let t1;
if ($[1] !== data) {
const items = [];
for (let i = MIN; i <= MAX; i = i + INCREMENT, i) {
items.push(
<Stringify
key={i}
onClick={() => data.get(i)}
shouldInvokeFns={true}
/>,
);
}
t1 = <>{items}</>;
$[1] = data;
$[2] = t1;
} else {
t1 = $[2];
}
return t1;
}
const MIN = 0;
const MAX = 3;
const INCREMENT = 1;
export const FIXTURE_ENTRYPOINT = {
params: [],
fn: Component,
};
```
### Eval output
(kind: ok) <div>{"onClick":{"kind":"Function","result":"value0"},"shouldInvokeFns":true}</div><div>{"onClick":{"kind":"Function","result":"value1"},"shouldInvokeFns":true}</div><div>{"onClick":{"kind":"Function"},"shouldInvokeFns":true}</div><div>{"onClick":{"kind":"Function"},"shouldInvokeFns":true}</div>

View File

@ -0,0 +1,77 @@
## Input
```javascript
import {identity, makeObject_Primitives, Stringify} from 'shared-runtime';
function Example(props) {
const object = props.object;
const f = () => {
// The argument maybe-aliases into the return
const obj = identity(object);
obj.property = props.value;
return obj;
};
const obj = f();
return <Stringify obj={obj} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Example,
params: [{object: makeObject_Primitives(), value: 42}],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { identity, makeObject_Primitives, Stringify } from "shared-runtime";
function Example(props) {
const $ = _c(7);
const object = props.object;
let t0;
if ($[0] !== object || $[1] !== props.value) {
t0 = () => {
const obj = identity(object);
obj.property = props.value;
return obj;
};
$[0] = object;
$[1] = props.value;
$[2] = t0;
} else {
t0 = $[2];
}
const f = t0;
let t1;
if ($[3] !== f) {
t1 = f();
$[3] = f;
$[4] = t1;
} else {
t1 = $[4];
}
const obj_0 = t1;
let t2;
if ($[5] !== obj_0) {
t2 = <Stringify obj={obj_0} />;
$[5] = obj_0;
$[6] = t2;
} else {
t2 = $[6];
}
return t2;
}
export const FIXTURE_ENTRYPOINT = {
fn: Example,
params: [{ object: makeObject_Primitives(), value: 42 }],
};
```
### Eval output
(kind: ok) <div>{"obj":{"a":0,"b":"value1","c":true,"property":42}}</div>

View File

@ -0,0 +1,18 @@
import {identity, makeObject_Primitives, Stringify} from 'shared-runtime';
function Example(props) {
const object = props.object;
const f = () => {
// The argument maybe-aliases into the return
const obj = identity(object);
obj.property = props.value;
return obj;
};
const obj = f();
return <Stringify obj={obj} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Example,
params: [{object: makeObject_Primitives(), value: 42}],
};

View File

@ -0,0 +1,77 @@
## Input
```javascript
import {makeObject_Primitives, Stringify} from 'shared-runtime';
function Example(props) {
const object = props.object;
const f = () => {
// The receiver maybe-aliases into the return
const obj = object.makeObject();
obj.property = props.value;
return obj;
};
const obj = f();
return <Stringify obj={obj} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Example,
params: [{object: {makeObject: makeObject_Primitives}, value: 42}],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { makeObject_Primitives, Stringify } from "shared-runtime";
function Example(props) {
const $ = _c(7);
const object = props.object;
let t0;
if ($[0] !== object || $[1] !== props.value) {
t0 = () => {
const obj = object.makeObject();
obj.property = props.value;
return obj;
};
$[0] = object;
$[1] = props.value;
$[2] = t0;
} else {
t0 = $[2];
}
const f = t0;
let t1;
if ($[3] !== f) {
t1 = f();
$[3] = f;
$[4] = t1;
} else {
t1 = $[4];
}
const obj_0 = t1;
let t2;
if ($[5] !== obj_0) {
t2 = <Stringify obj={obj_0} />;
$[5] = obj_0;
$[6] = t2;
} else {
t2 = $[6];
}
return t2;
}
export const FIXTURE_ENTRYPOINT = {
fn: Example,
params: [{ object: { makeObject: makeObject_Primitives }, value: 42 }],
};
```
### Eval output
(kind: ok) <div>{"obj":{"a":0,"b":"value1","c":true,"property":42}}</div>

View File

@ -0,0 +1,18 @@
import {makeObject_Primitives, Stringify} from 'shared-runtime';
function Example(props) {
const object = props.object;
const f = () => {
// The receiver maybe-aliases into the return
const obj = object.makeObject();
obj.property = props.value;
return obj;
};
const obj = f();
return <Stringify obj={obj} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Example,
params: [{object: {makeObject: makeObject_Primitives}, value: 42}],
};

View File

@ -0,0 +1,57 @@
## Input
```javascript
import {makeObject_Primitives, Stringify} from 'shared-runtime';
function Example(props) {
const obj = props.object.makeObject();
obj.property = props.value;
return <Stringify obj={obj} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Example,
params: [{object: {makeObject: makeObject_Primitives}, value: 42}],
};
```
## Code
```javascript
import { c as _c } from "react/compiler-runtime";
import { makeObject_Primitives, Stringify } from "shared-runtime";
function Example(props) {
const $ = _c(5);
let obj;
if ($[0] !== props.object || $[1] !== props.value) {
obj = props.object.makeObject();
obj.property = props.value;
$[0] = props.object;
$[1] = props.value;
$[2] = obj;
} else {
obj = $[2];
}
let t0;
if ($[3] !== obj) {
t0 = <Stringify obj={obj} />;
$[3] = obj;
$[4] = t0;
} else {
t0 = $[4];
}
return t0;
}
export const FIXTURE_ENTRYPOINT = {
fn: Example,
params: [{ object: { makeObject: makeObject_Primitives }, value: 42 }],
};
```
### Eval output
(kind: ok) <div>{"obj":{"a":0,"b":"value1","c":true,"property":42}}</div>

View File

@ -0,0 +1,12 @@
import {makeObject_Primitives, Stringify} from 'shared-runtime';
function Example(props) {
const obj = props.object.makeObject();
obj.property = props.value;
return <Stringify obj={obj} />;
}
export const FIXTURE_ENTRYPOINT = {
fn: Example,
params: [{object: {makeObject: makeObject_Primitives}, value: 42}],
};