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] First cut at dep inference #31386

Merged
merged 10 commits into from
Nov 22, 2024
Merged
Show file tree
Hide file tree
Changes from 7 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
Expand Up @@ -36,6 +36,7 @@ import {
inferReactivePlaces,
inferReferenceEffects,
inlineImmediatelyInvokedFunctionExpressions,
inferEffectDependencies,
} from '../Inference';
import {
constantPropagation,
Expand Down Expand Up @@ -353,6 +354,10 @@ function* runWithEnvironment(
name: 'PropagateScopeDependenciesHIR',
value: hir,
});

if (env.config.inferEffectDependencies) {
inferEffectDependencies(env, hir);
}

if (env.config.inlineJsxTransform) {
inlineJsxTransform(hir, env.config.inlineJsxTransform);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,19 @@ const EnvironmentConfigSchema = z.object({

enableFunctionDependencyRewrite: z.boolean().default(true),

/**
* Enables inference of optional dependency chains. Without this flag
* a property chain such as `props?.items?.foo` will infer as a dep on
* just `props`. With this flag enabled, we'll infer that full path as
* the dependency.
*/
enableOptionalDependencies: z.boolean().default(true),

/**
* Enables inference and auto-insertion of effect dependencies. Still experimental.
*/
inferEffectDependencies: z.boolean().default(false),

/**
* Enables inlining ReactElement object literals in place of JSX
* An alternative to the standard JSX transform which replaces JSX with React's jsxProd() runtime
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import {
ArrayExpression,
Effect,
Environment,
FunctionExpression,
GeneratedSource,
HIRFunction,
IdentifierId,
Instruction,
isUseEffectHookType,
makeInstructionId,
} from '../HIR';
import {createTemporaryPlace} from '../HIR/HIRBuilder';

/**
* 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(
env: Environment,
fn: HIRFunction,
): void {
const fnExpressions = new Map<IdentifierId, FunctionExpression>();

for (const [, block] of fn.body.blocks) {
let rewriteInstrs = new Map();
for (const instr of block.instructions) {
const {value, lvalue} = instr;
if (value.kind === 'FunctionExpression') {
fnExpressions.set(lvalue.identifier.id, value);
} else if (
/*
* This check is not final. Right now we only look for useEffects without a dependency array.
* This is likely not how we will ship this feature, but it is good enough for us to make progress
* on the implementation and test it.
*/
value.kind === 'CallExpression' &&
isUseEffectHookType(value.callee.identifier) &&
value.args.length === 1 &&
value.args[0].kind === 'Identifier'
) {
const fnExpr = fnExpressions.get(value.args[0].identifier.id);
if (fnExpr != null) {
const deps: ArrayExpression = {
kind: 'ArrayExpression',
elements: fnExpr.loweredFunc.dependencies.filter(
place => place.reactive,
),
loc: GeneratedSource,
};

const depsPlace = createTemporaryPlace(env, GeneratedSource);
depsPlace.effect = Effect.Read;
value.args[1] = depsPlace;

const newInstruction: Instruction = {
id: makeInstructionId(0),
loc: GeneratedSource,
lvalue: depsPlace,
value: deps,
};
rewriteInstrs.set(instr.id, newInstruction);
}
}
}
if (rewriteInstrs.size > 0) {
const newInstrs = [];
for (const instr of block.instructions) {
const newInstr = rewriteInstrs.get(instr.id);
if (newInstr != null) {
newInstrs.push(newInstr, instr);
} else {
newInstrs.push(instr);
}
}
block.instructions = newInstrs;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ export {inferMutableRanges} from './InferMutableRanges';
export {inferReactivePlaces} from './InferReactivePlaces';
export {default as inferReferenceEffects} from './InferReferenceEffects';
export {inlineImmediatelyInvokedFunctionExpressions} from './InlineImmediatelyInvokedFunctionExpressions';
export {inferEffectDependencies} from './InferEffectDependencies';
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@

## Input

```javascript
// @inferEffectDependencies
const moduleNonReactive = 0;

function Component({foo, bar}) {
const localNonreactive = 0;
const ref = useRef(0);
const localNonPrimitiveReactive = {
foo,
};
const localNonPrimitiveNonreactive = {};
useEffect(() => {
console.log(foo);
console.log(bar);
console.log(moduleNonReactive);
console.log(localNonreactive);
console.log(globalValue);
Comment on lines +16 to +20
Copy link
Member

Choose a reason for hiding this comment

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

could you add a ref here and a non-primitive local too?

console.log(ref.current);
console.log(localNonPrimitiveReactive);
console.log(localNonPrimitiveNonreactive);
});

// Optional chains and property accesses
// TODO: we may be able to save bytes by omitting property accesses if the
// object of the member expression is already included in the inferred deps
useEffect(() => {
console.log(bar?.baz);
console.log(bar.qux);
});

function f() {
console.log(foo);
}

// No inferred dep array, the argument is not a lambda
useEffect(f);
}

```

## Code

```javascript
import { c as _c } from "react/compiler-runtime"; // @inferEffectDependencies
const moduleNonReactive = 0;

function Component(t0) {
const $ = _c(12);
const { foo, bar } = t0;

const ref = useRef(0);
let t1;
if ($[0] !== foo) {
t1 = { foo };
$[0] = foo;
$[1] = t1;
} else {
t1 = $[1];
}
const localNonPrimitiveReactive = t1;
let t2;
if ($[2] === Symbol.for("react.memo_cache_sentinel")) {
t2 = {};
$[2] = t2;
} else {
t2 = $[2];
}
const localNonPrimitiveNonreactive = t2;
let t3;
if ($[3] !== bar || $[4] !== foo || $[5] !== localNonPrimitiveReactive) {
t3 = () => {
console.log(foo);
console.log(bar);
console.log(moduleNonReactive);
console.log(0);
console.log(globalValue);
console.log(ref.current);
console.log(localNonPrimitiveReactive);
console.log(localNonPrimitiveNonreactive);
};
$[3] = bar;
$[4] = foo;
$[5] = localNonPrimitiveReactive;
$[6] = t3;
} else {
t3 = $[6];
}
useEffect(t3, [foo, bar, localNonPrimitiveReactive]);
let t4;
if ($[7] !== bar.baz || $[8] !== bar.qux) {
t4 = () => {
console.log(bar?.baz);
console.log(bar.qux);
};
$[7] = bar.baz;
$[8] = bar.qux;
$[9] = t4;
} else {
t4 = $[9];
}
useEffect(t4, [bar, bar.qux]);
Copy link
Contributor Author

@jbrown215 jbrown215 Nov 19, 2024

Choose a reason for hiding this comment

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

This looks a little weird to me-- the reactive deps of the function on 93 are more precise than the deps we insert here, but we filter the effect deps to just its reactive deps...

Copy link
Contributor Author

Choose a reason for hiding this comment

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

@mofeiZ: I think you were working on a related problem here about capturing member expressions- does anything look strange to you here? Should I be filtering the deps differently?

Copy link
Contributor

Choose a reason for hiding this comment

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

Chatted about this offline, the correct fix here was to change effect dependencies to be derived from ReactiveScope.dependencies instead of LoweredFunction.dependencies (also see #31386 (comment))

let t5;
if ($[10] !== foo) {
t5 = function f() {
console.log(foo);
};
$[10] = foo;
$[11] = t5;
} else {
t5 = $[11];
}
const f = t5;

useEffect(f);
}

```

### Eval output
(kind: exception) Fixture not implemented
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// @inferEffectDependencies
const moduleNonReactive = 0;

function Component({foo, bar}) {
const localNonreactive = 0;
const ref = useRef(0);
const localNonPrimitiveReactive = {
foo,
};
const localNonPrimitiveNonreactive = {};
useEffect(() => {
console.log(foo);
console.log(bar);
console.log(moduleNonReactive);
console.log(localNonreactive);
console.log(globalValue);
console.log(ref.current);
console.log(localNonPrimitiveReactive);
console.log(localNonPrimitiveNonreactive);
});

// Optional chains and property accesses
// TODO: we may be able to save bytes by omitting property accesses if the
// object of the member expression is already included in the inferred deps
useEffect(() => {
console.log(bar?.baz);
console.log(bar.qux);
});

function f() {
console.log(foo);
}

// No inferred dep array, the argument is not a lambda
useEffect(f);
}
6 changes: 6 additions & 0 deletions compiler/packages/snap/src/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,11 @@ function makePluginOptions(
.filter(s => s.length > 0);
}

let inferEffectDependencies = false;
if (firstLine.includes('@inferEffectDependencies')) {
inferEffectDependencies = true;
}

let logs: Array<{filename: string | null; event: LoggerEvent}> = [];
let logger: Logger | null = null;
if (firstLine.includes('@logger')) {
Expand All @@ -197,6 +202,7 @@ function makePluginOptions(
hookPattern,
validatePreserveExistingMemoizationGuarantees,
validateBlocklistedImports,
inferEffectDependencies,
},
compilationMode,
logger,
Expand Down
Loading