[compiler] Validate against JSX in try statements

Per comments on the new validation pass, this disallows creating JSX (expression/fragment) within a try statement. Developers sometimes use this pattern thinking that they can catch errors during the rendering of the element, without realizing that rendering is lazy. The validation allows us to teach developers about the error boundary pattern.

ghstack-source-id: 0bc722aeaed426ddd40e075c008f0ff2576e0c33
Pull Request resolved: https://github.com/facebook/react/pull/30725
This commit is contained in:
Joe Savona 2024-08-16 17:05:29 -07:00
parent 6ebfd5b082
commit d2413bf377
11 changed files with 281 additions and 0 deletions

View File

@ -105,6 +105,7 @@ import {outlineFunctions} from '../Optimization/OutlineFunctions';
import {propagatePhiTypes} from '../TypeInference/PropagatePhiTypes'; import {propagatePhiTypes} from '../TypeInference/PropagatePhiTypes';
import {lowerContextAccess} from '../Optimization/LowerContextAccess'; import {lowerContextAccess} from '../Optimization/LowerContextAccess';
import {validateNoSetStateInPassiveEffects} from '../Validation/ValidateNoSetStateInPassiveEffects'; import {validateNoSetStateInPassiveEffects} from '../Validation/ValidateNoSetStateInPassiveEffects';
import {validateNoJSXInTryStatement} from '../Validation/ValidateNoJSXInTryStatement';
export type CompilerPipelineValue = export type CompilerPipelineValue =
| {kind: 'ast'; name: string; value: CodegenFunction} | {kind: 'ast'; name: string; value: CodegenFunction}
@ -249,6 +250,10 @@ function* runWithEnvironment(
validateNoSetStateInPassiveEffects(hir); validateNoSetStateInPassiveEffects(hir);
} }
if (env.config.validateNoJSXInTryStatements) {
validateNoJSXInTryStatement(hir);
}
inferReactivePlaces(hir); inferReactivePlaces(hir);
yield log({kind: 'hir', name: 'InferReactivePlaces', value: hir}); yield log({kind: 'hir', name: 'InferReactivePlaces', value: hir});

View File

