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] Allow all hooks to take callbacks which access refs, but ban hooks from taking direct ref value arguments #30917

Merged
merged 2 commits into from
Sep 16, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
11 changes: 11 additions & 0 deletions compiler/packages/babel-plugin-react-compiler/src/HIR/Globals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -362,6 +362,17 @@ const REACT_APIS: Array<[string, BuiltInType]> = [
returnValueKind: ValueKind.Mutable,
}),
],
[
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is left over from a previous version of this work, but seems reasonable to add anyways

'useImperativeHandle',
addHook(DEFAULT_SHAPES, {
positionalParams: [],
restParam: Effect.Freeze,
returnType: {kind: 'Primitive'},
calleeEffect: Effect.Read,
hookKind: 'useImperativeHandle',
returnValueKind: ValueKind.Frozen,
}),
],
[
'useMemo',
addHook(DEFAULT_SHAPES, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,7 @@ export type HookKind =
| 'useMemo'
| 'useCallback'
| 'useTransition'
| 'useImperativeHandle'
| 'Custom';

/*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import {
eachTerminalOperand,
} from '../HIR/visitors';
import {Err, Ok, Result} from '../Utils/Result';
import {isEffectHook} from './ValidateMemoizedEffectDependencies';

/**
* Validates that a function does not access a ref value during render. This includes a partial check
Expand Down Expand Up @@ -309,60 +308,37 @@ function validateNoRefAccessInRenderImpl(
});
break;
}
case 'MethodCall': {
if (!isEffectHook(instr.value.property.identifier)) {
for (const operand of eachInstructionValueOperand(instr.value)) {
const hookKind = getHookKindForType(
fn.env,
instr.value.property.identifier.type,
);
if (hookKind != null) {
validateNoRefValueAccess(errors, env, operand);
} else {
validateNoRefAccess(errors, env, operand, operand.loc);
}
}
}
validateNoRefValueAccess(errors, env, instr.value.receiver);
const methType = env.get(instr.value.property.identifier.id);
let returnType: RefAccessType = {kind: 'None'};
if (methType?.kind === 'Structure' && methType.fn !== null) {
returnType = methType.fn.returnType;
}
env.set(instr.lvalue.identifier.id, returnType);
break;
}
case 'MethodCall':
case 'CallExpression': {
const callee = instr.value.callee;
const callee =
instr.value.kind === 'CallExpression'
? instr.value.callee
: instr.value.property;
const hookKind = getHookKindForType(fn.env, callee.identifier.type);
const isUseEffect = isEffectHook(callee.identifier);
let returnType: RefAccessType = {kind: 'None'};
if (!isUseEffect) {
// Report a more precise error when calling a local function that accesses a ref
const fnType = env.get(instr.value.callee.identifier.id);
if (fnType?.kind === 'Structure' && fnType.fn !== null) {
returnType = fnType.fn.returnType;
if (fnType.fn.readRefEffect) {
errors.push({
severity: ErrorSeverity.InvalidReact,
reason:
'This function accesses a ref value (the `current` property), which may not be accessed during render. (https://react.dev/reference/react/useRef)',
loc: callee.loc,
description:
callee.identifier.name !== null &&
callee.identifier.name.kind === 'named'
? `Function \`${callee.identifier.name.value}\` accesses a ref`
: null,
suggestions: null,
});
}
const fnType = env.get(callee.identifier.id);
if (fnType?.kind === 'Structure' && fnType.fn !== null) {
returnType = fnType.fn.returnType;
if (fnType.fn.readRefEffect) {
errors.push({
severity: ErrorSeverity.InvalidReact,
reason:
'This function accesses a ref value (the `current` property), which may not be accessed during render. (https://react.dev/reference/react/useRef)',
loc: callee.loc,
description:
callee.identifier.name !== null &&
callee.identifier.name.kind === 'named'
? `Function \`${callee.identifier.name.value}\` accesses a ref`
: null,
suggestions: null,
});
}
for (const operand of eachInstructionValueOperand(instr.value)) {
if (hookKind != null) {
validateNoRefValueAccess(errors, env, operand);
} else {
validateNoRefAccess(errors, env, operand, operand.loc);
}
}
for (const operand of eachInstructionValueOperand(instr.value)) {
if (hookKind != null) {
validateNoDirectRefValueAccess(errors, operand, env);
} else {
validateNoRefAccess(errors, env, operand, operand.loc);
}
}
env.set(instr.lvalue.identifier.id, returnType);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@

## Input

```javascript
import {useEffect} from 'react';

function Component(props) {
const ref = useRef();
useEffect(() => {}, [ref.current]);
}

export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [],
};

```


## Error

```
3 | function Component(props) {
4 | const ref = useRef();
> 5 | useEffect(() => {}, [ref.current]);
| ^^^^^^^^^^^ InvalidReact: Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef) (5:5)

InvalidReact: Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef) (5:5)
6 | }
7 |
8 | export const FIXTURE_ENTRYPOINT = {
```


Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {useEffect} from 'react';

function Component(props) {
const ref = useRef();
useEffect(() => {}, [ref.current]);
}

export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [],
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@

## Input

```javascript
import {useEffect} from 'react';

function Component(props) {
const ref = useRef();
useFoo(() => {
ref.current = 42;
});
}

function useFoo(x) {}

export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [],
};

```

## Code

```javascript
import { c as _c } from "react/compiler-runtime";
import { useEffect } from "react";

function Component(props) {
const $ = _c(1);
const ref = useRef();
let t0;
if ($[0] === Symbol.for("react.memo_cache_sentinel")) {
t0 = () => {
ref.current = 42;
};
$[0] = t0;
} else {
t0 = $[0];
}
useFoo(t0);
}

function useFoo(x) {}

export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [],
};

```

### Eval output
(kind: exception) useRef is not defined
Copy link
Contributor

Choose a reason for hiding this comment

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

oops

Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import {useEffect} from 'react';

function Component(props) {
const ref = useRef();
useFoo(() => {
ref.current = 42;
});
}

function useFoo(x) {}

export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [],
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@

## Input

```javascript
// @flow

import {useImperativeHandle, useRef} from 'react';

component Component(prop: number) {
const ref1 = useRef(null);
const ref2 = useRef(1);
useImperativeHandle(ref1, () => {
const precomputed = prop + ref2.current;
return {
foo: () => prop + ref2.current + precomputed,
};
}, [prop]);
}

export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{prop: 1}],
};

```

## Code

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

import { useImperativeHandle, useRef } from "react";

function Component(t0) {
const $ = _c(3);
const { prop } = t0;
const ref1 = useRef(null);
const ref2 = useRef(1);
let t1;
let t2;
if ($[0] !== prop) {
t1 = () => {
const precomputed = prop + ref2.current;
return { foo: () => prop + ref2.current + precomputed };
};

t2 = [prop];
$[0] = prop;
$[1] = t1;
$[2] = t2;
} else {
t1 = $[1];
t2 = $[2];
}
useImperativeHandle(ref1, t1, t2);
}

export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{ prop: 1 }],
};

```

### Eval output
(kind: ok)
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// @flow

import {useImperativeHandle, useRef} from 'react';

component Component(prop: number) {
const ref1 = useRef(null);
const ref2 = useRef(1);
useImperativeHandle(ref1, () => {
const precomputed = prop + ref2.current;
return {
foo: () => prop + ref2.current + precomputed,
};
}, [prop]);
}

export const FIXTURE_ENTRYPOINT = {
fn: Component,
params: [{prop: 1}],
};