Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[compiler] bugfix for hoistable deps for nested functions #31345

Merged
merged 2 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {CompilerError} from '../CompilerError';
import {inRange} from '../ReactiveScopes/InferReactiveScopeVariables';
import {printDependency} from '../ReactiveScopes/PrintReactiveFunction';
import {
Set_equal,
Set_filter,
Expand All @@ -23,6 +24,8 @@ import {
} from './HIR';
import {collectTemporariesSidemap} from './PropagateScopeDependenciesHIR';

const DEBUG_PRINT = false;

/**
* Helper function for `PropagateScopeDependencies`. Uses control flow graph
* analysis to determine which `Identifier`s can be assumed to be non-null
Expand Down Expand Up @@ -86,15 +89,8 @@ export function collectHoistablePropertyLoads(
fn: HIRFunction,
temporaries: ReadonlyMap<IdentifierId, ReactiveScopeDependency>,
hoistableFromOptionals: ReadonlyMap<BlockId, ReactiveScopeDependency>,
nestedFnImmutableContext: ReadonlySet<IdentifierId> | null,
): ReadonlyMap<BlockId, BlockInfo> {
const registry = new PropertyPathRegistry();

const functionExpressionLoads = collectFunctionExpressionFakeLoads(fn);
const actuallyEvaluatedTemporaries = new Map(
[...temporaries].filter(([id]) => !functionExpressionLoads.has(id)),
);

/**
* Due to current limitations of mutable range inference, there are edge cases in
* which we infer known-immutable values (e.g. props or hook params) to have a
Expand All @@ -111,14 +107,51 @@ export function collectHoistablePropertyLoads(
}
}
}
const nodes = collectNonNullsInBlocks(fn, {
temporaries: actuallyEvaluatedTemporaries,
return collectHoistablePropertyLoadsImpl(fn, {
temporaries,
knownImmutableIdentifiers,
hoistableFromOptionals,
registry,
nestedFnImmutableContext,
nestedFnImmutableContext: null,
});
propagateNonNull(fn, nodes, registry);
}

type CollectHoistablePropertyLoadsContext = {
temporaries: ReadonlyMap<IdentifierId, ReactiveScopeDependency>;
knownImmutableIdentifiers: ReadonlySet<IdentifierId>;
hoistableFromOptionals: ReadonlyMap<BlockId, ReactiveScopeDependency>;
registry: PropertyPathRegistry;
/**
* (For nested / inner function declarations)
* Context variables (i.e. captured from an outer scope) that are immutable.
* Note that this technically could be merged into `knownImmutableIdentifiers`,
* but are currently kept separate for readability.
*/
nestedFnImmutableContext: ReadonlySet<IdentifierId> | null;
};
function collectHoistablePropertyLoadsImpl(
fn: HIRFunction,
context: CollectHoistablePropertyLoadsContext,
): ReadonlyMap<BlockId, BlockInfo> {
const functionExpressionLoads = collectFunctionExpressionFakeLoads(fn);
const actuallyEvaluatedTemporaries = new Map(
[...context.temporaries].filter(([id]) => !functionExpressionLoads.has(id)),
);

const nodes = collectNonNullsInBlocks(fn, {
...context,
temporaries: actuallyEvaluatedTemporaries,
});
propagateNonNull(fn, nodes, context.registry);

if (DEBUG_PRINT) {
console.log('(printing hoistable nodes in blocks)');
for (const [blockId, node] of nodes) {
console.log(
`bb${blockId}: ${[...node.assumedNonNullObjects].map(n => printDependency(n.fullPath)).join(' ')}`,
);
}
}

return nodes;
}
Expand Down Expand Up @@ -243,7 +276,7 @@ class PropertyPathRegistry {

function getMaybeNonNullInInstruction(
instr: InstructionValue,
context: CollectNonNullsInBlocksContext,
context: CollectHoistablePropertyLoadsContext,
): PropertyPathNode | null {
let path = null;
if (instr.kind === 'PropertyLoad') {
Expand All @@ -262,7 +295,7 @@ function getMaybeNonNullInInstruction(
function isImmutableAtInstr(
identifier: Identifier,
instr: InstructionId,
context: CollectNonNullsInBlocksContext,
context: CollectHoistablePropertyLoadsContext,
): boolean {
if (context.nestedFnImmutableContext != null) {
/**
Expand Down Expand Up @@ -295,22 +328,9 @@ function isImmutableAtInstr(
}
}

type CollectNonNullsInBlocksContext = {
temporaries: ReadonlyMap<IdentifierId, ReactiveScopeDependency>;
knownImmutableIdentifiers: ReadonlySet<IdentifierId>;
hoistableFromOptionals: ReadonlyMap<BlockId, ReactiveScopeDependency>;
registry: PropertyPathRegistry;
/**
* (For nested / inner function declarations)
* Context variables (i.e. captured from an outer scope) that are immutable.
* Note that this technically could be merged into `knownImmutableIdentifiers`,
* but are currently kept separate for readability.
*/
nestedFnImmutableContext: ReadonlySet<IdentifierId> | null;
};
function collectNonNullsInBlocks(
fn: HIRFunction,
context: CollectNonNullsInBlocksContext,
context: CollectHoistablePropertyLoadsContext,
): ReadonlyMap<BlockId, BlockInfo> {
/**
* Known non-null objects such as functional component props can be safely
Expand Down Expand Up @@ -348,7 +368,8 @@ function collectNonNullsInBlocks(
assumedNonNullObjects.add(maybeNonNull);
}
if (
instr.value.kind === 'FunctionExpression' &&
(instr.value.kind === 'FunctionExpression' ||
instr.value.kind === 'ObjectMethod') &&
!fn.env.config.enableTreatFunctionDepsAsConditional
) {
const innerFn = instr.value.loweredFunc;
Expand All @@ -357,18 +378,22 @@ function collectNonNullsInBlocks(
new Set(),
);
const innerOptionals = collectOptionalChainSidemap(innerFn.func);
const innerHoistableMap = collectHoistablePropertyLoads(
const innerHoistableMap = collectHoistablePropertyLoadsImpl(
innerFn.func,
innerTemporaries,
innerOptionals.hoistableObjects,
context.nestedFnImmutableContext ??
new Set(
innerFn.func.context
.filter(place =>
isImmutableAtInstr(place.identifier, instr.id, context),
)
.map(place => place.identifier.id),
),
{
...context,
temporaries: innerTemporaries, // TODO: remove in later PR
hoistableFromOptionals: innerOptionals.hoistableObjects, // TODO: remove in later PR
nestedFnImmutableContext:
context.nestedFnImmutableContext ??
new Set(
innerFn.func.context
.filter(place =>
isImmutableAtInstr(place.identifier, instr.id, context),
)
.map(place => place.identifier.id),
),
},
);
const innerHoistables = assertNonNull(
innerHoistableMap.get(innerFn.func.body.entry),
Expand Down Expand Up @@ -591,7 +616,10 @@ function collectFunctionExpressionFakeLoads(

for (const [_, block] of fn.body.blocks) {
for (const {lvalue, value} of block.instructions) {
if (value.kind === 'FunctionExpression') {
if (
value.kind === 'FunctionExpression' ||
value.kind === 'ObjectMethod'
) {
for (const reference of value.loweredFunc.dependencies) {
let curr: IdentifierId | undefined = reference.identifier.id;
while (curr != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export function propagateScopeDependenciesHIR(fn: HIRFunction): void {

const hoistablePropertyLoads = keyByScopeId(
fn,
collectHoistablePropertyLoads(fn, temporaries, hoistableObjects, null),
collectHoistablePropertyLoads(fn, temporaries, hoistableObjects),
);

const scopeDeps = collectDependencies(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@

## Input

```javascript
// @enablePropagateDepsInHIR
import {Stringify} from 'shared-runtime';

function Foo({a, shouldReadA}) {
return (
<Stringify
objectMethod={{
method() {
if (shouldReadA) return a.b.c;
return null;
},
}}
shouldInvokeFns={true}
/>
);
}

export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [{a: null, shouldReadA: true}],
sequentialRenders: [
{a: null, shouldReadA: true},
{a: null, shouldReadA: false},
{a: {b: {c: 4}}, shouldReadA: true},
],
};

```

## Code

```javascript
import { c as _c } from "react/compiler-runtime"; // @enablePropagateDepsInHIR
import { Stringify } from "shared-runtime";

function Foo(t0) {
const $ = _c(3);
const { a, shouldReadA } = t0;
let t1;
if ($[0] !== shouldReadA || $[1] !== a) {
t1 = (
<Stringify
objectMethod={{
method() {
if (shouldReadA) {
return a.b.c;
}
return null;
},
}}
shouldInvokeFns={true}
/>
);
$[0] = shouldReadA;
$[1] = a;
$[2] = t1;
} else {
t1 = $[2];
}
return t1;
}

export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [{ a: null, shouldReadA: true }],
sequentialRenders: [
{ a: null, shouldReadA: true },
{ a: null, shouldReadA: false },
{ a: { b: { c: 4 } }, shouldReadA: true },
],
};

```

### Eval output
(kind: ok) [[ (exception in render) TypeError: Cannot read properties of null (reading 'b') ]]
<div>{"objectMethod":{"method":{"kind":"Function","result":null}},"shouldInvokeFns":true}</div>
<div>{"objectMethod":{"method":{"kind":"Function","result":4}},"shouldInvokeFns":true}</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// @enablePropagateDepsInHIR
import {Stringify} from 'shared-runtime';

function Foo({a, shouldReadA}) {
return (
<Stringify
objectMethod={{
method() {
if (shouldReadA) return a.b.c;
return null;
},
}}
shouldInvokeFns={true}
/>
);
}

export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [{a: null, shouldReadA: true}],
sequentialRenders: [
{a: null, shouldReadA: true},
{a: null, shouldReadA: false},
{a: {b: {c: 4}}, shouldReadA: true},
],
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@

## Input

```javascript
// @enablePropagateDepsInHIR
import {Stringify} from 'shared-runtime';

function Foo({data}) {
return (
<Stringify foo={() => data.a.d} bar={data.a?.b.c} shouldInvokeFns={true} />
);
}

export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [{data: {a: null}}],
sequentialRenders: [{data: {a: {b: {c: 4}}}}],
};

```
## Code
```javascript
import { c as _c } from "react/compiler-runtime"; // @enablePropagateDepsInHIR
import { Stringify } from "shared-runtime";

function Foo(t0) {
const $ = _c(5);
const { data } = t0;
let t1;
if ($[0] !== data.a.d) {
t1 = () => data.a.d;
$[0] = data.a.d;
$[1] = t1;
} else {
t1 = $[1];
}
const t2 = data.a?.b.c;
let t3;
if ($[2] !== t1 || $[3] !== t2) {
t3 = <Stringify foo={t1} bar={t2} shouldInvokeFns={true} />;
$[2] = t1;
$[3] = t2;
$[4] = t3;
} else {
t3 = $[4];
}
return t3;
}

export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [{ data: { a: null } }],
sequentialRenders: [{ data: { a: { b: { c: 4 } } } }],
};

```
### Eval output
(kind: ok) <div>{"foo":{"kind":"Function"},"bar":4,"shouldInvokeFns":true}</div>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// @enablePropagateDepsInHIR
import {Stringify} from 'shared-runtime';

function Foo({data}) {
return (
<Stringify foo={() => data.a.d} bar={data.a?.b.c} shouldInvokeFns={true} />
);
}

export const FIXTURE_ENTRYPOINT = {
fn: Foo,
params: [{data: {a: null}}],
sequentialRenders: [{data: {a: {b: {c: 4}}}}],
};
Loading