@ -237,6 +237,12 @@ const EnvironmentConfigSchema = z.object({
*/ */
validateNoSetStateInPassiveEffects: z.boolean().default(false), validateNoSetStateInPassiveEffects: z.boolean().default(false),
/**
* Validates against creating JSX within a try block and recommends using an error boundary
* instead.
*/
validateNoJSXInTryStatements: z.boolean().default(false),
/** /**
* Validates that the dependencies of all effect hooks are memoized. This helps ensure * 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, * that Forget does not introduce infinite renders caused by a dependency changing,

View File

@ -0,0 +1,52 @@
/**
* 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, ErrorSeverity} from '..';
import {BlockId, HIRFunction} from '../HIR';
import {retainWhere} from '../Utils/utils';
/**
* Developers may not be aware of error boundaries and lazy evaluation of JSX, leading them
* to use patterns such as `let el; try { el = <Component /> } catch { ... }` to attempt to
* catch rendering errors. Such code will fail to catch errors in rendering, but developers
* may not realize this right away.
*
* This validation pass validates against this pattern: specifically, it errors for JSX
* created within a try block. JSX is allowed within a catch statement, unless that catch
* is itself nested inside an outer try.
*/
export function validateNoJSXInTryStatement(fn: HIRFunction): void {
const activeTryBlocks: Array<BlockId> = [];
const errors = new CompilerError();
for (const [, block] of fn.body.blocks) {
retainWhere(activeTryBlocks, id => id !== block.id);
if (activeTryBlocks.length !== 0) {
for (const instr of block.instructions) {
const {value} = instr;
switch (value.kind) {
case 'JsxExpression':
case 'JsxFragment': {
errors.push({
severity: ErrorSeverity.InvalidReact,
reason: `Unexpected JSX element within a try statement. To catch errors in rendering a given component, wrap that component in an error boundary. (https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary)`,
loc: value.loc,
});
break;
}
}
}
}
if (block.terminal.kind === 'try') {
activeTryBlocks.push(block.terminal.handler);
}
}
if (errors.hasErrors()) {
throw errors;
}
}

View File

@ -0,0 +1,38 @@
## Input
```javascript
// @validateNoJSXInTryStatements
import {identity} from 'shared-runtime';
function Component(props) {
let el;
try {
let value;
try {
value = identity(props.foo);
} catch {
el = <div value={value} />;
}
} catch {
return null;
}
return el;
}
```
## Error
```
9 | value = identity(props.foo);
10 | } catch {
> 11 | el = <div value={value} />;
| ^^^^^^^^^^^^^^^^^^^^^ InvalidReact: Unexpected JSX element within a try statement. To catch errors in rendering a given component, wrap that component in an error boundary. (https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary) (11:11)
12 | }
13 | } catch {
14 | return null;
```

View File

@ -0,0 +1,17 @@
// @validateNoJSXInTryStatements
import {identity} from 'shared-runtime';
function Component(props) {
let el;
try {
let value;
try {
value = identity(props.foo);
} catch {
el = <div value={value} />;
}
} catch {
return null;
}
return el;
}

View File

@ -0,0 +1,31 @@
## Input
```javascript
// @validateNoJSXInTryStatements
function Component(props) {
let el;
try {
el = <div />;
} catch {
return null;
}
return el;
}
```
## Error
```
3 | let el;
4 | try {
> 5 | el = <div />;
| ^^^^^^^ InvalidReact: Unexpected JSX element within a try statement. To catch errors in rendering a given component, wrap that component in an error boundary. (https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary) (5:5)
6 | } catch {
7 | return null;
8 | }
```

View File

@ -0,0 +1,10 @@
// @validateNoJSXInTryStatements
function Component(props) {
let el;
try {
el = <div />;
} catch {
return null;
}
return el;
}

View File

@ -0,0 +1,56 @@
## Input
```javascript
// @validateNoJSXInTryStatements
import {identity} from 'shared-runtime';
function Component(props) {
let el;
try {
let value;
try {
value = identity(props.foo);
} catch {
el = <div value={value} />;
}
} finally {
console.log(el);
}
return el;
}
```
## Error
```
4 | function Component(props) {
5 | let el;
> 6 | try {
| ^^^^^
> 7 | let value;
| ^^^^^^^^^^^^^^
> 8 | try {
| ^^^^^^^^^^^^^^
> 9 | value = identity(props.foo);
| ^^^^^^^^^^^^^^
> 10 | } catch {
| ^^^^^^^^^^^^^^
> 11 | el = <div value={value} />;
| ^^^^^^^^^^^^^^
> 12 | }
| ^^^^^^^^^^^^^^
> 13 | } finally {
| ^^^^^^^^^^^^^^
> 14 | console.log(el);
| ^^^^^^^^^^^^^^
> 15 | }
| ^^^^ Todo: (BuildHIR::lowerStatement) Handle TryStatement without a catch clause (6:15)
16 | return el;
17 | }
18 |
```

View File

@ -0,0 +1,17 @@
// @validateNoJSXInTryStatements
import {identity} from 'shared-runtime';
function Component(props) {
let el;
try {
let value;
try {
value = identity(props.foo);
} catch {
el = <div value={value} />;
}
} finally {
console.log(el);
}
return el;
}

View File

@ -0,0 +1,39 @@
## Input
```javascript
// @validateNoJSXInTryStatements
function Component(props) {
let el;
try {
el = <div />;
} finally {
console.log(el);
}
return el;
}
```
## Error
```
2 | function Component(props) {
3 | let el;
> 4 | try {
| ^^^^^
> 5 | el = <div />;
| ^^^^^^^^^^^^^^^^^
> 6 | } finally {
| ^^^^^^^^^^^^^^^^^
> 7 | console.log(el);
| ^^^^^^^^^^^^^^^^^
> 8 | }
| ^^^^ Todo: (BuildHIR::lowerStatement) Handle TryStatement without a catch clause (4:8)
9 | return el;
10 | }
11 |
```

View File

@ -0,0 +1,10 @@
// @validateNoJSXInTryStatements
function Component(props) {
let el;
try {
el = <div />;
} finally {
console.log(el);
}
return el;
}