Compiler: unfork prettier config (#30205)
Updates the prettier config to format all `.ts` and `.tsx` files in the repo using the existing defaults and removing overrides. The first commit in this PR contains the config changes, the second is just the result of running `yarn prettier-all`.
Jan Kassens committed
Jul 18, 2024 at 17:00 UTC
fd2b3e13d330a4559f5aa21462e1cb2cbbcf144b
1898 files changed
+12439
-12665
.prettierrc.js
+2
-20
@@ -1,10 +1,6 @@
1
'use strict';
2
3
-const {
4
- compilerPaths,
5
- esNextPaths,
6
- typescriptPaths,
7
-} = require('./scripts/shared/pathsByLanguageVersion');
3
+const {esNextPaths} = require('./scripts/shared/pathsByLanguageVersion');
4
5
module.exports = {
6
bracketSpacing: false,
@@ -28,25 +24,11 @@ module.exports = {
24
},
25
},
26
{
31
- files: typescriptPaths,
27
+ files: ['*.ts', '*.tsx'],
28
options: {
29
trailingComma: 'all',
30
parser: 'typescript',
31
},
32
},
37
- {
38
- files: compilerPaths,
39
- options: {
40
- requirePragma: false,
41
- parser: 'babel-ts',
42
- semi: true,
43
- singleQuote: false,
44
- trailingComma: 'es5',
45
- bracketSpacing: true,
46
- bracketSameLine: false,
47
- printWidth: 80,
48
- arrowParens: 'always',
49
- },
50
- },
33
],
34
};
compiler/apps/playground/__tests__/e2e/page.spec.ts
+14
-14
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { expect, test } from "@playwright/test";
9
-import { encodeStore, type Store } from "../../lib/stores";
8
+import {expect, test} from '@playwright/test';
9
+import {encodeStore, type Store} from '../../lib/stores';
10
11
const STORE: Store = {
12
source: `export default function TestComponent({ x }) {
@@ -17,33 +17,33 @@ const STORE: Store = {
17
const HASH = encodeStore(STORE);
18
19
function concat(data: Array<string>): string {
20
- return data.join("");
20
+ return data.join('');
21
}
22
23
-test("editor should compile successfully", async ({ page }) => {
24
- await page.goto(`/#${HASH}`, { waitUntil: "networkidle" });
23
+test('editor should compile successfully', async ({page}) => {
24
+ await page.goto(`/#${HASH}`, {waitUntil: 'networkidle'});
25
await page.screenshot({
26
fullPage: true,
27
- path: "test-results/00-on-networkidle.png",
27
+ path: 'test-results/00-on-networkidle.png',
28
});
29
30
// User input from hash compiles
31
await page.screenshot({
32
fullPage: true,
33
- path: "test-results/01-show-js-before.png",
33
+ path: 'test-results/01-show-js-before.png',
34
});
35
const userInput =
36
- (await page.locator(".monaco-editor").nth(2).allInnerTexts()) ?? [];
37
- expect(concat(userInput)).toMatchSnapshot("user-input.txt");
36
+ (await page.locator('.monaco-editor').nth(2).allInnerTexts()) ?? [];
37
+ expect(concat(userInput)).toMatchSnapshot('user-input.txt');
38
39
// Reset button works
40
- page.on("dialog", (dialog) => dialog.accept());
41
- await page.getByRole("button", { name: "Reset" }).click();
40
+ page.on('dialog', dialog => dialog.accept());
41
+ await page.getByRole('button', {name: 'Reset'}).click();
42
await page.screenshot({
43
fullPage: true,
44
- path: "test-results/02-show-js-after.png",
44
+ path: 'test-results/02-show-js-after.png',
45
});
46
const defaultInput =
47
- (await page.locator(".monaco-editor").nth(2).allInnerTexts()) ?? [];
48
- expect(concat(defaultInput)).toMatchSnapshot("default-input.txt");
47
+ (await page.locator('.monaco-editor').nth(2).allInnerTexts()) ?? [];
48
+ expect(concat(defaultInput)).toMatchSnapshot('default-input.txt');
49
});
compiler/apps/playground/app/index.tsx
+10
-12
@@ -5,25 +5,24 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import type { NextPage } from "next";
9
-import Head from "next/head";
10
-import { SnackbarProvider } from "notistack";
11
-import { Editor, Header, StoreProvider } from "../components";
12
-import MessageSnackbar from "../components/Message";
8
+import type {NextPage} from 'next';
9
+import Head from 'next/head';
10
+import {SnackbarProvider} from 'notistack';
11
+import {Editor, Header, StoreProvider} from '../components';
12
+import MessageSnackbar from '../components/Message';
13
14
const Home: NextPage = () => {
15
return (
16
<div className="flex flex-col w-screen h-screen font-light">
17
<Head>
18
<title>
19
- {process.env.NODE_ENV === "development"
20
- ? "[DEV] React Compiler Playground"
21
- : "React Compiler Playground"}
19
+ {process.env.NODE_ENV === 'development'
20
+ ? '[DEV] React Compiler Playground'
21
+ : 'React Compiler Playground'}
22
</title>
23
<meta
24
name="viewport"
25
- content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"
26
- ></meta>
25
+ content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"></meta>
26
<link rel="icon" href="/favicon.ico" />
27
<link rel="manifest" href="/site.webmanifest" />
28
<link
@@ -45,8 +44,7 @@ const Home: NextPage = () => {
44
<SnackbarProvider
45
preventDuplicate
46
maxSnack={10}
48
- Components={{ message: MessageSnackbar }}
49
- >
47
+ Components={{message: MessageSnackbar}}>
48
<Header />
49
<Editor />
50
</SnackbarProvider>
compiler/apps/playground/app/layout.tsx
+7
-12
@@ -5,26 +5,21 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import "../styles/globals.css";
8
+import '../styles/globals.css';
9
10
-export default function RootLayout({
11
- children,
12
-}: {
13
- children: React.ReactNode;
14
-}) {
15
- "use no memo";
10
+export default function RootLayout({children}: {children: React.ReactNode}) {
11
+ 'use no memo';
12
return (
13
<html lang="en">
14
<head>
15
<title>
20
- {process.env.NODE_ENV === "development"
21
- ? "[DEV] React Compiler Playground"
22
- : "React Compiler Playground"}
16
+ {process.env.NODE_ENV === 'development'
17
+ ? '[DEV] React Compiler Playground'
18
+ : 'React Compiler Playground'}
19
</title>
20
<meta
21
name="viewport"
26
- content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"
27
- ></meta>
22
+ content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"></meta>
23
<link rel="icon" href="/favicon.ico" />
24
<link rel="manifest" href="/site.webmanifest" />
25
<link
compiler/apps/playground/app/page.tsx
+5
-6
@@ -5,11 +5,11 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-"use client";
8
+'use client';
9
10
-import { SnackbarProvider } from "notistack";
11
-import { Editor, Header, StoreProvider } from "../components";
12
-import MessageSnackbar from "../components/Message";
10
+import {SnackbarProvider} from 'notistack';
11
+import {Editor, Header, StoreProvider} from '../components';
12
+import MessageSnackbar from '../components/Message';
13
14
export default function Hoot() {
15
return (
@@ -17,8 +17,7 @@ export default function Hoot() {
17
<SnackbarProvider
18
preventDuplicate
19
maxSnack={10}
20
- Components={{ message: MessageSnackbar }}
21
- >
20
+ Components={{message: MessageSnackbar}}>
21
<Header />
22
<Editor />
23
</SnackbarProvider>
compiler/apps/playground/babel.config.js
+3
-3
@@ -8,12 +8,12 @@
8
module.exports = function (api) {
9
api.cache(true);
10
return {
11
- presets: ["next/babel"],
11
+ presets: ['next/babel'],
12
plugins: [
13
[
14
- "babel-plugin-react-compiler",
14
+ 'babel-plugin-react-compiler',
15
{
16
- runtimeModule: "react-compiler-runtime",
16
+ runtimeModule: 'react-compiler-runtime',
17
},
18
],
19
],
compiler/apps/playground/colors.js
+66
-66
@@ -11,86 +11,86 @@
11
12
module.exports = {
13
// Text colors
14
- primary: "#23272F", // gray-90
15
- "primary-dark": "#F6F7F9", // gray-5
16
- secondary: "#404756", // gray-70
17
- "secondary-dark": "#EBECF0", // gray-10
18
- link: "#087EA4", // blue-50
19
- "link-dark": "#149ECA", // blue-40
20
- syntax: "#EBECF0", // gray-10
21
- wash: "#FFFFFF",
22
- "wash-dark": "#23272F", // gray-90
23
- card: "#F6F7F9", // gray-05
24
- "card-dark": "#343A46", // gray-80
25
- highlight: "#E6F7FF", // blue-10
26
- "highlight-dark": "rgba(88,175,223,.1)",
27
- border: "#EBECF0", // gray-10
28
- "border-dark": "#343A46", // gray-80
29
- "secondary-button": "#EBECF0", // gray-10
30
- "secondary-button-dark": "#404756", // gray-70
14
+ primary: '#23272F', // gray-90
15
+ 'primary-dark': '#F6F7F9', // gray-5
16
+ secondary: '#404756', // gray-70
17
+ 'secondary-dark': '#EBECF0', // gray-10
18
+ link: '#087EA4', // blue-50
19
+ 'link-dark': '#149ECA', // blue-40
20
+ syntax: '#EBECF0', // gray-10
21
+ wash: '#FFFFFF',
22
+ 'wash-dark': '#23272F', // gray-90
23
+ card: '#F6F7F9', // gray-05
24
+ 'card-dark': '#343A46', // gray-80
25
+ highlight: '#E6F7FF', // blue-10
26
+ 'highlight-dark': 'rgba(88,175,223,.1)',
27
+ border: '#EBECF0', // gray-10
28
+ 'border-dark': '#343A46', // gray-80
29
+ 'secondary-button': '#EBECF0', // gray-10
30
+ 'secondary-button-dark': '#404756', // gray-70
31
32
// Gray
33
- "gray-95": "#16181D",
34
- "gray-90": "#23272F",
35
- "gray-80": "#343A46",
36
- "gray-70": "#404756",
37
- "gray-60": "#4E5769",
38
- "gray-50": "#5E687E", // unused
39
- "gray-40": "#78839B",
40
- "gray-30": "#99A1B3",
41
- "gray-20": "#BCC1CD",
42
- "gray-10": "#EBECF0",
43
- "gray-5": "#F6F7F9",
33
+ 'gray-95': '#16181D',
34
+ 'gray-90': '#23272F',
35
+ 'gray-80': '#343A46',
36
+ 'gray-70': '#404756',
37
+ 'gray-60': '#4E5769',
38
+ 'gray-50': '#5E687E', // unused
39
+ 'gray-40': '#78839B',
40
+ 'gray-30': '#99A1B3',
41
+ 'gray-20': '#BCC1CD',
42
+ 'gray-10': '#EBECF0',
43
+ 'gray-5': '#F6F7F9',
44
45
// Blue
46
- "blue-60": "#045975",
47
- "blue-50": "#087EA4",
48
- "blue-40": "#149ECA", // Brand Blue
49
- "blue-30": "#58C4DC", // unused
50
- "blue-20": "#ABE2ED",
51
- "blue-10": "#E6F7FF", // todo: doesn't match illustrations
52
- "blue-5": "#E6F6FA",
46
+ 'blue-60': '#045975',
47
+ 'blue-50': '#087EA4',
48
+ 'blue-40': '#149ECA', // Brand Blue
49
+ 'blue-30': '#58C4DC', // unused
50
+ 'blue-20': '#ABE2ED',
51
+ 'blue-10': '#E6F7FF', // todo: doesn't match illustrations
52
+ 'blue-5': '#E6F6FA',
53
54
// Yellow
55
- "yellow-60": "#B65700",
56
- "yellow-50": "#C76A15",
57
- "yellow-40": "#DB7D27", // unused
58
- "yellow-30": "#FABD62", // unused
59
- "yellow-20": "#FCDEB0", // unused
60
- "yellow-10": "#FDE7C7",
61
- "yellow-5": "#FEF5E7",
55
+ 'yellow-60': '#B65700',
56
+ 'yellow-50': '#C76A15',
57
+ 'yellow-40': '#DB7D27', // unused
58
+ 'yellow-30': '#FABD62', // unused
59
+ 'yellow-20': '#FCDEB0', // unused
60
+ 'yellow-10': '#FDE7C7',
61
+ 'yellow-5': '#FEF5E7',
62
63
// Purple
64
- "purple-60": "#2B3491", // unused
65
- "purple-50": "#575FB7",
66
- "purple-40": "#6B75DB",
67
- "purple-30": "#8891EC",
68
- "purple-20": "#C3C8F5", // unused
69
- "purple-10": "#E7E9FB",
70
- "purple-5": "#F3F4FD",
64
+ 'purple-60': '#2B3491', // unused
65
+ 'purple-50': '#575FB7',
66
+ 'purple-40': '#6B75DB',
67
+ 'purple-30': '#8891EC',
68
+ 'purple-20': '#C3C8F5', // unused
69
+ 'purple-10': '#E7E9FB',
70
+ 'purple-5': '#F3F4FD',
71
72
// Green
73
- "green-60": "#2B6E62",
74
- "green-50": "#388F7F",
75
- "green-40": "#44AC99",
76
- "green-30": "#7FCCBF",
77
- "green-20": "#ABDED5",
78
- "green-10": "#E5F5F2",
79
- "green-5": "#F4FBF9",
73
+ 'green-60': '#2B6E62',
74
+ 'green-50': '#388F7F',
75
+ 'green-40': '#44AC99',
76
+ 'green-30': '#7FCCBF',
77
+ 'green-20': '#ABDED5',
78
+ 'green-10': '#E5F5F2',
79
+ 'green-5': '#F4FBF9',
80
81
// RED
82
- "red-60": "#712D28",
83
- "red-50": "#A6423A", // unused
84
- "red-40": "#C1554D",
85
- "red-30": "#D07D77",
86
- "red-20": "#E5B7B3", // unused
87
- "red-10": "#F2DBD9", // unused
88
- "red-5": "#FAF1F0",
82
+ 'red-60': '#712D28',
83
+ 'red-50': '#A6423A', // unused
84
+ 'red-40': '#C1554D',
85
+ 'red-30': '#D07D77',
86
+ 'red-20': '#E5B7B3', // unused
87
+ 'red-10': '#F2DBD9', // unused
88
+ 'red-5': '#FAF1F0',
89
90
// MISC
91
- "code-block": "#99a1b30f", // gray-30 @ 6%
92
- "gradient-blue": "#58C4DC", // Only used for the landing gradient for now.
91
+ 'code-block': '#99a1b30f', // gray-30 @ 6%
92
+ 'gradient-blue': '#58C4DC', // Only used for the landing gradient for now.
93
github: {
94
- highlight: "#fffbdd",
94
+ highlight: '#fffbdd',
95
},
96
};
compiler/apps/playground/components/Editor/EditorImpl.tsx
+67
-67
@@ -5,10 +5,10 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { parse as babelParse, ParserPlugin } from "@babel/parser";
9
-import * as HermesParser from "hermes-parser";
10
-import traverse, { NodePath } from "@babel/traverse";
11
-import * as t from "@babel/types";
8
+import {parse as babelParse, ParserPlugin} from '@babel/parser';
9
+import * as HermesParser from 'hermes-parser';
10
+import traverse, {NodePath} from '@babel/traverse';
11
+import * as t from '@babel/types';
12
import {
13
CompilerError,
14
CompilerErrorDetail,
@@ -20,51 +20,51 @@ import {
20
run,
21
ValueKind,
22
type Hook,
23
-} from "babel-plugin-react-compiler/src";
24
-import { type ReactFunctionType } from "babel-plugin-react-compiler/src/HIR/Environment";
25
-import clsx from "clsx";
26
-import invariant from "invariant";
27
-import { useSnackbar } from "notistack";
28
-import { useDeferredValue, useMemo } from "react";
29
-import { useMountEffect } from "../../hooks";
30
-import { defaultStore } from "../../lib/defaultStore";
23
+} from 'babel-plugin-react-compiler/src';
24
+import {type ReactFunctionType} from 'babel-plugin-react-compiler/src/HIR/Environment';
25
+import clsx from 'clsx';
26
+import invariant from 'invariant';
27
+import {useSnackbar} from 'notistack';
28
+import {useDeferredValue, useMemo} from 'react';
29
+import {useMountEffect} from '../../hooks';
30
+import {defaultStore} from '../../lib/defaultStore';
31
import {
32
createMessage,
33
initStoreFromUrlOrLocalStorage,
34
MessageLevel,
35
MessageSource,
36
type Store,
37
-} from "../../lib/stores";
38
-import { useStore, useStoreDispatch } from "../StoreContext";
39
-import Input from "./Input";
37
+} from '../../lib/stores';
38
+import {useStore, useStoreDispatch} from '../StoreContext';
39
+import Input from './Input';
40
import {
41
CompilerOutput,
42
default as Output,
43
PrintedCompilerPipelineValue,
44
-} from "./Output";
45
-import { printFunctionWithOutlined } from "babel-plugin-react-compiler/src/HIR/PrintHIR";
46
-import { printReactiveFunctionWithOutlined } from "babel-plugin-react-compiler/src/ReactiveScopes/PrintReactiveFunction";
44
+} from './Output';
45
+import {printFunctionWithOutlined} from 'babel-plugin-react-compiler/src/HIR/PrintHIR';
46
+import {printReactiveFunctionWithOutlined} from 'babel-plugin-react-compiler/src/ReactiveScopes/PrintReactiveFunction';
47
48
-function parseInput(input: string, language: "flow" | "typescript") {
48
+function parseInput(input: string, language: 'flow' | 'typescript') {
49
// Extract the first line to quickly check for custom test directives
50
- if (language === "flow") {
50
+ if (language === 'flow') {
51
return HermesParser.parse(input, {
52
babel: true,
53
- flow: "all",
54
- sourceType: "module",
53
+ flow: 'all',
54
+ sourceType: 'module',
55
enableExperimentalComponentSyntax: true,
56
});
57
} else {
58
return babelParse(input, {
59
- plugins: ["typescript", "jsx"],
60
- sourceType: "module",
59
+ plugins: ['typescript', 'jsx'],
60
+ sourceType: 'module',
61
});
62
}
63
}
64
65
function parseFunctions(
66
source: string,
67
- language: "flow" | "typescript"
67
+ language: 'flow' | 'typescript',
68
): Array<
69
NodePath<
70
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
@@ -105,7 +105,7 @@ function parseFunctions(
105
106
const COMMON_HOOKS: Array<[string, Hook]> = [
107
[
108
- "useFragment",
108
+ 'useFragment',
109
{
110
valueKind: ValueKind.Frozen,
111
effectKind: Effect.Freeze,
@@ -114,7 +114,7 @@ const COMMON_HOOKS: Array<[string, Hook]> = [
114
},
115
],
116
[
117
- "usePaginationFragment",
117
+ 'usePaginationFragment',
118
{
119
valueKind: ValueKind.Frozen,
120
effectKind: Effect.Freeze,
@@ -123,7 +123,7 @@ const COMMON_HOOKS: Array<[string, Hook]> = [
123
},
124
],
125
[
126
- "useRefetchableFragment",
126
+ 'useRefetchableFragment',
127
{
128
valueKind: ValueKind.Frozen,
129
effectKind: Effect.Freeze,
@@ -132,7 +132,7 @@ const COMMON_HOOKS: Array<[string, Hook]> = [
132
},
133
],
134
[
135
- "useLazyLoadQuery",
135
+ 'useLazyLoadQuery',
136
{
137
valueKind: ValueKind.Frozen,
138
effectKind: Effect.Freeze,
@@ -141,7 +141,7 @@ const COMMON_HOOKS: Array<[string, Hook]> = [
141
},
142
],
143
[
144
- "usePreloadedQuery",
144
+ 'usePreloadedQuery',
145
{
146
valueKind: ValueKind.Frozen,
147
effectKind: Effect.Freeze,
@@ -156,22 +156,22 @@ function isHookName(s: string): boolean {
156
}
157
158
function getReactFunctionType(
159
- id: NodePath<t.Identifier | null | undefined>
159
+ id: NodePath<t.Identifier | null | undefined>,
160
): ReactFunctionType {
161
if (id && id.node && id.isIdentifier()) {
162
if (isHookName(id.node.name)) {
163
- return "Hook";
163
+ return 'Hook';
164
}
165
166
const isPascalCaseNameSpace = /^[A-Z].*/;
167
if (isPascalCaseNameSpace.test(id.node.name)) {
168
- return "Component";
168
+ return 'Component';
169
}
170
}
171
- return "Other";
171
+ return 'Other';
172
}
173
174
-function compile(source: string): [CompilerOutput, "flow" | "typescript"] {
174
+function compile(source: string): [CompilerOutput, 'flow' | 'typescript'] {
175
const results = new Map<string, PrintedCompilerPipelineValue[]>();
176
const error = new CompilerError();
177
const upsert = (result: PrintedCompilerPipelineValue) => {
@@ -182,15 +182,15 @@ function compile(source: string): [CompilerOutput, "flow" | "typescript"] {
182
results.set(result.name, [result]);
183
}
184
};
185
- let language: "flow" | "typescript";
185
+ let language: 'flow' | 'typescript';
186
if (source.match(/\@flow/)) {
187
- language = "flow";
187
+ language = 'flow';
188
} else {
189
- language = "typescript";
189
+ language = 'typescript';
190
}
191
try {
192
// Extract the first line to quickly check for custom test directives
193
- const pragma = source.substring(0, source.indexOf("\n"));
193
+ const pragma = source.substring(0, source.indexOf('\n'));
194
const config = parseConfigPragma(pragma);
195
196
for (const fn of parseFunctions(source, language)) {
@@ -199,16 +199,16 @@ function compile(source: string): [CompilerOutput, "flow" | "typescript"] {
199
new CompilerErrorDetail({
200
reason: `Unexpected function type ${fn.node.type}`,
201
description:
202
- "Playground only supports parsing function declarations",
202
+ 'Playground only supports parsing function declarations',
203
severity: ErrorSeverity.Todo,
204
loc: fn.node.loc ?? null,
205
suggestions: null,
206
- })
206
+ }),
207
);
208
continue;
209
}
210
211
- const id = fn.get("id");
211
+ const id = fn.get('id');
212
for (const result of run(
213
fn,
214
{
@@ -216,20 +216,20 @@ function compile(source: string): [CompilerOutput, "flow" | "typescript"] {
216
customHooks: new Map([...COMMON_HOOKS]),
217
},
218
getReactFunctionType(id),
219
- "_c",
219
+ '_c',
220
+ null,
221
null,
222
null,
222
- null
223
)) {
224
const fnName = fn.node.id?.name ?? null;
225
switch (result.kind) {
226
- case "ast": {
226
+ case 'ast': {
227
upsert({
228
- kind: "ast",
228
+ kind: 'ast',
229
fnName,
230
name: result.name,
231
value: {
232
- type: "FunctionDeclaration",
232
+ type: 'FunctionDeclaration',
233
id: result.value.id,
234
async: result.value.async,
235
generator: result.value.generator,
@@ -239,27 +239,27 @@ function compile(source: string): [CompilerOutput, "flow" | "typescript"] {
239
});
240
break;
241
}
242
- case "hir": {
242
+ case 'hir': {
243
upsert({
244
- kind: "hir",
244
+ kind: 'hir',
245
fnName,
246
name: result.name,
247
value: printFunctionWithOutlined(result.value),
248
});
249
break;
250
}
251
- case "reactive": {
251
+ case 'reactive': {
252
upsert({
253
- kind: "reactive",
253
+ kind: 'reactive',
254
fnName,
255
name: result.name,
256
value: printReactiveFunctionWithOutlined(result.value),
257
});
258
break;
259
}
260
- case "debug": {
260
+ case 'debug': {
261
upsert({
262
- kind: "debug",
262
+ kind: 'debug',
263
fnName,
264
name: result.name,
265
value: result.value,
@@ -288,24 +288,24 @@ function compile(source: string): [CompilerOutput, "flow" | "typescript"] {
288
reason: `Unexpected failure when transforming input! ${err}`,
289
loc: null,
290
suggestions: null,
291
- })
291
+ }),
292
);
293
}
294
}
295
if (error.hasErrors()) {
296
- return [{ kind: "err", results, error: error }, language];
296
+ return [{kind: 'err', results, error: error}, language];
297
}
298
- return [{ kind: "ok", results }, language];
298
+ return [{kind: 'ok', results}, language];
299
}
300
301
export default function Editor() {
302
const store = useStore();
303
const deferredStore = useDeferredValue(store);
304
const dispatchStore = useStoreDispatch();
305
- const { enqueueSnackbar } = useSnackbar();
305
+ const {enqueueSnackbar} = useSnackbar();
306
const [compilerOutput, language] = useMemo(
307
() => compile(deferredStore.source),
308
- [deferredStore.source]
308
+ [deferredStore.source],
309
);
310
311
useMountEffect(() => {
@@ -313,35 +313,35 @@ export default function Editor() {
313
try {
314
mountStore = initStoreFromUrlOrLocalStorage();
315
} catch (e) {
316
- invariant(e instanceof Error, "Only Error may be caught.");
316
+ invariant(e instanceof Error, 'Only Error may be caught.');
317
enqueueSnackbar(e.message, {
318
- variant: "message",
318
+ variant: 'message',
319
...createMessage(
320
- "Bad URL - fell back to the default Playground.",
320
+ 'Bad URL - fell back to the default Playground.',
321
MessageLevel.Info,
322
- MessageSource.Playground
322
+ MessageSource.Playground,
323
),
324
});
325
mountStore = defaultStore;
326
}
327
dispatchStore({
328
- type: "setStore",
329
- payload: { store: mountStore },
328
+ type: 'setStore',
329
+ payload: {store: mountStore},
330
});
331
});
332
333
return (
334
<>
335
<div className="relative flex basis top-14">
336
- <div className={clsx("relative sm:basis-1/4")}>
336
+ <div className={clsx('relative sm:basis-1/4')}>
337
<Input
338
language={language}
339
errors={
340
- compilerOutput.kind === "err" ? compilerOutput.error.details : []
340
+ compilerOutput.kind === 'err' ? compilerOutput.error.details : []
341
}
342
/>
343
</div>
344
- <div className={clsx("flex sm:flex flex-wrap")}>
344
+ <div className={clsx('flex sm:flex flex-wrap')}>
345
<Output store={deferredStore} compilerOutput={compilerOutput} />
346
</div>
347
</div>
compiler/apps/playground/components/Editor/Input.tsx
+27
-28
@@ -5,28 +5,28 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import MonacoEditor, { loader, type Monaco } from "@monaco-editor/react";
9
-import { CompilerErrorDetail } from "babel-plugin-react-compiler/src";
10
-import invariant from "invariant";
11
-import type { editor } from "monaco-editor";
12
-import * as monaco from "monaco-editor";
13
-import { Resizable } from "re-resizable";
14
-import { useEffect, useState } from "react";
15
-import { renderReactCompilerMarkers } from "../../lib/reactCompilerMonacoDiagnostics";
16
-import { useStore, useStoreDispatch } from "../StoreContext";
17
-import { monacoOptions } from "./monacoOptions";
8
+import MonacoEditor, {loader, type Monaco} from '@monaco-editor/react';
9
+import {CompilerErrorDetail} from 'babel-plugin-react-compiler/src';
10
+import invariant from 'invariant';
11
+import type {editor} from 'monaco-editor';
12
+import * as monaco from 'monaco-editor';
13
+import {Resizable} from 're-resizable';
14
+import {useEffect, useState} from 'react';
15
+import {renderReactCompilerMarkers} from '../../lib/reactCompilerMonacoDiagnostics';
16
+import {useStore, useStoreDispatch} from '../StoreContext';
17
+import {monacoOptions} from './monacoOptions';
18
// TODO: Make TS recognize .d.ts files, in addition to loading them with webpack.
19
// @ts-ignore
20
-import React$Types from "../../node_modules/@types/react/index.d.ts";
20
+import React$Types from '../../node_modules/@types/react/index.d.ts';
21
22
-loader.config({ monaco });
22
+loader.config({monaco});
23
24
type Props = {
25
errors: CompilerErrorDetail[];
26
- language: "flow" | "typescript";
26
+ language: 'flow' | 'typescript';
27
};
28
29
-export default function Input({ errors, language }: Props) {
29
+export default function Input({errors, language}: Props) {
30
const [monaco, setMonaco] = useState<Monaco | null>(null);
31
const store = useStore();
32
const dispatchStore = useStoreDispatch();
@@ -36,11 +36,11 @@ export default function Input({ errors, language }: Props) {
36
if (!monaco) return;
37
const uri = monaco.Uri.parse(`file:///index.js`);
38
const model = monaco.editor.getModel(uri);
39
- invariant(model, "Model must exist for the selected input file.");
40
- renderReactCompilerMarkers({ monaco, model, details: errors });
39
+ invariant(model, 'Model must exist for the selected input file.');
40
+ renderReactCompilerMarkers({monaco, model, details: errors});
41
// N.B. that `tabSize` is a model property, not an editor property.
42
// So, the tab size has to be set per model.
43
- model.updateOptions({ tabSize: 2 });
43
+ model.updateOptions({tabSize: 2});
44
}, [monaco, errors]);
45
46
const flowDiagnosticDisable = [
@@ -64,11 +64,11 @@ export default function Input({ errors, language }: Props) {
64
8011,
65
8012,
66
8013,
67
- ...(language === "flow" ? flowDiagnosticDisable : []),
67
+ ...(language === 'flow' ? flowDiagnosticDisable : []),
68
],
69
noSemanticValidation: true,
70
// Monaco can't validate Flow component syntax
71
- noSyntaxValidation: language === "flow",
71
+ noSyntaxValidation: language === 'flow',
72
});
73
}, [monaco, language]);
74
@@ -76,7 +76,7 @@ export default function Input({ errors, language }: Props) {
76
if (!value) return;
77
78
dispatchStore({
79
- type: "updateFile",
79
+ type: 'updateFile',
80
payload: {
81
source: value,
82
},
@@ -91,11 +91,11 @@ export default function Input({ errors, language }: Props) {
91
target: monaco.languages.typescript.ScriptTarget.ES2015,
92
moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,
93
jsx: monaco.languages.typescript.JsxEmit.Preserve,
94
- typeRoots: ["node_modules/@types"],
94
+ typeRoots: ['node_modules/@types'],
95
allowSyntheticDefaultImports: true,
96
};
97
monaco.languages.typescript.javascriptDefaults.setCompilerOptions(
98
- tscOptions
98
+ tscOptions,
99
);
100
monaco.languages.typescript.typescriptDefaults.setCompilerOptions({
101
...tscOptions,
@@ -106,7 +106,7 @@ export default function Input({ errors, language }: Props) {
106
// Add React type declarations to Monaco
107
const reactLib = [
108
React$Types,
109
- "file:///node_modules/@types/react/index.d.ts",
109
+ 'file:///node_modules/@types/react/index.d.ts',
110
] as [any, string];
111
monaco.languages.typescript.javascriptDefaults.addExtraLib(...reactLib);
112
monaco.languages.typescript.typescriptDefaults.addExtraLib(...reactLib);
@@ -124,17 +124,16 @@ export default function Input({ errors, language }: Props) {
124
<div className="relative flex flex-col flex-none border-r border-gray-200">
125
<Resizable
126
minWidth={650}
127
- enable={{ right: true }}
127
+ enable={{right: true}}
128
// Restrict MonacoEditor's height, since the config autoLayout:true
129
// will grow the editor to fit within parent element
130
- className="!h-[calc(100vh_-_3.5rem)]"
131
- >
130
+ className="!h-[calc(100vh_-_3.5rem)]">
131
<MonacoEditor
133
- path={"index.js"}
132
+ path={'index.js'}
133
// .js and .jsx files are specified to be TS so that Monaco can actually
134
// check their syntax using its TS language service. They are still JS files
135
// due to their extensions, so TS language features don't work.
137
- language={"javascript"}
136
+ language={'javascript'}
137
value={store.source}
138
onMount={handleMount}
139
onChange={handleChange}
compiler/apps/playground/components/Editor/Output.tsx
+52
-57
@@ -5,46 +5,46 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import generate from "@babel/generator";
9
-import * as t from "@babel/types";
8
+import generate from '@babel/generator';
9
+import * as t from '@babel/types';
10
import {
11
CodeIcon,
12
DocumentAddIcon,
13
InformationCircleIcon,
14
-} from "@heroicons/react/outline";
15
-import MonacoEditor, { DiffEditor } from "@monaco-editor/react";
16
-import { type CompilerError } from "babel-plugin-react-compiler/src";
17
-import parserBabel from "prettier/plugins/babel";
18
-import * as prettierPluginEstree from "prettier/plugins/estree";
19
-import * as prettier from "prettier/standalone";
20
-import { memo, useEffect, useState } from "react";
21
-import { type Store } from "../../lib/stores";
22
-import TabbedWindow from "../TabbedWindow";
23
-import { monacoOptions } from "./monacoOptions";
14
+} from '@heroicons/react/outline';
15
+import MonacoEditor, {DiffEditor} from '@monaco-editor/react';
16
+import {type CompilerError} from 'babel-plugin-react-compiler/src';
17
+import parserBabel from 'prettier/plugins/babel';
18
+import * as prettierPluginEstree from 'prettier/plugins/estree';
19
+import * as prettier from 'prettier/standalone';
20
+import {memo, useEffect, useState} from 'react';
21
+import {type Store} from '../../lib/stores';
22
+import TabbedWindow from '../TabbedWindow';
23
+import {monacoOptions} from './monacoOptions';
24
const MemoizedOutput = memo(Output);
25
26
export default MemoizedOutput;
27
28
export type PrintedCompilerPipelineValue =
29
| {
30
- kind: "ast";
30
+ kind: 'ast';
31
name: string;
32
fnName: string | null;
33
value: t.FunctionDeclaration;
34
}
35
| {
36
- kind: "hir";
36
+ kind: 'hir';
37
name: string;
38
fnName: string | null;
39
value: string;
40
}
41
- | { kind: "reactive"; name: string; fnName: string | null; value: string }
42
- | { kind: "debug"; name: string; fnName: string | null; value: string };
41
+ | {kind: 'reactive'; name: string; fnName: string | null; value: string}
42
+ | {kind: 'debug'; name: string; fnName: string | null; value: string};
43
44
export type CompilerOutput =
45
- | { kind: "ok"; results: Map<string, PrintedCompilerPipelineValue[]> }
45
+ | {kind: 'ok'; results: Map<string, PrintedCompilerPipelineValue[]>}
46
| {
47
- kind: "err";
47
+ kind: 'err';
48
results: Map<string, PrintedCompilerPipelineValue[]>;
49
error: CompilerError;
50
};
@@ -63,7 +63,7 @@ async function tabify(source: string, compilerOutput: CompilerOutput) {
63
for (const [passName, results] of compilerOutput.results) {
64
for (const result of results) {
65
switch (result.kind) {
66
- case "hir": {
66
+ case 'hir': {
67
const prev = concattedResults.get(result.name);
68
const next = result.value;
69
const identName = `function ${result.fnName}`;
@@ -74,7 +74,7 @@ async function tabify(source: string, compilerOutput: CompilerOutput) {
74
}
75
break;
76
}
77
- case "reactive": {
77
+ case 'reactive': {
78
const prev = concattedResults.get(passName);
79
const next = result.value;
80
if (prev != null) {
@@ -84,30 +84,29 @@ async function tabify(source: string, compilerOutput: CompilerOutput) {
84
}
85
break;
86
}
87
- case "ast":
87
+ case 'ast':
88
topLevelFnDecls.push(result.value);
89
break;
90
- case "debug": {
90
+ case 'debug': {
91
concattedResults.set(passName, result.value);
92
break;
93
}
94
default: {
95
const _: never = result;
96
- throw new Error("Unexpected result kind");
96
+ throw new Error('Unexpected result kind');
97
}
98
}
99
}
100
}
101
let lastPassOutput: string | null = null;
102
- let nonDiffPasses = ["HIR", "BuildReactiveFunction", "EnvironmentConfig"];
102
+ let nonDiffPasses = ['HIR', 'BuildReactiveFunction', 'EnvironmentConfig'];
103
for (const [passName, text] of concattedResults) {
104
tabs.set(
105
passName,
106
<TextTabContent
107
output={text}
108
diff={lastPassOutput}
109
- showInfoPanel={!nonDiffPasses.includes(passName)}
110
- ></TextTabContent>
109
+ showInfoPanel={!nonDiffPasses.includes(passName)}></TextTabContent>,
110
);
111
lastPassOutput = text;
112
}
@@ -116,25 +115,24 @@ async function tabify(source: string, compilerOutput: CompilerOutput) {
115
// Make a synthetic Program so we can have a single AST with all the top level
116
// FunctionDeclarations
117
const ast = t.program(topLevelFnDecls);
119
- const { code, sourceMapUrl } = await codegen(ast, source);
118
+ const {code, sourceMapUrl} = await codegen(ast, source);
119
reorderedTabs.set(
121
- "JS",
120
+ 'JS',
121
<TextTabContent
122
output={code}
123
diff={null}
125
- showInfoPanel={false}
126
- ></TextTabContent>
124
+ showInfoPanel={false}></TextTabContent>,
125
);
126
if (sourceMapUrl) {
127
reorderedTabs.set(
130
- "SourceMap",
128
+ 'SourceMap',
129
<>
130
<iframe
131
src={sourceMapUrl}
132
className="w-full h-monaco_small sm:h-monaco"
133
title="Generated Code"
134
/>
137
- </>
135
+ </>,
136
);
137
}
138
}
@@ -146,23 +144,23 @@ async function tabify(source: string, compilerOutput: CompilerOutput) {
144
145
async function codegen(
146
ast: t.Program,
149
- source: string
150
-): Promise<{ code: any; sourceMapUrl: string | null }> {
147
+ source: string,
148
+): Promise<{code: any; sourceMapUrl: string | null}> {
149
const generated = generate(
150
ast,
153
- { sourceMaps: true, sourceFileName: "input.js" },
154
- source
151
+ {sourceMaps: true, sourceFileName: 'input.js'},
152
+ source,
153
);
154
const sourceMapUrl = getSourceMapUrl(
155
generated.code,
158
- JSON.stringify(generated.map)
156
+ JSON.stringify(generated.map),
157
);
158
const codegenOutput = await prettier.format(generated.code, {
159
semi: true,
162
- parser: "babel",
160
+ parser: 'babel',
161
plugins: [parserBabel, prettierPluginEstree],
162
});
165
- return { code: codegenOutput, sourceMapUrl };
163
+ return {code: codegenOutput, sourceMapUrl};
164
}
165
166
function utf16ToUTF8(s: string): string {
@@ -173,27 +171,27 @@ function getSourceMapUrl(code: string, map: string): string | null {
171
code = utf16ToUTF8(code);
172
map = utf16ToUTF8(map);
173
return `https://evanw.github.io/source-map-visualization/#${btoa(
176
- `${code.length}\0${code}${map.length}\0${map}`
174
+ `${code.length}\0${code}${map.length}\0${map}`,
175
)}`;
176
}
177
180
-function Output({ store, compilerOutput }: Props) {
181
- const [tabsOpen, setTabsOpen] = useState<Set<string>>(() => new Set(["JS"]));
178
+function Output({store, compilerOutput}: Props) {
179
+ const [tabsOpen, setTabsOpen] = useState<Set<string>>(() => new Set(['JS']));
180
const [tabs, setTabs] = useState<Map<string, React.ReactNode>>(
183
- () => new Map()
181
+ () => new Map(),
182
);
183
useEffect(() => {
186
- tabify(store.source, compilerOutput).then((tabs) => {
184
+ tabify(store.source, compilerOutput).then(tabs => {
185
setTabs(tabs);
186
});
187
}, [store.source, compilerOutput]);
188
191
- const changedPasses: Set<string> = new Set(["JS", "HIR"]); // Initial and final passes should always be bold
192
- let lastResult: string = "";
189
+ const changedPasses: Set<string> = new Set(['JS', 'HIR']); // Initial and final passes should always be bold
190
+ let lastResult: string = '';
191
for (const [passName, results] of compilerOutput.results) {
192
for (const result of results) {
195
- let currResult = "";
196
- if (result.kind === "hir" || result.kind === "reactive") {
193
+ let currResult = '';
194
+ if (result.kind === 'hir' || result.kind === 'reactive') {
195
currResult += `function ${result.fnName}\n\n${result.value}`;
196
}
197
if (currResult !== lastResult) {
@@ -212,18 +210,16 @@ function Output({ store, compilerOutput }: Props) {
210
tabs={tabs}
211
changedPasses={changedPasses}
212
/>
215
- {compilerOutput.kind === "err" ? (
213
+ {compilerOutput.kind === 'err' ? (
214
<div
215
className="flex flex-wrap absolute bottom-0 bg-white grow border-y border-grey-200 transition-all ease-in"
218
- style={{ width: "calc(100vw - 650px)" }}
219
- >
216
+ style={{width: 'calc(100vw - 650px)'}}>
217
<div className="w-full p-4 basis-full border-b">
218
<h2>COMPILER ERRORS</h2>
219
</div>
220
<pre
221
className="p-4 basis-full text-red-600 overflow-y-scroll whitespace-pre-wrap"
225
- style={{ width: "calc(100vw - 650px)", height: "150px" }}
226
- >
222
+ style={{width: 'calc(100vw - 650px)', height: '150px'}}>
223
<code>{compilerOutput.error.toString()}</code>
224
</pre>
225
</div>
@@ -251,8 +247,7 @@ function TextTabContent({
247
{diff != null && output !== diff ? (
248
<button
249
className="flex items-center gap-1 transition-colors duration-150 ease-in text-secondary hover:text-link"
254
- onClick={() => setDiffMode((diffMode) => !diffMode)}
255
- >
250
+ onClick={() => setDiffMode(diffMode => !diffMode)}>
251
{!diffMode ? (
252
<>
253
<DocumentAddIcon className="w-5 h-5" /> Show Diff
@@ -280,7 +275,7 @@ function TextTabContent({
275
options={{
276
...monacoOptions,
277
readOnly: true,
283
- lineNumbers: "off",
278
+ lineNumbers: 'off',
279
glyphMargin: false,
280
// Undocumented see https://github.com/Microsoft/vscode/issues/30795#issuecomment-410998882
281
lineDecorationsWidth: 0,
@@ -294,7 +289,7 @@ function TextTabContent({
289
options={{
290
...monacoOptions,
291
readOnly: true,
297
- lineNumbers: "off",
292
+ lineNumbers: 'off',
293
glyphMargin: false,
294
// Undocumented see https://github.com/Microsoft/vscode/issues/30795#issuecomment-410998882
295
lineDecorationsWidth: 0,
compiler/apps/playground/components/Editor/index.tsx
+2
-2
@@ -5,11 +5,11 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import dynamic from "next/dynamic";
8
+import dynamic from 'next/dynamic';
9
10
// monaco-editor is currently not compatible with ssr
11
// https://github.com/vercel/next.js/issues/31692
12
-const Editor = dynamic(() => import("./EditorImpl"), {
12
+const Editor = dynamic(() => import('./EditorImpl'), {
13
ssr: false,
14
});
15
compiler/apps/playground/components/Editor/monacoOptions.ts
+8
-8
@@ -5,11 +5,11 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import type { EditorProps } from "@monaco-editor/react";
8
+import type {EditorProps} from '@monaco-editor/react';
9
10
-export const monacoOptions: Partial<EditorProps["options"]> = {
10
+export const monacoOptions: Partial<EditorProps['options']> = {
11
fontSize: 14,
12
- padding: { top: 8 },
12
+ padding: {top: 8},
13
scrollbar: {
14
verticalScrollbarSize: 10,
15
alwaysConsumeMouseWheel: false,
@@ -22,11 +22,11 @@ export const monacoOptions: Partial<EditorProps["options"]> = {
22
fontFamily: '"Source Code Pro", monospace',
23
glyphMargin: true,
24
25
- autoClosingBrackets: "languageDefined",
26
- autoClosingDelete: "always",
27
- autoClosingOvertype: "always",
25
+ autoClosingBrackets: 'languageDefined',
26
+ autoClosingDelete: 'always',
27
+ autoClosingOvertype: 'always',
28
29
automaticLayout: true,
30
- wordWrap: "on",
31
- wrappingIndent: "deepIndent",
30
+ wordWrap: 'on',
31
+ wrappingIndent: 'deepIndent',
32
};
compiler/apps/playground/components/Header.tsx
+19
-22
@@ -5,24 +5,24 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { RefreshIcon, ShareIcon } from "@heroicons/react/outline";
9
-import { CheckIcon } from "@heroicons/react/solid";
10
-import clsx from "clsx";
11
-import Link from "next/link";
12
-import { useSnackbar } from "notistack";
13
-import { useState } from "react";
14
-import { defaultStore } from "../lib/defaultStore";
15
-import { IconGitHub } from "./Icons/IconGitHub";
16
-import Logo from "./Logo";
17
-import { useStoreDispatch } from "./StoreContext";
8
+import {RefreshIcon, ShareIcon} from '@heroicons/react/outline';
9
+import {CheckIcon} from '@heroicons/react/solid';
10
+import clsx from 'clsx';
11
+import Link from 'next/link';
12
+import {useSnackbar} from 'notistack';
13
+import {useState} from 'react';
14
+import {defaultStore} from '../lib/defaultStore';
15
+import {IconGitHub} from './Icons/IconGitHub';
16
+import Logo from './Logo';
17
+import {useStoreDispatch} from './StoreContext';
18
19
export default function Header() {
20
const [showCheck, setShowCheck] = useState(false);
21
const dispatchStore = useStoreDispatch();
22
- const { enqueueSnackbar, closeSnackbar } = useSnackbar();
22
+ const {enqueueSnackbar, closeSnackbar} = useSnackbar();
23
24
const handleReset = () => {
25
- if (confirm("Are you sure you want to reset the playground?")) {
25
+ if (confirm('Are you sure you want to reset the playground?')) {
26
/*
27
Close open snackbars if any. This is necessary because when displaying
28
outputs (Preview or not), we only close previous snackbars if we received
@@ -31,13 +31,13 @@ export default function Header() {
31
such as "Bad URL" will be closed by the outputs calling `closeSnackbar`.
32
*/
33
closeSnackbar();
34
- dispatchStore({ type: "setStore", payload: { store: defaultStore } });
34
+ dispatchStore({type: 'setStore', payload: {store: defaultStore}});
35
}
36
};
37
38
const handleShare = () => {
39
navigator.clipboard.writeText(location.href).then(() => {
40
- enqueueSnackbar("URL copied to clipboard");
40
+ enqueueSnackbar('URL copied to clipboard');
41
setShowCheck(true);
42
// Show the check mark icon briefly after URL is copied
43
setTimeout(() => setShowCheck(false), 1000);
@@ -49,8 +49,8 @@ export default function Header() {
49
<div className="flex items-center flex-none h-full gap-2 text-lg">
50
<Logo
51
className={clsx(
52
- "w-8 h-8 text-link",
53
- process.env.NODE_ENV === "development" && "text-yellow-600"
52
+ 'w-8 h-8 text-link',
53
+ process.env.NODE_ENV === 'development' && 'text-yellow-600',
54
)}
55
/>
56
<p className="hidden select-none sm:block">React Compiler Playground</p>
@@ -60,8 +60,7 @@ export default function Header() {
60
title="Reset Playground"
61
aria-label="Reset Playground"
62
className="flex items-center gap-1 transition-colors duration-150 ease-in text-secondary hover:text-link"
63
- onClick={handleReset}
64
- >
63
+ onClick={handleReset}>
64
<RefreshIcon className="w-5 h-5" />
65
<p className="hidden sm:block">Reset</p>
66
</button>
@@ -70,8 +69,7 @@ export default function Header() {
69
aria-label="Copy sharable URL"
70
className="flex items-center gap-1 transition-colors duration-150 ease-in text-secondary hover:text-link"
71
onClick={handleShare}
73
- disabled={showCheck}
74
- >
72
+ disabled={showCheck}>
73
{!showCheck ? (
74
<ShareIcon className="w-5 h-5" />
75
) : (
@@ -84,8 +82,7 @@ export default function Header() {
82
target="_blank"
83
rel="noreferrer noopener"
84
aria-label="Open on GitHub"
87
- className="flex items-center gap-1 transition-colors duration-150 ease-in text-secondary hover:text-link"
88
- >
85
+ className="flex items-center gap-1 transition-colors duration-150 ease-in text-secondary hover:text-link">
86
<IconGitHub />
87
</Link>
88
</div>
compiler/apps/playground/components/Icons/IconGitHub.tsx
+4
-5
@@ -5,9 +5,9 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { memo } from "react";
8
+import {memo} from 'react';
9
10
-export const IconGitHub = memo<JSX.IntrinsicElements["svg"]>(
10
+export const IconGitHub = memo<JSX.IntrinsicElements['svg']>(
11
function IconGitHub(props) {
12
return (
13
<svg
@@ -16,10 +16,9 @@ export const IconGitHub = memo<JSX.IntrinsicElements["svg"]>(
16
height="1.5em"
17
viewBox="0 -2 24 24"
18
fill="currentColor"
19
- {...props}
20
- >
19
+ {...props}>
20
<path d="M10 0a10 10 0 0 0-3.16 19.49c.5.1.68-.22.68-.48l-.01-1.7c-2.78.6-3.37-1.34-3.37-1.34-.46-1.16-1.11-1.47-1.11-1.47-.9-.62.07-.6.07-.6 1 .07 1.53 1.03 1.53 1.03.9 1.52 2.34 1.08 2.91.83.1-.65.35-1.09.63-1.34-2.22-.25-4.55-1.11-4.55-4.94 0-1.1.39-1.99 1.03-2.69a3.6 3.6 0 0 1 .1-2.64s.84-.27 2.75 1.02a9.58 9.58 0 0 1 5 0c1.91-1.3 2.75-1.02 2.75-1.02.55 1.37.2 2.4.1 2.64.64.7 1.03 1.6 1.03 2.69 0 3.84-2.34 4.68-4.57 4.93.36.31.68.92.68 1.85l-.01 2.75c0 .26.18.58.69.48A10 10 0 0 0 10 0"></path>
21
</svg>
22
);
24
- }
23
+ },
24
);
compiler/apps/playground/components/Logo.tsx
+2
-3
@@ -7,14 +7,13 @@
7
8
// https://github.com/reactjs/reactjs.org/blob/main/beta/src/components/Logo.tsx
9
10
-export default function Logo(props: JSX.IntrinsicElements["svg"]) {
10
+export default function Logo(props: JSX.IntrinsicElements['svg']) {
11
return (
12
<svg
13
viewBox="0 0 410 369"
14
fill="none"
15
xmlns="http://www.w3.org/2000/svg"
16
- {...props}
17
- >
16
+ {...props}>
17
<path
18
d="M204.995 224.552C226.56 224.552 244.042 207.07 244.042 185.506C244.042 163.941 226.56 146.459 204.995 146.459C183.43 146.459 165.948 163.941 165.948 185.506C165.948 207.07 183.43 224.552 204.995 224.552Z"
19
fill="currentColor"
compiler/apps/playground/components/Message.tsx
+11
-13
@@ -10,13 +10,13 @@ import {
10
ExclamationIcon,
11
InformationCircleIcon,
12
XIcon,
13
-} from "@heroicons/react/solid";
14
-import { CustomContentProps, SnackbarContent, useSnackbar } from "notistack";
15
-import { forwardRef } from "react";
16
-import { MessageLevel, MessageSource } from "../lib/stores";
13
+} from '@heroicons/react/solid';
14
+import {CustomContentProps, SnackbarContent, useSnackbar} from 'notistack';
15
+import {forwardRef} from 'react';
16
+import {MessageLevel, MessageSource} from '../lib/stores';
17
18
// https://notistack.com/examples/advanced/custom-component#custom-variant-(typescript)
19
-declare module "notistack" {
19
+declare module 'notistack' {
20
interface VariantOverrides {
21
message: {
22
title: string;
@@ -34,15 +34,14 @@ interface MessageProps extends CustomContentProps {
34
}
35
36
const Message = forwardRef<HTMLDivElement, MessageProps>(
37
- ({ id, title, level, source, codeframe }, ref) => {
38
- const { closeSnackbar } = useSnackbar();
37
+ ({id, title, level, source, codeframe}, ref) => {
38
+ const {closeSnackbar} = useSnackbar();
39
const isDismissible = source !== MessageSource.Playground;
40
41
return (
42
<SnackbarContent
43
ref={ref}
44
- className="flex items-start justify-between gap-3 px-4 py-3 text-sm bg-white border rounded-md shadow w-toast"
45
- >
44
+ className="flex items-start justify-between gap-3 px-4 py-3 text-sm bg-white border rounded-md shadow w-toast">
45
<div className="flex gap-3 w-toast-body">
46
{level === MessageLevel.Warning ? (
47
<div className="flex items-center justify-center flex-none rounded-md w-7 h-7 bg-amber-100">
@@ -69,16 +68,15 @@ const Message = forwardRef<HTMLDivElement, MessageProps>(
68
{isDismissible ? (
69
<button
70
className="flex items-center justify-center flex-none transition-colors duration-150 ease-in rounded-md justify-self-end group w-7 h-7 hover:bg-gray-200"
72
- onClick={() => closeSnackbar(id)}
73
- >
71
+ onClick={() => closeSnackbar(id)}>
72
<XIcon className="w-5 h-5 fill-gray-500 group-hover:fill-gray-800" />
73
</button>
74
) : null}
75
</SnackbarContent>
76
);
79
- }
77
+ },
78
);
79
82
-Message.displayName = "MessageComponent";
80
+Message.displayName = 'MessageComponent';
81
82
export default Message;
compiler/apps/playground/components/StoreContext.tsx
+12
-12
@@ -5,12 +5,12 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import type { Dispatch, ReactNode } from "react";
9
-import { useReducer } from "react";
10
-import createContext from "../lib/createContext";
11
-import { emptyStore } from "../lib/defaultStore";
12
-import type { Store } from "../lib/stores";
13
-import { saveStore } from "../lib/stores";
8
+import type {Dispatch, ReactNode} from 'react';
9
+import {useReducer} from 'react';
10
+import createContext from '../lib/createContext';
11
+import {emptyStore} from '../lib/defaultStore';
12
+import type {Store} from '../lib/stores';
13
+import {saveStore} from '../lib/stores';
14
15
const StoreContext = createContext<Store>();
16
@@ -29,7 +29,7 @@ export const useStoreDispatch = StoreDispatchContext.useContext;
29
/**
30
* Make Store and dispatch function available to all sub-components in children.
31
*/
32
-export function StoreProvider({ children }: { children: ReactNode }) {
32
+export function StoreProvider({children}: {children: ReactNode}) {
33
const [store, dispatch] = useReducer(storeReducer, emptyStore);
34
35
return (
@@ -43,13 +43,13 @@ export function StoreProvider({ children }: { children: ReactNode }) {
43
44
type ReducerAction =
45
| {
46
- type: "setStore";
46
+ type: 'setStore';
47
payload: {
48
store: Store;
49
};
50
}
51
| {
52
- type: "updateFile";
52
+ type: 'updateFile';
53
payload: {
54
source: string;
55
};
@@ -57,14 +57,14 @@ type ReducerAction =
57
58
function storeReducer(store: Store, action: ReducerAction): Store {
59
switch (action.type) {
60
- case "setStore": {
60
+ case 'setStore': {
61
const newStore = action.payload.store;
62
63
saveStore(newStore);
64
return newStore;
65
}
66
- case "updateFile": {
67
- const { source } = action.payload;
66
+ case 'updateFile': {
67
+ const {source} = action.payload;
68
69
const newStore = {
70
...store,
compiler/apps/playground/components/TabbedWindow.tsx
+10
-13
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { Resizable } from "re-resizable";
9
-import React, { useCallback } from "react";
8
+import {Resizable} from 're-resizable';
9
+import React, {useCallback} from 'react';
10
11
type TabsRecord = Map<string, React.ReactNode>;
12
@@ -21,15 +21,14 @@ export default function TabbedWindow(props: {
21
return (
22
<div
23
className="flex items-center justify-center"
24
- style={{ width: "calc(100vw - 650px)" }}
25
- >
24
+ style={{width: 'calc(100vw - 650px)'}}>
25
No compiler output detected, see errors below
26
</div>
27
);
28
}
29
return (
30
<div className="flex flex-row">
32
- {Array.from(props.tabs.keys()).map((name) => {
31
+ {Array.from(props.tabs.keys()).map(name => {
32
return (
33
<TabbedWindowItem
34
name={name}
@@ -73,15 +72,14 @@ function TabbedWindowItem({
72
return (
73
<div key={name} className="flex flex-row">
74
{isShow ? (
76
- <Resizable className="border-r" minWidth={550} enable={{ right: true }}>
75
+ <Resizable className="border-r" minWidth={550} enable={{right: true}}>
76
<h2
77
title="Minimize tab"
78
aria-label="Minimize tab"
79
onClick={toggleTabs}
80
className={`p-4 duration-150 ease-in border-b cursor-pointer border-grey-200 ${
82
- hasChanged ? "font-bold" : "font-light"
83
- } text-secondary hover:text-link`}
84
- >
81
+ hasChanged ? 'font-bold' : 'font-light'
82
+ } text-secondary hover:text-link`}>
83
- {name}
84
</h2>
85
{tabs.get(name) ?? <div>No output for {name}</div>}
@@ -91,12 +89,11 @@ function TabbedWindowItem({
89
<button
90
title={`Expand compiler tab: ${name}`}
91
aria-label={`Expand compiler tab: ${name}`}
94
- style={{ transform: "rotate(90deg) translate(-50%)" }}
92
+ style={{transform: 'rotate(90deg) translate(-50%)'}}
93
onClick={toggleTabs}
94
className={`flex-grow-0 w-5 transition-colors duration-150 ease-in ${
97
- hasChanged ? "font-bold" : "font-light"
98
- } text-secondary hover:text-link`}
99
- >
95
+ hasChanged ? 'font-bold' : 'font-light'
96
+ } text-secondary hover:text-link`}>
97
{name}
98
</button>
99
</div>
compiler/apps/playground/components/index.ts
+3
-3
@@ -5,6 +5,6 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-export { default as Editor } from "./Editor";
9
-export { default as Header } from "./Header";
10
-export { StoreProvider } from "./StoreContext";
8
+export {default as Editor} from './Editor';
9
+export {default as Header} from './Header';
10
+export {StoreProvider} from './StoreContext';
compiler/apps/playground/hooks/index.ts
+1
-1
@@ -5,4 +5,4 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-export { default as useMountEffect } from "./useMountEffect";
8
+export {default as useMountEffect} from './useMountEffect';
compiler/apps/playground/hooks/useMountEffect.ts
+2
-2
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import type { EffectCallback } from "react";
9
-import { useEffect } from "react";
8
+import type {EffectCallback} from 'react';
9
+import {useEffect} from 'react';
10
11
export default function useMountEffect(effect: EffectCallback) {
12
return useEffect(effect, []);
compiler/apps/playground/lib/createContext.ts
+3
-3
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import React from "react";
8
+import React from 'react';
9
10
/**
11
* Replacement to React.createContext.
@@ -29,9 +29,9 @@ export default function createContext<T>() {
29
function useContext() {
30
const c = React.useContext(context);
31
if (!c)
32
- throw new Error("useContext must be within a Provider with a value");
32
+ throw new Error('useContext must be within a Provider with a value');
33
return c;
34
}
35
36
- return { useContext, Provider: context.Provider };
36
+ return {useContext, Provider: context.Provider};
37
}
compiler/apps/playground/lib/defaultStore.ts
+2
-2
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import type { Store } from "./stores";
8
+import type {Store} from './stores';
9
10
const index = `\
11
export default function MyApp() {
@@ -18,5 +18,5 @@ export const defaultStore: Store = {
18
};
19
20
export const emptyStore: Store = {
21
- source: "",
21
+ source: '',
22
};
compiler/apps/playground/lib/reactCompilerMonacoDiagnostics.ts
+13
-13
@@ -5,16 +5,16 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { Monaco } from "@monaco-editor/react";
8
+import {Monaco} from '@monaco-editor/react';
9
import {
10
CompilerErrorDetail,
11
ErrorSeverity,
12
-} from "babel-plugin-react-compiler/src";
13
-import { MarkerSeverity, type editor } from "monaco-editor";
12
+} from 'babel-plugin-react-compiler/src';
13
+import {MarkerSeverity, type editor} from 'monaco-editor';
14
15
function mapReactCompilerSeverityToMonaco(
16
level: ErrorSeverity,
17
- monaco: Monaco
17
+ monaco: Monaco,
18
): MarkerSeverity {
19
switch (level) {
20
case ErrorSeverity.Todo:
@@ -26,9 +26,9 @@ function mapReactCompilerSeverityToMonaco(
26
27
function mapReactCompilerDiagnosticToMonacoMarker(
28
detail: CompilerErrorDetail,
29
- monaco: Monaco
29
+ monaco: Monaco,
30
): editor.IMarkerData | null {
31
- if (detail.loc == null || typeof detail.loc === "symbol") {
31
+ if (detail.loc == null || typeof detail.loc === 'symbol') {
32
return null;
33
}
34
const severity = mapReactCompilerSeverityToMonaco(detail.severity, monaco);
@@ -63,27 +63,27 @@ export function renderReactCompilerMarkers({
63
markers.push(marker);
64
}
65
if (markers.length > 0) {
66
- monaco.editor.setModelMarkers(model, "owner", markers);
67
- const newDecorations = markers.map((marker) => {
66
+ monaco.editor.setModelMarkers(model, 'owner', markers);
67
+ const newDecorations = markers.map(marker => {
68
return {
69
range: new monaco.Range(
70
marker.startLineNumber,
71
marker.startColumn,
72
marker.endLineNumber,
73
- marker.endColumn
73
+ marker.endColumn,
74
),
75
options: {
76
isWholeLine: true,
77
- glyphMarginClassName: "bg-red-300",
77
+ glyphMarginClassName: 'bg-red-300',
78
},
79
};
80
});
81
decorations = model.deltaDecorations(decorations, newDecorations);
82
} else {
83
- monaco.editor.setModelMarkers(model, "owner", []);
83
+ monaco.editor.setModelMarkers(model, 'owner', []);
84
decorations = model.deltaDecorations(
85
- model.getAllDecorations().map((d) => d.id),
86
- []
85
+ model.getAllDecorations().map(d => d.id),
86
+ [],
87
);
88
}
89
}
compiler/apps/playground/lib/stores/index.ts
+2
-2
@@ -5,5 +5,5 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-export * from "./messages";
9
-export * from "./store";
8
+export * from './messages';
9
+export * from './store';
compiler/apps/playground/lib/stores/messages.ts
+3
-3
@@ -27,10 +27,10 @@ export interface Message {
27
export function createMessage(
28
message: string,
29
level: MessageLevel,
30
- source: MessageSource
30
+ source: MessageSource,
31
): Message {
32
- const [title, ...body] = message.split("\n");
33
- const codeframe = body.length > 0 ? body.join("\n") : undefined;
32
+ const [title, ...body] = message.split('\n');
33
+ const codeframe = body.length > 0 ? body.join('\n') : undefined;
34
35
return {
36
source,
compiler/apps/playground/lib/stores/store.ts
+10
-10
@@ -5,12 +5,12 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import invariant from "invariant";
8
+import invariant from 'invariant';
9
import {
10
compressToEncodedURIComponent,
11
decompressFromEncodedURIComponent,
12
-} from "lz-string";
13
-import { defaultStore } from "../defaultStore";
12
+} from 'lz-string';
13
+import {defaultStore} from '../defaultStore';
14
15
/**
16
* Global Store for Playground
@@ -30,8 +30,8 @@ export function decodeStore(hash: string): Store {
30
*/
31
export function saveStore(store: Store) {
32
const hash = encodeStore(store);
33
- localStorage.setItem("playgroundStore", hash);
34
- history.replaceState({}, "", `#${hash}`);
33
+ localStorage.setItem('playgroundStore', hash);
34
+ history.replaceState({}, '', `#${hash}`);
35
}
36
37
/**
@@ -41,9 +41,9 @@ export function saveStore(store: Store) {
41
function isValidStore(raw: unknown): raw is Store {
42
return (
43
raw != null &&
44
- typeof raw == "object" &&
45
- "source" in raw &&
46
- typeof raw["source"] === "string"
44
+ typeof raw == 'object' &&
45
+ 'source' in raw &&
46
+ typeof raw['source'] === 'string'
47
);
48
}
49
@@ -53,7 +53,7 @@ function isValidStore(raw: unknown): raw is Store {
53
*/
54
export function initStoreFromUrlOrLocalStorage(): Store {
55
const encodedSourceFromUrl = location.hash.slice(1);
56
- const encodedSourceFromLocal = localStorage.getItem("playgroundStore");
56
+ const encodedSourceFromLocal = localStorage.getItem('playgroundStore');
57
const encodedSource = encodedSourceFromUrl || encodedSourceFromLocal;
58
59
// No data in the URL and no data in the localStorage to fallback to.
@@ -62,6 +62,6 @@ export function initStoreFromUrlOrLocalStorage(): Store {
62
63
const raw = decodeStore(encodedSource);
64
65
- invariant(isValidStore(raw), "Invalid Store");
65
+ invariant(isValidStore(raw), 'Invalid Store');
66
return raw;
67
}
compiler/apps/playground/next.config.js
+8
-8
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-const MonacoWebpackPlugin = require("monaco-editor-webpack-plugin");
9
-const path = require("path");
8
+const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
9
+const path = require('path');
10
11
const nextConfig = {
12
reactStrictMode: true,
@@ -14,24 +14,24 @@ const nextConfig = {
14
// Load *.d.ts files as strings using https://webpack.js.org/guides/asset-modules/#source-assets.
15
config.module.rules.push({
16
test: /\.d\.ts/,
17
- type: "asset/source",
17
+ type: 'asset/source',
18
});
19
20
// Monaco Editor
21
if (!options.isServer) {
22
config.plugins.push(
23
new MonacoWebpackPlugin({
24
- languages: ["typescript", "javascript"],
25
- filename: "static/[name].worker.js",
24
+ languages: ['typescript', 'javascript'],
25
+ filename: 'static/[name].worker.js',
26
})
27
);
28
}
29
30
config.resolve.alias = {
31
...config.resolve.alias,
32
- "react-compiler-runtime": path.resolve(
32
+ 'react-compiler-runtime': path.resolve(
33
__dirname,
34
- "../../packages/react-compiler-runtime"
34
+ '../../packages/react-compiler-runtime'
35
),
36
};
37
config.resolve.fallback = {
@@ -43,7 +43,7 @@ const nextConfig = {
43
return config;
44
},
45
46
- transpilePackages: ["monaco-editor"],
46
+ transpilePackages: ['monaco-editor'],
47
};
48
49
module.exports = nextConfig;
compiler/apps/playground/playwright.config.js
+9
-9
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { defineConfig, devices } from "@playwright/test";
9
-import path from "path";
8
+import {defineConfig, devices} from '@playwright/test';
9
+import path from 'path';
10
11
// Use process.env.PORT by default and fallback to port 3000
12
const PORT = process.env.PORT || 3000;
@@ -19,19 +19,19 @@ export default defineConfig({
19
// Timeout per test
20
timeout: 30 * 1000,
21
// Test directory
22
- testDir: path.join(__dirname, "__tests__/e2e"),
22
+ testDir: path.join(__dirname, '__tests__/e2e'),
23
// If a test fails, retry it additional 2 times
24
retries: 2,
25
// Artifacts folder where screenshots, videos, and traces are stored.
26
- outputDir: "test-results/",
26
+ outputDir: 'test-results/',
27
// Note: we only use text snapshots, so its safe to omit the host environment name
28
- snapshotPathTemplate: "{testDir}/__snapshots__/{testFilePath}/{arg}{ext}",
28
+ snapshotPathTemplate: '{testDir}/__snapshots__/{testFilePath}/{arg}{ext}',
29
30
// Run your local dev server before starting the tests:
31
// https://playwright.dev/docs/test-advanced#launching-a-development-web-server-during-the-tests
32
webServer: {
33
command:
34
- "yarn workspace babel-plugin-react-compiler build && yarn workspace react-compiler-runtime build && yarn dev",
34
+ 'yarn workspace babel-plugin-react-compiler build && yarn workspace react-compiler-runtime build && yarn dev',
35
url: baseURL,
36
timeout: 300 * 1000,
37
reuseExistingServer: !process.env.CI,
@@ -44,7 +44,7 @@ export default defineConfig({
44
45
// Retry a test if its failing with enabled tracing. This allows you to analyze the DOM, console logs, network traffic etc.
46
// More information: https://playwright.dev/docs/trace-viewer
47
- trace: "retry-with-trace",
47
+ trace: 'retry-with-trace',
48
49
// All available context options: https://playwright.dev/docs/api/class-browser#browser-new-context
50
// contextOptions: {
@@ -54,8 +54,8 @@ export default defineConfig({
54
55
projects: [
56
{
57
- name: "chromium",
58
- use: { ...devices["Desktop Chrome"] },
57
+ name: 'chromium',
58
+ use: {...devices['Desktop Chrome']},
59
},
60
// {
61
// name: 'Desktop Firefox',
compiler/apps/playground/scripts/downloadFonts.js
+4
-4
@@ -5,16 +5,16 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-const { execSync } = require("child_process");
8
+const {execSync} = require('child_process');
9
10
// So that we don't need to check them into the repo.
11
// See https://github.com/reactjs/reactjs.org/blob/main/beta/scripts/downloadFonts.js.
12
execSync(
13
- "curl https://conf.reactjs.org/fonts/Optimistic_Display_W_Lt.woff2 --output public/fonts/Optimistic_Display_W_Lt.woff2"
13
+ 'curl https://conf.reactjs.org/fonts/Optimistic_Display_W_Lt.woff2 --output public/fonts/Optimistic_Display_W_Lt.woff2'
14
);
15
execSync(
16
- "curl https://conf.reactjs.org/fonts/Optimistic_Display_W_Md.woff2 --output public/fonts/Optimistic_Display_W_Md.woff2"
16
+ 'curl https://conf.reactjs.org/fonts/Optimistic_Display_W_Md.woff2 --output public/fonts/Optimistic_Display_W_Md.woff2'
17
);
18
execSync(
19
- "curl https://conf.reactjs.org/fonts/Optimistic_Display_W_Bd.woff2 --output public/fonts/Optimistic_Display_W_Bd.woff2"
19
+ 'curl https://conf.reactjs.org/fonts/Optimistic_Display_W_Bd.woff2 --output public/fonts/Optimistic_Display_W_Bd.woff2'
20
);
compiler/apps/playground/tailwind.config.js
+14
-14
@@ -5,33 +5,33 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-const defaultTheme = require("tailwindcss/defaultTheme");
9
-const colors = require("./colors");
8
+const defaultTheme = require('tailwindcss/defaultTheme');
9
+const colors = require('./colors');
10
11
module.exports = {
12
content: [
13
- "./app/**/*.{js,ts,jsx,tsx}",
14
- "./pages/**/*.{js,ts,jsx,tsx}",
15
- "./components/**/*.{js,ts,jsx,tsx}",
16
- "./lib/forgetMonacoDiagnostics.ts",
13
+ './app/**/*.{js,ts,jsx,tsx}',
14
+ './pages/**/*.{js,ts,jsx,tsx}',
15
+ './components/**/*.{js,ts,jsx,tsx}',
16
+ './lib/forgetMonacoDiagnostics.ts',
17
],
18
theme: {
19
extend: {
20
colors,
21
width: {
22
- toast: "min(900px, 100vw - 40px)",
23
- "toast-body": "calc(100% - 60px)",
24
- "toast-title": "calc(100% - 40px)",
22
+ toast: 'min(900px, 100vw - 40px)',
23
+ 'toast-body': 'calc(100% - 60px)',
24
+ 'toast-title': 'calc(100% - 40px)',
25
},
26
height: {
27
- content: "calc(100vh - 45px)",
28
- monaco: "calc(100vh - 93px)",
29
- monaco_small: "calc(100vh - 129px)",
27
+ content: 'calc(100vh - 45px)',
28
+ monaco: 'calc(100vh - 93px)',
29
+ monaco_small: 'calc(100vh - 129px)',
30
},
31
fontFamily: {
32
sans: [
33
- "Optimistic Display",
34
- "-apple-system",
33
+ 'Optimistic Display',
34
+ '-apple-system',
35
...defaultTheme.fontFamily.sans,
36
],
37
},
compiler/packages/babel-plugin-react-compiler/jest.config.js
+1
-1
@@ -7,7 +7,7 @@
7
8
/** @type {import('jest').Config} */
9
const config = {
10
- projects: ["<rootDir>/scripts/jest/*.config.js"],
10
+ projects: ['<rootDir>/scripts/jest/*.config.js'],
11
};
12
13
module.exports = config;
compiler/packages/babel-plugin-react-compiler/rollup.config.js
+17
-17
@@ -5,29 +5,29 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import typescript from "@rollup/plugin-typescript";
9
-import { nodeResolve } from "@rollup/plugin-node-resolve";
10
-import commonjs from "@rollup/plugin-commonjs";
11
-import json from "@rollup/plugin-json";
12
-import path from "path";
13
-import process from "process";
14
-import terser from "@rollup/plugin-terser";
15
-import prettier from "rollup-plugin-prettier";
16
-import banner2 from "rollup-plugin-banner2";
8
+import typescript from '@rollup/plugin-typescript';
9
+import {nodeResolve} from '@rollup/plugin-node-resolve';
10
+import commonjs from '@rollup/plugin-commonjs';
11
+import json from '@rollup/plugin-json';
12
+import path from 'path';
13
+import process from 'process';
14
+import terser from '@rollup/plugin-terser';
15
+import prettier from 'rollup-plugin-prettier';
16
+import banner2 from 'rollup-plugin-banner2';
17
18
-const NO_INLINE = new Set(["@babel/types"]);
18
+const NO_INLINE = new Set(['@babel/types']);
19
20
const DEV_ROLLUP_CONFIG = {
21
- input: "src/index.ts",
21
+ input: 'src/index.ts',
22
output: {
23
- file: "dist/index.js",
24
- format: "cjs",
23
+ file: 'dist/index.js',
24
+ format: 'cjs',
25
sourcemap: false,
26
- exports: "named",
26
+ exports: 'named',
27
},
28
plugins: [
29
typescript({
30
- tsconfig: "./tsconfig.json",
30
+ tsconfig: './tsconfig.json',
31
compilerOptions: {
32
noEmit: true,
33
},
@@ -35,8 +35,8 @@ const DEV_ROLLUP_CONFIG = {
35
json(),
36
nodeResolve({
37
preferBuiltins: true,
38
- resolveOnly: (module) => NO_INLINE.has(module) === false,
39
- rootDir: path.join(process.cwd(), ".."),
38
+ resolveOnly: module => NO_INLINE.has(module) === false,
39
+ rootDir: path.join(process.cwd(), '..'),
40
}),
41
commonjs(),
42
terser({
compiler/packages/babel-plugin-react-compiler/scripts/babel-plugin-annotate-react-code.ts
+46
-46
@@ -5,15 +5,15 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import type * as BabelCore from "@babel/core";
9
-import { NodePath } from "@babel/core";
10
-import * as t from "@babel/types";
8
+import type * as BabelCore from '@babel/core';
9
+import {NodePath} from '@babel/core';
10
+import * as t from '@babel/types';
11
12
export default function AnnotateReactCodeBabelPlugin(
13
- _babel: typeof BabelCore
13
+ _babel: typeof BabelCore,
14
): BabelCore.PluginObj {
15
return {
16
- name: "annotate-react-code",
16
+ name: 'annotate-react-code',
17
visitor: {
18
Program(prog): void {
19
annotate(prog);
@@ -56,23 +56,23 @@ function buildTypeOfReactForget(): t.Statement {
56
// typeof globalThis[Symbol.for("react_forget")]
57
return t.expressionStatement(
58
t.unaryExpression(
59
- "typeof",
59
+ 'typeof',
60
t.memberExpression(
61
- t.identifier("globalThis"),
61
+ t.identifier('globalThis'),
62
t.callExpression(
63
t.memberExpression(
64
- t.identifier("Symbol"),
65
- t.identifier("for"),
64
+ t.identifier('Symbol'),
65
+ t.identifier('for'),
66
+ false,
67
false,
67
- false
68
),
69
- [t.stringLiteral("react_forget")]
69
+ [t.stringLiteral('react_forget')],
70
),
71
true,
72
- false
72
+ false,
73
),
74
- true
75
- )
74
+ true,
75
+ ),
76
);
77
}
78
@@ -89,9 +89,9 @@ type BabelFn =
89
| NodePath<t.ArrowFunctionExpression>;
90
91
export function isComponentDeclaration(
92
- node: t.FunctionDeclaration
92
+ node: t.FunctionDeclaration,
93
): node is ComponentDeclaration {
94
- return Object.prototype.hasOwnProperty.call(node, "__componentDeclaration");
94
+ return Object.prototype.hasOwnProperty.call(node, '__componentDeclaration');
95
}
96
97
/*
@@ -101,7 +101,7 @@ export function isComponentDeclaration(
101
function isComponentOrHookLike(
102
node: NodePath<
103
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
104
- >
104
+ >,
105
): boolean {
106
const functionName = getFunctionName(node);
107
// Check if the name is component or hook like:
@@ -114,7 +114,7 @@ function isComponentOrHookLike(
114
* helpers are _usually_ named with lowercase, but some code may
115
* violate this rule
116
*/
117
- node.get("params").length <= 1
117
+ node.get('params').length <= 1
118
);
119
} else if (functionName !== null && isHook(functionName)) {
120
// Hooks have hook invocations or JSX, but can take any # of arguments
@@ -151,11 +151,11 @@ function isHook(path: NodePath<t.Expression | t.PrivateName>): boolean {
151
} else if (
152
path.isMemberExpression() &&
153
!path.node.computed &&
154
- isHook(path.get("property"))
154
+ isHook(path.get('property'))
155
) {
156
- const obj = path.get("object").node;
156
+ const obj = path.get('object').node;
157
const isPascalCaseNameSpace = /^[A-Z].*/;
158
- return obj.type === "Identifier" && isPascalCaseNameSpace.test(obj.name);
158
+ return obj.type === 'Identifier' && isPascalCaseNameSpace.test(obj.name);
159
} else {
160
return false;
161
}
@@ -177,8 +177,8 @@ function isComponentName(path: NodePath<t.Expression>): boolean {
177
function isForwardRefCallback(path: NodePath<t.Expression>): boolean {
178
return !!(
179
path.parentPath.isCallExpression() &&
180
- path.parentPath.get("callee").isExpression() &&
181
- isReactAPI(path.parentPath.get("callee"), "forwardRef")
180
+ path.parentPath.get('callee').isExpression() &&
181
+ isReactAPI(path.parentPath.get('callee'), 'forwardRef')
182
);
183
}
184
@@ -190,22 +190,22 @@ function isForwardRefCallback(path: NodePath<t.Expression>): boolean {
190
function isMemoCallback(path: NodePath<t.Expression>): boolean {
191
return (
192
path.parentPath.isCallExpression() &&
193
- path.parentPath.get("callee").isExpression() &&
194
- isReactAPI(path.parentPath.get("callee"), "memo")
193
+ path.parentPath.get('callee').isExpression() &&
194
+ isReactAPI(path.parentPath.get('callee'), 'memo')
195
);
196
}
197
198
function isReactAPI(
199
path: NodePath<t.Expression | t.PrivateName | t.V8IntrinsicIdentifier>,
200
- functionName: string
200
+ functionName: string,
201
): boolean {
202
const node = path.node;
203
return (
204
- (node.type === "Identifier" && node.name === functionName) ||
205
- (node.type === "MemberExpression" &&
206
- node.object.type === "Identifier" &&
207
- node.object.name === "React" &&
208
- node.property.type === "Identifier" &&
204
+ (node.type === 'Identifier' && node.name === functionName) ||
205
+ (node.type === 'MemberExpression' &&
206
+ node.object.type === 'Identifier' &&
207
+ node.object.name === 'React' &&
208
+ node.property.type === 'Identifier' &&
209
node.property.name === functionName)
210
);
211
}
@@ -218,7 +218,7 @@ function callsHooksOrCreatesJsx(node: NodePath<t.Node>): boolean {
218
createsJsx = true;
219
},
220
CallExpression(call) {
221
- const callee = call.get("callee");
221
+ const callee = call.get('callee');
222
if (callee.isExpression() && isHook(callee)) {
223
invokesHooks = true;
224
}
@@ -239,10 +239,10 @@ function callsHooksOrCreatesJsx(node: NodePath<t.Node>): boolean {
239
function getFunctionName(
240
path: NodePath<
241
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
242
- >
242
+ >,
243
): NodePath<t.Expression> | null {
244
if (path.isFunctionDeclaration()) {
245
- const id = path.get("id");
245
+ const id = path.get('id');
246
if (id.isIdentifier()) {
247
return id;
248
}
@@ -250,31 +250,31 @@ function getFunctionName(
250
}
251
let id: NodePath<t.LVal | t.Expression | t.PrivateName> | null = null;
252
const parent = path.parentPath;
253
- if (parent.isVariableDeclarator() && parent.get("init").node === path.node) {
253
+ if (parent.isVariableDeclarator() && parent.get('init').node === path.node) {
254
// const useHook = () => {};
255
- id = parent.get("id");
255
+ id = parent.get('id');
256
} else if (
257
parent.isAssignmentExpression() &&
258
- parent.get("right").node === path.node &&
259
- parent.get("operator") === "="
258
+ parent.get('right').node === path.node &&
259
+ parent.get('operator') === '='
260
) {
261
// useHook = () => {};
262
- id = parent.get("left");
262
+ id = parent.get('left');
263
} else if (
264
parent.isProperty() &&
265
- parent.get("value").node === path.node &&
266
- !parent.get("computed") &&
267
- parent.get("key").isLVal()
265
+ parent.get('value').node === path.node &&
266
+ !parent.get('computed') &&
267
+ parent.get('key').isLVal()
268
) {
269
/*
270
* {useHook: () => {}}
271
* {useHook() {}}
272
*/
273
- id = parent.get("key");
273
+ id = parent.get('key');
274
} else if (
275
parent.isAssignmentPattern() &&
276
- parent.get("right").node === path.node &&
277
- !parent.get("computed")
276
+ parent.get('right').node === path.node &&
277
+ !parent.get('computed')
278
) {
279
/*
280
* const {useHook = () => {}} = {};
@@ -283,7 +283,7 @@ function getFunctionName(
283
* Kinda clowny, but we'd said we'd follow spec convention for
284
* `IsAnonymousFunctionDefinition()` usage.
285
*/
286
- id = parent.get("left");
286
+ id = parent.get('left');
287
}
288
if (id !== null && (id.isIdentifier() || id.isMemberExpression())) {
289
return id;
compiler/packages/babel-plugin-react-compiler/scripts/build-react-hooks-fixures.js
+26
-26
@@ -5,27 +5,27 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-"use strict";
8
+'use strict';
9
10
-const { tests } = require("./eslint-plugin-react-hooks-test-cases");
10
+const {tests} = require('./eslint-plugin-react-hooks-test-cases');
11
const {
12
runBabelPluginReactCompiler,
13
-} = require("../dist/Babel/RunReactCompilerBabelPlugin");
14
-const fs = require("fs");
15
-const path = require("path");
16
-const prettier = require("prettier");
17
-const prettierConfigPath = require.resolve("../.prettierrc");
18
-const process = require("process");
19
-const { createHash } = require("crypto");
20
-const { create } = require("domain");
13
+} = require('../dist/Babel/RunReactCompilerBabelPlugin');
14
+const fs = require('fs');
15
+const path = require('path');
16
+const prettier = require('prettier');
17
+const prettierConfigPath = require.resolve('../.prettierrc');
18
+const process = require('process');
19
+const {createHash} = require('crypto');
20
+const {create} = require('domain');
21
22
const FIXTURES_DIR = path.join(
23
process.cwd(),
24
- "src",
25
- "__tests__",
26
- "fixtures",
27
- "compiler",
28
- "rules-of-hooks"
24
+ 'src',
25
+ '__tests__',
26
+ 'fixtures',
27
+ 'compiler',
28
+ 'rules-of-hooks'
29
);
30
31
const PRETTIER_OPTIONS = prettier.resolveConfig.sync(FIXTURES_DIR, {
@@ -34,10 +34,10 @@ const PRETTIER_OPTIONS = prettier.resolveConfig.sync(FIXTURES_DIR, {
34
35
const fixtures = [];
36
for (const test of tests.valid) {
37
- fixtures.push({ code: test.code, valid: true });
37
+ fixtures.push({code: test.code, valid: true});
38
}
39
for (const test of tests.invalid) {
40
- fixtures.push({ code: test.code, valid: false });
40
+ fixtures.push({code: test.code, valid: false});
41
}
42
43
for (const fixture of fixtures) {
@@ -47,8 +47,8 @@ for (const fixture of fixtures) {
47
// Does the fixture pass with hooks validation disabled? if not skip it
48
runBabelPluginReactCompiler(
49
fixture.code,
50
- "rules-of-hooks.js",
51
- "typescript",
50
+ 'rules-of-hooks.js',
51
+ 'typescript',
52
{
53
environment: {
54
validateHooksUsage: false,
@@ -59,8 +59,8 @@ for (const fixture of fixtures) {
59
try {
60
runBabelPluginReactCompiler(
61
fixture.code,
62
- "rules-of-hooks.js",
63
- "typescript",
62
+ 'rules-of-hooks.js',
63
+ 'typescript',
64
{
65
environment: {
66
validateHooksUsage: true,
@@ -74,7 +74,7 @@ for (const fixture of fixtures) {
74
error = e;
75
}
76
let code = fixture.code;
77
- let prefix = "";
77
+ let prefix = '';
78
if (error !== null) {
79
prefix = `todo.bail.`;
80
code = `// @skip\n// Unsupported input\n${code}`;
@@ -92,11 +92,11 @@ for (const fixture of fixtures) {
92
code = `// @skip\n// Failed but should have passed\n${code}`;
93
}
94
const formatted = prettier.format(code, PRETTIER_OPTIONS);
95
- const hmac = createHash("sha256");
96
- hmac.update(formatted, "utf8");
95
+ const hmac = createHash('sha256');
96
+ hmac.update(formatted, 'utf8');
97
let name = `${prefix}rules-of-hooks-${hmac
98
- .digest("hex")
98
+ .digest('hex')
99
.substring(0, 12)}.js`;
100
const fixturePath = path.join(FIXTURES_DIR, name);
101
- fs.writeFileSync(fixturePath, formatted, "utf8");
101
+ fs.writeFileSync(fixturePath, formatted, 'utf8');
102
}
compiler/packages/babel-plugin-react-compiler/scripts/eslint-plugin-react-hooks-test-cases.js
+3
-3
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-"use strict";
8
+'use strict';
9
10
// NOTE: Extracted from https://github.com/facebook/react/blob/main/packages/eslint-plugin-react-hooks/__tests__/ESLintRulesOfHooks-test.js
11
@@ -13,9 +13,9 @@
13
* A string template tag that removes padding from the left side of multi-line strings
14
*/
15
function normalizeIndent(strings) {
16
- const codeLines = strings[0].split("\n");
16
+ const codeLines = strings[0].split('\n');
17
const leftPadding = codeLines[1].match(/\s+/)[0];
18
- return codeLines.map((line) => line.slice(leftPadding.length)).join("\n");
18
+ return codeLines.map(line => line.slice(leftPadding.length)).join('\n');
19
}
20
21
module.exports.tests = {
compiler/packages/babel-plugin-react-compiler/scripts/jest/e2e-classic.config.js
+2
-2
@@ -5,6 +5,6 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-const makeE2EConfig = require("../jest/makeE2EConfig");
8
+const makeE2EConfig = require('../jest/makeE2EConfig');
9
10
-module.exports = makeE2EConfig("e2e no forget", false);
10
+module.exports = makeE2EConfig('e2e no forget', false);
compiler/packages/babel-plugin-react-compiler/scripts/jest/e2e-forget.config.js
+3
-3
@@ -5,9 +5,9 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-const makeE2EConfig = require("../jest/makeE2EConfig");
8
+const makeE2EConfig = require('../jest/makeE2EConfig');
9
10
-const config = makeE2EConfig("e2e with forget", true);
11
-config.setupFilesAfterEnv = ["<rootDir>/../scripts/jest/setupEnvE2E.js"];
10
+const config = makeE2EConfig('e2e with forget', true);
11
+config.setupFilesAfterEnv = ['<rootDir>/../scripts/jest/setupEnvE2E.js'];
12
13
module.exports = config;
compiler/packages/babel-plugin-react-compiler/scripts/jest/main.config.js
+4
-4
@@ -6,10 +6,10 @@
6
*/
7
8
module.exports = {
9
- displayName: "main",
10
- preset: "ts-jest",
11
- rootDir: "../../src",
12
- testPathIgnorePatterns: ["e2e", "TestDriver", "test-utils", "fixtures"],
9
+ displayName: 'main',
10
+ preset: 'ts-jest',
11
+ rootDir: '../../src',
12
+ testPathIgnorePatterns: ['e2e', 'TestDriver', 'test-utils', 'fixtures'],
13
globals: {
14
__DEV__: true,
15
},
compiler/packages/babel-plugin-react-compiler/scripts/jest/makeE2EConfig.js
+11
-11
@@ -8,27 +8,27 @@
8
module.exports = function makeE2EConfig(displayName, useForget) {
9
return {
10
displayName,
11
- testEnvironment: "jsdom",
12
- rootDir: "../../src",
13
- testMatch: ["**/*.e2e.(js|tsx)"],
11
+ testEnvironment: 'jsdom',
12
+ rootDir: '../../src',
13
+ testMatch: ['**/*.e2e.(js|tsx)'],
14
modulePathIgnorePatterns: [
15
// ignore snapshots from the opposite forget configuration
16
- useForget ? ".*\\.no-forget\\.snap$" : ".*\\.with-forget\\.snap$",
16
+ useForget ? '.*\\.no-forget\\.snap$' : '.*\\.with-forget\\.snap$',
17
// ignore snapshots from the main project
18
- ".*\\.ts\\.snap$",
18
+ '.*\\.ts\\.snap$',
19
],
20
globals: {
21
__FORGET__: useForget,
22
},
23
snapshotResolver: useForget
24
- ? "<rootDir>/../scripts/jest/snapshot-resolver-with-forget.js"
25
- : "<rootDir>/../scripts/jest/snapshot-resolver-no-forget.js",
24
+ ? '<rootDir>/../scripts/jest/snapshot-resolver-with-forget.js'
25
+ : '<rootDir>/../scripts/jest/snapshot-resolver-no-forget.js',
26
27
transform: {
28
- "\\.[tj]sx?$": useForget
29
- ? "<rootDir>/../scripts/jest/transform-with-forget"
30
- : "<rootDir>/../scripts/jest/transform-no-forget",
28
+ '\\.[tj]sx?$': useForget
29
+ ? '<rootDir>/../scripts/jest/transform-with-forget'
30
+ : '<rootDir>/../scripts/jest/transform-no-forget',
31
},
32
- transformIgnorePatterns: ["/node_modules/"],
32
+ transformIgnorePatterns: ['/node_modules/'],
33
};
34
};
compiler/packages/babel-plugin-react-compiler/scripts/jest/makeSnapshotResolver.js
+2
-2
@@ -6,7 +6,7 @@
6
*/
7
8
module.exports = function makeSnapshotResolver(useForget) {
9
- const modeExtension = useForget ? ".with-forget" : ".no-forget";
9
+ const modeExtension = useForget ? '.with-forget' : '.no-forget';
10
return {
11
resolveSnapshotPath: (testPath, snapshotExtension) =>
12
testPath + modeExtension + snapshotExtension,
@@ -17,6 +17,6 @@ module.exports = function makeSnapshotResolver(useForget) {
17
-modeExtension.length - snapshotExtension.length
18
),
19
20
- testPathForConsistencyCheck: "some/__tests__/example.test.js",
20
+ testPathForConsistencyCheck: 'some/__tests__/example.test.js',
21
};
22
};
compiler/packages/babel-plugin-react-compiler/scripts/jest/makeTransform.ts
+31
-31
@@ -5,19 +5,19 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { jsx } from "@babel/plugin-syntax-jsx";
9
-import babelJest from "babel-jest";
10
-import { compile } from "babel-plugin-react-compiler";
11
-import { execSync } from "child_process";
12
-
13
-import type { NodePath, Visitor } from "@babel/traverse";
14
-import type { CallExpression, FunctionDeclaration } from "@babel/types";
15
-import * as t from "@babel/types";
8
+import {jsx} from '@babel/plugin-syntax-jsx';
9
+import babelJest from 'babel-jest';
10
+import {compile} from 'babel-plugin-react-compiler';
11
+import {execSync} from 'child_process';
12
+
13
+import type {NodePath, Visitor} from '@babel/traverse';
14
+import type {CallExpression, FunctionDeclaration} from '@babel/types';
15
+import * as t from '@babel/types';
16
import {
17
EnvironmentConfig,
18
validateEnvironmentConfig,
19
-} from "babel-plugin-react-compiler";
20
-import { basename } from "path";
19
+} from 'babel-plugin-react-compiler';
20
+import {basename} from 'path';
21
22
/**
23
* -- IMPORTANT --
@@ -30,14 +30,14 @@ const forgetOptions: EnvironmentConfig = validateEnvironmentConfig({
30
enableAssumeHooksFollowRulesOfReact: true,
31
enableFunctionOutlining: false,
32
});
33
-const debugMode = process.env["DEBUG_FORGET_COMPILER"] != null;
33
+const debugMode = process.env['DEBUG_FORGET_COMPILER'] != null;
34
35
module.exports = (useForget: boolean) => {
36
function createTransformer() {
37
return babelJest.createTransformer({
38
passPerPreset: true,
39
presets: [
40
- "@babel/preset-typescript",
40
+ '@babel/preset-typescript',
41
{
42
plugins: [
43
useForget
@@ -49,36 +49,36 @@ module.exports = (useForget: boolean) => {
49
* (see https://github.com/jestjs/jest/blob/v29.6.2/packages/babel-jest/src/index.ts#L84)
50
*/
51
compilerCacheKey: execSync(
52
- "yarn --silent --cwd ../.. hash packages/babel-plugin-react-compiler/dist"
52
+ 'yarn --silent --cwd ../.. hash packages/babel-plugin-react-compiler/dist',
53
).toString(),
54
transformOptionsCacheKey: forgetOptions,
55
e2eTransformerCacheKey,
56
},
57
]
58
- : "@babel/plugin-syntax-jsx",
58
+ : '@babel/plugin-syntax-jsx',
59
],
60
},
61
- "@babel/preset-react",
61
+ '@babel/preset-react',
62
{
63
plugins: [
64
[
65
- function BabelPluginRewriteRequirePath(): { visitor: Visitor } {
65
+ function BabelPluginRewriteRequirePath(): {visitor: Visitor} {
66
return {
67
visitor: {
68
CallExpression(path: NodePath<CallExpression>): void {
69
- const { callee } = path.node;
69
+ const {callee} = path.node;
70
if (
71
- callee.type === "Identifier" &&
72
- callee.name === "require"
71
+ callee.type === 'Identifier' &&
72
+ callee.name === 'require'
73
) {
74
const arg = path.node.arguments[0];
75
- if (arg.type === "StringLiteral") {
75
+ if (arg.type === 'StringLiteral') {
76
/*
77
* The compiler adds requires of "React", which is expected to be a wrapper
78
* around the "react" package. For tests, we just rewrite the require.
79
*/
80
- if (arg.value === "React") {
81
- arg.value = "react";
80
+ if (arg.value === 'React') {
81
+ arg.value = 'react';
82
}
83
}
84
}
@@ -87,7 +87,7 @@ module.exports = (useForget: boolean) => {
87
};
88
},
89
],
90
- "@babel/plugin-transform-modules-commonjs",
90
+ '@babel/plugin-transform-modules-commonjs',
91
],
92
},
93
],
@@ -125,7 +125,7 @@ function isReactComponentLike(fn: NodePath<FunctionDeclaration>): boolean {
125
126
fn.traverse({
127
DirectiveLiteral(path) {
128
- if (path.node.value === "use no forget") {
128
+ if (path.node.value === 'use no forget') {
129
hasNoUseForgetDirective = true;
130
}
131
},
@@ -140,7 +140,7 @@ function isReactComponentLike(fn: NodePath<FunctionDeclaration>): boolean {
140
CallExpression(path) {
141
// Is there hook usage?
142
if (
143
- path.node.callee.type === "Identifier" &&
143
+ path.node.callee.type === 'Identifier' &&
144
!/^use[A-Z0-9]/.test(path.node.callee.name)
145
) {
146
isReactComponent = true;
@@ -170,7 +170,7 @@ function ReactForgetFunctionTransform() {
170
const filename = basename(state.file.opts.filename);
171
if (fn.node.loc && fn.node.id) {
172
console.log(
173
- ` Compiling ${filename}:${fn.node.loc.start.line}:${fn.node.loc.start.column} ${fn.node.id.name}`
173
+ ` Compiling ${filename}:${fn.node.loc.start.line}:${fn.node.loc.start.column} ${fn.node.id.name}`,
174
);
175
} else {
176
console.log(` Compiling ${filename} ${fn.node.id?.name}`);
@@ -180,11 +180,11 @@ function ReactForgetFunctionTransform() {
180
const compiled = compile(
181
fn,
182
forgetOptions,
183
- "Other",
184
- "_c",
183
+ 'Other',
184
+ '_c',
185
+ null,
186
null,
187
null,
187
- null
188
);
189
compiledFns.add(compiled);
190
@@ -193,14 +193,14 @@ function ReactForgetFunctionTransform() {
193
compiled.params,
194
compiled.body,
195
compiled.generator,
196
- compiled.async
196
+ compiled.async,
197
);
198
fn.replaceWith(fun);
199
fn.skip();
200
},
201
};
202
return {
203
- name: "react-forget-e2e",
203
+ name: 'react-forget-e2e',
204
inherits: jsx,
205
visitor,
206
};
compiler/packages/babel-plugin-react-compiler/scripts/jest/setupEnvE2E.js
+1
-1
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-const ReactCompilerRuntime = require("react/compiler-runtime");
8
+const ReactCompilerRuntime = require('react/compiler-runtime');
9
10
/*
11
* Our e2e babel transform currently only compiles functions, not programs.
compiler/packages/babel-plugin-react-compiler/scripts/jest/snapshot-resolver-no-forget.js
+1
-1
@@ -5,6 +5,6 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-const makeSnapshotResolver = require("./makeSnapshotResolver");
8
+const makeSnapshotResolver = require('./makeSnapshotResolver');
9
10
module.exports = makeSnapshotResolver(false);
compiler/packages/babel-plugin-react-compiler/scripts/jest/snapshot-resolver-with-forget.js
+1
-1
@@ -5,6 +5,6 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-const makeSnapshotResolver = require("./makeSnapshotResolver");
8
+const makeSnapshotResolver = require('./makeSnapshotResolver');
9
10
module.exports = makeSnapshotResolver(true);
compiler/packages/babel-plugin-react-compiler/scripts/jest/transform-no-forget.js
+1
-1
@@ -5,4 +5,4 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-module.exports = require("./makeTransform")(false);
8
+module.exports = require('./makeTransform')(false);
compiler/packages/babel-plugin-react-compiler/scripts/jest/transform-with-forget.js
+1
-1
@@ -5,4 +5,4 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-module.exports = require("./makeTransform")(true);
8
+module.exports = require('./makeTransform')(true);
compiler/packages/babel-plugin-react-compiler/src/Babel/BabelPlugin.ts
+7
-7
@@ -5,12 +5,12 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import type * as BabelCore from "@babel/core";
9
-import { compileProgram, parsePluginOptions } from "../Entrypoint";
8
+import type * as BabelCore from '@babel/core';
9
+import {compileProgram, parsePluginOptions} from '../Entrypoint';
10
import {
11
injectReanimatedFlag,
12
pipelineUsesReanimatedPlugin,
13
-} from "../Entrypoint/Reanimated";
13
+} from '../Entrypoint/Reanimated';
14
15
/*
16
* The React Forget Babel Plugin
@@ -18,10 +18,10 @@ import {
18
* @returns
19
*/
20
export default function BabelPluginReactCompiler(
21
- _babel: typeof BabelCore
21
+ _babel: typeof BabelCore,
22
): BabelCore.PluginObj {
23
return {
24
- name: "react-forget",
24
+ name: 'react-forget',
25
visitor: {
26
/*
27
* Note: Babel does some "smart" merging of visitors across plugins, so even if A is inserted
@@ -31,8 +31,8 @@ export default function BabelPluginReactCompiler(
31
Program(prog, pass): void {
32
let opts = parsePluginOptions(pass.opts);
33
const isDev =
34
- (typeof __DEV__ !== "undefined" && __DEV__ === true) ||
35
- process.env["NODE_ENV"] === "development";
34
+ (typeof __DEV__ !== 'undefined' && __DEV__ === true) ||
35
+ process.env['NODE_ENV'] === 'development';
36
if (
37
opts.enableReanimatedCheck === true &&
38
pipelineUsesReanimatedPlugin(pass.file.opts.plugins)
compiler/packages/babel-plugin-react-compiler/src/Babel/RunReactCompilerBabelPlugin.ts
+15
-15
@@ -5,25 +5,25 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import type * as BabelCore from "@babel/core";
9
-import { transformFromAstSync } from "@babel/core";
10
-import * as BabelParser from "@babel/parser";
11
-import invariant from "invariant";
12
-import type { PluginOptions } from "../Entrypoint";
13
-import BabelPluginReactCompiler from "./BabelPlugin";
8
+import type * as BabelCore from '@babel/core';
9
+import {transformFromAstSync} from '@babel/core';
10
+import * as BabelParser from '@babel/parser';
11
+import invariant from 'invariant';
12
+import type {PluginOptions} from '../Entrypoint';
13
+import BabelPluginReactCompiler from './BabelPlugin';
14
15
-export const DEFAULT_PLUGINS = ["babel-plugin-fbt", "babel-plugin-fbt-runtime"];
15
+export const DEFAULT_PLUGINS = ['babel-plugin-fbt', 'babel-plugin-fbt-runtime'];
16
export function runBabelPluginReactCompiler(
17
text: string,
18
file: string,
19
- language: "flow" | "typescript",
19
+ language: 'flow' | 'typescript',
20
options: Partial<PluginOptions> | null,
21
- includeAst: boolean = false
21
+ includeAst: boolean = false,
22
): BabelCore.BabelFileResult {
23
const ast = BabelParser.parse(text, {
24
sourceFilename: file,
25
- plugins: [language, "jsx"],
26
- sourceType: "module",
25
+ plugins: [language, 'jsx'],
26
+ sourceType: 'module',
27
});
28
const result = transformFromAstSync(ast, text, {
29
ast: includeAst,
@@ -32,16 +32,16 @@ export function runBabelPluginReactCompiler(
32
retainLines: true,
33
plugins: [
34
[BabelPluginReactCompiler, options],
35
- "babel-plugin-fbt",
36
- "babel-plugin-fbt-runtime",
35
+ 'babel-plugin-fbt',
36
+ 'babel-plugin-fbt-runtime',
37
],
38
- sourceType: "module",
38
+ sourceType: 'module',
39
configFile: false,
40
babelrc: false,
41
});
42
invariant(
43
result?.code != null,
44
- `Expected BabelPluginReactForget to codegen successfully, got: ${result}`
44
+ `Expected BabelPluginReactForget to codegen successfully, got: ${result}`,
45
);
46
return result;
47
}
compiler/packages/babel-plugin-react-compiler/src/CompilerError.ts
+30
-30
@@ -5,37 +5,37 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import type { SourceLocation } from "./HIR";
9
-import { assertExhaustive } from "./Utils/utils";
8
+import type {SourceLocation} from './HIR';
9
+import {assertExhaustive} from './Utils/utils';
10
11
export enum ErrorSeverity {
12
/**
13
* Invalid JS syntax, or valid syntax that is semantically invalid which may indicate some
14
* misunderstanding on the user’s part.
15
*/
16
- InvalidJS = "InvalidJS",
16
+ InvalidJS = 'InvalidJS',
17
/**
18
* Code that breaks the rules of React.
19
*/
20
- InvalidReact = "InvalidReact",
20
+ InvalidReact = 'InvalidReact',
21
/**
22
* Incorrect configuration of the compiler.
23
*/
24
- InvalidConfig = "InvalidConfig",
24
+ InvalidConfig = 'InvalidConfig',
25
/**
26
* Code that can reasonably occur and that doesn't break any rules, but is unsafe to preserve
27
* memoization.
28
*/
29
- CannotPreserveMemoization = "CannotPreserveMemoization",
29
+ CannotPreserveMemoization = 'CannotPreserveMemoization',
30
/**
31
* Unhandled syntax that we don't support yet.
32
*/
33
- Todo = "Todo",
33
+ Todo = 'Todo',
34
/**
35
* An unexpected internal error in the compiler that indicates critical issues that can panic
36
* the compiler.
37
*/
38
- Invariant = "Invariant",
38
+ Invariant = 'Invariant',
39
}
40
41
export enum CompilerSuggestionOperation {
@@ -79,19 +79,19 @@ export class CompilerErrorDetail {
79
this.options = options;
80
}
81
82
- get reason(): CompilerErrorDetailOptions["reason"] {
82
+ get reason(): CompilerErrorDetailOptions['reason'] {
83
return this.options.reason;
84
}
85
- get description(): CompilerErrorDetailOptions["description"] {
85
+ get description(): CompilerErrorDetailOptions['description'] {
86
return this.options.description;
87
}
88
- get severity(): CompilerErrorDetailOptions["severity"] {
88
+ get severity(): CompilerErrorDetailOptions['severity'] {
89
return this.options.severity;
90
}
91
- get loc(): CompilerErrorDetailOptions["loc"] {
91
+ get loc(): CompilerErrorDetailOptions['loc'] {
92
return this.options.loc;
93
}
94
- get suggestions(): CompilerErrorDetailOptions["suggestions"] {
94
+ get suggestions(): CompilerErrorDetailOptions['suggestions'] {
95
return this.options.suggestions;
96
}
97
@@ -100,10 +100,10 @@ export class CompilerErrorDetail {
100
if (this.description != null) {
101
buffer.push(`. ${this.description}`);
102
}
103
- if (this.loc != null && typeof this.loc !== "symbol") {
103
+ if (this.loc != null && typeof this.loc !== 'symbol') {
104
buffer.push(` (${this.loc.start.line}:${this.loc.end.line})`);
105
}
106
- return buffer.join("");
106
+ return buffer.join('');
107
}
108
109
toString(): string {
@@ -116,7 +116,7 @@ export class CompilerError extends Error {
116
117
static invariant(
118
condition: unknown,
119
- options: Omit<CompilerErrorDetailOptions, "severity">
119
+ options: Omit<CompilerErrorDetailOptions, 'severity'>,
120
): asserts condition {
121
if (!condition) {
122
const errors = new CompilerError();
@@ -124,57 +124,57 @@ export class CompilerError extends Error {
124
new CompilerErrorDetail({
125
...options,
126
severity: ErrorSeverity.Invariant,
127
- })
127
+ }),
128
);
129
throw errors;
130
}
131
}
132
133
static throwTodo(
134
- options: Omit<CompilerErrorDetailOptions, "severity">
134
+ options: Omit<CompilerErrorDetailOptions, 'severity'>,
135
): never {
136
const errors = new CompilerError();
137
errors.pushErrorDetail(
138
- new CompilerErrorDetail({ ...options, severity: ErrorSeverity.Todo })
138
+ new CompilerErrorDetail({...options, severity: ErrorSeverity.Todo}),
139
);
140
throw errors;
141
}
142
143
static throwInvalidJS(
144
- options: Omit<CompilerErrorDetailOptions, "severity">
144
+ options: Omit<CompilerErrorDetailOptions, 'severity'>,
145
): never {
146
const errors = new CompilerError();
147
errors.pushErrorDetail(
148
new CompilerErrorDetail({
149
...options,
150
severity: ErrorSeverity.InvalidJS,
151
- })
151
+ }),
152
);
153
throw errors;
154
}
155
156
static throwInvalidReact(
157
- options: Omit<CompilerErrorDetailOptions, "severity">
157
+ options: Omit<CompilerErrorDetailOptions, 'severity'>,
158
): never {
159
const errors = new CompilerError();
160
errors.pushErrorDetail(
161
new CompilerErrorDetail({
162
...options,
163
severity: ErrorSeverity.InvalidReact,
164
- })
164
+ }),
165
);
166
throw errors;
167
}
168
169
static throwInvalidConfig(
170
- options: Omit<CompilerErrorDetailOptions, "severity">
170
+ options: Omit<CompilerErrorDetailOptions, 'severity'>,
171
): never {
172
const errors = new CompilerError();
173
errors.pushErrorDetail(
174
new CompilerErrorDetail({
175
...options,
176
severity: ErrorSeverity.InvalidConfig,
177
- })
177
+ }),
178
);
179
throw errors;
180
}
@@ -187,7 +187,7 @@ export class CompilerError extends Error {
187
188
constructor(...args: Array<any>) {
189
super(...args);
190
- this.name = "ReactCompilerError";
190
+ this.name = 'ReactCompilerError';
191
}
192
193
override get message(): string {
@@ -197,7 +197,7 @@ export class CompilerError extends Error {
197
override set message(_message: string) {}
198
199
override toString(): string {
200
- return this.details.map((detail) => detail.toString()).join("\n\n");
200
+ return this.details.map(detail => detail.toString()).join('\n\n');
201
}
202
203
push(options: CompilerErrorDetailOptions): CompilerErrorDetail {
@@ -206,7 +206,7 @@ export class CompilerError extends Error {
206
description: options.description ?? null,
207
severity: options.severity,
208
suggestions: options.suggestions,
209
- loc: typeof options.loc === "symbol" ? null : options.loc,
209
+ loc: typeof options.loc === 'symbol' ? null : options.loc,
210
});
211
return this.pushErrorDetail(detail);
212
}
@@ -226,7 +226,7 @@ export class CompilerError extends Error {
226
* but otherwise continue compiling the rest of the app.
227
*/
228
isCritical(): boolean {
229
- return this.details.some((detail) => {
229
+ return this.details.some(detail => {
230
switch (detail.severity) {
231
case ErrorSeverity.Invariant:
232
case ErrorSeverity.InvalidJS:
@@ -237,7 +237,7 @@ export class CompilerError extends Error {
237
case ErrorSeverity.Todo:
238
return false;
239
default:
240
- assertExhaustive(detail.severity, "Unhandled error severity");
240
+ assertExhaustive(detail.severity, 'Unhandled error severity');
241
}
242
});
243
}
compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Gating.ts
+22
-19
@@ -5,9 +5,9 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { NodePath } from "@babel/core";
9
-import * as t from "@babel/types";
10
-import { PluginOptions } from "./Options";
8
+import {NodePath} from '@babel/core';
9
+import * as t from '@babel/types';
10
+import {PluginOptions} from './Options';
11
12
export function insertGatedFunctionDeclaration(
13
fnPath: NodePath<
@@ -17,12 +17,12 @@ export function insertGatedFunctionDeclaration(
17
| t.FunctionDeclaration
18
| t.ArrowFunctionExpression
19
| t.FunctionExpression,
20
- gating: NonNullable<PluginOptions["gating"]>
20
+ gating: NonNullable<PluginOptions['gating']>,
21
): void {
22
const gatingExpression = t.conditionalExpression(
23
t.callExpression(t.identifier(gating.importSpecifierName), []),
24
buildFunctionExpression(compiled),
25
- buildFunctionExpression(fnPath.node)
25
+ buildFunctionExpression(fnPath.node),
26
);
27
28
/*
@@ -32,30 +32,30 @@ export function insertGatedFunctionDeclaration(
32
* conditional expression
33
*/
34
if (
35
- fnPath.parentPath.node.type !== "ExportDefaultDeclaration" &&
36
- fnPath.node.type === "FunctionDeclaration" &&
35
+ fnPath.parentPath.node.type !== 'ExportDefaultDeclaration' &&
36
+ fnPath.node.type === 'FunctionDeclaration' &&
37
fnPath.node.id != null
38
) {
39
fnPath.replaceWith(
40
- t.variableDeclaration("const", [
40
+ t.variableDeclaration('const', [
41
t.variableDeclarator(fnPath.node.id, gatingExpression),
42
- ])
42
+ ]),
43
);
44
} else if (
45
- fnPath.parentPath.node.type === "ExportDefaultDeclaration" &&
46
- fnPath.node.type !== "ArrowFunctionExpression" &&
45
+ fnPath.parentPath.node.type === 'ExportDefaultDeclaration' &&
46
+ fnPath.node.type !== 'ArrowFunctionExpression' &&
47
fnPath.node.id != null
48
) {
49
fnPath.insertAfter(
50
- t.exportDefaultDeclaration(t.identifier(fnPath.node.id.name))
50
+ t.exportDefaultDeclaration(t.identifier(fnPath.node.id.name)),
51
);
52
fnPath.parentPath.replaceWith(
53
- t.variableDeclaration("const", [
53
+ t.variableDeclaration('const', [
54
t.variableDeclarator(
55
t.identifier(fnPath.node.id.name),
56
- gatingExpression
56
+ gatingExpression,
57
),
58
- ])
58
+ ]),
59
);
60
} else {
61
fnPath.replaceWith(gatingExpression);
@@ -63,16 +63,19 @@ export function insertGatedFunctionDeclaration(
63
}
64
65
function buildFunctionExpression(
66
- node: t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
66
+ node:
67
+ | t.FunctionDeclaration
68
+ | t.ArrowFunctionExpression
69
+ | t.FunctionExpression,
70
): t.ArrowFunctionExpression | t.FunctionExpression {
71
if (
69
- node.type === "ArrowFunctionExpression" ||
70
- node.type === "FunctionExpression"
72
+ node.type === 'ArrowFunctionExpression' ||
73
+ node.type === 'FunctionExpression'
74
) {
75
return node;
76
} else {
77
const fn: t.FunctionExpression = {
75
- type: "FunctionExpression",
78
+ type: 'FunctionExpression',
79
async: node.async,
80
generator: node.generator,
81
loc: node.loc ?? null,
compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Imports.ts
+31
-31
@@ -5,19 +5,19 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { NodePath } from "@babel/core";
9
-import * as t from "@babel/types";
10
-import { CompilerError } from "../CompilerError";
11
-import { ExternalFunction, GeneratedSource } from "../HIR";
12
-import { getOrInsertDefault } from "../Utils/utils";
8
+import {NodePath} from '@babel/core';
9
+import * as t from '@babel/types';
10
+import {CompilerError} from '../CompilerError';
11
+import {ExternalFunction, GeneratedSource} from '../HIR';
12
+import {getOrInsertDefault} from '../Utils/utils';
13
14
export function addImportsToProgram(
15
path: NodePath<t.Program>,
16
- importList: Array<ExternalFunction>
16
+ importList: Array<ExternalFunction>,
17
): void {
18
const identifiers: Set<string> = new Set();
19
const sortedImports: Map<string, Array<string>> = new Map();
20
- for (const { importSpecifierName, source } of importList) {
20
+ for (const {importSpecifierName, source} of importList) {
21
/*
22
* Codegen currently does not rename import specifiers, so we do additional
23
* validation here
@@ -35,28 +35,28 @@ export function addImportsToProgram(
35
description: null,
36
loc: GeneratedSource,
37
suggestions: null,
38
- }
38
+ },
39
);
40
identifiers.add(importSpecifierName);
41
42
const importSpecifierNameList = getOrInsertDefault(
43
sortedImports,
44
source,
45
- []
45
+ [],
46
);
47
importSpecifierNameList.push(importSpecifierName);
48
}
49
50
const stmts: Array<t.ImportDeclaration> = [];
51
for (const [source, importSpecifierNameList] of sortedImports) {
52
- const importSpecifiers = importSpecifierNameList.map((name) => {
52
+ const importSpecifiers = importSpecifierNameList.map(name => {
53
const id = t.identifier(name);
54
return t.importSpecifier(id, id);
55
});
56
57
stmts.push(t.importDeclaration(importSpecifiers, t.stringLiteral(source)));
58
}
59
- path.unshiftContainer("body", stmts);
59
+ path.unshiftContainer('body', stmts);
60
}
61
62
/*
@@ -65,21 +65,21 @@ export function addImportsToProgram(
65
*/
66
function isNonNamespacedImport(
67
importDeclPath: NodePath<t.ImportDeclaration>,
68
- moduleName: string
68
+ moduleName: string,
69
): boolean {
70
return (
71
- importDeclPath.get("source").node.value === moduleName &&
71
+ importDeclPath.get('source').node.value === moduleName &&
72
importDeclPath
73
- .get("specifiers")
74
- .every((specifier) => specifier.isImportSpecifier()) &&
75
- importDeclPath.node.importKind !== "type" &&
76
- importDeclPath.node.importKind !== "typeof"
73
+ .get('specifiers')
74
+ .every(specifier => specifier.isImportSpecifier()) &&
75
+ importDeclPath.node.importKind !== 'type' &&
76
+ importDeclPath.node.importKind !== 'typeof'
77
);
78
}
79
80
function hasExistingNonNamespacedImportOfModule(
81
program: NodePath<t.Program>,
82
- moduleName: string
82
+ moduleName: string,
83
): boolean {
84
let hasExistingImport = false;
85
program.traverse({
@@ -100,7 +100,7 @@ function hasExistingNonNamespacedImportOfModule(
100
function addMemoCacheFunctionSpecifierToExistingImport(
101
program: NodePath<t.Program>,
102
moduleName: string,
103
- identifierName: string
103
+ identifierName: string,
104
): boolean {
105
let didInsertUseMemoCache = false;
106
program.traverse({
@@ -110,8 +110,8 @@ function addMemoCacheFunctionSpecifierToExistingImport(
110
isNonNamespacedImport(importDeclPath, moduleName)
111
) {
112
importDeclPath.pushContainer(
113
- "specifiers",
114
- t.importSpecifier(t.identifier(identifierName), t.identifier("c"))
113
+ 'specifiers',
114
+ t.importSpecifier(t.identifier(identifierName), t.identifier('c')),
115
);
116
didInsertUseMemoCache = true;
117
}
@@ -123,7 +123,7 @@ function addMemoCacheFunctionSpecifierToExistingImport(
123
export function updateMemoCacheFunctionImport(
124
program: NodePath<t.Program>,
125
moduleName: string,
126
- useMemoCacheIdentifier: string
126
+ useMemoCacheIdentifier: string,
127
): void {
128
/*
129
* If there isn't already an import of * as React, insert it so useMemoCache doesn't
@@ -131,25 +131,25 @@ export function updateMemoCacheFunctionImport(
131
*/
132
const hasExistingImport = hasExistingNonNamespacedImportOfModule(
133
program,
134
- moduleName
134
+ moduleName,
135
);
136
137
if (hasExistingImport) {
138
const didUpdateImport = addMemoCacheFunctionSpecifierToExistingImport(
139
program,
140
moduleName,
141
- useMemoCacheIdentifier
141
+ useMemoCacheIdentifier,
142
);
143
if (!didUpdateImport) {
144
throw new Error(
145
- `Expected an ImportDeclaration of \`${moduleName}\` in order to update ImportSpecifiers with useMemoCache`
145
+ `Expected an ImportDeclaration of \`${moduleName}\` in order to update ImportSpecifiers with useMemoCache`,
146
);
147
}
148
} else {
149
addMemoCacheFunctionImportDeclaration(
150
program,
151
moduleName,
152
- useMemoCacheIdentifier
152
+ useMemoCacheIdentifier,
153
);
154
}
155
}
@@ -157,13 +157,13 @@ export function updateMemoCacheFunctionImport(
157
function addMemoCacheFunctionImportDeclaration(
158
program: NodePath<t.Program>,
159
moduleName: string,
160
- localName: string
160
+ localName: string,
161
): void {
162
program.unshiftContainer(
163
- "body",
163
+ 'body',
164
t.importDeclaration(
165
- [t.importSpecifier(t.identifier(localName), t.identifier("c"))],
166
- t.stringLiteral(moduleName)
167
- )
165
+ [t.importSpecifier(t.identifier(localName), t.identifier('c'))],
166
+ t.stringLiteral(moduleName),
167
+ ),
168
);
169
}
compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Options.ts
+24
-24
@@ -5,11 +5,11 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import * as t from "@babel/types";
9
-import { z } from "zod";
10
-import { CompilerErrorDetailOptions } from "../CompilerError";
11
-import { ExternalFunction, PartialEnvironmentConfig } from "../HIR/Environment";
12
-import { hasOwnProperty } from "../Utils/utils";
8
+import * as t from '@babel/types';
9
+import {z} from 'zod';
10
+import {CompilerErrorDetailOptions} from '../CompilerError';
11
+import {ExternalFunction, PartialEnvironmentConfig} from '../HIR/Environment';
12
+import {hasOwnProperty} from '../Utils/utils';
13
14
const PanicThresholdOptionsSchema = z.enum([
15
/*
@@ -18,15 +18,15 @@ const PanicThresholdOptionsSchema = z.enum([
18
* If Forget is invoked through `BabelPluginReactCompiler`, this will at the least
19
* skip Forget compilation for the rest of current file.
20
*/
21
- "all_errors",
21
+ 'all_errors',
22
/*
23
* Panic by throwing an exception only on critical or unrecognized errors.
24
* For all other errors, skip the erroring function without inserting
25
* a Forget-compiled version (i.e. same behavior as noEmit).
26
*/
27
- "critical_errors",
27
+ 'critical_errors',
28
// Never panic by throwing an exception.
29
- "none",
29
+ 'none',
30
]);
31
32
export type PanicThresholdOptions = z.infer<typeof PanicThresholdOptionsSchema>;
@@ -130,13 +130,13 @@ const CompilationModeSchema = z.enum([
130
* false positives, since compilation has a greater impact than linting.
131
* This is the default mode
132
*/
133
- "infer",
133
+ 'infer',
134
// Compile only components using Flow component syntax and hooks using hook syntax.
135
- "syntax",
135
+ 'syntax',
136
// Compile only functions which are explicitly annotated with "use forget"
137
- "annotation",
137
+ 'annotation',
138
// Compile all top-level functions
139
- "all",
139
+ 'all',
140
]);
141
142
export type CompilationMode = z.infer<typeof CompilationModeSchema>;
@@ -156,17 +156,17 @@ export type CompilationMode = z.infer<typeof CompilationModeSchema>;
156
*/
157
export type LoggerEvent =
158
| {
159
- kind: "CompileError";
159
+ kind: 'CompileError';
160
fnLoc: t.SourceLocation | null;
161
detail: CompilerErrorDetailOptions;
162
}
163
| {
164
- kind: "CompileDiagnostic";
164
+ kind: 'CompileDiagnostic';
165
fnLoc: t.SourceLocation | null;
166
- detail: Omit<Omit<CompilerErrorDetailOptions, "severity">, "suggestions">;
166
+ detail: Omit<Omit<CompilerErrorDetailOptions, 'severity'>, 'suggestions'>;
167
}
168
| {
169
- kind: "CompileSuccess";
169
+ kind: 'CompileSuccess';
170
fnLoc: t.SourceLocation | null;
171
fnName: string | null;
172
memoSlots: number;
@@ -176,7 +176,7 @@ export type LoggerEvent =
176
prunedMemoValues: number;
177
}
178
| {
179
- kind: "PipelineError";
179
+ kind: 'PipelineError';
180
fnLoc: t.SourceLocation | null;
181
data: string;
182
};
@@ -186,8 +186,8 @@ export type Logger = {
186
};
187
188
export const defaultOptions: PluginOptions = {
189
- compilationMode: "infer",
190
- panicThreshold: "none",
189
+ compilationMode: 'infer',
190
+ panicThreshold: 'none',
191
environment: {},
192
logger: null,
193
gating: null,
@@ -196,19 +196,19 @@ export const defaultOptions: PluginOptions = {
196
eslintSuppressionRules: null,
197
flowSuppressions: false,
198
ignoreUseNoForget: false,
199
- sources: (filename) => {
200
- return filename.indexOf("node_modules") === -1;
199
+ sources: filename => {
200
+ return filename.indexOf('node_modules') === -1;
201
},
202
enableReanimatedCheck: true,
203
} as const;
204
205
export function parsePluginOptions(obj: unknown): PluginOptions {
206
- if (obj == null || typeof obj !== "object") {
206
+ if (obj == null || typeof obj !== 'object') {
207
return defaultOptions;
208
}
209
const parsedOptions = Object.create(null);
210
for (let [key, value] of Object.entries(obj)) {
211
- if (typeof value === "string") {
211
+ if (typeof value === 'string') {
212
// normalize string configs to be case insensitive
213
value = value.toLowerCase();
214
}
@@ -216,7 +216,7 @@ export function parsePluginOptions(obj: unknown): PluginOptions {
216
parsedOptions[key] = value;
217
}
218
}
219
- return { ...defaultOptions, ...parsedOptions };
219
+ return {...defaultOptions, ...parsedOptions};
220
}
221
222
function isCompilerFlag(s: string): s is keyof PluginOptions {
compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Pipeline.ts
+124
-124
@@ -5,10 +5,10 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { NodePath } from "@babel/traverse";
9
-import * as t from "@babel/types";
10
-import prettyFormat from "pretty-format";
11
-import { Logger } from ".";
8
+import {NodePath} from '@babel/traverse';
9
+import * as t from '@babel/types';
10
+import prettyFormat from 'pretty-format';
11
+import {Logger} from '.';
12
import {
13
HIRFunction,
14
ReactiveFunction,
@@ -22,13 +22,13 @@ import {
22
mergeConsecutiveBlocks,
23
mergeOverlappingReactiveScopesHIR,
24
pruneUnusedLabelsHIR,
25
-} from "../HIR";
25
+} from '../HIR';
26
import {
27
Environment,
28
EnvironmentConfig,
29
ReactFunctionType,
30
-} from "../HIR/Environment";
31
-import { findContextIdentifiers } from "../HIR/FindContextIdentifiers";
30
+} from '../HIR/Environment';
31
+import {findContextIdentifiers} from '../HIR/FindContextIdentifiers';
32
import {
33
analyseFunctions,
34
dropManualMemoization,
@@ -36,13 +36,13 @@ import {
36
inferReactivePlaces,
37
inferReferenceEffects,
38
inlineImmediatelyInvokedFunctionExpressions,
39
-} from "../Inference";
39
+} from '../Inference';
40
import {
41
constantPropagation,
42
deadCodeElimination,
43
pruneMaybeThrows,
44
-} from "../Optimization";
45
-import { instructionReordering } from "../Optimization/InstructionReordering";
44
+} from '../Optimization';
45
+import {instructionReordering} from '../Optimization/InstructionReordering';
46
import {
47
CodegenFunction,
48
alignObjectMethodScopes,
@@ -69,23 +69,23 @@ import {
69
pruneUnusedLabels,
70
pruneUnusedScopes,
71
renameVariables,
72
-} from "../ReactiveScopes";
73
-import { alignMethodCallScopes } from "../ReactiveScopes/AlignMethodCallScopes";
74
-import { alignReactiveScopesToBlockScopesHIR } from "../ReactiveScopes/AlignReactiveScopesToBlockScopesHIR";
75
-import { flattenReactiveLoopsHIR } from "../ReactiveScopes/FlattenReactiveLoopsHIR";
76
-import { flattenScopesWithHooksOrUseHIR } from "../ReactiveScopes/FlattenScopesWithHooksOrUseHIR";
77
-import { pruneAlwaysInvalidatingScopes } from "../ReactiveScopes/PruneAlwaysInvalidatingScopes";
78
-import pruneInitializationDependencies from "../ReactiveScopes/PruneInitializationDependencies";
79
-import { stabilizeBlockIds } from "../ReactiveScopes/StabilizeBlockIds";
80
-import { eliminateRedundantPhi, enterSSA, leaveSSA } from "../SSA";
81
-import { inferTypes } from "../TypeInference";
72
+} from '../ReactiveScopes';
73
+import {alignMethodCallScopes} from '../ReactiveScopes/AlignMethodCallScopes';
74
+import {alignReactiveScopesToBlockScopesHIR} from '../ReactiveScopes/AlignReactiveScopesToBlockScopesHIR';
75
+import {flattenReactiveLoopsHIR} from '../ReactiveScopes/FlattenReactiveLoopsHIR';
76
+import {flattenScopesWithHooksOrUseHIR} from '../ReactiveScopes/FlattenScopesWithHooksOrUseHIR';
77
+import {pruneAlwaysInvalidatingScopes} from '../ReactiveScopes/PruneAlwaysInvalidatingScopes';
78
+import pruneInitializationDependencies from '../ReactiveScopes/PruneInitializationDependencies';
79
+import {stabilizeBlockIds} from '../ReactiveScopes/StabilizeBlockIds';
80
+import {eliminateRedundantPhi, enterSSA, leaveSSA} from '../SSA';
81
+import {inferTypes} from '../TypeInference';
82
import {
83
logCodegenFunction,
84
logDebug,
85
logHIRFunction,
86
logReactiveFunction,
87
-} from "../Utils/logger";
88
-import { assertExhaustive } from "../Utils/utils";
87
+} from '../Utils/logger';
88
+import {assertExhaustive} from '../Utils/utils';
89
import {
90
validateContextVariableLValues,
91
validateHooksUsage,
@@ -95,15 +95,15 @@ import {
95
validateNoSetStateInRender,
96
validatePreservedManualMemoization,
97
validateUseMemo,
98
-} from "../Validation";
99
-import { validateLocalsNotReassignedAfterRender } from "../Validation/ValidateLocalsNotReassignedAfterRender";
100
-import { outlineFunctions } from "../Optimization/OutlineFunctions";
98
+} from '../Validation';
99
+import {validateLocalsNotReassignedAfterRender} from '../Validation/ValidateLocalsNotReassignedAfterRender';
100
+import {outlineFunctions} from '../Optimization/OutlineFunctions';
101
102
export type CompilerPipelineValue =
103
- | { kind: "ast"; name: string; value: CodegenFunction }
104
- | { kind: "hir"; name: string; value: HIRFunction }
105
- | { kind: "reactive"; name: string; value: ReactiveFunction }
106
- | { kind: "debug"; name: string; value: string };
103
+ | {kind: 'ast'; name: string; value: CodegenFunction}
104
+ | {kind: 'hir'; name: string; value: HIRFunction}
105
+ | {kind: 'reactive'; name: string; value: ReactiveFunction}
106
+ | {kind: 'debug'; name: string; value: string};
107
108
export function* run(
109
func: NodePath<
@@ -114,7 +114,7 @@ export function* run(
114
useMemoCacheIdentifier: string,
115
logger: Logger | null,
116
filename: string | null,
117
- code: string | null
117
+ code: string | null,
118
): Generator<CompilerPipelineValue, CodegenFunction> {
119
const contextIdentifiers = findContextIdentifiers(func);
120
const env = new Environment(
@@ -125,11 +125,11 @@ export function* run(
125
logger,
126
filename,
127
code,
128
- useMemoCacheIdentifier
128
+ useMemoCacheIdentifier,
129
);
130
yield {
131
- kind: "debug",
132
- name: "EnvironmentConfig",
131
+ kind: 'debug',
132
+ name: 'EnvironmentConfig',
133
value: prettyFormat(env.config),
134
};
135
const ast = yield* runWithEnvironment(func, env);
@@ -144,13 +144,13 @@ function* runWithEnvironment(
144
func: NodePath<
145
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
146
>,
147
- env: Environment
147
+ env: Environment,
148
): Generator<CompilerPipelineValue, CodegenFunction> {
149
const hir = lower(func, env).unwrap();
150
- yield log({ kind: "hir", name: "HIR", value: hir });
150
+ yield log({kind: 'hir', name: 'HIR', value: hir});
151
152
pruneMaybeThrows(hir);
153
- yield log({ kind: "hir", name: "PruneMaybeThrows", value: hir });
153
+ yield log({kind: 'hir', name: 'PruneMaybeThrows', value: hir});
154
155
validateContextVariableLValues(hir);
156
validateUseMemo(hir);
@@ -161,35 +161,35 @@ function* runWithEnvironment(
161
!env.config.enableChangeDetectionForDebugging
162
) {
163
dropManualMemoization(hir);
164
- yield log({ kind: "hir", name: "DropManualMemoization", value: hir });
164
+ yield log({kind: 'hir', name: 'DropManualMemoization', value: hir});
165
}
166
167
inlineImmediatelyInvokedFunctionExpressions(hir);
168
yield log({
169
- kind: "hir",
170
- name: "InlineImmediatelyInvokedFunctionExpressions",
169
+ kind: 'hir',
170
+ name: 'InlineImmediatelyInvokedFunctionExpressions',
171
value: hir,
172
});
173
174
mergeConsecutiveBlocks(hir);
175
- yield log({ kind: "hir", name: "MergeConsecutiveBlocks", value: hir });
175
+ yield log({kind: 'hir', name: 'MergeConsecutiveBlocks', value: hir});
176
177
assertConsistentIdentifiers(hir);
178
assertTerminalSuccessorsExist(hir);
179
180
enterSSA(hir);
181
- yield log({ kind: "hir", name: "SSA", value: hir });
181
+ yield log({kind: 'hir', name: 'SSA', value: hir});
182
183
eliminateRedundantPhi(hir);
184
- yield log({ kind: "hir", name: "EliminateRedundantPhi", value: hir });
184
+ yield log({kind: 'hir', name: 'EliminateRedundantPhi', value: hir});
185
186
assertConsistentIdentifiers(hir);
187
188
constantPropagation(hir);
189
- yield log({ kind: "hir", name: "ConstantPropagation", value: hir });
189
+ yield log({kind: 'hir', name: 'ConstantPropagation', value: hir});
190
191
inferTypes(hir);
192
- yield log({ kind: "hir", name: "InferTypes", value: hir });
192
+ yield log({kind: 'hir', name: 'InferTypes', value: hir});
193
194
if (env.config.validateHooksUsage) {
195
validateHooksUsage(hir);
@@ -200,27 +200,27 @@ function* runWithEnvironment(
200
}
201
202
analyseFunctions(hir);
203
- yield log({ kind: "hir", name: "AnalyseFunctions", value: hir });
203
+ yield log({kind: 'hir', name: 'AnalyseFunctions', value: hir});
204
205
inferReferenceEffects(hir);
206
- yield log({ kind: "hir", name: "InferReferenceEffects", value: hir });
206
+ yield log({kind: 'hir', name: 'InferReferenceEffects', value: hir});
207
208
validateLocalsNotReassignedAfterRender(hir);
209
210
// Note: Has to come after infer reference effects because "dead" code may still affect inference
211
deadCodeElimination(hir);
212
- yield log({ kind: "hir", name: "DeadCodeElimination", value: hir });
212
+ yield log({kind: 'hir', name: 'DeadCodeElimination', value: hir});
213
214
if (env.config.enableInstructionReordering) {
215
instructionReordering(hir);
216
- yield log({ kind: "hir", name: "InstructionReordering", value: hir });
216
+ yield log({kind: 'hir', name: 'InstructionReordering', value: hir});
217
}
218
219
pruneMaybeThrows(hir);
220
- yield log({ kind: "hir", name: "PruneMaybeThrows", value: hir });
220
+ yield log({kind: 'hir', name: 'PruneMaybeThrows', value: hir});
221
222
inferMutableRanges(hir);
223
- yield log({ kind: "hir", name: "InferMutableRanges", value: hir });
223
+ yield log({kind: 'hir', name: 'InferMutableRanges', value: hir});
224
225
if (env.config.assertValidMutableRanges) {
226
assertValidMutableRanges(hir);
@@ -235,67 +235,67 @@ function* runWithEnvironment(
235
}
236
237
inferReactivePlaces(hir);
238
- yield log({ kind: "hir", name: "InferReactivePlaces", value: hir });
238
+ yield log({kind: 'hir', name: 'InferReactivePlaces', value: hir});
239
240
leaveSSA(hir);
241
- yield log({ kind: "hir", name: "LeaveSSA", value: hir });
241
+ yield log({kind: 'hir', name: 'LeaveSSA', value: hir});
242
243
inferReactiveScopeVariables(hir);
244
- yield log({ kind: "hir", name: "InferReactiveScopeVariables", value: hir });
244
+ yield log({kind: 'hir', name: 'InferReactiveScopeVariables', value: hir});
245
246
if (env.config.enableFunctionOutlining) {
247
outlineFunctions(hir);
248
- yield log({ kind: "hir", name: "OutlineFunctions", value: hir });
248
+ yield log({kind: 'hir', name: 'OutlineFunctions', value: hir});
249
}
250
251
alignMethodCallScopes(hir);
252
yield log({
253
- kind: "hir",
254
- name: "AlignMethodCallScopes",
253
+ kind: 'hir',
254
+ name: 'AlignMethodCallScopes',
255
value: hir,
256
});
257
258
alignObjectMethodScopes(hir);
259
yield log({
260
- kind: "hir",
261
- name: "AlignObjectMethodScopes",
260
+ kind: 'hir',
261
+ name: 'AlignObjectMethodScopes',
262
value: hir,
263
});
264
265
const fbtOperands = memoizeFbtOperandsInSameScope(hir);
266
yield log({
267
- kind: "hir",
268
- name: "MemoizeFbtAndMacroOperandsInSameScope",
267
+ kind: 'hir',
268
+ name: 'MemoizeFbtAndMacroOperandsInSameScope',
269
value: hir,
270
});
271
272
if (env.config.enableReactiveScopesInHIR) {
273
pruneUnusedLabelsHIR(hir);
274
yield log({
275
- kind: "hir",
276
- name: "PruneUnusedLabelsHIR",
275
+ kind: 'hir',
276
+ name: 'PruneUnusedLabelsHIR',
277
value: hir,
278
});
279
280
alignReactiveScopesToBlockScopesHIR(hir);
281
yield log({
282
- kind: "hir",
283
- name: "AlignReactiveScopesToBlockScopesHIR",
282
+ kind: 'hir',
283
+ name: 'AlignReactiveScopesToBlockScopesHIR',
284
value: hir,
285
});
286
287
mergeOverlappingReactiveScopesHIR(hir);
288
yield log({
289
- kind: "hir",
290
- name: "MergeOverlappingReactiveScopesHIR",
289
+ kind: 'hir',
290
+ name: 'MergeOverlappingReactiveScopesHIR',
291
value: hir,
292
});
293
assertValidBlockNesting(hir);
294
295
buildReactiveScopeTerminalsHIR(hir);
296
yield log({
297
- kind: "hir",
298
- name: "BuildReactiveScopeTerminalsHIR",
297
+ kind: 'hir',
298
+ name: 'BuildReactiveScopeTerminalsHIR',
299
value: hir,
300
});
301
@@ -303,15 +303,15 @@ function* runWithEnvironment(
303
304
flattenReactiveLoopsHIR(hir);
305
yield log({
306
- kind: "hir",
307
- name: "FlattenReactiveLoopsHIR",
306
+ kind: 'hir',
307
+ name: 'FlattenReactiveLoopsHIR',
308
value: hir,
309
});
310
311
flattenScopesWithHooksOrUseHIR(hir);
312
yield log({
313
- kind: "hir",
314
- name: "FlattenScopesWithHooksOrUseHIR",
313
+ kind: 'hir',
314
+ name: 'FlattenScopesWithHooksOrUseHIR',
315
value: hir,
316
});
317
assertTerminalSuccessorsExist(hir);
@@ -320,8 +320,8 @@ function* runWithEnvironment(
320
321
const reactiveFunction = buildReactiveFunction(hir);
322
yield log({
323
- kind: "reactive",
324
- name: "BuildReactiveFunction",
323
+ kind: 'reactive',
324
+ name: 'BuildReactiveFunction',
325
value: reactiveFunction,
326
});
327
@@ -329,44 +329,44 @@ function* runWithEnvironment(
329
330
pruneUnusedLabels(reactiveFunction);
331
yield log({
332
- kind: "reactive",
333
- name: "PruneUnusedLabels",
332
+ kind: 'reactive',
333
+ name: 'PruneUnusedLabels',
334
value: reactiveFunction,
335
});
336
337
if (!env.config.enableReactiveScopesInHIR) {
338
alignReactiveScopesToBlockScopes(reactiveFunction);
339
yield log({
340
- kind: "reactive",
341
- name: "AlignReactiveScopesToBlockScopes",
340
+ kind: 'reactive',
341
+ name: 'AlignReactiveScopesToBlockScopes',
342
value: reactiveFunction,
343
});
344
345
mergeOverlappingReactiveScopes(reactiveFunction);
346
yield log({
347
- kind: "reactive",
348
- name: "MergeOverlappingReactiveScopes",
347
+ kind: 'reactive',
348
+ name: 'MergeOverlappingReactiveScopes',
349
value: reactiveFunction,
350
});
351
352
buildReactiveBlocks(reactiveFunction);
353
yield log({
354
- kind: "reactive",
355
- name: "BuildReactiveBlocks",
354
+ kind: 'reactive',
355
+ name: 'BuildReactiveBlocks',
356
value: reactiveFunction,
357
});
358
359
flattenReactiveLoops(reactiveFunction);
360
yield log({
361
- kind: "reactive",
362
- name: "FlattenReactiveLoops",
361
+ kind: 'reactive',
362
+ name: 'FlattenReactiveLoops',
363
value: reactiveFunction,
364
});
365
366
flattenScopesWithHooksOrUse(reactiveFunction);
367
yield log({
368
- kind: "reactive",
369
- name: "FlattenScopesWithHooks",
368
+ kind: 'reactive',
369
+ name: 'FlattenScopesWithHooks',
370
value: reactiveFunction,
371
});
372
}
@@ -375,101 +375,101 @@ function* runWithEnvironment(
375
376
propagateScopeDependencies(reactiveFunction);
377
yield log({
378
- kind: "reactive",
379
- name: "PropagateScopeDependencies",
378
+ kind: 'reactive',
379
+ name: 'PropagateScopeDependencies',
380
value: reactiveFunction,
381
});
382
383
pruneNonEscapingScopes(reactiveFunction);
384
yield log({
385
- kind: "reactive",
386
- name: "PruneNonEscapingScopes",
385
+ kind: 'reactive',
386
+ name: 'PruneNonEscapingScopes',
387
value: reactiveFunction,
388
});
389
390
pruneNonReactiveDependencies(reactiveFunction);
391
yield log({
392
- kind: "reactive",
393
- name: "PruneNonReactiveDependencies",
392
+ kind: 'reactive',
393
+ name: 'PruneNonReactiveDependencies',
394
value: reactiveFunction,
395
});
396
397
pruneUnusedScopes(reactiveFunction);
398
yield log({
399
- kind: "reactive",
400
- name: "PruneUnusedScopes",
399
+ kind: 'reactive',
400
+ name: 'PruneUnusedScopes',
401
value: reactiveFunction,
402
});
403
404
mergeReactiveScopesThatInvalidateTogether(reactiveFunction);
405
yield log({
406
- kind: "reactive",
407
- name: "MergeReactiveScopesThatInvalidateTogether",
406
+ kind: 'reactive',
407
+ name: 'MergeReactiveScopesThatInvalidateTogether',
408
value: reactiveFunction,
409
});
410
411
pruneAlwaysInvalidatingScopes(reactiveFunction);
412
yield log({
413
- kind: "reactive",
414
- name: "PruneAlwaysInvalidatingScopes",
413
+ kind: 'reactive',
414
+ name: 'PruneAlwaysInvalidatingScopes',
415
value: reactiveFunction,
416
});
417
418
if (env.config.enableChangeDetectionForDebugging != null) {
419
pruneInitializationDependencies(reactiveFunction);
420
yield log({
421
- kind: "reactive",
422
- name: "PruneInitializationDependencies",
421
+ kind: 'reactive',
422
+ name: 'PruneInitializationDependencies',
423
value: reactiveFunction,
424
});
425
}
426
427
propagateEarlyReturns(reactiveFunction);
428
yield log({
429
- kind: "reactive",
430
- name: "PropagateEarlyReturns",
429
+ kind: 'reactive',
430
+ name: 'PropagateEarlyReturns',
431
value: reactiveFunction,
432
});
433
434
promoteUsedTemporaries(reactiveFunction);
435
yield log({
436
- kind: "reactive",
437
- name: "PromoteUsedTemporaries",
436
+ kind: 'reactive',
437
+ name: 'PromoteUsedTemporaries',
438
value: reactiveFunction,
439
});
440
441
pruneUnusedLValues(reactiveFunction);
442
yield log({
443
- kind: "reactive",
444
- name: "PruneUnusedLValues",
443
+ kind: 'reactive',
444
+ name: 'PruneUnusedLValues',
445
value: reactiveFunction,
446
});
447
448
extractScopeDeclarationsFromDestructuring(reactiveFunction);
449
yield log({
450
- kind: "reactive",
451
- name: "ExtractScopeDeclarationsFromDestructuring",
450
+ kind: 'reactive',
451
+ name: 'ExtractScopeDeclarationsFromDestructuring',
452
value: reactiveFunction,
453
});
454
455
stabilizeBlockIds(reactiveFunction);
456
yield log({
457
- kind: "reactive",
458
- name: "StabilizeBlockIds",
457
+ kind: 'reactive',
458
+ name: 'StabilizeBlockIds',
459
value: reactiveFunction,
460
});
461
462
const uniqueIdentifiers = renameVariables(reactiveFunction);
463
yield log({
464
- kind: "reactive",
465
- name: "RenameVariables",
464
+ kind: 'reactive',
465
+ name: 'RenameVariables',
466
value: reactiveFunction,
467
});
468
469
pruneHoistedContexts(reactiveFunction);
470
yield log({
471
- kind: "reactive",
472
- name: "PruneHoistedContexts",
471
+ kind: 'reactive',
472
+ name: 'PruneHoistedContexts',
473
value: reactiveFunction,
474
});
475
@@ -488,9 +488,9 @@ function* runWithEnvironment(
488
uniqueIdentifiers,
489
fbtOperands,
490
}).unwrap();
491
- yield log({ kind: "ast", name: "Codegen", value: ast });
491
+ yield log({kind: 'ast', name: 'Codegen', value: ast});
492
for (const outlined of ast.outlined) {
493
- yield log({ kind: "ast", name: "Codegen (outlined)", value: outlined.fn });
493
+ yield log({kind: 'ast', name: 'Codegen (outlined)', value: outlined.fn});
494
}
495
496
/**
@@ -499,7 +499,7 @@ function* runWithEnvironment(
499
* thrown by babel functions or other unexpected exceptions).
500
*/
501
if (env.config.throwUnknownException__testonly) {
502
- throw new Error("unexpected error");
502
+ throw new Error('unexpected error');
503
}
504
505
return ast;
@@ -514,7 +514,7 @@ export function compileFn(
514
useMemoCacheIdentifier: string,
515
logger: Logger | null,
516
filename: string | null,
517
- code: string | null
517
+ code: string | null,
518
): CodegenFunction {
519
let generator = run(
520
func,
@@ -523,7 +523,7 @@ export function compileFn(
523
useMemoCacheIdentifier,
524
logger,
525
filename,
526
- code
526
+ code,
527
);
528
while (true) {
529
const next = generator.next();
@@ -535,24 +535,24 @@ export function compileFn(
535
536
export function log(value: CompilerPipelineValue): CompilerPipelineValue {
537
switch (value.kind) {
538
- case "ast": {
538
+ case 'ast': {
539
logCodegenFunction(value.name, value.value);
540
break;
541
}
542
- case "hir": {
542
+ case 'hir': {
543
logHIRFunction(value.name, value.value);
544
break;
545
}
546
- case "reactive": {
546
+ case 'reactive': {
547
logReactiveFunction(value.name, value.value);
548
break;
549
}
550
- case "debug": {
550
+ case 'debug': {
551
logDebug(value.name, value.value);
552
break;
553
}
554
default: {
555
- assertExhaustive(value, "Unexpected compilation kind");
555
+ assertExhaustive(value, 'Unexpected compilation kind');
556
}
557
}
558
return value;
compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Program.ts
+160
-160
@@ -5,32 +5,32 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { NodePath } from "@babel/core";
9
-import * as t from "@babel/types";
8
+import {NodePath} from '@babel/core';
9
+import * as t from '@babel/types';
10
import {
11
CompilerError,
12
CompilerErrorDetail,
13
ErrorSeverity,
14
-} from "../CompilerError";
14
+} from '../CompilerError';
15
import {
16
ExternalFunction,
17
ReactFunctionType,
18
parseEnvironmentConfig,
19
tryParseExternalFunction,
20
-} from "../HIR/Environment";
21
-import { CodegenFunction } from "../ReactiveScopes";
22
-import { isComponentDeclaration } from "../Utils/ComponentDeclaration";
23
-import { isHookDeclaration } from "../Utils/HookDeclaration";
24
-import { assertExhaustive } from "../Utils/utils";
25
-import { insertGatedFunctionDeclaration } from "./Gating";
26
-import { addImportsToProgram, updateMemoCacheFunctionImport } from "./Imports";
27
-import { PluginOptions } from "./Options";
28
-import { compileFn } from "./Pipeline";
20
+} from '../HIR/Environment';
21
+import {CodegenFunction} from '../ReactiveScopes';
22
+import {isComponentDeclaration} from '../Utils/ComponentDeclaration';
23
+import {isHookDeclaration} from '../Utils/HookDeclaration';
24
+import {assertExhaustive} from '../Utils/utils';
25
+import {insertGatedFunctionDeclaration} from './Gating';
26
+import {addImportsToProgram, updateMemoCacheFunctionImport} from './Imports';
27
+import {PluginOptions} from './Options';
28
+import {compileFn} from './Pipeline';
29
import {
30
filterSuppressionsThatAffectFunction,
31
findProgramSuppressions,
32
suppressionsToCompilerError,
33
-} from "./Suppression";
33
+} from './Suppression';
34
35
export type CompilerPass = {
36
opts: PluginOptions;
@@ -40,11 +40,11 @@ export type CompilerPass = {
40
};
41
42
function findDirectiveEnablingMemoization(
43
- directives: Array<t.Directive>
43
+ directives: Array<t.Directive>,
44
): t.Directive | null {
45
for (const directive of directives) {
46
const directiveValue = directive.value.value;
47
- if (directiveValue === "use forget" || directiveValue === "use memo") {
47
+ if (directiveValue === 'use forget' || directiveValue === 'use memo') {
48
return directive;
49
}
50
}
@@ -53,13 +53,13 @@ function findDirectiveEnablingMemoization(
53
54
function findDirectiveDisablingMemoization(
55
directives: Array<t.Directive>,
56
- options: PluginOptions
56
+ options: PluginOptions,
57
): t.Directive | null {
58
for (const directive of directives) {
59
const directiveValue = directive.value.value;
60
if (
61
- (directiveValue === "use no forget" ||
62
- directiveValue === "use no memo") &&
61
+ (directiveValue === 'use no forget' ||
62
+ directiveValue === 'use no memo') &&
63
!options.ignoreUseNoForget
64
) {
65
return directive;
@@ -75,7 +75,7 @@ function isCriticalError(err: unknown): boolean {
75
function isConfigError(err: unknown): boolean {
76
if (err instanceof CompilerError) {
77
return err.details.some(
78
- (detail) => detail.severity === ErrorSeverity.InvalidConfig
78
+ detail => detail.severity === ErrorSeverity.InvalidConfig,
79
);
80
}
81
return false;
@@ -92,7 +92,7 @@ export type CompileResult = {
92
* functions which were outlined. Only original functions need to be gated
93
* if gating mode is enabled.
94
*/
95
- kind: "original" | "outlined";
95
+ kind: 'original' | 'outlined';
96
originalFn: BabelFn;
97
compiledFn: CodegenFunction;
98
};
@@ -100,13 +100,13 @@ export type CompileResult = {
100
function handleError(
101
err: unknown,
102
pass: CompilerPass,
103
- fnLoc: t.SourceLocation | null
103
+ fnLoc: t.SourceLocation | null,
104
): void {
105
if (pass.opts.logger) {
106
if (err instanceof CompilerError) {
107
for (const detail of err.details) {
108
pass.opts.logger.logEvent(pass.filename, {
109
- kind: "CompileError",
109
+ kind: 'CompileError',
110
fnLoc,
111
detail: detail.options,
112
});
@@ -116,19 +116,19 @@ function handleError(
116
if (err instanceof Error) {
117
stringifiedError = err.stack ?? err.message;
118
} else {
119
- stringifiedError = err?.toString() ?? "[ null ]";
119
+ stringifiedError = err?.toString() ?? '[ null ]';
120
}
121
122
pass.opts.logger.logEvent(pass.filename, {
123
- kind: "PipelineError",
123
+ kind: 'PipelineError',
124
fnLoc,
125
data: stringifiedError,
126
});
127
}
128
}
129
if (
130
- pass.opts.panicThreshold === "all_errors" ||
131
- (pass.opts.panicThreshold === "critical_errors" && isCriticalError(err)) ||
130
+ pass.opts.panicThreshold === 'all_errors' ||
131
+ (pass.opts.panicThreshold === 'critical_errors' && isCriticalError(err)) ||
132
isConfigError(err) // Always throws regardless of panic threshold
133
) {
134
throw err;
@@ -137,16 +137,16 @@ function handleError(
137
138
export function createNewFunctionNode(
139
originalFn: BabelFn,
140
- compiledFn: CodegenFunction
140
+ compiledFn: CodegenFunction,
141
): t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression {
142
let transformedFn:
143
| t.FunctionDeclaration
144
| t.ArrowFunctionExpression
145
| t.FunctionExpression;
146
switch (originalFn.node.type) {
147
- case "FunctionDeclaration": {
147
+ case 'FunctionDeclaration': {
148
const fn: t.FunctionDeclaration = {
149
- type: "FunctionDeclaration",
149
+ type: 'FunctionDeclaration',
150
id: compiledFn.id,
151
loc: originalFn.node.loc ?? null,
152
async: compiledFn.async,
@@ -157,9 +157,9 @@ export function createNewFunctionNode(
157
transformedFn = fn;
158
break;
159
}
160
- case "ArrowFunctionExpression": {
160
+ case 'ArrowFunctionExpression': {
161
const fn: t.ArrowFunctionExpression = {
162
- type: "ArrowFunctionExpression",
162
+ type: 'ArrowFunctionExpression',
163
loc: originalFn.node.loc ?? null,
164
async: compiledFn.async,
165
generator: compiledFn.generator,
@@ -170,9 +170,9 @@ export function createNewFunctionNode(
170
transformedFn = fn;
171
break;
172
}
173
- case "FunctionExpression": {
173
+ case 'FunctionExpression': {
174
const fn: t.FunctionExpression = {
175
- type: "FunctionExpression",
175
+ type: 'FunctionExpression',
176
id: compiledFn.id,
177
loc: originalFn.node.loc ?? null,
178
async: compiledFn.async,
@@ -198,15 +198,15 @@ export function createNewFunctionNode(
198
const ALREADY_COMPILED: WeakSet<object> | Set<object> = new (WeakSet ?? Set)();
199
200
const DEFAULT_ESLINT_SUPPRESSIONS = [
201
- "react-hooks/exhaustive-deps",
202
- "react-hooks/rules-of-hooks",
201
+ 'react-hooks/exhaustive-deps',
202
+ 'react-hooks/rules-of-hooks',
203
];
204
205
function isFilePartOfSources(
206
sources: Array<string> | ((filename: string) => boolean),
207
- filename: string
207
+ filename: string,
208
): boolean {
209
- if (typeof sources === "function") {
209
+ if (typeof sources === 'function') {
210
return sources(filename);
211
}
212
@@ -221,7 +221,7 @@ function isFilePartOfSources(
221
222
export function compileProgram(
223
program: NodePath<t.Program>,
224
- pass: CompilerPass
224
+ pass: CompilerPass,
225
): void {
226
if (pass.opts.sources) {
227
if (pass.filename === null) {
@@ -233,7 +233,7 @@ export function compileProgram(
233
"When the 'sources' config options is specified, the React compiler will only compile files with a name",
234
severity: ErrorSeverity.InvalidConfig,
235
loc: null,
236
- })
236
+ }),
237
);
238
handleError(error, pass, null);
239
return;
@@ -253,8 +253,8 @@ export function compileProgram(
253
}
254
255
const environment = parseEnvironmentConfig(pass.opts.environment ?? {});
256
- const useMemoCacheIdentifier = program.scope.generateUidIdentifier("c");
257
- const moduleName = pass.opts.runtimeModule ?? "react/compiler-runtime";
256
+ const useMemoCacheIdentifier = program.scope.generateUidIdentifier('c');
257
+ const moduleName = pass.opts.runtimeModule ?? 'react/compiler-runtime';
258
if (hasMemoCacheFunctionImport(program, moduleName)) {
259
return;
260
}
@@ -267,12 +267,12 @@ export function compileProgram(
267
const suppressions = findProgramSuppressions(
268
pass.comments,
269
pass.opts.eslintSuppressionRules ?? DEFAULT_ESLINT_SUPPRESSIONS,
270
- pass.opts.flowSuppressions
270
+ pass.opts.flowSuppressions,
271
);
272
const lintError = suppressionsToCompilerError(suppressions);
273
let hasCriticalError = lintError != null;
274
const queue: Array<{
275
- kind: "original" | "outlined";
275
+ kind: 'original' | 'outlined';
276
fn: BabelFn;
277
fnType: ReactFunctionType;
278
}> = [];
@@ -292,7 +292,7 @@ export function compileProgram(
292
ALREADY_COMPILED.add(fn.node);
293
fn.skip();
294
295
- queue.push({ kind: "original", fn, fnType });
295
+ queue.push({kind: 'original', fn, fnType});
296
};
297
298
// Main traversal to compile with Forget
@@ -324,14 +324,14 @@ export function compileProgram(
324
},
325
{
326
...pass,
327
- opts: { ...pass.opts, ...pass.opts },
327
+ opts: {...pass.opts, ...pass.opts},
328
filename: pass.filename ?? null,
329
- }
329
+ },
330
);
331
332
const processFn = (
333
fn: BabelFn,
334
- fnType: ReactFunctionType
334
+ fnType: ReactFunctionType,
335
): null | CodegenFunction => {
336
if (lintError != null) {
337
/**
@@ -341,7 +341,7 @@ export function compileProgram(
341
*/
342
const suppressionsInFunction = filterSuppressionsThatAffectFunction(
343
suppressions,
344
- fn
344
+ fn,
345
);
346
if (suppressionsInFunction.length > 0) {
347
handleError(lintError, pass, fn.node.loc ?? null);
@@ -357,7 +357,7 @@ export function compileProgram(
357
if (environment.isErr()) {
358
CompilerError.throwInvalidConfig({
359
reason:
360
- "Error in validating environment config. This is an advanced setting and not meant to be used directly",
360
+ 'Error in validating environment config. This is an advanced setting and not meant to be used directly',
361
description: environment.unwrapErr().toString(),
362
suggestions: null,
363
loc: null,
@@ -372,10 +372,10 @@ export function compileProgram(
372
useMemoCacheIdentifier.name,
373
pass.opts.logger,
374
pass.filename,
375
- pass.code
375
+ pass.code,
376
);
377
pass.opts.logger?.logEvent(pass.filename, {
378
- kind: "CompileSuccess",
378
+ kind: 'CompileSuccess',
379
fnLoc: fn.node.loc ?? null,
380
fnName: compiledFn.id?.name ?? null,
381
memoSlots: compiledFn.memoSlotsUsed,
@@ -404,11 +404,11 @@ export function compileProgram(
404
}
405
for (const outlined of compiled.outlined) {
406
CompilerError.invariant(outlined.fn.outlined.length === 0, {
407
- reason: "Unexpected nested outlined functions",
407
+ reason: 'Unexpected nested outlined functions',
408
loc: outlined.fn.loc,
409
});
410
const fn = current.fn.insertAfter(
411
- createNewFunctionNode(current.fn, outlined.fn)
411
+ createNewFunctionNode(current.fn, outlined.fn),
412
)[0]!;
413
fn.skip();
414
ALREADY_COMPILED.add(fn.node);
@@ -437,9 +437,9 @@ export function compileProgram(
437
if (pass.opts.gating != null) {
438
const error = checkFunctionReferencedBeforeDeclarationAtTopLevel(
439
program,
440
- compiledFns.map((result) => {
440
+ compiledFns.map(result => {
441
return result.originalFn;
442
- })
442
+ }),
443
);
444
if (error) {
445
handleError(error, pass, null);
@@ -460,32 +460,32 @@ export function compileProgram(
460
pass.opts.environment?.enableEmitInstrumentForget;
461
if (enableEmitInstrumentForget != null) {
462
externalFunctions.push(
463
- tryParseExternalFunction(enableEmitInstrumentForget.fn)
463
+ tryParseExternalFunction(enableEmitInstrumentForget.fn),
464
);
465
if (enableEmitInstrumentForget.gating != null) {
466
externalFunctions.push(
467
- tryParseExternalFunction(enableEmitInstrumentForget.gating)
467
+ tryParseExternalFunction(enableEmitInstrumentForget.gating),
468
);
469
}
470
}
471
472
if (pass.opts.environment?.enableEmitFreeze != null) {
473
const enableEmitFreeze = tryParseExternalFunction(
474
- pass.opts.environment.enableEmitFreeze
474
+ pass.opts.environment.enableEmitFreeze,
475
);
476
externalFunctions.push(enableEmitFreeze);
477
}
478
479
if (pass.opts.environment?.enableEmitHookGuards != null) {
480
const enableEmitHookGuards = tryParseExternalFunction(
481
- pass.opts.environment.enableEmitHookGuards
481
+ pass.opts.environment.enableEmitHookGuards,
482
);
483
externalFunctions.push(enableEmitHookGuards);
484
}
485
486
if (pass.opts.environment?.enableChangeDetectionForDebugging != null) {
487
const enableChangeDetectionForDebugging = tryParseExternalFunction(
488
- pass.opts.environment.enableChangeDetectionForDebugging
488
+ pass.opts.environment.enableChangeDetectionForDebugging,
489
);
490
externalFunctions.push(enableChangeDetectionForDebugging);
491
}
@@ -499,10 +499,10 @@ export function compileProgram(
499
* error elsewhere in the file, regardless of bailout mode.
500
*/
501
for (const result of compiledFns) {
502
- const { kind, originalFn, compiledFn } = result;
502
+ const {kind, originalFn, compiledFn} = result;
503
const transformedFn = createNewFunctionNode(originalFn, compiledFn);
504
505
- if (gating != null && kind === "original") {
505
+ if (gating != null && kind === 'original') {
506
insertGatedFunctionDeclaration(originalFn, transformedFn, gating);
507
} else {
508
originalFn.replaceWith(transformedFn);
@@ -523,7 +523,7 @@ export function compileProgram(
523
updateMemoCacheFunctionImport(
524
program,
525
moduleName,
526
- useMemoCacheIdentifier.name
526
+ useMemoCacheIdentifier.name,
527
);
528
}
529
addImportsToProgram(program, externalFunctions);
@@ -532,18 +532,18 @@ export function compileProgram(
532
533
function getReactFunctionType(
534
fn: BabelFn,
535
- pass: CompilerPass
535
+ pass: CompilerPass,
536
): ReactFunctionType | null {
537
const hookPattern = pass.opts.environment?.hookPattern ?? null;
538
- if (fn.node.body.type === "BlockStatement") {
538
+ if (fn.node.body.type === 'BlockStatement') {
539
// Opt-outs disable compilation regardless of mode
540
const useNoForget = findDirectiveDisablingMemoization(
541
fn.node.body.directives,
542
- pass.opts
542
+ pass.opts,
543
);
544
if (useNoForget != null) {
545
pass.opts.logger?.logEvent(pass.filename, {
546
- kind: "CompileError",
546
+ kind: 'CompileError',
547
fnLoc: fn.node.body.loc ?? null,
548
detail: {
549
severity: ErrorSeverity.Todo,
@@ -556,7 +556,7 @@ function getReactFunctionType(
556
}
557
// Otherwise opt-ins enable compilation regardless of mode
558
if (findDirectiveEnablingMemoization(fn.node.body.directives) != null) {
559
- return getComponentOrHookLike(fn, hookPattern) ?? "Other";
559
+ return getComponentOrHookLike(fn, hookPattern) ?? 'Other';
560
}
561
}
562
@@ -564,36 +564,36 @@ function getReactFunctionType(
564
let componentSyntaxType: ReactFunctionType | null = null;
565
if (fn.isFunctionDeclaration()) {
566
if (isComponentDeclaration(fn.node)) {
567
- componentSyntaxType = "Component";
567
+ componentSyntaxType = 'Component';
568
} else if (isHookDeclaration(fn.node)) {
569
- componentSyntaxType = "Hook";
569
+ componentSyntaxType = 'Hook';
570
}
571
}
572
573
switch (pass.opts.compilationMode) {
574
- case "annotation": {
574
+ case 'annotation': {
575
// opt-ins are checked above
576
return null;
577
}
578
- case "infer": {
578
+ case 'infer': {
579
// Check if this is a component or hook-like function
580
return componentSyntaxType ?? getComponentOrHookLike(fn, hookPattern);
581
}
582
- case "syntax": {
582
+ case 'syntax': {
583
return componentSyntaxType;
584
}
585
- case "all": {
585
+ case 'all': {
586
// Compile only top level functions
587
if (fn.scope.getProgramParent() !== fn.scope.parent) {
588
return null;
589
}
590
591
- return getComponentOrHookLike(fn, hookPattern) ?? "Other";
591
+ return getComponentOrHookLike(fn, hookPattern) ?? 'Other';
592
}
593
default: {
594
assertExhaustive(
595
pass.opts.compilationMode,
596
- `Unexpected compilationMode \`${pass.opts.compilationMode}\``
596
+ `Unexpected compilationMode \`${pass.opts.compilationMode}\``,
597
);
598
}
599
}
@@ -606,12 +606,12 @@ function getReactFunctionType(
606
*/
607
function hasMemoCacheFunctionImport(
608
program: NodePath<t.Program>,
609
- moduleName: string
609
+ moduleName: string,
610
): boolean {
611
let hasUseMemoCache = false;
612
program.traverse({
613
ImportSpecifier(path) {
614
- const imported = path.get("imported");
614
+ const imported = path.get('imported');
615
let importedName: string | null = null;
616
if (imported.isIdentifier()) {
617
importedName = imported.node.name;
@@ -619,9 +619,9 @@ function hasMemoCacheFunctionImport(
619
importedName = imported.node.value;
620
}
621
if (
622
- importedName === "c" &&
622
+ importedName === 'c' &&
623
path.parentPath.isImportDeclaration() &&
624
- path.parentPath.get("source").node.value === moduleName
624
+ path.parentPath.get('source').node.value === moduleName
625
) {
626
hasUseMemoCache = true;
627
}
@@ -644,18 +644,18 @@ function isHookName(s: string, hookPattern: string | null): boolean {
644
645
function isHook(
646
path: NodePath<t.Expression | t.PrivateName>,
647
- hookPattern: string | null
647
+ hookPattern: string | null,
648
): boolean {
649
if (path.isIdentifier()) {
650
return isHookName(path.node.name, hookPattern);
651
} else if (
652
path.isMemberExpression() &&
653
!path.node.computed &&
654
- isHook(path.get("property"), hookPattern)
654
+ isHook(path.get('property'), hookPattern)
655
) {
656
- const obj = path.get("object").node;
656
+ const obj = path.get('object').node;
657
const isPascalCaseNameSpace = /^[A-Z].*/;
658
- return obj.type === "Identifier" && isPascalCaseNameSpace.test(obj.name);
658
+ return obj.type === 'Identifier' && isPascalCaseNameSpace.test(obj.name);
659
} else {
660
return false;
661
}
@@ -672,15 +672,15 @@ function isComponentName(path: NodePath<t.Expression>): boolean {
672
673
function isReactAPI(
674
path: NodePath<t.Expression | t.PrivateName | t.V8IntrinsicIdentifier>,
675
- functionName: string
675
+ functionName: string,
676
): boolean {
677
const node = path.node;
678
return (
679
- (node.type === "Identifier" && node.name === functionName) ||
680
- (node.type === "MemberExpression" &&
681
- node.object.type === "Identifier" &&
682
- node.object.name === "React" &&
683
- node.property.type === "Identifier" &&
679
+ (node.type === 'Identifier' && node.name === functionName) ||
680
+ (node.type === 'MemberExpression' &&
681
+ node.object.type === 'Identifier' &&
682
+ node.object.name === 'React' &&
683
+ node.property.type === 'Identifier' &&
684
node.property.name === functionName)
685
);
686
}
@@ -693,8 +693,8 @@ function isReactAPI(
693
function isForwardRefCallback(path: NodePath<t.Expression>): boolean {
694
return !!(
695
path.parentPath.isCallExpression() &&
696
- path.parentPath.get("callee").isExpression() &&
697
- isReactAPI(path.parentPath.get("callee"), "forwardRef")
696
+ path.parentPath.get('callee').isExpression() &&
697
+ isReactAPI(path.parentPath.get('callee'), 'forwardRef')
698
);
699
}
700
@@ -706,50 +706,50 @@ function isForwardRefCallback(path: NodePath<t.Expression>): boolean {
706
function isMemoCallback(path: NodePath<t.Expression>): boolean {
707
return (
708
path.parentPath.isCallExpression() &&
709
- path.parentPath.get("callee").isExpression() &&
710
- isReactAPI(path.parentPath.get("callee"), "memo")
709
+ path.parentPath.get('callee').isExpression() &&
710
+ isReactAPI(path.parentPath.get('callee'), 'memo')
711
);
712
}
713
714
function isValidPropsAnnotation(
715
- annot: t.TypeAnnotation | t.TSTypeAnnotation | t.Noop | null | undefined
715
+ annot: t.TypeAnnotation | t.TSTypeAnnotation | t.Noop | null | undefined,
716
): boolean {
717
if (annot == null) {
718
return true;
719
- } else if (annot.type === "TSTypeAnnotation") {
719
+ } else if (annot.type === 'TSTypeAnnotation') {
720
switch (annot.typeAnnotation.type) {
721
- case "TSArrayType":
722
- case "TSBigIntKeyword":
723
- case "TSBooleanKeyword":
724
- case "TSConstructorType":
725
- case "TSFunctionType":
726
- case "TSLiteralType":
727
- case "TSNeverKeyword":
728
- case "TSNumberKeyword":
729
- case "TSStringKeyword":
730
- case "TSSymbolKeyword":
731
- case "TSTupleType":
721
+ case 'TSArrayType':
722
+ case 'TSBigIntKeyword':
723
+ case 'TSBooleanKeyword':
724
+ case 'TSConstructorType':
725
+ case 'TSFunctionType':
726
+ case 'TSLiteralType':
727
+ case 'TSNeverKeyword':
728
+ case 'TSNumberKeyword':
729
+ case 'TSStringKeyword':
730
+ case 'TSSymbolKeyword':
731
+ case 'TSTupleType':
732
return false;
733
}
734
return true;
735
- } else if (annot.type === "TypeAnnotation") {
735
+ } else if (annot.type === 'TypeAnnotation') {
736
switch (annot.typeAnnotation.type) {
737
- case "ArrayTypeAnnotation":
738
- case "BooleanLiteralTypeAnnotation":
739
- case "BooleanTypeAnnotation":
740
- case "EmptyTypeAnnotation":
741
- case "FunctionTypeAnnotation":
742
- case "NumberLiteralTypeAnnotation":
743
- case "NumberTypeAnnotation":
744
- case "StringLiteralTypeAnnotation":
745
- case "StringTypeAnnotation":
746
- case "SymbolTypeAnnotation":
747
- case "ThisTypeAnnotation":
748
- case "TupleTypeAnnotation":
737
+ case 'ArrayTypeAnnotation':
738
+ case 'BooleanLiteralTypeAnnotation':
739
+ case 'BooleanTypeAnnotation':
740
+ case 'EmptyTypeAnnotation':
741
+ case 'FunctionTypeAnnotation':
742
+ case 'NumberLiteralTypeAnnotation':
743
+ case 'NumberTypeAnnotation':
744
+ case 'StringLiteralTypeAnnotation':
745
+ case 'StringTypeAnnotation':
746
+ case 'SymbolTypeAnnotation':
747
+ case 'ThisTypeAnnotation':
748
+ case 'TupleTypeAnnotation':
749
return false;
750
}
751
return true;
752
- } else if (annot.type === "Noop") {
752
+ } else if (annot.type === 'Noop') {
753
return true;
754
} else {
755
assertExhaustive(annot, `Unexpected annotation node \`${annot}\``);
@@ -757,7 +757,7 @@ function isValidPropsAnnotation(
757
}
758
759
function isValidComponentParams(
760
- params: Array<NodePath<t.Identifier | t.Pattern | t.RestElement>>
760
+ params: Array<NodePath<t.Identifier | t.Pattern | t.RestElement>>,
761
): boolean {
762
if (params.length === 0) {
763
return true;
@@ -770,8 +770,8 @@ function isValidComponentParams(
770
return !params[0].isRestElement();
771
} else if (params[1].isIdentifier()) {
772
// check if second param might be a ref
773
- const { name } = params[1].node;
774
- return name.includes("ref") || name.includes("Ref");
773
+ const {name} = params[1].node;
774
+ return name.includes('ref') || name.includes('Ref');
775
} else {
776
/**
777
* Otherwise, avoid helper functions that take more than one argument.
@@ -792,19 +792,19 @@ function getComponentOrHookLike(
792
node: NodePath<
793
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
794
>,
795
- hookPattern: string | null
795
+ hookPattern: string | null,
796
): ReactFunctionType | null {
797
const functionName = getFunctionName(node);
798
// Check if the name is component or hook like:
799
if (functionName !== null && isComponentName(functionName)) {
800
let isComponent =
801
callsHooksOrCreatesJsx(node, hookPattern) &&
802
- isValidComponentParams(node.get("params")) &&
802
+ isValidComponentParams(node.get('params')) &&
803
!returnsNonNode(node);
804
- return isComponent ? "Component" : null;
804
+ return isComponent ? 'Component' : null;
805
} else if (functionName !== null && isHook(functionName, hookPattern)) {
806
// Hooks have hook invocations or JSX, but can take any # of arguments
807
- return callsHooksOrCreatesJsx(node, hookPattern) ? "Hook" : null;
807
+ return callsHooksOrCreatesJsx(node, hookPattern) ? 'Hook' : null;
808
}
809
810
/*
@@ -814,7 +814,7 @@ function getComponentOrHookLike(
814
if (node.isFunctionExpression() || node.isArrowFunctionExpression()) {
815
if (isForwardRefCallback(node) || isMemoCallback(node)) {
816
// As an added check we also look for hook invocations or JSX
817
- return callsHooksOrCreatesJsx(node, hookPattern) ? "Component" : null;
817
+ return callsHooksOrCreatesJsx(node, hookPattern) ? 'Component' : null;
818
}
819
}
820
return null;
@@ -823,12 +823,12 @@ function getComponentOrHookLike(
823
function skipNestedFunctions(
824
node: NodePath<
825
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
826
- >
826
+ >,
827
) {
828
return (
829
fn: NodePath<
830
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
831
- >
831
+ >,
832
): void => {
833
if (fn.node !== node.node) {
834
fn.skip();
@@ -840,7 +840,7 @@ function callsHooksOrCreatesJsx(
840
node: NodePath<
841
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
842
>,
843
- hookPattern: string | null
843
+ hookPattern: string | null,
844
): boolean {
845
let invokesHooks = false;
846
let createsJsx = false;
@@ -850,7 +850,7 @@ function callsHooksOrCreatesJsx(
850
createsJsx = true;
851
},
852
CallExpression(call) {
853
- const callee = call.get("callee");
853
+ const callee = call.get('callee');
854
if (callee.isExpression() && isHook(callee, hookPattern)) {
855
invokesHooks = true;
856
}
@@ -866,7 +866,7 @@ function callsHooksOrCreatesJsx(
866
function returnsNonNode(
867
node: NodePath<
868
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
869
- >
869
+ >,
870
): boolean {
871
let hasReturn = false;
872
let returnsNonNode = false;
@@ -879,12 +879,12 @@ function returnsNonNode(
879
returnsNonNode = true;
880
} else {
881
switch (argument.type) {
882
- case "ObjectExpression":
883
- case "ArrowFunctionExpression":
884
- case "FunctionExpression":
885
- case "BigIntLiteral":
886
- case "ClassExpression":
887
- case "NewExpression": // technically `new Array()` is legit, but unlikely
882
+ case 'ObjectExpression':
883
+ case 'ArrowFunctionExpression':
884
+ case 'FunctionExpression':
885
+ case 'BigIntLiteral':
886
+ case 'ClassExpression':
887
+ case 'NewExpression': // technically `new Array()` is legit, but unlikely
888
returnsNonNode = true;
889
}
890
}
@@ -908,10 +908,10 @@ function returnsNonNode(
908
function getFunctionName(
909
path: NodePath<
910
t.FunctionDeclaration | t.ArrowFunctionExpression | t.FunctionExpression
911
- >
911
+ >,
912
): NodePath<t.Expression> | null {
913
if (path.isFunctionDeclaration()) {
914
- const id = path.get("id");
914
+ const id = path.get('id');
915
if (id.isIdentifier()) {
916
return id;
917
}
@@ -919,31 +919,31 @@ function getFunctionName(
919
}
920
let id: NodePath<t.LVal | t.Expression | t.PrivateName> | null = null;
921
const parent = path.parentPath;
922
- if (parent.isVariableDeclarator() && parent.get("init").node === path.node) {
922
+ if (parent.isVariableDeclarator() && parent.get('init').node === path.node) {
923
// const useHook = () => {};
924
- id = parent.get("id");
924
+ id = parent.get('id');
925
} else if (
926
parent.isAssignmentExpression() &&
927
- parent.get("right").node === path.node &&
928
- parent.get("operator") === "="
927
+ parent.get('right').node === path.node &&
928
+ parent.get('operator') === '='
929
) {
930
// useHook = () => {};
931
- id = parent.get("left");
931
+ id = parent.get('left');
932
} else if (
933
parent.isProperty() &&
934
- parent.get("value").node === path.node &&
935
- !parent.get("computed") &&
936
- parent.get("key").isLVal()
934
+ parent.get('value').node === path.node &&
935
+ !parent.get('computed') &&
936
+ parent.get('key').isLVal()
937
) {
938
/*
939
* {useHook: () => {}}
940
* {useHook() {}}
941
*/
942
- id = parent.get("key");
942
+ id = parent.get('key');
943
} else if (
944
parent.isAssignmentPattern() &&
945
- parent.get("right").node === path.node &&
946
- !parent.get("computed")
945
+ parent.get('right').node === path.node &&
946
+ !parent.get('computed')
947
) {
948
/*
949
* const {useHook = () => {}} = {};
@@ -952,7 +952,7 @@ function getFunctionName(
952
* Kinda clowny, but we'd said we'd follow spec convention for
953
* `IsAnonymousFunctionDefinition()` usage.
954
*/
955
- id = parent.get("left");
955
+ id = parent.get('left');
956
}
957
if (id !== null && (id.isIdentifier() || id.isMemberExpression())) {
958
return id;
@@ -963,17 +963,17 @@ function getFunctionName(
963
964
function checkFunctionReferencedBeforeDeclarationAtTopLevel(
965
program: NodePath<t.Program>,
966
- fns: Array<BabelFn>
966
+ fns: Array<BabelFn>,
967
): CompilerError | null {
968
const fnIds = new Set(
969
fns
970
- .map((fn) => getFunctionName(fn))
970
+ .map(fn => getFunctionName(fn))
971
.filter(
972
- (name): name is NodePath<t.Identifier> => !!name && name.isIdentifier()
972
+ (name): name is NodePath<t.Identifier> => !!name && name.isIdentifier(),
973
)
974
- .map((name) => name.node)
974
+ .map(name => name.node),
975
);
976
- const fnNames = new Map([...fnIds].map((id) => [id.name, id]));
976
+ const fnNames = new Map([...fnIds].map(id => [id.name, id]));
977
const errors = new CompilerError();
978
979
program.traverse({
@@ -1019,7 +1019,7 @@ function checkFunctionReferencedBeforeDeclarationAtTopLevel(
1019
loc: fn.loc ?? null,
1020
suggestions: null,
1021
severity: ErrorSeverity.Invariant,
1022
- })
1022
+ }),
1023
);
1024
}
1025
},
compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Reanimated.ts
+9
-9
@@ -1,13 +1,13 @@
1
-import type * as BabelCore from "@babel/core";
2
-import { hasOwnProperty } from "../Utils/utils";
3
-import { PluginOptions } from "./Options";
1
+import type * as BabelCore from '@babel/core';
2
+import {hasOwnProperty} from '../Utils/utils';
3
+import {PluginOptions} from './Options';
4
5
function hasModule(name: string): boolean {
6
try {
7
return !!require.resolve(name);
8
} catch (error: any) {
9
if (
10
- error.code === "MODULE_NOT_FOUND" &&
10
+ error.code === 'MODULE_NOT_FOUND' &&
11
error.message.indexOf(name) !== -1
12
) {
13
return false;
@@ -24,22 +24,22 @@ function hasModule(name: string): boolean {
24
* See https://github.com/expo/expo/blob/e4b8d86442482c7316365a6b7ec1141eec73409d/packages/babel-preset-expo/src/index.ts#L300-L301
25
*/
26
export function pipelineUsesReanimatedPlugin(
27
- plugins: Array<BabelCore.PluginItem> | null | undefined
27
+ plugins: Array<BabelCore.PluginItem> | null | undefined,
28
): boolean {
29
if (Array.isArray(plugins)) {
30
for (const plugin of plugins) {
31
- if (hasOwnProperty(plugin, "key")) {
31
+ if (hasOwnProperty(plugin, 'key')) {
32
const key = (plugin as any).key; // already checked
33
if (
34
- typeof key === "string" &&
35
- key.indexOf("react-native-reanimated") !== -1
34
+ typeof key === 'string' &&
35
+ key.indexOf('react-native-reanimated') !== -1
36
) {
37
return true;
38
}
39
}
40
}
41
}
42
- return hasModule("react-native-reanimated");
42
+ return hasModule('react-native-reanimated');
43
}
44
45
export function injectReanimatedFlag(options: PluginOptions): PluginOptions {
compiler/packages/babel-plugin-react-compiler/src/Entrypoint/Suppression.ts
+23
-23
@@ -5,15 +5,15 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { NodePath } from "@babel/core";
9
-import * as t from "@babel/types";
8
+import {NodePath} from '@babel/core';
9
+import * as t from '@babel/types';
10
import {
11
CompilerError,
12
CompilerErrorDetail,
13
CompilerSuggestionOperation,
14
ErrorSeverity,
15
-} from "../CompilerError";
16
-import { assertExhaustive } from "../Utils/utils";
15
+} from '../CompilerError';
16
+import {assertExhaustive} from '../Utils/utils';
17
18
/**
19
* Captures the start and end range of a pair of eslint-disable ... eslint-enable comments. In the
@@ -29,7 +29,7 @@ export type SuppressionRange = {
29
source: SuppressionSource;
30
};
31
32
-type SuppressionSource = "Eslint" | "Flow";
32
+type SuppressionSource = 'Eslint' | 'Flow';
33
34
/**
35
* An suppression affects a function if:
@@ -38,7 +38,7 @@ type SuppressionSource = "Eslint" | "Flow";
38
*/
39
export function filterSuppressionsThatAffectFunction(
40
suppressionRanges: Array<SuppressionRange>,
41
- fn: NodePath<t.Function>
41
+ fn: NodePath<t.Function>,
42
): Array<SuppressionRange> {
43
const suppressionsInScope: Array<SuppressionRange> = [];
44
const fnNode = fn.node;
@@ -78,21 +78,21 @@ export function filterSuppressionsThatAffectFunction(
78
export function findProgramSuppressions(
79
programComments: Array<t.Comment>,
80
ruleNames: Array<string>,
81
- flowSuppressions: boolean
81
+ flowSuppressions: boolean,
82
): Array<SuppressionRange> {
83
const suppressionRanges: Array<SuppressionRange> = [];
84
let disableComment: t.Comment | null = null;
85
let enableComment: t.Comment | null = null;
86
let source: SuppressionSource | null = null;
87
88
- const rulePattern = `(${ruleNames.join("|")})`;
88
+ const rulePattern = `(${ruleNames.join('|')})`;
89
const disableNextLinePattern = new RegExp(
90
- `eslint-disable-next-line ${rulePattern}`
90
+ `eslint-disable-next-line ${rulePattern}`,
91
);
92
const disablePattern = new RegExp(`eslint-disable ${rulePattern}`);
93
const enablePattern = new RegExp(`eslint-enable ${rulePattern}`);
94
const flowSuppressionPattern = new RegExp(
95
- "\\$(FlowFixMe\\w*|FlowExpectedError|FlowIssue)\\[react\\-rule"
95
+ '\\$(FlowFixMe\\w*|FlowExpectedError|FlowIssue)\\[react\\-rule',
96
);
97
98
for (const comment of programComments) {
@@ -110,7 +110,7 @@ export function findProgramSuppressions(
110
) {
111
disableComment = comment;
112
enableComment = comment;
113
- source = "Eslint";
113
+ source = 'Eslint';
114
}
115
116
if (
@@ -120,15 +120,15 @@ export function findProgramSuppressions(
120
) {
121
disableComment = comment;
122
enableComment = comment;
123
- source = "Flow";
123
+ source = 'Flow';
124
}
125
126
if (disablePattern.test(comment.value)) {
127
disableComment = comment;
128
- source = "Eslint";
128
+ source = 'Eslint';
129
}
130
131
- if (enablePattern.test(comment.value) && source === "Eslint") {
131
+ if (enablePattern.test(comment.value) && source === 'Eslint') {
132
enableComment = comment;
133
}
134
@@ -147,7 +147,7 @@ export function findProgramSuppressions(
147
}
148
149
export function suppressionsToCompilerError(
150
- suppressionRanges: Array<SuppressionRange>
150
+ suppressionRanges: Array<SuppressionRange>,
151
): CompilerError | null {
152
if (suppressionRanges.length === 0) {
153
return null;
@@ -162,21 +162,21 @@ export function suppressionsToCompilerError(
162
}
163
let reason, suggestion;
164
switch (suppressionRange.source) {
165
- case "Eslint":
165
+ case 'Eslint':
166
reason =
167
- "React Compiler has skipped optimizing this component because one or more React ESLint rules were disabled";
167
+ 'React Compiler has skipped optimizing this component because one or more React ESLint rules were disabled';
168
suggestion =
169
- "Remove the ESLint suppression and address the React error";
169
+ 'Remove the ESLint suppression and address the React error';
170
break;
171
- case "Flow":
171
+ case 'Flow':
172
reason =
173
- "React Compiler has skipped optimizing this component because one or more React rule violations were reported by Flow";
174
- suggestion = "Remove the Flow suppression and address the React error";
173
+ 'React Compiler has skipped optimizing this component because one or more React rule violations were reported by Flow';
174
+ suggestion = 'Remove the Flow suppression and address the React error';
175
break;
176
default:
177
assertExhaustive(
178
suppressionRange.source,
179
- "Unhandled suppression source"
179
+ 'Unhandled suppression source',
180
);
181
}
182
error.pushErrorDetail(
@@ -195,7 +195,7 @@ export function suppressionsToCompilerError(
195
op: CompilerSuggestionOperation.Remove,
196
},
197
],
198
- })
198
+ }),
199
);
200
}
201
return error;
compiler/packages/babel-plugin-react-compiler/src/Entrypoint/index.ts
+6
-6
@@ -5,9 +5,9 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-export * from "./Gating";
9
-export * from "./Imports";
10
-export * from "./Options";
11
-export * from "./Pipeline";
12
-export * from "./Program";
13
-export * from "./Suppression";
8
+export * from './Gating';
9
+export * from './Imports';
10
+export * from './Options';
11
+export * from './Pipeline';
12
+export * from './Program';
13
+export * from './Suppression';
compiler/packages/babel-plugin-react-compiler/src/HIR/AssertConsistentIdentifiers.ts
+6
-6
@@ -5,20 +5,20 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
8
+import {CompilerError} from '../CompilerError';
9
import {
10
GeneratedSource,
11
HIRFunction,
12
Identifier,
13
IdentifierId,
14
SourceLocation,
15
-} from "./HIR";
16
-import { printPlace } from "./PrintHIR";
15
+} from './HIR';
16
+import {printPlace} from './PrintHIR';
17
import {
18
eachInstructionLValue,
19
eachInstructionValueOperand,
20
eachTerminalOperand,
21
-} from "./visitors";
21
+} from './visitors';
22
23
/*
24
* Validation pass to check that there is a 1:1 mapping between Identifier objects and IdentifierIds,
@@ -44,7 +44,7 @@ export function assertConsistentIdentifiers(fn: HIRFunction): void {
44
CompilerError.invariant(!assignments.has(instr.lvalue.identifier.id), {
45
reason: `Expected lvalues to be assigned exactly once`,
46
description: `Found duplicate assignment of '${printPlace(
47
- instr.lvalue
47
+ instr.lvalue,
48
)}'`,
49
loc: instr.lvalue.loc,
50
suggestions: null,
@@ -68,7 +68,7 @@ type Identifiers = Map<IdentifierId, Identifier>;
68
function validate(
69
identifiers: Identifiers,
70
identifier: Identifier,
71
- loc: SourceLocation | null = null
71
+ loc: SourceLocation | null = null,
72
): void {
73
const previous = identifiers.get(identifier.id);
74
if (previous === undefined) {
compiler/packages/babel-plugin-react-compiler/src/HIR/AssertTerminalBlocksExist.ts
+9
-9
@@ -5,18 +5,18 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
9
-import { GeneratedSource, HIRFunction } from "./HIR";
10
-import { printTerminal } from "./PrintHIR";
11
-import { eachTerminalSuccessor, mapTerminalSuccessors } from "./visitors";
8
+import {CompilerError} from '../CompilerError';
9
+import {GeneratedSource, HIRFunction} from './HIR';
10
+import {printTerminal} from './PrintHIR';
11
+import {eachTerminalSuccessor, mapTerminalSuccessors} from './visitors';
12
13
export function assertTerminalSuccessorsExist(fn: HIRFunction): void {
14
for (const [, block] of fn.body.blocks) {
15
- mapTerminalSuccessors(block.terminal, (successor) => {
15
+ mapTerminalSuccessors(block.terminal, successor => {
16
CompilerError.invariant(fn.body.blocks.has(successor), {
17
reason: `Terminal successor references unknown block`,
18
description: `Block bb${successor} does not exist for terminal '${printTerminal(
19
- block.terminal
19
+ block.terminal,
20
)}'`,
21
loc: (block.terminal as any).loc ?? GeneratedSource,
22
suggestions: null,
@@ -31,16 +31,16 @@ export function assertTerminalPredsExist(fn: HIRFunction): void {
31
for (const pred of block.preds) {
32
const predBlock = fn.body.blocks.get(pred);
33
CompilerError.invariant(predBlock != null, {
34
- reason: "Expected predecessor block to exist",
34
+ reason: 'Expected predecessor block to exist',
35
description: `Block ${block.id} references non-existent ${pred}`,
36
loc: GeneratedSource,
37
});
38
CompilerError.invariant(
39
[...eachTerminalSuccessor(predBlock.terminal)].includes(block.id),
40
{
41
- reason: "Terminal successor does not reference correct predecessor",
41
+ reason: 'Terminal successor does not reference correct predecessor',
42
loc: GeneratedSource,
43
- }
43
+ },
44
);
45
}
46
}
compiler/packages/babel-plugin-react-compiler/src/HIR/AssertValidBlockNesting.ts
+12
-12
@@ -1,4 +1,4 @@
1
-import { CompilerError } from "..";
1
+import {CompilerError} from '..';
2
import {
3
BlockId,
4
GeneratedSource,
@@ -7,13 +7,13 @@ import {
7
Place,
8
ReactiveScope,
9
ScopeId,
10
-} from "./HIR";
10
+} from './HIR';
11
import {
12
eachInstructionLValue,
13
eachInstructionOperand,
14
eachTerminalOperand,
15
terminalFallthrough,
16
-} from "./visitors";
16
+} from './visitors';
17
18
/**
19
* This pass asserts that program blocks and scopes properly form a tree hierarchy
@@ -41,11 +41,11 @@ import {
41
*/
42
type Block =
43
| ({
44
- kind: "ProgramBlockSubtree";
44
+ kind: 'ProgramBlockSubtree';
45
id: BlockId;
46
} & MutableRange)
47
| ({
48
- kind: "Scope";
48
+ kind: 'Scope';
49
id: ScopeId;
50
} & MutableRange);
51
@@ -96,7 +96,7 @@ export function getScopes(fn: HIRFunction): Set<ReactiveScope> {
96
*/
97
export function rangePreOrderComparator(
98
a: MutableRange,
99
- b: MutableRange
99
+ b: MutableRange,
100
): number {
101
const startDiff = a.start - b.start;
102
if (startDiff !== 0) return startDiff;
@@ -108,7 +108,7 @@ export function recursivelyTraverseItems<T, TContext>(
108
getRange: (val: T) => MutableRange,
109
context: TContext,
110
enter: (val: T, context: TContext) => void,
111
- exit: (val: T, context: TContext) => void
111
+ exit: (val: T, context: TContext) => void,
112
): void {
113
items.sort((a, b) => rangePreOrderComparator(getRange(a), getRange(b)));
114
let activeItems: Array<T> = [];
@@ -122,7 +122,7 @@ export function recursivelyTraverseItems<T, TContext>(
122
const disjoint = currRange.start >= maybeParentRange.end;
123
const nested = currRange.end <= maybeParentRange.end;
124
CompilerError.invariant(disjoint || nested, {
125
- reason: "Invalid nesting in program blocks or scopes",
125
+ reason: 'Invalid nesting in program blocks or scopes',
126
description: `Items overlap but are not nested: ${maybeParentRange.start}:${maybeParentRange.end}(${currRange.start}:${currRange.end})`,
127
loc: GeneratedSource,
128
});
@@ -148,8 +148,8 @@ const no_op: () => void = () => {};
148
export function assertValidBlockNesting(fn: HIRFunction): void {
149
const scopes = getScopes(fn);
150
151
- const blocks: Array<Block> = [...scopes].map((scope) => ({
152
- kind: "Scope",
151
+ const blocks: Array<Block> = [...scopes].map(scope => ({
152
+ kind: 'Scope',
153
id: scope.id,
154
...scope.range,
155
})) as Array<Block>;
@@ -159,7 +159,7 @@ export function assertValidBlockNesting(fn: HIRFunction): void {
159
const fallthrough = fn.body.blocks.get(fallthroughId)!;
160
const end = fallthrough.instructions[0]?.id ?? fallthrough.terminal.id;
161
blocks.push({
162
- kind: "ProgramBlockSubtree",
162
+ kind: 'ProgramBlockSubtree',
163
id: block.id,
164
start: block.terminal.id,
165
end,
@@ -167,5 +167,5 @@ export function assertValidBlockNesting(fn: HIRFunction): void {
167
}
168
}
169
170
- recursivelyTraverseItems(blocks, (block) => block, null, no_op, no_op);
170
+ recursivelyTraverseItems(blocks, block => block, null, no_op, no_op);
171
}
compiler/packages/babel-plugin-react-compiler/src/HIR/AssertValidMutableRanges.ts
+5
-5
@@ -5,13 +5,13 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import invariant from "invariant";
9
-import { HIRFunction, Identifier, MutableRange } from "./HIR";
8
+import invariant from 'invariant';
9
+import {HIRFunction, Identifier, MutableRange} from './HIR';
10
import {
11
eachInstructionLValue,
12
eachInstructionOperand,
13
eachTerminalOperand,
14
-} from "./visitors";
14
+} from './visitors';
15
16
/*
17
* Checks that all mutable ranges in the function are well-formed, with
@@ -49,8 +49,8 @@ function validateMutableRange(mutableRange: MutableRange): void {
49
invariant(
50
(mutableRange.start === 0 && mutableRange.end === 0) ||
51
mutableRange.end > mutableRange.start,
52
- "Identifier scope mutableRange was invalid: [%s:%s]",
52
+ 'Identifier scope mutableRange was invalid: [%s:%s]',
53
mutableRange.start,
54
- mutableRange.end
54
+ mutableRange.end,
55
);
56
}
compiler/packages/babel-plugin-react-compiler/src/HIR/BuildHIR.ts
+857
-857
@@ -5,18 +5,18 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { NodePath, Scope } from "@babel/traverse";
9
-import * as t from "@babel/types";
10
-import { Expression } from "@babel/types";
11
-import invariant from "invariant";
8
+import {NodePath, Scope} from '@babel/traverse';
9
+import * as t from '@babel/types';
10
+import {Expression} from '@babel/types';
11
+import invariant from 'invariant';
12
import {
13
CompilerError,
14
CompilerSuggestionOperation,
15
ErrorSeverity,
16
-} from "../CompilerError";
17
-import { Err, Ok, Result } from "../Utils/Result";
18
-import { assertExhaustive, hasNode } from "../Utils/utils";
19
-import { Environment } from "./Environment";
16
+} from '../CompilerError';
17
+import {Err, Ok, Result} from '../Utils/Result';
18
+import {assertExhaustive, hasNode} from '../Utils/utils';
19
+import {Environment} from './Environment';
20
import {
21
ArrayExpression,
22
ArrayPattern,
@@ -45,9 +45,9 @@ import {
45
makeInstructionId,
46
makeType,
47
promoteTemporary,
48
-} from "./HIR";
49
-import HIRBuilder, { Bindings } from "./HIRBuilder";
50
-import { BuiltInArrayId } from "./ObjectShape";
48
+} from './HIR';
49
+import HIRBuilder, {Bindings} from './HIRBuilder';
50
+import {BuiltInArrayId} from './ObjectShape';
51
52
/*
53
* *******************************************************************************************
@@ -72,14 +72,14 @@ export function lower(
72
bindings: Bindings | null = null,
73
capturedRefs: Array<t.Identifier> = [],
74
// the outermost function being compiled, in case lower() is called recursively (for lambdas)
75
- parent: NodePath<t.Function> | null = null
75
+ parent: NodePath<t.Function> | null = null,
76
): Result<HIRFunction, CompilerError> {
77
const builder = new HIRBuilder(env, parent ?? func, bindings, capturedRefs);
78
const context: Array<Place> = [];
79
80
for (const ref of capturedRefs ?? []) {
81
context.push({
82
- kind: "Identifier",
82
+ kind: 'Identifier',
83
identifier: builder.resolveBinding(ref),
84
effect: Effect.Unknown,
85
reactive: false,
@@ -91,16 +91,16 @@ export function lower(
91
if (func.isFunctionDeclaration() || func.isFunctionExpression()) {
92
const idNode = (
93
func as NodePath<t.FunctionDeclaration | t.FunctionExpression>
94
- ).get("id");
94
+ ).get('id');
95
if (hasNode(idNode)) {
96
id = idNode.node.name;
97
}
98
}
99
const params: Array<Place | SpreadPattern> = [];
100
- func.get("params").forEach((param) => {
100
+ func.get('params').forEach(param => {
101
if (param.isIdentifier()) {
102
const binding = builder.resolveIdentifier(param);
103
- if (binding.kind !== "Identifier") {
103
+ if (binding.kind !== 'Identifier') {
104
builder.errors.push({
105
reason: `(BuildHIR::lower) Could not find binding for param \`${param.node.name}\``,
106
severity: ErrorSeverity.Invariant,
@@ -110,7 +110,7 @@ export function lower(
110
return;
111
}
112
const place: Place = {
113
- kind: "Identifier",
113
+ kind: 'Identifier',
114
identifier: binding.identifier,
115
effect: Effect.Unknown,
116
reactive: false,
@@ -123,7 +123,7 @@ export function lower(
123
param.isAssignmentPattern()
124
) {
125
const place: Place = {
126
- kind: "Identifier",
126
+ kind: 'Identifier',
127
identifier: builder.makeTemporary(param.node.loc ?? GeneratedSource),
128
effect: Effect.Unknown,
129
reactive: false,
@@ -137,27 +137,27 @@ export function lower(
137
InstructionKind.Let,
138
param,
139
place,
140
- "Assignment"
140
+ 'Assignment',
141
);
142
} else if (param.isRestElement()) {
143
const place: Place = {
144
- kind: "Identifier",
144
+ kind: 'Identifier',
145
identifier: builder.makeTemporary(param.node.loc ?? GeneratedSource),
146
effect: Effect.Unknown,
147
reactive: false,
148
loc: param.node.loc ?? GeneratedSource,
149
};
150
params.push({
151
- kind: "Spread",
151
+ kind: 'Spread',
152
place,
153
});
154
lowerAssignment(
155
builder,
156
param.node.loc ?? GeneratedSource,
157
InstructionKind.Let,
158
- param.get("argument"),
158
+ param.get('argument'),
159
place,
160
- "Assignment"
160
+ 'Assignment',
161
);
162
} else {
163
builder.errors.push({
@@ -170,11 +170,11 @@ export function lower(
170
});
171
172
let directives: Array<string> = [];
173
- const body = func.get("body");
173
+ const body = func.get('body');
174
if (body.isExpression()) {
175
- const fallthrough = builder.reserve("block");
175
+ const fallthrough = builder.reserve('block');
176
const terminal: ReturnTerminal = {
177
- kind: "return",
177
+ kind: 'return',
178
loc: GeneratedSource,
179
value: lowerExpressionToTemporary(builder, body),
180
id: makeInstructionId(0),
@@ -182,7 +182,7 @@ export function lower(
182
builder.terminateWithContinuation(terminal, fallthrough);
183
} else if (body.isBlockStatement()) {
184
lowerStatement(builder, body);
185
- directives = body.get("directives").map((d) => d.node.value.value);
185
+ directives = body.get('directives').map(d => d.node.value.value);
186
} else {
187
builder.errors.push({
188
severity: ErrorSeverity.InvalidJS,
@@ -199,22 +199,22 @@ export function lower(
199
200
builder.terminate(
201
{
202
- kind: "return",
202
+ kind: 'return',
203
loc: GeneratedSource,
204
value: lowerValueToTemporary(builder, {
205
- kind: "Primitive",
205
+ kind: 'Primitive',
206
value: undefined,
207
loc: GeneratedSource,
208
}),
209
id: makeInstructionId(0),
210
},
211
- null
211
+ null,
212
);
213
214
return Ok({
215
id,
216
params,
217
- fnType: parent == null ? env.fnType : "Other",
217
+ fnType: parent == null ? env.fnType : 'Other',
218
returnType: null, // TODO: extract the actual return type node if present
219
body: builder.build(),
220
context,
@@ -231,13 +231,13 @@ export function lower(
231
function lowerStatement(
232
builder: HIRBuilder,
233
stmtPath: NodePath<t.Statement>,
234
- label: string | null = null
234
+ label: string | null = null,
235
): void {
236
const stmtNode = stmtPath.node;
237
switch (stmtNode.type) {
238
- case "ThrowStatement": {
238
+ case 'ThrowStatement': {
239
const stmt = stmtPath as NodePath<t.ThrowStatement>;
240
- const value = lowerExpressionToTemporary(builder, stmt.get("argument"));
240
+ const value = lowerExpressionToTemporary(builder, stmt.get('argument'));
241
const handler = builder.resolveThrowHandler();
242
if (handler != null) {
243
/*
@@ -247,56 +247,56 @@ function lowerStatement(
247
*/
248
builder.errors.push({
249
reason:
250
- "(BuildHIR::lowerStatement) Support ThrowStatement inside of try/catch",
250
+ '(BuildHIR::lowerStatement) Support ThrowStatement inside of try/catch',
251
severity: ErrorSeverity.Todo,
252
loc: stmt.node.loc ?? null,
253
suggestions: null,
254
});
255
}
256
const terminal: ThrowTerminal = {
257
- kind: "throw",
257
+ kind: 'throw',
258
value,
259
id: makeInstructionId(0),
260
loc: stmt.node.loc ?? GeneratedSource,
261
};
262
- builder.terminate(terminal, "block");
262
+ builder.terminate(terminal, 'block');
263
return;
264
}
265
- case "ReturnStatement": {
265
+ case 'ReturnStatement': {
266
const stmt = stmtPath as NodePath<t.ReturnStatement>;
267
- const argument = stmt.get("argument");
267
+ const argument = stmt.get('argument');
268
let value;
269
if (argument.node === null) {
270
value = lowerValueToTemporary(builder, {
271
- kind: "Primitive",
271
+ kind: 'Primitive',
272
value: undefined,
273
loc: GeneratedSource,
274
});
275
} else {
276
value = lowerExpressionToTemporary(
277
builder,
278
- argument as NodePath<t.Expression>
278
+ argument as NodePath<t.Expression>,
279
);
280
}
281
const terminal: ReturnTerminal = {
282
- kind: "return",
282
+ kind: 'return',
283
loc: stmt.node.loc ?? GeneratedSource,
284
value,
285
id: makeInstructionId(0),
286
};
287
- builder.terminate(terminal, "block");
287
+ builder.terminate(terminal, 'block');
288
return;
289
}
290
- case "IfStatement": {
290
+ case 'IfStatement': {
291
const stmt = stmtPath as NodePath<t.IfStatement>;
292
// Block for code following the if
293
- const continuationBlock = builder.reserve("block");
293
+ const continuationBlock = builder.reserve('block');
294
// Block for the consequent (if the test is truthy)
295
- const consequentBlock = builder.enter("block", (_blockId) => {
296
- const consequent = stmt.get("consequent");
295
+ const consequentBlock = builder.enter('block', _blockId => {
296
+ const consequent = stmt.get('consequent');
297
lowerStatement(builder, consequent);
298
return {
299
- kind: "goto",
299
+ kind: 'goto',
300
block: continuationBlock.id,
301
variant: GotoVariant.Break,
302
id: makeInstructionId(0),
@@ -305,12 +305,12 @@ function lowerStatement(
305
});
306
// Block for the alternate (if the test is not truthy)
307
let alternateBlock: BlockId;
308
- const alternate = stmt.get("alternate");
308
+ const alternate = stmt.get('alternate');
309
if (hasNode(alternate)) {
310
- alternateBlock = builder.enter("block", (_blockId) => {
310
+ alternateBlock = builder.enter('block', _blockId => {
311
lowerStatement(builder, alternate);
312
return {
313
- kind: "goto",
313
+ kind: 'goto',
314
block: continuationBlock.id,
315
variant: GotoVariant.Break,
316
id: makeInstructionId(0),
@@ -321,9 +321,9 @@ function lowerStatement(
321
// If there is no else clause, use the continuation directly
322
alternateBlock = continuationBlock.id;
323
}
324
- const test = lowerExpressionToTemporary(builder, stmt.get("test"));
324
+ const test = lowerExpressionToTemporary(builder, stmt.get('test'));
325
const terminal: IfTerminal = {
326
- kind: "if",
326
+ kind: 'if',
327
test,
328
consequent: consequentBlock,
329
alternate: alternateBlock,
@@ -334,9 +334,9 @@ function lowerStatement(
334
builder.terminateWithContinuation(terminal, continuationBlock);
335
return;
336
}
337
- case "BlockStatement": {
337
+ case 'BlockStatement': {
338
const stmt = stmtPath as NodePath<t.BlockStatement>;
339
- const statements = stmt.get("body");
339
+ const statements = stmt.get('body');
340
/**
341
* Hoistable identifier bindings defined for this precise block
342
* scope (excluding bindings from parent or child block scopes).
@@ -345,7 +345,7 @@ function lowerStatement(
345
346
for (const [, binding] of Object.entries(stmt.scope.bindings)) {
347
// refs to params are always valid / never need to be hoisted
348
- if (binding.kind !== "param") {
348
+ if (binding.kind !== 'param') {
349
hoistableIdentifiers.add(binding.identifier);
350
}
351
}
@@ -375,7 +375,7 @@ function lowerStatement(
375
if (
376
!id2.isReferencedIdentifier() &&
377
// isReferencedIdentifier is broken and returns false for reassignments
378
- id.parent.type !== "AssignmentExpression"
378
+ id.parent.type !== 'AssignmentExpression'
379
) {
380
return;
381
}
@@ -389,7 +389,7 @@ function lowerStatement(
389
if (
390
binding != null &&
391
hoistableIdentifiers.has(binding.identifier) &&
392
- (fnDepth > 0 || binding.kind === "hoisted")
392
+ (fnDepth > 0 || binding.kind === 'hoisted')
393
) {
394
willHoist.add(id);
395
}
@@ -410,7 +410,7 @@ function lowerStatement(
410
for (const id of willHoist) {
411
const binding = stmt.scope.getBinding(id.node.name);
412
CompilerError.invariant(binding != null, {
413
- reason: "Expected to find binding for hoisted identifier",
413
+ reason: 'Expected to find binding for hoisted identifier',
414
description: `Could not find a binding for ${id.node.name}`,
415
suggestions: null,
416
loc: id.node.loc ?? GeneratedSource,
@@ -422,28 +422,28 @@ function lowerStatement(
422
if (!binding.path.isVariableDeclarator()) {
423
builder.errors.push({
424
severity: ErrorSeverity.Todo,
425
- reason: "Unsupported declaration type for hoisting",
425
+ reason: 'Unsupported declaration type for hoisting',
426
description: `variable "${binding.identifier.name}" declared with ${binding.path.type}`,
427
suggestions: null,
428
loc: id.parentPath.node.loc ?? GeneratedSource,
429
});
430
continue;
431
- } else if (!binding.path.get("id").isIdentifier()) {
431
+ } else if (!binding.path.get('id').isIdentifier()) {
432
builder.errors.push({
433
severity: ErrorSeverity.Todo,
434
- reason: "Unsupported variable declaration type for hoisting",
434
+ reason: 'Unsupported variable declaration type for hoisting',
435
description: `variable "${
436
binding.identifier.name
437
- }" declared with ${binding.path.get("id").type}`,
437
+ }" declared with ${binding.path.get('id').type}`,
438
suggestions: null,
439
loc: id.parentPath.node.loc ?? GeneratedSource,
440
});
441
continue;
442
- } else if (binding.kind !== "const" && binding.kind !== "var") {
442
+ } else if (binding.kind !== 'const' && binding.kind !== 'var') {
443
// Avoid double errors on var declarations, which we do not plan to support anyways
444
builder.errors.push({
445
severity: ErrorSeverity.Todo,
446
- reason: "Handle non-const declarations for hoisting",
446
+ reason: 'Handle non-const declarations for hoisting',
447
description: `variable "${binding.identifier.name}" declared with ${binding.kind}`,
448
suggestions: null,
449
loc: id.parentPath.node.loc ?? GeneratedSource,
@@ -451,20 +451,20 @@ function lowerStatement(
451
continue;
452
}
453
const identifier = builder.resolveIdentifier(id);
454
- CompilerError.invariant(identifier.kind === "Identifier", {
454
+ CompilerError.invariant(identifier.kind === 'Identifier', {
455
reason:
456
- "Expected hoisted binding to be a local identifier, not a global",
456
+ 'Expected hoisted binding to be a local identifier, not a global',
457
loc: id.node.loc ?? GeneratedSource,
458
});
459
const place: Place = {
460
effect: Effect.Unknown,
461
identifier: identifier.identifier,
462
- kind: "Identifier",
462
+ kind: 'Identifier',
463
reactive: false,
464
loc: id.node.loc ?? GeneratedSource,
465
};
466
lowerValueToTemporary(builder, {
467
- kind: "DeclareContext",
467
+ kind: 'DeclareContext',
468
lvalue: {
469
kind: InstructionKind.HoistedConst,
470
place,
@@ -478,62 +478,62 @@ function lowerStatement(
478
479
return;
480
}
481
- case "BreakStatement": {
481
+ case 'BreakStatement': {
482
const stmt = stmtPath as NodePath<t.BreakStatement>;
483
const block = builder.lookupBreak(stmt.node.label?.name ?? null);
484
builder.terminate(
485
{
486
- kind: "goto",
486
+ kind: 'goto',
487
block,
488
variant: GotoVariant.Break,
489
id: makeInstructionId(0),
490
loc: stmt.node.loc ?? GeneratedSource,
491
},
492
- "block"
492
+ 'block',
493
);
494
return;
495
}
496
- case "ContinueStatement": {
496
+ case 'ContinueStatement': {
497
const stmt = stmtPath as NodePath<t.ContinueStatement>;
498
const block = builder.lookupContinue(stmt.node.label?.name ?? null);
499
builder.terminate(
500
{
501
- kind: "goto",
501
+ kind: 'goto',
502
block,
503
variant: GotoVariant.Continue,
504
id: makeInstructionId(0),
505
loc: stmt.node.loc ?? GeneratedSource,
506
},
507
- "block"
507
+ 'block',
508
);
509
return;
510
}
511
- case "ForStatement": {
511
+ case 'ForStatement': {
512
const stmt = stmtPath as NodePath<t.ForStatement>;
513
514
- const testBlock = builder.reserve("loop");
514
+ const testBlock = builder.reserve('loop');
515
// Block for code following the loop
516
- const continuationBlock = builder.reserve("block");
516
+ const continuationBlock = builder.reserve('block');
517
518
- const initBlock = builder.enter("loop", (_blockId) => {
519
- const init = stmt.get("init");
518
+ const initBlock = builder.enter('loop', _blockId => {
519
+ const init = stmt.get('init');
520
if (!init.isVariableDeclaration()) {
521
builder.errors.push({
522
reason:
523
- "(BuildHIR::lowerStatement) Handle non-variable initialization in ForStatement",
523
+ '(BuildHIR::lowerStatement) Handle non-variable initialization in ForStatement',
524
severity: ErrorSeverity.Todo,
525
loc: stmt.node.loc ?? null,
526
suggestions: null,
527
});
528
return {
529
- kind: "unsupported",
529
+ kind: 'unsupported',
530
id: makeInstructionId(0),
531
loc: init.node?.loc ?? GeneratedSource,
532
};
533
}
534
lowerStatement(builder, init);
535
return {
536
- kind: "goto",
536
+ kind: 'goto',
537
block: testBlock.id,
538
variant: GotoVariant.Break,
539
id: makeInstructionId(0),
@@ -542,12 +542,12 @@ function lowerStatement(
542
});
543
544
let updateBlock: BlockId | null = null;
545
- const update = stmt.get("update");
545
+ const update = stmt.get('update');
546
if (hasNode(update)) {
547
- updateBlock = builder.enter("loop", (_blockId) => {
547
+ updateBlock = builder.enter('loop', _blockId => {
548
lowerExpressionToTemporary(builder, update);
549
return {
550
- kind: "goto",
550
+ kind: 'goto',
551
block: testBlock.id,
552
variant: GotoVariant.Break,
553
id: makeInstructionId(0),
@@ -556,28 +556,28 @@ function lowerStatement(
556
});
557
}
558
559
- const bodyBlock = builder.enter("block", (_blockId) => {
559
+ const bodyBlock = builder.enter('block', _blockId => {
560
return builder.loop(
561
label,
562
updateBlock ?? testBlock.id,
563
continuationBlock.id,
564
() => {
565
- const body = stmt.get("body");
565
+ const body = stmt.get('body');
566
lowerStatement(builder, body);
567
return {
568
- kind: "goto",
568
+ kind: 'goto',
569
block: updateBlock ?? testBlock.id,
570
variant: GotoVariant.Continue,
571
id: makeInstructionId(0),
572
loc: body.node.loc ?? GeneratedSource,
573
};
574
- }
574
+ },
575
);
576
});
577
578
builder.terminateWithContinuation(
579
{
580
- kind: "for",
580
+ kind: 'for',
581
loc: stmtNode.loc ?? GeneratedSource,
582
init: initBlock,
583
test: testBlock.id,
@@ -586,10 +586,10 @@ function lowerStatement(
586
fallthrough: continuationBlock.id,
587
id: makeInstructionId(0),
588
},
589
- testBlock
589
+ testBlock,
590
);
591
592
- const test = stmt.get("test");
592
+ const test = stmt.get('test');
593
if (test.node == null) {
594
builder.errors.push({
595
reason: `(BuildHIR::lowerStatement) Handle empty test in ForStatement`,
@@ -600,44 +600,44 @@ function lowerStatement(
600
} else {
601
builder.terminateWithContinuation(
602
{
603
- kind: "branch",
603
+ kind: 'branch',
604
test: lowerExpressionToTemporary(
605
builder,
606
- test as NodePath<t.Expression>
606
+ test as NodePath<t.Expression>,
607
),
608
consequent: bodyBlock,
609
alternate: continuationBlock.id,
610
id: makeInstructionId(0),
611
loc: stmt.node.loc ?? GeneratedSource,
612
},
613
- continuationBlock
613
+ continuationBlock,
614
);
615
}
616
return;
617
}
618
- case "WhileStatement": {
618
+ case 'WhileStatement': {
619
const stmt = stmtPath as NodePath<t.WhileStatement>;
620
// Block used to evaluate whether to (re)enter or exit the loop
621
- const conditionalBlock = builder.reserve("loop");
621
+ const conditionalBlock = builder.reserve('loop');
622
// Block for code following the loop
623
- const continuationBlock = builder.reserve("block");
623
+ const continuationBlock = builder.reserve('block');
624
// Loop body
625
- const loopBlock = builder.enter("block", (_blockId) => {
625
+ const loopBlock = builder.enter('block', _blockId => {
626
return builder.loop(
627
label,
628
conditionalBlock.id,
629
continuationBlock.id,
630
() => {
631
- const body = stmt.get("body");
631
+ const body = stmt.get('body');
632
lowerStatement(builder, body);
633
return {
634
- kind: "goto",
634
+ kind: 'goto',
635
block: conditionalBlock.id,
636
variant: GotoVariant.Continue,
637
id: makeInstructionId(0),
638
loc: body.node.loc ?? GeneratedSource,
639
};
640
- }
640
+ },
641
);
642
});
643
/*
@@ -647,22 +647,22 @@ function lowerStatement(
647
const loc = stmt.node.loc ?? GeneratedSource;
648
builder.terminateWithContinuation(
649
{
650
- kind: "while",
650
+ kind: 'while',
651
loc,
652
test: conditionalBlock.id,
653
loop: loopBlock,
654
fallthrough: continuationBlock.id,
655
id: makeInstructionId(0),
656
},
657
- conditionalBlock
657
+ conditionalBlock,
658
);
659
/*
660
* The conditional block is empty and exists solely as conditional for
661
* (re)entering or exiting the loop
662
*/
663
- const test = lowerExpressionToTemporary(builder, stmt.get("test"));
663
+ const test = lowerExpressionToTemporary(builder, stmt.get('test'));
664
const terminal: BranchTerminal = {
665
- kind: "branch",
665
+ kind: 'branch',
666
test,
667
consequent: loopBlock,
668
alternate: continuationBlock.id,
@@ -673,21 +673,21 @@ function lowerStatement(
673
builder.terminateWithContinuation(terminal, continuationBlock);
674
return;
675
}
676
- case "LabeledStatement": {
676
+ case 'LabeledStatement': {
677
const stmt = stmtPath as NodePath<t.LabeledStatement>;
678
const label = stmt.node.label.name;
679
- const body = stmt.get("body");
679
+ const body = stmt.get('body');
680
switch (body.node.type) {
681
- case "ForInStatement":
682
- case "ForOfStatement":
683
- case "ForStatement":
684
- case "WhileStatement":
685
- case "DoWhileStatement": {
681
+ case 'ForInStatement':
682
+ case 'ForOfStatement':
683
+ case 'ForStatement':
684
+ case 'WhileStatement':
685
+ case 'DoWhileStatement': {
686
/*
687
* labeled loops are special because of continue, so push the label
688
* down
689
*/
690
- lowerStatement(builder, stmt.get("body"), label);
690
+ lowerStatement(builder, stmt.get('body'), label);
691
break;
692
}
693
default: {
@@ -695,14 +695,14 @@ function lowerStatement(
695
* All other statements create a continuation block to allow `break`,
696
* explicitly *don't* pass the label down
697
*/
698
- const continuationBlock = builder.reserve("block");
699
- const block = builder.enter("block", () => {
700
- const body = stmt.get("body");
698
+ const continuationBlock = builder.reserve('block');
699
+ const block = builder.enter('block', () => {
700
+ const body = stmt.get('body');
701
builder.label(label, continuationBlock.id, () => {
702
lowerStatement(builder, body);
703
});
704
return {
705
- kind: "goto",
705
+ kind: 'goto',
706
block: continuationBlock.id,
707
variant: GotoVariant.Break,
708
id: makeInstructionId(0),
@@ -711,22 +711,22 @@ function lowerStatement(
711
});
712
builder.terminateWithContinuation(
713
{
714
- kind: "label",
714
+ kind: 'label',
715
block,
716
fallthrough: continuationBlock.id,
717
id: makeInstructionId(0),
718
loc: stmt.node.loc ?? GeneratedSource,
719
},
720
- continuationBlock
720
+ continuationBlock,
721
);
722
}
723
}
724
return;
725
}
726
- case "SwitchStatement": {
726
+ case 'SwitchStatement': {
727
const stmt = stmtPath as NodePath<t.SwitchStatement>;
728
// Block following the switch
729
- const continuationBlock = builder.reserve("block");
729
+ const continuationBlock = builder.reserve('block');
730
/*
731
* The goto target for any cases that fallthrough, which initially starts
732
* as the continuation block and is then updated as we iterate through cases
@@ -739,9 +739,9 @@ function lowerStatement(
739
*/
740
const cases: Array<Case> = [];
741
let hasDefault = false;
742
- for (let ii = stmt.get("cases").length - 1; ii >= 0; ii--) {
743
- const case_: NodePath<t.SwitchCase> = stmt.get("cases")[ii];
744
- const testExpr = case_.get("test");
742
+ for (let ii = stmt.get('cases').length - 1; ii >= 0; ii--) {
743
+ const case_: NodePath<t.SwitchCase> = stmt.get('cases')[ii];
744
+ const testExpr = case_.get('test');
745
if (testExpr.node == null) {
746
if (hasDefault) {
747
builder.errors.push({
@@ -754,17 +754,17 @@ function lowerStatement(
754
}
755
hasDefault = true;
756
}
757
- const block = builder.enter("block", (_blockId) => {
757
+ const block = builder.enter('block', _blockId => {
758
return builder.switch(label, continuationBlock.id, () => {
759
case_
760
- .get("consequent")
761
- .forEach((consequent) => lowerStatement(builder, consequent));
760
+ .get('consequent')
761
+ .forEach(consequent => lowerStatement(builder, consequent));
762
/*
763
* always generate a fallthrough to the next block, this may be dead code
764
* if there was an explicit break, but if so it will be pruned later.
765
*/
766
return {
767
- kind: "goto",
767
+ kind: 'goto',
768
block: fallthrough,
769
variant: GotoVariant.Break,
770
id: makeInstructionId(0),
@@ -792,30 +792,30 @@ function lowerStatement(
792
* could bypass any of the other cases and jump directly to the continuation.
793
*/
794
if (!hasDefault) {
795
- cases.push({ test: null, block: continuationBlock.id });
795
+ cases.push({test: null, block: continuationBlock.id});
796
}
797
798
const test = lowerExpressionToTemporary(
799
builder,
800
- stmt.get("discriminant")
800
+ stmt.get('discriminant'),
801
);
802
builder.terminateWithContinuation(
803
{
804
- kind: "switch",
804
+ kind: 'switch',
805
test,
806
cases,
807
fallthrough: continuationBlock.id,
808
id: makeInstructionId(0),
809
loc: stmt.node.loc ?? GeneratedSource,
810
},
811
- continuationBlock
811
+ continuationBlock,
812
);
813
return;
814
}
815
- case "VariableDeclaration": {
815
+ case 'VariableDeclaration': {
816
const stmt = stmtPath as NodePath<t.VariableDeclaration>;
817
- const nodeKind: t.VariableDeclaration["kind"] = stmt.node.kind;
818
- if (nodeKind === "var") {
817
+ const nodeKind: t.VariableDeclaration['kind'] = stmt.node.kind;
818
+ if (nodeKind === 'var') {
819
builder.errors.push({
820
reason: `(BuildHIR::lowerStatement) Handle ${nodeKind} kinds in VariableDeclaration`,
821
severity: ErrorSeverity.Todo,
@@ -825,10 +825,10 @@ function lowerStatement(
825
return;
826
}
827
const kind =
828
- nodeKind === "let" ? InstructionKind.Let : InstructionKind.Const;
829
- for (const declaration of stmt.get("declarations")) {
830
- const id = declaration.get("id");
831
- const init = declaration.get("init");
828
+ nodeKind === 'let' ? InstructionKind.Let : InstructionKind.Const;
829
+ for (const declaration of stmt.get('declarations')) {
830
+ const id = declaration.get('id');
831
+ const init = declaration.get('init');
832
if (hasNode(init)) {
833
const value = lowerExpressionToTemporary(builder, init);
834
lowerAssignment(
@@ -838,12 +838,12 @@ function lowerStatement(
838
id,
839
value,
840
id.isObjectPattern() || id.isArrayPattern()
841
- ? "Destructure"
842
- : "Assignment"
841
+ ? 'Destructure'
842
+ : 'Assignment',
843
);
844
} else if (id.isIdentifier()) {
845
const binding = builder.resolveIdentifier(id);
846
- if (binding.kind !== "Identifier") {
846
+ if (binding.kind !== 'Identifier') {
847
builder.errors.push({
848
reason: `(BuildHIR::lowerAssignment) Could not find binding for declaration.`,
849
severity: ErrorSeverity.Invariant,
@@ -854,7 +854,7 @@ function lowerStatement(
854
const place: Place = {
855
effect: Effect.Unknown,
856
identifier: binding.identifier,
857
- kind: "Identifier",
857
+ kind: 'Identifier',
858
reactive: false,
859
loc: id.node.loc ?? GeneratedSource,
860
};
@@ -867,16 +867,16 @@ function lowerStatement(
867
loc: id.node.loc ?? null,
868
suggestions: [
869
{
870
- description: "Change to a `let` declaration",
870
+ description: 'Change to a `let` declaration',
871
op: CompilerSuggestionOperation.Replace,
872
range: [declRangeStart, declRangeStart + 5], // "const".length
873
- text: "let",
873
+ text: 'let',
874
},
875
],
876
});
877
}
878
lowerValueToTemporary(builder, {
879
- kind: "DeclareContext",
879
+ kind: 'DeclareContext',
880
lvalue: {
881
kind: InstructionKind.Let,
882
place,
@@ -884,19 +884,19 @@ function lowerStatement(
884
loc: id.node.loc ?? GeneratedSource,
885
});
886
} else {
887
- const typeAnnotation = id.get("typeAnnotation");
887
+ const typeAnnotation = id.get('typeAnnotation');
888
let type: t.FlowType | t.TSType | null;
889
if (typeAnnotation.isTSTypeAnnotation()) {
890
- const typePath = typeAnnotation.get("typeAnnotation");
890
+ const typePath = typeAnnotation.get('typeAnnotation');
891
type = typePath.node;
892
} else if (typeAnnotation.isTypeAnnotation()) {
893
- const typePath = typeAnnotation.get("typeAnnotation");
893
+ const typePath = typeAnnotation.get('typeAnnotation');
894
type = typePath.node;
895
} else {
896
type = null;
897
}
898
lowerValueToTemporary(builder, {
899
- kind: "DeclareLocal",
899
+ kind: 'DeclareLocal',
900
lvalue: {
901
kind,
902
place,
@@ -918,35 +918,35 @@ function lowerStatement(
918
}
919
return;
920
}
921
- case "ExpressionStatement": {
921
+ case 'ExpressionStatement': {
922
const stmt = stmtPath as NodePath<t.ExpressionStatement>;
923
- const expression = stmt.get("expression");
923
+ const expression = stmt.get('expression');
924
lowerExpressionToTemporary(builder, expression);
925
return;
926
}
927
- case "DoWhileStatement": {
927
+ case 'DoWhileStatement': {
928
const stmt = stmtPath as NodePath<t.DoWhileStatement>;
929
// Block used to evaluate whether to (re)enter or exit the loop
930
- const conditionalBlock = builder.reserve("loop");
930
+ const conditionalBlock = builder.reserve('loop');
931
// Block for code following the loop
932
- const continuationBlock = builder.reserve("block");
932
+ const continuationBlock = builder.reserve('block');
933
// Loop body, executed at least once uncondtionally prior to exit
934
- const loopBlock = builder.enter("block", (_loopBlockId) => {
934
+ const loopBlock = builder.enter('block', _loopBlockId => {
935
return builder.loop(
936
label,
937
conditionalBlock.id,
938
continuationBlock.id,
939
() => {
940
- const body = stmt.get("body");
940
+ const body = stmt.get('body');
941
lowerStatement(builder, body);
942
return {
943
- kind: "goto",
943
+ kind: 'goto',
944
block: conditionalBlock.id,
945
variant: GotoVariant.Continue,
946
id: makeInstructionId(0),
947
loc: body.node.loc ?? GeneratedSource,
948
};
949
- }
949
+ },
950
);
951
});
952
/*
@@ -956,22 +956,22 @@ function lowerStatement(
956
const loc = stmt.node.loc ?? GeneratedSource;
957
builder.terminateWithContinuation(
958
{
959
- kind: "do-while",
959
+ kind: 'do-while',
960
loc,
961
test: conditionalBlock.id,
962
loop: loopBlock,
963
fallthrough: continuationBlock.id,
964
id: makeInstructionId(0),
965
},
966
- conditionalBlock
966
+ conditionalBlock,
967
);
968
/*
969
* The conditional block is empty and exists solely as conditional for
970
* (re)entering or exiting the loop
971
*/
972
- const test = lowerExpressionToTemporary(builder, stmt.get("test"));
972
+ const test = lowerExpressionToTemporary(builder, stmt.get('test'));
973
const terminal: BranchTerminal = {
974
- kind: "branch",
974
+ kind: 'branch',
975
test,
976
consequent: loopBlock,
977
alternate: continuationBlock.id,
@@ -982,20 +982,20 @@ function lowerStatement(
982
builder.terminateWithContinuation(terminal, continuationBlock);
983
return;
984
}
985
- case "FunctionDeclaration": {
985
+ case 'FunctionDeclaration': {
986
const stmt = stmtPath as NodePath<t.FunctionDeclaration>;
987
stmt.skip();
988
- CompilerError.invariant(stmt.get("id").type === "Identifier", {
989
- reason: "function declarations must have a name",
988
+ CompilerError.invariant(stmt.get('id').type === 'Identifier', {
989
+ reason: 'function declarations must have a name',
990
description: null,
991
loc: stmt.node.loc ?? null,
992
suggestions: null,
993
});
994
- const id = stmt.get("id") as NodePath<t.Identifier>;
994
+ const id = stmt.get('id') as NodePath<t.Identifier>;
995
996
const fn = lowerValueToTemporary(
997
builder,
998
- lowerFunctionToValue(builder, stmt)
998
+ lowerFunctionToValue(builder, stmt),
999
);
1000
lowerAssignment(
1001
builder,
@@ -1003,16 +1003,16 @@ function lowerStatement(
1003
InstructionKind.Let,
1004
id,
1005
fn,
1006
- "Assignment"
1006
+ 'Assignment',
1007
);
1008
1009
return;
1010
}
1011
- case "ForOfStatement": {
1011
+ case 'ForOfStatement': {
1012
const stmt = stmtPath as NodePath<t.ForOfStatement>;
1013
- const continuationBlock = builder.reserve("block");
1014
- const initBlock = builder.reserve("loop");
1015
- const testBlock = builder.reserve("loop");
1013
+ const continuationBlock = builder.reserve('block');
1014
+ const initBlock = builder.reserve('loop');
1015
+ const testBlock = builder.reserve('loop');
1016
1017
if (stmt.node.await) {
1018
builder.errors.push({
@@ -1024,12 +1024,12 @@ function lowerStatement(
1024
return;
1025
}
1026
1027
- const loopBlock = builder.enter("block", (_blockId) => {
1027
+ const loopBlock = builder.enter('block', _blockId => {
1028
return builder.loop(label, initBlock.id, continuationBlock.id, () => {
1029
- const body = stmt.get("body");
1029
+ const body = stmt.get('body');
1030
lowerStatement(builder, body);
1031
return {
1032
- kind: "goto",
1032
+ kind: 'goto',
1033
block: initBlock.id,
1034
variant: GotoVariant.Continue,
1035
id: makeInstructionId(0),
@@ -1039,10 +1039,10 @@ function lowerStatement(
1039
});
1040
1041
const loc = stmt.node.loc ?? GeneratedSource;
1042
- const value = lowerExpressionToTemporary(builder, stmt.get("right"));
1042
+ const value = lowerExpressionToTemporary(builder, stmt.get('right'));
1043
builder.terminateWithContinuation(
1044
{
1045
- kind: "for-of",
1045
+ kind: 'for-of',
1046
loc,
1047
init: initBlock.id,
1048
test: testBlock.id,
@@ -1050,7 +1050,7 @@ function lowerStatement(
1050
fallthrough: continuationBlock.id,
1051
id: makeInstructionId(0),
1052
},
1053
- initBlock
1053
+ initBlock,
1054
);
1055
1056
/*
@@ -1059,38 +1059,38 @@ function lowerStatement(
1059
* instructions when we handle other syntax like Patterns)
1060
*/
1061
const iterator = lowerValueToTemporary(builder, {
1062
- kind: "GetIterator",
1062
+ kind: 'GetIterator',
1063
loc: value.loc,
1064
- collection: { ...value },
1064
+ collection: {...value},
1065
});
1066
builder.terminateWithContinuation(
1067
{
1068
id: makeInstructionId(0),
1069
- kind: "goto",
1069
+ kind: 'goto',
1070
block: testBlock.id,
1071
variant: GotoVariant.Break,
1072
loc: stmt.node.loc ?? GeneratedSource,
1073
},
1074
- testBlock
1074
+ testBlock,
1075
);
1076
1077
- const left = stmt.get("left");
1077
+ const left = stmt.get('left');
1078
const leftLoc = left.node.loc ?? GeneratedSource;
1079
let test: Place;
1080
if (left.isVariableDeclaration()) {
1081
- const declarations = left.get("declarations");
1081
+ const declarations = left.get('declarations');
1082
CompilerError.invariant(declarations.length === 1, {
1083
reason: `Expected only one declaration in the init of a ForOfStatement, got ${declarations.length}`,
1084
description: null,
1085
loc: left.node.loc ?? null,
1086
suggestions: null,
1087
});
1088
- const id = declarations[0].get("id");
1088
+ const id = declarations[0].get('id');
1089
const advanceIterator = lowerValueToTemporary(builder, {
1090
- kind: "IteratorNext",
1090
+ kind: 'IteratorNext',
1091
loc: leftLoc,
1092
- iterator: { ...iterator },
1093
- collection: { ...value },
1092
+ iterator: {...iterator},
1093
+ collection: {...value},
1094
});
1095
const assign = lowerAssignment(
1096
builder,
@@ -1098,7 +1098,7 @@ function lowerStatement(
1098
InstructionKind.Let,
1099
id,
1100
advanceIterator,
1101
- "Assignment"
1101
+ 'Assignment',
1102
);
1103
test = lowerValueToTemporary(builder, assign);
1104
} else {
@@ -1113,27 +1113,27 @@ function lowerStatement(
1113
builder.terminateWithContinuation(
1114
{
1115
id: makeInstructionId(0),
1116
- kind: "branch",
1116
+ kind: 'branch',
1117
test,
1118
consequent: loopBlock,
1119
alternate: continuationBlock.id,
1120
loc: stmt.node.loc ?? GeneratedSource,
1121
},
1122
- continuationBlock
1122
+ continuationBlock,
1123
);
1124
return;
1125
}
1126
- case "ForInStatement": {
1126
+ case 'ForInStatement': {
1127
const stmt = stmtPath as NodePath<t.ForInStatement>;
1128
- const continuationBlock = builder.reserve("block");
1129
- const initBlock = builder.reserve("loop");
1128
+ const continuationBlock = builder.reserve('block');
1129
+ const initBlock = builder.reserve('loop');
1130
1131
- const loopBlock = builder.enter("block", (_blockId) => {
1131
+ const loopBlock = builder.enter('block', _blockId => {
1132
return builder.loop(label, initBlock.id, continuationBlock.id, () => {
1133
- const body = stmt.get("body");
1133
+ const body = stmt.get('body');
1134
lowerStatement(builder, body);
1135
return {
1136
- kind: "goto",
1136
+ kind: 'goto',
1137
block: initBlock.id,
1138
variant: GotoVariant.Continue,
1139
id: makeInstructionId(0),
@@ -1143,17 +1143,17 @@ function lowerStatement(
1143
});
1144
1145
const loc = stmt.node.loc ?? GeneratedSource;
1146
- const value = lowerExpressionToTemporary(builder, stmt.get("right"));
1146
+ const value = lowerExpressionToTemporary(builder, stmt.get('right'));
1147
builder.terminateWithContinuation(
1148
{
1149
- kind: "for-in",
1149
+ kind: 'for-in',
1150
loc,
1151
init: initBlock.id,
1152
loop: loopBlock,
1153
fallthrough: continuationBlock.id,
1154
id: makeInstructionId(0),
1155
},
1156
- initBlock
1156
+ initBlock,
1157
);
1158
1159
/*
@@ -1161,20 +1161,20 @@ function lowerStatement(
1161
* right (Expression), so we synthesize a new InstrValue and assignment (potentially multiple
1162
* instructions when we handle other syntax like Patterns)
1163
*/
1164
- const left = stmt.get("left");
1164
+ const left = stmt.get('left');
1165
const leftLoc = left.node.loc ?? GeneratedSource;
1166
let test: Place;
1167
if (left.isVariableDeclaration()) {
1168
- const declarations = left.get("declarations");
1168
+ const declarations = left.get('declarations');
1169
CompilerError.invariant(declarations.length === 1, {
1170
reason: `Expected only one declaration in the init of a ForInStatement, got ${declarations.length}`,
1171
description: null,
1172
loc: left.node.loc ?? null,
1173
suggestions: null,
1174
});
1175
- const id = declarations[0].get("id");
1175
+ const id = declarations[0].get('id');
1176
const nextPropertyTemp = lowerValueToTemporary(builder, {
1177
- kind: "NextPropertyOf",
1177
+ kind: 'NextPropertyOf',
1178
loc: leftLoc,
1179
value,
1180
});
@@ -1184,7 +1184,7 @@ function lowerStatement(
1184
InstructionKind.Let,
1185
id,
1186
nextPropertyTemp,
1187
- "Assignment"
1187
+ 'Assignment',
1188
);
1189
test = lowerValueToTemporary(builder, assign);
1190
} else {
@@ -1199,38 +1199,38 @@ function lowerStatement(
1199
builder.terminateWithContinuation(
1200
{
1201
id: makeInstructionId(0),
1202
- kind: "branch",
1202
+ kind: 'branch',
1203
test,
1204
consequent: loopBlock,
1205
alternate: continuationBlock.id,
1206
loc: stmt.node.loc ?? GeneratedSource,
1207
},
1208
- continuationBlock
1208
+ continuationBlock,
1209
);
1210
return;
1211
}
1212
- case "DebuggerStatement": {
1212
+ case 'DebuggerStatement': {
1213
const stmt = stmtPath as NodePath<t.DebuggerStatement>;
1214
const loc = stmt.node.loc ?? GeneratedSource;
1215
builder.push({
1216
id: makeInstructionId(0),
1217
lvalue: buildTemporaryPlace(builder, loc),
1218
value: {
1219
- kind: "Debugger",
1219
+ kind: 'Debugger',
1220
loc,
1221
},
1222
loc,
1223
});
1224
return;
1225
}
1226
- case "EmptyStatement": {
1226
+ case 'EmptyStatement': {
1227
return;
1228
}
1229
- case "TryStatement": {
1229
+ case 'TryStatement': {
1230
const stmt = stmtPath as NodePath<t.TryStatement>;
1231
- const continuationBlock = builder.reserve("block");
1231
+ const continuationBlock = builder.reserve('block');
1232
1233
- const handlerPath = stmt.get("handler");
1233
+ const handlerPath = stmt.get('handler');
1234
if (!hasNode(handlerPath)) {
1235
builder.errors.push({
1236
reason: `(BuildHIR::lowerStatement) Handle TryStatement without a catch clause`,
@@ -1240,7 +1240,7 @@ function lowerStatement(
1240
});
1241
return;
1242
}
1243
- if (hasNode(stmt.get("finalizer"))) {
1243
+ if (hasNode(stmt.get('finalizer'))) {
1244
builder.errors.push({
1245
reason: `(BuildHIR::lowerStatement) Handle TryStatement with a finalizer ('finally') clause`,
1246
severity: ErrorSeverity.Todo,
@@ -1249,16 +1249,16 @@ function lowerStatement(
1249
});
1250
}
1251
1252
- const handlerBindingPath = handlerPath.get("param");
1252
+ const handlerBindingPath = handlerPath.get('param');
1253
let handlerBinding: {
1254
place: Place;
1255
path: NodePath<t.Identifier | t.ArrayPattern | t.ObjectPattern>;
1256
} | null = null;
1257
if (hasNode(handlerBindingPath)) {
1258
const place: Place = {
1259
- kind: "Identifier",
1259
+ kind: 'Identifier',
1260
identifier: builder.makeTemporary(
1261
- handlerBindingPath.node.loc ?? GeneratedSource
1261
+ handlerBindingPath.node.loc ?? GeneratedSource,
1262
),
1263
effect: Effect.Unknown,
1264
reactive: false,
@@ -1266,10 +1266,10 @@ function lowerStatement(
1266
};
1267
promoteTemporary(place.identifier);
1268
lowerValueToTemporary(builder, {
1269
- kind: "DeclareLocal",
1269
+ kind: 'DeclareLocal',
1270
lvalue: {
1271
kind: InstructionKind.Catch,
1272
- place: { ...place },
1272
+ place: {...place},
1273
},
1274
type: null,
1275
loc: handlerBindingPath.node.loc ?? GeneratedSource,
@@ -1281,20 +1281,20 @@ function lowerStatement(
1281
};
1282
}
1283
1284
- const handler = builder.enter("catch", (_blockId) => {
1284
+ const handler = builder.enter('catch', _blockId => {
1285
if (handlerBinding !== null) {
1286
lowerAssignment(
1287
builder,
1288
handlerBinding.path.node.loc ?? GeneratedSource,
1289
InstructionKind.Catch,
1290
handlerBinding.path,
1291
- { ...handlerBinding.place },
1292
- "Assignment"
1291
+ {...handlerBinding.place},
1292
+ 'Assignment',
1293
);
1294
}
1295
- lowerStatement(builder, handlerPath.get("body"));
1295
+ lowerStatement(builder, handlerPath.get('body'));
1296
return {
1297
- kind: "goto",
1297
+ kind: 'goto',
1298
block: continuationBlock.id,
1299
variant: GotoVariant.Break,
1300
id: makeInstructionId(0),
@@ -1302,13 +1302,13 @@ function lowerStatement(
1302
};
1303
});
1304
1305
- const block = builder.enter("block", (_blockId) => {
1306
- const block = stmt.get("block");
1305
+ const block = builder.enter('block', _blockId => {
1306
+ const block = stmt.get('block');
1307
builder.enterTryCatch(handler, () => {
1308
lowerStatement(builder, block);
1309
});
1310
return {
1311
- kind: "goto",
1311
+ kind: 'goto',
1312
block: continuationBlock.id,
1313
variant: GotoVariant.Try,
1314
id: makeInstructionId(0),
@@ -1318,51 +1318,51 @@ function lowerStatement(
1318
1319
builder.terminateWithContinuation(
1320
{
1321
- kind: "try",
1321
+ kind: 'try',
1322
block,
1323
handlerBinding:
1324
- handlerBinding !== null ? { ...handlerBinding.place } : null,
1324
+ handlerBinding !== null ? {...handlerBinding.place} : null,
1325
handler,
1326
fallthrough: continuationBlock.id,
1327
id: makeInstructionId(0),
1328
loc: stmt.node.loc ?? GeneratedSource,
1329
},
1330
- continuationBlock
1330
+ continuationBlock,
1331
);
1332
1333
return;
1334
}
1335
- case "TypeAlias":
1336
- case "TSInterfaceDeclaration":
1337
- case "TSTypeAliasDeclaration": {
1335
+ case 'TypeAlias':
1336
+ case 'TSInterfaceDeclaration':
1337
+ case 'TSTypeAliasDeclaration': {
1338
// We do not preserve type annotations/syntax through transformation
1339
return;
1340
}
1341
- case "ClassDeclaration":
1342
- case "DeclareClass":
1343
- case "DeclareExportAllDeclaration":
1344
- case "DeclareExportDeclaration":
1345
- case "DeclareFunction":
1346
- case "DeclareInterface":
1347
- case "DeclareModule":
1348
- case "DeclareModuleExports":
1349
- case "DeclareOpaqueType":
1350
- case "DeclareTypeAlias":
1351
- case "DeclareVariable":
1352
- case "EnumDeclaration":
1353
- case "ExportAllDeclaration":
1354
- case "ExportDefaultDeclaration":
1355
- case "ExportNamedDeclaration":
1356
- case "ImportDeclaration":
1357
- case "InterfaceDeclaration":
1358
- case "OpaqueType":
1359
- case "TSDeclareFunction":
1360
- case "TSEnumDeclaration":
1361
- case "TSExportAssignment":
1362
- case "TSImportEqualsDeclaration":
1363
- case "TSModuleDeclaration":
1364
- case "TSNamespaceExportDeclaration":
1365
- case "WithStatement": {
1341
+ case 'ClassDeclaration':
1342
+ case 'DeclareClass':
1343
+ case 'DeclareExportAllDeclaration':
1344
+ case 'DeclareExportDeclaration':
1345
+ case 'DeclareFunction':
1346
+ case 'DeclareInterface':
1347
+ case 'DeclareModule':
1348
+ case 'DeclareModuleExports':
1349
+ case 'DeclareOpaqueType':
1350
+ case 'DeclareTypeAlias':
1351
+ case 'DeclareVariable':
1352
+ case 'EnumDeclaration':
1353
+ case 'ExportAllDeclaration':
1354
+ case 'ExportDefaultDeclaration':
1355
+ case 'ExportNamedDeclaration':
1356
+ case 'ImportDeclaration':
1357
+ case 'InterfaceDeclaration':
1358
+ case 'OpaqueType':
1359
+ case 'TSDeclareFunction':
1360
+ case 'TSEnumDeclaration':
1361
+ case 'TSExportAssignment':
1362
+ case 'TSImportEqualsDeclaration':
1363
+ case 'TSModuleDeclaration':
1364
+ case 'TSNamespaceExportDeclaration':
1365
+ case 'WithStatement': {
1366
builder.errors.push({
1367
reason: `(BuildHIR::lowerStatement) Handle ${stmtPath.type} statements`,
1368
severity: ErrorSeverity.Todo,
@@ -1370,7 +1370,7 @@ function lowerStatement(
1370
suggestions: null,
1371
});
1372
lowerValueToTemporary(builder, {
1373
- kind: "UnsupportedNode",
1373
+ kind: 'UnsupportedNode',
1374
loc: stmtPath.node.loc ?? GeneratedSource,
1375
node: stmtPath.node,
1376
});
@@ -1381,7 +1381,7 @@ function lowerStatement(
1381
stmtNode,
1382
`Unsupported statement kind '${
1383
(stmtNode as any as NodePath<t.Statement>).type
1384
- }'`
1384
+ }'`,
1385
);
1386
}
1387
}
@@ -1389,16 +1389,16 @@ function lowerStatement(
1389
1390
function lowerObjectMethod(
1391
builder: HIRBuilder,
1392
- property: NodePath<t.ObjectMethod>
1392
+ property: NodePath<t.ObjectMethod>,
1393
): InstructionValue {
1394
const loc = property.node.loc ?? GeneratedSource;
1395
const loweredFunc = lowerFunction(builder, property);
1396
if (!loweredFunc) {
1397
- return { kind: "UnsupportedNode", node: property.node, loc: loc };
1397
+ return {kind: 'UnsupportedNode', node: property.node, loc: loc};
1398
}
1399
1400
return {
1401
- kind: "ObjectMethod",
1401
+ kind: 'ObjectMethod',
1402
loc,
1403
loweredFunc,
1404
};
@@ -1406,12 +1406,12 @@ function lowerObjectMethod(
1406
1407
function lowerObjectPropertyKey(
1408
builder: HIRBuilder,
1409
- property: NodePath<t.ObjectProperty | t.ObjectMethod>
1409
+ property: NodePath<t.ObjectProperty | t.ObjectMethod>,
1410
): ObjectPropertyKey | null {
1411
- const key = property.get("key");
1411
+ const key = property.get('key');
1412
if (key.isStringLiteral()) {
1413
return {
1414
- kind: "string",
1414
+ kind: 'string',
1415
name: key.node.value,
1416
};
1417
} else if (property.node.computed && key.isExpression()) {
@@ -1431,12 +1431,12 @@ function lowerObjectPropertyKey(
1431
}
1432
const place = lowerExpressionToTemporary(builder, key);
1433
return {
1434
- kind: "computed",
1434
+ kind: 'computed',
1435
name: place,
1436
};
1437
} else if (key.isIdentifier()) {
1438
return {
1439
- kind: "identifier",
1439
+ kind: 'identifier',
1440
name: key.node.name,
1441
};
1442
}
@@ -1452,12 +1452,12 @@ function lowerObjectPropertyKey(
1452
1453
function lowerExpression(
1454
builder: HIRBuilder,
1455
- exprPath: NodePath<t.Expression>
1455
+ exprPath: NodePath<t.Expression>,
1456
): InstructionValue {
1457
const exprNode = exprPath.node;
1458
const exprLoc = exprNode.loc ?? GeneratedSource;
1459
switch (exprNode.type) {
1460
- case "Identifier": {
1460
+ case 'Identifier': {
1461
const expr = exprPath as NodePath<t.Identifier>;
1462
const place = lowerIdentifier(builder, expr);
1463
return {
@@ -1466,29 +1466,29 @@ function lowerExpression(
1466
loc: exprLoc,
1467
};
1468
}
1469
- case "NullLiteral": {
1469
+ case 'NullLiteral': {
1470
return {
1471
- kind: "Primitive",
1471
+ kind: 'Primitive',
1472
value: null,
1473
loc: exprLoc,
1474
};
1475
}
1476
- case "BooleanLiteral":
1477
- case "NumericLiteral":
1478
- case "StringLiteral": {
1476
+ case 'BooleanLiteral':
1477
+ case 'NumericLiteral':
1478
+ case 'StringLiteral': {
1479
const expr = exprPath as NodePath<
1480
t.StringLiteral | t.BooleanLiteral | t.NumericLiteral
1481
>;
1482
const value = expr.node.value;
1483
return {
1484
- kind: "Primitive",
1484
+ kind: 'Primitive',
1485
value,
1486
loc: exprLoc,
1487
};
1488
}
1489
- case "ObjectExpression": {
1489
+ case 'ObjectExpression': {
1490
const expr = exprPath as NodePath<t.ObjectExpression>;
1491
- const propertyPaths = expr.get("properties");
1491
+ const propertyPaths = expr.get('properties');
1492
const properties: Array<ObjectProperty | SpreadPattern> = [];
1493
for (const propertyPath of propertyPaths) {
1494
if (propertyPath.isObjectProperty()) {
@@ -1496,7 +1496,7 @@ function lowerExpression(
1496
if (!loweredKey) {
1497
continue;
1498
}
1499
- const valuePath = propertyPath.get("value");
1499
+ const valuePath = propertyPath.get('value');
1500
if (!valuePath.isExpression()) {
1501
builder.errors.push({
1502
reason: `(BuildHIR::lowerExpression) Handle ${valuePath.type} values in ObjectExpression`,
@@ -1508,22 +1508,22 @@ function lowerExpression(
1508
}
1509
const value = lowerExpressionToTemporary(builder, valuePath);
1510
properties.push({
1511
- kind: "ObjectProperty",
1512
- type: "property",
1511
+ kind: 'ObjectProperty',
1512
+ type: 'property',
1513
place: value,
1514
key: loweredKey,
1515
});
1516
} else if (propertyPath.isSpreadElement()) {
1517
const place = lowerExpressionToTemporary(
1518
builder,
1519
- propertyPath.get("argument")
1519
+ propertyPath.get('argument'),
1520
);
1521
properties.push({
1522
- kind: "Spread",
1522
+ kind: 'Spread',
1523
place,
1524
});
1525
} else if (propertyPath.isObjectMethod()) {
1526
- if (propertyPath.node.kind !== "method") {
1526
+ if (propertyPath.node.kind !== 'method') {
1527
builder.errors.push({
1528
reason: `(BuildHIR::lowerExpression) Handle ${propertyPath.node.kind} functions in ObjectExpression`,
1529
severity: ErrorSeverity.Todo,
@@ -1539,8 +1539,8 @@ function lowerExpression(
1539
continue;
1540
}
1541
properties.push({
1542
- kind: "ObjectProperty",
1543
- type: "method",
1542
+ kind: 'ObjectProperty',
1543
+ type: 'method',
1544
place,
1545
key: loweredKey,
1546
});
@@ -1555,18 +1555,18 @@ function lowerExpression(
1555
}
1556
}
1557
return {
1558
- kind: "ObjectExpression",
1558
+ kind: 'ObjectExpression',
1559
properties,
1560
loc: exprLoc,
1561
};
1562
}
1563
- case "ArrayExpression": {
1563
+ case 'ArrayExpression': {
1564
const expr = exprPath as NodePath<t.ArrayExpression>;
1565
- let elements: ArrayExpression["elements"] = [];
1566
- for (const element of expr.get("elements")) {
1565
+ let elements: ArrayExpression['elements'] = [];
1566
+ for (const element of expr.get('elements')) {
1567
if (element.node == null) {
1568
elements.push({
1569
- kind: "Hole",
1569
+ kind: 'Hole',
1570
});
1571
continue;
1572
} else if (element.isExpression()) {
@@ -1574,9 +1574,9 @@ function lowerExpression(
1574
} else if (element.isSpreadElement()) {
1575
const place = lowerExpressionToTemporary(
1576
builder,
1577
- element.get("argument")
1577
+ element.get('argument'),
1578
);
1579
- elements.push({ kind: "Spread", place });
1579
+ elements.push({kind: 'Spread', place});
1580
} else {
1581
builder.errors.push({
1582
reason: `(BuildHIR::lowerExpression) Handle ${element.type} elements in ArrayExpression`,
@@ -1588,14 +1588,14 @@ function lowerExpression(
1588
}
1589
}
1590
return {
1591
- kind: "ArrayExpression",
1591
+ kind: 'ArrayExpression',
1592
elements,
1593
loc: exprLoc,
1594
};
1595
}
1596
- case "NewExpression": {
1596
+ case 'NewExpression': {
1597
const expr = exprPath as NodePath<t.NewExpression>;
1598
- const calleePath = expr.get("callee");
1598
+ const calleePath = expr.get('callee');
1599
if (!calleePath.isExpression()) {
1600
builder.errors.push({
1601
reason: `Expected an expression as the \`new\` expression receiver (v8 intrinsics are not supported)`,
@@ -1604,25 +1604,25 @@ function lowerExpression(
1604
loc: calleePath.node.loc ?? null,
1605
suggestions: null,
1606
});
1607
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
1607
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
1608
}
1609
const callee = lowerExpressionToTemporary(builder, calleePath);
1610
- const args = lowerArguments(builder, expr.get("arguments"));
1610
+ const args = lowerArguments(builder, expr.get('arguments'));
1611
1612
return {
1613
- kind: "NewExpression",
1613
+ kind: 'NewExpression',
1614
callee,
1615
args,
1616
loc: exprLoc,
1617
};
1618
}
1619
- case "OptionalCallExpression": {
1619
+ case 'OptionalCallExpression': {
1620
const expr = exprPath as NodePath<t.OptionalCallExpression>;
1621
return lowerOptionalCallExpression(builder, expr, null);
1622
}
1623
- case "CallExpression": {
1623
+ case 'CallExpression': {
1624
const expr = exprPath as NodePath<t.CallExpression>;
1625
- const calleePath = expr.get("callee");
1625
+ const calleePath = expr.get('callee');
1626
if (!calleePath.isExpression()) {
1627
builder.errors.push({
1628
reason: `Expected Expression, got ${calleePath.type} in CallExpression (v8 intrinsics not supported). This error is likely caused by a bug in React Compiler. Please file an issue`,
@@ -1630,33 +1630,33 @@ function lowerExpression(
1630
loc: calleePath.node.loc ?? null,
1631
suggestions: null,
1632
});
1633
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
1633
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
1634
}
1635
if (calleePath.isMemberExpression()) {
1636
const memberExpr = lowerMemberExpression(builder, calleePath);
1637
const propertyPlace = lowerValueToTemporary(builder, memberExpr.value);
1638
- const args = lowerArguments(builder, expr.get("arguments"));
1638
+ const args = lowerArguments(builder, expr.get('arguments'));
1639
return {
1640
- kind: "MethodCall",
1640
+ kind: 'MethodCall',
1641
receiver: memberExpr.object,
1642
- property: { ...propertyPlace },
1642
+ property: {...propertyPlace},
1643
args,
1644
loc: exprLoc,
1645
};
1646
} else {
1647
const callee = lowerExpressionToTemporary(builder, calleePath);
1648
- const args = lowerArguments(builder, expr.get("arguments"));
1648
+ const args = lowerArguments(builder, expr.get('arguments'));
1649
return {
1650
- kind: "CallExpression",
1650
+ kind: 'CallExpression',
1651
callee,
1652
args,
1653
loc: exprLoc,
1654
};
1655
}
1656
}
1657
- case "BinaryExpression": {
1657
+ case 'BinaryExpression': {
1658
const expr = exprPath as NodePath<t.BinaryExpression>;
1659
- const leftPath = expr.get("left");
1659
+ const leftPath = expr.get('left');
1660
if (!leftPath.isExpression()) {
1661
builder.errors.push({
1662
reason: `(BuildHIR::lowerExpression) Expected Expression, got ${leftPath.type} lval in BinaryExpression`,
@@ -1664,38 +1664,38 @@ function lowerExpression(
1664
loc: leftPath.node.loc ?? null,
1665
suggestions: null,
1666
});
1667
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
1667
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
1668
}
1669
const left = lowerExpressionToTemporary(builder, leftPath);
1670
- const right = lowerExpressionToTemporary(builder, expr.get("right"));
1670
+ const right = lowerExpressionToTemporary(builder, expr.get('right'));
1671
const operator = expr.node.operator;
1672
- if (operator === "|>") {
1672
+ if (operator === '|>') {
1673
builder.errors.push({
1674
reason: `(BuildHIR::lowerExpression) Pipe operator not supported`,
1675
severity: ErrorSeverity.Todo,
1676
loc: leftPath.node.loc ?? null,
1677
suggestions: null,
1678
});
1679
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
1679
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
1680
}
1681
return {
1682
- kind: "BinaryExpression",
1682
+ kind: 'BinaryExpression',
1683
operator,
1684
left,
1685
right,
1686
loc: exprLoc,
1687
};
1688
}
1689
- case "SequenceExpression": {
1689
+ case 'SequenceExpression': {
1690
const expr = exprPath as NodePath<t.SequenceExpression>;
1691
const exprLoc = expr.node.loc ?? GeneratedSource;
1692
1693
const continuationBlock = builder.reserve(builder.currentBlockKind());
1694
const place = buildTemporaryPlace(builder, exprLoc);
1695
1696
- const sequenceBlock = builder.enter("sequence", (_) => {
1696
+ const sequenceBlock = builder.enter('sequence', _ => {
1697
let last: Place | null = null;
1698
- for (const item of expr.get("expressions")) {
1698
+ for (const item of expr.get('expressions')) {
1699
last = lowerExpressionToTemporary(builder, item);
1700
}
1701
if (last === null) {
@@ -1707,15 +1707,15 @@ function lowerExpression(
1707
});
1708
} else {
1709
lowerValueToTemporary(builder, {
1710
- kind: "StoreLocal",
1711
- lvalue: { kind: InstructionKind.Const, place: { ...place } },
1710
+ kind: 'StoreLocal',
1711
+ lvalue: {kind: InstructionKind.Const, place: {...place}},
1712
value: last,
1713
type: null,
1714
loc: exprLoc,
1715
});
1716
}
1717
return {
1718
- kind: "goto",
1718
+ kind: 'goto',
1719
id: makeInstructionId(0),
1720
block: continuationBlock.id,
1721
loc: exprLoc,
@@ -1725,38 +1725,38 @@ function lowerExpression(
1725
1726
builder.terminateWithContinuation(
1727
{
1728
- kind: "sequence",
1728
+ kind: 'sequence',
1729
block: sequenceBlock,
1730
fallthrough: continuationBlock.id,
1731
id: makeInstructionId(0),
1732
loc: exprLoc,
1733
},
1734
- continuationBlock
1734
+ continuationBlock,
1735
);
1736
- return { kind: "LoadLocal", place, loc: place.loc };
1736
+ return {kind: 'LoadLocal', place, loc: place.loc};
1737
}
1738
- case "ConditionalExpression": {
1738
+ case 'ConditionalExpression': {
1739
const expr = exprPath as NodePath<t.ConditionalExpression>;
1740
const exprLoc = expr.node.loc ?? GeneratedSource;
1741
1742
// Block for code following the if
1743
const continuationBlock = builder.reserve(builder.currentBlockKind());
1744
- const testBlock = builder.reserve("value");
1744
+ const testBlock = builder.reserve('value');
1745
const place = buildTemporaryPlace(builder, exprLoc);
1746
1747
// Block for the consequent (if the test is truthy)
1748
- const consequentBlock = builder.enter("value", (_blockId) => {
1749
- const consequentPath = expr.get("consequent");
1748
+ const consequentBlock = builder.enter('value', _blockId => {
1749
+ const consequentPath = expr.get('consequent');
1750
const consequent = lowerExpressionToTemporary(builder, consequentPath);
1751
lowerValueToTemporary(builder, {
1752
- kind: "StoreLocal",
1753
- lvalue: { kind: InstructionKind.Const, place: { ...place } },
1752
+ kind: 'StoreLocal',
1753
+ lvalue: {kind: InstructionKind.Const, place: {...place}},
1754
value: consequent,
1755
type: null,
1756
loc: exprLoc,
1757
});
1758
return {
1759
- kind: "goto",
1759
+ kind: 'goto',
1760
block: continuationBlock.id,
1761
variant: GotoVariant.Break,
1762
id: makeInstructionId(0),
@@ -1764,18 +1764,18 @@ function lowerExpression(
1764
};
1765
});
1766
// Block for the alternate (if the test is not truthy)
1767
- const alternateBlock = builder.enter("value", (_blockId) => {
1768
- const alternatePath = expr.get("alternate");
1767
+ const alternateBlock = builder.enter('value', _blockId => {
1768
+ const alternatePath = expr.get('alternate');
1769
const alternate = lowerExpressionToTemporary(builder, alternatePath);
1770
lowerValueToTemporary(builder, {
1771
- kind: "StoreLocal",
1772
- lvalue: { kind: InstructionKind.Const, place: { ...place } },
1771
+ kind: 'StoreLocal',
1772
+ lvalue: {kind: InstructionKind.Const, place: {...place}},
1773
value: alternate,
1774
type: null,
1775
loc: exprLoc,
1776
});
1777
return {
1778
- kind: "goto",
1778
+ kind: 'goto',
1779
block: continuationBlock.id,
1780
variant: GotoVariant.Break,
1781
id: makeInstructionId(0),
@@ -1785,65 +1785,65 @@ function lowerExpression(
1785
1786
builder.terminateWithContinuation(
1787
{
1788
- kind: "ternary",
1788
+ kind: 'ternary',
1789
fallthrough: continuationBlock.id,
1790
id: makeInstructionId(0),
1791
test: testBlock.id,
1792
loc: exprLoc,
1793
},
1794
- testBlock
1794
+ testBlock,
1795
);
1796
- const testPlace = lowerExpressionToTemporary(builder, expr.get("test"));
1796
+ const testPlace = lowerExpressionToTemporary(builder, expr.get('test'));
1797
builder.terminateWithContinuation(
1798
{
1799
- kind: "branch",
1800
- test: { ...testPlace },
1799
+ kind: 'branch',
1800
+ test: {...testPlace},
1801
consequent: consequentBlock,
1802
alternate: alternateBlock,
1803
id: makeInstructionId(0),
1804
loc: exprLoc,
1805
},
1806
- continuationBlock
1806
+ continuationBlock,
1807
);
1808
- return { kind: "LoadLocal", place, loc: place.loc };
1808
+ return {kind: 'LoadLocal', place, loc: place.loc};
1809
}
1810
- case "LogicalExpression": {
1810
+ case 'LogicalExpression': {
1811
const expr = exprPath as NodePath<t.LogicalExpression>;
1812
const exprLoc = expr.node.loc ?? GeneratedSource;
1813
const continuationBlock = builder.reserve(builder.currentBlockKind());
1814
- const testBlock = builder.reserve("value");
1814
+ const testBlock = builder.reserve('value');
1815
const place = buildTemporaryPlace(builder, exprLoc);
1816
const leftPlace = buildTemporaryPlace(
1817
builder,
1818
- expr.get("left").node.loc ?? GeneratedSource
1818
+ expr.get('left').node.loc ?? GeneratedSource,
1819
);
1820
- const consequent = builder.enter("value", () => {
1820
+ const consequent = builder.enter('value', () => {
1821
lowerValueToTemporary(builder, {
1822
- kind: "StoreLocal",
1823
- lvalue: { kind: InstructionKind.Const, place: { ...place } },
1824
- value: { ...leftPlace },
1822
+ kind: 'StoreLocal',
1823
+ lvalue: {kind: InstructionKind.Const, place: {...place}},
1824
+ value: {...leftPlace},
1825
type: null,
1826
loc: leftPlace.loc,
1827
});
1828
return {
1829
- kind: "goto",
1829
+ kind: 'goto',
1830
block: continuationBlock.id,
1831
variant: GotoVariant.Break,
1832
id: makeInstructionId(0),
1833
loc: leftPlace.loc,
1834
};
1835
});
1836
- const alternate = builder.enter("value", () => {
1837
- const right = lowerExpressionToTemporary(builder, expr.get("right"));
1836
+ const alternate = builder.enter('value', () => {
1837
+ const right = lowerExpressionToTemporary(builder, expr.get('right'));
1838
lowerValueToTemporary(builder, {
1839
- kind: "StoreLocal",
1840
- lvalue: { kind: InstructionKind.Const, place: { ...place } },
1841
- value: { ...right },
1839
+ kind: 'StoreLocal',
1840
+ lvalue: {kind: InstructionKind.Const, place: {...place}},
1841
+ value: {...right},
1842
type: null,
1843
loc: right.loc,
1844
});
1845
return {
1846
- kind: "goto",
1846
+ kind: 'goto',
1847
block: continuationBlock.id,
1848
variant: GotoVariant.Break,
1849
id: makeInstructionId(0),
@@ -1852,21 +1852,21 @@ function lowerExpression(
1852
});
1853
builder.terminateWithContinuation(
1854
{
1855
- kind: "logical",
1855
+ kind: 'logical',
1856
fallthrough: continuationBlock.id,
1857
id: makeInstructionId(0),
1858
test: testBlock.id,
1859
operator: expr.node.operator,
1860
loc: exprLoc,
1861
},
1862
- testBlock
1862
+ testBlock,
1863
);
1864
- const leftValue = lowerExpressionToTemporary(builder, expr.get("left"));
1864
+ const leftValue = lowerExpressionToTemporary(builder, expr.get('left'));
1865
builder.push({
1866
id: makeInstructionId(0),
1867
- lvalue: { ...leftPlace },
1867
+ lvalue: {...leftPlace},
1868
value: {
1869
- kind: "LoadLocal",
1869
+ kind: 'LoadLocal',
1870
place: leftValue,
1871
loc: exprLoc,
1872
},
@@ -1874,50 +1874,50 @@ function lowerExpression(
1874
});
1875
builder.terminateWithContinuation(
1876
{
1877
- kind: "branch",
1878
- test: { ...leftPlace },
1877
+ kind: 'branch',
1878
+ test: {...leftPlace},
1879
consequent,
1880
alternate,
1881
id: makeInstructionId(0),
1882
loc: exprLoc,
1883
},
1884
- continuationBlock
1884
+ continuationBlock,
1885
);
1886
- return { kind: "LoadLocal", place, loc: place.loc };
1886
+ return {kind: 'LoadLocal', place, loc: place.loc};
1887
}
1888
- case "AssignmentExpression": {
1888
+ case 'AssignmentExpression': {
1889
const expr = exprPath as NodePath<t.AssignmentExpression>;
1890
const operator = expr.node.operator;
1891
1892
- if (operator === "=") {
1893
- const left = expr.get("left");
1892
+ if (operator === '=') {
1893
+ const left = expr.get('left');
1894
return lowerAssignment(
1895
builder,
1896
left.node.loc ?? GeneratedSource,
1897
InstructionKind.Reassign,
1898
left,
1899
- lowerExpressionToTemporary(builder, expr.get("right")),
1899
+ lowerExpressionToTemporary(builder, expr.get('right')),
1900
left.isArrayPattern() || left.isObjectPattern()
1901
- ? "Destructure"
1902
- : "Assignment"
1901
+ ? 'Destructure'
1902
+ : 'Assignment',
1903
);
1904
}
1905
1906
const operators: {
1907
- [key: string]: Exclude<t.BinaryExpression["operator"], "|>">;
1907
+ [key: string]: Exclude<t.BinaryExpression['operator'], '|>'>;
1908
} = {
1909
- "+=": "+",
1910
- "-=": "-",
1911
- "/=": "/",
1912
- "%=": "%",
1913
- "*=": "*",
1914
- "**=": "**",
1915
- "&=": "&",
1916
- "|=": "|",
1917
- ">>=": ">>",
1918
- ">>>=": ">>>",
1919
- "<<=": "<<",
1920
- "^=": "^",
1909
+ '+=': '+',
1910
+ '-=': '-',
1911
+ '/=': '/',
1912
+ '%=': '%',
1913
+ '*=': '*',
1914
+ '**=': '**',
1915
+ '&=': '&',
1916
+ '|=': '|',
1917
+ '>>=': '>>',
1918
+ '>>>=': '>>>',
1919
+ '<<=': '<<',
1920
+ '^=': '^',
1921
};
1922
const binaryOperator = operators[operator];
1923
if (binaryOperator == null) {
@@ -1927,83 +1927,83 @@ function lowerExpression(
1927
loc: expr.node.loc ?? null,
1928
suggestions: null,
1929
});
1930
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
1930
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
1931
}
1932
- const left = expr.get("left");
1932
+ const left = expr.get('left');
1933
const leftNode = left.node;
1934
switch (leftNode.type) {
1935
- case "Identifier": {
1935
+ case 'Identifier': {
1936
const leftExpr = left as NodePath<t.Identifier>;
1937
const identifier = lowerIdentifier(builder, leftExpr);
1938
const leftPlace = lowerExpressionToTemporary(builder, leftExpr);
1939
- const right = lowerExpressionToTemporary(builder, expr.get("right"));
1939
+ const right = lowerExpressionToTemporary(builder, expr.get('right'));
1940
const binaryPlace = lowerValueToTemporary(builder, {
1941
- kind: "BinaryExpression",
1941
+ kind: 'BinaryExpression',
1942
operator: binaryOperator,
1943
left: leftPlace,
1944
right,
1945
loc: exprLoc,
1946
});
1947
const kind = getStoreKind(builder, leftExpr);
1948
- if (kind === "StoreLocal") {
1948
+ if (kind === 'StoreLocal') {
1949
lowerValueToTemporary(builder, {
1950
- kind: "StoreLocal",
1950
+ kind: 'StoreLocal',
1951
lvalue: {
1952
- place: { ...identifier },
1952
+ place: {...identifier},
1953
kind: InstructionKind.Reassign,
1954
},
1955
- value: { ...binaryPlace },
1955
+ value: {...binaryPlace},
1956
type: null,
1957
loc: exprLoc,
1958
});
1959
- return { kind: "LoadLocal", place: identifier, loc: exprLoc };
1959
+ return {kind: 'LoadLocal', place: identifier, loc: exprLoc};
1960
} else {
1961
lowerValueToTemporary(builder, {
1962
- kind: "StoreContext",
1962
+ kind: 'StoreContext',
1963
lvalue: {
1964
- place: { ...identifier },
1964
+ place: {...identifier},
1965
kind: InstructionKind.Reassign,
1966
},
1967
- value: { ...binaryPlace },
1967
+ value: {...binaryPlace},
1968
loc: exprLoc,
1969
});
1970
- return { kind: "LoadContext", place: identifier, loc: exprLoc };
1970
+ return {kind: 'LoadContext', place: identifier, loc: exprLoc};
1971
}
1972
}
1973
- case "MemberExpression": {
1973
+ case 'MemberExpression': {
1974
// a.b.c += <right>
1975
const leftExpr = left as NodePath<t.MemberExpression>;
1976
- const { object, property, value } = lowerMemberExpression(
1976
+ const {object, property, value} = lowerMemberExpression(
1977
builder,
1978
- leftExpr
1978
+ leftExpr,
1979
);
1980
1981
// Store the previous value to a temporary
1982
const previousValuePlace = lowerValueToTemporary(builder, value);
1983
// Store the new value to a temporary
1984
const newValuePlace = lowerValueToTemporary(builder, {
1985
- kind: "BinaryExpression",
1985
+ kind: 'BinaryExpression',
1986
operator: binaryOperator,
1987
- left: { ...previousValuePlace },
1988
- right: lowerExpressionToTemporary(builder, expr.get("right")),
1987
+ left: {...previousValuePlace},
1988
+ right: lowerExpressionToTemporary(builder, expr.get('right')),
1989
loc: leftExpr.node.loc ?? GeneratedSource,
1990
});
1991
1992
// Save the result back to the property
1993
- if (typeof property === "string") {
1993
+ if (typeof property === 'string') {
1994
return {
1995
- kind: "PropertyStore",
1996
- object: { ...object },
1995
+ kind: 'PropertyStore',
1996
+ object: {...object},
1997
property,
1998
- value: { ...newValuePlace },
1998
+ value: {...newValuePlace},
1999
loc: leftExpr.node.loc ?? GeneratedSource,
2000
};
2001
} else {
2002
return {
2003
- kind: "ComputedStore",
2004
- object: { ...object },
2005
- property: { ...property },
2006
- value: { ...newValuePlace },
2003
+ kind: 'ComputedStore',
2004
+ object: {...object},
2005
+ property: {...property},
2006
+ value: {...newValuePlace},
2007
loc: leftExpr.node.loc ?? GeneratedSource,
2008
};
2009
}
@@ -2015,36 +2015,36 @@ function lowerExpression(
2015
loc: expr.node.loc ?? null,
2016
suggestions: null,
2017
});
2018
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
2018
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
2019
}
2020
}
2021
}
2022
- case "OptionalMemberExpression": {
2022
+ case 'OptionalMemberExpression': {
2023
const expr = exprPath as NodePath<t.OptionalMemberExpression>;
2024
- const { value } = lowerOptionalMemberExpression(builder, expr, null);
2025
- return { kind: "LoadLocal", place: value, loc: value.loc };
2024
+ const {value} = lowerOptionalMemberExpression(builder, expr, null);
2025
+ return {kind: 'LoadLocal', place: value, loc: value.loc};
2026
}
2027
- case "MemberExpression": {
2027
+ case 'MemberExpression': {
2028
const expr = exprPath as NodePath<
2029
t.MemberExpression | t.OptionalMemberExpression
2030
>;
2031
- const { value } = lowerMemberExpression(builder, expr);
2031
+ const {value} = lowerMemberExpression(builder, expr);
2032
const place = lowerValueToTemporary(builder, value);
2033
- return { kind: "LoadLocal", place, loc: place.loc };
2033
+ return {kind: 'LoadLocal', place, loc: place.loc};
2034
}
2035
- case "JSXElement": {
2035
+ case 'JSXElement': {
2036
const expr = exprPath as NodePath<t.JSXElement>;
2037
- const opening = expr.get("openingElement");
2037
+ const opening = expr.get('openingElement');
2038
const openingLoc = opening.node.loc ?? GeneratedSource;
2039
- const tag = lowerJsxElementName(builder, opening.get("name"));
2039
+ const tag = lowerJsxElementName(builder, opening.get('name'));
2040
const props: Array<JsxAttribute> = [];
2041
- for (const attribute of opening.get("attributes")) {
2041
+ for (const attribute of opening.get('attributes')) {
2042
if (attribute.isJSXSpreadAttribute()) {
2043
const argument = lowerExpressionToTemporary(
2044
builder,
2045
- attribute.get("argument")
2045
+ attribute.get('argument'),
2046
);
2047
- props.push({ kind: "JsxSpreadAttribute", argument });
2047
+ props.push({kind: 'JsxSpreadAttribute', argument});
2048
continue;
2049
}
2050
if (!attribute.isJSXAttribute()) {
@@ -2056,11 +2056,11 @@ function lowerExpression(
2056
});
2057
continue;
2058
}
2059
- const namePath = attribute.get("name");
2059
+ const namePath = attribute.get('name');
2060
let propName;
2061
if (namePath.isJSXIdentifier()) {
2062
propName = namePath.node.name;
2063
- if (propName.indexOf(":") !== -1) {
2063
+ if (propName.indexOf(':') !== -1) {
2064
builder.errors.push({
2065
reason: `(BuildHIR::lowerExpression) Unexpected colon in attribute name \`${name}\``,
2066
severity: ErrorSeverity.Todo,
@@ -2070,7 +2070,7 @@ function lowerExpression(
2070
}
2071
} else {
2072
CompilerError.invariant(namePath.isJSXNamespacedName(), {
2073
- reason: "Refinement",
2073
+ reason: 'Refinement',
2074
description: null,
2075
loc: namePath.node.loc ?? null,
2076
suggestions: null,
@@ -2079,13 +2079,13 @@ function lowerExpression(
2079
const name = namePath.node.name.name;
2080
propName = `${namespace}:${name}`;
2081
}
2082
- const valueExpr = attribute.get("value");
2082
+ const valueExpr = attribute.get('value');
2083
let value;
2084
if (valueExpr.isJSXElement() || valueExpr.isStringLiteral()) {
2085
value = lowerExpressionToTemporary(builder, valueExpr);
2086
} else if (valueExpr.type == null) {
2087
value = lowerValueToTemporary(builder, {
2088
- kind: "Primitive",
2088
+ kind: 'Primitive',
2089
value: true,
2090
loc: attribute.node.loc ?? GeneratedSource,
2091
});
@@ -2099,7 +2099,7 @@ function lowerExpression(
2099
});
2100
continue;
2101
}
2102
- const expression = valueExpr.get("expression");
2102
+ const expression = valueExpr.get('expression');
2103
if (!expression.isExpression()) {
2104
builder.errors.push({
2105
reason: `(BuildHIR::lowerExpression) Handle ${expression.type} expressions in JSXExpressionContainer within JSXElement`,
@@ -2111,18 +2111,18 @@ function lowerExpression(
2111
}
2112
value = lowerExpressionToTemporary(builder, expression);
2113
}
2114
- props.push({ kind: "JsxAttribute", name: propName, place: value });
2114
+ props.push({kind: 'JsxAttribute', name: propName, place: value});
2115
}
2116
if (
2117
- tag.kind === "BuiltinTag" &&
2118
- (tag.name === "fbt" || tag.name === "fbs")
2117
+ tag.kind === 'BuiltinTag' &&
2118
+ (tag.name === 'fbt' || tag.name === 'fbs')
2119
) {
2120
const tagName = tag.name;
2121
- const openingIdentifier = opening.get("name");
2121
+ const openingIdentifier = opening.get('name');
2122
const tagIdentifier = openingIdentifier.isJSXIdentifier()
2123
? builder.resolveIdentifier(openingIdentifier)
2124
: null;
2125
- if (tagIdentifier != null && tagIdentifier.kind === "Identifier") {
2125
+ if (tagIdentifier != null && tagIdentifier.kind === 'Identifier') {
2126
CompilerError.throwTodo({
2127
reason: `Support <${tagName}> tags where '${tagName}' is a local variable instead of a global`,
2128
loc: openingIdentifier.node.loc ?? GeneratedSource,
@@ -2135,7 +2135,7 @@ function lowerExpression(
2135
JSXNamespacedName(path) {
2136
if (
2137
path.node.namespace.name === tagName &&
2138
- path.node.name.name === "enum"
2138
+ path.node.name.name === 'enum'
2139
) {
2140
fbtEnumLocations.push(path.node.loc ?? GeneratedSource);
2141
}
@@ -2153,20 +2153,20 @@ function lowerExpression(
2153
2154
let children: Array<Place>;
2155
if (
2156
- tag.kind === "BuiltinTag" &&
2157
- (tag.name === "fbt" || tag.name === "fbs")
2156
+ tag.kind === 'BuiltinTag' &&
2157
+ (tag.name === 'fbt' || tag.name === 'fbs')
2158
) {
2159
children = expr
2160
- .get("children")
2161
- .map((child) => {
2160
+ .get('children')
2161
+ .map(child => {
2162
if (child.isJSXText()) {
2163
/*
2164
* FBT whitespace normalization differs from standard JSX:
2165
* https://github.com/facebook/fbt/blob/0b4e0d13c30bffd0daa2a75715d606e3587b4e40/packages/babel-plugin-fbt/src/FbtUtil.js#L76-L87
2166
*/
2167
- const text = child.node.value.replace(/[^\S\u00A0]+/g, " ");
2167
+ const text = child.node.value.replace(/[^\S\u00A0]+/g, ' ');
2168
return lowerValueToTemporary(builder, {
2169
- kind: "JSXText",
2169
+ kind: 'JSXText',
2170
value: text,
2171
loc: child.node.loc ?? GeneratedSource,
2172
});
@@ -2176,81 +2176,81 @@ function lowerExpression(
2176
.filter(notNull);
2177
} else {
2178
children = expr
2179
- .get("children")
2180
- .map((child) => lowerJsxElement(builder, child))
2179
+ .get('children')
2180
+ .map(child => lowerJsxElement(builder, child))
2181
.filter(notNull);
2182
}
2183
return {
2184
- kind: "JsxExpression",
2184
+ kind: 'JsxExpression',
2185
tag,
2186
props,
2187
children: children.length === 0 ? null : children,
2188
loc: exprLoc,
2189
openingLoc: openingLoc,
2190
- closingLoc: expr.get("closingElement").node?.loc ?? GeneratedSource,
2190
+ closingLoc: expr.get('closingElement').node?.loc ?? GeneratedSource,
2191
};
2192
}
2193
- case "JSXFragment": {
2193
+ case 'JSXFragment': {
2194
const expr = exprPath as NodePath<t.JSXFragment>;
2195
const children: Array<Place> = expr
2196
- .get("children")
2197
- .map((child) => lowerJsxElement(builder, child))
2196
+ .get('children')
2197
+ .map(child => lowerJsxElement(builder, child))
2198
.filter(notNull);
2199
return {
2200
- kind: "JsxFragment",
2200
+ kind: 'JsxFragment',
2201
children,
2202
loc: exprLoc,
2203
};
2204
}
2205
- case "ArrowFunctionExpression":
2206
- case "FunctionExpression": {
2205
+ case 'ArrowFunctionExpression':
2206
+ case 'FunctionExpression': {
2207
const expr = exprPath as NodePath<
2208
t.FunctionExpression | t.ArrowFunctionExpression
2209
>;
2210
return lowerFunctionToValue(builder, expr);
2211
}
2212
- case "TaggedTemplateExpression": {
2212
+ case 'TaggedTemplateExpression': {
2213
const expr = exprPath as NodePath<t.TaggedTemplateExpression>;
2214
- if (expr.get("quasi").get("expressions").length !== 0) {
2214
+ if (expr.get('quasi').get('expressions').length !== 0) {
2215
builder.errors.push({
2216
reason:
2217
- "(BuildHIR::lowerExpression) Handle tagged template with interpolations",
2217
+ '(BuildHIR::lowerExpression) Handle tagged template with interpolations',
2218
severity: ErrorSeverity.Todo,
2219
loc: exprPath.node.loc ?? null,
2220
suggestions: null,
2221
});
2222
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
2222
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
2223
}
2224
- CompilerError.invariant(expr.get("quasi").get("quasis").length == 1, {
2224
+ CompilerError.invariant(expr.get('quasi').get('quasis').length == 1, {
2225
reason:
2226
"there should be only one quasi as we don't support interpolations yet",
2227
description: null,
2228
loc: expr.node.loc ?? null,
2229
suggestions: null,
2230
});
2231
- const value = expr.get("quasi").get("quasis").at(0)!.node.value;
2231
+ const value = expr.get('quasi').get('quasis').at(0)!.node.value;
2232
if (value.raw !== value.cooked) {
2233
builder.errors.push({
2234
reason:
2235
- "(BuildHIR::lowerExpression) Handle tagged template where cooked value is different from raw value",
2235
+ '(BuildHIR::lowerExpression) Handle tagged template where cooked value is different from raw value',
2236
severity: ErrorSeverity.Todo,
2237
loc: exprPath.node.loc ?? null,
2238
suggestions: null,
2239
});
2240
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
2240
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
2241
}
2242
2243
return {
2244
- kind: "TaggedTemplateExpression",
2245
- tag: lowerExpressionToTemporary(builder, expr.get("tag")),
2244
+ kind: 'TaggedTemplateExpression',
2245
+ tag: lowerExpressionToTemporary(builder, expr.get('tag')),
2246
value,
2247
loc: exprLoc,
2248
};
2249
}
2250
- case "TemplateLiteral": {
2250
+ case 'TemplateLiteral': {
2251
const expr = exprPath as NodePath<t.TemplateLiteral>;
2252
- const subexprs = expr.get("expressions");
2253
- const quasis = expr.get("quasis");
2252
+ const subexprs = expr.get('expressions');
2253
+ const quasis = expr.get('quasis');
2254
2255
if (subexprs.length !== quasis.length - 1) {
2256
builder.errors.push({
@@ -2259,46 +2259,46 @@ function lowerExpression(
2259
loc: exprPath.node.loc ?? null,
2260
suggestions: null,
2261
});
2262
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
2262
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
2263
}
2264
2265
- if (subexprs.some((e) => !e.isExpression())) {
2265
+ if (subexprs.some(e => !e.isExpression())) {
2266
builder.errors.push({
2267
reason: `(BuildHIR::lowerAssignment) Handle TSType in TemplateLiteral.`,
2268
severity: ErrorSeverity.Todo,
2269
loc: exprPath.node.loc ?? null,
2270
suggestions: null,
2271
});
2272
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
2272
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
2273
}
2274
2275
- const subexprPlaces = subexprs.map((e) =>
2276
- lowerExpressionToTemporary(builder, e as NodePath<t.Expression>)
2275
+ const subexprPlaces = subexprs.map(e =>
2276
+ lowerExpressionToTemporary(builder, e as NodePath<t.Expression>),
2277
);
2278
2279
return {
2280
- kind: "TemplateLiteral",
2280
+ kind: 'TemplateLiteral',
2281
subexprs: subexprPlaces,
2282
- quasis: expr.get("quasis").map((q) => q.node.value),
2282
+ quasis: expr.get('quasis').map(q => q.node.value),
2283
loc: exprLoc,
2284
};
2285
}
2286
- case "UnaryExpression": {
2286
+ case 'UnaryExpression': {
2287
let expr = exprPath as NodePath<t.UnaryExpression>;
2288
- if (expr.node.operator === "delete") {
2289
- const argument = expr.get("argument");
2288
+ if (expr.node.operator === 'delete') {
2289
+ const argument = expr.get('argument');
2290
if (argument.isMemberExpression()) {
2291
- const { object, property } = lowerMemberExpression(builder, argument);
2292
- if (typeof property === "string") {
2291
+ const {object, property} = lowerMemberExpression(builder, argument);
2292
+ if (typeof property === 'string') {
2293
return {
2294
- kind: "PropertyDelete",
2294
+ kind: 'PropertyDelete',
2295
object,
2296
property,
2297
loc: exprLoc,
2298
};
2299
} else {
2300
return {
2301
- kind: "ComputedDelete",
2301
+ kind: 'ComputedDelete',
2302
object,
2303
property,
2304
loc: exprLoc,
@@ -2311,70 +2311,70 @@ function lowerExpression(
2311
loc: expr.node.loc ?? null,
2312
suggestions: [
2313
{
2314
- description: "Remove this line",
2314
+ description: 'Remove this line',
2315
range: [expr.node.start!, expr.node.end!],
2316
op: CompilerSuggestionOperation.Remove,
2317
},
2318
],
2319
});
2320
- return { kind: "UnsupportedNode", node: expr.node, loc: exprLoc };
2320
+ return {kind: 'UnsupportedNode', node: expr.node, loc: exprLoc};
2321
}
2322
- } else if (expr.node.operator === "throw") {
2322
+ } else if (expr.node.operator === 'throw') {
2323
builder.errors.push({
2324
reason: `Throw expressions are not supported`,
2325
severity: ErrorSeverity.InvalidJS,
2326
loc: expr.node.loc ?? null,
2327
suggestions: [
2328
{
2329
- description: "Remove this line",
2329
+ description: 'Remove this line',
2330
range: [expr.node.start!, expr.node.end!],
2331
op: CompilerSuggestionOperation.Remove,
2332
},
2333
],
2334
});
2335
- return { kind: "UnsupportedNode", node: expr.node, loc: exprLoc };
2335
+ return {kind: 'UnsupportedNode', node: expr.node, loc: exprLoc};
2336
} else {
2337
return {
2338
- kind: "UnaryExpression",
2338
+ kind: 'UnaryExpression',
2339
operator: expr.node.operator,
2340
- value: lowerExpressionToTemporary(builder, expr.get("argument")),
2340
+ value: lowerExpressionToTemporary(builder, expr.get('argument')),
2341
loc: exprLoc,
2342
};
2343
}
2344
}
2345
- case "AwaitExpression": {
2345
+ case 'AwaitExpression': {
2346
let expr = exprPath as NodePath<t.AwaitExpression>;
2347
return {
2348
- kind: "Await",
2349
- value: lowerExpressionToTemporary(builder, expr.get("argument")),
2348
+ kind: 'Await',
2349
+ value: lowerExpressionToTemporary(builder, expr.get('argument')),
2350
loc: exprLoc,
2351
};
2352
}
2353
- case "TypeCastExpression": {
2353
+ case 'TypeCastExpression': {
2354
let expr = exprPath as NodePath<t.TypeCastExpression>;
2355
- const typeAnnotation = expr.get("typeAnnotation").get("typeAnnotation");
2355
+ const typeAnnotation = expr.get('typeAnnotation').get('typeAnnotation');
2356
return {
2357
- kind: "TypeCastExpression",
2358
- value: lowerExpressionToTemporary(builder, expr.get("expression")),
2357
+ kind: 'TypeCastExpression',
2358
+ value: lowerExpressionToTemporary(builder, expr.get('expression')),
2359
typeAnnotation: typeAnnotation.node,
2360
type: lowerType(typeAnnotation.node),
2361
loc: exprLoc,
2362
};
2363
}
2364
- case "TSAsExpression": {
2364
+ case 'TSAsExpression': {
2365
let expr = exprPath as NodePath<t.TSAsExpression>;
2366
- const typeAnnotation = expr.get("typeAnnotation");
2366
+ const typeAnnotation = expr.get('typeAnnotation');
2367
return {
2368
- kind: "TypeCastExpression",
2369
- value: lowerExpressionToTemporary(builder, expr.get("expression")),
2368
+ kind: 'TypeCastExpression',
2369
+ value: lowerExpressionToTemporary(builder, expr.get('expression')),
2370
typeAnnotation: typeAnnotation.node,
2371
type: lowerType(typeAnnotation.node),
2372
loc: exprLoc,
2373
};
2374
}
2375
- case "UpdateExpression": {
2375
+ case 'UpdateExpression': {
2376
let expr = exprPath as NodePath<t.UpdateExpression>;
2377
- const argument = expr.get("argument");
2377
+ const argument = expr.get('argument');
2378
if (!argument.isIdentifier()) {
2379
builder.errors.push({
2380
reason: `(BuildHIR::lowerExpression) Handle UpdateExpression with ${argument.type} argument`,
@@ -2382,7 +2382,7 @@ function lowerExpression(
2382
loc: exprPath.node.loc ?? null,
2383
suggestions: null,
2384
});
2385
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
2385
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
2386
} else if (builder.isContextIdentifier(argument)) {
2387
builder.errors.push({
2388
reason: `(BuildHIR::lowerExpression) Handle UpdateExpression to variables captured within lambdas.`,
@@ -2390,13 +2390,13 @@ function lowerExpression(
2390
loc: exprPath.node.loc ?? null,
2391
suggestions: null,
2392
});
2393
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
2393
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
2394
}
2395
const lvalue = lowerIdentifierForAssignment(
2396
builder,
2397
argument.node.loc ?? GeneratedSource,
2398
InstructionKind.Reassign,
2399
- argument
2399
+ argument,
2400
);
2401
if (lvalue === null) {
2402
/*
@@ -2411,20 +2411,20 @@ function lowerExpression(
2411
suggestions: null,
2412
});
2413
}
2414
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
2415
- } else if (lvalue.kind === "Global") {
2414
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
2415
+ } else if (lvalue.kind === 'Global') {
2416
builder.errors.push({
2417
reason: `(BuildHIR::lowerExpression) Support UpdateExpression where argument is a global`,
2418
severity: ErrorSeverity.Todo,
2419
loc: exprLoc,
2420
suggestions: null,
2421
});
2422
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
2422
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
2423
}
2424
const value = lowerIdentifier(builder, argument);
2425
if (expr.node.prefix) {
2426
return {
2427
- kind: "PrefixUpdate",
2427
+ kind: 'PrefixUpdate',
2428
lvalue,
2429
operation: expr.node.operator,
2430
value,
@@ -2432,7 +2432,7 @@ function lowerExpression(
2432
};
2433
} else {
2434
return {
2435
- kind: "PostfixUpdate",
2435
+ kind: 'PostfixUpdate',
2436
lvalue,
2437
operation: expr.node.operator,
2438
value,
@@ -2440,27 +2440,27 @@ function lowerExpression(
2440
};
2441
}
2442
}
2443
- case "RegExpLiteral": {
2443
+ case 'RegExpLiteral': {
2444
let expr = exprPath as NodePath<t.RegExpLiteral>;
2445
return {
2446
- kind: "RegExpLiteral",
2446
+ kind: 'RegExpLiteral',
2447
pattern: expr.node.pattern,
2448
flags: expr.node.flags,
2449
loc: expr.node.loc ?? GeneratedSource,
2450
};
2451
}
2452
- case "TSNonNullExpression": {
2452
+ case 'TSNonNullExpression': {
2453
let expr = exprPath as NodePath<t.TSNonNullExpression>;
2454
- return lowerExpression(builder, expr.get("expression"));
2454
+ return lowerExpression(builder, expr.get('expression'));
2455
}
2456
- case "MetaProperty": {
2456
+ case 'MetaProperty': {
2457
let expr = exprPath as NodePath<t.MetaProperty>;
2458
if (
2459
- expr.node.meta.name === "import" &&
2460
- expr.node.property.name === "meta"
2459
+ expr.node.meta.name === 'import' &&
2460
+ expr.node.property.name === 'meta'
2461
) {
2462
return {
2463
- kind: "MetaProperty",
2463
+ kind: 'MetaProperty',
2464
meta: expr.node.meta.name,
2465
property: expr.node.property.name,
2466
loc: expr.node.loc ?? GeneratedSource,
@@ -2473,7 +2473,7 @@ function lowerExpression(
2473
loc: exprPath.node.loc ?? null,
2474
suggestions: null,
2475
});
2476
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
2476
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
2477
}
2478
default: {
2479
builder.errors.push({
@@ -2482,7 +2482,7 @@ function lowerExpression(
2482
loc: exprPath.node.loc ?? null,
2483
suggestions: null,
2484
});
2485
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
2485
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
2486
}
2487
}
2488
}
@@ -2490,13 +2490,13 @@ function lowerExpression(
2490
function lowerOptionalMemberExpression(
2491
builder: HIRBuilder,
2492
expr: NodePath<t.OptionalMemberExpression>,
2493
- parentAlternate: BlockId | null
2494
-): { object: Place; value: Place } {
2493
+ parentAlternate: BlockId | null,
2494
+): {object: Place; value: Place} {
2495
const optional = expr.node.optional;
2496
const loc = expr.node.loc ?? GeneratedSource;
2497
const place = buildTemporaryPlace(builder, loc);
2498
const continuationBlock = builder.reserve(builder.currentBlockKind());
2499
- const consequent = builder.reserve("value");
2499
+ const consequent = builder.reserve('value');
2500
2501
/*
2502
* block to evaluate if the callee is null/undefined, this sets the result of the call to undefined.
@@ -2506,21 +2506,21 @@ function lowerOptionalMemberExpression(
2506
const alternate =
2507
parentAlternate !== null
2508
? parentAlternate
2509
- : builder.enter("value", () => {
2509
+ : builder.enter('value', () => {
2510
const temp = lowerValueToTemporary(builder, {
2511
- kind: "Primitive",
2511
+ kind: 'Primitive',
2512
value: undefined,
2513
loc,
2514
});
2515
lowerValueToTemporary(builder, {
2516
- kind: "StoreLocal",
2517
- lvalue: { kind: InstructionKind.Const, place: { ...place } },
2518
- value: { ...temp },
2516
+ kind: 'StoreLocal',
2517
+ lvalue: {kind: InstructionKind.Const, place: {...place}},
2518
+ value: {...temp},
2519
type: null,
2520
loc,
2521
});
2522
return {
2523
- kind: "goto",
2523
+ kind: 'goto',
2524
variant: GotoVariant.Break,
2525
block: continuationBlock.id,
2526
id: makeInstructionId(0),
@@ -2529,13 +2529,13 @@ function lowerOptionalMemberExpression(
2529
});
2530
2531
let object: Place | null = null;
2532
- const testBlock = builder.enter("value", () => {
2533
- const objectPath = expr.get("object");
2532
+ const testBlock = builder.enter('value', () => {
2533
+ const objectPath = expr.get('object');
2534
if (objectPath.isOptionalMemberExpression()) {
2535
- const { value } = lowerOptionalMemberExpression(
2535
+ const {value} = lowerOptionalMemberExpression(
2536
builder,
2537
objectPath,
2538
- alternate
2538
+ alternate,
2539
);
2540
object = value;
2541
} else if (objectPath.isOptionalCallExpression()) {
@@ -2545,8 +2545,8 @@ function lowerOptionalMemberExpression(
2545
object = lowerExpressionToTemporary(builder, objectPath);
2546
}
2547
return {
2548
- kind: "branch",
2549
- test: { ...object },
2548
+ kind: 'branch',
2549
+ test: {...object},
2550
consequent: consequent.id,
2551
alternate,
2552
id: makeInstructionId(0),
@@ -2554,7 +2554,7 @@ function lowerOptionalMemberExpression(
2554
};
2555
});
2556
CompilerError.invariant(object !== null, {
2557
- reason: "Satisfy type checker",
2557
+ reason: 'Satisfy type checker',
2558
description: null,
2559
loc: null,
2560
suggestions: null,
@@ -2565,17 +2565,17 @@ function lowerOptionalMemberExpression(
2565
* the semantic of conditional evaluation depending on the callee
2566
*/
2567
builder.enterReserved(consequent, () => {
2568
- const { value } = lowerMemberExpression(builder, expr, object);
2568
+ const {value} = lowerMemberExpression(builder, expr, object);
2569
const temp = lowerValueToTemporary(builder, value);
2570
lowerValueToTemporary(builder, {
2571
- kind: "StoreLocal",
2572
- lvalue: { kind: InstructionKind.Const, place: { ...place } },
2573
- value: { ...temp },
2571
+ kind: 'StoreLocal',
2572
+ lvalue: {kind: InstructionKind.Const, place: {...place}},
2573
+ value: {...temp},
2574
type: null,
2575
loc,
2576
});
2577
return {
2578
- kind: "goto",
2578
+ kind: 'goto',
2579
variant: GotoVariant.Break,
2580
block: continuationBlock.id,
2581
id: makeInstructionId(0),
@@ -2585,30 +2585,30 @@ function lowerOptionalMemberExpression(
2585
2586
builder.terminateWithContinuation(
2587
{
2588
- kind: "optional",
2588
+ kind: 'optional',
2589
optional,
2590
test: testBlock,
2591
fallthrough: continuationBlock.id,
2592
id: makeInstructionId(0),
2593
loc,
2594
},
2595
- continuationBlock
2595
+ continuationBlock,
2596
);
2597
2598
- return { object, value: place };
2598
+ return {object, value: place};
2599
}
2600
2601
function lowerOptionalCallExpression(
2602
builder: HIRBuilder,
2603
expr: NodePath<t.OptionalCallExpression>,
2604
- parentAlternate: BlockId | null
2604
+ parentAlternate: BlockId | null,
2605
): InstructionValue {
2606
const optional = expr.node.optional;
2607
- const calleePath = expr.get("callee");
2607
+ const calleePath = expr.get('callee');
2608
const loc = expr.node.loc ?? GeneratedSource;
2609
const place = buildTemporaryPlace(builder, loc);
2610
const continuationBlock = builder.reserve(builder.currentBlockKind());
2611
- const consequent = builder.reserve("value");
2611
+ const consequent = builder.reserve('value');
2612
2613
/*
2614
* block to evaluate if the callee is null/undefined, this sets the result of the call to undefined.
@@ -2618,21 +2618,21 @@ function lowerOptionalCallExpression(
2618
const alternate =
2619
parentAlternate !== null
2620
? parentAlternate
2621
- : builder.enter("value", () => {
2621
+ : builder.enter('value', () => {
2622
const temp = lowerValueToTemporary(builder, {
2623
- kind: "Primitive",
2623
+ kind: 'Primitive',
2624
value: undefined,
2625
loc,
2626
});
2627
lowerValueToTemporary(builder, {
2628
- kind: "StoreLocal",
2629
- lvalue: { kind: InstructionKind.Const, place: { ...place } },
2630
- value: { ...temp },
2628
+ kind: 'StoreLocal',
2629
+ lvalue: {kind: InstructionKind.Const, place: {...place}},
2630
+ value: {...temp},
2631
type: null,
2632
loc,
2633
});
2634
return {
2635
- kind: "goto",
2635
+ kind: 'goto',
2636
variant: GotoVariant.Break,
2637
block: continuationBlock.id,
2638
id: makeInstructionId(0),
@@ -2645,25 +2645,25 @@ function lowerOptionalCallExpression(
2645
* scoped within the optional
2646
*/
2647
let callee:
2648
- | { kind: "CallExpression"; callee: Place }
2649
- | { kind: "MethodCall"; receiver: Place; property: Place };
2650
- const testBlock = builder.enter("value", () => {
2648
+ | {kind: 'CallExpression'; callee: Place}
2649
+ | {kind: 'MethodCall'; receiver: Place; property: Place};
2650
+ const testBlock = builder.enter('value', () => {
2651
if (calleePath.isOptionalCallExpression()) {
2652
// Recursively call lowerOptionalCallExpression to thread down the alternate block
2653
const value = lowerOptionalCallExpression(builder, calleePath, alternate);
2654
const valuePlace = lowerValueToTemporary(builder, value);
2655
callee = {
2656
- kind: "CallExpression",
2656
+ kind: 'CallExpression',
2657
callee: valuePlace,
2658
};
2659
} else if (calleePath.isOptionalMemberExpression()) {
2660
- const { object, value } = lowerOptionalMemberExpression(
2660
+ const {object, value} = lowerOptionalMemberExpression(
2661
builder,
2662
calleePath,
2663
- alternate
2663
+ alternate,
2664
);
2665
callee = {
2666
- kind: "MethodCall",
2666
+ kind: 'MethodCall',
2667
receiver: object,
2668
property: value,
2669
};
@@ -2671,21 +2671,21 @@ function lowerOptionalCallExpression(
2671
const memberExpr = lowerMemberExpression(builder, calleePath);
2672
const propertyPlace = lowerValueToTemporary(builder, memberExpr.value);
2673
callee = {
2674
- kind: "MethodCall",
2674
+ kind: 'MethodCall',
2675
receiver: memberExpr.object,
2676
property: propertyPlace,
2677
};
2678
} else {
2679
callee = {
2680
- kind: "CallExpression",
2680
+ kind: 'CallExpression',
2681
callee: lowerExpressionToTemporary(builder, calleePath),
2682
};
2683
}
2684
const testPlace =
2685
- callee.kind === "CallExpression" ? callee.callee : callee.property;
2685
+ callee.kind === 'CallExpression' ? callee.callee : callee.property;
2686
return {
2687
- kind: "branch",
2688
- test: { ...testPlace },
2687
+ kind: 'branch',
2688
+ test: {...testPlace},
2689
consequent: consequent.id,
2690
alternate,
2691
id: makeInstructionId(0),
@@ -2698,15 +2698,15 @@ function lowerOptionalCallExpression(
2698
* the semantic of conditional evaluation depending on the callee
2699
*/
2700
builder.enterReserved(consequent, () => {
2701
- const args = lowerArguments(builder, expr.get("arguments"));
2701
+ const args = lowerArguments(builder, expr.get('arguments'));
2702
const temp = buildTemporaryPlace(builder, loc);
2703
- if (callee.kind === "CallExpression") {
2703
+ if (callee.kind === 'CallExpression') {
2704
builder.push({
2705
id: makeInstructionId(0),
2706
- lvalue: { ...temp },
2706
+ lvalue: {...temp},
2707
value: {
2708
- kind: "CallExpression",
2709
- callee: { ...callee.callee },
2708
+ kind: 'CallExpression',
2709
+ callee: {...callee.callee},
2710
args,
2711
loc,
2712
},
@@ -2715,11 +2715,11 @@ function lowerOptionalCallExpression(
2715
} else {
2716
builder.push({
2717
id: makeInstructionId(0),
2718
- lvalue: { ...temp },
2718
+ lvalue: {...temp},
2719
value: {
2720
- kind: "MethodCall",
2721
- receiver: { ...callee.receiver },
2722
- property: { ...callee.property },
2720
+ kind: 'MethodCall',
2721
+ receiver: {...callee.receiver},
2722
+ property: {...callee.property},
2723
args,
2724
loc,
2725
},
@@ -2727,14 +2727,14 @@ function lowerOptionalCallExpression(
2727
});
2728
}
2729
lowerValueToTemporary(builder, {
2730
- kind: "StoreLocal",
2731
- lvalue: { kind: InstructionKind.Const, place: { ...place } },
2732
- value: { ...temp },
2730
+ kind: 'StoreLocal',
2731
+ lvalue: {kind: InstructionKind.Const, place: {...place}},
2732
+ value: {...temp},
2733
type: null,
2734
loc,
2735
});
2736
return {
2737
- kind: "goto",
2737
+ kind: 'goto',
2738
variant: GotoVariant.Break,
2739
block: continuationBlock.id,
2740
id: makeInstructionId(0),
@@ -2744,17 +2744,17 @@ function lowerOptionalCallExpression(
2744
2745
builder.terminateWithContinuation(
2746
{
2747
- kind: "optional",
2747
+ kind: 'optional',
2748
optional,
2749
test: testBlock,
2750
fallthrough: continuationBlock.id,
2751
id: makeInstructionId(0),
2752
loc,
2753
},
2754
- continuationBlock
2754
+ continuationBlock,
2755
);
2756
2757
- return { kind: "LoadLocal", place, loc: place.loc };
2757
+ return {kind: 'LoadLocal', place, loc: place.loc};
2758
}
2759
2760
/*
@@ -2766,7 +2766,7 @@ function lowerOptionalCallExpression(
2766
*/
2767
function lowerReorderableExpression(
2768
builder: HIRBuilder,
2769
- expr: NodePath<t.Expression>
2769
+ expr: NodePath<t.Expression>,
2770
): Place {
2771
if (!isReorderableExpression(builder, expr, true)) {
2772
builder.errors.push({
@@ -2782,36 +2782,36 @@ function lowerReorderableExpression(
2782
function isReorderableExpression(
2783
builder: HIRBuilder,
2784
expr: NodePath<t.Expression>,
2785
- allowLocalIdentifiers: boolean
2785
+ allowLocalIdentifiers: boolean,
2786
): boolean {
2787
switch (expr.node.type) {
2788
- case "Identifier": {
2788
+ case 'Identifier': {
2789
const binding = builder.resolveIdentifier(expr as NodePath<t.Identifier>);
2790
- if (binding.kind === "Identifier") {
2790
+ if (binding.kind === 'Identifier') {
2791
return allowLocalIdentifiers;
2792
} else {
2793
// global, definitely safe
2794
return true;
2795
}
2796
}
2797
- case "RegExpLiteral":
2798
- case "StringLiteral":
2799
- case "NumericLiteral":
2800
- case "NullLiteral":
2801
- case "BooleanLiteral":
2802
- case "BigIntLiteral": {
2797
+ case 'RegExpLiteral':
2798
+ case 'StringLiteral':
2799
+ case 'NumericLiteral':
2800
+ case 'NullLiteral':
2801
+ case 'BooleanLiteral':
2802
+ case 'BigIntLiteral': {
2803
return true;
2804
}
2805
- case "UnaryExpression": {
2805
+ case 'UnaryExpression': {
2806
const unary = expr as NodePath<t.UnaryExpression>;
2807
switch (expr.node.operator) {
2808
- case "!":
2809
- case "+":
2810
- case "-": {
2808
+ case '!':
2809
+ case '+':
2810
+ case '-': {
2811
return isReorderableExpression(
2812
builder,
2813
- unary.get("argument"),
2814
- allowLocalIdentifiers
2813
+ unary.get('argument'),
2814
+ allowLocalIdentifiers,
2815
);
2816
}
2817
default: {
@@ -2819,57 +2819,57 @@ function isReorderableExpression(
2819
}
2820
}
2821
}
2822
- case "TypeCastExpression": {
2822
+ case 'TypeCastExpression': {
2823
return isReorderableExpression(
2824
builder,
2825
- (expr as NodePath<t.TypeCastExpression>).get("expression"),
2826
- allowLocalIdentifiers
2825
+ (expr as NodePath<t.TypeCastExpression>).get('expression'),
2826
+ allowLocalIdentifiers,
2827
);
2828
}
2829
- case "ConditionalExpression": {
2829
+ case 'ConditionalExpression': {
2830
const conditional = expr as NodePath<t.ConditionalExpression>;
2831
return (
2832
isReorderableExpression(
2833
builder,
2834
- conditional.get("test"),
2835
- allowLocalIdentifiers
2834
+ conditional.get('test'),
2835
+ allowLocalIdentifiers,
2836
) &&
2837
isReorderableExpression(
2838
builder,
2839
- conditional.get("consequent"),
2840
- allowLocalIdentifiers
2839
+ conditional.get('consequent'),
2840
+ allowLocalIdentifiers,
2841
) &&
2842
isReorderableExpression(
2843
builder,
2844
- conditional.get("alternate"),
2845
- allowLocalIdentifiers
2844
+ conditional.get('alternate'),
2845
+ allowLocalIdentifiers,
2846
)
2847
);
2848
}
2849
- case "ArrayExpression": {
2849
+ case 'ArrayExpression': {
2850
return (expr as NodePath<t.ArrayExpression>)
2851
- .get("elements")
2851
+ .get('elements')
2852
.every(
2853
- (element) =>
2853
+ element =>
2854
element.isExpression() &&
2855
- isReorderableExpression(builder, element, allowLocalIdentifiers)
2855
+ isReorderableExpression(builder, element, allowLocalIdentifiers),
2856
);
2857
}
2858
- case "ObjectExpression": {
2858
+ case 'ObjectExpression': {
2859
return (expr as NodePath<t.ObjectExpression>)
2860
- .get("properties")
2861
- .every((property) => {
2860
+ .get('properties')
2861
+ .every(property => {
2862
if (!property.isObjectProperty() || property.node.computed) {
2863
return false;
2864
}
2865
- const value = property.get("value");
2865
+ const value = property.get('value');
2866
return (
2867
value.isExpression() &&
2868
isReorderableExpression(builder, value, allowLocalIdentifiers)
2869
);
2870
});
2871
}
2872
- case "MemberExpression": {
2872
+ case 'MemberExpression': {
2873
/*
2874
* A common pattern is switch statements where the case test values are properties of a global,
2875
* eg `case ProductOptions.Option: { ... }`
@@ -2879,11 +2879,11 @@ function isReorderableExpression(
2879
const test = expr as NodePath<t.MemberExpression>;
2880
let innerObject: NodePath<t.Expression> = test;
2881
while (innerObject.isMemberExpression()) {
2882
- innerObject = innerObject.get("object");
2882
+ innerObject = innerObject.get('object');
2883
}
2884
if (
2885
innerObject.isIdentifier() &&
2886
- builder.resolveIdentifier(innerObject).kind !== "Identifier"
2886
+ builder.resolveIdentifier(innerObject).kind !== 'Identifier'
2887
) {
2888
// This is a property/computed load from a global, that's safe to reorder
2889
return true;
@@ -2891,33 +2891,33 @@ function isReorderableExpression(
2891
return false;
2892
}
2893
}
2894
- case "ArrowFunctionExpression": {
2894
+ case 'ArrowFunctionExpression': {
2895
const fn = expr as NodePath<t.ArrowFunctionExpression>;
2896
- const body = fn.get("body");
2897
- if (body.node.type === "BlockStatement") {
2896
+ const body = fn.get('body');
2897
+ if (body.node.type === 'BlockStatement') {
2898
return body.node.body.length === 0;
2899
} else {
2900
// For TypeScript
2901
- invariant(body.isExpression(), "Expected an expression");
2901
+ invariant(body.isExpression(), 'Expected an expression');
2902
return isReorderableExpression(
2903
builder,
2904
body,
2905
- /* disallow local identifiers in the body */ false
2905
+ /* disallow local identifiers in the body */ false,
2906
);
2907
}
2908
}
2909
- case "CallExpression": {
2909
+ case 'CallExpression': {
2910
const call = expr as NodePath<t.CallExpression>;
2911
- const callee = call.get("callee");
2911
+ const callee = call.get('callee');
2912
return (
2913
callee.isExpression() &&
2914
isReorderableExpression(builder, callee, allowLocalIdentifiers) &&
2915
call
2916
- .get("arguments")
2916
+ .get('arguments')
2917
.every(
2918
- (arg) =>
2918
+ arg =>
2919
arg.isExpression() &&
2920
- isReorderableExpression(builder, arg, allowLocalIdentifiers)
2920
+ isReorderableExpression(builder, arg, allowLocalIdentifiers),
2921
)
2922
);
2923
}
@@ -2936,14 +2936,14 @@ function lowerArguments(
2936
| t.JSXNamespacedName
2937
| t.ArgumentPlaceholder
2938
>
2939
- >
2939
+ >,
2940
): Array<Place | SpreadPattern> {
2941
let args: Array<Place | SpreadPattern> = [];
2942
for (const argPath of expr) {
2943
if (argPath.isSpreadElement()) {
2944
args.push({
2945
- kind: "Spread",
2946
- place: lowerExpressionToTemporary(builder, argPath.get("argument")),
2945
+ kind: 'Spread',
2946
+ place: lowerExpressionToTemporary(builder, argPath.get('argument')),
2947
});
2948
} else if (argPath.isExpression()) {
2949
args.push(lowerExpressionToTemporary(builder, argPath));
@@ -2967,12 +2967,12 @@ type LoweredMemberExpression = {
2967
function lowerMemberExpression(
2968
builder: HIRBuilder,
2969
expr: NodePath<t.MemberExpression | t.OptionalMemberExpression>,
2970
- loweredObject: Place | null = null
2970
+ loweredObject: Place | null = null,
2971
): LoweredMemberExpression {
2972
const exprNode = expr.node;
2973
const exprLoc = exprNode.loc ?? GeneratedSource;
2974
- const objectNode = expr.get("object");
2975
- const propertyNode = expr.get("property");
2974
+ const objectNode = expr.get('object');
2975
+ const propertyNode = expr.get('property');
2976
const object =
2977
loweredObject ?? lowerExpressionToTemporary(builder, objectNode);
2978
@@ -2987,16 +2987,16 @@ function lowerMemberExpression(
2987
return {
2988
object,
2989
property: propertyNode.toString(),
2990
- value: { kind: "UnsupportedNode", node: exprNode, loc: exprLoc },
2990
+ value: {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc},
2991
};
2992
}
2993
const value: InstructionValue = {
2994
- kind: "PropertyLoad",
2995
- object: { ...object },
2994
+ kind: 'PropertyLoad',
2995
+ object: {...object},
2996
property: propertyNode.node.name,
2997
loc: exprLoc,
2998
};
2999
- return { object, property: propertyNode.node.name, value };
2999
+ return {object, property: propertyNode.node.name, value};
3000
} else {
3001
if (!propertyNode.isExpression()) {
3002
builder.errors.push({
@@ -3009,7 +3009,7 @@ function lowerMemberExpression(
3009
object,
3010
property: propertyNode.toString(),
3011
value: {
3012
- kind: "UnsupportedNode",
3012
+ kind: 'UnsupportedNode',
3013
node: exprNode,
3014
loc: exprLoc,
3015
},
@@ -3017,12 +3017,12 @@ function lowerMemberExpression(
3017
}
3018
const property = lowerExpressionToTemporary(builder, propertyNode);
3019
const value: InstructionValue = {
3020
- kind: "ComputedLoad",
3021
- object: { ...object },
3022
- property: { ...property },
3020
+ kind: 'ComputedLoad',
3021
+ object: {...object},
3022
+ property: {...property},
3023
loc: exprLoc,
3024
};
3025
- return { object, property, value };
3025
+ return {object, property, value};
3026
}
3027
}
3028
@@ -3030,7 +3030,7 @@ function lowerJsxElementName(
3030
builder: HIRBuilder,
3031
exprPath: NodePath<
3032
t.JSXIdentifier | t.JSXMemberExpression | t.JSXNamespacedName
3033
- >
3033
+ >,
3034
): Place | BuiltinTag {
3035
const exprNode = exprPath.node;
3036
const exprLoc = exprNode.loc ?? GeneratedSource;
@@ -3045,7 +3045,7 @@ function lowerJsxElementName(
3045
});
3046
} else {
3047
return {
3048
- kind: "BuiltinTag",
3048
+ kind: 'BuiltinTag',
3049
name: tag,
3050
loc: exprLoc,
3051
};
@@ -3056,7 +3056,7 @@ function lowerJsxElementName(
3056
const namespace = exprPath.node.namespace.name;
3057
const name = exprPath.node.name.name;
3058
const tag = `${namespace}:${name}`;
3059
- if (namespace.indexOf(":") !== -1 || name.indexOf(":") !== -1) {
3059
+ if (namespace.indexOf(':') !== -1 || name.indexOf(':') !== -1) {
3060
builder.errors.push({
3061
reason: `Expected JSXNamespacedName to have no colons in the namespace or name`,
3062
description: `Got \`${namespace}\` : \`${name}\``,
@@ -3066,7 +3066,7 @@ function lowerJsxElementName(
3066
});
3067
}
3068
const place = lowerValueToTemporary(builder, {
3069
- kind: "Primitive",
3069
+ kind: 'Primitive',
3070
value: tag,
3071
loc: exprLoc,
3072
});
@@ -3079,7 +3079,7 @@ function lowerJsxElementName(
3079
suggestions: null,
3080
});
3081
return lowerValueToTemporary(builder, {
3082
- kind: "UnsupportedNode",
3082
+ kind: 'UnsupportedNode',
3083
node: exprNode,
3084
loc: exprLoc,
3085
});
@@ -3088,10 +3088,10 @@ function lowerJsxElementName(
3088
3089
function lowerJsxMemberExpression(
3090
builder: HIRBuilder,
3091
- exprPath: NodePath<t.JSXMemberExpression>
3091
+ exprPath: NodePath<t.JSXMemberExpression>,
3092
): Place {
3093
const loc = exprPath.node.loc ?? GeneratedSource;
3094
- const object = exprPath.get("object");
3094
+ const object = exprPath.get('object');
3095
let objectPlace: Place;
3096
if (object.isJSXMemberExpression()) {
3097
objectPlace = lowerJsxMemberExpression(builder, object);
@@ -3104,9 +3104,9 @@ function lowerJsxMemberExpression(
3104
});
3105
objectPlace = lowerIdentifier(builder, object);
3106
}
3107
- const property = exprPath.get("property").node.name;
3107
+ const property = exprPath.get('property').node.name;
3108
return lowerValueToTemporary(builder, {
3109
- kind: "PropertyLoad",
3109
+ kind: 'PropertyLoad',
3110
object: objectPlace,
3111
property,
3112
loc,
@@ -3121,14 +3121,14 @@ function lowerJsxElement(
3121
| t.JSXSpreadChild
3122
| t.JSXElement
3123
| t.JSXFragment
3124
- >
3124
+ >,
3125
): Place | null {
3126
const exprNode = exprPath.node;
3127
const exprLoc = exprNode.loc ?? GeneratedSource;
3128
if (exprPath.isJSXElement() || exprPath.isJSXFragment()) {
3129
return lowerExpressionToTemporary(builder, exprPath);
3130
} else if (exprPath.isJSXExpressionContainer()) {
3131
- const expression = exprPath.get("expression");
3131
+ const expression = exprPath.get('expression');
3132
if (expression.isJSXEmptyExpression()) {
3133
return null;
3134
} else {
@@ -3146,7 +3146,7 @@ function lowerJsxElement(
3146
return null;
3147
}
3148
const place = lowerValueToTemporary(builder, {
3149
- kind: "JSXText",
3149
+ kind: 'JSXText',
3150
value: text,
3151
loc: exprLoc,
3152
});
@@ -3159,7 +3159,7 @@ function lowerJsxElement(
3159
suggestions: null,
3160
});
3161
const place = lowerValueToTemporary(builder, {
3162
- kind: "UnsupportedNode",
3162
+ kind: 'UnsupportedNode',
3163
node: exprNode,
3164
loc: exprLoc,
3165
});
@@ -3190,7 +3190,7 @@ function trimJsxText(original: string): string | null {
3190
}
3191
}
3192
3193
- let str = "";
3193
+ let str = '';
3194
3195
for (let i = 0; i < lines.length; i++) {
3196
const line = lines[i];
@@ -3200,21 +3200,21 @@ function trimJsxText(original: string): string | null {
3200
const isLastNonEmptyLine = i === lastNonEmptyLine;
3201
3202
// replace rendered whitespace tabs with spaces
3203
- let trimmedLine = line.replace(/\t/g, " ");
3203
+ let trimmedLine = line.replace(/\t/g, ' ');
3204
3205
// trim whitespace touching a newline
3206
if (!isFirstLine) {
3207
- trimmedLine = trimmedLine.replace(/^[ ]+/, "");
3207
+ trimmedLine = trimmedLine.replace(/^[ ]+/, '');
3208
}
3209
3210
// trim whitespace touching an endline
3211
if (!isLastLine) {
3212
- trimmedLine = trimmedLine.replace(/[ ]+$/, "");
3212
+ trimmedLine = trimmedLine.replace(/[ ]+$/, '');
3213
}
3214
3215
if (trimmedLine) {
3216
if (!isLastNonEmptyLine) {
3217
- trimmedLine += " ";
3217
+ trimmedLine += ' ';
3218
}
3219
3220
str += trimmedLine;
@@ -3232,20 +3232,20 @@ function lowerFunctionToValue(
3232
builder: HIRBuilder,
3233
expr: NodePath<
3234
t.FunctionExpression | t.ArrowFunctionExpression | t.FunctionDeclaration
3235
- >
3235
+ >,
3236
): InstructionValue {
3237
const exprNode = expr.node;
3238
const exprLoc = exprNode.loc ?? GeneratedSource;
3239
let name: string | null = null;
3240
if (expr.isFunctionExpression()) {
3241
- name = expr.get("id")?.node?.name ?? null;
3241
+ name = expr.get('id')?.node?.name ?? null;
3242
}
3243
const loweredFunc = lowerFunction(builder, expr);
3244
if (!loweredFunc) {
3245
- return { kind: "UnsupportedNode", node: exprNode, loc: exprLoc };
3245
+ return {kind: 'UnsupportedNode', node: exprNode, loc: exprLoc};
3246
}
3247
return {
3248
- kind: "FunctionExpression",
3248
+ kind: 'FunctionExpression',
3249
name,
3250
expr: expr.node,
3251
loc: exprLoc,
@@ -3260,7 +3260,7 @@ function lowerFunction(
3260
| t.ArrowFunctionExpression
3261
| t.FunctionDeclaration
3262
| t.ObjectMethod
3263
- >
3263
+ >,
3264
): LoweredFunction | null {
3265
const componentScope: Scope = builder.parentFunction.scope;
3266
const captured = gatherCapturedDeps(builder, expr, componentScope);
@@ -3278,13 +3278,13 @@ function lowerFunction(
3278
builder.environment,
3279
builder.bindings,
3280
[...builder.context, ...captured.identifiers],
3281
- builder.parentFunction
3281
+ builder.parentFunction,
3282
);
3283
let loweredFunc: HIRFunction;
3284
if (lowering.isErr()) {
3285
lowering
3286
.unwrapErr()
3287
- .details.forEach((detail) => builder.errors.pushErrorDetail(detail));
3287
+ .details.forEach(detail => builder.errors.pushErrorDetail(detail));
3288
return null;
3289
}
3290
loweredFunc = lowering.unwrap();
@@ -3296,7 +3296,7 @@ function lowerFunction(
3296
3297
function lowerExpressionToTemporary(
3298
builder: HIRBuilder,
3299
- exprPath: NodePath<t.Expression>
3299
+ exprPath: NodePath<t.Expression>,
3300
): Place {
3301
const value = lowerExpression(builder, exprPath);
3302
return lowerValueToTemporary(builder, value);
@@ -3304,9 +3304,9 @@ function lowerExpressionToTemporary(
3304
3305
function lowerValueToTemporary(
3306
builder: HIRBuilder,
3307
- value: InstructionValue
3307
+ value: InstructionValue,
3308
): Place {
3309
- if (value.kind === "LoadLocal" && value.place.identifier.name === null) {
3309
+ if (value.kind === 'LoadLocal' && value.place.identifier.name === null) {
3310
return value.place;
3311
}
3312
const place: Place = buildTemporaryPlace(builder, value.loc);
@@ -3314,22 +3314,22 @@ function lowerValueToTemporary(
3314
id: makeInstructionId(0),
3315
value: value,
3316
loc: value.loc,
3317
- lvalue: { ...place },
3317
+ lvalue: {...place},
3318
});
3319
return place;
3320
}
3321
3322
function lowerIdentifier(
3323
builder: HIRBuilder,
3324
- exprPath: NodePath<t.Identifier | t.JSXIdentifier>
3324
+ exprPath: NodePath<t.Identifier | t.JSXIdentifier>,
3325
): Place {
3326
const exprNode = exprPath.node;
3327
const exprLoc = exprNode.loc ?? GeneratedSource;
3328
const binding = builder.resolveIdentifier(exprPath);
3329
switch (binding.kind) {
3330
- case "Identifier": {
3330
+ case 'Identifier': {
3331
const place: Place = {
3332
- kind: "Identifier",
3332
+ kind: 'Identifier',
3333
identifier: binding.identifier,
3334
effect: Effect.Unknown,
3335
reactive: false,
@@ -3339,7 +3339,7 @@ function lowerIdentifier(
3339
}
3340
default: {
3341
return lowerValueToTemporary(builder, {
3342
- kind: "LoadGlobal",
3342
+ kind: 'LoadGlobal',
3343
binding,
3344
loc: exprLoc,
3345
});
@@ -3350,7 +3350,7 @@ function lowerIdentifier(
3350
// Creates a temporary Identifier and Place referencing that identifier.
3351
function buildTemporaryPlace(builder: HIRBuilder, loc: SourceLocation): Place {
3352
const place: Place = {
3353
- kind: "Identifier",
3353
+ kind: 'Identifier',
3354
identifier: builder.makeTemporary(loc),
3355
effect: Effect.Unknown,
3356
reactive: false,
@@ -3361,30 +3361,30 @@ function buildTemporaryPlace(builder: HIRBuilder, loc: SourceLocation): Place {
3361
3362
function getStoreKind(
3363
builder: HIRBuilder,
3364
- identifier: NodePath<t.Identifier>
3365
-): "StoreLocal" | "StoreContext" {
3364
+ identifier: NodePath<t.Identifier>,
3365
+): 'StoreLocal' | 'StoreContext' {
3366
const isContext = builder.isContextIdentifier(identifier);
3367
- return isContext ? "StoreContext" : "StoreLocal";
3367
+ return isContext ? 'StoreContext' : 'StoreLocal';
3368
}
3369
3370
function getLoadKind(
3371
builder: HIRBuilder,
3372
- identifier: NodePath<t.Identifier | t.JSXIdentifier>
3373
-): "LoadLocal" | "LoadContext" {
3372
+ identifier: NodePath<t.Identifier | t.JSXIdentifier>,
3373
+): 'LoadLocal' | 'LoadContext' {
3374
const isContext = builder.isContextIdentifier(identifier);
3375
- return isContext ? "LoadContext" : "LoadLocal";
3375
+ return isContext ? 'LoadContext' : 'LoadLocal';
3376
}
3377
3378
function lowerIdentifierForAssignment(
3379
builder: HIRBuilder,
3380
loc: SourceLocation,
3381
kind: InstructionKind,
3382
- path: NodePath<t.Identifier>
3383
-): Place | { kind: "Global"; name: string } | null {
3382
+ path: NodePath<t.Identifier>,
3383
+): Place | {kind: 'Global'; name: string} | null {
3384
const binding = builder.resolveIdentifier(path);
3385
- if (binding.kind !== "Identifier") {
3385
+ if (binding.kind !== 'Identifier') {
3386
if (kind === InstructionKind.Reassign) {
3387
- return { kind: "Global", name: path.node.name };
3387
+ return {kind: 'Global', name: path.node.name};
3388
} else {
3389
// Else its an internal error bc we couldn't find the binding
3390
builder.errors.push({
@@ -3396,7 +3396,7 @@ function lowerIdentifierForAssignment(
3396
return null;
3397
}
3398
} else if (
3399
- binding.bindingKind === "const" &&
3399
+ binding.bindingKind === 'const' &&
3400
kind === InstructionKind.Reassign
3401
) {
3402
builder.errors.push({
@@ -3412,7 +3412,7 @@ function lowerIdentifierForAssignment(
3412
}
3413
3414
const place: Place = {
3415
- kind: "Identifier",
3415
+ kind: 'Identifier',
3416
identifier: binding.identifier,
3417
effect: Effect.Unknown,
3418
reactive: false,
@@ -3427,30 +3427,30 @@ function lowerAssignment(
3427
kind: InstructionKind,
3428
lvaluePath: NodePath<t.LVal>,
3429
value: Place,
3430
- assignmentKind: "Destructure" | "Assignment"
3430
+ assignmentKind: 'Destructure' | 'Assignment',
3431
): InstructionValue {
3432
const lvalueNode = lvaluePath.node;
3433
switch (lvalueNode.type) {
3434
- case "Identifier": {
3434
+ case 'Identifier': {
3435
const lvalue = lvaluePath as NodePath<t.Identifier>;
3436
const place = lowerIdentifierForAssignment(builder, loc, kind, lvalue);
3437
if (place === null) {
3438
return {
3439
- kind: "UnsupportedNode",
3439
+ kind: 'UnsupportedNode',
3440
loc: lvalue.node.loc ?? GeneratedSource,
3441
node: lvalue.node,
3442
};
3443
- } else if (place.kind === "Global") {
3443
+ } else if (place.kind === 'Global') {
3444
const temporary = lowerValueToTemporary(builder, {
3445
- kind: "StoreGlobal",
3445
+ kind: 'StoreGlobal',
3446
name: place.name,
3447
value,
3448
loc,
3449
});
3450
- return { kind: "LoadLocal", place: temporary, loc: temporary.loc };
3450
+ return {kind: 'LoadLocal', place: temporary, loc: temporary.loc};
3451
}
3452
const isHoistedIdentifier = builder.environment.isHoistedIdentifier(
3453
- lvalue.node
3453
+ lvalue.node,
3454
);
3455
3456
let temporary;
@@ -3465,54 +3465,54 @@ function lowerAssignment(
3465
});
3466
}
3467
lowerValueToTemporary(builder, {
3468
- kind: "DeclareContext",
3468
+ kind: 'DeclareContext',
3469
lvalue: {
3470
kind: InstructionKind.Let,
3471
- place: { ...place },
3471
+ place: {...place},
3472
},
3473
loc: place.loc,
3474
});
3475
}
3476
3477
temporary = lowerValueToTemporary(builder, {
3478
- kind: "StoreContext",
3479
- lvalue: { place: { ...place }, kind: InstructionKind.Reassign },
3478
+ kind: 'StoreContext',
3479
+ lvalue: {place: {...place}, kind: InstructionKind.Reassign},
3480
value,
3481
loc,
3482
});
3483
} else {
3484
- const typeAnnotation = lvalue.get("typeAnnotation");
3484
+ const typeAnnotation = lvalue.get('typeAnnotation');
3485
let type: t.FlowType | t.TSType | null;
3486
if (typeAnnotation.isTSTypeAnnotation()) {
3487
- const typePath = typeAnnotation.get("typeAnnotation");
3487
+ const typePath = typeAnnotation.get('typeAnnotation');
3488
type = typePath.node;
3489
} else if (typeAnnotation.isTypeAnnotation()) {
3490
- const typePath = typeAnnotation.get("typeAnnotation");
3490
+ const typePath = typeAnnotation.get('typeAnnotation');
3491
type = typePath.node;
3492
} else {
3493
type = null;
3494
}
3495
temporary = lowerValueToTemporary(builder, {
3496
- kind: "StoreLocal",
3497
- lvalue: { place: { ...place }, kind },
3496
+ kind: 'StoreLocal',
3497
+ lvalue: {place: {...place}, kind},
3498
value,
3499
type,
3500
loc,
3501
});
3502
}
3503
- return { kind: "LoadLocal", place: temporary, loc: temporary.loc };
3503
+ return {kind: 'LoadLocal', place: temporary, loc: temporary.loc};
3504
}
3505
- case "MemberExpression": {
3505
+ case 'MemberExpression': {
3506
// This can only occur because of a coding error, parsers enforce this condition
3507
CompilerError.invariant(kind === InstructionKind.Reassign, {
3508
- reason: "MemberExpression may only appear in an assignment expression",
3508
+ reason: 'MemberExpression may only appear in an assignment expression',
3509
description: null,
3510
loc: lvaluePath.node.loc ?? null,
3511
suggestions: null,
3512
});
3513
const lvalue = lvaluePath as NodePath<t.MemberExpression>;
3514
- const property = lvalue.get("property");
3515
- const object = lowerExpressionToTemporary(builder, lvalue.get("object"));
3514
+ const property = lvalue.get('property');
3515
+ const object = lowerExpressionToTemporary(builder, lvalue.get('object'));
3516
if (!lvalue.node.computed) {
3517
if (!property.isIdentifier()) {
3518
builder.errors.push({
@@ -3521,43 +3521,43 @@ function lowerAssignment(
3521
loc: property.node.loc ?? null,
3522
suggestions: null,
3523
});
3524
- return { kind: "UnsupportedNode", node: lvalueNode, loc };
3524
+ return {kind: 'UnsupportedNode', node: lvalueNode, loc};
3525
}
3526
const temporary = lowerValueToTemporary(builder, {
3527
- kind: "PropertyStore",
3527
+ kind: 'PropertyStore',
3528
object,
3529
property: property.node.name,
3530
value,
3531
loc,
3532
});
3533
- return { kind: "LoadLocal", place: temporary, loc: temporary.loc };
3533
+ return {kind: 'LoadLocal', place: temporary, loc: temporary.loc};
3534
} else {
3535
if (!property.isExpression()) {
3536
builder.errors.push({
3537
reason:
3538
- "(BuildHIR::lowerAssignment) Expected private name to appear as a non-computed property",
3538
+ '(BuildHIR::lowerAssignment) Expected private name to appear as a non-computed property',
3539
severity: ErrorSeverity.Todo,
3540
loc: property.node.loc ?? null,
3541
suggestions: null,
3542
});
3543
- return { kind: "UnsupportedNode", node: lvalueNode, loc };
3543
+ return {kind: 'UnsupportedNode', node: lvalueNode, loc};
3544
}
3545
const propertyPlace = lowerExpressionToTemporary(builder, property);
3546
const temporary = lowerValueToTemporary(builder, {
3547
- kind: "ComputedStore",
3547
+ kind: 'ComputedStore',
3548
object,
3549
property: propertyPlace,
3550
value,
3551
loc,
3552
});
3553
- return { kind: "LoadLocal", place: temporary, loc: temporary.loc };
3553
+ return {kind: 'LoadLocal', place: temporary, loc: temporary.loc};
3554
}
3555
}
3556
- case "ArrayPattern": {
3556
+ case 'ArrayPattern': {
3557
const lvalue = lvaluePath as NodePath<t.ArrayPattern>;
3558
- const elements = lvalue.get("elements");
3559
- const items: ArrayPattern["items"] = [];
3560
- const followups: Array<{ place: Place; path: NodePath<t.LVal> }> = [];
3558
+ const elements = lvalue.get('elements');
3559
+ const items: ArrayPattern['items'] = [];
3560
+ const followups: Array<{place: Place; path: NodePath<t.LVal>}> = [];
3561
/*
3562
* A given destructuring statement must contain all declarations or all
3563
* reassignments. This is enforced by the parser, but we rewrite nested
@@ -3568,81 +3568,81 @@ function lowerAssignment(
3568
*/
3569
const forceTemporaries =
3570
kind === InstructionKind.Reassign &&
3571
- (elements.some((element) => !element.isIdentifier()) ||
3571
+ (elements.some(element => !element.isIdentifier()) ||
3572
elements.some(
3573
- (element) =>
3573
+ element =>
3574
element.isIdentifier() &&
3575
- (getStoreKind(builder, element) !== "StoreLocal" ||
3576
- builder.resolveIdentifier(element).kind !== "Identifier")
3575
+ (getStoreKind(builder, element) !== 'StoreLocal' ||
3576
+ builder.resolveIdentifier(element).kind !== 'Identifier'),
3577
));
3578
for (let i = 0; i < elements.length; i++) {
3579
const element = elements[i];
3580
if (element.node == null) {
3581
items.push({
3582
- kind: "Hole",
3582
+ kind: 'Hole',
3583
});
3584
continue;
3585
}
3586
if (element.isRestElement()) {
3587
- const argument = element.get("argument");
3587
+ const argument = element.get('argument');
3588
if (
3589
argument.isIdentifier() &&
3590
!forceTemporaries &&
3591
- (assignmentKind === "Assignment" ||
3592
- getStoreKind(builder, argument) === "StoreLocal")
3591
+ (assignmentKind === 'Assignment' ||
3592
+ getStoreKind(builder, argument) === 'StoreLocal')
3593
) {
3594
const identifier = lowerIdentifierForAssignment(
3595
builder,
3596
element.node.loc ?? GeneratedSource,
3597
kind,
3598
- argument
3598
+ argument,
3599
);
3600
if (identifier === null) {
3601
continue;
3602
- } else if (identifier.kind === "Global") {
3602
+ } else if (identifier.kind === 'Global') {
3603
builder.errors.push({
3604
severity: ErrorSeverity.Todo,
3605
reason:
3606
- "Expected reassignment of globals to enable forceTemporaries",
3606
+ 'Expected reassignment of globals to enable forceTemporaries',
3607
loc: element.node.loc ?? GeneratedSource,
3608
});
3609
continue;
3610
}
3611
items.push({
3612
- kind: "Spread",
3612
+ kind: 'Spread',
3613
place: identifier,
3614
});
3615
} else {
3616
const temp = buildTemporaryPlace(
3617
builder,
3618
- element.node.loc ?? GeneratedSource
3618
+ element.node.loc ?? GeneratedSource,
3619
);
3620
promoteTemporary(temp.identifier);
3621
items.push({
3622
- kind: "Spread",
3623
- place: { ...temp },
3622
+ kind: 'Spread',
3623
+ place: {...temp},
3624
});
3625
- followups.push({ place: temp, path: argument as NodePath<t.LVal> }); // TODO remove type cast
3625
+ followups.push({place: temp, path: argument as NodePath<t.LVal>}); // TODO remove type cast
3626
}
3627
} else if (
3628
element.isIdentifier() &&
3629
!forceTemporaries &&
3630
- (assignmentKind === "Assignment" ||
3631
- getStoreKind(builder, element) === "StoreLocal")
3630
+ (assignmentKind === 'Assignment' ||
3631
+ getStoreKind(builder, element) === 'StoreLocal')
3632
) {
3633
const identifier = lowerIdentifierForAssignment(
3634
builder,
3635
element.node.loc ?? GeneratedSource,
3636
kind,
3637
- element
3637
+ element,
3638
);
3639
if (identifier === null) {
3640
continue;
3641
- } else if (identifier.kind === "Global") {
3641
+ } else if (identifier.kind === 'Global') {
3642
builder.errors.push({
3643
severity: ErrorSeverity.Todo,
3644
reason:
3645
- "Expected reassignment of globals to enable forceTemporaries",
3645
+ 'Expected reassignment of globals to enable forceTemporaries',
3646
loc: element.node.loc ?? GeneratedSource,
3647
});
3648
continue;
@@ -3651,42 +3651,42 @@ function lowerAssignment(
3651
} else {
3652
const temp = buildTemporaryPlace(
3653
builder,
3654
- element.node.loc ?? GeneratedSource
3654
+ element.node.loc ?? GeneratedSource,
3655
);
3656
promoteTemporary(temp.identifier);
3657
- items.push({ ...temp });
3658
- followups.push({ place: temp, path: element as NodePath<t.LVal> }); // TODO remove type cast
3657
+ items.push({...temp});
3658
+ followups.push({place: temp, path: element as NodePath<t.LVal>}); // TODO remove type cast
3659
}
3660
}
3661
const temporary = lowerValueToTemporary(builder, {
3662
- kind: "Destructure",
3662
+ kind: 'Destructure',
3663
lvalue: {
3664
kind,
3665
pattern: {
3666
- kind: "ArrayPattern",
3666
+ kind: 'ArrayPattern',
3667
items,
3668
},
3669
},
3670
value,
3671
loc,
3672
});
3673
- for (const { place, path } of followups) {
3673
+ for (const {place, path} of followups) {
3674
lowerAssignment(
3675
builder,
3676
path.node.loc ?? loc,
3677
kind,
3678
path,
3679
place,
3680
- assignmentKind
3680
+ assignmentKind,
3681
);
3682
}
3683
- return { kind: "LoadLocal", place: temporary, loc: value.loc };
3683
+ return {kind: 'LoadLocal', place: temporary, loc: value.loc};
3684
}
3685
- case "ObjectPattern": {
3685
+ case 'ObjectPattern': {
3686
const lvalue = lvaluePath as NodePath<t.ObjectPattern>;
3687
- const propertiesPaths = lvalue.get("properties");
3688
- const properties: ObjectPattern["properties"] = [];
3689
- const followups: Array<{ place: Place; path: NodePath<t.LVal> }> = [];
3687
+ const propertiesPaths = lvalue.get('properties');
3688
+ const properties: ObjectPattern['properties'] = [];
3689
+ const followups: Array<{place: Place; path: NodePath<t.LVal>}> = [];
3690
/*
3691
* A given destructuring statement must contain all declarations or all
3692
* reassignments. This is enforced by the parser, but we rewrite nested
@@ -3698,18 +3698,18 @@ function lowerAssignment(
3698
const forceTemporaries =
3699
kind === InstructionKind.Reassign &&
3700
propertiesPaths.some(
3701
- (property) =>
3701
+ property =>
3702
property.isRestElement() ||
3703
(property.isObjectProperty() &&
3704
- (!property.get("value").isIdentifier() ||
3704
+ (!property.get('value').isIdentifier() ||
3705
builder.resolveIdentifier(
3706
- property.get("value") as NodePath<t.Identifier>
3707
- ).kind !== "Identifier"))
3706
+ property.get('value') as NodePath<t.Identifier>,
3707
+ ).kind !== 'Identifier')),
3708
);
3709
for (let i = 0; i < propertiesPaths.length; i++) {
3710
const property = propertiesPaths[i];
3711
if (property.isRestElement()) {
3712
- const argument = property.get("argument");
3712
+ const argument = property.get('argument');
3713
if (!argument.isIdentifier()) {
3714
builder.errors.push({
3715
reason: `(BuildHIR::lowerAssignment) Handle ${argument.node.type} rest element in ObjectPattern`,
@@ -3721,38 +3721,38 @@ function lowerAssignment(
3721
}
3722
if (
3723
forceTemporaries ||
3724
- getStoreKind(builder, argument) === "StoreContext"
3724
+ getStoreKind(builder, argument) === 'StoreContext'
3725
) {
3726
const temp = buildTemporaryPlace(
3727
builder,
3728
- property.node.loc ?? GeneratedSource
3728
+ property.node.loc ?? GeneratedSource,
3729
);
3730
promoteTemporary(temp.identifier);
3731
properties.push({
3732
- kind: "Spread",
3733
- place: { ...temp },
3732
+ kind: 'Spread',
3733
+ place: {...temp},
3734
});
3735
- followups.push({ place: temp, path: argument as NodePath<t.LVal> }); // TODO remove type cast
3735
+ followups.push({place: temp, path: argument as NodePath<t.LVal>}); // TODO remove type cast
3736
} else {
3737
const identifier = lowerIdentifierForAssignment(
3738
builder,
3739
property.node.loc ?? GeneratedSource,
3740
kind,
3741
- argument
3741
+ argument,
3742
);
3743
if (identifier === null) {
3744
continue;
3745
- } else if (identifier.kind === "Global") {
3745
+ } else if (identifier.kind === 'Global') {
3746
builder.errors.push({
3747
severity: ErrorSeverity.Todo,
3748
reason:
3749
- "Expected reassignment of globals to enable forceTemporaries",
3749
+ 'Expected reassignment of globals to enable forceTemporaries',
3750
loc: property.node.loc ?? GeneratedSource,
3751
});
3752
continue;
3753
}
3754
properties.push({
3755
- kind: "Spread",
3755
+ kind: 'Spread',
3756
place: identifier,
3757
});
3758
}
@@ -3780,7 +3780,7 @@ function lowerAssignment(
3780
if (!loweredKey) {
3781
continue;
3782
}
3783
- const element = property.get("value");
3783
+ const element = property.get('value');
3784
if (!element.isLVal()) {
3785
builder.errors.push({
3786
reason: `(BuildHIR::lowerAssignment) Expected object property value to be an LVal, got: ${element.type}`,
@@ -3793,98 +3793,98 @@ function lowerAssignment(
3793
if (
3794
element.isIdentifier() &&
3795
!forceTemporaries &&
3796
- (assignmentKind === "Assignment" ||
3797
- getStoreKind(builder, element) === "StoreLocal")
3796
+ (assignmentKind === 'Assignment' ||
3797
+ getStoreKind(builder, element) === 'StoreLocal')
3798
) {
3799
const identifier = lowerIdentifierForAssignment(
3800
builder,
3801
element.node.loc ?? GeneratedSource,
3802
kind,
3803
- element
3803
+ element,
3804
);
3805
if (identifier === null) {
3806
continue;
3807
- } else if (identifier.kind === "Global") {
3807
+ } else if (identifier.kind === 'Global') {
3808
builder.errors.push({
3809
severity: ErrorSeverity.Todo,
3810
reason:
3811
- "Expected reassignment of globals to enable forceTemporaries",
3811
+ 'Expected reassignment of globals to enable forceTemporaries',
3812
loc: element.node.loc ?? GeneratedSource,
3813
});
3814
continue;
3815
}
3816
properties.push({
3817
- kind: "ObjectProperty",
3818
- type: "property",
3817
+ kind: 'ObjectProperty',
3818
+ type: 'property',
3819
place: identifier,
3820
key: loweredKey,
3821
});
3822
} else {
3823
const temp = buildTemporaryPlace(
3824
builder,
3825
- element.node.loc ?? GeneratedSource
3825
+ element.node.loc ?? GeneratedSource,
3826
);
3827
promoteTemporary(temp.identifier);
3828
properties.push({
3829
- kind: "ObjectProperty",
3830
- type: "property",
3831
- place: { ...temp },
3829
+ kind: 'ObjectProperty',
3830
+ type: 'property',
3831
+ place: {...temp},
3832
key: loweredKey,
3833
});
3834
- followups.push({ place: temp, path: element as NodePath<t.LVal> }); // TODO remove type cast
3834
+ followups.push({place: temp, path: element as NodePath<t.LVal>}); // TODO remove type cast
3835
}
3836
}
3837
}
3838
const temporary = lowerValueToTemporary(builder, {
3839
- kind: "Destructure",
3839
+ kind: 'Destructure',
3840
lvalue: {
3841
kind,
3842
pattern: {
3843
- kind: "ObjectPattern",
3843
+ kind: 'ObjectPattern',
3844
properties,
3845
},
3846
},
3847
value,
3848
loc,
3849
});
3850
- for (const { place, path } of followups) {
3850
+ for (const {place, path} of followups) {
3851
lowerAssignment(
3852
builder,
3853
path.node.loc ?? loc,
3854
kind,
3855
path,
3856
place,
3857
- assignmentKind
3857
+ assignmentKind,
3858
);
3859
}
3860
- return { kind: "LoadLocal", place: temporary, loc: value.loc };
3860
+ return {kind: 'LoadLocal', place: temporary, loc: value.loc};
3861
}
3862
- case "AssignmentPattern": {
3862
+ case 'AssignmentPattern': {
3863
const lvalue = lvaluePath as NodePath<t.AssignmentPattern>;
3864
const loc = lvalue.node.loc ?? GeneratedSource;
3865
const temp = buildTemporaryPlace(builder, loc);
3866
3867
- const testBlock = builder.reserve("value");
3867
+ const testBlock = builder.reserve('value');
3868
const continuationBlock = builder.reserve(builder.currentBlockKind());
3869
3870
- const consequent = builder.enter("value", () => {
3870
+ const consequent = builder.enter('value', () => {
3871
/*
3872
* Because we reorder evaluation, we restrict the allowed default values to those where
3873
* evaluation order is unobservable
3874
*/
3875
const defaultValue = lowerReorderableExpression(
3876
builder,
3877
- lvalue.get("right")
3877
+ lvalue.get('right'),
3878
);
3879
lowerValueToTemporary(builder, {
3880
- kind: "StoreLocal",
3881
- lvalue: { kind: InstructionKind.Const, place: { ...temp } },
3882
- value: { ...defaultValue },
3880
+ kind: 'StoreLocal',
3881
+ lvalue: {kind: InstructionKind.Const, place: {...temp}},
3882
+ value: {...defaultValue},
3883
type: null,
3884
loc,
3885
});
3886
return {
3887
- kind: "goto",
3887
+ kind: 'goto',
3888
variant: GotoVariant.Break,
3889
block: continuationBlock.id,
3890
id: makeInstructionId(0),
@@ -3892,16 +3892,16 @@ function lowerAssignment(
3892
};
3893
});
3894
3895
- const alternate = builder.enter("value", () => {
3895
+ const alternate = builder.enter('value', () => {
3896
lowerValueToTemporary(builder, {
3897
- kind: "StoreLocal",
3898
- lvalue: { kind: InstructionKind.Const, place: { ...temp } },
3899
- value: { ...value },
3897
+ kind: 'StoreLocal',
3898
+ lvalue: {kind: InstructionKind.Const, place: {...temp}},
3899
+ value: {...value},
3900
type: null,
3901
loc,
3902
});
3903
return {
3904
- kind: "goto",
3904
+ kind: 'goto',
3905
variant: GotoVariant.Break,
3906
block: continuationBlock.id,
3907
id: makeInstructionId(0),
@@ -3910,45 +3910,45 @@ function lowerAssignment(
3910
});
3911
builder.terminateWithContinuation(
3912
{
3913
- kind: "ternary",
3913
+ kind: 'ternary',
3914
test: testBlock.id,
3915
fallthrough: continuationBlock.id,
3916
id: makeInstructionId(0),
3917
loc,
3918
},
3919
- testBlock
3919
+ testBlock,
3920
);
3921
const undef = lowerValueToTemporary(builder, {
3922
- kind: "Primitive",
3922
+ kind: 'Primitive',
3923
value: undefined,
3924
loc,
3925
});
3926
const test = lowerValueToTemporary(builder, {
3927
- kind: "BinaryExpression",
3928
- left: { ...value },
3929
- operator: "===",
3930
- right: { ...undef },
3927
+ kind: 'BinaryExpression',
3928
+ left: {...value},
3929
+ operator: '===',
3930
+ right: {...undef},
3931
loc,
3932
});
3933
builder.terminateWithContinuation(
3934
{
3935
- kind: "branch",
3936
- test: { ...test },
3935
+ kind: 'branch',
3936
+ test: {...test},
3937
consequent,
3938
alternate,
3939
id: makeInstructionId(0),
3940
loc,
3941
},
3942
- continuationBlock
3942
+ continuationBlock,
3943
);
3944
3945
return lowerAssignment(
3946
builder,
3947
loc,
3948
kind,
3949
- lvalue.get("left"),
3949
+ lvalue.get('left'),
3950
temp,
3951
- assignmentKind
3951
+ assignmentKind,
3952
);
3953
}
3954
default: {
@@ -3958,7 +3958,7 @@ function lowerAssignment(
3958
loc: lvaluePath.node.loc ?? null,
3959
suggestions: null,
3960
});
3961
- return { kind: "UnsupportedNode", node: lvalueNode, loc };
3961
+ return {kind: 'UnsupportedNode', node: lvalueNode, loc};
3962
}
3963
}
3964
}
@@ -3967,11 +3967,11 @@ function isValidDependency(path: NodePath<t.MemberExpression>): boolean {
3967
const parent: NodePath<t.Node> = path.parentPath;
3968
return (
3969
!path.node.computed &&
3970
- !(parent.isCallExpression() && parent.get("callee") === path)
3970
+ !(parent.isCallExpression() && parent.get('callee') === path)
3971
);
3972
}
3973
3974
-function captureScopes({ from, to }: { from: Scope; to: Scope }): Set<Scope> {
3974
+function captureScopes({from, to}: {from: Scope; to: Scope}): Set<Scope> {
3975
let scopes: Set<Scope> = new Set();
3976
while (from) {
3977
scopes.add(from);
@@ -3993,8 +3993,8 @@ function gatherCapturedDeps(
3993
| t.FunctionDeclaration
3994
| t.ObjectMethod
3995
>,
3996
- componentScope: Scope
3997
-): { identifiers: Array<t.Identifier>; refs: Array<Place> } {
3996
+ componentScope: Scope,
3997
+): {identifiers: Array<t.Identifier>; refs: Array<Place>} {
3998
const capturedIds: Map<t.Identifier, number> = new Map();
3999
const capturedRefs: Set<Place> = new Set();
4000
const seenPaths: Set<string> = new Set();
@@ -4022,7 +4022,7 @@ function gatherCapturedDeps(
4022
path:
4023
| NodePath<t.MemberExpression>
4024
| NodePath<t.Identifier>
4025
- | NodePath<t.JSXOpeningElement>
4025
+ | NodePath<t.JSXOpeningElement>,
4026
): void {
4027
// Base context variable to depend on
4028
let baseIdentifier: NodePath<t.Identifier> | NodePath<t.JSXIdentifier>;
@@ -4036,18 +4036,18 @@ function gatherCapturedDeps(
4036
| NodePath<t.Identifier>
4037
| NodePath<t.JSXIdentifier>;
4038
if (path.isJSXOpeningElement()) {
4039
- const name = path.get("name");
4039
+ const name = path.get('name');
4040
if (!(name.isJSXMemberExpression() || name.isJSXIdentifier())) {
4041
// TODO: should JSX namespaced names be handled here as well?
4042
return;
4043
}
4044
let current: NodePath<t.JSXMemberExpression | t.JSXIdentifier> = name;
4045
while (current.isJSXMemberExpression()) {
4046
- current = current.get("object");
4046
+ current = current.get('object');
4047
}
4048
invariant(
4049
current.isJSXIdentifier(),
4050
- "Invalid logic in gatherCapturedDeps"
4050
+ 'Invalid logic in gatherCapturedDeps',
4051
);
4052
baseIdentifier = current;
4053
@@ -4073,7 +4073,7 @@ function gatherCapturedDeps(
4073
// Calculate baseIdentifier
4074
let currentId: NodePath<Expression> = path;
4075
while (currentId.isMemberExpression()) {
4076
- currentId = currentId.get("object");
4076
+ currentId = currentId.get('object');
4077
}
4078
if (!currentId.isIdentifier()) {
4079
return;
@@ -4127,20 +4127,20 @@ function gatherCapturedDeps(
4127
let pathTokens = [];
4128
let current: NodePath<Expression> = dependency;
4129
while (current.isMemberExpression()) {
4130
- const property = current.get("property") as NodePath<t.Identifier>;
4130
+ const property = current.get('property') as NodePath<t.Identifier>;
4131
pathTokens.push(property.node.name);
4132
- current = current.get("object");
4132
+ current = current.get('object');
4133
}
4134
4135
- exprKey += "." + pathTokens.reverse().join(".");
4135
+ exprKey += '.' + pathTokens.reverse().join('.');
4136
} else if (dependency.isJSXMemberExpression()) {
4137
let pathTokens = [];
4138
let current: NodePath<t.JSXMemberExpression | t.JSXIdentifier> =
4139
dependency;
4140
while (current.isJSXMemberExpression()) {
4141
- const property = current.get("property");
4141
+ const property = current.get('property');
4142
pathTokens.push(property.node.name);
4143
- current = current.get("object");
4143
+ current = current.get('object');
4144
}
4145
}
4146
@@ -4148,7 +4148,7 @@ function gatherCapturedDeps(
4148
let loweredDep: Place;
4149
if (dependency.isJSXIdentifier()) {
4150
loweredDep = lowerValueToTemporary(builder, {
4151
- kind: "LoadLocal",
4151
+ kind: 'LoadLocal',
4152
place: lowerIdentifier(builder, dependency),
4153
loc: path.node.loc ?? GeneratedSource,
4154
});
@@ -4182,20 +4182,20 @@ function gatherCapturedDeps(
4182
* AssignmentExpression if it's an Identifier. Work around it by explicitly
4183
* visiting it.
4184
*/
4185
- const left = path.get("left");
4185
+ const left = path.get('left');
4186
if (left.isIdentifier()) {
4187
handleMaybeDependency(left);
4188
}
4189
return;
4190
} else if (path.isJSXElement()) {
4191
- handleMaybeDependency(path.get("openingElement"));
4191
+ handleMaybeDependency(path.get('openingElement'));
4192
} else if (path.isMemberExpression() || path.isIdentifier()) {
4193
handleMaybeDependency(path);
4194
}
4195
},
4196
});
4197
4198
- return { identifiers: [...capturedIds.keys()], refs: [...capturedRefs] };
4198
+ return {identifiers: [...capturedIds.keys()], refs: [...capturedRefs]};
4199
}
4200
4201
function notNull<T>(value: T | null): value is T {
@@ -4204,40 +4204,40 @@ function notNull<T>(value: T | null): value is T {
4204
4205
export function lowerType(node: t.FlowType | t.TSType): Type {
4206
switch (node.type) {
4207
- case "GenericTypeAnnotation": {
4207
+ case 'GenericTypeAnnotation': {
4208
const id = node.id;
4209
- if (id.type === "Identifier" && id.name === "Array") {
4210
- return { kind: "Object", shapeId: BuiltInArrayId };
4209
+ if (id.type === 'Identifier' && id.name === 'Array') {
4210
+ return {kind: 'Object', shapeId: BuiltInArrayId};
4211
}
4212
return makeType();
4213
}
4214
- case "TSTypeReference": {
4214
+ case 'TSTypeReference': {
4215
const typeName = node.typeName;
4216
- if (typeName.type === "Identifier" && typeName.name === "Array") {
4217
- return { kind: "Object", shapeId: BuiltInArrayId };
4216
+ if (typeName.type === 'Identifier' && typeName.name === 'Array') {
4217
+ return {kind: 'Object', shapeId: BuiltInArrayId};
4218
}
4219
return makeType();
4220
}
4221
- case "ArrayTypeAnnotation":
4222
- case "TSArrayType": {
4223
- return { kind: "Object", shapeId: BuiltInArrayId };
4221
+ case 'ArrayTypeAnnotation':
4222
+ case 'TSArrayType': {
4223
+ return {kind: 'Object', shapeId: BuiltInArrayId};
4224
}
4225
- case "BooleanLiteralTypeAnnotation":
4226
- case "BooleanTypeAnnotation":
4227
- case "NullLiteralTypeAnnotation":
4228
- case "NumberLiteralTypeAnnotation":
4229
- case "NumberTypeAnnotation":
4230
- case "StringLiteralTypeAnnotation":
4231
- case "StringTypeAnnotation":
4232
- case "TSBooleanKeyword":
4233
- case "TSNullKeyword":
4234
- case "TSNumberKeyword":
4235
- case "TSStringKeyword":
4236
- case "TSSymbolKeyword":
4237
- case "TSUndefinedKeyword":
4238
- case "TSVoidKeyword":
4239
- case "VoidTypeAnnotation": {
4240
- return { kind: "Primitive" };
4225
+ case 'BooleanLiteralTypeAnnotation':
4226
+ case 'BooleanTypeAnnotation':
4227
+ case 'NullLiteralTypeAnnotation':
4228
+ case 'NumberLiteralTypeAnnotation':
4229
+ case 'NumberTypeAnnotation':
4230
+ case 'StringLiteralTypeAnnotation':
4231
+ case 'StringTypeAnnotation':
4232
+ case 'TSBooleanKeyword':
4233
+ case 'TSNullKeyword':
4234
+ case 'TSNumberKeyword':
4235
+ case 'TSStringKeyword':
4236
+ case 'TSSymbolKeyword':
4237
+ case 'TSUndefinedKeyword':
4238
+ case 'TSVoidKeyword':
4239
+ case 'VoidTypeAnnotation': {
4240
+ return {kind: 'Primitive'};
4241
}
4242
default: {
4243
return makeType();
compiler/packages/babel-plugin-react-compiler/src/HIR/BuildReactiveScopeTerminalsHIR.ts
+18
-18
@@ -1,6 +1,6 @@
1
-import { CompilerError } from "../CompilerError";
2
-import { getScopes, recursivelyTraverseItems } from "./AssertValidBlockNesting";
3
-import { Environment } from "./Environment";
1
+import {CompilerError} from '../CompilerError';
2
+import {getScopes, recursivelyTraverseItems} from './AssertValidBlockNesting';
3
+import {Environment} from './Environment';
4
import {
5
BasicBlock,
6
BlockId,
@@ -12,7 +12,7 @@ import {
12
ReactiveScope,
13
ReactiveScopeTerminal,
14
ScopeId,
15
-} from "./HIR";
15
+} from './HIR';
16
17
/**
18
* This pass assumes that all program blocks are properly nested with respect to fallthroughs
@@ -72,14 +72,14 @@ export function buildReactiveScopeTerminalsHIR(fn: HIRFunction): void {
72
const queuedRewrites: Array<TerminalRewriteInfo> = [];
73
recursivelyTraverseItems(
74
[...getScopes(fn)],
75
- (scope) => scope.range,
75
+ scope => scope.range,
76
{
77
fallthroughs: new Map(),
78
rewrites: queuedRewrites,
79
env: fn.env,
80
},
81
pushStartScopeTerminal,
82
- pushEndScopeTerminal
82
+ pushEndScopeTerminal,
83
);
84
85
/**
@@ -166,14 +166,14 @@ export function buildReactiveScopeTerminalsHIR(fn: HIRFunction): void {
166
167
type TerminalRewriteInfo =
168
| {
169
- kind: "StartScope";
169
+ kind: 'StartScope';
170
blockId: BlockId;
171
fallthroughId: BlockId;
172
instrId: InstructionId;
173
scope: ReactiveScope;
174
}
175
| {
176
- kind: "EndScope";
176
+ kind: 'EndScope';
177
instrId: InstructionId;
178
fallthroughId: BlockId;
179
};
@@ -190,12 +190,12 @@ type ScopeTraversalContext = {
190
191
function pushStartScopeTerminal(
192
scope: ReactiveScope,
193
- context: ScopeTraversalContext
193
+ context: ScopeTraversalContext,
194
): void {
195
const blockId = context.env.nextBlockId;
196
const fallthroughId = context.env.nextBlockId;
197
context.rewrites.push({
198
- kind: "StartScope",
198
+ kind: 'StartScope',
199
blockId,
200
fallthroughId,
201
instrId: scope.range.start,
@@ -206,15 +206,15 @@ function pushStartScopeTerminal(
206
207
function pushEndScopeTerminal(
208
scope: ReactiveScope,
209
- context: ScopeTraversalContext
209
+ context: ScopeTraversalContext,
210
): void {
211
const fallthroughId = context.fallthroughs.get(scope.id);
212
CompilerError.invariant(fallthroughId != null, {
213
- reason: "Expected scope to exist",
213
+ reason: 'Expected scope to exist',
214
loc: GeneratedSource,
215
});
216
context.rewrites.push({
217
- kind: "EndScope",
217
+ kind: 'EndScope',
218
fallthroughId,
219
instrId: scope.range.end,
220
});
@@ -248,13 +248,13 @@ type RewriteContext = {
248
function handleRewrite(
249
terminalInfo: TerminalRewriteInfo,
250
idx: number,
251
- context: RewriteContext
251
+ context: RewriteContext,
252
): void {
253
// TODO make consistent instruction IDs instead of reusing
254
const terminal: ReactiveScopeTerminal | GotoTerminal =
255
- terminalInfo.kind === "StartScope"
255
+ terminalInfo.kind === 'StartScope'
256
? {
257
- kind: "scope",
257
+ kind: 'scope',
258
fallthrough: terminalInfo.fallthroughId,
259
block: terminalInfo.blockId,
260
scope: terminalInfo.scope,
@@ -262,7 +262,7 @@ function handleRewrite(
262
loc: GeneratedSource,
263
}
264
: {
265
- kind: "goto",
265
+ kind: 'goto',
266
variant: GotoVariant.Break,
267
block: terminalInfo.fallthroughId,
268
id: terminalInfo.instrId,
@@ -281,7 +281,7 @@ function handleRewrite(
281
});
282
context.nextPreds = new Set([currBlockId]);
283
context.nextBlockId =
284
- terminalInfo.kind === "StartScope"
284
+ terminalInfo.kind === 'StartScope'
285
? terminalInfo.blockId
286
: terminalInfo.fallthroughId;
287
context.instrSliceIdx = idx;
compiler/packages/babel-plugin-react-compiler/src/HIR/ComputeUnconditionalBlocks.ts
+3
-3
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { BlockId, HIRFunction, computePostDominatorTree } from ".";
9
-import { CompilerError } from "..";
8
+import {BlockId, HIRFunction, computePostDominatorTree} from '.';
9
+import {CompilerError} from '..';
10
11
export function computeUnconditionalBlocks(fn: HIRFunction): Set<BlockId> {
12
// Construct the set of blocks that is always reachable from the entry block.
@@ -23,7 +23,7 @@ export function computeUnconditionalBlocks(fn: HIRFunction): Set<BlockId> {
23
while (current !== null && current !== exit) {
24
CompilerError.invariant(!unconditionalBlocks.has(current), {
25
reason:
26
- "Internal error: non-terminating loop in ComputeUnconditionalBlocks",
26
+ 'Internal error: non-terminating loop in ComputeUnconditionalBlocks',
27
loc: null,
28
suggestions: null,
29
});
compiler/packages/babel-plugin-react-compiler/src/HIR/Dominator.ts
+12
-12
@@ -5,10 +5,10 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import prettyFormat from "pretty-format";
9
-import { CompilerError } from "../CompilerError";
10
-import { BlockId, HIRFunction } from "./HIR";
11
-import { eachTerminalSuccessor } from "./visitors";
8
+import prettyFormat from 'pretty-format';
9
+import {CompilerError} from '../CompilerError';
10
+import {BlockId, HIRFunction} from './HIR';
11
+import {eachTerminalSuccessor} from './visitors';
12
13
/*
14
* Computes the dominator tree of the given function. The returned `Dominator` stores the immediate
@@ -34,7 +34,7 @@ export function computeDominatorTree(fn: HIRFunction): Dominator<BlockId> {
34
*/
35
export function computePostDominatorTree(
36
fn: HIRFunction,
37
- options: { includeThrowsAsExitNode: boolean }
37
+ options: {includeThrowsAsExitNode: boolean},
38
): PostDominator<BlockId> {
39
const graph = buildReverseGraph(fn, options.includeThrowsAsExitNode);
40
const nodes = computeImmediateDominators(graph);
@@ -87,7 +87,7 @@ export class Dominator<T> {
87
get(id: T): T | null {
88
const dominator = this.#nodes.get(id);
89
CompilerError.invariant(dominator !== undefined, {
90
- reason: "Unknown node",
90
+ reason: 'Unknown node',
91
description: null,
92
loc: null,
93
suggestions: null,
@@ -128,7 +128,7 @@ export class PostDominator<T> {
128
get(id: T): T | null {
129
const dominator = this.#nodes.get(id);
130
CompilerError.invariant(dominator !== undefined, {
131
- reason: "Unknown node",
131
+ reason: 'Unknown node',
132
description: null,
133
loc: null,
134
suggestions: null,
@@ -217,7 +217,7 @@ function intersect<T>(a: T, b: T, graph: Graph<T>, nodes: Map<T, T>): T {
217
218
// Turns the HIRFunction into a simplified internal form that is shared for dominator/post-dominator computation
219
function buildGraph(fn: HIRFunction): Graph<BlockId> {
220
- const graph: Graph<BlockId> = { entry: fn.body.entry, nodes: new Map() };
220
+ const graph: Graph<BlockId> = {entry: fn.body.entry, nodes: new Map()};
221
let index = 0;
222
for (const [id, block] of fn.body.blocks) {
223
graph.nodes.set(id, {
@@ -237,7 +237,7 @@ function buildGraph(fn: HIRFunction): Graph<BlockId> {
237
*/
238
function buildReverseGraph(
239
fn: HIRFunction,
240
- includeThrowsAsExitNode: boolean
240
+ includeThrowsAsExitNode: boolean,
241
): Graph<BlockId> {
242
const nodes: Map<BlockId, Node<BlockId>> = new Map();
243
const exitId = fn.env.nextBlockId;
@@ -256,10 +256,10 @@ function buildReverseGraph(
256
preds: new Set(eachTerminalSuccessor(block.terminal)),
257
succs: new Set(block.preds),
258
};
259
- if (block.terminal.kind === "return") {
259
+ if (block.terminal.kind === 'return') {
260
node.preds.add(exitId);
261
exit.succs.add(id);
262
- } else if (block.terminal.kind === "throw" && includeThrowsAsExitNode) {
262
+ } else if (block.terminal.kind === 'throw' && includeThrowsAsExitNode) {
263
node.preds.add(exitId);
264
exit.succs.add(id);
265
}
@@ -282,7 +282,7 @@ function buildReverseGraph(
282
}
283
visit(exitId);
284
285
- const rpo: Graph<BlockId> = { entry: exitId, nodes: new Map() };
285
+ const rpo: Graph<BlockId> = {entry: exitId, nodes: new Map()};
286
let index = 0;
287
for (const id of postorder.reverse()) {
288
const node = nodes.get(id)!;
compiler/packages/babel-plugin-react-compiler/src/HIR/Environment.ts
+55
-55
@@ -5,19 +5,19 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import * as t from "@babel/types";
9
-import { ZodError, z } from "zod";
10
-import { fromZodError } from "zod-validation-error";
11
-import { CompilerError } from "../CompilerError";
12
-import { Logger } from "../Entrypoint";
13
-import { Err, Ok, Result } from "../Utils/Result";
8
+import * as t from '@babel/types';
9
+import {ZodError, z} from 'zod';
10
+import {fromZodError} from 'zod-validation-error';
11
+import {CompilerError} from '../CompilerError';
12
+import {Logger} from '../Entrypoint';
13
+import {Err, Ok, Result} from '../Utils/Result';
14
import {
15
DEFAULT_GLOBALS,
16
DEFAULT_SHAPES,
17
Global,
18
GlobalRegistry,
19
installReAnimatedTypes,
20
-} from "./Globals";
20
+} from './Globals';
21
import {
22
BlockId,
23
BuiltInType,
@@ -35,7 +35,7 @@ import {
35
makeIdentifierId,
36
makeIdentifierName,
37
makeScopeId,
38
-} from "./HIR";
38
+} from './HIR';
39
import {
40
BuiltInMixedReadonlyId,
41
DefaultMutatingHook,
@@ -43,8 +43,8 @@ import {
43
FunctionSignature,
44
ShapeRegistry,
45
addHook,
46
-} from "./ObjectShape";
47
-import { Scope as BabelScope } from "@babel/traverse";
46
+} from './ObjectShape';
47
+import {Scope as BabelScope} from '@babel/traverse';
48
49
export const ExternalFunctionSchema = z.object({
50
// Source for the imported module that exports the `importSpecifierName` functions
@@ -61,8 +61,8 @@ export const InstrumentationSchema = z
61
globalGating: z.string().nullish(),
62
})
63
.refine(
64
- (opts) => opts.gating != null || opts.globalGating != null,
65
- "Expected at least one of gating or globalGating"
64
+ opts => opts.gating != null || opts.globalGating != null,
65
+ 'Expected at least one of gating or globalGating',
66
);
67
68
export type ExternalFunction = z.infer<typeof ExternalFunctionSchema>;
@@ -443,34 +443,34 @@ export function parseConfigPragma(pragma: string): EnvironmentConfig {
443
// Get the defaults to programmatically check for boolean properties
444
const defaultConfig = EnvironmentConfigSchema.parse({});
445
446
- for (const token of pragma.split(" ")) {
447
- if (!token.startsWith("@")) {
446
+ for (const token of pragma.split(' ')) {
447
+ if (!token.startsWith('@')) {
448
continue;
449
}
450
const keyVal = token.slice(1);
451
- let [key, val]: any = keyVal.split(":");
451
+ let [key, val]: any = keyVal.split(':');
452
453
- if (key === "validateNoCapitalizedCalls") {
453
+ if (key === 'validateNoCapitalizedCalls') {
454
maybeConfig[key] = [];
455
continue;
456
}
457
458
if (
459
- key === "enableChangeDetectionForDebugging" &&
460
- (val === undefined || val === "true")
459
+ key === 'enableChangeDetectionForDebugging' &&
460
+ (val === undefined || val === 'true')
461
) {
462
maybeConfig[key] = {
463
- source: "react-compiler-runtime",
464
- importSpecifierName: "$structuralCheck",
463
+ source: 'react-compiler-runtime',
464
+ importSpecifierName: '$structuralCheck',
465
};
466
continue;
467
}
468
469
- if (typeof defaultConfig[key as keyof EnvironmentConfig] !== "boolean") {
469
+ if (typeof defaultConfig[key as keyof EnvironmentConfig] !== 'boolean') {
470
// skip parsing non-boolean properties
471
continue;
472
}
473
- if (val === undefined || val === "true") {
473
+ if (val === undefined || val === 'true') {
474
val = true;
475
} else {
476
val = false;
@@ -483,7 +483,7 @@ export function parseConfigPragma(pragma: string): EnvironmentConfig {
483
return config.data;
484
}
485
CompilerError.invariant(false, {
486
- reason: "Internal error, could not parse config from pragma string",
486
+ reason: 'Internal error, could not parse config from pragma string',
487
description: `${fromZodError(config.error)}`,
488
loc: null,
489
suggestions: null,
@@ -492,18 +492,18 @@ export function parseConfigPragma(pragma: string): EnvironmentConfig {
492
493
export type PartialEnvironmentConfig = Partial<EnvironmentConfig>;
494
495
-export type ReactFunctionType = "Component" | "Hook" | "Other";
495
+export type ReactFunctionType = 'Component' | 'Hook' | 'Other';
496
497
export function printFunctionType(type: ReactFunctionType): string {
498
switch (type) {
499
- case "Component": {
500
- return "component";
499
+ case 'Component': {
500
+ return 'component';
501
}
502
- case "Hook": {
503
- return "hook";
502
+ case 'Hook': {
503
+ return 'hook';
504
}
505
default: {
506
- return "function";
506
+ return 'function';
507
}
508
}
509
}
@@ -537,7 +537,7 @@ export class Environment {
537
logger: Logger | null,
538
filename: string | null,
539
code: string | null,
540
- useMemoCacheIdentifier: string
540
+ useMemoCacheIdentifier: string,
541
) {
542
this.#scope = scope;
543
this.fnType = fnType;
@@ -574,13 +574,13 @@ export class Environment {
574
positionalParams: [],
575
restParam: hook.effectKind,
576
returnType: hook.transitiveMixedData
577
- ? { kind: "Object", shapeId: BuiltInMixedReadonlyId }
578
- : { kind: "Poly" },
577
+ ? {kind: 'Object', shapeId: BuiltInMixedReadonlyId}
578
+ : {kind: 'Poly'},
579
returnValueKind: hook.valueKind,
580
calleeEffect: Effect.Read,
581
- hookKind: "Custom",
581
+ hookKind: 'Custom',
582
noAlias: hook.noAlias,
583
- })
583
+ }),
584
);
585
}
586
@@ -613,14 +613,14 @@ export class Environment {
613
}
614
615
generateGloballyUniqueIdentifierName(
616
- name: string | null
616
+ name: string | null,
617
): ValidatedIdentifier {
618
const identifierNode = this.#scope.generateUidIdentifier(name ?? undefined);
619
return makeIdentifierName(identifierNode.name);
620
}
621
622
outlineFunction(fn: HIRFunction, type: ReactFunctionType | null): void {
623
- this.#outlinedFunctions.push({ fn, type });
623
+ this.#outlinedFunctions.push({fn, type});
624
}
625
626
getOutlinedFunctions(): Array<{
@@ -635,7 +635,7 @@ export class Environment {
635
const match = new RegExp(this.config.hookPattern).exec(binding.name);
636
if (
637
match != null &&
638
- typeof match[1] === "string" &&
638
+ typeof match[1] === 'string' &&
639
isHookName(match[1])
640
) {
641
const resolvedName = match[1];
@@ -644,17 +644,17 @@ export class Environment {
644
}
645
646
switch (binding.kind) {
647
- case "ModuleLocal": {
647
+ case 'ModuleLocal': {
648
// don't resolve module locals
649
return isHookName(binding.name) ? this.#getCustomHookType() : null;
650
}
651
- case "Global": {
651
+ case 'Global': {
652
return (
653
this.#globals.get(binding.name) ??
654
(isHookName(binding.name) ? this.#getCustomHookType() : null)
655
);
656
}
657
- case "ImportSpecifier": {
657
+ case 'ImportSpecifier': {
658
if (this.#isKnownReactModule(binding.module)) {
659
/**
660
* For `import {imported as name} from "..."` form, we use the `imported`
@@ -681,8 +681,8 @@ export class Environment {
681
: null;
682
}
683
}
684
- case "ImportDefault":
685
- case "ImportNamespace": {
684
+ case 'ImportDefault':
685
+ case 'ImportNamespace': {
686
if (this.#isKnownReactModule(binding.module)) {
687
// only resolve imports to modules we know about
688
return (
@@ -698,19 +698,19 @@ export class Environment {
698
699
#isKnownReactModule(moduleName: string): boolean {
700
return (
701
- moduleName.toLowerCase() === "react" ||
702
- moduleName.toLowerCase() === "react-dom" ||
701
+ moduleName.toLowerCase() === 'react' ||
702
+ moduleName.toLowerCase() === 'react-dom' ||
703
(this.config.enableSharedRuntime__testonly &&
704
- moduleName === "shared-runtime")
704
+ moduleName === 'shared-runtime')
705
);
706
}
707
708
getPropertyType(
709
receiver: Type,
710
- property: string
710
+ property: string,
711
): BuiltInType | PolyType | null {
712
let shapeId = null;
713
- if (receiver.kind === "Object" || receiver.kind === "Function") {
713
+ if (receiver.kind === 'Object' || receiver.kind === 'Function') {
714
shapeId = receiver.shapeId;
715
}
716
if (shapeId !== null) {
@@ -726,7 +726,7 @@ export class Environment {
726
suggestions: null,
727
});
728
let value =
729
- shape.properties.get(property) ?? shape.properties.get("*") ?? null;
729
+ shape.properties.get(property) ?? shape.properties.get('*') ?? null;
730
if (value === null && isHookName(property)) {
731
value = this.#getCustomHookType();
732
}
@@ -739,7 +739,7 @@ export class Environment {
739
}
740
741
getFunctionSignature(type: FunctionType): FunctionSignature | null {
742
- const { shapeId } = type;
742
+ const {shapeId} = type;
743
if (shapeId !== null) {
744
const shape = this.#shapes.get(shapeId);
745
CompilerError.invariant(shape !== undefined, {
@@ -773,7 +773,7 @@ export function isHookName(name: string): boolean {
773
}
774
775
export function parseEnvironmentConfig(
776
- partialConfig: PartialEnvironmentConfig
776
+ partialConfig: PartialEnvironmentConfig,
777
): Result<EnvironmentConfig, ZodError<PartialEnvironmentConfig>> {
778
const config = EnvironmentConfigSchema.safeParse(partialConfig);
779
if (config.success) {
@@ -784,7 +784,7 @@ export function parseEnvironmentConfig(
784
}
785
786
export function validateEnvironmentConfig(
787
- partialConfig: PartialEnvironmentConfig
787
+ partialConfig: PartialEnvironmentConfig,
788
): EnvironmentConfig {
789
const config = EnvironmentConfigSchema.safeParse(partialConfig);
790
if (config.success) {
@@ -793,7 +793,7 @@ export function validateEnvironmentConfig(
793
794
CompilerError.throwInvalidConfig({
795
reason:
796
- "Could not validate environment config. Update React Compiler config to fix the error",
796
+ 'Could not validate environment config. Update React Compiler config to fix the error',
797
description: `${fromZodError(config.error)}`,
798
loc: null,
799
suggestions: null,
@@ -801,10 +801,10 @@ export function validateEnvironmentConfig(
801
}
802
803
export function tryParseExternalFunction(
804
- maybeExternalFunction: any
804
+ maybeExternalFunction: any,
805
): ExternalFunction {
806
const externalFunction = ExternalFunctionSchema.safeParse(
807
- maybeExternalFunction
807
+ maybeExternalFunction,
808
);
809
if (externalFunction.success) {
810
return externalFunction.data;
@@ -812,7 +812,7 @@ export function tryParseExternalFunction(
812
813
CompilerError.throwInvalidConfig({
814
reason:
815
- "Could not parse external function. Update React Compiler config to fix the error",
815
+ 'Could not parse external function. Update React Compiler config to fix the error',
816
description: `${fromZodError(externalFunction.error)}`,
817
loc: null,
818
suggestions: null,
compiler/packages/babel-plugin-react-compiler/src/HIR/FindContextIdentifiers.ts
+27
-27
@@ -5,11 +5,11 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import type { NodePath } from "@babel/traverse";
9
-import type * as t from "@babel/types";
10
-import { CompilerError } from "../CompilerError";
11
-import { getOrInsertDefault } from "../Utils/utils";
12
-import { GeneratedSource } from "./HIR";
8
+import type {NodePath} from '@babel/traverse';
9
+import type * as t from '@babel/types';
10
+import {CompilerError} from '../CompilerError';
11
+import {getOrInsertDefault} from '../Utils/utils';
12
+import {GeneratedSource} from './HIR';
13
14
type IdentifierInfo = {
15
reassigned: boolean;
@@ -35,7 +35,7 @@ type FindContextIdentifierState = {
35
const withFunctionScope = {
36
enter: function (
37
path: BabelFunction,
38
- state: FindContextIdentifierState
38
+ state: FindContextIdentifierState,
39
): void {
40
state.currentFn.push(path);
41
},
@@ -45,7 +45,7 @@ const withFunctionScope = {
45
};
46
47
export function findContextIdentifiers(
48
- func: NodePath<t.Function>
48
+ func: NodePath<t.Function>,
49
): Set<t.Identifier> {
50
const state: FindContextIdentifierState = {
51
currentFn: [],
@@ -60,17 +60,17 @@ export function findContextIdentifiers(
60
ObjectMethod: withFunctionScope,
61
AssignmentExpression(
62
path: NodePath<t.AssignmentExpression>,
63
- state: FindContextIdentifierState
63
+ state: FindContextIdentifierState,
64
): void {
65
- const left = path.get("left");
65
+ const left = path.get('left');
66
const currentFn = state.currentFn.at(-1) ?? null;
67
handleAssignment(currentFn, state.identifiers, left);
68
},
69
UpdateExpression(
70
path: NodePath<t.UpdateExpression>,
71
- state: FindContextIdentifierState
71
+ state: FindContextIdentifierState,
72
): void {
73
- const argument = path.get("argument");
73
+ const argument = path.get('argument');
74
const currentFn = state.currentFn.at(-1) ?? null;
75
if (argument.isLVal()) {
76
handleAssignment(currentFn, state.identifiers, argument);
@@ -78,7 +78,7 @@ export function findContextIdentifiers(
78
},
79
Identifier(
80
path: NodePath<t.Identifier>,
81
- state: FindContextIdentifierState
81
+ state: FindContextIdentifierState,
82
): void {
83
const currentFn = state.currentFn.at(-1) ?? null;
84
if (path.isReferencedIdentifier()) {
@@ -86,7 +86,7 @@ export function findContextIdentifiers(
86
}
87
},
88
},
89
- state
89
+ state,
90
);
91
92
const result = new Set<t.Identifier>();
@@ -103,7 +103,7 @@ export function findContextIdentifiers(
103
function handleIdentifier(
104
currentFn: BabelFunction | null,
105
identifiers: Map<t.Identifier, IdentifierInfo>,
106
- path: NodePath<t.Identifier>
106
+ path: NodePath<t.Identifier>,
107
): void {
108
const name = path.node.name;
109
const binding = path.scope.getBinding(name);
@@ -126,7 +126,7 @@ function handleIdentifier(
126
function handleAssignment(
127
currentFn: BabelFunction | null,
128
identifiers: Map<t.Identifier, IdentifierInfo>,
129
- lvalPath: NodePath<t.LVal>
129
+ lvalPath: NodePath<t.LVal>,
130
): void {
131
/*
132
* Find all reassignments to identifiers declared outside of currentFn
@@ -134,7 +134,7 @@ function handleAssignment(
134
*/
135
const lvalNode = lvalPath.node;
136
switch (lvalNode.type) {
137
- case "Identifier": {
137
+ case 'Identifier': {
138
const path = lvalPath as NodePath<t.Identifier>;
139
const name = path.node.name;
140
const binding = path.scope.getBinding(name);
@@ -155,20 +155,20 @@ function handleAssignment(
155
}
156
break;
157
}
158
- case "ArrayPattern": {
158
+ case 'ArrayPattern': {
159
const path = lvalPath as NodePath<t.ArrayPattern>;
160
- for (const element of path.get("elements")) {
160
+ for (const element of path.get('elements')) {
161
if (nonNull(element)) {
162
handleAssignment(currentFn, identifiers, element);
163
}
164
}
165
break;
166
}
167
- case "ObjectPattern": {
167
+ case 'ObjectPattern': {
168
const path = lvalPath as NodePath<t.ObjectPattern>;
169
- for (const property of path.get("properties")) {
169
+ for (const property of path.get('properties')) {
170
if (property.isObjectProperty()) {
171
- const valuePath = property.get("value");
171
+ const valuePath = property.get('value');
172
CompilerError.invariant(valuePath.isLVal(), {
173
reason: `[FindContextIdentifiers] Expected object property value to be an LVal, got: ${valuePath.type}`,
174
description: null,
@@ -188,18 +188,18 @@ function handleAssignment(
188
}
189
break;
190
}
191
- case "AssignmentPattern": {
191
+ case 'AssignmentPattern': {
192
const path = lvalPath as NodePath<t.AssignmentPattern>;
193
- const left = path.get("left");
193
+ const left = path.get('left');
194
handleAssignment(currentFn, identifiers, left);
195
break;
196
}
197
- case "RestElement": {
197
+ case 'RestElement': {
198
const path = lvalPath as NodePath<t.RestElement>;
199
- handleAssignment(currentFn, identifiers, path.get("argument"));
199
+ handleAssignment(currentFn, identifiers, path.get('argument'));
200
break;
201
}
202
- case "MemberExpression": {
202
+ case 'MemberExpression': {
203
// Interior mutability (not a reassign)
204
break;
205
}
@@ -215,7 +215,7 @@ function handleAssignment(
215
}
216
217
function nonNull<T extends NonNullable<t.Node>>(
218
- t: NodePath<T | null>
218
+ t: NodePath<T | null>,
219
): t is NodePath<T> {
220
return t.node != null;
221
}
compiler/packages/babel-plugin-react-compiler/src/HIR/Globals.ts
+148
-148
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { Effect, ValueKind, ValueReason } from "./HIR";
8
+import {Effect, ValueKind, ValueReason} from './HIR';
9
import {
10
BUILTIN_SHAPES,
11
BuiltInArrayId,
@@ -21,8 +21,8 @@ import {
21
addFunction,
22
addHook,
23
addObject,
24
-} from "./ObjectShape";
25
-import { BuiltInType, PolyType } from "./Types";
24
+} from './ObjectShape';
25
+import {BuiltInType, PolyType} from './Types';
26
27
/*
28
* This file exports types and defaults for JavaScript global objects.
@@ -37,59 +37,59 @@ export const DEFAULT_SHAPES: ShapeRegistry = new Map(BUILTIN_SHAPES);
37
38
// Hack until we add ObjectShapes for all globals
39
const UNTYPED_GLOBALS: Set<string> = new Set([
40
- "String",
41
- "Object",
42
- "Function",
43
- "Number",
44
- "RegExp",
45
- "Date",
46
- "Error",
47
- "Function",
48
- "TypeError",
49
- "RangeError",
50
- "ReferenceError",
51
- "SyntaxError",
52
- "URIError",
53
- "EvalError",
54
- "Boolean",
55
- "DataView",
56
- "Float32Array",
57
- "Float64Array",
58
- "Int8Array",
59
- "Int16Array",
60
- "Int32Array",
61
- "Map",
62
- "Set",
63
- "WeakMap",
64
- "Uint8Array",
65
- "Uint8ClampedArray",
66
- "Uint16Array",
67
- "Uint32Array",
68
- "ArrayBuffer",
69
- "JSON",
70
- "parseFloat",
71
- "parseInt",
72
- "console",
73
- "isNaN",
74
- "eval",
75
- "isFinite",
76
- "encodeURI",
77
- "decodeURI",
78
- "encodeURIComponent",
79
- "decodeURIComponent",
40
+ 'String',
41
+ 'Object',
42
+ 'Function',
43
+ 'Number',
44
+ 'RegExp',
45
+ 'Date',
46
+ 'Error',
47
+ 'Function',
48
+ 'TypeError',
49
+ 'RangeError',
50
+ 'ReferenceError',
51
+ 'SyntaxError',
52
+ 'URIError',
53
+ 'EvalError',
54
+ 'Boolean',
55
+ 'DataView',
56
+ 'Float32Array',
57
+ 'Float64Array',
58
+ 'Int8Array',
59
+ 'Int16Array',
60
+ 'Int32Array',
61
+ 'Map',
62
+ 'Set',
63
+ 'WeakMap',
64
+ 'Uint8Array',
65
+ 'Uint8ClampedArray',
66
+ 'Uint16Array',
67
+ 'Uint32Array',
68
+ 'ArrayBuffer',
69
+ 'JSON',
70
+ 'parseFloat',
71
+ 'parseInt',
72
+ 'console',
73
+ 'isNaN',
74
+ 'eval',
75
+ 'isFinite',
76
+ 'encodeURI',
77
+ 'decodeURI',
78
+ 'encodeURIComponent',
79
+ 'decodeURIComponent',
80
]);
81
82
const TYPED_GLOBALS: Array<[string, BuiltInType]> = [
83
[
84
- "Array",
85
- addObject(DEFAULT_SHAPES, "Array", [
84
+ 'Array',
85
+ addObject(DEFAULT_SHAPES, 'Array', [
86
[
87
- "isArray",
87
+ 'isArray',
88
// Array.isArray(value)
89
addFunction(DEFAULT_SHAPES, [], {
90
positionalParams: [Effect.Read],
91
restParam: null,
92
- returnType: { kind: "Primitive" },
92
+ returnType: {kind: 'Primitive'},
93
calleeEffect: Effect.Read,
94
returnValueKind: ValueKind.Primitive,
95
}),
@@ -106,12 +106,12 @@ const TYPED_GLOBALS: Array<[string, BuiltInType]> = [
106
* function)
107
*/
108
[
109
- "of",
109
+ 'of',
110
// Array.of(element0, ..., elementN)
111
addFunction(DEFAULT_SHAPES, [], {
112
positionalParams: [],
113
restParam: Effect.Read,
114
- returnType: { kind: "Object", shapeId: BuiltInArrayId },
114
+ returnType: {kind: 'Object', shapeId: BuiltInArrayId},
115
calleeEffect: Effect.Read,
116
returnValueKind: ValueKind.Mutable,
117
}),
@@ -119,85 +119,85 @@ const TYPED_GLOBALS: Array<[string, BuiltInType]> = [
119
]),
120
],
121
[
122
- "Math",
123
- addObject(DEFAULT_SHAPES, "Math", [
122
+ 'Math',
123
+ addObject(DEFAULT_SHAPES, 'Math', [
124
// Static properties (TODO)
125
- ["PI", { kind: "Primitive" }],
125
+ ['PI', {kind: 'Primitive'}],
126
// Static methods (TODO)
127
[
128
- "max",
128
+ 'max',
129
// Math.max(value0, ..., valueN)
130
addFunction(DEFAULT_SHAPES, [], {
131
positionalParams: [],
132
restParam: Effect.Read,
133
- returnType: { kind: "Primitive" },
133
+ returnType: {kind: 'Primitive'},
134
calleeEffect: Effect.Read,
135
returnValueKind: ValueKind.Primitive,
136
}),
137
],
138
]),
139
],
140
- ["Infinity", { kind: "Primitive" }],
141
- ["NaN", { kind: "Primitive" }],
140
+ ['Infinity', {kind: 'Primitive'}],
141
+ ['NaN', {kind: 'Primitive'}],
142
[
143
- "console",
144
- addObject(DEFAULT_SHAPES, "console", [
143
+ 'console',
144
+ addObject(DEFAULT_SHAPES, 'console', [
145
[
146
- "error",
146
+ 'error',
147
addFunction(DEFAULT_SHAPES, [], {
148
positionalParams: [],
149
restParam: Effect.Read,
150
- returnType: { kind: "Primitive" },
150
+ returnType: {kind: 'Primitive'},
151
calleeEffect: Effect.Read,
152
returnValueKind: ValueKind.Primitive,
153
}),
154
],
155
[
156
- "info",
156
+ 'info',
157
addFunction(DEFAULT_SHAPES, [], {
158
positionalParams: [],
159
restParam: Effect.Read,
160
- returnType: { kind: "Primitive" },
160
+ returnType: {kind: 'Primitive'},
161
calleeEffect: Effect.Read,
162
returnValueKind: ValueKind.Primitive,
163
}),
164
],
165
[
166
- "log",
166
+ 'log',
167
addFunction(DEFAULT_SHAPES, [], {
168
positionalParams: [],
169
restParam: Effect.Read,
170
- returnType: { kind: "Primitive" },
170
+ returnType: {kind: 'Primitive'},
171
calleeEffect: Effect.Read,
172
returnValueKind: ValueKind.Primitive,
173
}),
174
],
175
[
176
- "table",
176
+ 'table',
177
addFunction(DEFAULT_SHAPES, [], {
178
positionalParams: [],
179
restParam: Effect.Read,
180
- returnType: { kind: "Primitive" },
180
+ returnType: {kind: 'Primitive'},
181
calleeEffect: Effect.Read,
182
returnValueKind: ValueKind.Primitive,
183
}),
184
],
185
[
186
- "trace",
186
+ 'trace',
187
addFunction(DEFAULT_SHAPES, [], {
188
positionalParams: [],
189
restParam: Effect.Read,
190
- returnType: { kind: "Primitive" },
190
+ returnType: {kind: 'Primitive'},
191
calleeEffect: Effect.Read,
192
returnValueKind: ValueKind.Primitive,
193
}),
194
],
195
[
196
- "warn",
196
+ 'warn',
197
addFunction(DEFAULT_SHAPES, [], {
198
positionalParams: [],
199
restParam: Effect.Read,
200
- returnType: { kind: "Primitive" },
200
+ returnType: {kind: 'Primitive'},
201
calleeEffect: Effect.Read,
202
returnValueKind: ValueKind.Primitive,
203
}),
@@ -205,31 +205,31 @@ const TYPED_GLOBALS: Array<[string, BuiltInType]> = [
205
]),
206
],
207
[
208
- "Boolean",
208
+ 'Boolean',
209
addFunction(DEFAULT_SHAPES, [], {
210
positionalParams: [],
211
restParam: Effect.Read,
212
- returnType: { kind: "Primitive" },
212
+ returnType: {kind: 'Primitive'},
213
calleeEffect: Effect.Read,
214
returnValueKind: ValueKind.Primitive,
215
}),
216
],
217
[
218
- "Number",
218
+ 'Number',
219
addFunction(DEFAULT_SHAPES, [], {
220
positionalParams: [],
221
restParam: Effect.Read,
222
- returnType: { kind: "Primitive" },
222
+ returnType: {kind: 'Primitive'},
223
calleeEffect: Effect.Read,
224
returnValueKind: ValueKind.Primitive,
225
}),
226
],
227
[
228
- "String",
228
+ 'String',
229
addFunction(DEFAULT_SHAPES, [], {
230
positionalParams: [],
231
restParam: Effect.Read,
232
- returnType: { kind: "Primitive" },
232
+ returnType: {kind: 'Primitive'},
233
calleeEffect: Effect.Read,
234
returnValueKind: ValueKind.Primitive,
235
}),
@@ -244,179 +244,179 @@ const TYPED_GLOBALS: Array<[string, BuiltInType]> = [
244
*/
245
const REACT_APIS: Array<[string, BuiltInType]> = [
246
[
247
- "useContext",
247
+ 'useContext',
248
addHook(DEFAULT_SHAPES, {
249
positionalParams: [],
250
restParam: Effect.Read,
251
- returnType: { kind: "Poly" },
251
+ returnType: {kind: 'Poly'},
252
calleeEffect: Effect.Read,
253
- hookKind: "useContext",
253
+ hookKind: 'useContext',
254
returnValueKind: ValueKind.Frozen,
255
returnValueReason: ValueReason.Context,
256
}),
257
],
258
[
259
- "useState",
259
+ 'useState',
260
addHook(DEFAULT_SHAPES, {
261
positionalParams: [],
262
restParam: Effect.Freeze,
263
- returnType: { kind: "Object", shapeId: BuiltInUseStateId },
263
+ returnType: {kind: 'Object', shapeId: BuiltInUseStateId},
264
calleeEffect: Effect.Read,
265
- hookKind: "useState",
265
+ hookKind: 'useState',
266
returnValueKind: ValueKind.Frozen,
267
returnValueReason: ValueReason.State,
268
}),
269
],
270
[
271
- "useActionState",
271
+ 'useActionState',
272
addHook(DEFAULT_SHAPES, {
273
positionalParams: [],
274
restParam: Effect.Freeze,
275
- returnType: { kind: "Object", shapeId: BuiltInUseActionStateId },
275
+ returnType: {kind: 'Object', shapeId: BuiltInUseActionStateId},
276
calleeEffect: Effect.Read,
277
- hookKind: "useActionState",
277
+ hookKind: 'useActionState',
278
returnValueKind: ValueKind.Frozen,
279
returnValueReason: ValueReason.State,
280
}),
281
],
282
[
283
- "useReducer",
283
+ 'useReducer',
284
addHook(DEFAULT_SHAPES, {
285
positionalParams: [],
286
restParam: Effect.Freeze,
287
- returnType: { kind: "Object", shapeId: BuiltInUseReducerId },
287
+ returnType: {kind: 'Object', shapeId: BuiltInUseReducerId},
288
calleeEffect: Effect.Read,
289
- hookKind: "useReducer",
289
+ hookKind: 'useReducer',
290
returnValueKind: ValueKind.Frozen,
291
returnValueReason: ValueReason.ReducerState,
292
}),
293
],
294
[
295
- "useRef",
295
+ 'useRef',
296
addHook(DEFAULT_SHAPES, {
297
positionalParams: [],
298
restParam: Effect.Capture,
299
- returnType: { kind: "Object", shapeId: BuiltInUseRefId },
299
+ returnType: {kind: 'Object', shapeId: BuiltInUseRefId},
300
calleeEffect: Effect.Read,
301
- hookKind: "useRef",
301
+ hookKind: 'useRef',
302
returnValueKind: ValueKind.Mutable,
303
}),
304
],
305
[
306
- "useMemo",
306
+ 'useMemo',
307
addHook(DEFAULT_SHAPES, {
308
positionalParams: [],
309
restParam: Effect.Freeze,
310
- returnType: { kind: "Poly" },
310
+ returnType: {kind: 'Poly'},
311
calleeEffect: Effect.Read,
312
- hookKind: "useMemo",
312
+ hookKind: 'useMemo',
313
returnValueKind: ValueKind.Frozen,
314
}),
315
],
316
[
317
- "useCallback",
317
+ 'useCallback',
318
addHook(DEFAULT_SHAPES, {
319
positionalParams: [],
320
restParam: Effect.Freeze,
321
- returnType: { kind: "Poly" },
321
+ returnType: {kind: 'Poly'},
322
calleeEffect: Effect.Read,
323
- hookKind: "useCallback",
323
+ hookKind: 'useCallback',
324
returnValueKind: ValueKind.Frozen,
325
}),
326
],
327
[
328
- "useEffect",
328
+ 'useEffect',
329
addHook(
330
DEFAULT_SHAPES,
331
{
332
positionalParams: [],
333
restParam: Effect.Freeze,
334
- returnType: { kind: "Primitive" },
334
+ returnType: {kind: 'Primitive'},
335
calleeEffect: Effect.Read,
336
- hookKind: "useEffect",
336
+ hookKind: 'useEffect',
337
returnValueKind: ValueKind.Frozen,
338
},
339
- BuiltInUseEffectHookId
339
+ BuiltInUseEffectHookId,
340
),
341
],
342
[
343
- "useLayoutEffect",
343
+ 'useLayoutEffect',
344
addHook(
345
DEFAULT_SHAPES,
346
{
347
positionalParams: [],
348
restParam: Effect.Freeze,
349
- returnType: { kind: "Poly" },
349
+ returnType: {kind: 'Poly'},
350
calleeEffect: Effect.Read,
351
- hookKind: "useLayoutEffect",
351
+ hookKind: 'useLayoutEffect',
352
returnValueKind: ValueKind.Frozen,
353
},
354
- BuiltInUseLayoutEffectHookId
354
+ BuiltInUseLayoutEffectHookId,
355
),
356
],
357
[
358
- "useInsertionEffect",
358
+ 'useInsertionEffect',
359
addHook(
360
DEFAULT_SHAPES,
361
{
362
positionalParams: [],
363
restParam: Effect.Freeze,
364
- returnType: { kind: "Poly" },
364
+ returnType: {kind: 'Poly'},
365
calleeEffect: Effect.Read,
366
- hookKind: "useInsertionEffect",
366
+ hookKind: 'useInsertionEffect',
367
returnValueKind: ValueKind.Frozen,
368
},
369
- BuiltInUseInsertionEffectHookId
369
+ BuiltInUseInsertionEffectHookId,
370
),
371
],
372
[
373
- "use",
373
+ 'use',
374
addFunction(
375
DEFAULT_SHAPES,
376
[],
377
{
378
positionalParams: [],
379
restParam: Effect.Freeze,
380
- returnType: { kind: "Poly" },
380
+ returnType: {kind: 'Poly'},
381
calleeEffect: Effect.Read,
382
returnValueKind: ValueKind.Frozen,
383
},
384
- BuiltInUseOperatorId
384
+ BuiltInUseOperatorId,
385
),
386
],
387
];
388
389
TYPED_GLOBALS.push(
390
[
391
- "React",
391
+ 'React',
392
addObject(DEFAULT_SHAPES, null, [
393
...REACT_APIS,
394
[
395
- "createElement",
395
+ 'createElement',
396
addFunction(DEFAULT_SHAPES, [], {
397
positionalParams: [],
398
restParam: Effect.Freeze,
399
- returnType: { kind: "Poly" },
399
+ returnType: {kind: 'Poly'},
400
calleeEffect: Effect.Read,
401
returnValueKind: ValueKind.Frozen,
402
}),
403
],
404
[
405
- "cloneElement",
405
+ 'cloneElement',
406
addFunction(DEFAULT_SHAPES, [], {
407
positionalParams: [],
408
restParam: Effect.Freeze,
409
- returnType: { kind: "Poly" },
409
+ returnType: {kind: 'Poly'},
410
calleeEffect: Effect.Read,
411
returnValueKind: ValueKind.Frozen,
412
}),
413
],
414
[
415
- "createRef",
415
+ 'createRef',
416
addFunction(DEFAULT_SHAPES, [], {
417
positionalParams: [],
418
restParam: Effect.Capture, // createRef takes no paramters
419
- returnType: { kind: "Object", shapeId: BuiltInUseRefId },
419
+ returnType: {kind: 'Object', shapeId: BuiltInUseRefId},
420
calleeEffect: Effect.Read,
421
returnValueKind: ValueKind.Mutable,
422
}),
@@ -424,15 +424,15 @@ TYPED_GLOBALS.push(
424
]),
425
],
426
[
427
- "_jsx",
427
+ '_jsx',
428
addFunction(DEFAULT_SHAPES, [], {
429
positionalParams: [],
430
restParam: Effect.Freeze,
431
- returnType: { kind: "Poly" },
431
+ returnType: {kind: 'Poly'},
432
calleeEffect: Effect.Read,
433
returnValueKind: ValueKind.Frozen,
434
}),
435
- ]
435
+ ],
436
);
437
438
export type Global = BuiltInType | PolyType;
@@ -442,7 +442,7 @@ export const DEFAULT_GLOBALS: GlobalRegistry = new Map(REACT_APIS);
442
// Hack until we add ObjectShapes for all globals
443
for (const name of UNTYPED_GLOBALS) {
444
DEFAULT_GLOBALS.set(name, {
445
- kind: "Poly",
445
+ kind: 'Poly',
446
});
447
}
448
@@ -452,22 +452,22 @@ for (const [name, type_] of TYPED_GLOBALS) {
452
453
// Recursive global type
454
DEFAULT_GLOBALS.set(
455
- "globalThis",
456
- addObject(DEFAULT_SHAPES, "globalThis", TYPED_GLOBALS)
455
+ 'globalThis',
456
+ addObject(DEFAULT_SHAPES, 'globalThis', TYPED_GLOBALS),
457
);
458
459
export function installReAnimatedTypes(
460
globals: GlobalRegistry,
461
- registry: ShapeRegistry
461
+ registry: ShapeRegistry,
462
): void {
463
// hooks that freeze args and return frozen value
464
const frozenHooks = [
465
- "useFrameCallback",
466
- "useAnimatedStyle",
467
- "useAnimatedProps",
468
- "useAnimatedScrollHandler",
469
- "useAnimatedReaction",
470
- "useWorkletCallback",
465
+ 'useFrameCallback',
466
+ 'useAnimatedStyle',
467
+ 'useAnimatedProps',
468
+ 'useAnimatedScrollHandler',
469
+ 'useAnimatedReaction',
470
+ 'useWorkletCallback',
471
];
472
for (const hook of frozenHooks) {
473
globals.set(
@@ -475,12 +475,12 @@ export function installReAnimatedTypes(
475
addHook(registry, {
476
positionalParams: [],
477
restParam: Effect.Freeze,
478
- returnType: { kind: "Poly" },
478
+ returnType: {kind: 'Poly'},
479
returnValueKind: ValueKind.Frozen,
480
noAlias: true,
481
calleeEffect: Effect.Read,
482
- hookKind: "Custom",
483
- })
482
+ hookKind: 'Custom',
483
+ }),
484
);
485
}
486
@@ -488,31 +488,31 @@ export function installReAnimatedTypes(
488
* hooks that return a mutable value. ideally these should be modelled as a
489
* ref, but this works for now.
490
*/
491
- const mutableHooks = ["useSharedValue", "useDerivedValue"];
491
+ const mutableHooks = ['useSharedValue', 'useDerivedValue'];
492
for (const hook of mutableHooks) {
493
globals.set(
494
hook,
495
addHook(registry, {
496
positionalParams: [],
497
restParam: Effect.Freeze,
498
- returnType: { kind: "Poly" },
498
+ returnType: {kind: 'Poly'},
499
returnValueKind: ValueKind.Mutable,
500
noAlias: true,
501
calleeEffect: Effect.Read,
502
- hookKind: "Custom",
503
- })
502
+ hookKind: 'Custom',
503
+ }),
504
);
505
}
506
507
// functions that return mutable value
508
const funcs = [
509
- "withTiming",
510
- "withSpring",
511
- "createAnimatedPropAdapter",
512
- "withDecay",
513
- "withRepeat",
514
- "runOnUI",
515
- "executeOnUIRuntimeSync",
509
+ 'withTiming',
510
+ 'withSpring',
511
+ 'createAnimatedPropAdapter',
512
+ 'withDecay',
513
+ 'withRepeat',
514
+ 'runOnUI',
515
+ 'executeOnUIRuntimeSync',
516
];
517
for (const fn of funcs) {
518
globals.set(
@@ -520,11 +520,11 @@ export function installReAnimatedTypes(
520
addFunction(registry, [], {
521
positionalParams: [],
522
restParam: Effect.Read,
523
- returnType: { kind: "Poly" },
523
+ returnType: {kind: 'Poly'},
524
calleeEffect: Effect.Read,
525
returnValueKind: ValueKind.Mutable,
526
noAlias: true,
527
- })
527
+ }),
528
);
529
}
530
}
compiler/packages/babel-plugin-react-compiler/src/HIR/HIR.ts
+207
-207
@@ -5,13 +5,13 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { BindingKind } from "@babel/traverse";
9
-import * as t from "@babel/types";
10
-import { CompilerError, CompilerErrorDetailOptions } from "../CompilerError";
11
-import { assertExhaustive } from "../Utils/utils";
12
-import { Environment, ReactFunctionType } from "./Environment";
13
-import { HookKind } from "./ObjectShape";
14
-import { Type } from "./Types";
8
+import {BindingKind} from '@babel/traverse';
9
+import * as t from '@babel/types';
10
+import {CompilerError, CompilerErrorDetailOptions} from '../CompilerError';
11
+import {assertExhaustive} from '../Utils/utils';
12
+import {Environment, ReactFunctionType} from './Environment';
13
+import {HookKind} from './ObjectShape';
14
+import {Type} from './Types';
15
16
/*
17
* *******************************************************************************************
@@ -60,13 +60,13 @@ export type ReactiveFunction = {
60
};
61
62
export type ReactiveScopeBlock = {
63
- kind: "scope";
63
+ kind: 'scope';
64
scope: ReactiveScope;
65
instructions: ReactiveBlock;
66
};
67
68
export type PrunedReactiveScopeBlock = {
69
- kind: "pruned-scope";
69
+ kind: 'pruned-scope';
70
scope: ReactiveScope;
71
instructions: ReactiveBlock;
72
};
@@ -80,14 +80,14 @@ export type ReactiveStatement =
80
| PrunedReactiveScopeBlock;
81
82
export type ReactiveInstructionStatement = {
83
- kind: "instruction";
83
+ kind: 'instruction';
84
instruction: ReactiveInstruction;
85
};
86
87
export type ReactiveTerminalStatement<
88
Tterminal extends ReactiveTerminal = ReactiveTerminal,
89
> = {
90
- kind: "terminal";
90
+ kind: 'terminal';
91
terminal: Tterminal;
92
label: {
93
id: BlockId;
@@ -111,7 +111,7 @@ export type ReactiveValue =
111
| ReactiveFunctionValue;
112
113
export type ReactiveFunctionValue = {
114
- kind: "ReactiveFunctionValue";
114
+ kind: 'ReactiveFunctionValue';
115
fn: ReactiveFunction;
116
dependencies: Array<Place>;
117
returnType: t.FlowType | t.TSType | null;
@@ -119,15 +119,15 @@ export type ReactiveFunctionValue = {
119
};
120
121
export type ReactiveLogicalValue = {
122
- kind: "LogicalExpression";
123
- operator: t.LogicalExpression["operator"];
122
+ kind: 'LogicalExpression';
123
+ operator: t.LogicalExpression['operator'];
124
left: ReactiveValue;
125
right: ReactiveValue;
126
loc: SourceLocation;
127
};
128
129
export type ReactiveTernaryValue = {
130
- kind: "ConditionalExpression";
130
+ kind: 'ConditionalExpression';
131
test: ReactiveValue;
132
consequent: ReactiveValue;
133
alternate: ReactiveValue;
@@ -135,7 +135,7 @@ export type ReactiveTernaryValue = {
135
};
136
137
export type ReactiveSequenceValue = {
138
- kind: "SequenceExpression";
138
+ kind: 'SequenceExpression';
139
instructions: Array<ReactiveInstruction>;
140
id: InstructionId;
141
value: ReactiveValue;
@@ -143,7 +143,7 @@ export type ReactiveSequenceValue = {
143
};
144
145
export type ReactiveOptionalCallValue = {
146
- kind: "OptionalExpression";
146
+ kind: 'OptionalExpression';
147
id: InstructionId;
148
value: ReactiveValue;
149
optional: boolean;
@@ -166,48 +166,48 @@ export type ReactiveTerminal =
166
| ReactiveTryTerminal;
167
168
function _staticInvariantReactiveTerminalHasLocation(
169
- terminal: ReactiveTerminal
169
+ terminal: ReactiveTerminal,
170
): SourceLocation {
171
// If this fails, it is because a variant of ReactiveTerminal is missing a .loc - add it!
172
return terminal.loc;
173
}
174
175
function _staticInvariantReactiveTerminalHasInstructionId(
176
- terminal: ReactiveTerminal
176
+ terminal: ReactiveTerminal,
177
): InstructionId {
178
// If this fails, it is because a variant of ReactiveTerminal is missing a .id - add it!
179
return terminal.id;
180
}
181
182
-export type ReactiveTerminalTargetKind = "implicit" | "labeled" | "unlabeled";
182
+export type ReactiveTerminalTargetKind = 'implicit' | 'labeled' | 'unlabeled';
183
export type ReactiveBreakTerminal = {
184
- kind: "break";
184
+ kind: 'break';
185
target: BlockId;
186
id: InstructionId;
187
targetKind: ReactiveTerminalTargetKind;
188
loc: SourceLocation;
189
};
190
export type ReactiveContinueTerminal = {
191
- kind: "continue";
191
+ kind: 'continue';
192
target: BlockId;
193
id: InstructionId;
194
targetKind: ReactiveTerminalTargetKind;
195
loc: SourceLocation;
196
};
197
export type ReactiveReturnTerminal = {
198
- kind: "return";
198
+ kind: 'return';
199
value: Place;
200
id: InstructionId;
201
loc: SourceLocation;
202
};
203
export type ReactiveThrowTerminal = {
204
- kind: "throw";
204
+ kind: 'throw';
205
value: Place;
206
id: InstructionId;
207
loc: SourceLocation;
208
};
209
export type ReactiveSwitchTerminal = {
210
- kind: "switch";
210
+ kind: 'switch';
211
test: Place;
212
cases: Array<{
213
test: Place | null;
@@ -217,21 +217,21 @@ export type ReactiveSwitchTerminal = {
217
loc: SourceLocation;
218
};
219
export type ReactiveDoWhileTerminal = {
220
- kind: "do-while";
220
+ kind: 'do-while';
221
loop: ReactiveBlock;
222
test: ReactiveValue;
223
id: InstructionId;
224
loc: SourceLocation;
225
};
226
export type ReactiveWhileTerminal = {
227
- kind: "while";
227
+ kind: 'while';
228
test: ReactiveValue;
229
loop: ReactiveBlock;
230
id: InstructionId;
231
loc: SourceLocation;
232
};
233
export type ReactiveForTerminal = {
234
- kind: "for";
234
+ kind: 'for';
235
init: ReactiveValue;
236
test: ReactiveValue;
237
update: ReactiveValue | null;
@@ -240,7 +240,7 @@ export type ReactiveForTerminal = {
240
loc: SourceLocation;
241
};
242
export type ReactiveForOfTerminal = {
243
- kind: "for-of";
243
+ kind: 'for-of';
244
init: ReactiveValue;
245
test: ReactiveValue;
246
loop: ReactiveBlock;
@@ -248,14 +248,14 @@ export type ReactiveForOfTerminal = {
248
loc: SourceLocation;
249
};
250
export type ReactiveForInTerminal = {
251
- kind: "for-in";
251
+ kind: 'for-in';
252
init: ReactiveValue;
253
loop: ReactiveBlock;
254
id: InstructionId;
255
loc: SourceLocation;
256
};
257
export type ReactiveIfTerminal = {
258
- kind: "if";
258
+ kind: 'if';
259
test: Place;
260
consequent: ReactiveBlock;
261
alternate: ReactiveBlock | null;
@@ -263,13 +263,13 @@ export type ReactiveIfTerminal = {
263
loc: SourceLocation;
264
};
265
export type ReactiveLabelTerminal = {
266
- kind: "label";
266
+ kind: 'label';
267
block: ReactiveBlock;
268
id: InstructionId;
269
loc: SourceLocation;
270
};
271
export type ReactiveTryTerminal = {
272
- kind: "try";
272
+ kind: 'try';
273
block: ReactiveBlock;
274
handlerBinding: Place | null;
275
handler: ReactiveBlock;
@@ -295,15 +295,15 @@ export type HIRFunction = {
295
296
export type FunctionEffect =
297
| {
298
- kind: "GlobalMutation";
298
+ kind: 'GlobalMutation';
299
error: CompilerErrorDetailOptions;
300
}
301
| {
302
- kind: "ReactMutation";
302
+ kind: 'ReactMutation';
303
error: CompilerErrorDetailOptions;
304
}
305
| {
306
- kind: "ContextMutation";
306
+ kind: 'ContextMutation';
307
places: ReadonlySet<Place>;
308
effect: Effect;
309
loc: SourceLocation;
@@ -334,7 +334,7 @@ export type HIR = {
334
* an exception occurs, therefore the block model only represents explicit throw
335
* statements and not implicit exceptions which may occur.
336
*/
337
-export type BlockKind = "block" | "value" | "loop" | "sequence" | "catch";
337
+export type BlockKind = 'block' | 'value' | 'loop' | 'sequence' | 'catch';
338
339
/**
340
* Returns true for "block" and "catch" block kinds which correspond to statements
@@ -343,7 +343,7 @@ export type BlockKind = "block" | "value" | "loop" | "sequence" | "catch";
343
* Inverse of isExpressionBlockKind()
344
*/
345
export function isStatementBlockKind(kind: BlockKind): boolean {
346
- return kind === "block" || kind === "catch";
346
+ return kind === 'block' || kind === 'catch';
347
}
348
349
/**
@@ -394,24 +394,24 @@ export type Terminal =
394
| ReactiveScopeTerminal
395
| PrunedScopeTerminal;
396
397
-export type TerminalWithFallthrough = Terminal & { fallthrough: BlockId };
397
+export type TerminalWithFallthrough = Terminal & {fallthrough: BlockId};
398
399
function _staticInvariantTerminalHasLocation(
400
- terminal: Terminal
400
+ terminal: Terminal,
401
): SourceLocation {
402
// If this fails, it is because a variant of Terminal is missing a .loc - add it!
403
return terminal.loc;
404
}
405
406
function _staticInvariantTerminalHasInstructionId(
407
- terminal: Terminal
407
+ terminal: Terminal,
408
): InstructionId {
409
// If this fails, it is because a variant of Terminal is missing a .id - add it!
410
return terminal.id;
411
}
412
413
function _staticInvariantTerminalHasFallthrough(
414
- terminal: Terminal
414
+ terminal: Terminal,
415
): BlockId | never | undefined {
416
// If this fails, it is because a variant of Terminal is missing a fallthrough annotation
417
return terminal.fallthrough;
@@ -422,7 +422,7 @@ function _staticInvariantTerminalHasFallthrough(
422
* A terminal that couldn't be lowered correctly.
423
*/
424
export type UnsupportedTerminal = {
425
- kind: "unsupported";
425
+ kind: 'unsupported';
426
id: InstructionId;
427
loc: SourceLocation;
428
fallthrough?: never;
@@ -434,23 +434,23 @@ export type UnsupportedTerminal = {
434
* before reaching the fallthrough.
435
*/
436
export type UnreachableTerminal = {
437
- kind: "unreachable";
437
+ kind: 'unreachable';
438
id: InstructionId;
439
loc: SourceLocation;
440
fallthrough?: never;
441
};
442
443
export type ThrowTerminal = {
444
- kind: "throw";
444
+ kind: 'throw';
445
value: Place;
446
id: InstructionId;
447
loc: SourceLocation;
448
fallthrough?: never;
449
};
450
-export type Case = { test: Place | null; block: BlockId };
450
+export type Case = {test: Place | null; block: BlockId};
451
452
export type ReturnTerminal = {
453
- kind: "return";
453
+ kind: 'return';
454
loc: SourceLocation;
455
value: Place;
456
id: InstructionId;
@@ -458,7 +458,7 @@ export type ReturnTerminal = {
458
};
459
460
export type GotoTerminal = {
461
- kind: "goto";
461
+ kind: 'goto';
462
block: BlockId;
463
variant: GotoVariant;
464
id: InstructionId;
@@ -467,13 +467,13 @@ export type GotoTerminal = {
467
};
468
469
export enum GotoVariant {
470
- Break = "Break",
471
- Continue = "Continue",
472
- Try = "Try",
470
+ Break = 'Break',
471
+ Continue = 'Continue',
472
+ Try = 'Try',
473
}
474
475
export type IfTerminal = {
476
- kind: "if";
476
+ kind: 'if';
477
test: Place;
478
consequent: BlockId;
479
alternate: BlockId;
@@ -483,7 +483,7 @@ export type IfTerminal = {
483
};
484
485
export type BranchTerminal = {
486
- kind: "branch";
486
+ kind: 'branch';
487
test: Place;
488
consequent: BlockId;
489
alternate: BlockId;
@@ -493,7 +493,7 @@ export type BranchTerminal = {
493
};
494
495
export type SwitchTerminal = {
496
- kind: "switch";
496
+ kind: 'switch';
497
test: Place;
498
cases: Array<Case>;
499
fallthrough: BlockId;
@@ -502,7 +502,7 @@ export type SwitchTerminal = {
502
};
503
504
export type DoWhileTerminal = {
505
- kind: "do-while";
505
+ kind: 'do-while';
506
loop: BlockId;
507
test: BlockId;
508
fallthrough: BlockId;
@@ -511,7 +511,7 @@ export type DoWhileTerminal = {
511
};
512
513
export type WhileTerminal = {
514
- kind: "while";
514
+ kind: 'while';
515
loc: SourceLocation;
516
test: BlockId;
517
loop: BlockId;
@@ -520,7 +520,7 @@ export type WhileTerminal = {
520
};
521
522
export type ForTerminal = {
523
- kind: "for";
523
+ kind: 'for';
524
loc: SourceLocation;
525
init: BlockId;
526
test: BlockId;
@@ -531,7 +531,7 @@ export type ForTerminal = {
531
};
532
533
export type ForOfTerminal = {
534
- kind: "for-of";
534
+ kind: 'for-of';
535
loc: SourceLocation;
536
init: BlockId;
537
test: BlockId;
@@ -541,7 +541,7 @@ export type ForOfTerminal = {
541
};
542
543
export type ForInTerminal = {
544
- kind: "for-in";
544
+ kind: 'for-in';
545
loc: SourceLocation;
546
init: BlockId;
547
loop: BlockId;
@@ -550,8 +550,8 @@ export type ForInTerminal = {
550
};
551
552
export type LogicalTerminal = {
553
- kind: "logical";
554
- operator: t.LogicalExpression["operator"];
553
+ kind: 'logical';
554
+ operator: t.LogicalExpression['operator'];
555
test: BlockId;
556
fallthrough: BlockId;
557
id: InstructionId;
@@ -559,7 +559,7 @@ export type LogicalTerminal = {
559
};
560
561
export type TernaryTerminal = {
562
- kind: "ternary";
562
+ kind: 'ternary';
563
test: BlockId;
564
fallthrough: BlockId;
565
id: InstructionId;
@@ -567,7 +567,7 @@ export type TernaryTerminal = {
567
};
568
569
export type LabelTerminal = {
570
- kind: "label";
570
+ kind: 'label';
571
block: BlockId;
572
fallthrough: BlockId;
573
id: InstructionId;
@@ -575,7 +575,7 @@ export type LabelTerminal = {
575
};
576
577
export type OptionalTerminal = {
578
- kind: "optional";
578
+ kind: 'optional';
579
/*
580
* Specifies whether this node was optional. If false, it means that the original
581
* node was part of an optional chain but this specific item was non-optional.
@@ -590,7 +590,7 @@ export type OptionalTerminal = {
590
};
591
592
export type SequenceTerminal = {
593
- kind: "sequence";
593
+ kind: 'sequence';
594
block: BlockId;
595
fallthrough: BlockId;
596
id: InstructionId;
@@ -598,7 +598,7 @@ export type SequenceTerminal = {
598
};
599
600
export type TryTerminal = {
601
- kind: "try";
601
+ kind: 'try';
602
block: BlockId;
603
handlerBinding: Place | null;
604
handler: BlockId;
@@ -609,7 +609,7 @@ export type TryTerminal = {
609
};
610
611
export type MaybeThrowTerminal = {
612
- kind: "maybe-throw";
612
+ kind: 'maybe-throw';
613
continuation: BlockId;
614
handler: BlockId;
615
id: InstructionId;
@@ -618,7 +618,7 @@ export type MaybeThrowTerminal = {
618
};
619
620
export type ReactiveScopeTerminal = {
621
- kind: "scope";
621
+ kind: 'scope';
622
fallthrough: BlockId;
623
block: BlockId;
624
scope: ReactiveScope;
@@ -627,7 +627,7 @@ export type ReactiveScopeTerminal = {
627
};
628
629
export type PrunedScopeTerminal = {
630
- kind: "pruned-scope";
630
+ kind: 'pruned-scope';
631
fallthrough: BlockId;
632
block: BlockId;
633
scope: ReactiveScope;
@@ -671,7 +671,7 @@ export type LValuePattern = {
671
};
672
673
export type ArrayExpression = {
674
- kind: "ArrayExpression";
674
+ kind: 'ArrayExpression';
675
elements: Array<Place | SpreadPattern | Hole>;
676
loc: SourceLocation;
677
};
@@ -679,42 +679,42 @@ export type ArrayExpression = {
679
export type Pattern = ArrayPattern | ObjectPattern;
680
681
export type Hole = {
682
- kind: "Hole";
682
+ kind: 'Hole';
683
};
684
685
export type SpreadPattern = {
686
- kind: "Spread";
686
+ kind: 'Spread';
687
place: Place;
688
};
689
690
export type ArrayPattern = {
691
- kind: "ArrayPattern";
691
+ kind: 'ArrayPattern';
692
items: Array<Place | SpreadPattern | Hole>;
693
};
694
695
export type ObjectPattern = {
696
- kind: "ObjectPattern";
696
+ kind: 'ObjectPattern';
697
properties: Array<ObjectProperty | SpreadPattern>;
698
};
699
700
export type ObjectPropertyKey =
701
| {
702
- kind: "string";
702
+ kind: 'string';
703
name: string;
704
}
705
| {
706
- kind: "identifier";
706
+ kind: 'identifier';
707
name: string;
708
}
709
| {
710
- kind: "computed";
710
+ kind: 'computed';
711
name: Place;
712
};
713
714
export type ObjectProperty = {
715
- kind: "ObjectProperty";
715
+ kind: 'ObjectProperty';
716
key: ObjectPropertyKey;
717
- type: "property" | "method";
717
+ type: 'property' | 'method';
718
place: Place;
719
};
720
@@ -724,34 +724,34 @@ export type LoweredFunction = {
724
};
725
726
export type ObjectMethod = {
727
- kind: "ObjectMethod";
727
+ kind: 'ObjectMethod';
728
loc: SourceLocation;
729
loweredFunc: LoweredFunction;
730
};
731
732
export enum InstructionKind {
733
// const declaration
734
- Const = "Const",
734
+ Const = 'Const',
735
// let declaration
736
- Let = "Let",
736
+ Let = 'Let',
737
// assing a new value to a let binding
738
- Reassign = "Reassign",
738
+ Reassign = 'Reassign',
739
// catch clause binding
740
- Catch = "Catch",
740
+ Catch = 'Catch',
741
742
// hoisted const declarations
743
- HoistedConst = "HoistedConst",
743
+ HoistedConst = 'HoistedConst',
744
}
745
746
function _staticInvariantInstructionValueHasLocation(
747
- value: InstructionValue
747
+ value: InstructionValue,
748
): SourceLocation {
749
// If this fails, it is because a variant of InstructionValue is missing a .loc - add it!
750
return value.loc;
751
}
752
753
export type Phi = {
754
- kind: "Phi";
754
+ kind: 'Phi';
755
id: Identifier;
756
operands: Map<BlockId, Identifier>;
757
type: Type;
@@ -768,15 +768,15 @@ export type Phi = {
768
export type ManualMemoDependency = {
769
root:
770
| {
771
- kind: "NamedLocal";
771
+ kind: 'NamedLocal';
772
value: Place;
773
}
774
- | { kind: "Global"; identifierName: string };
774
+ | {kind: 'Global'; identifierName: string};
775
path: Array<string>;
776
};
777
778
export type StartMemoize = {
779
- kind: "StartMemoize";
779
+ kind: 'StartMemoize';
780
// Start/FinishMemoize markers should have matching ids
781
manualMemoId: number;
782
/**
@@ -787,7 +787,7 @@ export type StartMemoize = {
787
loc: SourceLocation;
788
};
789
export type FinishMemoize = {
790
- kind: "FinishMemoize";
790
+ kind: 'FinishMemoize';
791
// Start/FinishMemoize markers should have matching ids
792
manualMemoId: number;
793
decl: Place;
@@ -812,7 +812,7 @@ export type FinishMemoize = {
812
* is a FunctionType.
813
*/
814
export type MethodCall = {
815
- kind: "MethodCall";
815
+ kind: 'MethodCall';
816
receiver: Place;
817
property: Place;
818
args: Array<Place | SpreadPattern>;
@@ -820,7 +820,7 @@ export type MethodCall = {
820
};
821
822
export type CallExpression = {
823
- kind: "CallExpression";
823
+ kind: 'CallExpression';
824
callee: Place;
825
args: Array<Place | SpreadPattern>;
826
loc: SourceLocation;
@@ -828,7 +828,7 @@ export type CallExpression = {
828
};
829
830
export type LoadLocal = {
831
- kind: "LoadLocal";
831
+ kind: 'LoadLocal';
832
place: Place;
833
loc: SourceLocation;
834
};
@@ -845,18 +845,18 @@ export type LoadLocal = {
845
export type InstructionValue =
846
| LoadLocal
847
| {
848
- kind: "LoadContext";
848
+ kind: 'LoadContext';
849
place: Place;
850
loc: SourceLocation;
851
}
852
| {
853
- kind: "DeclareLocal";
853
+ kind: 'DeclareLocal';
854
lvalue: LValue;
855
type: t.FlowType | t.TSType | null;
856
loc: SourceLocation;
857
}
858
| {
859
- kind: "DeclareContext";
859
+ kind: 'DeclareContext';
860
lvalue: {
861
kind: InstructionKind.Let | InstructionKind.HoistedConst;
862
place: Place;
@@ -864,14 +864,14 @@ export type InstructionValue =
864
loc: SourceLocation;
865
}
866
| {
867
- kind: "StoreLocal";
867
+ kind: 'StoreLocal';
868
lvalue: LValue;
869
value: Place;
870
type: t.FlowType | t.TSType | null;
871
loc: SourceLocation;
872
}
873
| {
874
- kind: "StoreContext";
874
+ kind: 'StoreContext';
875
lvalue: {
876
kind: InstructionKind.Reassign;
877
place: Place;
@@ -881,20 +881,20 @@ export type InstructionValue =
881
}
882
| Destructure
883
| {
884
- kind: "Primitive";
884
+ kind: 'Primitive';
885
value: number | boolean | string | null | undefined;
886
loc: SourceLocation;
887
}
888
| JSXText
889
| {
890
- kind: "BinaryExpression";
891
- operator: Exclude<t.BinaryExpression["operator"], "|>">;
890
+ kind: 'BinaryExpression';
891
+ operator: Exclude<t.BinaryExpression['operator'], '|>'>;
892
left: Place;
893
right: Place;
894
loc: SourceLocation;
895
}
896
| {
897
- kind: "NewExpression";
897
+ kind: 'NewExpression';
898
callee: Place;
899
args: Array<Place | SpreadPattern>;
900
loc: SourceLocation;
@@ -902,20 +902,20 @@ export type InstructionValue =
902
| CallExpression
903
| MethodCall
904
| {
905
- kind: "UnaryExpression";
906
- operator: Exclude<t.UnaryExpression["operator"], "throw" | "delete">;
905
+ kind: 'UnaryExpression';
906
+ operator: Exclude<t.UnaryExpression['operator'], 'throw' | 'delete'>;
907
value: Place;
908
loc: SourceLocation;
909
}
910
| {
911
- kind: "TypeCastExpression";
911
+ kind: 'TypeCastExpression';
912
value: Place;
913
typeAnnotation: t.FlowType | t.TSType;
914
type: Type;
915
loc: SourceLocation;
916
}
917
| {
918
- kind: "JsxExpression";
918
+ kind: 'JsxExpression';
919
tag: Place | BuiltinTag;
920
props: Array<JsxAttribute>;
921
children: Array<Place> | null; // null === no children
@@ -924,21 +924,21 @@ export type InstructionValue =
924
closingLoc: SourceLocation;
925
}
926
| {
927
- kind: "ObjectExpression";
927
+ kind: 'ObjectExpression';
928
properties: Array<ObjectProperty | SpreadPattern>;
929
loc: SourceLocation;
930
}
931
| ObjectMethod
932
| ArrayExpression
933
- | { kind: "JsxFragment"; children: Array<Place>; loc: SourceLocation }
933
+ | {kind: 'JsxFragment'; children: Array<Place>; loc: SourceLocation}
934
| {
935
- kind: "RegExpLiteral";
935
+ kind: 'RegExpLiteral';
936
pattern: string;
937
flags: string;
938
loc: SourceLocation;
939
}
940
| {
941
- kind: "MetaProperty";
941
+ kind: 'MetaProperty';
942
meta: string;
943
property: string;
944
loc: SourceLocation;
@@ -946,7 +946,7 @@ export type InstructionValue =
946
947
// store `object.property = value`
948
| {
949
- kind: "PropertyStore";
949
+ kind: 'PropertyStore';
950
object: Place;
951
property: string;
952
value: Place;
@@ -956,7 +956,7 @@ export type InstructionValue =
956
| PropertyLoad
957
// `delete object.property`
958
| {
959
- kind: "PropertyDelete";
959
+ kind: 'PropertyDelete';
960
object: Place;
961
property: string;
962
loc: SourceLocation;
@@ -964,7 +964,7 @@ export type InstructionValue =
964
965
// store `object[index] = value` - like PropertyStore but with a dynamic property
966
| {
967
- kind: "ComputedStore";
967
+ kind: 'ComputedStore';
968
object: Place;
969
property: Place;
970
value: Place;
@@ -972,14 +972,14 @@ export type InstructionValue =
972
}
973
// load `object[index]` - like PropertyLoad but with a dynamic property
974
| {
975
- kind: "ComputedLoad";
975
+ kind: 'ComputedLoad';
976
object: Place;
977
property: Place;
978
loc: SourceLocation;
979
}
980
// `delete object[property]`
981
| {
982
- kind: "ComputedDelete";
982
+ kind: 'ComputedDelete';
983
object: Place;
984
property: Place;
985
loc: SourceLocation;
@@ -988,35 +988,35 @@ export type InstructionValue =
988
| StoreGlobal
989
| FunctionExpression
990
| {
991
- kind: "TaggedTemplateExpression";
991
+ kind: 'TaggedTemplateExpression';
992
tag: Place;
993
- value: { raw: string; cooked?: string };
993
+ value: {raw: string; cooked?: string};
994
loc: SourceLocation;
995
}
996
| {
997
- kind: "TemplateLiteral";
997
+ kind: 'TemplateLiteral';
998
subexprs: Array<Place>;
999
- quasis: Array<{ raw: string; cooked?: string }>;
999
+ quasis: Array<{raw: string; cooked?: string}>;
1000
loc: SourceLocation;
1001
}
1002
| {
1003
- kind: "Await";
1003
+ kind: 'Await';
1004
value: Place;
1005
loc: SourceLocation;
1006
}
1007
| {
1008
- kind: "GetIterator";
1008
+ kind: 'GetIterator';
1009
collection: Place; // the collection
1010
loc: SourceLocation;
1011
}
1012
| {
1013
- kind: "IteratorNext";
1013
+ kind: 'IteratorNext';
1014
iterator: Place; // the iterator created with GetIterator
1015
collection: Place; // the collection being iterated over (which may be an iterable or iterator)
1016
loc: SourceLocation;
1017
}
1018
| {
1019
- kind: "NextPropertyOf";
1019
+ kind: 'NextPropertyOf';
1020
value: Place; // the collection
1021
loc: SourceLocation;
1022
}
@@ -1026,9 +1026,9 @@ export type InstructionValue =
1026
* but evaluates to the value of <value> prior to the update.
1027
*/
1028
| {
1029
- kind: "PrefixUpdate";
1029
+ kind: 'PrefixUpdate';
1030
lvalue: Place;
1031
- operation: t.UpdateExpression["operator"];
1031
+ operation: t.UpdateExpression['operator'];
1032
value: Place;
1033
loc: SourceLocation;
1034
}
@@ -1038,14 +1038,14 @@ export type InstructionValue =
1038
* and evaluates to the value after the update
1039
*/
1040
| {
1041
- kind: "PostfixUpdate";
1041
+ kind: 'PostfixUpdate';
1042
lvalue: Place;
1043
- operation: t.UpdateExpression["operator"];
1043
+ operation: t.UpdateExpression['operator'];
1044
value: Place;
1045
loc: SourceLocation;
1046
}
1047
// `debugger` statement
1048
- | { kind: "Debugger"; loc: SourceLocation }
1048
+ | {kind: 'Debugger'; loc: SourceLocation}
1049
/*
1050
* Represents semantic information from useMemo/useCallback that the developer
1051
* has indicated a particular value should be memoized. This value is ignored
@@ -1063,17 +1063,17 @@ export type InstructionValue =
1063
* passing through in codegen.
1064
*/
1065
| {
1066
- kind: "UnsupportedNode";
1066
+ kind: 'UnsupportedNode';
1067
node: t.Node;
1068
loc: SourceLocation;
1069
};
1070
1071
export type JsxAttribute =
1072
- | { kind: "JsxSpreadAttribute"; argument: Place }
1073
- | { kind: "JsxAttribute"; name: string; place: Place };
1072
+ | {kind: 'JsxSpreadAttribute'; argument: Place}
1073
+ | {kind: 'JsxAttribute'; name: string; place: Place};
1074
1075
export type FunctionExpression = {
1076
- kind: "FunctionExpression";
1076
+ kind: 'FunctionExpression';
1077
name: string | null;
1078
loweredFunc: LoweredFunction;
1079
expr:
@@ -1084,7 +1084,7 @@ export type FunctionExpression = {
1084
};
1085
1086
export type Destructure = {
1087
- kind: "Destructure";
1087
+ kind: 'Destructure';
1088
lvalue: LValuePattern;
1089
value: Place;
1090
loc: SourceLocation;
@@ -1096,7 +1096,7 @@ export type Destructure = {
1096
* - a path into an identifier
1097
*/
1098
export type Place = {
1099
- kind: "Identifier";
1099
+ kind: 'Identifier';
1100
identifier: Identifier;
1101
effect: Effect;
1102
reactive: boolean;
@@ -1105,35 +1105,35 @@ export type Place = {
1105
1106
// A primitive value with a specific (constant) value.
1107
export type Primitive = {
1108
- kind: "Primitive";
1108
+ kind: 'Primitive';
1109
value: number | boolean | string | null | undefined;
1110
loc: SourceLocation;
1111
};
1112
1113
-export type JSXText = { kind: "JSXText"; value: string; loc: SourceLocation };
1113
+export type JSXText = {kind: 'JSXText'; value: string; loc: SourceLocation};
1114
1115
export type PropertyLoad = {
1116
- kind: "PropertyLoad";
1116
+ kind: 'PropertyLoad';
1117
object: Place;
1118
property: string;
1119
loc: SourceLocation;
1120
};
1121
1122
export type LoadGlobal = {
1123
- kind: "LoadGlobal";
1123
+ kind: 'LoadGlobal';
1124
binding: NonLocalBinding;
1125
loc: SourceLocation;
1126
};
1127
1128
export type StoreGlobal = {
1129
- kind: "StoreGlobal";
1129
+ kind: 'StoreGlobal';
1130
name: string;
1131
value: Place;
1132
loc: SourceLocation;
1133
};
1134
1135
export type BuiltinTag = {
1136
- kind: "BuiltinTag";
1136
+ kind: 'BuiltinTag';
1137
name: string;
1138
loc: SourceLocation;
1139
};
@@ -1151,26 +1151,26 @@ export type MutableRange = {
1151
1152
export type VariableBinding =
1153
// let, const, etc declared within the current component/hook
1154
- | { kind: "Identifier"; identifier: Identifier; bindingKind: BindingKind }
1154
+ | {kind: 'Identifier'; identifier: Identifier; bindingKind: BindingKind}
1155
// bindings declard outside the current component/hook
1156
| NonLocalBinding;
1157
1158
export type NonLocalBinding =
1159
// `import Foo from 'foo'`: name=Foo, module=foo
1160
- | { kind: "ImportDefault"; name: string; module: string }
1160
+ | {kind: 'ImportDefault'; name: string; module: string}
1161
// `import * as Foo from 'foo'`: name=Foo, module=foo
1162
- | { kind: "ImportNamespace"; name: string; module: string }
1162
+ | {kind: 'ImportNamespace'; name: string; module: string}
1163
// `import {bar as baz} from 'foo'`: name=baz, module=foo, imported=bar
1164
| {
1165
- kind: "ImportSpecifier";
1165
+ kind: 'ImportSpecifier';
1166
name: string;
1167
module: string;
1168
imported: string;
1169
}
1170
// let, const, function, etc declared in the module but outside the current component/hook
1171
- | { kind: "ModuleLocal"; name: string }
1171
+ | {kind: 'ModuleLocal'; name: string}
1172
// an unresolved binding
1173
- | { kind: "Global"; name: string };
1173
+ | {kind: 'Global'; name: string};
1174
1175
// Represents a user-defined variable (has a name) or a temporary variable (no name).
1176
export type Identifier = {
@@ -1193,8 +1193,8 @@ export type Identifier = {
1193
};
1194
1195
export type IdentifierName = ValidatedIdentifier | PromotedIdentifier;
1196
-export type ValidatedIdentifier = { kind: "named"; value: ValidIdentifierName };
1197
-export type PromotedIdentifier = { kind: "promoted"; value: string };
1196
+export type ValidatedIdentifier = {kind: 'named'; value: ValidIdentifierName};
1197
+export type PromotedIdentifier = {kind: 'promoted'; value: string};
1198
1199
/**
1200
* Simulated opaque type for identifier names to ensure values can only be created
@@ -1202,7 +1202,7 @@ export type PromotedIdentifier = { kind: "promoted"; value: string };
1202
*/
1203
const opaqueValidIdentifierName = Symbol();
1204
export type ValidIdentifierName = string & {
1205
- [opaqueValidIdentifierName]: "ValidIdentifierName";
1205
+ [opaqueValidIdentifierName]: 'ValidIdentifierName';
1206
};
1207
1208
/**
@@ -1218,7 +1218,7 @@ export function makeIdentifierName(name: string): ValidatedIdentifier {
1218
suggestions: null,
1219
});
1220
return {
1221
- kind: "named",
1221
+ kind: 'named',
1222
value: name as ValidIdentifierName,
1223
};
1224
}
@@ -1234,13 +1234,13 @@ export function promoteTemporary(identifier: Identifier): void {
1234
suggestions: null,
1235
});
1236
identifier.name = {
1237
- kind: "promoted",
1237
+ kind: 'promoted',
1238
value: `#t${identifier.id}`,
1239
};
1240
}
1241
1242
export function isPromotedTemporary(name: string): boolean {
1243
- return name.startsWith("#t");
1243
+ return name.startsWith('#t');
1244
}
1245
1246
/**
@@ -1255,13 +1255,13 @@ export function promoteTemporaryJsxTag(identifier: Identifier): void {
1255
suggestions: null,
1256
});
1257
identifier.name = {
1258
- kind: "promoted",
1258
+ kind: 'promoted',
1259
value: `#T${identifier.id}`,
1260
};
1261
}
1262
1263
export function isPromotedJsxTemporary(name: string): boolean {
1264
- return name.startsWith("#T");
1264
+ return name.startsWith('#T');
1265
}
1266
1267
export type AbstractValue = {
@@ -1277,39 +1277,39 @@ export enum ValueReason {
1277
/**
1278
* Defined outside the React function.
1279
*/
1280
- Global = "global",
1280
+ Global = 'global',
1281
1282
/**
1283
* Used in a JSX expression.
1284
*/
1285
- JsxCaptured = "jsx-captured",
1285
+ JsxCaptured = 'jsx-captured',
1286
1287
/**
1288
* Return value of a function with known frozen return value, e.g. `useState`.
1289
*/
1290
- KnownReturnSignature = "known-return-signature",
1290
+ KnownReturnSignature = 'known-return-signature',
1291
1292
/**
1293
* A value returned from `useContext`
1294
*/
1295
- Context = "context",
1295
+ Context = 'context',
1296
1297
/**
1298
* A value returned from `useState`
1299
*/
1300
- State = "state",
1300
+ State = 'state',
1301
1302
/**
1303
* A value returned from `useReducer`
1304
*/
1305
- ReducerState = "reducer-state",
1305
+ ReducerState = 'reducer-state',
1306
1307
/**
1308
* Props of a component or arguments of a hook.
1309
*/
1310
- ReactiveFunctionArgument = "reactive-function-argument",
1310
+ ReactiveFunctionArgument = 'reactive-function-argument',
1311
1312
- Other = "other",
1312
+ Other = 'other',
1313
}
1314
1315
/*
@@ -1317,24 +1317,24 @@ export enum ValueReason {
1317
* see the main docblock for the module for details.
1318
*/
1319
export enum ValueKind {
1320
- MaybeFrozen = "maybefrozen",
1321
- Frozen = "frozen",
1322
- Primitive = "primitive",
1323
- Global = "global",
1324
- Mutable = "mutable",
1325
- Context = "context",
1320
+ MaybeFrozen = 'maybefrozen',
1321
+ Frozen = 'frozen',
1322
+ Primitive = 'primitive',
1323
+ Global = 'global',
1324
+ Mutable = 'mutable',
1325
+ Context = 'context',
1326
}
1327
1328
// The effect with which a value is modified.
1329
export enum Effect {
1330
// Default value: not allowed after lifetime inference
1331
- Unknown = "<unknown>",
1331
+ Unknown = '<unknown>',
1332
// This reference freezes the value (corresponds to a place where codegen should emit a freeze instruction)
1333
- Freeze = "freeze",
1333
+ Freeze = 'freeze',
1334
// This reference reads the value
1335
- Read = "read",
1335
+ Read = 'read',
1336
// This reference reads and stores the value
1337
- Capture = "capture",
1337
+ Capture = 'capture',
1338
/*
1339
* This reference *may* write to (mutate) the value. This covers two similar cases:
1340
* - The compiler is being conservative and assuming that a value *may* be mutated
@@ -1343,20 +1343,20 @@ export enum Effect {
1343
* In both cases, we conservatively assume that mutable values will be mutated.
1344
* But we do not error if the value is known to be immutable.
1345
*/
1346
- ConditionallyMutate = "mutate?",
1346
+ ConditionallyMutate = 'mutate?',
1347
1348
/*
1349
* This reference *does* write to (mutate) the value. It is an error (invalid input)
1350
* if an immutable value flows into a location with this effect.
1351
*/
1352
- Mutate = "mutate",
1352
+ Mutate = 'mutate',
1353
// This reference may alias to (mutate) the value
1354
- Store = "store",
1354
+ Store = 'store',
1355
}
1356
1357
export function isMutableEffect(
1358
effect: Effect,
1359
- location: SourceLocation
1359
+ location: SourceLocation,
1360
): boolean {
1361
switch (effect) {
1362
case Effect.Capture:
@@ -1368,7 +1368,7 @@ export function isMutableEffect(
1368
1369
case Effect.Unknown: {
1370
CompilerError.invariant(false, {
1371
- reason: "Unexpected unknown effect",
1371
+ reason: 'Unexpected unknown effect',
1372
description: null,
1373
loc: location,
1374
suggestions: null,
@@ -1448,11 +1448,11 @@ export type ReactiveScopeDependency = {
1448
* accidentally.
1449
*/
1450
const opaqueBlockId = Symbol();
1451
-export type BlockId = number & { [opaqueBlockId]: "BlockId" };
1451
+export type BlockId = number & {[opaqueBlockId]: 'BlockId'};
1452
1453
export function makeBlockId(id: number): BlockId {
1454
CompilerError.invariant(id >= 0 && Number.isInteger(id), {
1455
- reason: "Expected block id to be a non-negative integer",
1455
+ reason: 'Expected block id to be a non-negative integer',
1456
description: null,
1457
loc: null,
1458
suggestions: null,
@@ -1465,11 +1465,11 @@ export function makeBlockId(id: number): BlockId {
1465
* accidentally.
1466
*/
1467
const opaqueScopeId = Symbol();
1468
-export type ScopeId = number & { [opaqueScopeId]: "ScopeId" };
1468
+export type ScopeId = number & {[opaqueScopeId]: 'ScopeId'};
1469
1470
export function makeScopeId(id: number): ScopeId {
1471
CompilerError.invariant(id >= 0 && Number.isInteger(id), {
1472
- reason: "Expected block id to be a non-negative integer",
1472
+ reason: 'Expected block id to be a non-negative integer',
1473
description: null,
1474
loc: null,
1475
suggestions: null,
@@ -1482,11 +1482,11 @@ export function makeScopeId(id: number): ScopeId {
1482
* accidentally.
1483
*/
1484
const opaqueIdentifierId = Symbol();
1485
-export type IdentifierId = number & { [opaqueIdentifierId]: "IdentifierId" };
1485
+export type IdentifierId = number & {[opaqueIdentifierId]: 'IdentifierId'};
1486
1487
export function makeIdentifierId(id: number): IdentifierId {
1488
CompilerError.invariant(id >= 0 && Number.isInteger(id), {
1489
- reason: "Expected identifier id to be a non-negative integer",
1489
+ reason: 'Expected identifier id to be a non-negative integer',
1490
description: null,
1491
loc: null,
1492
suggestions: null,
@@ -1499,11 +1499,11 @@ export function makeIdentifierId(id: number): IdentifierId {
1499
* accidentally.
1500
*/
1501
const opaqueInstructionId = Symbol();
1502
-export type InstructionId = number & { [opaqueInstructionId]: "IdentifierId" };
1502
+export type InstructionId = number & {[opaqueInstructionId]: 'IdentifierId'};
1503
1504
export function makeInstructionId(id: number): InstructionId {
1505
CompilerError.invariant(id >= 0 && Number.isInteger(id), {
1506
- reason: "Expected instruction id to be a non-negative integer",
1506
+ reason: 'Expected instruction id to be a non-negative integer',
1507
description: null,
1508
loc: null,
1509
suggestions: null,
@@ -1512,55 +1512,55 @@ export function makeInstructionId(id: number): InstructionId {
1512
}
1513
1514
export function isObjectMethodType(id: Identifier): boolean {
1515
- return id.type.kind == "ObjectMethod";
1515
+ return id.type.kind == 'ObjectMethod';
1516
}
1517
1518
export function isObjectType(id: Identifier): boolean {
1519
- return id.type.kind === "Object";
1519
+ return id.type.kind === 'Object';
1520
}
1521
1522
export function isPrimitiveType(id: Identifier): boolean {
1523
- return id.type.kind === "Primitive";
1523
+ return id.type.kind === 'Primitive';
1524
}
1525
1526
export function isArrayType(id: Identifier): boolean {
1527
- return id.type.kind === "Object" && id.type.shapeId === "BuiltInArray";
1527
+ return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInArray';
1528
}
1529
1530
export function isRefValueType(id: Identifier): boolean {
1531
- return id.type.kind === "Object" && id.type.shapeId === "BuiltInRefValue";
1531
+ return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInRefValue';
1532
}
1533
1534
export function isUseRefType(id: Identifier): boolean {
1535
- return id.type.kind === "Object" && id.type.shapeId === "BuiltInUseRefId";
1535
+ return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInUseRefId';
1536
}
1537
1538
export function isUseStateType(id: Identifier): boolean {
1539
- return id.type.kind === "Object" && id.type.shapeId === "BuiltInUseState";
1539
+ return id.type.kind === 'Object' && id.type.shapeId === 'BuiltInUseState';
1540
}
1541
1542
export function isSetStateType(id: Identifier): boolean {
1543
- return id.type.kind === "Function" && id.type.shapeId === "BuiltInSetState";
1543
+ return id.type.kind === 'Function' && id.type.shapeId === 'BuiltInSetState';
1544
}
1545
1546
export function isUseActionStateType(id: Identifier): boolean {
1547
return (
1548
- id.type.kind === "Object" && id.type.shapeId === "BuiltInUseActionState"
1548
+ id.type.kind === 'Object' && id.type.shapeId === 'BuiltInUseActionState'
1549
);
1550
}
1551
1552
export function isSetActionStateType(id: Identifier): boolean {
1553
return (
1554
- id.type.kind === "Function" && id.type.shapeId === "BuiltInSetActionState"
1554
+ id.type.kind === 'Function' && id.type.shapeId === 'BuiltInSetActionState'
1555
);
1556
}
1557
1558
export function isUseReducerType(id: Identifier): boolean {
1559
- return id.type.kind === "Function" && id.type.shapeId === "BuiltInUseReducer";
1559
+ return id.type.kind === 'Function' && id.type.shapeId === 'BuiltInUseReducer';
1560
}
1561
1562
export function isDispatcherType(id: Identifier): boolean {
1563
- return id.type.kind === "Function" && id.type.shapeId === "BuiltInDispatch";
1563
+ return id.type.kind === 'Function' && id.type.shapeId === 'BuiltInDispatch';
1564
}
1565
1566
export function isStableType(id: Identifier): boolean {
@@ -1569,19 +1569,19 @@ export function isStableType(id: Identifier): boolean {
1569
1570
export function isUseEffectHookType(id: Identifier): boolean {
1571
return (
1572
- id.type.kind === "Function" && id.type.shapeId === "BuiltInUseEffectHook"
1572
+ id.type.kind === 'Function' && id.type.shapeId === 'BuiltInUseEffectHook'
1573
);
1574
}
1575
export function isUseLayoutEffectHookType(id: Identifier): boolean {
1576
return (
1577
- id.type.kind === "Function" &&
1578
- id.type.shapeId === "BuiltInUseLayoutEffectHook"
1577
+ id.type.kind === 'Function' &&
1578
+ id.type.shapeId === 'BuiltInUseLayoutEffectHook'
1579
);
1580
}
1581
export function isUseInsertionEffectHookType(id: Identifier): boolean {
1582
return (
1583
- id.type.kind === "Function" &&
1584
- id.type.shapeId === "BuiltInUseInsertionEffectHook"
1583
+ id.type.kind === 'Function' &&
1584
+ id.type.shapeId === 'BuiltInUseInsertionEffectHook'
1585
);
1586
}
1587
@@ -1591,19 +1591,19 @@ export function getHookKind(env: Environment, id: Identifier): HookKind | null {
1591
1592
export function isUseOperator(id: Identifier): boolean {
1593
return (
1594
- id.type.kind === "Function" && id.type.shapeId === "BuiltInUseOperator"
1594
+ id.type.kind === 'Function' && id.type.shapeId === 'BuiltInUseOperator'
1595
);
1596
}
1597
1598
export function getHookKindForType(
1599
env: Environment,
1600
- type: Type
1600
+ type: Type,
1601
): HookKind | null {
1602
- if (type.kind === "Function") {
1602
+ if (type.kind === 'Function') {
1603
const signature = env.getFunctionSignature(type);
1604
return signature?.hookKind ?? null;
1605
}
1606
return null;
1607
}
1608
1609
-export * from "./Types";
1609
+export * from './Types';
compiler/packages/babel-plugin-react-compiler/src/HIR/HIRBuilder.ts
+67
-67
@@ -5,10 +5,10 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { Binding, NodePath } from "@babel/traverse";
9
-import * as t from "@babel/types";
10
-import { CompilerError } from "../CompilerError";
11
-import { Environment } from "./Environment";
8
+import {Binding, NodePath} from '@babel/traverse';
9
+import * as t from '@babel/types';
10
+import {CompilerError} from '../CompilerError';
11
+import {Environment} from './Environment';
12
import {
13
BasicBlock,
14
BlockId,
@@ -28,13 +28,13 @@ import {
28
makeIdentifierName,
29
makeInstructionId,
30
makeType,
31
-} from "./HIR";
32
-import { printInstruction } from "./PrintHIR";
31
+} from './HIR';
32
+import {printInstruction} from './PrintHIR';
33
import {
34
eachTerminalSuccessor,
35
mapTerminalSuccessors,
36
terminalFallthrough,
37
-} from "./visitors";
37
+} from './visitors';
38
39
/*
40
* *******************************************************************************************
@@ -54,31 +54,31 @@ export type WipBlock = {
54
type Scope = LoopScope | LabelScope | SwitchScope;
55
56
type LoopScope = {
57
- kind: "loop";
57
+ kind: 'loop';
58
label: string | null;
59
continueBlock: BlockId;
60
breakBlock: BlockId;
61
};
62
63
type SwitchScope = {
64
- kind: "switch";
64
+ kind: 'switch';
65
breakBlock: BlockId;
66
label: string | null;
67
};
68
69
type LabelScope = {
70
- kind: "label";
70
+ kind: 'label';
71
label: string;
72
breakBlock: BlockId;
73
};
74
75
function newBlock(id: BlockId, kind: BlockKind): WipBlock {
76
- return { id, kind, instructions: [] };
76
+ return {id, kind, instructions: []};
77
}
78
79
export type Bindings = Map<
80
string,
81
- { node: t.Identifier; identifier: Identifier }
81
+ {node: t.Identifier; identifier: Identifier}
82
>;
83
84
/*
@@ -90,13 +90,13 @@ export type ExceptionsMode =
90
* Mode used for code not covered by explicit exception handling, any
91
* errors are assumed to be thrown out of the function
92
*/
93
- | { kind: "ThrowExceptions" }
93
+ | {kind: 'ThrowExceptions'}
94
/*
95
* Mode used for code that *is* covered by explicit exception handling
96
* (ie try/catch), which requires modeling the possibility of control
97
* flow to the exception handler.
98
*/
99
- | { kind: "CatchExceptions"; handler: BlockId };
99
+ | {kind: 'CatchExceptions'; handler: BlockId};
100
101
// Helper class for constructing a CFG
102
export default class HIRBuilder {
@@ -131,14 +131,14 @@ export default class HIRBuilder {
131
env: Environment,
132
parentFunction: NodePath<t.Function>, // the outermost function being compiled
133
bindings: Bindings | null = null,
134
- context: Array<t.Identifier> | null = null
134
+ context: Array<t.Identifier> | null = null,
135
) {
136
this.#env = env;
137
this.#bindings = bindings ?? new Map();
138
this.parentFunction = parentFunction;
139
this.#context = context ?? [];
140
this.#entry = makeBlockId(env.nextBlockId);
141
- this.#current = newBlock(this.#entry, "block");
141
+ this.#current = newBlock(this.#entry, 'block');
142
}
143
144
currentBlockKind(): BlockKind {
@@ -153,13 +153,13 @@ export default class HIRBuilder {
153
const continuationBlock = this.reserve(this.currentBlockKind());
154
this.terminateWithContinuation(
155
{
156
- kind: "maybe-throw",
156
+ kind: 'maybe-throw',
157
continuation: continuationBlock.id,
158
handler: exceptionHandler,
159
id: makeInstructionId(0),
160
loc: instruction.loc,
161
},
162
- continuationBlock
162
+ continuationBlock,
163
);
164
}
165
}
@@ -180,7 +180,7 @@ export default class HIRBuilder {
180
return {
181
id,
182
name: null,
183
- mutableRange: { start: makeInstructionId(0), end: makeInstructionId(0) },
183
+ mutableRange: {start: makeInstructionId(0), end: makeInstructionId(0)},
184
scope: null,
185
type: makeType(),
186
loc,
@@ -188,7 +188,7 @@ export default class HIRBuilder {
188
}
189
190
#resolveBabelBinding(
191
- path: NodePath<t.Identifier | t.JSXIdentifier>
191
+ path: NodePath<t.Identifier | t.JSXIdentifier>,
192
): Binding | null {
193
const originalName = path.node.name;
194
const binding = path.scope.getBinding(originalName);
@@ -229,12 +229,12 @@ export default class HIRBuilder {
229
* ```
230
*/
231
resolveIdentifier(
232
- path: NodePath<t.Identifier | t.JSXIdentifier>
232
+ path: NodePath<t.Identifier | t.JSXIdentifier>,
233
): VariableBinding {
234
const originalName = path.node.name;
235
const babelBinding = this.#resolveBabelBinding(path);
236
if (babelBinding == null) {
237
- return { kind: "Global", name: originalName };
237
+ return {kind: 'Global', name: originalName};
238
}
239
240
// Check if the binding is from module scope
@@ -246,7 +246,7 @@ export default class HIRBuilder {
246
const importDeclaration =
247
path.parentPath as NodePath<t.ImportDeclaration>;
248
return {
249
- kind: "ImportDefault",
249
+ kind: 'ImportDefault',
250
name: originalName,
251
module: importDeclaration.node.source.value,
252
};
@@ -254,11 +254,11 @@ export default class HIRBuilder {
254
const importDeclaration =
255
path.parentPath as NodePath<t.ImportDeclaration>;
256
return {
257
- kind: "ImportSpecifier",
257
+ kind: 'ImportSpecifier',
258
name: originalName,
259
module: importDeclaration.node.source.value,
260
imported:
261
- path.node.imported.type === "Identifier"
261
+ path.node.imported.type === 'Identifier'
262
? path.node.imported.name
263
: path.node.imported.value,
264
};
@@ -266,13 +266,13 @@ export default class HIRBuilder {
266
const importDeclaration =
267
path.parentPath as NodePath<t.ImportDeclaration>;
268
return {
269
- kind: "ImportNamespace",
269
+ kind: 'ImportNamespace',
270
name: originalName,
271
module: importDeclaration.node.source.value,
272
};
273
} else {
274
return {
275
- kind: "ModuleLocal",
275
+ kind: 'ModuleLocal',
276
name: originalName,
277
};
278
}
@@ -283,7 +283,7 @@ export default class HIRBuilder {
283
babelBinding.scope.rename(originalName, resolvedBinding.name.value);
284
}
285
return {
286
- kind: "Identifier",
286
+ kind: 'Identifier',
287
identifier: resolvedBinding,
288
bindingKind: babelBinding.kind,
289
};
@@ -294,7 +294,7 @@ export default class HIRBuilder {
294
if (binding) {
295
// Check if the binding is from module scope, if so return null
296
const outerBinding = this.parentFunction.scope.parent.getBinding(
297
- path.node.name
297
+ path.node.name,
298
);
299
if (binding === outerBinding) {
300
return false;
@@ -324,7 +324,7 @@ export default class HIRBuilder {
324
type: makeType(),
325
loc: node.loc ?? GeneratedSource,
326
};
327
- this.#bindings.set(name, { node, identifier });
327
+ this.#bindings.set(name, {node, identifier});
328
return identifier;
329
} else if (mapping.node === node) {
330
return mapping.identifier;
@@ -345,7 +345,7 @@ export default class HIRBuilder {
345
if (
346
!rpoBlocks.has(id) &&
347
block.instructions.some(
348
- (instr) => instr.value.kind === "FunctionExpression"
348
+ instr => instr.value.kind === 'FunctionExpression',
349
)
350
) {
351
CompilerError.throwTodo({
@@ -369,7 +369,7 @@ export default class HIRBuilder {
369
370
// Terminate the current block w the given terminal, and start a new block
371
terminate(terminal: Terminal, nextBlockKind: BlockKind | null): void {
372
- const { id: blockId, kind, instructions } = this.#current;
372
+ const {id: blockId, kind, instructions} = this.#current;
373
this.#completed.set(blockId, {
374
kind,
375
id: blockId,
@@ -389,7 +389,7 @@ export default class HIRBuilder {
389
* reserved block as the new current block
390
*/
391
terminateWithContinuation(terminal: Terminal, continuation: WipBlock): void {
392
- const { id: blockId, kind, instructions } = this.#current;
392
+ const {id: blockId, kind, instructions} = this.#current;
393
this.#completed.set(blockId, {
394
kind: kind,
395
id: blockId,
@@ -412,7 +412,7 @@ export default class HIRBuilder {
412
413
// Save a previously reserved block as completed
414
complete(block: WipBlock, terminal: Terminal): void {
415
- const { id: blockId, kind, instructions } = block;
415
+ const {id: blockId, kind, instructions} = block;
416
this.#completed.set(blockId, {
417
kind,
418
id: blockId,
@@ -431,7 +431,7 @@ export default class HIRBuilder {
431
const current = this.#current;
432
this.#current = wip;
433
const terminal = fn();
434
- const { id: blockId, kind, instructions } = this.#current;
434
+ const {id: blockId, kind, instructions} = this.#current;
435
this.#completed.set(blockId, {
436
kind,
437
id: blockId,
@@ -459,7 +459,7 @@ export default class HIRBuilder {
459
460
label<T>(label: string, breakBlock: BlockId, fn: () => T): T {
461
this.#scopes.push({
462
- kind: "label",
462
+ kind: 'label',
463
breakBlock,
464
label,
465
});
@@ -467,22 +467,22 @@ export default class HIRBuilder {
467
const last = this.#scopes.pop();
468
CompilerError.invariant(
469
last != null &&
470
- last.kind === "label" &&
470
+ last.kind === 'label' &&
471
last.label === label &&
472
last.breakBlock === breakBlock,
473
{
474
- reason: "Mismatched label",
474
+ reason: 'Mismatched label',
475
description: null,
476
loc: null,
477
suggestions: null,
478
- }
478
+ },
479
);
480
return value;
481
}
482
483
switch<T>(label: string | null, breakBlock: BlockId, fn: () => T): T {
484
this.#scopes.push({
485
- kind: "switch",
485
+ kind: 'switch',
486
breakBlock,
487
label,
488
});
@@ -490,15 +490,15 @@ export default class HIRBuilder {
490
const last = this.#scopes.pop();
491
CompilerError.invariant(
492
last != null &&
493
- last.kind === "switch" &&
493
+ last.kind === 'switch' &&
494
last.label === label &&
495
last.breakBlock === breakBlock,
496
{
497
- reason: "Mismatched label",
497
+ reason: 'Mismatched label',
498
description: null,
499
loc: null,
500
suggestions: null,
501
- }
501
+ },
502
);
503
return value;
504
}
@@ -513,10 +513,10 @@ export default class HIRBuilder {
513
continueBlock: BlockId,
514
// block following the loop. "break" jumps here.
515
breakBlock: BlockId,
516
- fn: () => T
516
+ fn: () => T,
517
): T {
518
this.#scopes.push({
519
- kind: "loop",
519
+ kind: 'loop',
520
label,
521
continueBlock,
522
breakBlock,
@@ -525,16 +525,16 @@ export default class HIRBuilder {
525
const last = this.#scopes.pop();
526
CompilerError.invariant(
527
last != null &&
528
- last.kind === "loop" &&
528
+ last.kind === 'loop' &&
529
last.label === label &&
530
last.continueBlock === continueBlock &&
531
last.breakBlock === breakBlock,
532
{
533
- reason: "Mismatched loops",
533
+ reason: 'Mismatched loops',
534
description: null,
535
loc: null,
536
suggestions: null,
537
- }
537
+ },
538
);
539
return value;
540
}
@@ -548,14 +548,14 @@ export default class HIRBuilder {
548
const scope = this.#scopes[ii];
549
if (
550
(label === null &&
551
- (scope.kind === "loop" || scope.kind === "switch")) ||
551
+ (scope.kind === 'loop' || scope.kind === 'switch')) ||
552
label === scope.label
553
) {
554
return scope.breakBlock;
555
}
556
}
557
CompilerError.invariant(false, {
558
- reason: "Expected a loop or switch to be in scope",
558
+ reason: 'Expected a loop or switch to be in scope',
559
description: null,
560
loc: null,
561
suggestions: null,
@@ -570,13 +570,13 @@ export default class HIRBuilder {
570
lookupContinue(label: string | null): BlockId {
571
for (let ii = this.#scopes.length - 1; ii >= 0; ii--) {
572
const scope = this.#scopes[ii];
573
- if (scope.kind === "loop") {
573
+ if (scope.kind === 'loop') {
574
if (label === null || label === scope.label) {
575
return scope.continueBlock;
576
}
577
} else if (label !== null && scope.label === label) {
578
CompilerError.invariant(false, {
579
- reason: "Continue may only refer to a labeled loop",
579
+ reason: 'Continue may only refer to a labeled loop',
580
description: null,
581
loc: null,
582
suggestions: null,
@@ -584,7 +584,7 @@ export default class HIRBuilder {
584
}
585
}
586
CompilerError.invariant(false, {
587
- reason: "Expected a loop to be in scope",
587
+ reason: 'Expected a loop to be in scope',
588
description: null,
589
loc: null,
590
suggestions: null,
@@ -633,7 +633,7 @@ function _shrink(func: HIR): void {
633
}
634
reachable.add(blockId);
635
const block = func.blocks.get(blockId)!;
636
- block.terminal = mapTerminalSuccessors(block.terminal, (prevTarget) => {
636
+ block.terminal = mapTerminalSuccessors(block.terminal, prevTarget => {
637
const target = resolveBlockTarget(prevTarget);
638
queue.push(target);
639
return target;
@@ -649,7 +649,7 @@ function _shrink(func: HIR): void {
649
export function removeUnreachableForUpdates(fn: HIR): void {
650
for (const [, block] of fn.blocks) {
651
if (
652
- block.terminal.kind === "for" &&
652
+ block.terminal.kind === 'for' &&
653
block.terminal.update !== null &&
654
!fn.blocks.has(block.terminal.update)
655
) {
@@ -670,10 +670,10 @@ export function removeDeadDoWhileStatements(func: HIR): void {
670
* MergeConsecutiveBlocks figures out how to merge as appropriate.
671
*/
672
for (const [_, block] of func.blocks) {
673
- if (block.terminal.kind === "do-while") {
673
+ if (block.terminal.kind === 'do-while') {
674
if (!visited.has(block.terminal.test)) {
675
block.terminal = {
676
- kind: "goto",
676
+ kind: 'goto',
677
block: block.terminal.loop,
678
variant: GotoVariant.Break,
679
id: block.terminal.id,
@@ -700,7 +700,7 @@ export function reversePostorderBlocks(func: HIR): void {
700
* may be in the output: blocks will be removed in the case of unreachable code in
701
* the input.
702
*/
703
-function getReversePostorderedBlocks(func: HIR): HIR["blocks"] {
703
+function getReversePostorderedBlocks(func: HIR): HIR['blocks'] {
704
const visited: Set<BlockId> = new Set();
705
const used: Set<BlockId> = new Set();
706
const usedFallthroughs: Set<BlockId> = new Set();
@@ -772,7 +772,7 @@ function getReversePostorderedBlocks(func: HIR): HIR["blocks"] {
772
...block,
773
instructions: [],
774
terminal: {
775
- kind: "unreachable",
775
+ kind: 'unreachable',
776
id: block.terminal.id,
777
loc: block.terminal.loc,
778
},
@@ -813,7 +813,7 @@ export function markPredecessors(func: HIR): void {
813
return;
814
}
815
CompilerError.invariant(block != null, {
816
- reason: "unexpected missing block",
816
+ reason: 'unexpected missing block',
817
description: `block ${blockId}`,
818
loc: GeneratedSource,
819
});
@@ -826,7 +826,7 @@ export function markPredecessors(func: HIR): void {
826
}
827
visited.add(blockId);
828
829
- const { terminal } = block;
829
+ const {terminal} = block;
830
831
for (const successor of eachTerminalSuccessor(terminal)) {
832
visit(successor, block);
@@ -841,7 +841,7 @@ export function markPredecessors(func: HIR): void {
841
*/
842
function getTargetIfIndirection(block: BasicBlock): number | null {
843
return block.instructions.length === 0 &&
844
- block.terminal.kind === "goto" &&
844
+ block.terminal.kind === 'goto' &&
845
block.terminal.variant === GotoVariant.Break
846
? block.terminal.block
847
: null;
@@ -854,14 +854,14 @@ function getTargetIfIndirection(block: BasicBlock): number | null {
854
export function removeUnnecessaryTryCatch(fn: HIR): void {
855
for (const [, block] of fn.blocks) {
856
if (
857
- block.terminal.kind === "try" &&
857
+ block.terminal.kind === 'try' &&
858
!fn.blocks.has(block.terminal.handler)
859
) {
860
const handlerId = block.terminal.handler;
861
const fallthroughId = block.terminal.fallthrough;
862
const fallthrough = fn.blocks.get(fallthroughId);
863
block.terminal = {
864
- kind: "goto",
864
+ kind: 'goto',
865
block: block.terminal.block,
866
id: makeInstructionId(0),
867
loc: block.terminal.loc,
@@ -882,13 +882,13 @@ export function removeUnnecessaryTryCatch(fn: HIR): void {
882
883
export function createTemporaryPlace(
884
env: Environment,
885
- loc: SourceLocation
885
+ loc: SourceLocation,
886
): Place {
887
return {
888
- kind: "Identifier",
888
+ kind: 'Identifier',
889
identifier: {
890
id: env.nextIdentifierId,
891
- mutableRange: { start: makeInstructionId(0), end: makeInstructionId(0) },
891
+ mutableRange: {start: makeInstructionId(0), end: makeInstructionId(0)},
892
name: null,
893
scope: null,
894
type: makeType(),
compiler/packages/babel-plugin-react-compiler/src/HIR/MergeConsecutiveBlocks.ts
+12
-12
@@ -5,16 +5,16 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
8
+import {CompilerError} from '../CompilerError';
9
import {
10
BlockId,
11
Effect,
12
GeneratedSource,
13
HIRFunction,
14
Instruction,
15
-} from "./HIR";
16
-import { markPredecessors } from "./HIRBuilder";
17
-import { terminalFallthrough, terminalHasFallthrough } from "./visitors";
15
+} from './HIR';
16
+import {markPredecessors} from './HIRBuilder';
17
+import {terminalFallthrough, terminalHasFallthrough} from './visitors';
18
19
/*
20
* Merges sequences of blocks that will always execute consecutively —
@@ -39,8 +39,8 @@ export function mergeConsecutiveBlocks(fn: HIRFunction): void {
39
40
for (const instr of block.instructions) {
41
if (
42
- instr.value.kind === "FunctionExpression" ||
43
- instr.value.kind === "ObjectMethod"
42
+ instr.value.kind === 'FunctionExpression' ||
43
+ instr.value.kind === 'ObjectMethod'
44
) {
45
mergeConsecutiveBlocks(instr.value.loweredFunc.func);
46
}
@@ -50,7 +50,7 @@ export function mergeConsecutiveBlocks(fn: HIRFunction): void {
50
// Can only merge blocks with a single predecessor
51
block.preds.size !== 1 ||
52
// Value blocks cannot merge
53
- block.kind !== "block" ||
53
+ block.kind !== 'block' ||
54
// Merging across fallthroughs could move the predecessor out of its block scope
55
fallthroughBlocks.has(block.id)
56
) {
@@ -65,7 +65,7 @@ export function mergeConsecutiveBlocks(fn: HIRFunction): void {
65
loc: null,
66
suggestions: null,
67
});
68
- if (predecessor.terminal.kind !== "goto" || predecessor.kind !== "block") {
68
+ if (predecessor.terminal.kind !== 'goto' || predecessor.kind !== 'block') {
69
/*
70
* The predecessor is not guaranteed to transfer control to this block,
71
* they aren't consecutive.
@@ -85,16 +85,16 @@ export function mergeConsecutiveBlocks(fn: HIRFunction): void {
85
const instr: Instruction = {
86
id: predecessor.terminal.id,
87
lvalue: {
88
- kind: "Identifier",
88
+ kind: 'Identifier',
89
identifier: phi.id,
90
effect: Effect.ConditionallyMutate,
91
reactive: false,
92
loc: GeneratedSource,
93
},
94
value: {
95
- kind: "LoadLocal",
95
+ kind: 'LoadLocal',
96
place: {
97
- kind: "Identifier",
97
+ kind: 'Identifier',
98
identifier: operand,
99
effect: Effect.Read,
100
reactive: false,
@@ -113,7 +113,7 @@ export function mergeConsecutiveBlocks(fn: HIRFunction): void {
113
fn.body.blocks.delete(block.id);
114
}
115
markPredecessors(fn.body);
116
- for (const [, { terminal }] of fn.body.blocks) {
116
+ for (const [, {terminal}] of fn.body.blocks) {
117
if (terminalHasFallthrough(terminal)) {
118
terminal.fallthrough = merged.get(terminal.fallthrough);
119
}
compiler/packages/babel-plugin-react-compiler/src/HIR/MergeOverlappingReactiveScopesHIR.ts
+20
-20
@@ -4,16 +4,16 @@ import {
4
Place,
5
ReactiveScope,
6
makeInstructionId,
7
-} from ".";
8
-import { getPlaceScope } from "../ReactiveScopes/BuildReactiveBlocks";
9
-import { isMutable } from "../ReactiveScopes/InferReactiveScopeVariables";
10
-import DisjointSet from "../Utils/DisjointSet";
11
-import { getOrInsertDefault } from "../Utils/utils";
7
+} from '.';
8
+import {getPlaceScope} from '../ReactiveScopes/BuildReactiveBlocks';
9
+import {isMutable} from '../ReactiveScopes/InferReactiveScopeVariables';
10
+import DisjointSet from '../Utils/DisjointSet';
11
+import {getOrInsertDefault} from '../Utils/utils';
12
import {
13
eachInstructionLValue,
14
eachInstructionOperand,
15
eachTerminalOperand,
16
-} from "./visitors";
16
+} from './visitors';
17
18
/**
19
* While previous passes ensure that reactive scopes span valid sets of program
@@ -113,10 +113,10 @@ export function mergeOverlappingReactiveScopesHIR(fn: HIRFunction): void {
113
joinedScopes.forEach((scope, groupScope) => {
114
if (scope !== groupScope) {
115
groupScope.range.start = makeInstructionId(
116
- Math.min(groupScope.range.start, scope.range.start)
116
+ Math.min(groupScope.range.start, scope.range.start),
117
);
118
groupScope.range.end = makeInstructionId(
119
- Math.max(groupScope.range.end, scope.range.end)
119
+ Math.max(groupScope.range.end, scope.range.end),
120
);
121
}
122
});
@@ -129,8 +129,8 @@ export function mergeOverlappingReactiveScopesHIR(fn: HIRFunction): void {
129
}
130
131
type ScopeInfo = {
132
- scopeStarts: Array<{ id: InstructionId; scopes: Set<ReactiveScope> }>;
133
- scopeEnds: Array<{ id: InstructionId; scopes: Set<ReactiveScope> }>;
132
+ scopeStarts: Array<{id: InstructionId; scopes: Set<ReactiveScope>}>;
133
+ scopeEnds: Array<{id: InstructionId; scopes: Set<ReactiveScope>}>;
134
placeScopes: Map<Place, ReactiveScope>;
135
};
136
@@ -150,7 +150,7 @@ function collectScopeInfo(fn: HIRFunction): ScopeInfo {
150
placeScopes.set(place, scope);
151
if (scope.range.start !== scope.range.end) {
152
getOrInsertDefault(scopeStarts, scope.range.start, new Set()).add(
153
- scope
153
+ scope,
154
);
155
getOrInsertDefault(scopeEnds, scope.range.end, new Set()).add(scope);
156
}
@@ -173,10 +173,10 @@ function collectScopeInfo(fn: HIRFunction): ScopeInfo {
173
174
return {
175
scopeStarts: [...scopeStarts.entries()]
176
- .map(([id, scopes]) => ({ id, scopes }))
176
+ .map(([id, scopes]) => ({id, scopes}))
177
.sort((a, b) => b.id - a.id),
178
scopeEnds: [...scopeEnds.entries()]
179
- .map(([id, scopes]) => ({ id, scopes }))
179
+ .map(([id, scopes]) => ({id, scopes}))
180
.sort((a, b) => b.id - a.id),
181
placeScopes,
182
};
@@ -184,8 +184,8 @@ function collectScopeInfo(fn: HIRFunction): ScopeInfo {
184
185
function visitInstructionId(
186
id: InstructionId,
187
- { scopeEnds, scopeStarts }: ScopeInfo,
188
- { activeScopes, joined }: TraversalState
187
+ {scopeEnds, scopeStarts}: ScopeInfo,
188
+ {activeScopes, joined}: TraversalState,
189
): void {
190
/**
191
* Handle all scopes that end at this instruction.
@@ -200,7 +200,7 @@ function visitInstructionId(
200
* order of start IDs because the scopes stack is ordered as such
201
*/
202
const scopesSortedStartDescending = [...scopeEndTop.scopes].sort(
203
- (a, b) => b.range.start - a.range.start
203
+ (a, b) => b.range.start - a.range.start,
204
);
205
for (const scope of scopesSortedStartDescending) {
206
const idx = activeScopes.indexOf(scope);
@@ -227,7 +227,7 @@ function visitInstructionId(
227
scopeStarts.pop();
228
229
const scopesSortedEndDescending = [...scopeStartTop.scopes].sort(
230
- (a, b) => b.range.end - a.range.end
230
+ (a, b) => b.range.end - a.range.end,
231
);
232
activeScopes.push(...scopesSortedEndDescending);
233
/**
@@ -247,14 +247,14 @@ function visitInstructionId(
247
function visitPlace(
248
id: InstructionId,
249
place: Place,
250
- { activeScopes, joined }: TraversalState
250
+ {activeScopes, joined}: TraversalState,
251
): void {
252
/**
253
* If an instruction mutates an outer scope, flatten all scopes from the top
254
* of the stack to the mutated outer scope.
255
*/
256
const placeScope = getPlaceScope(id, place);
257
- if (placeScope != null && isMutable({ id } as any, place)) {
257
+ if (placeScope != null && isMutable({id} as any, place)) {
258
const placeScopeIdx = activeScopes.indexOf(placeScope);
259
if (placeScopeIdx !== -1 && placeScopeIdx !== activeScopes.length - 1) {
260
joined.union([placeScope, ...activeScopes.slice(placeScopeIdx + 1)]);
@@ -264,7 +264,7 @@ function visitPlace(
264
265
function getOverlappingReactiveScopes(
266
fn: HIRFunction,
267
- context: ScopeInfo
267
+ context: ScopeInfo,
268
): DisjointSet<ReactiveScope> {
269
const state: TraversalState = {
270
joined: new DisjointSet<ReactiveScope>(),
compiler/packages/babel-plugin-react-compiler/src/HIR/ObjectShape.ts
+107
-107
@@ -5,15 +5,15 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
9
-import { Effect, ValueKind, ValueReason } from "./HIR";
8
+import {CompilerError} from '../CompilerError';
9
+import {Effect, ValueKind, ValueReason} from './HIR';
10
import {
11
BuiltInType,
12
FunctionType,
13
ObjectType,
14
PolyType,
15
PrimitiveType,
16
-} from "./Types";
16
+} from './Types';
17
18
/*
19
* This file exports types and defaults for JavaScript object shapes. These are
@@ -22,7 +22,7 @@ import {
22
*/
23
24
const PRIMITIVE_TYPE: PrimitiveType = {
25
- kind: "Primitive",
25
+ kind: 'Primitive',
26
};
27
28
let nextAnonId = 0;
@@ -42,8 +42,8 @@ function createAnonId(): string {
42
export function addFunction(
43
registry: ShapeRegistry,
44
properties: Iterable<[string, BuiltInType | PolyType]>,
45
- fn: Omit<FunctionSignature, "hookKind">,
46
- id: string | null = null
45
+ fn: Omit<FunctionSignature, 'hookKind'>,
46
+ id: string | null = null,
47
): FunctionType {
48
const shapeId = id ?? createAnonId();
49
addShape(registry, shapeId, properties, {
@@ -51,7 +51,7 @@ export function addFunction(
51
hookKind: null,
52
});
53
return {
54
- kind: "Function",
54
+ kind: 'Function',
55
return: fn.returnType,
56
shapeId,
57
};
@@ -64,13 +64,13 @@ export function addFunction(
64
*/
65
export function addHook(
66
registry: ShapeRegistry,
67
- fn: FunctionSignature & { hookKind: HookKind },
68
- id: string | null = null
67
+ fn: FunctionSignature & {hookKind: HookKind},
68
+ id: string | null = null,
69
): FunctionType {
70
const shapeId = id ?? createAnonId();
71
addShape(registry, shapeId, [], fn);
72
return {
73
- kind: "Function",
73
+ kind: 'Function',
74
return: fn.returnType,
75
shapeId,
76
};
@@ -84,12 +84,12 @@ export function addHook(
84
export function addObject(
85
registry: ShapeRegistry,
86
id: string | null,
87
- properties: Iterable<[string, BuiltInType | PolyType]>
87
+ properties: Iterable<[string, BuiltInType | PolyType]>,
88
): ObjectType {
89
const shapeId = id ?? createAnonId();
90
addShape(registry, shapeId, properties, null);
91
return {
92
- kind: "Object",
92
+ kind: 'Object',
93
shapeId,
94
};
95
}
@@ -98,7 +98,7 @@ function addShape(
98
registry: ShapeRegistry,
99
id: string,
100
properties: Iterable<[string, BuiltInType | PolyType]>,
101
- functionType: FunctionSignature | null
101
+ functionType: FunctionSignature | null,
102
): ObjectShape {
103
const shape: ObjectShape = {
104
properties: new Map(properties),
@@ -116,17 +116,17 @@ function addShape(
116
}
117
118
export type HookKind =
119
- | "useContext"
120
- | "useState"
121
- | "useActionState"
122
- | "useReducer"
123
- | "useRef"
124
- | "useEffect"
125
- | "useLayoutEffect"
126
- | "useInsertionEffect"
127
- | "useMemo"
128
- | "useCallback"
129
- | "Custom";
119
+ | 'useContext'
120
+ | 'useState'
121
+ | 'useActionState'
122
+ | 'useReducer'
123
+ | 'useRef'
124
+ | 'useEffect'
125
+ | 'useLayoutEffect'
126
+ | 'useInsertionEffect'
127
+ | 'useMemo'
128
+ | 'useCallback'
129
+ | 'Custom';
130
131
/*
132
* Call signature of a function, used for type and effect inference.
@@ -190,91 +190,91 @@ export type ObjectShape = {
190
* the inferred types for [] and {}.
191
*/
192
export type ShapeRegistry = Map<string, ObjectShape>;
193
-export const BuiltInPropsId = "BuiltInProps";
194
-export const BuiltInArrayId = "BuiltInArray";
195
-export const BuiltInFunctionId = "BuiltInFunction";
196
-export const BuiltInJsxId = "BuiltInJsx";
197
-export const BuiltInObjectId = "BuiltInObject";
198
-export const BuiltInUseStateId = "BuiltInUseState";
199
-export const BuiltInSetStateId = "BuiltInSetState";
200
-export const BuiltInUseActionStateId = "BuiltInUseActionState";
201
-export const BuiltInSetActionStateId = "BuiltInSetActionState";
202
-export const BuiltInUseRefId = "BuiltInUseRefId";
203
-export const BuiltInRefValueId = "BuiltInRefValue";
204
-export const BuiltInMixedReadonlyId = "BuiltInMixedReadonly";
205
-export const BuiltInUseEffectHookId = "BuiltInUseEffectHook";
206
-export const BuiltInUseLayoutEffectHookId = "BuiltInUseLayoutEffectHook";
207
-export const BuiltInUseInsertionEffectHookId = "BuiltInUseInsertionEffectHook";
208
-export const BuiltInUseOperatorId = "BuiltInUseOperator";
209
-export const BuiltInUseReducerId = "BuiltInUseReducer";
210
-export const BuiltInDispatchId = "BuiltInDispatch";
193
+export const BuiltInPropsId = 'BuiltInProps';
194
+export const BuiltInArrayId = 'BuiltInArray';
195
+export const BuiltInFunctionId = 'BuiltInFunction';
196
+export const BuiltInJsxId = 'BuiltInJsx';
197
+export const BuiltInObjectId = 'BuiltInObject';
198
+export const BuiltInUseStateId = 'BuiltInUseState';
199
+export const BuiltInSetStateId = 'BuiltInSetState';
200
+export const BuiltInUseActionStateId = 'BuiltInUseActionState';
201
+export const BuiltInSetActionStateId = 'BuiltInSetActionState';
202
+export const BuiltInUseRefId = 'BuiltInUseRefId';
203
+export const BuiltInRefValueId = 'BuiltInRefValue';
204
+export const BuiltInMixedReadonlyId = 'BuiltInMixedReadonly';
205
+export const BuiltInUseEffectHookId = 'BuiltInUseEffectHook';
206
+export const BuiltInUseLayoutEffectHookId = 'BuiltInUseLayoutEffectHook';
207
+export const BuiltInUseInsertionEffectHookId = 'BuiltInUseInsertionEffectHook';
208
+export const BuiltInUseOperatorId = 'BuiltInUseOperator';
209
+export const BuiltInUseReducerId = 'BuiltInUseReducer';
210
+export const BuiltInDispatchId = 'BuiltInDispatch';
211
212
// ShapeRegistry with default definitions for built-ins.
213
export const BUILTIN_SHAPES: ShapeRegistry = new Map();
214
215
// If the `ref` prop exists, it has the ref type
216
addObject(BUILTIN_SHAPES, BuiltInPropsId, [
217
- ["ref", { kind: "Object", shapeId: BuiltInUseRefId }],
217
+ ['ref', {kind: 'Object', shapeId: BuiltInUseRefId}],
218
]);
219
220
/* Built-in array shape */
221
addObject(BUILTIN_SHAPES, BuiltInArrayId, [
222
[
223
- "indexOf",
223
+ 'indexOf',
224
addFunction(BUILTIN_SHAPES, [], {
225
positionalParams: [],
226
restParam: Effect.Read,
227
- returnType: { kind: "Primitive" },
227
+ returnType: {kind: 'Primitive'},
228
calleeEffect: Effect.Read,
229
returnValueKind: ValueKind.Primitive,
230
}),
231
],
232
[
233
- "includes",
233
+ 'includes',
234
addFunction(BUILTIN_SHAPES, [], {
235
positionalParams: [],
236
restParam: Effect.Read,
237
- returnType: { kind: "Primitive" },
237
+ returnType: {kind: 'Primitive'},
238
calleeEffect: Effect.Read,
239
returnValueKind: ValueKind.Primitive,
240
}),
241
],
242
[
243
- "pop",
243
+ 'pop',
244
addFunction(BUILTIN_SHAPES, [], {
245
positionalParams: [],
246
restParam: null,
247
- returnType: { kind: "Poly" },
247
+ returnType: {kind: 'Poly'},
248
calleeEffect: Effect.Store,
249
returnValueKind: ValueKind.Mutable,
250
}),
251
],
252
[
253
- "at",
253
+ 'at',
254
addFunction(BUILTIN_SHAPES, [], {
255
positionalParams: [Effect.Read],
256
restParam: null,
257
- returnType: { kind: "Poly" },
257
+ returnType: {kind: 'Poly'},
258
calleeEffect: Effect.Capture,
259
returnValueKind: ValueKind.Mutable,
260
}),
261
],
262
[
263
- "concat",
263
+ 'concat',
264
addFunction(BUILTIN_SHAPES, [], {
265
positionalParams: [],
266
restParam: Effect.Capture,
267
returnType: {
268
- kind: "Object",
268
+ kind: 'Object',
269
shapeId: BuiltInArrayId,
270
},
271
calleeEffect: Effect.Capture,
272
returnValueKind: ValueKind.Mutable,
273
}),
274
],
275
- ["length", PRIMITIVE_TYPE],
275
+ ['length', PRIMITIVE_TYPE],
276
[
277
- "push",
277
+ 'push',
278
addFunction(BUILTIN_SHAPES, [], {
279
positionalParams: [],
280
restParam: Effect.Capture,
@@ -284,12 +284,12 @@ addObject(BUILTIN_SHAPES, BuiltInArrayId, [
284
}),
285
],
286
[
287
- "slice",
287
+ 'slice',
288
addFunction(BUILTIN_SHAPES, [], {
289
positionalParams: [],
290
restParam: Effect.Read,
291
returnType: {
292
- kind: "Object",
292
+ kind: 'Object',
293
shapeId: BuiltInArrayId,
294
},
295
calleeEffect: Effect.Capture,
@@ -297,11 +297,11 @@ addObject(BUILTIN_SHAPES, BuiltInArrayId, [
297
}),
298
],
299
[
300
- "map",
300
+ 'map',
301
addFunction(BUILTIN_SHAPES, [], {
302
positionalParams: [],
303
restParam: Effect.ConditionallyMutate,
304
- returnType: { kind: "Object", shapeId: BuiltInArrayId },
304
+ returnType: {kind: 'Object', shapeId: BuiltInArrayId},
305
/*
306
* callee is ConditionallyMutate because items of the array
307
* flow into the lambda and may be mutated there, even though
@@ -314,11 +314,11 @@ addObject(BUILTIN_SHAPES, BuiltInArrayId, [
314
}),
315
],
316
[
317
- "filter",
317
+ 'filter',
318
addFunction(BUILTIN_SHAPES, [], {
319
positionalParams: [],
320
restParam: Effect.ConditionallyMutate,
321
- returnType: { kind: "Object", shapeId: BuiltInArrayId },
321
+ returnType: {kind: 'Object', shapeId: BuiltInArrayId},
322
/*
323
* callee is ConditionallyMutate because items of the array
324
* flow into the lambda and may be mutated there, even though
@@ -331,11 +331,11 @@ addObject(BUILTIN_SHAPES, BuiltInArrayId, [
331
}),
332
],
333
[
334
- "every",
334
+ 'every',
335
addFunction(BUILTIN_SHAPES, [], {
336
positionalParams: [],
337
restParam: Effect.ConditionallyMutate,
338
- returnType: { kind: "Primitive" },
338
+ returnType: {kind: 'Primitive'},
339
/*
340
* callee is ConditionallyMutate because items of the array
341
* flow into the lambda and may be mutated there, even though
@@ -348,11 +348,11 @@ addObject(BUILTIN_SHAPES, BuiltInArrayId, [
348
}),
349
],
350
[
351
- "some",
351
+ 'some',
352
addFunction(BUILTIN_SHAPES, [], {
353
positionalParams: [],
354
restParam: Effect.ConditionallyMutate,
355
- returnType: { kind: "Primitive" },
355
+ returnType: {kind: 'Primitive'},
356
/*
357
* callee is ConditionallyMutate because items of the array
358
* flow into the lambda and may be mutated there, even though
@@ -365,11 +365,11 @@ addObject(BUILTIN_SHAPES, BuiltInArrayId, [
365
}),
366
],
367
[
368
- "find",
368
+ 'find',
369
addFunction(BUILTIN_SHAPES, [], {
370
positionalParams: [],
371
restParam: Effect.ConditionallyMutate,
372
- returnType: { kind: "Poly" },
372
+ returnType: {kind: 'Poly'},
373
calleeEffect: Effect.ConditionallyMutate,
374
returnValueKind: ValueKind.Mutable,
375
noAlias: true,
@@ -377,11 +377,11 @@ addObject(BUILTIN_SHAPES, BuiltInArrayId, [
377
}),
378
],
379
[
380
- "findIndex",
380
+ 'findIndex',
381
addFunction(BUILTIN_SHAPES, [], {
382
positionalParams: [],
383
restParam: Effect.ConditionallyMutate,
384
- returnType: { kind: "Primitive" },
384
+ returnType: {kind: 'Primitive'},
385
/*
386
* callee is ConditionallyMutate because items of the array
387
* flow into the lambda and may be mutated there, even though
@@ -394,7 +394,7 @@ addObject(BUILTIN_SHAPES, BuiltInArrayId, [
394
}),
395
],
396
[
397
- "join",
397
+ 'join',
398
addFunction(BUILTIN_SHAPES, [], {
399
positionalParams: [],
400
restParam: Effect.Read,
@@ -409,7 +409,7 @@ addObject(BUILTIN_SHAPES, BuiltInArrayId, [
409
/* Built-in Object shape */
410
addObject(BUILTIN_SHAPES, BuiltInObjectId, [
411
[
412
- "toString",
412
+ 'toString',
413
addFunction(BUILTIN_SHAPES, [], {
414
positionalParams: [],
415
restParam: null,
@@ -425,9 +425,9 @@ addObject(BUILTIN_SHAPES, BuiltInObjectId, [
425
]);
426
427
addObject(BUILTIN_SHAPES, BuiltInUseStateId, [
428
- ["0", { kind: "Poly" }],
428
+ ['0', {kind: 'Poly'}],
429
[
430
- "1",
430
+ '1',
431
addFunction(
432
BUILTIN_SHAPES,
433
[],
@@ -438,15 +438,15 @@ addObject(BUILTIN_SHAPES, BuiltInUseStateId, [
438
calleeEffect: Effect.Read,
439
returnValueKind: ValueKind.Primitive,
440
},
441
- BuiltInSetStateId
441
+ BuiltInSetStateId,
442
),
443
],
444
]);
445
446
addObject(BUILTIN_SHAPES, BuiltInUseActionStateId, [
447
- ["0", { kind: "Poly" }],
447
+ ['0', {kind: 'Poly'}],
448
[
449
- "1",
449
+ '1',
450
addFunction(
451
BUILTIN_SHAPES,
452
[],
@@ -457,15 +457,15 @@ addObject(BUILTIN_SHAPES, BuiltInUseActionStateId, [
457
calleeEffect: Effect.Read,
458
returnValueKind: ValueKind.Primitive,
459
},
460
- BuiltInSetActionStateId
460
+ BuiltInSetActionStateId,
461
),
462
],
463
]);
464
465
addObject(BUILTIN_SHAPES, BuiltInUseReducerId, [
466
- ["0", { kind: "Poly" }],
466
+ ['0', {kind: 'Poly'}],
467
[
468
- "1",
468
+ '1',
469
addFunction(
470
BUILTIN_SHAPES,
471
[],
@@ -476,22 +476,22 @@ addObject(BUILTIN_SHAPES, BuiltInUseReducerId, [
476
calleeEffect: Effect.Read,
477
returnValueKind: ValueKind.Primitive,
478
},
479
- BuiltInDispatchId
479
+ BuiltInDispatchId,
480
),
481
],
482
]);
483
484
addObject(BUILTIN_SHAPES, BuiltInUseRefId, [
485
- ["current", { kind: "Object", shapeId: BuiltInRefValueId }],
485
+ ['current', {kind: 'Object', shapeId: BuiltInRefValueId}],
486
]);
487
488
addObject(BUILTIN_SHAPES, BuiltInRefValueId, [
489
- ["*", { kind: "Object", shapeId: BuiltInRefValueId }],
489
+ ['*', {kind: 'Object', shapeId: BuiltInRefValueId}],
490
]);
491
492
addObject(BUILTIN_SHAPES, BuiltInMixedReadonlyId, [
493
[
494
- "toString",
494
+ 'toString',
495
addFunction(BUILTIN_SHAPES, [], {
496
positionalParams: [],
497
restParam: Effect.Read,
@@ -501,34 +501,34 @@ addObject(BUILTIN_SHAPES, BuiltInMixedReadonlyId, [
501
}),
502
],
503
[
504
- "map",
504
+ 'map',
505
addFunction(BUILTIN_SHAPES, [], {
506
positionalParams: [],
507
restParam: Effect.Read,
508
- returnType: { kind: "Object", shapeId: BuiltInArrayId },
508
+ returnType: {kind: 'Object', shapeId: BuiltInArrayId},
509
calleeEffect: Effect.ConditionallyMutate,
510
returnValueKind: ValueKind.Mutable,
511
noAlias: true,
512
}),
513
],
514
[
515
- "filter",
515
+ 'filter',
516
addFunction(BUILTIN_SHAPES, [], {
517
positionalParams: [],
518
restParam: Effect.Read,
519
- returnType: { kind: "Object", shapeId: BuiltInArrayId },
519
+ returnType: {kind: 'Object', shapeId: BuiltInArrayId},
520
calleeEffect: Effect.ConditionallyMutate,
521
returnValueKind: ValueKind.Mutable,
522
noAlias: true,
523
}),
524
],
525
[
526
- "concat",
526
+ 'concat',
527
addFunction(BUILTIN_SHAPES, [], {
528
positionalParams: [],
529
restParam: Effect.Capture,
530
returnType: {
531
- kind: "Object",
531
+ kind: 'Object',
532
shapeId: BuiltInArrayId,
533
},
534
calleeEffect: Effect.Capture,
@@ -536,12 +536,12 @@ addObject(BUILTIN_SHAPES, BuiltInMixedReadonlyId, [
536
}),
537
],
538
[
539
- "slice",
539
+ 'slice',
540
addFunction(BUILTIN_SHAPES, [], {
541
positionalParams: [],
542
restParam: Effect.Read,
543
returnType: {
544
- kind: "Object",
544
+ kind: 'Object',
545
shapeId: BuiltInArrayId,
546
},
547
calleeEffect: Effect.Capture,
@@ -549,11 +549,11 @@ addObject(BUILTIN_SHAPES, BuiltInMixedReadonlyId, [
549
}),
550
],
551
[
552
- "every",
552
+ 'every',
553
addFunction(BUILTIN_SHAPES, [], {
554
positionalParams: [],
555
restParam: Effect.ConditionallyMutate,
556
- returnType: { kind: "Primitive" },
556
+ returnType: {kind: 'Primitive'},
557
calleeEffect: Effect.ConditionallyMutate,
558
returnValueKind: ValueKind.Primitive,
559
noAlias: true,
@@ -561,11 +561,11 @@ addObject(BUILTIN_SHAPES, BuiltInMixedReadonlyId, [
561
}),
562
],
563
[
564
- "some",
564
+ 'some',
565
addFunction(BUILTIN_SHAPES, [], {
566
positionalParams: [],
567
restParam: Effect.ConditionallyMutate,
568
- returnType: { kind: "Primitive" },
568
+ returnType: {kind: 'Primitive'},
569
calleeEffect: Effect.ConditionallyMutate,
570
returnValueKind: ValueKind.Primitive,
571
noAlias: true,
@@ -573,11 +573,11 @@ addObject(BUILTIN_SHAPES, BuiltInMixedReadonlyId, [
573
}),
574
],
575
[
576
- "find",
576
+ 'find',
577
addFunction(BUILTIN_SHAPES, [], {
578
positionalParams: [],
579
restParam: Effect.ConditionallyMutate,
580
- returnType: { kind: "Poly" },
580
+ returnType: {kind: 'Poly'},
581
calleeEffect: Effect.ConditionallyMutate,
582
returnValueKind: ValueKind.Mutable,
583
noAlias: true,
@@ -585,11 +585,11 @@ addObject(BUILTIN_SHAPES, BuiltInMixedReadonlyId, [
585
}),
586
],
587
[
588
- "findIndex",
588
+ 'findIndex',
589
addFunction(BUILTIN_SHAPES, [], {
590
positionalParams: [],
591
restParam: Effect.ConditionallyMutate,
592
- returnType: { kind: "Primitive" },
592
+ returnType: {kind: 'Primitive'},
593
calleeEffect: Effect.ConditionallyMutate,
594
returnValueKind: ValueKind.Primitive,
595
noAlias: true,
@@ -597,7 +597,7 @@ addObject(BUILTIN_SHAPES, BuiltInMixedReadonlyId, [
597
}),
598
],
599
[
600
- "join",
600
+ 'join',
601
addFunction(BUILTIN_SHAPES, [], {
602
positionalParams: [],
603
restParam: Effect.Read,
@@ -606,7 +606,7 @@ addObject(BUILTIN_SHAPES, BuiltInMixedReadonlyId, [
606
returnValueKind: ValueKind.Primitive,
607
}),
608
],
609
- ["*", { kind: "Object", shapeId: BuiltInMixedReadonlyId }],
609
+ ['*', {kind: 'Object', shapeId: BuiltInMixedReadonlyId}],
610
]);
611
612
addObject(BUILTIN_SHAPES, BuiltInJsxId, []);
@@ -617,12 +617,12 @@ export const DefaultMutatingHook = addHook(
617
{
618
positionalParams: [],
619
restParam: Effect.ConditionallyMutate,
620
- returnType: { kind: "Poly" },
620
+ returnType: {kind: 'Poly'},
621
calleeEffect: Effect.Read,
622
- hookKind: "Custom",
622
+ hookKind: 'Custom',
623
returnValueKind: ValueKind.Mutable,
624
},
625
- "DefaultMutatingHook"
625
+ 'DefaultMutatingHook',
626
);
627
628
export const DefaultNonmutatingHook = addHook(
@@ -630,10 +630,10 @@ export const DefaultNonmutatingHook = addHook(
630
{
631
positionalParams: [],
632
restParam: Effect.Freeze,
633
- returnType: { kind: "Poly" },
633
+ returnType: {kind: 'Poly'},
634
calleeEffect: Effect.Read,
635
- hookKind: "Custom",
635
+ hookKind: 'Custom',
636
returnValueKind: ValueKind.Frozen,
637
},
638
- "DefaultNonmutatingHook"
638
+ 'DefaultNonmutatingHook',
639
);
compiler/packages/babel-plugin-react-compiler/src/HIR/PrintHIR.ts
+247
-247
@@ -5,12 +5,12 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import generate from "@babel/generator";
9
-import { printReactiveFunction } from "..";
10
-import { CompilerError } from "../CompilerError";
11
-import { printReactiveScopeSummary } from "../ReactiveScopes/PrintReactiveFunction";
12
-import DisjointSet from "../Utils/DisjointSet";
13
-import { assertExhaustive } from "../Utils/utils";
8
+import generate from '@babel/generator';
9
+import {printReactiveFunction} from '..';
10
+import {CompilerError} from '../CompilerError';
11
+import {printReactiveScopeSummary} from '../ReactiveScopes/PrintReactiveFunction';
12
+import DisjointSet from '../Utils/DisjointSet';
13
+import {assertExhaustive} from '../Utils/utils';
14
import type {
15
FunctionExpression,
16
HIR,
@@ -34,8 +34,8 @@ import type {
34
SpreadPattern,
35
Terminal,
36
Type,
37
-} from "./HIR";
38
-import { GotoVariant, InstructionKind } from "./HIR";
37
+} from './HIR';
38
+import {GotoVariant, InstructionKind} from './HIR';
39
40
export type Options = {
41
indent: number;
@@ -46,51 +46,51 @@ export function printFunctionWithOutlined(fn: HIRFunction): string {
46
for (const outlined of fn.env.getOutlinedFunctions()) {
47
output.push(`\nfunction ${outlined.fn.id}:\n${printHIR(outlined.fn.body)}`);
48
}
49
- return output.join("\n");
49
+ return output.join('\n');
50
}
51
52
export function printFunction(fn: HIRFunction): string {
53
const output = [];
54
- let definition = "";
54
+ let definition = '';
55
if (fn.id !== null) {
56
definition += fn.id;
57
}
58
if (fn.params.length !== 0) {
59
definition +=
60
- "(" +
60
+ '(' +
61
fn.params
62
- .map((param) => {
63
- if (param.kind === "Identifier") {
62
+ .map(param => {
63
+ if (param.kind === 'Identifier') {
64
return printPlace(param);
65
} else {
66
return `...${printPlace(param.place)}`;
67
}
68
})
69
- .join(", ") +
70
- ")";
69
+ .join(', ') +
70
+ ')';
71
}
72
if (definition.length !== 0) {
73
output.push(definition);
74
}
75
output.push(printHIR(fn.body));
76
output.push(...fn.directives);
77
- return output.join("\n");
77
+ return output.join('\n');
78
}
79
80
export function printHIR(ir: HIR, options: Options | null = null): string {
81
let output = [];
82
- let indent = " ".repeat(options?.indent ?? 0);
83
- const push = (text: string, indent: string = " "): void => {
82
+ let indent = ' '.repeat(options?.indent ?? 0);
83
+ const push = (text: string, indent: string = ' '): void => {
84
output.push(`${indent}${text}`);
85
};
86
for (const [blockId, block] of ir.blocks) {
87
output.push(`bb${blockId} (${block.kind}):`);
88
if (block.preds.size > 0) {
89
- const preds = ["predecessor blocks:"];
89
+ const preds = ['predecessor blocks:'];
90
for (const pred of block.preds) {
91
preds.push(`bb${pred}`);
92
}
93
- push(preds.join(" "));
93
+ push(preds.join(' '));
94
}
95
for (const phi of block.phis) {
96
push(printPhi(phi));
@@ -100,46 +100,46 @@ export function printHIR(ir: HIR, options: Options | null = null): string {
100
}
101
const terminal = printTerminal(block.terminal);
102
if (Array.isArray(terminal)) {
103
- terminal.forEach((line) => push(line));
103
+ terminal.forEach(line => push(line));
104
} else {
105
push(terminal);
106
}
107
}
108
- return output.map((line) => indent + line).join("\n");
108
+ return output.map(line => indent + line).join('\n');
109
}
110
111
export function printMixedHIR(
112
- value: Instruction | InstructionValue | Terminal
112
+ value: Instruction | InstructionValue | Terminal,
113
): string {
114
- if (!("kind" in value)) {
114
+ if (!('kind' in value)) {
115
return printInstruction(value);
116
}
117
switch (value.kind) {
118
- case "try":
119
- case "maybe-throw":
120
- case "sequence":
121
- case "label":
122
- case "optional":
123
- case "branch":
124
- case "if":
125
- case "logical":
126
- case "ternary":
127
- case "return":
128
- case "switch":
129
- case "throw":
130
- case "while":
131
- case "for":
132
- case "unreachable":
133
- case "unsupported":
134
- case "goto":
135
- case "do-while":
136
- case "for-in":
137
- case "for-of":
138
- case "scope":
139
- case "pruned-scope": {
118
+ case 'try':
119
+ case 'maybe-throw':
120
+ case 'sequence':
121
+ case 'label':
122
+ case 'optional':
123
+ case 'branch':
124
+ case 'if':
125
+ case 'logical':
126
+ case 'ternary':
127
+ case 'return':
128
+ case 'switch':
129
+ case 'throw':
130
+ case 'while':
131
+ case 'for':
132
+ case 'unreachable':
133
+ case 'unsupported':
134
+ case 'goto':
135
+ case 'do-while':
136
+ case 'for-in':
137
+ case 'for-of':
138
+ case 'scope':
139
+ case 'pruned-scope': {
140
const terminal = printTerminal(value);
141
if (Array.isArray(terminal)) {
142
- return terminal.join("; ");
142
+ return terminal.join('; ');
143
}
144
return terminal;
145
}
@@ -165,66 +165,66 @@ export function printPhi(phi: Phi): string {
165
items.push(printIdentifier(phi.id));
166
items.push(printMutableRange(phi.id));
167
items.push(printType(phi.type));
168
- items.push(": phi(");
168
+ items.push(': phi(');
169
const phis = [];
170
for (const [blockId, id] of phi.operands) {
171
phis.push(`bb${blockId}: ${printIdentifier(id)}`);
172
}
173
174
- items.push(phis.join(", "));
175
- items.push(")");
176
- return items.join("");
174
+ items.push(phis.join(', '));
175
+ items.push(')');
176
+ return items.join('');
177
}
178
179
export function printTerminal(terminal: Terminal): Array<string> | string {
180
let value;
181
switch (terminal.kind) {
182
- case "if": {
182
+ case 'if': {
183
value = `[${terminal.id}] If (${printPlace(terminal.test)}) then:bb${
184
terminal.consequent
185
} else:bb${terminal.alternate}${
186
- terminal.fallthrough ? ` fallthrough=bb${terminal.fallthrough}` : ""
186
+ terminal.fallthrough ? ` fallthrough=bb${terminal.fallthrough}` : ''
187
}`;
188
break;
189
}
190
- case "branch": {
190
+ case 'branch': {
191
value = `[${terminal.id}] Branch (${printPlace(terminal.test)}) then:bb${
192
terminal.consequent
193
} else:bb${terminal.alternate}`;
194
break;
195
}
196
- case "logical": {
196
+ case 'logical': {
197
value = `[${terminal.id}] Logical ${terminal.operator} test:bb${terminal.test} fallthrough=bb${terminal.fallthrough}`;
198
break;
199
}
200
- case "ternary": {
200
+ case 'ternary': {
201
value = `[${terminal.id}] Ternary test:bb${terminal.test} fallthrough=bb${terminal.fallthrough}`;
202
break;
203
}
204
- case "optional": {
204
+ case 'optional': {
205
value = `[${terminal.id}] Optional (optional=${terminal.optional}) test:bb${terminal.test} fallthrough=bb${terminal.fallthrough}`;
206
break;
207
}
208
- case "throw": {
208
+ case 'throw': {
209
value = `[${terminal.id}] Throw ${printPlace(terminal.value)}`;
210
break;
211
}
212
- case "return": {
212
+ case 'return': {
213
value = `[${terminal.id}] Return${
214
- terminal.value != null ? " " + printPlace(terminal.value) : ""
214
+ terminal.value != null ? ' ' + printPlace(terminal.value) : ''
215
}`;
216
break;
217
}
218
- case "goto": {
218
+ case 'goto': {
219
value = `[${terminal.id}] Goto${
220
- terminal.variant === GotoVariant.Continue ? "(Continue)" : ""
220
+ terminal.variant === GotoVariant.Continue ? '(Continue)' : ''
221
} bb${terminal.block}`;
222
break;
223
}
224
- case "switch": {
224
+ case 'switch': {
225
const output = [];
226
output.push(`[${terminal.id}] Switch (${printPlace(terminal.test)})`);
227
- terminal.cases.forEach((case_) => {
227
+ terminal.cases.forEach(case_ => {
228
if (case_.test !== null) {
229
output.push(` Case ${printPlace(case_.test)}: bb${case_.block}`);
230
} else {
@@ -237,78 +237,78 @@ export function printTerminal(terminal: Terminal): Array<string> | string {
237
value = output;
238
break;
239
}
240
- case "do-while": {
240
+ case 'do-while': {
241
value = `[${terminal.id}] DoWhile loop=${`bb${terminal.loop}`} test=bb${
242
terminal.test
243
} fallthrough=${`bb${terminal.fallthrough}`}`;
244
break;
245
}
246
- case "while": {
246
+ case 'while': {
247
value = `[${terminal.id}] While test=bb${terminal.test} loop=${
248
- terminal.loop !== null ? `bb${terminal.loop}` : ""
249
- } fallthrough=${terminal.fallthrough ? `bb${terminal.fallthrough}` : ""}`;
248
+ terminal.loop !== null ? `bb${terminal.loop}` : ''
249
+ } fallthrough=${terminal.fallthrough ? `bb${terminal.fallthrough}` : ''}`;
250
break;
251
}
252
- case "for": {
252
+ case 'for': {
253
value = `[${terminal.id}] For init=bb${terminal.init} test=bb${terminal.test} loop=bb${terminal.loop} update=bb${terminal.update} fallthrough=bb${terminal.fallthrough}`;
254
break;
255
}
256
- case "for-of": {
256
+ case 'for-of': {
257
value = `[${terminal.id}] ForOf init=bb${terminal.init} test=bb${terminal.test} loop=bb${terminal.loop} fallthrough=bb${terminal.fallthrough}`;
258
break;
259
}
260
- case "for-in": {
260
+ case 'for-in': {
261
value = `[${terminal.id}] ForIn init=bb${terminal.init} loop=bb${terminal.loop} fallthrough=bb${terminal.fallthrough}`;
262
break;
263
}
264
- case "label": {
264
+ case 'label': {
265
value = `[${terminal.id}] Label block=bb${terminal.block} fallthrough=${
266
- terminal.fallthrough ? `bb${terminal.fallthrough}` : ""
266
+ terminal.fallthrough ? `bb${terminal.fallthrough}` : ''
267
}`;
268
break;
269
}
270
- case "sequence": {
270
+ case 'sequence': {
271
value = `[${terminal.id}] Sequence block=bb${terminal.block} fallthrough=bb${terminal.fallthrough}`;
272
break;
273
}
274
- case "unreachable": {
274
+ case 'unreachable': {
275
value = `[${terminal.id}] Unreachable`;
276
break;
277
}
278
- case "unsupported": {
278
+ case 'unsupported': {
279
value = `Unsupported`;
280
break;
281
}
282
- case "maybe-throw": {
282
+ case 'maybe-throw': {
283
value = `MaybeThrow continuation=bb${terminal.continuation} handler=bb${terminal.handler}`;
284
break;
285
}
286
- case "scope": {
286
+ case 'scope': {
287
value = `Scope ${printReactiveScopeSummary(terminal.scope)} block=bb${
288
terminal.block
289
} fallthrough=bb${terminal.fallthrough}`;
290
break;
291
}
292
- case "pruned-scope": {
292
+ case 'pruned-scope': {
293
value = `<pruned> Scope ${printReactiveScopeSummary(
294
- terminal.scope
294
+ terminal.scope,
295
)} block=bb${terminal.block} fallthrough=bb${terminal.fallthrough}`;
296
break;
297
}
298
- case "try": {
298
+ case 'try': {
299
value = `Try block=bb${terminal.block} handler=bb${terminal.handler}${
300
terminal.handlerBinding !== null
301
? ` handlerBinding=(${printPlace(terminal.handlerBinding)})`
302
- : ""
302
+ : ''
303
} fallthrough=${
304
- terminal.fallthrough != null ? `bb${terminal.fallthrough}` : ""
304
+ terminal.fallthrough != null ? `bb${terminal.fallthrough}` : ''
305
}`;
306
break;
307
}
308
default: {
309
assertExhaustive(
310
terminal,
311
- `Unexpected terminal kind \`${terminal as any as Terminal}\``
311
+ `Unexpected terminal kind \`${terminal as any as Terminal}\``,
312
);
313
}
314
}
@@ -316,311 +316,311 @@ export function printTerminal(terminal: Terminal): Array<string> | string {
316
}
317
318
function printHole(): string {
319
- return "<hole>";
319
+ return '<hole>';
320
}
321
322
function printObjectPropertyKey(key: ObjectPropertyKey): string {
323
switch (key.kind) {
324
- case "identifier":
324
+ case 'identifier':
325
return key.name;
326
- case "string":
326
+ case 'string':
327
return `"${key.name}"`;
328
- case "computed": {
328
+ case 'computed': {
329
return `[${printPlace(key.name)}]`;
330
}
331
}
332
}
333
334
export function printInstructionValue(instrValue: ReactiveValue): string {
335
- let value = "";
335
+ let value = '';
336
switch (instrValue.kind) {
337
- case "ArrayExpression": {
337
+ case 'ArrayExpression': {
338
value = `Array [${instrValue.elements
339
- .map((element) => {
340
- if (element.kind === "Identifier") {
339
+ .map(element => {
340
+ if (element.kind === 'Identifier') {
341
return printPlace(element);
342
- } else if (element.kind === "Hole") {
342
+ } else if (element.kind === 'Hole') {
343
return printHole();
344
} else {
345
return `...${printPlace(element.place)}`;
346
}
347
})
348
- .join(", ")}]`;
348
+ .join(', ')}]`;
349
break;
350
}
351
- case "ObjectExpression": {
351
+ case 'ObjectExpression': {
352
const properties = [];
353
if (instrValue.properties !== null) {
354
for (const property of instrValue.properties) {
355
- if (property.kind === "ObjectProperty") {
355
+ if (property.kind === 'ObjectProperty') {
356
properties.push(
357
`${printObjectPropertyKey(property.key)}: ${printPlace(
358
- property.place
359
- )}`
358
+ property.place,
359
+ )}`,
360
);
361
} else {
362
properties.push(`...${printPlace(property.place)}`);
363
}
364
}
365
}
366
- value = `Object { ${properties.join(", ")} }`;
366
+ value = `Object { ${properties.join(', ')} }`;
367
break;
368
}
369
- case "UnaryExpression": {
369
+ case 'UnaryExpression': {
370
value = `Unary ${printPlace(instrValue.value)}`;
371
break;
372
}
373
- case "BinaryExpression": {
373
+ case 'BinaryExpression': {
374
value = `Binary ${printPlace(instrValue.left)} ${
375
instrValue.operator
376
} ${printPlace(instrValue.right)}`;
377
break;
378
}
379
- case "NewExpression": {
379
+ case 'NewExpression': {
380
value = `New ${printPlace(instrValue.callee)}(${instrValue.args
381
- .map((arg) => printPattern(arg))
382
- .join(", ")})`;
381
+ .map(arg => printPattern(arg))
382
+ .join(', ')})`;
383
break;
384
}
385
- case "CallExpression": {
385
+ case 'CallExpression': {
386
value = `Call ${printPlace(instrValue.callee)}(${instrValue.args
387
- .map((arg) => printPattern(arg))
388
- .join(", ")})`;
387
+ .map(arg => printPattern(arg))
388
+ .join(', ')})`;
389
break;
390
}
391
- case "MethodCall": {
391
+ case 'MethodCall': {
392
value = `MethodCall ${printPlace(instrValue.receiver)}.${printPlace(
393
- instrValue.property
394
- )}(${instrValue.args.map((arg) => printPattern(arg)).join(", ")})`;
393
+ instrValue.property,
394
+ )}(${instrValue.args.map(arg => printPattern(arg)).join(', ')})`;
395
break;
396
}
397
- case "JSXText": {
397
+ case 'JSXText': {
398
value = `JSXText ${JSON.stringify(instrValue.value)}`;
399
break;
400
}
401
- case "Primitive": {
401
+ case 'Primitive': {
402
if (instrValue.value === undefined) {
403
- value = "<undefined>";
403
+ value = '<undefined>';
404
} else {
405
value = JSON.stringify(instrValue.value);
406
}
407
break;
408
}
409
- case "TypeCastExpression": {
409
+ case 'TypeCastExpression': {
410
value = `TypeCast ${printPlace(instrValue.value)}: ${printType(
411
- instrValue.type
411
+ instrValue.type,
412
)}`;
413
break;
414
}
415
- case "JsxExpression": {
415
+ case 'JsxExpression': {
416
const propItems = [];
417
for (const attribute of instrValue.props) {
418
- if (attribute.kind === "JsxAttribute") {
418
+ if (attribute.kind === 'JsxAttribute') {
419
propItems.push(
420
`${attribute.name}={${
421
- attribute.place !== null ? printPlace(attribute.place) : "<empty>"
422
- }}`
421
+ attribute.place !== null ? printPlace(attribute.place) : '<empty>'
422
+ }}`,
423
);
424
} else {
425
propItems.push(`...${printPlace(attribute.argument)}`);
426
}
427
}
428
const tag =
429
- instrValue.tag.kind === "Identifier"
429
+ instrValue.tag.kind === 'Identifier'
430
? printPlace(instrValue.tag)
431
: instrValue.tag.name;
432
- const props = propItems.length !== 0 ? " " + propItems.join(" ") : "";
432
+ const props = propItems.length !== 0 ? ' ' + propItems.join(' ') : '';
433
if (instrValue.children !== null) {
434
- const children = instrValue.children.map((child) => {
434
+ const children = instrValue.children.map(child => {
435
return `{${printPlace(child)}}`;
436
});
437
value = `JSX <${tag}${props}${
438
- props.length > 0 ? " " : ""
439
- }>${children.join("")}</${tag}>`;
438
+ props.length > 0 ? ' ' : ''
439
+ }>${children.join('')}</${tag}>`;
440
} else {
441
- value = `JSX <${tag}${props}${props.length > 0 ? " " : ""}/>`;
441
+ value = `JSX <${tag}${props}${props.length > 0 ? ' ' : ''}/>`;
442
}
443
break;
444
}
445
- case "JsxFragment": {
445
+ case 'JsxFragment': {
446
value = `JsxFragment [${instrValue.children
447
- .map((child) => printPlace(child))
448
- .join(", ")}]`;
447
+ .map(child => printPlace(child))
448
+ .join(', ')}]`;
449
break;
450
}
451
- case "UnsupportedNode": {
451
+ case 'UnsupportedNode': {
452
value = `UnsupportedNode(${generate(instrValue.node).code})`;
453
break;
454
}
455
- case "LoadLocal": {
455
+ case 'LoadLocal': {
456
value = `LoadLocal ${printPlace(instrValue.place)}`;
457
break;
458
}
459
- case "DeclareLocal": {
459
+ case 'DeclareLocal': {
460
value = `DeclareLocal ${instrValue.lvalue.kind} ${printPlace(
461
- instrValue.lvalue.place
461
+ instrValue.lvalue.place,
462
)}`;
463
break;
464
}
465
- case "DeclareContext": {
465
+ case 'DeclareContext': {
466
value = `DeclareContext ${instrValue.lvalue.kind} ${printPlace(
467
- instrValue.lvalue.place
467
+ instrValue.lvalue.place,
468
)}`;
469
break;
470
}
471
- case "StoreLocal": {
471
+ case 'StoreLocal': {
472
value = `StoreLocal ${instrValue.lvalue.kind} ${printPlace(
473
- instrValue.lvalue.place
473
+ instrValue.lvalue.place,
474
)} = ${printPlace(instrValue.value)}`;
475
break;
476
}
477
- case "LoadContext": {
477
+ case 'LoadContext': {
478
value = `LoadContext ${printPlace(instrValue.place)}`;
479
break;
480
}
481
- case "StoreContext": {
481
+ case 'StoreContext': {
482
value = `StoreContext ${instrValue.lvalue.kind} ${printPlace(
483
- instrValue.lvalue.place
483
+ instrValue.lvalue.place,
484
)} = ${printPlace(instrValue.value)}`;
485
break;
486
}
487
- case "Destructure": {
487
+ case 'Destructure': {
488
value = `Destructure ${instrValue.lvalue.kind} ${printPattern(
489
- instrValue.lvalue.pattern
489
+ instrValue.lvalue.pattern,
490
)} = ${printPlace(instrValue.value)}`;
491
break;
492
}
493
- case "PropertyLoad": {
493
+ case 'PropertyLoad': {
494
value = `PropertyLoad ${printPlace(instrValue.object)}.${
495
instrValue.property
496
}`;
497
break;
498
}
499
- case "PropertyStore": {
499
+ case 'PropertyStore': {
500
value = `PropertyStore ${printPlace(instrValue.object)}.${
501
instrValue.property
502
} = ${printPlace(instrValue.value)}`;
503
break;
504
}
505
- case "PropertyDelete": {
505
+ case 'PropertyDelete': {
506
value = `PropertyDelete ${printPlace(instrValue.object)}.${
507
instrValue.property
508
}`;
509
break;
510
}
511
- case "ComputedLoad": {
511
+ case 'ComputedLoad': {
512
value = `ComputedLoad ${printPlace(instrValue.object)}[${printPlace(
513
- instrValue.property
513
+ instrValue.property,
514
)}]`;
515
break;
516
}
517
- case "ComputedStore": {
517
+ case 'ComputedStore': {
518
value = `ComputedStore ${printPlace(instrValue.object)}[${printPlace(
519
- instrValue.property
519
+ instrValue.property,
520
)}] = ${printPlace(instrValue.value)}`;
521
break;
522
}
523
- case "ComputedDelete": {
523
+ case 'ComputedDelete': {
524
value = `ComputedDelete ${printPlace(instrValue.object)}[${printPlace(
525
- instrValue.property
525
+ instrValue.property,
526
)}]`;
527
break;
528
}
529
- case "ObjectMethod":
530
- case "FunctionExpression": {
529
+ case 'ObjectMethod':
530
+ case 'FunctionExpression': {
531
const kind =
532
- instrValue.kind === "FunctionExpression" ? "Function" : "ObjectMethod";
533
- const name = getFunctionName(instrValue, "");
532
+ instrValue.kind === 'FunctionExpression' ? 'Function' : 'ObjectMethod';
533
+ const name = getFunctionName(instrValue, '');
534
const fn = printFunction(instrValue.loweredFunc.func)
535
- .split("\n")
536
- .map((line) => ` ${line}`)
537
- .join("\n");
535
+ .split('\n')
536
+ .map(line => ` ${line}`)
537
+ .join('\n');
538
const deps = instrValue.loweredFunc.dependencies
539
- .map((dep) => printPlace(dep))
540
- .join(",");
539
+ .map(dep => printPlace(dep))
540
+ .join(',');
541
const context = instrValue.loweredFunc.func.context
542
- .map((dep) => printPlace(dep))
543
- .join(",");
542
+ .map(dep => printPlace(dep))
543
+ .join(',');
544
const effects =
545
instrValue.loweredFunc.func.effects
546
- ?.map((effect) => {
547
- if (effect.kind === "ContextMutation") {
546
+ ?.map(effect => {
547
+ if (effect.kind === 'ContextMutation') {
548
return `ContextMutation places=[${[...effect.places]
549
- .map((place) => printPlace(place))
550
- .join(", ")}] effect=${effect.effect}`;
549
+ .map(place => printPlace(place))
550
+ .join(', ')}] effect=${effect.effect}`;
551
} else {
552
return `GlobalMutation`;
553
}
554
})
555
- .join(", ") ?? "";
555
+ .join(', ') ?? '';
556
value = `${kind} ${name} @deps[${deps}] @context[${context}] @effects[${effects}]:\n${fn}`;
557
break;
558
}
559
- case "TaggedTemplateExpression": {
559
+ case 'TaggedTemplateExpression': {
560
value = `${printPlace(instrValue.tag)}\`${instrValue.value.raw}\``;
561
break;
562
}
563
- case "LogicalExpression": {
563
+ case 'LogicalExpression': {
564
value = `Logical ${printInstructionValue(instrValue.left)} ${
565
instrValue.operator
566
} ${printInstructionValue(instrValue.right)}`;
567
break;
568
}
569
- case "SequenceExpression": {
569
+ case 'SequenceExpression': {
570
value = [
571
`Sequence`,
572
...instrValue.instructions.map(
573
- (instr) => ` ${printInstruction(instr)}`
573
+ instr => ` ${printInstruction(instr)}`,
574
),
575
` ${printInstructionValue(instrValue.value)}`,
576
- ].join("\n");
576
+ ].join('\n');
577
break;
578
}
579
- case "ConditionalExpression": {
579
+ case 'ConditionalExpression': {
580
value = `Ternary ${printInstructionValue(
581
- instrValue.test
581
+ instrValue.test,
582
)} ? ${printInstructionValue(
583
- instrValue.consequent
583
+ instrValue.consequent,
584
)} : ${printInstructionValue(instrValue.alternate)}`;
585
break;
586
}
587
- case "TemplateLiteral": {
588
- value = "`";
587
+ case 'TemplateLiteral': {
588
+ value = '`';
589
CompilerError.invariant(
590
instrValue.subexprs.length === instrValue.quasis.length - 1,
591
{
592
- reason: "Bad assumption about quasi length.",
592
+ reason: 'Bad assumption about quasi length.',
593
description: null,
594
loc: instrValue.loc,
595
suggestions: null,
596
- }
596
+ },
597
);
598
for (let i = 0; i < instrValue.subexprs.length; i++) {
599
value += instrValue.quasis[i].raw;
600
value += `\${${printPlace(instrValue.subexprs[i])}}`;
601
}
602
- value += instrValue.quasis.at(-1)!.raw + "`";
602
+ value += instrValue.quasis.at(-1)!.raw + '`';
603
break;
604
}
605
- case "LoadGlobal": {
605
+ case 'LoadGlobal': {
606
switch (instrValue.binding.kind) {
607
- case "Global": {
607
+ case 'Global': {
608
value = `LoadGlobal(global) ${instrValue.binding.name}`;
609
break;
610
}
611
- case "ModuleLocal": {
611
+ case 'ModuleLocal': {
612
value = `LoadGlobal(module) ${instrValue.binding.name}`;
613
break;
614
}
615
- case "ImportDefault": {
615
+ case 'ImportDefault': {
616
value = `LoadGlobal import ${instrValue.binding.name} from '${instrValue.binding.module}'`;
617
break;
618
}
619
- case "ImportNamespace": {
619
+ case 'ImportNamespace': {
620
value = `LoadGlobal import * as ${instrValue.binding.name} from '${instrValue.binding.module}'`;
621
break;
622
}
623
- case "ImportSpecifier": {
623
+ case 'ImportSpecifier': {
624
if (instrValue.binding.imported !== instrValue.binding.name) {
625
value = `LoadGlobal import { ${instrValue.binding.imported} as ${instrValue.binding.name} } from '${instrValue.binding.module}'`;
626
} else {
@@ -631,76 +631,76 @@ export function printInstructionValue(instrValue: ReactiveValue): string {
631
default: {
632
assertExhaustive(
633
instrValue.binding,
634
- `Unexpected binding kind \`${(instrValue.binding as any).kind}\``
634
+ `Unexpected binding kind \`${(instrValue.binding as any).kind}\``,
635
);
636
}
637
}
638
break;
639
}
640
- case "StoreGlobal": {
640
+ case 'StoreGlobal': {
641
value = `StoreGlobal ${instrValue.name} = ${printPlace(
642
- instrValue.value
642
+ instrValue.value,
643
)}`;
644
break;
645
}
646
- case "OptionalExpression": {
646
+ case 'OptionalExpression': {
647
value = `OptionalExpression ${printInstructionValue(instrValue.value)}`;
648
break;
649
}
650
- case "RegExpLiteral": {
650
+ case 'RegExpLiteral': {
651
value = `RegExp /${instrValue.pattern}/${instrValue.flags}`;
652
break;
653
}
654
- case "MetaProperty": {
654
+ case 'MetaProperty': {
655
value = `MetaProperty ${instrValue.meta}.${instrValue.property}`;
656
break;
657
}
658
- case "Await": {
658
+ case 'Await': {
659
value = `Await ${printPlace(instrValue.value)}`;
660
break;
661
}
662
- case "GetIterator": {
662
+ case 'GetIterator': {
663
value = `GetIterator collection=${printPlace(instrValue.collection)}`;
664
break;
665
}
666
- case "IteratorNext": {
666
+ case 'IteratorNext': {
667
value = `IteratorNext iterator=${printPlace(
668
- instrValue.iterator
668
+ instrValue.iterator,
669
)} collection=${printPlace(instrValue.collection)}`;
670
break;
671
}
672
- case "NextPropertyOf": {
672
+ case 'NextPropertyOf': {
673
value = `NextPropertyOf ${printPlace(instrValue.value)}`;
674
break;
675
}
676
- case "Debugger": {
676
+ case 'Debugger': {
677
value = `Debugger`;
678
break;
679
}
680
- case "PostfixUpdate": {
680
+ case 'PostfixUpdate': {
681
value = `PostfixUpdate ${printPlace(instrValue.lvalue)} = ${printPlace(
682
- instrValue.value
682
+ instrValue.value,
683
)} ${instrValue.operation}`;
684
break;
685
}
686
- case "PrefixUpdate": {
686
+ case 'PrefixUpdate': {
687
value = `PrefixUpdate ${printPlace(instrValue.lvalue)} = ${
688
instrValue.operation
689
} ${printPlace(instrValue.value)}`;
690
break;
691
}
692
- case "StartMemoize": {
692
+ case 'StartMemoize': {
693
value = `StartMemoize deps=${
694
- instrValue.deps?.map((dep) => printManualMemoDependency(dep, false)) ??
695
- "(none)"
694
+ instrValue.deps?.map(dep => printManualMemoDependency(dep, false)) ??
695
+ '(none)'
696
}`;
697
break;
698
}
699
- case "FinishMemoize": {
699
+ case 'FinishMemoize': {
700
value = `FinishMemoize decl=${printPlace(instrValue.decl)}`;
701
break;
702
}
703
- case "ReactiveFunctionValue": {
703
+ case 'ReactiveFunctionValue': {
704
value = `FunctionValue ${printReactiveFunction(instrValue.fn)}`;
705
break;
706
}
@@ -709,7 +709,7 @@ export function printInstructionValue(instrValue: ReactiveValue): string {
709
instrValue,
710
`Unexpected instruction kind '${
711
(instrValue as any as InstructionValue).kind
712
- }'`
712
+ }'`,
713
);
714
}
715
}
@@ -732,11 +732,11 @@ function printMutableRange(identifier: Identifier): string {
732
) {
733
return `[${range.start}:${range.end}] scope=[${scopeRange.start}:${scopeRange.end}]`;
734
}
735
- return isMutable(range) ? `[${range.start}:${range.end}]` : "";
735
+ return isMutable(range) ? `[${range.start}:${range.end}]` : '';
736
}
737
// in non-debug mode, prefer the scope range if it exists
738
const range = identifier.scope?.range ?? identifier.mutableRange;
739
- return isMutable(range) ? `[${range.start}:${range.end}]` : "";
739
+ return isMutable(range) ? `[${range.start}:${range.end}]` : '';
740
}
741
742
export function printLValue(lval: LValue): string {
@@ -766,53 +766,53 @@ export function printLValue(lval: LValue): string {
766
767
export function printPattern(pattern: Pattern | Place | SpreadPattern): string {
768
switch (pattern.kind) {
769
- case "ArrayPattern": {
769
+ case 'ArrayPattern': {
770
return (
771
- "[ " +
771
+ '[ ' +
772
pattern.items
773
- .map((item) => {
774
- if (item.kind === "Hole") {
775
- return "<hole>";
773
+ .map(item => {
774
+ if (item.kind === 'Hole') {
775
+ return '<hole>';
776
}
777
return printPattern(item);
778
})
779
- .join(", ") +
780
- " ]"
779
+ .join(', ') +
780
+ ' ]'
781
);
782
}
783
- case "ObjectPattern": {
783
+ case 'ObjectPattern': {
784
return (
785
- "{ " +
785
+ '{ ' +
786
pattern.properties
787
- .map((item) => {
787
+ .map(item => {
788
switch (item.kind) {
789
- case "ObjectProperty": {
789
+ case 'ObjectProperty': {
790
return `${printObjectPropertyKey(item.key)}: ${printPattern(
791
- item.place
791
+ item.place,
792
)}`;
793
}
794
- case "Spread": {
794
+ case 'Spread': {
795
return printPattern(item);
796
}
797
default: {
798
- assertExhaustive(item, "Unexpected object property kind");
798
+ assertExhaustive(item, 'Unexpected object property kind');
799
}
800
}
801
})
802
- .join(", ") +
803
- " }"
802
+ .join(', ') +
803
+ ' }'
804
);
805
}
806
- case "Spread": {
806
+ case 'Spread': {
807
return `...${printPlace(pattern.place)}`;
808
}
809
- case "Identifier": {
809
+ case 'Identifier': {
810
return printPlace(pattern);
811
}
812
default: {
813
assertExhaustive(
814
pattern,
815
- `Unexpected pattern kind \`${(pattern as any).kind}\``
815
+ `Unexpected pattern kind \`${(pattern as any).kind}\``,
816
);
817
}
818
}
@@ -821,13 +821,13 @@ export function printPattern(pattern: Pattern | Place | SpreadPattern): string {
821
export function printPlace(place: Place): string {
822
const items = [
823
place.effect,
824
- " ",
824
+ ' ',
825
printIdentifier(place.identifier),
826
printMutableRange(place.identifier),
827
printType(place.identifier.type),
828
- place.reactive ? "{reactive}" : null,
828
+ place.reactive ? '{reactive}' : null,
829
];
830
- return items.filter((x) => x != null).join("");
830
+ return items.filter(x => x != null).join('');
831
}
832
833
export function printIdentifier(id: Identifier): string {
@@ -836,25 +836,25 @@ export function printIdentifier(id: Identifier): string {
836
837
function printName(name: IdentifierName | null): string {
838
if (name === null) {
839
- return "";
839
+ return '';
840
}
841
return name.value;
842
}
843
844
function printScope(scope: ReactiveScope | null): string {
845
- return `${scope !== null ? `_@${scope.id}` : ""}`;
845
+ return `${scope !== null ? `_@${scope.id}` : ''}`;
846
}
847
848
export function printManualMemoDependency(
849
val: ManualMemoDependency,
850
- nameOnly: boolean
850
+ nameOnly: boolean,
851
): string {
852
let rootStr;
853
- if (val.root.kind === "Global") {
853
+ if (val.root.kind === 'Global') {
854
rootStr = val.root.identifierName;
855
} else {
856
- CompilerError.invariant(val.root.value.identifier.name?.kind === "named", {
857
- reason: "DepsValidation: expected named local variable in depslist",
856
+ CompilerError.invariant(val.root.value.identifier.name?.kind === 'named', {
857
+ reason: 'DepsValidation: expected named local variable in depslist',
858
suggestions: null,
859
loc: val.root.value.loc,
860
});
@@ -862,14 +862,14 @@ export function printManualMemoDependency(
862
? val.root.value.identifier.name.value
863
: printIdentifier(val.root.value.identifier);
864
}
865
- return `${rootStr}${val.path.length > 0 ? "." : ""}${val.path.join(".")}`;
865
+ return `${rootStr}${val.path.length > 0 ? '.' : ''}${val.path.join('.')}`;
866
}
867
export function printType(type: Type): string {
868
- if (type.kind === "Type") return "";
868
+ if (type.kind === 'Type') return '';
869
// TODO(mofeiZ): add debugName for generated ids
870
- if (type.kind === "Object" && type.shapeId != null) {
870
+ if (type.kind === 'Object' && type.shapeId != null) {
871
return `:T${type.kind}<${type.shapeId}>`;
872
- } else if (type.kind === "Function" && type.shapeId != null) {
872
+ } else if (type.kind === 'Function' && type.shapeId != null) {
873
return `:T${type.kind}<${type.shapeId}>`;
874
} else {
875
return `:T${type.kind}`;
@@ -877,8 +877,8 @@ export function printType(type: Type): string {
877
}
878
879
export function printSourceLocation(loc: SourceLocation): string {
880
- if (typeof loc === "symbol") {
881
- return "generated";
880
+ if (typeof loc === 'symbol') {
881
+ return 'generated';
882
} else {
883
return `${loc.start.line}:${loc.start.column}:${loc.end.line}:${loc.end.column}`;
884
}
@@ -889,20 +889,20 @@ export function printAliases(aliases: DisjointSet<Identifier>): string {
889
890
const items = [];
891
for (const aliasSet of aliasSets) {
892
- items.push([...aliasSet].map((id) => printIdentifier(id)).join(","));
892
+ items.push([...aliasSet].map(id => printIdentifier(id)).join(','));
893
}
894
895
- return items.join("\n");
895
+ return items.join('\n');
896
}
897
898
function getFunctionName(
899
instrValue: ObjectMethod | FunctionExpression,
900
- defaultValue: string
900
+ defaultValue: string,
901
): string {
902
switch (instrValue.kind) {
903
- case "FunctionExpression":
903
+ case 'FunctionExpression':
904
return instrValue.name ?? defaultValue;
905
- case "ObjectMethod":
905
+ case 'ObjectMethod':
906
return defaultValue;
907
}
908
}
compiler/packages/babel-plugin-react-compiler/src/HIR/PruneUnusedLabelsHIR.ts
+10
-10
@@ -1,5 +1,5 @@
1
-import { CompilerError } from "..";
2
-import { BlockId, GotoVariant, HIRFunction } from "./HIR";
1
+import {CompilerError} from '..';
2
+import {BlockId, GotoVariant, HIRFunction} from './HIR';
3
4
export function pruneUnusedLabelsHIR(fn: HIRFunction): void {
5
const merged: Array<{
@@ -10,16 +10,16 @@ export function pruneUnusedLabelsHIR(fn: HIRFunction): void {
10
const rewrites: Map<BlockId, BlockId> = new Map();
11
for (const [blockId, block] of fn.body.blocks) {
12
const terminal = block.terminal;
13
- if (terminal.kind === "label") {
14
- const { block: nextId, fallthrough: fallthroughId } = terminal;
13
+ if (terminal.kind === 'label') {
14
+ const {block: nextId, fallthrough: fallthroughId} = terminal;
15
const next = fn.body.blocks.get(nextId)!;
16
const fallthrough = fn.body.blocks.get(fallthroughId)!;
17
if (
18
- next.terminal.kind === "goto" &&
18
+ next.terminal.kind === 'goto' &&
19
next.terminal.variant === GotoVariant.Break &&
20
next.terminal.block === fallthroughId
21
) {
22
- if (next.kind === "block" && fallthrough.kind === "block") {
22
+ if (next.kind === 'block' && fallthrough.kind === 'block') {
23
// Only merge normal block types
24
merged.push({
25
label: blockId,
@@ -45,9 +45,9 @@ export function pruneUnusedLabelsHIR(fn: HIRFunction): void {
45
CompilerError.invariant(
46
next.phis.size === 0 && fallthrough.phis.size === 0,
47
{
48
- reason: "Unexpected phis when merging label blocks",
48
+ reason: 'Unexpected phis when merging label blocks',
49
loc: label.terminal.loc,
50
- }
50
+ },
51
);
52
53
CompilerError.invariant(
@@ -56,9 +56,9 @@ export function pruneUnusedLabelsHIR(fn: HIRFunction): void {
56
next.preds.has(originalLabelId) &&
57
fallthrough.preds.has(nextId),
58
{
59
- reason: "Unexpected block predecessors when merging label blocks",
59
+ reason: 'Unexpected block predecessors when merging label blocks',
60
loc: label.terminal.loc,
61
- }
61
+ },
62
);
63
64
label.instructions.push(...next.instructions, ...fallthrough.instructions);
compiler/packages/babel-plugin-react-compiler/src/HIR/Types.ts
+36
-36
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
8
+import {CompilerError} from '../CompilerError';
9
10
export type BuiltInType = PrimitiveType | FunctionType | ObjectType;
11
@@ -16,7 +16,7 @@ export type Type =
16
| PolyType
17
| PropType
18
| ObjectMethod;
19
-export type PrimitiveType = { kind: "Primitive" };
19
+export type PrimitiveType = {kind: 'Primitive'};
20
21
/*
22
* An {@link FunctionType} or {@link ObjectType} (also a JS object) may be associated with an
@@ -34,36 +34,36 @@ export type PrimitiveType = { kind: "Primitive" };
34
*/
35
36
export type FunctionType = {
37
- kind: "Function";
37
+ kind: 'Function';
38
shapeId: string | null;
39
return: Type;
40
};
41
42
export type ObjectType = {
43
- kind: "Object";
43
+ kind: 'Object';
44
shapeId: string | null;
45
};
46
47
export type TypeVar = {
48
- kind: "Type";
48
+ kind: 'Type';
49
id: TypeId;
50
};
51
export type PolyType = {
52
- kind: "Poly";
52
+ kind: 'Poly';
53
};
54
export type PhiType = {
55
- kind: "Phi";
55
+ kind: 'Phi';
56
operands: Array<Type>;
57
};
58
export type PropType = {
59
- kind: "Property";
59
+ kind: 'Property';
60
objectType: Type;
61
objectName: string;
62
propertyName: string;
63
};
64
65
export type ObjectMethod = {
66
- kind: "ObjectMethod";
66
+ kind: 'ObjectMethod';
67
};
68
69
/*
@@ -71,11 +71,11 @@ export type ObjectMethod = {
71
* accidentally.
72
*/
73
const opaqueTypeId = Symbol();
74
-export type TypeId = number & { [opaqueTypeId]: "IdentifierId" };
74
+export type TypeId = number & {[opaqueTypeId]: 'IdentifierId'};
75
76
export function makeTypeId(id: number): TypeId {
77
CompilerError.invariant(id >= 0 && Number.isInteger(id), {
78
- reason: "Expected instruction id to be a non-negative integer",
78
+ reason: 'Expected instruction id to be a non-negative integer',
79
description: null,
80
loc: null,
81
suggestions: null,
@@ -86,7 +86,7 @@ export function makeTypeId(id: number): TypeId {
86
let typeCounter = 0;
87
export function makeType(): TypeVar {
88
return {
89
- kind: "Type",
89
+ kind: 'Type',
90
id: makeTypeId(typeCounter++),
91
};
92
}
@@ -97,40 +97,40 @@ export function makeType(): TypeVar {
97
*/
98
export function duplicateType(type: Type): Type {
99
switch (type.kind) {
100
- case "Function": {
100
+ case 'Function': {
101
return {
102
- kind: "Function",
102
+ kind: 'Function',
103
return: duplicateType(type.return),
104
shapeId: type.shapeId,
105
};
106
}
107
- case "Object": {
108
- return { kind: "Object", shapeId: type.shapeId };
107
+ case 'Object': {
108
+ return {kind: 'Object', shapeId: type.shapeId};
109
}
110
- case "ObjectMethod": {
111
- return { kind: "ObjectMethod" };
110
+ case 'ObjectMethod': {
111
+ return {kind: 'ObjectMethod'};
112
}
113
- case "Phi": {
113
+ case 'Phi': {
114
return {
115
- kind: "Phi",
116
- operands: type.operands.map((operand) => duplicateType(operand)),
115
+ kind: 'Phi',
116
+ operands: type.operands.map(operand => duplicateType(operand)),
117
};
118
}
119
- case "Poly": {
120
- return { kind: "Poly" };
119
+ case 'Poly': {
120
+ return {kind: 'Poly'};
121
}
122
- case "Primitive": {
123
- return { kind: "Primitive" };
122
+ case 'Primitive': {
123
+ return {kind: 'Primitive'};
124
}
125
- case "Property": {
125
+ case 'Property': {
126
return {
127
- kind: "Property",
127
+ kind: 'Property',
128
objectType: duplicateType(type.objectType),
129
objectName: type.objectName,
130
propertyName: type.propertyName,
131
};
132
}
133
- case "Type": {
133
+ case 'Type': {
134
return makeType();
135
}
136
}
@@ -151,7 +151,7 @@ export function typeEquals(tA: Type, tB: Type): boolean {
151
}
152
153
function typeVarEquals(tA: Type, tB: Type): boolean {
154
- if (tA.kind === "Type" && tB.kind === "Type") {
154
+ if (tA.kind === 'Type' && tB.kind === 'Type') {
155
return tA.id === tB.id;
156
}
157
return false;
@@ -162,11 +162,11 @@ function typeKindCheck(tA: Type, tb: Type, type: string): boolean {
162
}
163
164
function objectMethodTypeEquals(tA: Type, tB: Type): boolean {
165
- return typeKindCheck(tA, tB, "ObjectMethod");
165
+ return typeKindCheck(tA, tB, 'ObjectMethod');
166
}
167
168
function propTypeEquals(tA: Type, tB: Type): boolean {
169
- if (tA.kind === "Property" && tB.kind === "Property") {
169
+ if (tA.kind === 'Property' && tB.kind === 'Property') {
170
if (!typeEquals(tA.objectType, tB.objectType)) {
171
return false;
172
}
@@ -180,15 +180,15 @@ function propTypeEquals(tA: Type, tB: Type): boolean {
180
}
181
182
function primitiveTypeEquals(tA: Type, tB: Type): boolean {
183
- return typeKindCheck(tA, tB, "Primitive");
183
+ return typeKindCheck(tA, tB, 'Primitive');
184
}
185
186
function polyTypeEquals(tA: Type, tB: Type): boolean {
187
- return typeKindCheck(tA, tB, "Poly");
187
+ return typeKindCheck(tA, tB, 'Poly');
188
}
189
190
function objectTypeEquals(tA: Type, tB: Type): boolean {
191
- if (tA.kind === "Object" && tB.kind == "Object") {
191
+ if (tA.kind === 'Object' && tB.kind == 'Object') {
192
return tA.shapeId === tB.shapeId;
193
}
194
@@ -196,14 +196,14 @@ function objectTypeEquals(tA: Type, tB: Type): boolean {
196
}
197
198
function funcTypeEquals(tA: Type, tB: Type): boolean {
199
- if (tA.kind !== "Function" || tB.kind !== "Function") {
199
+ if (tA.kind !== 'Function' || tB.kind !== 'Function') {
200
return false;
201
}
202
return typeEquals(tA.return, tB.return);
203
}
204
205
function phiTypeEquals(tA: Type, tB: Type): boolean {
206
- if (tA.kind === "Phi" && tB.kind === "Phi") {
206
+ if (tA.kind === 'Phi' && tB.kind === 'Phi') {
207
if (tA.operands.length !== tB.operands.length) {
208
return false;
209
}
compiler/packages/babel-plugin-react-compiler/src/HIR/index.ts
+14
-14
@@ -5,16 +5,16 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-export { assertConsistentIdentifiers } from "./AssertConsistentIdentifiers";
8
+export {assertConsistentIdentifiers} from './AssertConsistentIdentifiers';
9
export {
10
assertTerminalSuccessorsExist,
11
assertTerminalPredsExist,
12
-} from "./AssertTerminalBlocksExist";
13
-export { assertValidBlockNesting } from "./AssertValidBlockNesting";
14
-export { assertValidMutableRanges } from "./AssertValidMutableRanges";
15
-export { lower } from "./BuildHIR";
16
-export { buildReactiveScopeTerminalsHIR } from "./BuildReactiveScopeTerminalsHIR";
17
-export { computeDominatorTree, computePostDominatorTree } from "./Dominator";
12
+} from './AssertTerminalBlocksExist';
13
+export {assertValidBlockNesting} from './AssertValidBlockNesting';
14
+export {assertValidMutableRanges} from './AssertValidMutableRanges';
15
+export {lower} from './BuildHIR';
16
+export {buildReactiveScopeTerminalsHIR} from './BuildReactiveScopeTerminalsHIR';
17
+export {computeDominatorTree, computePostDominatorTree} from './Dominator';
18
export {
19
Environment,
20
parseConfigPragma,
@@ -22,15 +22,15 @@ export {
22
type EnvironmentConfig,
23
type ExternalFunction,
24
type Hook,
25
-} from "./Environment";
26
-export * from "./HIR";
25
+} from './Environment';
26
+export * from './HIR';
27
export {
28
markInstructionIds,
29
markPredecessors,
30
removeUnnecessaryTryCatch,
31
reversePostorderBlocks,
32
-} from "./HIRBuilder";
33
-export { mergeConsecutiveBlocks } from "./MergeConsecutiveBlocks";
34
-export { mergeOverlappingReactiveScopesHIR } from "./MergeOverlappingReactiveScopesHIR";
35
-export { printFunction, printHIR } from "./PrintHIR";
36
-export { pruneUnusedLabelsHIR } from "./PruneUnusedLabelsHIR";
32
+} from './HIRBuilder';
33
+export {mergeConsecutiveBlocks} from './MergeConsecutiveBlocks';
34
+export {mergeOverlappingReactiveScopesHIR} from './MergeOverlappingReactiveScopesHIR';
35
+export {printFunction, printHIR} from './PrintHIR';
36
+export {pruneUnusedLabelsHIR} from './PruneUnusedLabelsHIR';
compiler/packages/babel-plugin-react-compiler/src/HIR/visitors.ts
+293
-293
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { assertExhaustive } from "../Utils/utils";
8
+import {assertExhaustive} from '../Utils/utils';
9
import {
10
BlockId,
11
Instruction,
@@ -17,10 +17,10 @@ import {
17
ReactiveValue,
18
SpreadPattern,
19
Terminal,
20
-} from "./HIR";
20
+} from './HIR';
21
22
export function* eachInstructionLValue(
23
- instr: ReactiveInstruction
23
+ instr: ReactiveInstruction,
24
): Iterable<Place> {
25
if (instr.lvalue !== null) {
26
yield instr.lvalue;
@@ -29,22 +29,22 @@ export function* eachInstructionLValue(
29
}
30
31
export function* eachInstructionValueLValue(
32
- value: ReactiveValue
32
+ value: ReactiveValue,
33
): Iterable<Place> {
34
switch (value.kind) {
35
- case "DeclareContext":
36
- case "StoreContext":
37
- case "DeclareLocal":
38
- case "StoreLocal": {
35
+ case 'DeclareContext':
36
+ case 'StoreContext':
37
+ case 'DeclareLocal':
38
+ case 'StoreLocal': {
39
yield value.lvalue.place;
40
break;
41
}
42
- case "Destructure": {
42
+ case 'Destructure': {
43
yield* eachPatternOperand(value.lvalue.pattern);
44
break;
45
}
46
- case "PostfixUpdate":
47
- case "PrefixUpdate": {
46
+ case 'PostfixUpdate':
47
+ case 'PrefixUpdate': {
48
yield value.lvalue;
49
break;
50
}
@@ -55,103 +55,103 @@ export function* eachInstructionOperand(instr: Instruction): Iterable<Place> {
55
yield* eachInstructionValueOperand(instr.value);
56
}
57
export function* eachInstructionValueOperand(
58
- instrValue: InstructionValue
58
+ instrValue: InstructionValue,
59
): Iterable<Place> {
60
switch (instrValue.kind) {
61
- case "NewExpression":
62
- case "CallExpression": {
61
+ case 'NewExpression':
62
+ case 'CallExpression': {
63
yield instrValue.callee;
64
yield* eachCallArgument(instrValue.args);
65
break;
66
}
67
- case "BinaryExpression": {
67
+ case 'BinaryExpression': {
68
yield instrValue.left;
69
yield instrValue.right;
70
break;
71
}
72
- case "MethodCall": {
72
+ case 'MethodCall': {
73
yield instrValue.receiver;
74
yield instrValue.property;
75
yield* eachCallArgument(instrValue.args);
76
break;
77
}
78
- case "DeclareContext":
79
- case "DeclareLocal": {
78
+ case 'DeclareContext':
79
+ case 'DeclareLocal': {
80
break;
81
}
82
- case "LoadLocal":
83
- case "LoadContext": {
82
+ case 'LoadLocal':
83
+ case 'LoadContext': {
84
yield instrValue.place;
85
break;
86
}
87
- case "StoreLocal": {
87
+ case 'StoreLocal': {
88
yield instrValue.value;
89
break;
90
}
91
- case "StoreContext": {
91
+ case 'StoreContext': {
92
yield instrValue.lvalue.place;
93
yield instrValue.value;
94
break;
95
}
96
- case "StoreGlobal": {
96
+ case 'StoreGlobal': {
97
yield instrValue.value;
98
break;
99
}
100
- case "Destructure": {
100
+ case 'Destructure': {
101
yield instrValue.value;
102
break;
103
}
104
- case "PropertyLoad": {
104
+ case 'PropertyLoad': {
105
yield instrValue.object;
106
break;
107
}
108
- case "PropertyDelete": {
108
+ case 'PropertyDelete': {
109
yield instrValue.object;
110
break;
111
}
112
- case "PropertyStore": {
112
+ case 'PropertyStore': {
113
yield instrValue.object;
114
yield instrValue.value;
115
break;
116
}
117
- case "ComputedLoad": {
117
+ case 'ComputedLoad': {
118
yield instrValue.object;
119
yield instrValue.property;
120
break;
121
}
122
- case "ComputedDelete": {
122
+ case 'ComputedDelete': {
123
yield instrValue.object;
124
yield instrValue.property;
125
break;
126
}
127
- case "ComputedStore": {
127
+ case 'ComputedStore': {
128
yield instrValue.object;
129
yield instrValue.property;
130
yield instrValue.value;
131
break;
132
}
133
- case "UnaryExpression": {
133
+ case 'UnaryExpression': {
134
yield instrValue.value;
135
break;
136
}
137
- case "JsxExpression": {
138
- if (instrValue.tag.kind === "Identifier") {
137
+ case 'JsxExpression': {
138
+ if (instrValue.tag.kind === 'Identifier') {
139
yield instrValue.tag;
140
}
141
for (const attribute of instrValue.props) {
142
switch (attribute.kind) {
143
- case "JsxAttribute": {
143
+ case 'JsxAttribute': {
144
yield attribute.place;
145
break;
146
}
147
- case "JsxSpreadAttribute": {
147
+ case 'JsxSpreadAttribute': {
148
yield attribute.argument;
149
break;
150
}
151
default: {
152
assertExhaustive(
153
attribute,
154
- `Unexpected attribute kind \`${(attribute as any).kind}\``
154
+ `Unexpected attribute kind \`${(attribute as any).kind}\``,
155
);
156
}
157
}
@@ -161,15 +161,15 @@ export function* eachInstructionValueOperand(
161
}
162
break;
163
}
164
- case "JsxFragment": {
164
+ case 'JsxFragment': {
165
yield* instrValue.children;
166
break;
167
}
168
- case "ObjectExpression": {
168
+ case 'ObjectExpression': {
169
for (const property of instrValue.properties) {
170
if (
171
- property.kind === "ObjectProperty" &&
172
- property.key.kind === "computed"
171
+ property.kind === 'ObjectProperty' &&
172
+ property.key.kind === 'computed'
173
) {
174
yield property.key.name;
175
}
@@ -177,92 +177,92 @@ export function* eachInstructionValueOperand(
177
}
178
break;
179
}
180
- case "ArrayExpression": {
180
+ case 'ArrayExpression': {
181
for (const element of instrValue.elements) {
182
- if (element.kind === "Identifier") {
182
+ if (element.kind === 'Identifier') {
183
yield element;
184
- } else if (element.kind === "Spread") {
184
+ } else if (element.kind === 'Spread') {
185
yield element.place;
186
}
187
}
188
break;
189
}
190
- case "ObjectMethod":
191
- case "FunctionExpression": {
190
+ case 'ObjectMethod':
191
+ case 'FunctionExpression': {
192
yield* instrValue.loweredFunc.dependencies;
193
break;
194
}
195
- case "TaggedTemplateExpression": {
195
+ case 'TaggedTemplateExpression': {
196
yield instrValue.tag;
197
break;
198
}
199
- case "TypeCastExpression": {
199
+ case 'TypeCastExpression': {
200
yield instrValue.value;
201
break;
202
}
203
- case "TemplateLiteral": {
203
+ case 'TemplateLiteral': {
204
yield* instrValue.subexprs;
205
break;
206
}
207
- case "Await": {
207
+ case 'Await': {
208
yield instrValue.value;
209
break;
210
}
211
- case "GetIterator": {
211
+ case 'GetIterator': {
212
yield instrValue.collection;
213
break;
214
}
215
- case "IteratorNext": {
215
+ case 'IteratorNext': {
216
yield instrValue.iterator;
217
yield instrValue.collection;
218
break;
219
}
220
- case "NextPropertyOf": {
220
+ case 'NextPropertyOf': {
221
yield instrValue.value;
222
break;
223
}
224
- case "PostfixUpdate":
225
- case "PrefixUpdate": {
224
+ case 'PostfixUpdate':
225
+ case 'PrefixUpdate': {
226
yield instrValue.value;
227
break;
228
}
229
- case "StartMemoize": {
229
+ case 'StartMemoize': {
230
if (instrValue.deps != null) {
231
for (const dep of instrValue.deps) {
232
- if (dep.root.kind === "NamedLocal") {
232
+ if (dep.root.kind === 'NamedLocal') {
233
yield dep.root.value;
234
}
235
}
236
}
237
break;
238
}
239
- case "FinishMemoize": {
239
+ case 'FinishMemoize': {
240
yield instrValue.decl;
241
break;
242
}
243
- case "Debugger":
244
- case "RegExpLiteral":
245
- case "MetaProperty":
246
- case "LoadGlobal":
247
- case "UnsupportedNode":
248
- case "Primitive":
249
- case "JSXText": {
243
+ case 'Debugger':
244
+ case 'RegExpLiteral':
245
+ case 'MetaProperty':
246
+ case 'LoadGlobal':
247
+ case 'UnsupportedNode':
248
+ case 'Primitive':
249
+ case 'JSXText': {
250
break;
251
}
252
default: {
253
assertExhaustive(
254
instrValue,
255
- `Unexpected instruction kind \`${(instrValue as any).kind}\``
255
+ `Unexpected instruction kind \`${(instrValue as any).kind}\``,
256
);
257
}
258
}
259
}
260
261
export function* eachCallArgument(
262
- args: Array<Place | SpreadPattern>
262
+ args: Array<Place | SpreadPattern>,
263
): Iterable<Place> {
264
for (const arg of args) {
265
- if (arg.kind === "Identifier") {
265
+ if (arg.kind === 'Identifier') {
266
yield arg;
267
} else {
268
yield arg.place;
@@ -272,17 +272,17 @@ export function* eachCallArgument(
272
273
export function doesPatternContainSpreadElement(pattern: Pattern): boolean {
274
switch (pattern.kind) {
275
- case "ArrayPattern": {
275
+ case 'ArrayPattern': {
276
for (const item of pattern.items) {
277
- if (item.kind === "Spread") {
277
+ if (item.kind === 'Spread') {
278
return true;
279
}
280
}
281
break;
282
}
283
- case "ObjectPattern": {
283
+ case 'ObjectPattern': {
284
for (const property of pattern.properties) {
285
- if (property.kind === "Spread") {
285
+ if (property.kind === 'Spread') {
286
return true;
287
}
288
}
@@ -291,7 +291,7 @@ export function doesPatternContainSpreadElement(pattern: Pattern): boolean {
291
default: {
292
assertExhaustive(
293
pattern,
294
- `Unexpected pattern kind \`${(pattern as any).kind}\``
294
+ `Unexpected pattern kind \`${(pattern as any).kind}\``,
295
);
296
}
297
}
@@ -300,33 +300,33 @@ export function doesPatternContainSpreadElement(pattern: Pattern): boolean {
300
301
export function* eachPatternOperand(pattern: Pattern): Iterable<Place> {
302
switch (pattern.kind) {
303
- case "ArrayPattern": {
303
+ case 'ArrayPattern': {
304
for (const item of pattern.items) {
305
- if (item.kind === "Identifier") {
305
+ if (item.kind === 'Identifier') {
306
yield item;
307
- } else if (item.kind === "Spread") {
307
+ } else if (item.kind === 'Spread') {
308
yield item.place;
309
- } else if (item.kind === "Hole") {
309
+ } else if (item.kind === 'Hole') {
310
continue;
311
} else {
312
assertExhaustive(
313
item,
314
- `Unexpected item kind \`${(item as any).kind}\``
314
+ `Unexpected item kind \`${(item as any).kind}\``,
315
);
316
}
317
}
318
break;
319
}
320
- case "ObjectPattern": {
320
+ case 'ObjectPattern': {
321
for (const property of pattern.properties) {
322
- if (property.kind === "ObjectProperty") {
322
+ if (property.kind === 'ObjectProperty') {
323
yield property.place;
324
- } else if (property.kind === "Spread") {
324
+ } else if (property.kind === 'Spread') {
325
yield property.place;
326
} else {
327
assertExhaustive(
328
property,
329
- `Unexpected item kind \`${(property as any).kind}\``
329
+ `Unexpected item kind \`${(property as any).kind}\``,
330
);
331
}
332
}
@@ -335,7 +335,7 @@ export function* eachPatternOperand(pattern: Pattern): Iterable<Place> {
335
default: {
336
assertExhaustive(
337
pattern,
338
- `Unexpected pattern kind \`${(pattern as any).kind}\``
338
+ `Unexpected pattern kind \`${(pattern as any).kind}\``,
339
);
340
}
341
}
@@ -343,21 +343,21 @@ export function* eachPatternOperand(pattern: Pattern): Iterable<Place> {
343
344
export function mapInstructionLValues(
345
instr: Instruction,
346
- fn: (place: Place) => Place
346
+ fn: (place: Place) => Place,
347
): void {
348
switch (instr.value.kind) {
349
- case "DeclareLocal":
350
- case "StoreLocal": {
349
+ case 'DeclareLocal':
350
+ case 'StoreLocal': {
351
const lvalue = instr.value.lvalue;
352
lvalue.place = fn(lvalue.place);
353
break;
354
}
355
- case "Destructure": {
355
+ case 'Destructure': {
356
mapPatternOperands(instr.value.lvalue.pattern, fn);
357
break;
358
}
359
- case "PostfixUpdate":
360
- case "PrefixUpdate": {
359
+ case 'PostfixUpdate':
360
+ case 'PrefixUpdate': {
361
instr.value.lvalue = fn(instr.value.lvalue);
362
break;
363
}
@@ -369,124 +369,124 @@ export function mapInstructionLValues(
369
370
export function mapInstructionOperands(
371
instr: Instruction,
372
- fn: (place: Place) => Place
372
+ fn: (place: Place) => Place,
373
): void {
374
mapInstructionValueOperands(instr.value, fn);
375
}
376
377
export function mapInstructionValueOperands(
378
instrValue: InstructionValue,
379
- fn: (place: Place) => Place
379
+ fn: (place: Place) => Place,
380
): void {
381
switch (instrValue.kind) {
382
- case "BinaryExpression": {
382
+ case 'BinaryExpression': {
383
instrValue.left = fn(instrValue.left);
384
instrValue.right = fn(instrValue.right);
385
break;
386
}
387
- case "PropertyLoad": {
387
+ case 'PropertyLoad': {
388
instrValue.object = fn(instrValue.object);
389
break;
390
}
391
- case "PropertyDelete": {
391
+ case 'PropertyDelete': {
392
instrValue.object = fn(instrValue.object);
393
break;
394
}
395
- case "PropertyStore": {
395
+ case 'PropertyStore': {
396
instrValue.object = fn(instrValue.object);
397
instrValue.value = fn(instrValue.value);
398
break;
399
}
400
- case "ComputedLoad": {
400
+ case 'ComputedLoad': {
401
instrValue.object = fn(instrValue.object);
402
instrValue.property = fn(instrValue.property);
403
break;
404
}
405
- case "ComputedDelete": {
405
+ case 'ComputedDelete': {
406
instrValue.object = fn(instrValue.object);
407
instrValue.property = fn(instrValue.property);
408
break;
409
}
410
- case "ComputedStore": {
410
+ case 'ComputedStore': {
411
instrValue.object = fn(instrValue.object);
412
instrValue.property = fn(instrValue.property);
413
instrValue.value = fn(instrValue.value);
414
break;
415
}
416
- case "DeclareContext":
417
- case "DeclareLocal": {
416
+ case 'DeclareContext':
417
+ case 'DeclareLocal': {
418
break;
419
}
420
- case "LoadLocal":
421
- case "LoadContext": {
420
+ case 'LoadLocal':
421
+ case 'LoadContext': {
422
instrValue.place = fn(instrValue.place);
423
break;
424
}
425
- case "StoreLocal": {
425
+ case 'StoreLocal': {
426
instrValue.value = fn(instrValue.value);
427
break;
428
}
429
- case "StoreContext": {
429
+ case 'StoreContext': {
430
instrValue.lvalue.place = fn(instrValue.lvalue.place);
431
instrValue.value = fn(instrValue.value);
432
break;
433
}
434
- case "StoreGlobal": {
434
+ case 'StoreGlobal': {
435
instrValue.value = fn(instrValue.value);
436
break;
437
}
438
- case "Destructure": {
438
+ case 'Destructure': {
439
instrValue.value = fn(instrValue.value);
440
break;
441
}
442
- case "NewExpression":
443
- case "CallExpression": {
442
+ case 'NewExpression':
443
+ case 'CallExpression': {
444
instrValue.callee = fn(instrValue.callee);
445
instrValue.args = mapCallArguments(instrValue.args, fn);
446
break;
447
}
448
- case "MethodCall": {
448
+ case 'MethodCall': {
449
instrValue.receiver = fn(instrValue.receiver);
450
instrValue.property = fn(instrValue.property);
451
instrValue.args = mapCallArguments(instrValue.args, fn);
452
break;
453
}
454
- case "UnaryExpression": {
454
+ case 'UnaryExpression': {
455
instrValue.value = fn(instrValue.value);
456
break;
457
}
458
- case "JsxExpression": {
459
- if (instrValue.tag.kind === "Identifier") {
458
+ case 'JsxExpression': {
459
+ if (instrValue.tag.kind === 'Identifier') {
460
instrValue.tag = fn(instrValue.tag);
461
}
462
for (const attribute of instrValue.props) {
463
switch (attribute.kind) {
464
- case "JsxAttribute": {
464
+ case 'JsxAttribute': {
465
attribute.place = fn(attribute.place);
466
break;
467
}
468
- case "JsxSpreadAttribute": {
468
+ case 'JsxSpreadAttribute': {
469
attribute.argument = fn(attribute.argument);
470
break;
471
}
472
default: {
473
assertExhaustive(
474
attribute,
475
- `Unexpected attribute kind \`${(attribute as any).kind}\``
475
+ `Unexpected attribute kind \`${(attribute as any).kind}\``,
476
);
477
}
478
}
479
}
480
if (instrValue.children) {
481
- instrValue.children = instrValue.children.map((p) => fn(p));
481
+ instrValue.children = instrValue.children.map(p => fn(p));
482
}
483
break;
484
}
485
- case "ObjectExpression": {
485
+ case 'ObjectExpression': {
486
for (const property of instrValue.properties) {
487
if (
488
- property.kind === "ObjectProperty" &&
489
- property.key.kind === "computed"
488
+ property.kind === 'ObjectProperty' &&
489
+ property.key.kind === 'computed'
490
) {
491
property.key.name = fn(property.key.name);
492
}
@@ -494,11 +494,11 @@ export function mapInstructionValueOperands(
494
}
495
break;
496
}
497
- case "ArrayExpression": {
498
- instrValue.elements = instrValue.elements.map((element) => {
499
- if (element.kind === "Identifier") {
497
+ case 'ArrayExpression': {
498
+ instrValue.elements = instrValue.elements.map(element => {
499
+ if (element.kind === 'Identifier') {
500
return fn(element);
501
- } else if (element.kind === "Spread") {
501
+ } else if (element.kind === 'Spread') {
502
element.place = fn(element.place);
503
return element;
504
} else {
@@ -507,85 +507,85 @@ export function mapInstructionValueOperands(
507
});
508
break;
509
}
510
- case "JsxFragment": {
511
- instrValue.children = instrValue.children.map((e) => fn(e));
510
+ case 'JsxFragment': {
511
+ instrValue.children = instrValue.children.map(e => fn(e));
512
break;
513
}
514
- case "ObjectMethod":
515
- case "FunctionExpression": {
514
+ case 'ObjectMethod':
515
+ case 'FunctionExpression': {
516
instrValue.loweredFunc.dependencies =
517
- instrValue.loweredFunc.dependencies.map((d) => fn(d));
517
+ instrValue.loweredFunc.dependencies.map(d => fn(d));
518
break;
519
}
520
- case "TaggedTemplateExpression": {
520
+ case 'TaggedTemplateExpression': {
521
instrValue.tag = fn(instrValue.tag);
522
break;
523
}
524
- case "TypeCastExpression": {
524
+ case 'TypeCastExpression': {
525
instrValue.value = fn(instrValue.value);
526
break;
527
}
528
- case "TemplateLiteral": {
528
+ case 'TemplateLiteral': {
529
instrValue.subexprs = instrValue.subexprs.map(fn);
530
break;
531
}
532
- case "Await": {
532
+ case 'Await': {
533
instrValue.value = fn(instrValue.value);
534
break;
535
}
536
- case "GetIterator": {
536
+ case 'GetIterator': {
537
instrValue.collection = fn(instrValue.collection);
538
break;
539
}
540
- case "IteratorNext": {
540
+ case 'IteratorNext': {
541
instrValue.iterator = fn(instrValue.iterator);
542
instrValue.collection = fn(instrValue.collection);
543
break;
544
}
545
- case "NextPropertyOf": {
545
+ case 'NextPropertyOf': {
546
instrValue.value = fn(instrValue.value);
547
break;
548
}
549
- case "PostfixUpdate":
550
- case "PrefixUpdate": {
549
+ case 'PostfixUpdate':
550
+ case 'PrefixUpdate': {
551
instrValue.value = fn(instrValue.value);
552
break;
553
}
554
- case "StartMemoize": {
554
+ case 'StartMemoize': {
555
if (instrValue.deps != null) {
556
for (const dep of instrValue.deps) {
557
- if (dep.root.kind === "NamedLocal") {
557
+ if (dep.root.kind === 'NamedLocal') {
558
dep.root.value = fn(dep.root.value);
559
}
560
}
561
}
562
break;
563
}
564
- case "FinishMemoize": {
564
+ case 'FinishMemoize': {
565
instrValue.decl = fn(instrValue.decl);
566
break;
567
}
568
- case "Debugger":
569
- case "RegExpLiteral":
570
- case "MetaProperty":
571
- case "LoadGlobal":
572
- case "UnsupportedNode":
573
- case "Primitive":
574
- case "JSXText": {
568
+ case 'Debugger':
569
+ case 'RegExpLiteral':
570
+ case 'MetaProperty':
571
+ case 'LoadGlobal':
572
+ case 'UnsupportedNode':
573
+ case 'Primitive':
574
+ case 'JSXText': {
575
break;
576
}
577
default: {
578
- assertExhaustive(instrValue, "Unexpected instruction kind");
578
+ assertExhaustive(instrValue, 'Unexpected instruction kind');
579
}
580
}
581
}
582
583
export function mapCallArguments(
584
args: Array<Place | SpreadPattern>,
585
- fn: (place: Place) => Place
585
+ fn: (place: Place) => Place,
586
): Array<Place | SpreadPattern> {
587
- return args.map((arg) => {
588
- if (arg.kind === "Identifier") {
587
+ return args.map(arg => {
588
+ if (arg.kind === 'Identifier') {
589
return fn(arg);
590
} else {
591
arg.place = fn(arg.place);
@@ -596,14 +596,14 @@ export function mapCallArguments(
596
597
export function mapPatternOperands(
598
pattern: Pattern,
599
- fn: (place: Place) => Place
599
+ fn: (place: Place) => Place,
600
): void {
601
switch (pattern.kind) {
602
- case "ArrayPattern": {
603
- pattern.items = pattern.items.map((item) => {
604
- if (item.kind === "Identifier") {
602
+ case 'ArrayPattern': {
603
+ pattern.items = pattern.items.map(item => {
604
+ if (item.kind === 'Identifier') {
605
return fn(item);
606
- } else if (item.kind === "Spread") {
606
+ } else if (item.kind === 'Spread') {
607
item.place = fn(item.place);
608
return item;
609
} else {
@@ -612,7 +612,7 @@ export function mapPatternOperands(
612
});
613
break;
614
}
615
- case "ObjectPattern": {
615
+ case 'ObjectPattern': {
616
for (const property of pattern.properties) {
617
property.place = fn(property.place);
618
}
@@ -621,7 +621,7 @@ export function mapPatternOperands(
621
default: {
622
assertExhaustive(
623
pattern,
624
- `Unexpected pattern kind \`${(pattern as any).kind}\``
624
+ `Unexpected pattern kind \`${(pattern as any).kind}\``,
625
);
626
}
627
}
@@ -630,25 +630,25 @@ export function mapPatternOperands(
630
// Maps a terminal node's block assignments using the provided function.
631
export function mapTerminalSuccessors(
632
terminal: Terminal,
633
- fn: (block: BlockId) => BlockId
633
+ fn: (block: BlockId) => BlockId,
634
): Terminal {
635
switch (terminal.kind) {
636
- case "goto": {
636
+ case 'goto': {
637
const target = fn(terminal.block);
638
return {
639
- kind: "goto",
639
+ kind: 'goto',
640
block: target,
641
variant: terminal.variant,
642
id: makeInstructionId(0),
643
loc: terminal.loc,
644
};
645
}
646
- case "if": {
646
+ case 'if': {
647
const consequent = fn(terminal.consequent);
648
const alternate = fn(terminal.alternate);
649
const fallthrough = fn(terminal.fallthrough);
650
return {
651
- kind: "if",
651
+ kind: 'if',
652
test: terminal.test,
653
consequent,
654
alternate,
@@ -657,11 +657,11 @@ export function mapTerminalSuccessors(
657
loc: terminal.loc,
658
};
659
}
660
- case "branch": {
660
+ case 'branch': {
661
const consequent = fn(terminal.consequent);
662
const alternate = fn(terminal.alternate);
663
return {
664
- kind: "branch",
664
+ kind: 'branch',
665
test: terminal.test,
666
consequent,
667
alternate,
@@ -669,8 +669,8 @@ export function mapTerminalSuccessors(
669
loc: terminal.loc,
670
};
671
}
672
- case "switch": {
673
- const cases = terminal.cases.map((case_) => {
672
+ case 'switch': {
673
+ const cases = terminal.cases.map(case_ => {
674
const target = fn(case_.block);
675
return {
676
test: case_.test,
@@ -679,7 +679,7 @@ export function mapTerminalSuccessors(
679
});
680
const fallthrough = fn(terminal.fallthrough);
681
return {
682
- kind: "switch",
682
+ kind: 'switch',
683
test: terminal.test,
684
cases,
685
fallthrough,
@@ -687,11 +687,11 @@ export function mapTerminalSuccessors(
687
loc: terminal.loc,
688
};
689
}
690
- case "logical": {
690
+ case 'logical': {
691
const test = fn(terminal.test);
692
const fallthrough = fn(terminal.fallthrough);
693
return {
694
- kind: "logical",
694
+ kind: 'logical',
695
test,
696
fallthrough,
697
operator: terminal.operator,
@@ -699,22 +699,22 @@ export function mapTerminalSuccessors(
699
loc: terminal.loc,
700
};
701
}
702
- case "ternary": {
702
+ case 'ternary': {
703
const test = fn(terminal.test);
704
const fallthrough = fn(terminal.fallthrough);
705
return {
706
- kind: "ternary",
706
+ kind: 'ternary',
707
test,
708
fallthrough,
709
id: makeInstructionId(0),
710
loc: terminal.loc,
711
};
712
}
713
- case "optional": {
713
+ case 'optional': {
714
const test = fn(terminal.test);
715
const fallthrough = fn(terminal.fallthrough);
716
return {
717
- kind: "optional",
717
+ kind: 'optional',
718
optional: terminal.optional,
719
test,
720
fallthrough,
@@ -722,23 +722,23 @@ export function mapTerminalSuccessors(
722
loc: terminal.loc,
723
};
724
}
725
- case "return": {
725
+ case 'return': {
726
return {
727
- kind: "return",
727
+ kind: 'return',
728
loc: terminal.loc,
729
value: terminal.value,
730
id: makeInstructionId(0),
731
};
732
}
733
- case "throw": {
733
+ case 'throw': {
734
return terminal;
735
}
736
- case "do-while": {
736
+ case 'do-while': {
737
const loop = fn(terminal.loop);
738
const test = fn(terminal.test);
739
const fallthrough = fn(terminal.fallthrough);
740
return {
741
- kind: "do-while",
741
+ kind: 'do-while',
742
loc: terminal.loc,
743
test,
744
loop,
@@ -746,12 +746,12 @@ export function mapTerminalSuccessors(
746
id: makeInstructionId(0),
747
};
748
}
749
- case "while": {
749
+ case 'while': {
750
const test = fn(terminal.test);
751
const loop = fn(terminal.loop);
752
const fallthrough = fn(terminal.fallthrough);
753
return {
754
- kind: "while",
754
+ kind: 'while',
755
loc: terminal.loc,
756
test,
757
loop,
@@ -759,14 +759,14 @@ export function mapTerminalSuccessors(
759
id: makeInstructionId(0),
760
};
761
}
762
- case "for": {
762
+ case 'for': {
763
const init = fn(terminal.init);
764
const test = fn(terminal.test);
765
const update = terminal.update !== null ? fn(terminal.update) : null;
766
const loop = fn(terminal.loop);
767
const fallthrough = fn(terminal.fallthrough);
768
return {
769
- kind: "for",
769
+ kind: 'for',
770
loc: terminal.loc,
771
init,
772
test,
@@ -776,13 +776,13 @@ export function mapTerminalSuccessors(
776
id: makeInstructionId(0),
777
};
778
}
779
- case "for-of": {
779
+ case 'for-of': {
780
const init = fn(terminal.init);
781
const loop = fn(terminal.loop);
782
const test = fn(terminal.test);
783
const fallthrough = fn(terminal.fallthrough);
784
return {
785
- kind: "for-of",
785
+ kind: 'for-of',
786
loc: terminal.loc,
787
init,
788
test,
@@ -791,12 +791,12 @@ export function mapTerminalSuccessors(
791
id: makeInstructionId(0),
792
};
793
}
794
- case "for-in": {
794
+ case 'for-in': {
795
const init = fn(terminal.init);
796
const loop = fn(terminal.loop);
797
const fallthrough = fn(terminal.fallthrough);
798
return {
799
- kind: "for-in",
799
+ kind: 'for-in',
800
loc: terminal.loc,
801
init,
802
loop,
@@ -804,45 +804,45 @@ export function mapTerminalSuccessors(
804
id: makeInstructionId(0),
805
};
806
}
807
- case "label": {
807
+ case 'label': {
808
const block = fn(terminal.block);
809
const fallthrough = fn(terminal.fallthrough);
810
return {
811
- kind: "label",
811
+ kind: 'label',
812
block,
813
fallthrough,
814
id: makeInstructionId(0),
815
loc: terminal.loc,
816
};
817
}
818
- case "sequence": {
818
+ case 'sequence': {
819
const block = fn(terminal.block);
820
const fallthrough = fn(terminal.fallthrough);
821
return {
822
- kind: "sequence",
822
+ kind: 'sequence',
823
block,
824
fallthrough,
825
id: makeInstructionId(0),
826
loc: terminal.loc,
827
};
828
}
829
- case "maybe-throw": {
829
+ case 'maybe-throw': {
830
const continuation = fn(terminal.continuation);
831
const handler = fn(terminal.handler);
832
return {
833
- kind: "maybe-throw",
833
+ kind: 'maybe-throw',
834
continuation,
835
handler,
836
id: makeInstructionId(0),
837
loc: terminal.loc,
838
};
839
}
840
- case "try": {
840
+ case 'try': {
841
const block = fn(terminal.block);
842
const handler = fn(terminal.handler);
843
const fallthrough = fn(terminal.fallthrough);
844
return {
845
- kind: "try",
845
+ kind: 'try',
846
block,
847
handlerBinding: terminal.handlerBinding,
848
handler,
@@ -851,8 +851,8 @@ export function mapTerminalSuccessors(
851
loc: terminal.loc,
852
};
853
}
854
- case "scope":
855
- case "pruned-scope": {
854
+ case 'scope':
855
+ case 'pruned-scope': {
856
const block = fn(terminal.block);
857
const fallthrough = fn(terminal.fallthrough);
858
return {
@@ -864,14 +864,14 @@ export function mapTerminalSuccessors(
864
loc: terminal.loc,
865
};
866
}
867
- case "unreachable":
868
- case "unsupported": {
867
+ case 'unreachable':
868
+ case 'unsupported': {
869
return terminal;
870
}
871
default: {
872
assertExhaustive(
873
terminal,
874
- `Unexpected terminal kind \`${(terminal as any as Terminal).kind}\``
874
+ `Unexpected terminal kind \`${(terminal as any as Terminal).kind}\``,
875
);
876
}
877
}
@@ -879,41 +879,41 @@ export function mapTerminalSuccessors(
879
880
export function terminalHasFallthrough<
881
T extends Terminal,
882
- U extends T & { fallthrough: BlockId },
882
+ U extends T & {fallthrough: BlockId},
883
>(terminal: T): terminal is U {
884
switch (terminal.kind) {
885
- case "maybe-throw":
886
- case "branch":
887
- case "goto":
888
- case "return":
889
- case "throw":
890
- case "unreachable":
891
- case "unsupported": {
885
+ case 'maybe-throw':
886
+ case 'branch':
887
+ case 'goto':
888
+ case 'return':
889
+ case 'throw':
890
+ case 'unreachable':
891
+ case 'unsupported': {
892
const _: undefined = terminal.fallthrough;
893
return false;
894
}
895
- case "try":
896
- case "do-while":
897
- case "for-of":
898
- case "for-in":
899
- case "for":
900
- case "if":
901
- case "label":
902
- case "logical":
903
- case "optional":
904
- case "sequence":
905
- case "switch":
906
- case "ternary":
907
- case "while":
908
- case "scope":
909
- case "pruned-scope": {
895
+ case 'try':
896
+ case 'do-while':
897
+ case 'for-of':
898
+ case 'for-in':
899
+ case 'for':
900
+ case 'if':
901
+ case 'label':
902
+ case 'logical':
903
+ case 'optional':
904
+ case 'sequence':
905
+ case 'switch':
906
+ case 'ternary':
907
+ case 'while':
908
+ case 'scope':
909
+ case 'pruned-scope': {
910
const _: BlockId = terminal.fallthrough;
911
return true;
912
}
913
default: {
914
assertExhaustive(
915
terminal,
916
- `Unexpected terminal kind \`${(terminal as any).kind}\``
916
+ `Unexpected terminal kind \`${(terminal as any).kind}\``,
917
);
918
}
919
}
@@ -939,87 +939,87 @@ export function terminalFallthrough(terminal: Terminal): BlockId | null {
939
*/
940
export function* eachTerminalSuccessor(terminal: Terminal): Iterable<BlockId> {
941
switch (terminal.kind) {
942
- case "goto": {
942
+ case 'goto': {
943
yield terminal.block;
944
break;
945
}
946
- case "if": {
946
+ case 'if': {
947
yield terminal.consequent;
948
yield terminal.alternate;
949
break;
950
}
951
- case "branch": {
951
+ case 'branch': {
952
yield terminal.consequent;
953
yield terminal.alternate;
954
break;
955
}
956
- case "switch": {
956
+ case 'switch': {
957
for (const case_ of terminal.cases) {
958
yield case_.block;
959
}
960
break;
961
}
962
- case "optional":
963
- case "ternary":
964
- case "logical": {
962
+ case 'optional':
963
+ case 'ternary':
964
+ case 'logical': {
965
yield terminal.test;
966
break;
967
}
968
- case "return": {
968
+ case 'return': {
969
break;
970
}
971
- case "throw": {
971
+ case 'throw': {
972
break;
973
}
974
- case "do-while": {
974
+ case 'do-while': {
975
yield terminal.loop;
976
break;
977
}
978
- case "while": {
978
+ case 'while': {
979
yield terminal.test;
980
break;
981
}
982
- case "for": {
982
+ case 'for': {
983
yield terminal.init;
984
break;
985
}
986
- case "for-of": {
986
+ case 'for-of': {
987
yield terminal.init;
988
break;
989
}
990
- case "for-in": {
990
+ case 'for-in': {
991
yield terminal.init;
992
break;
993
}
994
- case "label": {
994
+ case 'label': {
995
yield terminal.block;
996
break;
997
}
998
- case "sequence": {
998
+ case 'sequence': {
999
yield terminal.block;
1000
break;
1001
}
1002
- case "maybe-throw": {
1002
+ case 'maybe-throw': {
1003
yield terminal.continuation;
1004
yield terminal.handler;
1005
break;
1006
}
1007
- case "try": {
1007
+ case 'try': {
1008
yield terminal.block;
1009
break;
1010
}
1011
- case "scope":
1012
- case "pruned-scope": {
1011
+ case 'scope':
1012
+ case 'pruned-scope': {
1013
yield terminal.block;
1014
break;
1015
}
1016
- case "unreachable":
1017
- case "unsupported":
1016
+ case 'unreachable':
1017
+ case 'unsupported':
1018
break;
1019
default: {
1020
assertExhaustive(
1021
terminal,
1022
- `Unexpected terminal kind \`${(terminal as any as Terminal).kind}\``
1022
+ `Unexpected terminal kind \`${(terminal as any as Terminal).kind}\``,
1023
);
1024
}
1025
}
@@ -1027,18 +1027,18 @@ export function* eachTerminalSuccessor(terminal: Terminal): Iterable<BlockId> {
1027
1028
export function mapTerminalOperands(
1029
terminal: Terminal,
1030
- fn: (place: Place) => Place
1030
+ fn: (place: Place) => Place,
1031
): void {
1032
switch (terminal.kind) {
1033
- case "if": {
1033
+ case 'if': {
1034
terminal.test = fn(terminal.test);
1035
break;
1036
}
1037
- case "branch": {
1037
+ case 'branch': {
1038
terminal.test = fn(terminal.test);
1039
break;
1040
}
1041
- case "switch": {
1041
+ case 'switch': {
1042
terminal.test = fn(terminal.test);
1043
for (const case_ of terminal.cases) {
1044
if (case_.test === null) {
@@ -1048,12 +1048,12 @@ export function mapTerminalOperands(
1048
}
1049
break;
1050
}
1051
- case "return":
1052
- case "throw": {
1051
+ case 'return':
1052
+ case 'throw': {
1053
terminal.value = fn(terminal.value);
1054
break;
1055
}
1056
- case "try": {
1056
+ case 'try': {
1057
if (terminal.handlerBinding !== null) {
1058
terminal.handlerBinding = fn(terminal.handlerBinding);
1059
} else {
@@ -1061,29 +1061,29 @@ export function mapTerminalOperands(
1061
}
1062
break;
1063
}
1064
- case "maybe-throw":
1065
- case "sequence":
1066
- case "label":
1067
- case "optional":
1068
- case "ternary":
1069
- case "logical":
1070
- case "do-while":
1071
- case "while":
1072
- case "for":
1073
- case "for-of":
1074
- case "for-in":
1075
- case "goto":
1076
- case "unreachable":
1077
- case "unsupported":
1078
- case "scope":
1079
- case "pruned-scope": {
1064
+ case 'maybe-throw':
1065
+ case 'sequence':
1066
+ case 'label':
1067
+ case 'optional':
1068
+ case 'ternary':
1069
+ case 'logical':
1070
+ case 'do-while':
1071
+ case 'while':
1072
+ case 'for':
1073
+ case 'for-of':
1074
+ case 'for-in':
1075
+ case 'goto':
1076
+ case 'unreachable':
1077
+ case 'unsupported':
1078
+ case 'scope':
1079
+ case 'pruned-scope': {
1080
// no-op
1081
break;
1082
}
1083
default: {
1084
assertExhaustive(
1085
terminal,
1086
- `Unexpected terminal kind \`${(terminal as any).kind}\``
1086
+ `Unexpected terminal kind \`${(terminal as any).kind}\``,
1087
);
1088
}
1089
}
@@ -1091,15 +1091,15 @@ export function mapTerminalOperands(
1091
1092
export function* eachTerminalOperand(terminal: Terminal): Iterable<Place> {
1093
switch (terminal.kind) {
1094
- case "if": {
1094
+ case 'if': {
1095
yield terminal.test;
1096
break;
1097
}
1098
- case "branch": {
1098
+ case 'branch': {
1099
yield terminal.test;
1100
break;
1101
}
1102
- case "switch": {
1102
+ case 'switch': {
1103
yield terminal.test;
1104
for (const case_ of terminal.cases) {
1105
if (case_.test === null) {
@@ -1109,40 +1109,40 @@ export function* eachTerminalOperand(terminal: Terminal): Iterable<Place> {
1109
}
1110
break;
1111
}
1112
- case "return":
1113
- case "throw": {
1112
+ case 'return':
1113
+ case 'throw': {
1114
yield terminal.value;
1115
break;
1116
}
1117
- case "try": {
1117
+ case 'try': {
1118
if (terminal.handlerBinding !== null) {
1119
yield terminal.handlerBinding;
1120
}
1121
break;
1122
}
1123
- case "maybe-throw":
1124
- case "sequence":
1125
- case "label":
1126
- case "optional":
1127
- case "ternary":
1128
- case "logical":
1129
- case "do-while":
1130
- case "while":
1131
- case "for":
1132
- case "for-of":
1133
- case "for-in":
1134
- case "goto":
1135
- case "unreachable":
1136
- case "unsupported":
1137
- case "scope":
1138
- case "pruned-scope": {
1123
+ case 'maybe-throw':
1124
+ case 'sequence':
1125
+ case 'label':
1126
+ case 'optional':
1127
+ case 'ternary':
1128
+ case 'logical':
1129
+ case 'do-while':
1130
+ case 'while':
1131
+ case 'for':
1132
+ case 'for-of':
1133
+ case 'for-in':
1134
+ case 'goto':
1135
+ case 'unreachable':
1136
+ case 'unsupported':
1137
+ case 'scope':
1138
+ case 'pruned-scope': {
1139
// no-op
1140
break;
1141
}
1142
default: {
1143
assertExhaustive(
1144
terminal,
1145
- `Unexpected terminal kind \`${(terminal as any).kind}\``
1145
+ `Unexpected terminal kind \`${(terminal as any).kind}\``,
1146
);
1147
}
1148
}
compiler/packages/babel-plugin-react-compiler/src/Inference/AnalyseFunctions.ts
+23
-23
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
8
+import {CompilerError} from '../CompilerError';
9
import {
10
Effect,
11
HIRFunction,
@@ -17,14 +17,14 @@ import {
17
isRefValueType,
18
isUseRefType,
19
makeInstructionId,
20
-} from "../HIR";
21
-import { deadCodeElimination } from "../Optimization";
22
-import { inferReactiveScopeVariables } from "../ReactiveScopes";
23
-import { leaveSSA } from "../SSA";
24
-import { logHIRFunction } from "../Utils/logger";
25
-import { inferMutableContextVariables } from "./InferMutableContextVariables";
26
-import { inferMutableRanges } from "./InferMutableRanges";
27
-import inferReferenceEffects from "./InferReferenceEffects";
20
+} from '../HIR';
21
+import {deadCodeElimination} from '../Optimization';
22
+import {inferReactiveScopeVariables} from '../ReactiveScopes';
23
+import {leaveSSA} from '../SSA';
24
+import {logHIRFunction} from '../Utils/logger';
25
+import {inferMutableContextVariables} from './InferMutableContextVariables';
26
+import {inferMutableRanges} from './InferMutableRanges';
27
+import inferReferenceEffects from './InferReferenceEffects';
28
29
// Helper class to track indirections such as LoadLocal and PropertyLoad.
30
export class IdentifierState {
@@ -42,7 +42,7 @@ export class IdentifierState {
42
const objectDependency = this.properties.get(object.identifier);
43
let nextDependency: ReactiveScopeDependency;
44
if (objectDependency === undefined) {
45
- nextDependency = { identifier: object.identifier, path: [property] };
45
+ nextDependency = {identifier: object.identifier, path: [property]};
46
} else {
47
nextDependency = {
48
identifier: objectDependency.identifier,
@@ -54,7 +54,7 @@ export class IdentifierState {
54
55
declareTemporary(lvalue: Place, value: Place): void {
56
const resolved: ReactiveScopeDependency = this.properties.get(
57
- value.identifier
57
+ value.identifier,
58
) ?? {
59
identifier: value.identifier,
60
path: [],
@@ -69,30 +69,30 @@ export default function analyseFunctions(func: HIRFunction): void {
69
for (const [_, block] of func.body.blocks) {
70
for (const instr of block.instructions) {
71
switch (instr.value.kind) {
72
- case "ObjectMethod":
73
- case "FunctionExpression": {
72
+ case 'ObjectMethod':
73
+ case 'FunctionExpression': {
74
lower(instr.value.loweredFunc.func);
75
infer(instr.value.loweredFunc, state, func.context);
76
break;
77
}
78
- case "PropertyLoad": {
78
+ case 'PropertyLoad': {
79
state.declareProperty(
80
instr.lvalue,
81
instr.value.object,
82
- instr.value.property
82
+ instr.value.property,
83
);
84
break;
85
}
86
- case "ComputedLoad": {
86
+ case 'ComputedLoad': {
87
/*
88
* The path is set to an empty string as the path doesn't really
89
* matter for a computed load.
90
*/
91
- state.declareProperty(instr.lvalue, instr.value.object, "");
91
+ state.declareProperty(instr.lvalue, instr.value.object, '');
92
break;
93
}
94
- case "LoadLocal":
95
- case "LoadContext": {
94
+ case 'LoadLocal':
95
+ case 'LoadContext': {
96
if (instr.lvalue.identifier.name === null) {
97
state.declareTemporary(instr.lvalue, instr.value.place);
98
}
@@ -105,19 +105,19 @@ export default function analyseFunctions(func: HIRFunction): void {
105
106
function lower(func: HIRFunction): void {
107
analyseFunctions(func);
108
- inferReferenceEffects(func, { isFunctionExpression: true });
108
+ inferReferenceEffects(func, {isFunctionExpression: true});
109
deadCodeElimination(func);
110
inferMutableRanges(func);
111
leaveSSA(func);
112
inferReactiveScopeVariables(func);
113
inferMutableContextVariables(func);
114
- logHIRFunction("AnalyseFunction (inner)", func);
114
+ logHIRFunction('AnalyseFunction (inner)', func);
115
}
116
117
function infer(
118
loweredFunc: LoweredFunction,
119
state: IdentifierState,
120
- context: Array<Place>
120
+ context: Array<Place>,
121
): void {
122
const mutations = new Map<string, Effect>();
123
for (const operand of loweredFunc.func.context) {
@@ -166,7 +166,7 @@ function infer(
166
*/
167
for (const place of context) {
168
CompilerError.invariant(place.identifier.name !== null, {
169
- reason: "context refs should always have a name",
169
+ reason: 'context refs should always have a name',
170
description: null,
171
loc: place.loc,
172
suggestions: null,
compiler/packages/babel-plugin-react-compiler/src/Inference/DropManualMemoization.ts
+50
-50
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError, SourceLocation } from "..";
8
+import {CompilerError, SourceLocation} from '..';
9
import {
10
CallExpression,
11
Effect,
@@ -28,11 +28,11 @@ import {
28
TInstruction,
29
getHookKindForType,
30
makeInstructionId,
31
-} from "../HIR";
32
-import { createTemporaryPlace, markInstructionIds } from "../HIR/HIRBuilder";
31
+} from '../HIR';
32
+import {createTemporaryPlace, markInstructionIds} from '../HIR/HIRBuilder';
33
34
type ManualMemoCallee = {
35
- kind: "useMemo" | "useCallback";
35
+ kind: 'useMemo' | 'useCallback';
36
loadInstr: TInstruction<LoadGlobal> | TInstruction<PropertyLoad>;
37
};
38
@@ -51,19 +51,19 @@ type IdentifierSidemap = {
51
*/
52
export function collectMaybeMemoDependencies(
53
value: InstructionValue,
54
- maybeDeps: Map<IdentifierId, ManualMemoDependency>
54
+ maybeDeps: Map<IdentifierId, ManualMemoDependency>,
55
): ManualMemoDependency | null {
56
switch (value.kind) {
57
- case "LoadGlobal": {
57
+ case 'LoadGlobal': {
58
return {
59
root: {
60
- kind: "Global",
60
+ kind: 'Global',
61
identifierName: value.binding.name,
62
},
63
path: [],
64
};
65
}
66
- case "PropertyLoad": {
66
+ case 'PropertyLoad': {
67
const object = maybeDeps.get(value.object.identifier.id);
68
if (object != null) {
69
return {
@@ -74,26 +74,26 @@ export function collectMaybeMemoDependencies(
74
break;
75
}
76
77
- case "LoadLocal":
78
- case "LoadContext": {
77
+ case 'LoadLocal':
78
+ case 'LoadContext': {
79
const source = maybeDeps.get(value.place.identifier.id);
80
if (source != null) {
81
return source;
82
} else if (
83
value.place.identifier.name != null &&
84
- value.place.identifier.name.kind === "named"
84
+ value.place.identifier.name.kind === 'named'
85
) {
86
return {
87
root: {
88
- kind: "NamedLocal",
89
- value: { ...value.place },
88
+ kind: 'NamedLocal',
89
+ value: {...value.place},
90
},
91
path: [],
92
};
93
}
94
break;
95
}
96
- case "StoreLocal": {
96
+ case 'StoreLocal': {
97
/*
98
* Value blocks rely on StoreLocal to populate their return value.
99
* We need to track these as optional property chains are valid in
@@ -102,7 +102,7 @@ export function collectMaybeMemoDependencies(
102
const lvalue = value.lvalue.place.identifier;
103
const rvalue = value.value.identifier.id;
104
const aliased = maybeDeps.get(rvalue);
105
- if (aliased != null && lvalue.name?.kind !== "named") {
105
+ if (aliased != null && lvalue.name?.kind !== 'named') {
106
maybeDeps.set(lvalue.id, aliased);
107
return aliased;
108
}
@@ -115,34 +115,34 @@ export function collectMaybeMemoDependencies(
115
function collectTemporaries(
116
instr: Instruction,
117
env: Environment,
118
- sidemap: IdentifierSidemap
118
+ sidemap: IdentifierSidemap,
119
): void {
120
- const { value, lvalue } = instr;
120
+ const {value, lvalue} = instr;
121
switch (value.kind) {
122
- case "FunctionExpression": {
122
+ case 'FunctionExpression': {
123
sidemap.functions.set(
124
instr.lvalue.identifier.id,
125
- instr as TInstruction<FunctionExpression>
125
+ instr as TInstruction<FunctionExpression>,
126
);
127
break;
128
}
129
- case "LoadGlobal": {
129
+ case 'LoadGlobal': {
130
const global = env.getGlobalDeclaration(value.binding);
131
const hookKind = global !== null ? getHookKindForType(env, global) : null;
132
const lvalId = instr.lvalue.identifier.id;
133
- if (hookKind === "useMemo" || hookKind === "useCallback") {
133
+ if (hookKind === 'useMemo' || hookKind === 'useCallback') {
134
sidemap.manualMemos.set(lvalId, {
135
kind: hookKind,
136
loadInstr: instr as TInstruction<LoadGlobal>,
137
});
138
- } else if (value.binding.name === "React") {
138
+ } else if (value.binding.name === 'React') {
139
sidemap.react.add(lvalId);
140
}
141
break;
142
}
143
- case "PropertyLoad": {
143
+ case 'PropertyLoad': {
144
if (sidemap.react.has(value.object.identifier.id)) {
145
- if (value.property === "useMemo" || value.property === "useCallback") {
145
+ if (value.property === 'useMemo' || value.property === 'useCallback') {
146
sidemap.manualMemos.set(instr.lvalue.identifier.id, {
147
kind: value.property,
148
loadInstr: instr as TInstruction<PropertyLoad>,
@@ -151,11 +151,11 @@ function collectTemporaries(
151
}
152
break;
153
}
154
- case "ArrayExpression": {
155
- if (value.elements.every((e) => e.kind === "Identifier")) {
154
+ case 'ArrayExpression': {
155
+ if (value.elements.every(e => e.kind === 'Identifier')) {
156
sidemap.maybeDepsLists.set(
157
instr.lvalue.identifier.id,
158
- value.elements as Array<Place>
158
+ value.elements as Array<Place>,
159
);
160
}
161
break;
@@ -173,14 +173,14 @@ function makeManualMemoizationMarkers(
173
env: Environment,
174
depsList: Array<ManualMemoDependency> | null,
175
memoDecl: Place,
176
- manualMemoId: number
176
+ manualMemoId: number,
177
): [TInstruction<StartMemoize>, TInstruction<FinishMemoize>] {
178
return [
179
{
180
id: makeInstructionId(0),
181
lvalue: createTemporaryPlace(env, fnExpr.loc),
182
value: {
183
- kind: "StartMemoize",
183
+ kind: 'StartMemoize',
184
manualMemoId,
185
/*
186
* Use deps list from source instead of inferred deps
@@ -195,9 +195,9 @@ function makeManualMemoizationMarkers(
195
id: makeInstructionId(0),
196
lvalue: createTemporaryPlace(env, fnExpr.loc),
197
value: {
198
- kind: "FinishMemoize",
198
+ kind: 'FinishMemoize',
199
manualMemoId,
200
- decl: { ...memoDecl },
200
+ decl: {...memoDecl},
201
loc: fnExpr.loc,
202
},
203
loc: fnExpr.loc,
@@ -208,9 +208,9 @@ function makeManualMemoizationMarkers(
208
function getManualMemoizationReplacement(
209
fn: Place,
210
loc: SourceLocation,
211
- kind: "useMemo" | "useCallback"
211
+ kind: 'useMemo' | 'useCallback',
212
): LoadLocal | CallExpression {
213
- if (kind === "useMemo") {
213
+ if (kind === 'useMemo') {
214
/*
215
* Replace the hook callee with the fn arg.
216
*
@@ -230,7 +230,7 @@ function getManualMemoizationReplacement(
230
* inline the useMemo callback along with any other immediately invoked IIFEs.
231
*/
232
return {
233
- kind: "CallExpression",
233
+ kind: 'CallExpression',
234
callee: fn,
235
/*
236
* Drop the args, including the deps array which DCE will remove
@@ -256,9 +256,9 @@ function getManualMemoizationReplacement(
256
* $4 = LoadLocal $2 // reference the function
257
*/
258
return {
259
- kind: "LoadLocal",
259
+ kind: 'LoadLocal',
260
place: {
261
- kind: "Identifier",
261
+ kind: 'Identifier',
262
identifier: fn.identifier,
263
effect: Effect.Unknown,
264
reactive: false,
@@ -271,8 +271,8 @@ function getManualMemoizationReplacement(
271
272
function extractManualMemoizationArgs(
273
instr: TInstruction<CallExpression> | TInstruction<MethodCall>,
274
- kind: "useCallback" | "useMemo",
275
- sidemap: IdentifierSidemap
274
+ kind: 'useCallback' | 'useMemo',
275
+ sidemap: IdentifierSidemap,
276
): {
277
fnPlace: Place;
278
depsList: Array<ManualMemoDependency> | null;
@@ -287,7 +287,7 @@ function extractManualMemoizationArgs(
287
suggestions: null,
288
});
289
}
290
- if (fnPlace.kind === "Spread" || depsListPlace?.kind === "Spread") {
290
+ if (fnPlace.kind === 'Spread' || depsListPlace?.kind === 'Spread') {
291
CompilerError.throwInvalidReact({
292
reason: `Unexpected spread argument to ${kind}`,
293
loc: instr.value.loc,
@@ -297,7 +297,7 @@ function extractManualMemoizationArgs(
297
let depsList: Array<ManualMemoDependency> | null = null;
298
if (depsListPlace != null) {
299
const maybeDepsList = sidemap.maybeDepsLists.get(
300
- depsListPlace.identifier.id
300
+ depsListPlace.identifier.id,
301
);
302
if (maybeDepsList == null) {
303
CompilerError.throwInvalidReact({
@@ -306,7 +306,7 @@ function extractManualMemoizationArgs(
306
loc: depsListPlace.loc,
307
});
308
}
309
- depsList = maybeDepsList.map((dep) => {
309
+ depsList = maybeDepsList.map(dep => {
310
const maybeDep = sidemap.maybeDeps.get(dep.identifier.id);
311
if (maybeDep == null) {
312
CompilerError.throwInvalidReact({
@@ -362,25 +362,25 @@ export function dropManualMemoization(func: HIRFunction): void {
362
for (let i = 0; i < block.instructions.length; i++) {
363
const instr = block.instructions[i]!;
364
if (
365
- instr.value.kind === "CallExpression" ||
366
- instr.value.kind === "MethodCall"
365
+ instr.value.kind === 'CallExpression' ||
366
+ instr.value.kind === 'MethodCall'
367
) {
368
const id =
369
- instr.value.kind === "CallExpression"
369
+ instr.value.kind === 'CallExpression'
370
? instr.value.callee.identifier.id
371
: instr.value.property.identifier.id;
372
373
const manualMemo = sidemap.manualMemos.get(id);
374
if (manualMemo != null) {
375
- const { fnPlace, depsList } = extractManualMemoizationArgs(
375
+ const {fnPlace, depsList} = extractManualMemoizationArgs(
376
instr as TInstruction<CallExpression> | TInstruction<MethodCall>,
377
manualMemo.kind,
378
- sidemap
378
+ sidemap,
379
);
380
instr.value = getManualMemoizationReplacement(
381
fnPlace,
382
instr.value.loc,
383
- manualMemo.kind
383
+ manualMemo.kind,
384
);
385
if (isValidationEnabled) {
386
/**
@@ -404,10 +404,10 @@ export function dropManualMemoization(func: HIRFunction): void {
404
});
405
}
406
const memoDecl: Place =
407
- manualMemo.kind === "useMemo"
407
+ manualMemo.kind === 'useMemo'
408
? instr.lvalue
409
: {
410
- kind: "Identifier",
410
+ kind: 'Identifier',
411
identifier: fnPlace.identifier,
412
effect: Effect.Unknown,
413
reactive: false,
@@ -419,7 +419,7 @@ export function dropManualMemoization(func: HIRFunction): void {
419
func.env,
420
depsList,
421
memoDecl,
422
- nextManualMemoId++
422
+ nextManualMemoId++,
423
);
424
425
/**
compiler/packages/babel-plugin-react-compiler/src/Inference/InferAlias.ts
+12
-12
@@ -11,8 +11,8 @@ import {
11
Instruction,
12
isPrimitiveType,
13
Place,
14
-} from "../HIR/HIR";
15
-import DisjointSet from "../Utils/DisjointSet";
14
+} from '../HIR/HIR';
15
+import DisjointSet from '../Utils/DisjointSet';
16
17
export type AliasSet = Set<Identifier>;
18
@@ -29,34 +29,34 @@ export function inferAliases(func: HIRFunction): DisjointSet<Identifier> {
29
30
function inferInstr(
31
instr: Instruction,
32
- aliases: DisjointSet<Identifier>
32
+ aliases: DisjointSet<Identifier>,
33
): void {
34
- const { lvalue, value: instrValue } = instr;
34
+ const {lvalue, value: instrValue} = instr;
35
let alias: Place | null = null;
36
switch (instrValue.kind) {
37
- case "LoadLocal":
38
- case "LoadContext": {
37
+ case 'LoadLocal':
38
+ case 'LoadContext': {
39
if (isPrimitiveType(instrValue.place.identifier)) {
40
return;
41
}
42
alias = instrValue.place;
43
break;
44
}
45
- case "StoreLocal":
46
- case "StoreContext": {
45
+ case 'StoreLocal':
46
+ case 'StoreContext': {
47
alias = instrValue.value;
48
break;
49
}
50
- case "Destructure": {
50
+ case 'Destructure': {
51
alias = instrValue.value;
52
break;
53
}
54
- case "ComputedLoad":
55
- case "PropertyLoad": {
54
+ case 'ComputedLoad':
55
+ case 'PropertyLoad': {
56
alias = instrValue.object;
57
break;
58
}
59
- case "TypeCastExpression": {
59
+ case 'TypeCastExpression': {
60
alias = instrValue.value;
61
break;
62
}
compiler/packages/babel-plugin-react-compiler/src/Inference/InferAliasForPhis.ts
+3
-3
@@ -5,12 +5,12 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { HIRFunction, Identifier } from "../HIR/HIR";
9
-import DisjointSet from "../Utils/DisjointSet";
8
+import {HIRFunction, Identifier} from '../HIR/HIR';
9
+import DisjointSet from '../Utils/DisjointSet';
10
11
export function inferAliasForPhis(
12
func: HIRFunction,
13
- aliases: DisjointSet<Identifier>
13
+ aliases: DisjointSet<Identifier>,
14
): void {
15
for (const [_, block] of func.body.blocks) {
16
for (const phi of block.phis) {
compiler/packages/babel-plugin-react-compiler/src/Inference/InferAliasForStores.ts
+7
-7
@@ -11,20 +11,20 @@ import {
11
Identifier,
12
InstructionId,
13
Place,
14
-} from "../HIR/HIR";
14
+} from '../HIR/HIR';
15
import {
16
eachInstructionLValue,
17
eachInstructionValueOperand,
18
-} from "../HIR/visitors";
19
-import DisjointSet from "../Utils/DisjointSet";
18
+} from '../HIR/visitors';
19
+import DisjointSet from '../Utils/DisjointSet';
20
21
export function inferAliasForStores(
22
func: HIRFunction,
23
- aliases: DisjointSet<Identifier>
23
+ aliases: DisjointSet<Identifier>,
24
): void {
25
for (const [_, block] of func.body.blocks) {
26
for (const instr of block.instructions) {
27
- const { value, lvalue } = instr;
27
+ const {value, lvalue} = instr;
28
const isStore =
29
lvalue.effect === Effect.Store ||
30
/*
@@ -32,7 +32,7 @@ export function inferAliasForStores(
32
* as Effect.Store.
33
*/
34
![...eachInstructionValueOperand(value)].every(
35
- (operand) => operand.effect !== Effect.Store
35
+ operand => operand.effect !== Effect.Store,
36
);
37
38
if (!isStore) {
@@ -57,7 +57,7 @@ function maybeAlias(
57
aliases: DisjointSet<Identifier>,
58
lvalue: Place,
59
rvalue: Place,
60
- id: InstructionId
60
+ id: InstructionId,
61
): void {
62
if (
63
lvalue.identifier.mutableRange.end > id + 1 ||
compiler/packages/babel-plugin-react-compiler/src/Inference/InferMutableContextVariables.ts
+10
-10
@@ -5,12 +5,12 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { Effect, HIRFunction, Identifier, Place } from "../HIR";
8
+import {Effect, HIRFunction, Identifier, Place} from '../HIR';
9
import {
10
eachInstructionValueOperand,
11
eachTerminalOperand,
12
-} from "../HIR/visitors";
13
-import { IdentifierState } from "./AnalyseFunctions";
12
+} from '../HIR/visitors';
13
+import {IdentifierState} from './AnalyseFunctions';
14
15
/*
16
* This pass infers which of the given function's context (free) variables
@@ -61,24 +61,24 @@ export function inferMutableContextVariables(fn: HIRFunction): void {
61
for (const [, block] of fn.body.blocks) {
62
for (const instr of block.instructions) {
63
switch (instr.value.kind) {
64
- case "PropertyLoad": {
64
+ case 'PropertyLoad': {
65
state.declareProperty(
66
instr.lvalue,
67
instr.value.object,
68
- instr.value.property
68
+ instr.value.property,
69
);
70
break;
71
}
72
- case "ComputedLoad": {
72
+ case 'ComputedLoad': {
73
/*
74
* The path is set to an empty string as the path doesn't really
75
* matter for a computed load.
76
*/
77
- state.declareProperty(instr.lvalue, instr.value.object, "");
77
+ state.declareProperty(instr.lvalue, instr.value.object, '');
78
break;
79
}
80
- case "LoadLocal":
81
- case "LoadContext": {
80
+ case 'LoadLocal':
81
+ case 'LoadContext': {
82
if (instr.lvalue.identifier.name === null) {
83
state.declareTemporary(instr.lvalue, instr.value.place);
84
}
@@ -105,7 +105,7 @@ export function inferMutableContextVariables(fn: HIRFunction): void {
105
function visitOperand(
106
state: IdentifierState,
107
knownMutatedIdentifiers: Set<Identifier>,
108
- operand: Place
108
+ operand: Place,
109
): void {
110
const resolved = state.resolve(operand.identifier);
111
if (operand.effect === Effect.Mutate || operand.effect === Effect.Store) {
compiler/packages/babel-plugin-react-compiler/src/Inference/InferMutableLifetimes.ts
+12
-12
@@ -13,14 +13,14 @@ import {
13
InstructionKind,
14
makeInstructionId,
15
Place,
16
-} from "../HIR/HIR";
17
-import { printPlace } from "../HIR/PrintHIR";
16
+} from '../HIR/HIR';
17
+import {printPlace} from '../HIR/PrintHIR';
18
import {
19
eachInstructionLValue,
20
eachInstructionOperand,
21
eachTerminalOperand,
22
-} from "../HIR/visitors";
23
-import { assertExhaustive } from "../Utils/utils";
22
+} from '../HIR/visitors';
23
+import {assertExhaustive} from '../Utils/utils';
24
25
/*
26
* For each usage of a value in the given function, determines if the usage
@@ -72,7 +72,7 @@ function infer(place: Place, instrId: InstructionId): void {
72
function inferPlace(
73
place: Place,
74
instrId: InstructionId,
75
- inferMutableRangeForStores: boolean
75
+ inferMutableRangeForStores: boolean,
76
): void {
77
switch (place.effect) {
78
case Effect.Unknown: {
@@ -99,7 +99,7 @@ function inferPlace(
99
100
export function inferMutableLifetimes(
101
func: HIRFunction,
102
- inferMutableRangeForStores: boolean
102
+ inferMutableRangeForStores: boolean,
103
): void {
104
/*
105
* Context variables only appear to mutate where they are assigned, but we need
@@ -125,7 +125,7 @@ export function inferMutableLifetimes(
125
phi.id.mutableRange.start = operand.mutableRange.start;
126
} else {
127
phi.id.mutableRange.start = makeInstructionId(
128
- Math.min(phi.id.mutableRange.start, operand.mutableRange.start)
128
+ Math.min(phi.id.mutableRange.start, operand.mutableRange.start),
129
);
130
}
131
}
@@ -153,23 +153,23 @@ export function inferMutableLifetimes(
153
}
154
155
if (
156
- instr.value.kind === "DeclareContext" ||
157
- (instr.value.kind === "StoreContext" &&
156
+ instr.value.kind === 'DeclareContext' ||
157
+ (instr.value.kind === 'StoreContext' &&
158
instr.value.lvalue.kind !== InstructionKind.Reassign)
159
) {
160
// Save declarations of context variables
161
contextVariableDeclarationInstructions.set(
162
instr.value.lvalue.place.identifier,
163
- instr.id
163
+ instr.id,
164
);
165
- } else if (instr.value.kind === "StoreContext") {
165
+ } else if (instr.value.kind === 'StoreContext') {
166
/*
167
* Else this is a reassignment, extend the range from the declaration (if present).
168
* Note that declarations may not be present for context variables that are reassigned
169
* within a function expression before (or without) a read of the same variable
170
*/
171
const declaration = contextVariableDeclarationInstructions.get(
172
- instr.value.lvalue.place.identifier
172
+ instr.value.lvalue.place.identifier,
173
);
174
if (declaration != null) {
175
const range = instr.value.lvalue.place.identifier.mutableRange;
compiler/packages/babel-plugin-react-compiler/src/Inference/InferMutableRanges.ts
+7
-7
@@ -5,13 +5,13 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { HIRFunction, Identifier } from "../HIR/HIR";
9
-import { inferAliases } from "./InferAlias";
10
-import { inferAliasForPhis } from "./InferAliasForPhis";
11
-import { inferAliasForStores } from "./InferAliasForStores";
12
-import { inferMutableLifetimes } from "./InferMutableLifetimes";
13
-import { inferMutableRangesForAlias } from "./InferMutableRangesForAlias";
14
-import { inferTryCatchAliases } from "./InferTryCatchAliases";
8
+import {HIRFunction, Identifier} from '../HIR/HIR';
9
+import {inferAliases} from './InferAlias';
10
+import {inferAliasForPhis} from './InferAliasForPhis';
11
+import {inferAliasForStores} from './InferAliasForStores';
12
+import {inferMutableLifetimes} from './InferMutableLifetimes';
13
+import {inferMutableRangesForAlias} from './InferMutableRangesForAlias';
14
+import {inferTryCatchAliases} from './InferTryCatchAliases';
15
16
export function inferMutableRanges(ir: HIRFunction): void {
17
// Infer mutable ranges for non fields
compiler/packages/babel-plugin-react-compiler/src/Inference/InferMutableRangesForAlias.ts
+4
-4
@@ -5,12 +5,12 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { HIRFunction, Identifier, InstructionId } from "../HIR/HIR";
9
-import DisjointSet from "../Utils/DisjointSet";
8
+import {HIRFunction, Identifier, InstructionId} from '../HIR/HIR';
9
+import DisjointSet from '../Utils/DisjointSet';
10
11
export function inferMutableRangesForAlias(
12
_fn: HIRFunction,
13
- aliases: DisjointSet<Identifier>
13
+ aliases: DisjointSet<Identifier>,
14
): void {
15
const aliasSets = aliases.buildSets();
16
for (const aliasSet of aliasSets) {
@@ -19,7 +19,7 @@ export function inferMutableRangesForAlias(
19
* mutated.
20
*/
21
const mutatingIdentifiers = [...aliasSet].filter(
22
- (id) => id.mutableRange.end - id.mutableRange.start > 1
22
+ id => id.mutableRange.end - id.mutableRange.start > 1,
23
);
24
25
if (mutatingIdentifiers.length > 0) {
compiler/packages/babel-plugin-react-compiler/src/Inference/InferReactivePlaces.ts
+24
-24
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "..";
8
+import {CompilerError} from '..';
9
import {
10
BlockId,
11
Effect,
@@ -17,19 +17,19 @@ import {
17
getHookKind,
18
isStableType,
19
isUseOperator,
20
-} from "../HIR";
21
-import { PostDominator } from "../HIR/Dominator";
20
+} from '../HIR';
21
+import {PostDominator} from '../HIR/Dominator';
22
import {
23
eachInstructionLValue,
24
eachInstructionValueOperand,
25
eachTerminalOperand,
26
-} from "../HIR/visitors";
26
+} from '../HIR/visitors';
27
import {
28
findDisjointMutableValues,
29
isMutable,
30
-} from "../ReactiveScopes/InferReactiveScopeVariables";
31
-import DisjointSet from "../Utils/DisjointSet";
32
-import { assertExhaustive } from "../Utils/utils";
30
+} from '../ReactiveScopes/InferReactiveScopeVariables';
31
+import DisjointSet from '../Utils/DisjointSet';
32
+import {assertExhaustive} from '../Utils/utils';
33
34
/*
35
* Infers which `Place`s are reactive, ie may *semantically* change
@@ -112,7 +112,7 @@ import { assertExhaustive } from "../Utils/utils";
112
export function inferReactivePlaces(fn: HIRFunction): void {
113
const reactiveIdentifiers = new ReactivityMap(findDisjointMutableValues(fn));
114
for (const param of fn.params) {
115
- const place = param.kind === "Identifier" ? param : param.place;
115
+ const place = param.kind === 'Identifier' ? param : param.place;
116
reactiveIdentifiers.markReactive(place);
117
}
118
@@ -130,14 +130,14 @@ export function inferReactivePlaces(fn: HIRFunction): void {
130
for (const blockId of controlBlocks) {
131
const controlBlock = fn.body.blocks.get(blockId)!;
132
switch (controlBlock.terminal.kind) {
133
- case "if":
134
- case "branch": {
133
+ case 'if':
134
+ case 'branch': {
135
if (reactiveIdentifiers.isReactive(controlBlock.terminal.test)) {
136
return true;
137
}
138
break;
139
}
140
- case "switch": {
140
+ case 'switch': {
141
if (reactiveIdentifiers.isReactive(controlBlock.terminal.test)) {
142
return true;
143
}
@@ -185,7 +185,7 @@ export function inferReactivePlaces(fn: HIRFunction): void {
185
}
186
}
187
for (const instruction of block.instructions) {
188
- const { value } = instruction;
188
+ const {value} = instruction;
189
let hasReactiveInput = false;
190
/*
191
* NOTE: we want to mark all operands as reactive or not, so we
@@ -204,13 +204,13 @@ export function inferReactivePlaces(fn: HIRFunction): void {
204
* but we are conservative and assume that the value could be reactive.
205
*/
206
if (
207
- value.kind === "CallExpression" &&
207
+ value.kind === 'CallExpression' &&
208
(getHookKind(fn.env, value.callee.identifier) != null ||
209
isUseOperator(value.callee.identifier))
210
) {
211
hasReactiveInput = true;
212
} else if (
213
- value.kind === "MethodCall" &&
213
+ value.kind === 'MethodCall' &&
214
(getHookKind(fn.env, value.property.identifier) != null ||
215
isUseOperator(value.property.identifier))
216
) {
@@ -248,7 +248,7 @@ export function inferReactivePlaces(fn: HIRFunction): void {
248
}
249
case Effect.Unknown: {
250
CompilerError.invariant(false, {
251
- reason: "Unexpected unknown effect",
251
+ reason: 'Unexpected unknown effect',
252
description: null,
253
loc: operand.loc,
254
suggestions: null,
@@ -257,7 +257,7 @@ export function inferReactivePlaces(fn: HIRFunction): void {
257
default: {
258
assertExhaustive(
259
operand.effect,
260
- `Unexpected effect kind \`${operand.effect}\``
260
+ `Unexpected effect kind \`${operand.effect}\``,
261
);
262
}
263
}
@@ -265,25 +265,25 @@ export function inferReactivePlaces(fn: HIRFunction): void {
265
}
266
267
switch (value.kind) {
268
- case "LoadLocal": {
268
+ case 'LoadLocal': {
269
identifierMapping.set(
270
instruction.lvalue.identifier,
271
- value.place.identifier
271
+ value.place.identifier,
272
);
273
break;
274
}
275
- case "PropertyLoad":
276
- case "ComputedLoad": {
275
+ case 'PropertyLoad':
276
+ case 'ComputedLoad': {
277
const resolvedId =
278
identifierMapping.get(value.object.identifier) ??
279
value.object.identifier;
280
identifierMapping.set(instruction.lvalue.identifier, resolvedId);
281
break;
282
}
283
- case "LoadContext": {
283
+ case 'LoadContext': {
284
identifierMapping.set(
285
instruction.lvalue.identifier,
286
- value.place.identifier
286
+ value.place.identifier,
287
);
288
break;
289
}
@@ -304,7 +304,7 @@ export function inferReactivePlaces(fn: HIRFunction): void {
304
function postDominatorFrontier(
305
fn: HIRFunction,
306
postDominators: PostDominator<BlockId>,
307
- targetId: BlockId
307
+ targetId: BlockId,
308
): Set<BlockId> {
309
const visited = new Set<BlockId>();
310
const frontier = new Set<BlockId>();
@@ -328,7 +328,7 @@ function postDominatorFrontier(
328
function postDominatorsOf(
329
fn: HIRFunction,
330
postDominators: PostDominator<BlockId>,
331
- targetId: BlockId
331
+ targetId: BlockId,
332
): Set<BlockId> {
333
const result = new Set<BlockId>();
334
const visited = new Set<BlockId>();
compiler/packages/babel-plugin-react-compiler/src/Inference/InferReferenceEffects.ts
+203
-203
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError, ErrorSeverity } from "../CompilerError";
9
-import { Environment } from "../HIR";
8
+import {CompilerError, ErrorSeverity} from '../CompilerError';
9
+import {Environment} from '../HIR';
10
import {
11
AbstractValue,
12
BasicBlock,
@@ -31,14 +31,14 @@ import {
31
isObjectType,
32
isRefValueType,
33
isUseRefType,
34
-} from "../HIR/HIR";
35
-import { FunctionSignature } from "../HIR/ObjectShape";
34
+} from '../HIR/HIR';
35
+import {FunctionSignature} from '../HIR/ObjectShape';
36
import {
37
printIdentifier,
38
printMixedHIR,
39
printPlace,
40
printSourceLocation,
41
-} from "../HIR/PrintHIR";
41
+} from '../HIR/PrintHIR';
42
import {
43
eachCallArgument,
44
eachInstructionOperand,
@@ -46,12 +46,12 @@ import {
46
eachPatternOperand,
47
eachTerminalOperand,
48
eachTerminalSuccessor,
49
-} from "../HIR/visitors";
50
-import { assertExhaustive } from "../Utils/utils";
51
-import { isEffectHook } from "../Validation/ValidateMemoizedEffectDependencies";
49
+} from '../HIR/visitors';
50
+import {assertExhaustive} from '../Utils/utils';
51
+import {isEffectHook} from '../Validation/ValidateMemoizedEffectDependencies';
52
53
const UndefinedValue: InstructionValue = {
54
- kind: "Primitive",
54
+ kind: 'Primitive',
55
loc: GeneratedSource,
56
value: undefined,
57
};
@@ -100,7 +100,7 @@ const UndefinedValue: InstructionValue = {
100
*/
101
export default function inferReferenceEffects(
102
fn: HIRFunction,
103
- options: { isFunctionExpression: boolean } = { isFunctionExpression: false }
103
+ options: {isFunctionExpression: boolean} = {isFunctionExpression: false},
104
): void {
105
/*
106
* Initial state contains function params
@@ -108,7 +108,7 @@ export default function inferReferenceEffects(
108
*/
109
const initialState = InferenceState.empty(fn.env);
110
const value: InstructionValue = {
111
- kind: "Primitive",
111
+ kind: 'Primitive',
112
loc: fn.loc,
113
value: undefined,
114
};
@@ -121,7 +121,7 @@ export default function inferReferenceEffects(
121
for (const ref of fn.context) {
122
// TODO(gsn): This is a hack.
123
const value: InstructionValue = {
124
- kind: "ObjectExpression",
124
+ kind: 'ObjectExpression',
125
properties: [],
126
loc: ref.loc,
127
};
@@ -145,10 +145,10 @@ export default function inferReferenceEffects(
145
context: new Set(),
146
};
147
148
- if (fn.fnType === "Component") {
148
+ if (fn.fnType === 'Component') {
149
CompilerError.invariant(fn.params.length <= 2, {
150
reason:
151
- "Expected React component to have not more than two parameters: one for props and for ref",
151
+ 'Expected React component to have not more than two parameters: one for props and for ref',
152
description: null,
153
loc: fn.loc,
154
suggestions: null,
@@ -160,17 +160,17 @@ export default function inferReferenceEffects(
160
inferParam(props, initialState, paramKind);
161
}
162
if (ref) {
163
- if (ref.kind === "Identifier") {
163
+ if (ref.kind === 'Identifier') {
164
place = ref;
165
value = {
166
- kind: "ObjectExpression",
166
+ kind: 'ObjectExpression',
167
properties: [],
168
loc: ref.loc,
169
};
170
} else {
171
place = ref.place;
172
value = {
173
- kind: "ObjectExpression",
173
+ kind: 'ObjectExpression',
174
properties: [],
175
loc: ref.place.loc,
176
};
@@ -238,13 +238,13 @@ export default function inferReferenceEffects(
238
}
239
240
if (!options.isFunctionExpression) {
241
- functionEffects.forEach((eff) => {
241
+ functionEffects.forEach(eff => {
242
switch (eff.kind) {
243
- case "ReactMutation":
244
- case "GlobalMutation": {
243
+ case 'ReactMutation':
244
+ case 'GlobalMutation': {
245
CompilerError.throw(eff.error);
246
}
247
- case "ContextMutation": {
247
+ case 'ContextMutation': {
248
CompilerError.throw({
249
severity: ErrorSeverity.Invariant,
250
reason: `Unexpected ContextMutation in top-level function effects`,
@@ -254,7 +254,7 @@ export default function inferReferenceEffects(
254
default:
255
assertExhaustive(
256
eff,
257
- `Unexpected function effect kind \`${(eff as any).kind}\``
257
+ `Unexpected function effect kind \`${(eff as any).kind}\``,
258
);
259
}
260
});
@@ -279,7 +279,7 @@ class InferenceState {
279
constructor(
280
env: Environment,
281
values: Map<InstructionValue, AbstractValue>,
282
- variables: Map<IdentifierId, Set<InstructionValue>>
282
+ variables: Map<IdentifierId, Set<InstructionValue>>,
283
) {
284
this.#env = env;
285
this.#values = values;
@@ -292,9 +292,9 @@ class InferenceState {
292
293
// (Re)initializes a @param value with its default @param kind.
294
initialize(value: InstructionValue, kind: AbstractValue): void {
295
- CompilerError.invariant(value.kind !== "LoadLocal", {
295
+ CompilerError.invariant(value.kind !== 'LoadLocal', {
296
reason:
297
- "Expected all top-level identifiers to be defined as variables, not values",
297
+ 'Expected all top-level identifiers to be defined as variables, not values',
298
description: null,
299
loc: value.loc,
300
suggestions: null,
@@ -353,7 +353,7 @@ class InferenceState {
353
define(place: Place, value: InstructionValue): void {
354
CompilerError.invariant(this.#values.has(value), {
355
reason: `Expected value to be initialized at '${printSourceLocation(
356
- value.loc
356
+ value.loc,
357
)}'`,
358
description: null,
359
loc: value.loc,
@@ -382,12 +382,12 @@ class InferenceState {
382
place: Place,
383
effectKind: Effect,
384
reason: ValueReason,
385
- functionEffects: Array<FunctionEffect>
385
+ functionEffects: Array<FunctionEffect>,
386
): void {
387
const values = this.#variables.get(place.identifier.id);
388
if (values === undefined) {
389
CompilerError.invariant(effectKind !== Effect.Store, {
390
- reason: "[InferReferenceEffects] Unhandled store reference effect",
390
+ reason: '[InferReferenceEffects] Unhandled store reference effect',
391
description: null,
392
loc: place.loc,
393
suggestions: null,
@@ -402,14 +402,14 @@ class InferenceState {
402
// Propagate effects of function expressions to the outer (ie current) effect context
403
for (const value of values) {
404
if (
405
- (value.kind === "FunctionExpression" ||
406
- value.kind === "ObjectMethod") &&
405
+ (value.kind === 'FunctionExpression' ||
406
+ value.kind === 'ObjectMethod') &&
407
value.loweredFunc.func.effects != null
408
) {
409
for (const effect of value.loweredFunc.func.effects) {
410
if (
411
- effect.kind === "GlobalMutation" ||
412
- effect.kind === "ReactMutation"
411
+ effect.kind === 'GlobalMutation' ||
412
+ effect.kind === 'ReactMutation'
413
) {
414
// Known effects are always propagated upwards
415
functionEffects.push(effect);
@@ -429,12 +429,12 @@ class InferenceState {
429
for (const place of effect.places) {
430
if (this.isDefined(place)) {
431
const replayedEffect = this.reference(
432
- { ...place, loc: effect.loc },
432
+ {...place, loc: effect.loc},
433
effect.effect,
434
- reason
434
+ reason,
435
);
436
if (replayedEffect != null) {
437
- if (replayedEffect.kind === "ContextMutation") {
437
+ if (replayedEffect.kind === 'ContextMutation') {
438
// Case 1, still a context value so propagate the original effect
439
functionEffects.push(effect);
440
} else {
@@ -457,11 +457,11 @@ class InferenceState {
457
reference(
458
place: Place,
459
effectKind: Effect,
460
- reason: ValueReason
460
+ reason: ValueReason,
461
): FunctionEffect | null {
462
const values = this.#variables.get(place.identifier.id);
463
CompilerError.invariant(values !== undefined, {
464
- reason: "[InferReferenceEffects] Expected value to be initialized",
464
+ reason: '[InferReferenceEffects] Expected value to be initialized',
465
description: null,
466
loc: place.loc,
467
suggestions: null,
@@ -483,7 +483,7 @@ class InferenceState {
483
reason: reasonSet,
484
context: new Set(),
485
};
486
- values.forEach((value) => {
486
+ values.forEach(value => {
487
this.#values.set(value, {
488
kind: ValueKind.Frozen,
489
reason: reasonSet,
@@ -494,13 +494,13 @@ class InferenceState {
494
this.#env.config.enablePreserveExistingMemoizationGuarantees ||
495
this.#env.config.enableTransitivelyFreezeFunctionExpressions
496
) {
497
- if (value.kind === "FunctionExpression") {
497
+ if (value.kind === 'FunctionExpression') {
498
for (const operand of eachInstructionValueOperand(value)) {
499
this.referenceAndRecordEffects(
500
operand,
501
Effect.Freeze,
502
ValueReason.Other,
503
- []
503
+ [],
504
);
505
}
506
}
@@ -530,7 +530,7 @@ class InferenceState {
530
// no-op: refs are validate via ValidateNoRefAccessInRender
531
} else if (valueKind.kind === ValueKind.Context) {
532
functionEffect = {
533
- kind: "ContextMutation",
533
+ kind: 'ContextMutation',
534
loc: place.loc,
535
effect: effectKind,
536
places:
@@ -548,13 +548,13 @@ class InferenceState {
548
kind:
549
valueKind.reason.size === 1 &&
550
valueKind.reason.has(ValueReason.Global)
551
- ? "GlobalMutation"
552
- : "ReactMutation",
551
+ ? 'GlobalMutation'
552
+ : 'ReactMutation',
553
error: {
554
reason,
555
description:
556
place.identifier.name !== null &&
557
- place.identifier.name.kind === "named"
557
+ place.identifier.name.kind === 'named'
558
? `Found mutation of \`${place.identifier.name.value}\``
559
: null,
560
loc: place.loc,
@@ -574,7 +574,7 @@ class InferenceState {
574
// no-op: refs are validate via ValidateNoRefAccessInRender
575
} else if (valueKind.kind === ValueKind.Context) {
576
functionEffect = {
577
- kind: "ContextMutation",
577
+ kind: 'ContextMutation',
578
loc: place.loc,
579
effect: effectKind,
580
places:
@@ -592,13 +592,13 @@ class InferenceState {
592
kind:
593
valueKind.reason.size === 1 &&
594
valueKind.reason.has(ValueReason.Global)
595
- ? "GlobalMutation"
596
- : "ReactMutation",
595
+ ? 'GlobalMutation'
596
+ : 'ReactMutation',
597
error: {
598
reason,
599
description:
600
place.identifier.name !== null &&
601
- place.identifier.name.kind === "named"
601
+ place.identifier.name.kind === 'named'
602
? `Found mutation of \`${place.identifier.name.value}\``
603
: null,
604
loc: place.loc,
@@ -639,7 +639,7 @@ class InferenceState {
639
case Effect.Unknown: {
640
CompilerError.invariant(false, {
641
reason:
642
- "Unexpected unknown effect, expected to infer a precise effect kind",
642
+ 'Unexpected unknown effect, expected to infer a precise effect kind',
643
description: null,
644
loc: place.loc,
645
suggestions: null,
@@ -648,12 +648,12 @@ class InferenceState {
648
default: {
649
assertExhaustive(
650
effectKind,
651
- `Unexpected reference kind \`${effectKind as any as string}\``
651
+ `Unexpected reference kind \`${effectKind as any as string}\``,
652
);
653
}
654
}
655
CompilerError.invariant(effect !== null, {
656
- reason: "Expected effect to be set",
656
+ reason: 'Expected effect to be set',
657
description: null,
658
loc: place.loc,
659
suggestions: null,
@@ -727,7 +727,7 @@ class InferenceState {
727
return new InferenceState(
728
this.#env,
729
nextValues ?? new Map(this.#values),
730
- nextVariables ?? new Map(this.#variables)
730
+ nextVariables ?? new Map(this.#variables),
731
);
732
}
733
}
@@ -741,7 +741,7 @@ class InferenceState {
741
return new InferenceState(
742
this.#env,
743
new Map(this.#values),
744
- new Map(this.#variables)
744
+ new Map(this.#variables),
745
);
746
}
747
@@ -750,7 +750,7 @@ class InferenceState {
750
* object so that it can printed as JSON.
751
*/
752
debug(): any {
753
- const result: any = { values: {}, variables: {} };
753
+ const result: any = {values: {}, variables: {}};
754
const objects: Map<InstructionValue, number> = new Map();
755
function identify(value: InstructionValue): number {
756
let id = objects.get(value);
@@ -762,7 +762,7 @@ class InferenceState {
762
}
763
for (const [value, kind] of this.#values) {
764
const id = identify(value);
765
- result.values[id] = { kind, value: printMixedHIR(value) };
765
+ result.values[id] = {kind, value: printMixedHIR(value)};
766
}
767
for (const [variable, values] of this.#variables) {
768
result.variables[`$${variable}`] = [...values].map(identify);
@@ -790,21 +790,21 @@ class InferenceState {
790
function inferParam(
791
param: Place | SpreadPattern,
792
initialState: InferenceState,
793
- paramKind: AbstractValue
793
+ paramKind: AbstractValue,
794
): void {
795
let value: InstructionValue;
796
let place: Place;
797
- if (param.kind === "Identifier") {
797
+ if (param.kind === 'Identifier') {
798
place = param;
799
value = {
800
- kind: "Primitive",
800
+ kind: 'Primitive',
801
loc: param.loc,
802
value: undefined,
803
};
804
} else {
805
place = param.place;
806
value = {
807
- kind: "Primitive",
807
+ kind: 'Primitive',
808
loc: param.place.loc,
809
value: undefined,
810
};
@@ -908,7 +908,7 @@ function mergeValues(a: ValueKind, b: ValueKind): ValueKind {
908
reason: `Unexpected value kind in mergeValues()`,
909
description: `Found kinds ${a} and ${b}`,
910
loc: GeneratedSource,
911
- }
911
+ },
912
);
913
return ValueKind.Primitive;
914
}
@@ -928,7 +928,7 @@ function isSuperset<T>(a: ReadonlySet<T>, b: ReadonlySet<T>): boolean {
928
929
function mergeAbstractValues(
930
a: AbstractValue,
931
- b: AbstractValue
931
+ b: AbstractValue,
932
): AbstractValue {
933
const kind = mergeValues(a.kind, b.kind);
934
if (
@@ -947,7 +947,7 @@ function mergeAbstractValues(
947
for (const c of b.context) {
948
context.add(c);
949
}
950
- return { kind, reason, context };
950
+ return {kind, reason, context};
951
}
952
953
/*
@@ -958,7 +958,7 @@ function inferBlock(
958
env: Environment,
959
functionEffects: Array<FunctionEffect>,
960
state: InferenceState,
961
- block: BasicBlock
961
+ block: BasicBlock,
962
): void {
963
for (const phi of block.phis) {
964
state.inferPhi(phi);
@@ -966,11 +966,11 @@ function inferBlock(
966
967
for (const instr of block.instructions) {
968
const instrValue = instr.value;
969
- let effect: { kind: Effect; reason: ValueReason } | null = null;
969
+ let effect: {kind: Effect; reason: ValueReason} | null = null;
970
let lvalueEffect = Effect.ConditionallyMutate;
971
let valueKind: AbstractValue;
972
switch (instrValue.kind) {
973
- case "BinaryExpression": {
973
+ case 'BinaryExpression': {
974
valueKind = {
975
kind: ValueKind.Primitive,
976
reason: new Set([ValueReason.Other]),
@@ -982,7 +982,7 @@ function inferBlock(
982
};
983
break;
984
}
985
- case "ArrayExpression": {
985
+ case 'ArrayExpression': {
986
valueKind = hasContextRefOperand(state, instrValue)
987
? {
988
kind: ValueKind.Context,
@@ -994,11 +994,11 @@ function inferBlock(
994
reason: new Set([ValueReason.Other]),
995
context: new Set(),
996
};
997
- effect = { kind: Effect.Capture, reason: ValueReason.Other };
997
+ effect = {kind: Effect.Capture, reason: ValueReason.Other};
998
lvalueEffect = Effect.Store;
999
break;
1000
}
1001
- case "NewExpression": {
1001
+ case 'NewExpression': {
1002
/**
1003
* For new expressions, we infer a `read` effect on the Class / Function type
1004
* to avoid extending mutable ranges of locally created classes, e.g.
@@ -1021,7 +1021,7 @@ function inferBlock(
1021
instrValue.callee,
1022
Effect.Read,
1023
ValueReason.Other,
1024
- functionEffects
1024
+ functionEffects,
1025
);
1026
1027
for (const operand of eachCallArgument(instrValue.args)) {
@@ -1029,7 +1029,7 @@ function inferBlock(
1029
operand,
1030
Effect.ConditionallyMutate,
1031
ValueReason.Other,
1032
- functionEffects
1032
+ functionEffects,
1033
);
1034
}
1035
@@ -1038,7 +1038,7 @@ function inferBlock(
1038
instr.lvalue.effect = lvalueEffect;
1039
continue;
1040
}
1041
- case "ObjectExpression": {
1041
+ case 'ObjectExpression': {
1042
valueKind = hasContextRefOperand(state, instrValue)
1043
? {
1044
kind: ValueKind.Context,
@@ -1053,14 +1053,14 @@ function inferBlock(
1053
1054
for (const property of instrValue.properties) {
1055
switch (property.kind) {
1056
- case "ObjectProperty": {
1057
- if (property.key.kind === "computed") {
1056
+ case 'ObjectProperty': {
1057
+ if (property.key.kind === 'computed') {
1058
// Object keys must be primitives, so we know they're frozen at this point
1059
state.referenceAndRecordEffects(
1060
property.key.name,
1061
Effect.Freeze,
1062
ValueReason.Other,
1063
- functionEffects
1063
+ functionEffects,
1064
);
1065
}
1066
// Object construction captures but does not modify the key/property values
@@ -1068,24 +1068,24 @@ function inferBlock(
1068
property.place,
1069
Effect.Capture,
1070
ValueReason.Other,
1071
- functionEffects
1071
+ functionEffects,
1072
);
1073
break;
1074
}
1075
- case "Spread": {
1075
+ case 'Spread': {
1076
// Object construction captures but does not modify the key/property values
1077
state.referenceAndRecordEffects(
1078
property.place,
1079
Effect.Capture,
1080
ValueReason.Other,
1081
- functionEffects
1081
+ functionEffects,
1082
);
1083
break;
1084
}
1085
default: {
1086
assertExhaustive(
1087
property,
1088
- `Unexpected property kind \`${(property as any).kind}\``
1088
+ `Unexpected property kind \`${(property as any).kind}\``,
1089
);
1090
}
1091
}
@@ -1096,16 +1096,16 @@ function inferBlock(
1096
instr.lvalue.effect = Effect.Store;
1097
continue;
1098
}
1099
- case "UnaryExpression": {
1099
+ case 'UnaryExpression': {
1100
valueKind = {
1101
kind: ValueKind.Primitive,
1102
reason: new Set([ValueReason.Other]),
1103
context: new Set(),
1104
};
1105
- effect = { kind: Effect.Read, reason: ValueReason.Other };
1105
+ effect = {kind: Effect.Read, reason: ValueReason.Other};
1106
break;
1107
}
1108
- case "UnsupportedNode": {
1108
+ case 'UnsupportedNode': {
1109
// TODO: handle other statement kinds
1110
valueKind = {
1111
kind: ValueKind.Mutable,
@@ -1114,13 +1114,13 @@ function inferBlock(
1114
};
1115
break;
1116
}
1117
- case "JsxExpression": {
1118
- if (instrValue.tag.kind === "Identifier") {
1117
+ case 'JsxExpression': {
1118
+ if (instrValue.tag.kind === 'Identifier') {
1119
state.referenceAndRecordEffects(
1120
instrValue.tag,
1121
Effect.Freeze,
1122
ValueReason.JsxCaptured,
1123
- functionEffects
1123
+ functionEffects,
1124
);
1125
}
1126
if (instrValue.children !== null) {
@@ -1129,17 +1129,17 @@ function inferBlock(
1129
child,
1130
Effect.Freeze,
1131
ValueReason.JsxCaptured,
1132
- functionEffects
1132
+ functionEffects,
1133
);
1134
}
1135
}
1136
for (const attr of instrValue.props) {
1137
- if (attr.kind === "JsxSpreadAttribute") {
1137
+ if (attr.kind === 'JsxSpreadAttribute') {
1138
state.referenceAndRecordEffects(
1139
attr.argument,
1140
Effect.Freeze,
1141
ValueReason.JsxCaptured,
1142
- functionEffects
1142
+ functionEffects,
1143
);
1144
} else {
1145
const propEffects: Array<FunctionEffect> = [];
@@ -1147,12 +1147,12 @@ function inferBlock(
1147
attr.place,
1148
Effect.Freeze,
1149
ValueReason.JsxCaptured,
1150
- propEffects
1150
+ propEffects,
1151
);
1152
functionEffects.push(
1153
...propEffects.filter(
1154
- (propEffect) => propEffect.kind !== "GlobalMutation"
1155
- )
1154
+ propEffect => propEffect.kind !== 'GlobalMutation',
1155
+ ),
1156
);
1157
}
1158
}
@@ -1166,7 +1166,7 @@ function inferBlock(
1166
instr.lvalue.effect = Effect.ConditionallyMutate;
1167
continue;
1168
}
1169
- case "JsxFragment": {
1169
+ case 'JsxFragment': {
1170
valueKind = {
1171
kind: ValueKind.Frozen,
1172
reason: new Set([ValueReason.Other]),
@@ -1178,7 +1178,7 @@ function inferBlock(
1178
};
1179
break;
1180
}
1181
- case "TaggedTemplateExpression": {
1181
+ case 'TaggedTemplateExpression': {
1182
valueKind = {
1183
kind: ValueKind.Mutable,
1184
reason: new Set([ValueReason.Other]),
@@ -1190,7 +1190,7 @@ function inferBlock(
1190
};
1191
break;
1192
}
1193
- case "TemplateLiteral": {
1193
+ case 'TemplateLiteral': {
1194
/*
1195
* template literal (with no tag function) always produces
1196
* an immutable string
@@ -1200,10 +1200,10 @@ function inferBlock(
1200
reason: new Set([ValueReason.Other]),
1201
context: new Set(),
1202
};
1203
- effect = { kind: Effect.Read, reason: ValueReason.Other };
1203
+ effect = {kind: Effect.Read, reason: ValueReason.Other};
1204
break;
1205
}
1206
- case "RegExpLiteral": {
1206
+ case 'RegExpLiteral': {
1207
// RegExp instances are mutable objects
1208
valueKind = {
1209
kind: ValueKind.Mutable,
@@ -1216,8 +1216,8 @@ function inferBlock(
1216
};
1217
break;
1218
}
1219
- case "MetaProperty": {
1220
- if (instrValue.meta !== "import" || instrValue.property !== "meta") {
1219
+ case 'MetaProperty': {
1220
+ if (instrValue.meta !== 'import' || instrValue.property !== 'meta') {
1221
continue;
1222
}
1223
@@ -1228,16 +1228,16 @@ function inferBlock(
1228
};
1229
break;
1230
}
1231
- case "LoadGlobal":
1231
+ case 'LoadGlobal':
1232
valueKind = {
1233
kind: ValueKind.Global,
1234
reason: new Set([ValueReason.Global]),
1235
context: new Set(),
1236
};
1237
break;
1238
- case "Debugger":
1239
- case "JSXText":
1240
- case "Primitive": {
1238
+ case 'Debugger':
1239
+ case 'JSXText':
1240
+ case 'Primitive': {
1241
valueKind = {
1242
kind: ValueKind.Primitive,
1243
reason: new Set([ValueReason.Other]),
@@ -1245,15 +1245,15 @@ function inferBlock(
1245
};
1246
break;
1247
}
1248
- case "ObjectMethod":
1249
- case "FunctionExpression": {
1248
+ case 'ObjectMethod':
1249
+ case 'FunctionExpression': {
1250
let hasMutableOperand = false;
1251
for (const operand of eachInstructionOperand(instr)) {
1252
state.referenceAndRecordEffects(
1253
operand,
1254
operand.effect === Effect.Unknown ? Effect.Read : operand.effect,
1255
ValueReason.Other,
1256
- []
1256
+ [],
1257
);
1258
hasMutableOperand ||= isMutableEffect(operand.effect, operand.loc);
1259
@@ -1282,13 +1282,13 @@ function inferBlock(
1282
const values = state.values(operand);
1283
for (const value of values) {
1284
if (
1285
- (value.kind === "ObjectMethod" ||
1286
- value.kind === "FunctionExpression") &&
1285
+ (value.kind === 'ObjectMethod' ||
1286
+ value.kind === 'FunctionExpression') &&
1287
value.loweredFunc.func.effects !== null
1288
) {
1289
instrValue.loweredFunc.func.effects ??= [];
1290
instrValue.loweredFunc.func.effects.push(
1291
- ...value.loweredFunc.func.effects
1291
+ ...value.loweredFunc.func.effects,
1292
);
1293
}
1294
}
@@ -1306,10 +1306,10 @@ function inferBlock(
1306
instr.lvalue.effect = Effect.Store;
1307
continue;
1308
}
1309
- case "CallExpression": {
1309
+ case 'CallExpression': {
1310
const signature = getFunctionCallSignature(
1311
env,
1312
- instrValue.callee.identifier.type
1312
+ instrValue.callee.identifier.type,
1313
);
1314
1315
const effects =
@@ -1334,20 +1334,20 @@ function inferBlock(
1334
for (let i = 0; i < instrValue.args.length; i++) {
1335
const argumentEffects: Array<FunctionEffect> = [];
1336
const arg = instrValue.args[i];
1337
- const place = arg.kind === "Identifier" ? arg : arg.place;
1337
+ const place = arg.kind === 'Identifier' ? arg : arg.place;
1338
if (effects !== null) {
1339
state.referenceAndRecordEffects(
1340
place,
1341
effects[i],
1342
ValueReason.Other,
1343
- argumentEffects
1343
+ argumentEffects,
1344
);
1345
} else {
1346
state.referenceAndRecordEffects(
1347
place,
1348
Effect.ConditionallyMutate,
1349
ValueReason.Other,
1350
- argumentEffects
1350
+ argumentEffects,
1351
);
1352
}
1353
/*
@@ -1356,9 +1356,9 @@ function inferBlock(
1356
*/
1357
functionEffects.push(
1358
...argumentEffects.filter(
1359
- (argEffect) =>
1360
- !isUseEffect || i !== 0 || argEffect.kind !== "GlobalMutation"
1361
- )
1359
+ argEffect =>
1360
+ !isUseEffect || i !== 0 || argEffect.kind !== 'GlobalMutation',
1361
+ ),
1362
);
1363
hasCaptureArgument ||= place.effect === Effect.Capture;
1364
}
@@ -1367,14 +1367,14 @@ function inferBlock(
1367
instrValue.callee,
1368
signature.calleeEffect,
1369
ValueReason.Other,
1370
- functionEffects
1370
+ functionEffects,
1371
);
1372
} else {
1373
state.referenceAndRecordEffects(
1374
instrValue.callee,
1375
Effect.ConditionallyMutate,
1376
ValueReason.Other,
1377
- functionEffects
1377
+ functionEffects,
1378
);
1379
}
1380
hasCaptureArgument ||= instrValue.callee.effect === Effect.Capture;
@@ -1386,10 +1386,10 @@ function inferBlock(
1386
: Effect.ConditionallyMutate;
1387
continue;
1388
}
1389
- case "MethodCall": {
1389
+ case 'MethodCall': {
1390
CompilerError.invariant(state.isDefined(instrValue.receiver), {
1391
reason:
1392
- "[InferReferenceEffects] Internal error: receiver of PropertyCall should have been defined by corresponding PropertyLoad",
1392
+ '[InferReferenceEffects] Internal error: receiver of PropertyCall should have been defined by corresponding PropertyLoad',
1393
description: null,
1394
loc: instrValue.loc,
1395
suggestions: null,
@@ -1398,12 +1398,12 @@ function inferBlock(
1398
instrValue.property,
1399
Effect.Read,
1400
ValueReason.Other,
1401
- functionEffects
1401
+ functionEffects,
1402
);
1403
1404
const signature = getFunctionCallSignature(
1405
env,
1406
- instrValue.property.identifier.type
1406
+ instrValue.property.identifier.type,
1407
);
1408
1409
const returnValueKind: AbstractValue =
@@ -1429,19 +1429,19 @@ function inferBlock(
1429
* treating as all reads (except that the receiver may be captured)
1430
*/
1431
for (const arg of instrValue.args) {
1432
- const place = arg.kind === "Identifier" ? arg : arg.place;
1432
+ const place = arg.kind === 'Identifier' ? arg : arg.place;
1433
state.referenceAndRecordEffects(
1434
place,
1435
Effect.Read,
1436
ValueReason.Other,
1437
- functionEffects
1437
+ functionEffects,
1438
);
1439
}
1440
state.referenceAndRecordEffects(
1441
instrValue.receiver,
1442
Effect.Capture,
1443
ValueReason.Other,
1444
- functionEffects
1444
+ functionEffects,
1445
);
1446
state.initialize(instrValue, returnValueKind);
1447
state.define(instr.lvalue, instrValue);
@@ -1459,7 +1459,7 @@ function inferBlock(
1459
for (let i = 0; i < instrValue.args.length; i++) {
1460
const argumentEffects: Array<FunctionEffect> = [];
1461
const arg = instrValue.args[i];
1462
- const place = arg.kind === "Identifier" ? arg : arg.place;
1462
+ const place = arg.kind === 'Identifier' ? arg : arg.place;
1463
if (effects !== null) {
1464
/*
1465
* If effects are inferred for an argument, we should fail invalid
@@ -1469,14 +1469,14 @@ function inferBlock(
1469
place,
1470
effects[i],
1471
ValueReason.Other,
1472
- argumentEffects
1472
+ argumentEffects,
1473
);
1474
} else {
1475
state.referenceAndRecordEffects(
1476
place,
1477
Effect.ConditionallyMutate,
1478
ValueReason.Other,
1479
- argumentEffects
1479
+ argumentEffects,
1480
);
1481
}
1482
/*
@@ -1485,9 +1485,9 @@ function inferBlock(
1485
*/
1486
functionEffects.push(
1487
...argumentEffects.filter(
1488
- (argEffect) =>
1489
- !isUseEffect || i !== 0 || argEffect.kind !== "GlobalMutation"
1490
- )
1488
+ argEffect =>
1489
+ !isUseEffect || i !== 0 || argEffect.kind !== 'GlobalMutation',
1490
+ ),
1491
);
1492
hasCaptureArgument ||= place.effect === Effect.Capture;
1493
}
@@ -1496,14 +1496,14 @@ function inferBlock(
1496
instrValue.receiver,
1497
signature.calleeEffect,
1498
ValueReason.Other,
1499
- functionEffects
1499
+ functionEffects,
1500
);
1501
} else {
1502
state.referenceAndRecordEffects(
1503
instrValue.receiver,
1504
Effect.ConditionallyMutate,
1505
ValueReason.Other,
1506
- functionEffects
1506
+ functionEffects,
1507
);
1508
}
1509
hasCaptureArgument ||= instrValue.receiver.effect === Effect.Capture;
@@ -1515,7 +1515,7 @@ function inferBlock(
1515
: Effect.ConditionallyMutate;
1516
continue;
1517
}
1518
- case "PropertyStore": {
1518
+ case 'PropertyStore': {
1519
const effect =
1520
state.kind(instrValue.object).kind === ValueKind.Context
1521
? Effect.ConditionallyMutate
@@ -1524,13 +1524,13 @@ function inferBlock(
1524
instrValue.value,
1525
effect,
1526
ValueReason.Other,
1527
- functionEffects
1527
+ functionEffects,
1528
);
1529
state.referenceAndRecordEffects(
1530
instrValue.object,
1531
Effect.Store,
1532
ValueReason.Other,
1533
- functionEffects
1533
+ functionEffects,
1534
);
1535
1536
const lvalue = instr.lvalue;
@@ -1538,22 +1538,22 @@ function inferBlock(
1538
lvalue.effect = Effect.Store;
1539
continue;
1540
}
1541
- case "PropertyDelete": {
1541
+ case 'PropertyDelete': {
1542
// `delete` returns a boolean (immutable) and modifies the object
1543
valueKind = {
1544
kind: ValueKind.Primitive,
1545
reason: new Set([ValueReason.Other]),
1546
context: new Set(),
1547
};
1548
- effect = { kind: Effect.Mutate, reason: ValueReason.Other };
1548
+ effect = {kind: Effect.Mutate, reason: ValueReason.Other};
1549
break;
1550
}
1551
- case "PropertyLoad": {
1551
+ case 'PropertyLoad': {
1552
state.referenceAndRecordEffects(
1553
instrValue.object,
1554
Effect.Read,
1555
ValueReason.Other,
1556
- functionEffects
1556
+ functionEffects,
1557
);
1558
const lvalue = instr.lvalue;
1559
lvalue.effect = Effect.ConditionallyMutate;
@@ -1561,7 +1561,7 @@ function inferBlock(
1561
state.define(lvalue, instrValue);
1562
continue;
1563
}
1564
- case "ComputedStore": {
1564
+ case 'ComputedStore': {
1565
const effect =
1566
state.kind(instrValue.object).kind === ValueKind.Context
1567
? Effect.ConditionallyMutate
@@ -1570,19 +1570,19 @@ function inferBlock(
1570
instrValue.value,
1571
effect,
1572
ValueReason.Other,
1573
- functionEffects
1573
+ functionEffects,
1574
);
1575
state.referenceAndRecordEffects(
1576
instrValue.property,
1577
Effect.Capture,
1578
ValueReason.Other,
1579
- functionEffects
1579
+ functionEffects,
1580
);
1581
state.referenceAndRecordEffects(
1582
instrValue.object,
1583
Effect.Store,
1584
ValueReason.Other,
1585
- functionEffects
1585
+ functionEffects,
1586
);
1587
1588
const lvalue = instr.lvalue;
@@ -1590,18 +1590,18 @@ function inferBlock(
1590
lvalue.effect = Effect.Store;
1591
continue;
1592
}
1593
- case "ComputedDelete": {
1593
+ case 'ComputedDelete': {
1594
state.referenceAndRecordEffects(
1595
instrValue.object,
1596
Effect.Mutate,
1597
ValueReason.Other,
1598
- functionEffects
1598
+ functionEffects,
1599
);
1600
state.referenceAndRecordEffects(
1601
instrValue.property,
1602
Effect.Read,
1603
ValueReason.Other,
1604
- functionEffects
1604
+ functionEffects,
1605
);
1606
state.initialize(instrValue, {
1607
kind: ValueKind.Primitive,
@@ -1612,18 +1612,18 @@ function inferBlock(
1612
instr.lvalue.effect = Effect.Mutate;
1613
continue;
1614
}
1615
- case "ComputedLoad": {
1615
+ case 'ComputedLoad': {
1616
state.referenceAndRecordEffects(
1617
instrValue.object,
1618
Effect.Read,
1619
ValueReason.Other,
1620
- functionEffects
1620
+ functionEffects,
1621
);
1622
state.referenceAndRecordEffects(
1623
instrValue.property,
1624
Effect.Read,
1625
ValueReason.Other,
1626
- functionEffects
1626
+ functionEffects,
1627
);
1628
const lvalue = instr.lvalue;
1629
lvalue.effect = Effect.ConditionallyMutate;
@@ -1631,7 +1631,7 @@ function inferBlock(
1631
state.define(lvalue, instrValue);
1632
continue;
1633
}
1634
- case "Await": {
1634
+ case 'Await': {
1635
state.initialize(instrValue, state.kind(instrValue.value));
1636
/*
1637
* Awaiting a value causes it to change state (go from unresolved to resolved or error)
@@ -1642,14 +1642,14 @@ function inferBlock(
1642
instrValue.value,
1643
Effect.ConditionallyMutate,
1644
ValueReason.Other,
1645
- functionEffects
1645
+ functionEffects,
1646
);
1647
const lvalue = instr.lvalue;
1648
lvalue.effect = Effect.ConditionallyMutate;
1649
state.alias(lvalue, instrValue.value);
1650
continue;
1651
}
1652
- case "TypeCastExpression": {
1652
+ case 'TypeCastExpression': {
1653
/*
1654
* A type cast expression has no effect at runtime, so it's equivalent to a raw
1655
* identifier:
@@ -1663,29 +1663,29 @@ function inferBlock(
1663
instrValue.value,
1664
Effect.Read,
1665
ValueReason.Other,
1666
- functionEffects
1666
+ functionEffects,
1667
);
1668
const lvalue = instr.lvalue;
1669
lvalue.effect = Effect.ConditionallyMutate;
1670
state.alias(lvalue, instrValue.value);
1671
continue;
1672
}
1673
- case "StartMemoize":
1674
- case "FinishMemoize": {
1673
+ case 'StartMemoize':
1674
+ case 'FinishMemoize': {
1675
for (const val of eachInstructionValueOperand(instrValue)) {
1676
if (env.config.enablePreserveExistingMemoizationGuarantees) {
1677
state.referenceAndRecordEffects(
1678
val,
1679
Effect.Freeze,
1680
ValueReason.Other,
1681
- []
1681
+ [],
1682
);
1683
} else {
1684
state.referenceAndRecordEffects(
1685
val,
1686
Effect.Read,
1687
ValueReason.Other,
1688
- []
1688
+ [],
1689
);
1690
}
1691
}
@@ -1699,7 +1699,7 @@ function inferBlock(
1699
state.define(lvalue, instrValue);
1700
continue;
1701
}
1702
- case "LoadLocal": {
1702
+ case 'LoadLocal': {
1703
const lvalue = instr.lvalue;
1704
const effect =
1705
state.isDefined(lvalue) &&
@@ -1710,19 +1710,19 @@ function inferBlock(
1710
instrValue.place,
1711
effect,
1712
ValueReason.Other,
1713
- []
1713
+ [],
1714
);
1715
lvalue.effect = Effect.ConditionallyMutate;
1716
// direct aliasing: `a = b`;
1717
state.alias(lvalue, instrValue.place);
1718
continue;
1719
}
1720
- case "LoadContext": {
1720
+ case 'LoadContext': {
1721
state.referenceAndRecordEffects(
1722
instrValue.place,
1723
Effect.Capture,
1724
ValueReason.Other,
1725
- functionEffects
1725
+ functionEffects,
1726
);
1727
const lvalue = instr.lvalue;
1728
lvalue.effect = Effect.ConditionallyMutate;
@@ -1731,7 +1731,7 @@ function inferBlock(
1731
state.define(lvalue, instrValue);
1732
continue;
1733
}
1734
- case "DeclareLocal": {
1734
+ case 'DeclareLocal': {
1735
const value = UndefinedValue;
1736
state.initialize(
1737
value,
@@ -1746,12 +1746,12 @@ function inferBlock(
1746
kind: ValueKind.Primitive,
1747
reason: new Set([ValueReason.Other]),
1748
context: new Set(),
1749
- }
1749
+ },
1750
);
1751
state.define(instrValue.lvalue.place, value);
1752
continue;
1753
}
1754
- case "DeclareContext": {
1754
+ case 'DeclareContext': {
1755
state.initialize(instrValue, {
1756
kind: ValueKind.Mutable,
1757
reason: new Set([ValueReason.Other]),
@@ -1760,8 +1760,8 @@ function inferBlock(
1760
state.define(instrValue.lvalue.place, instrValue);
1761
continue;
1762
}
1763
- case "PostfixUpdate":
1764
- case "PrefixUpdate": {
1763
+ case 'PostfixUpdate':
1764
+ case 'PrefixUpdate': {
1765
const effect =
1766
state.isDefined(instrValue.lvalue) &&
1767
state.kind(instrValue.lvalue).kind === ValueKind.Context
@@ -1771,7 +1771,7 @@ function inferBlock(
1771
instrValue.value,
1772
effect,
1773
ValueReason.Other,
1774
- functionEffects
1774
+ functionEffects,
1775
);
1776
1777
const lvalue = instr.lvalue;
@@ -1787,7 +1787,7 @@ function inferBlock(
1787
instrValue.lvalue.effect = Effect.Store;
1788
continue;
1789
}
1790
- case "StoreLocal": {
1790
+ case 'StoreLocal': {
1791
const effect =
1792
state.isDefined(instrValue.lvalue.place) &&
1793
state.kind(instrValue.lvalue.place).kind === ValueKind.Context
@@ -1797,7 +1797,7 @@ function inferBlock(
1797
instrValue.value,
1798
effect,
1799
ValueReason.Other,
1800
- []
1800
+ [],
1801
);
1802
1803
const lvalue = instr.lvalue;
@@ -1813,18 +1813,18 @@ function inferBlock(
1813
instrValue.lvalue.place.effect = Effect.Store;
1814
continue;
1815
}
1816
- case "StoreContext": {
1816
+ case 'StoreContext': {
1817
state.referenceAndRecordEffects(
1818
instrValue.value,
1819
Effect.ConditionallyMutate,
1820
ValueReason.Other,
1821
- functionEffects
1821
+ functionEffects,
1822
);
1823
state.referenceAndRecordEffects(
1824
instrValue.lvalue.place,
1825
Effect.Mutate,
1826
ValueReason.Other,
1827
- functionEffects
1827
+ functionEffects,
1828
);
1829
1830
const lvalue = instr.lvalue;
@@ -1832,21 +1832,21 @@ function inferBlock(
1832
lvalue.effect = Effect.Store;
1833
continue;
1834
}
1835
- case "StoreGlobal": {
1835
+ case 'StoreGlobal': {
1836
state.referenceAndRecordEffects(
1837
instrValue.value,
1838
Effect.Capture,
1839
ValueReason.Other,
1840
- functionEffects
1840
+ functionEffects,
1841
);
1842
const lvalue = instr.lvalue;
1843
lvalue.effect = Effect.Store;
1844
1845
functionEffects.push({
1846
- kind: "GlobalMutation",
1846
+ kind: 'GlobalMutation',
1847
error: {
1848
reason:
1849
- "Unexpected reassignment of a variable which was defined outside of the component. Components and hooks should be pure and side-effect free, but variable reassignment is a form of side-effect. If this variable is used in rendering, use useState instead. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render)",
1849
+ 'Unexpected reassignment of a variable which was defined outside of the component. Components and hooks should be pure and side-effect free, but variable reassignment is a form of side-effect. If this variable is used in rendering, use useState instead. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render)',
1850
loc: instr.loc,
1851
suggestions: null,
1852
severity: ErrorSeverity.InvalidReact,
@@ -1854,7 +1854,7 @@ function inferBlock(
1854
});
1855
continue;
1856
}
1857
- case "Destructure": {
1857
+ case 'Destructure': {
1858
let effect: Effect = Effect.Capture;
1859
for (const place of eachPatternOperand(instrValue.lvalue.pattern)) {
1860
if (
@@ -1869,7 +1869,7 @@ function inferBlock(
1869
instrValue.value,
1870
effect,
1871
ValueReason.Other,
1872
- functionEffects
1872
+ functionEffects,
1873
);
1874
1875
const lvalue = instr.lvalue;
@@ -1887,7 +1887,7 @@ function inferBlock(
1887
}
1888
continue;
1889
}
1890
- case "GetIterator": {
1890
+ case 'GetIterator': {
1891
/**
1892
* This instruction represents the step of retrieving an iterator from the collection
1893
* in `for (... of <collection>)` syntax. We model two cases:
@@ -1927,7 +1927,7 @@ function inferBlock(
1927
lvalueEffect = Effect.Store;
1928
break;
1929
}
1930
- case "IteratorNext": {
1930
+ case 'IteratorNext': {
1931
/**
1932
* This instruction represents advancing an iterator with .next(). We use a
1933
* conditional mutate to model the two cases for GetIterator:
@@ -1942,7 +1942,7 @@ function inferBlock(
1942
instrValue.iterator,
1943
Effect.ConditionallyMutate,
1944
ValueReason.Other,
1945
- functionEffects
1945
+ functionEffects,
1946
);
1947
/**
1948
* Regardless of the effect on the iterator, the *result* of advancing the iterator
@@ -1954,15 +1954,15 @@ function inferBlock(
1954
instrValue.collection,
1955
Effect.Capture,
1956
ValueReason.Other,
1957
- functionEffects
1957
+ functionEffects,
1958
);
1959
state.initialize(instrValue, state.kind(instrValue.collection));
1960
state.define(instr.lvalue, instrValue);
1961
instr.lvalue.effect = Effect.Store;
1962
continue;
1963
}
1964
- case "NextPropertyOf": {
1965
- effect = { kind: Effect.Read, reason: ValueReason.Other };
1964
+ case 'NextPropertyOf': {
1965
+ effect = {kind: Effect.Read, reason: ValueReason.Other};
1966
lvalueEffect = Effect.Store;
1967
valueKind = {
1968
kind: ValueKind.Primitive,
@@ -1972,7 +1972,7 @@ function inferBlock(
1972
break;
1973
}
1974
default: {
1975
- assertExhaustive(instrValue, "Unexpected instruction kind");
1975
+ assertExhaustive(instrValue, 'Unexpected instruction kind');
1976
}
1977
}
1978
@@ -1987,7 +1987,7 @@ function inferBlock(
1987
operand,
1988
effect.kind,
1989
effect.reason,
1990
- functionEffects
1990
+ functionEffects,
1991
);
1992
}
1993
@@ -1998,7 +1998,7 @@ function inferBlock(
1998
1999
for (const operand of eachTerminalOperand(block.terminal)) {
2000
let effect;
2001
- if (block.terminal.kind === "return" || block.terminal.kind === "throw") {
2001
+ if (block.terminal.kind === 'return' || block.terminal.kind === 'throw') {
2002
if (
2003
state.isDefined(operand) &&
2004
state.kind(operand).kind === ValueKind.Context
@@ -2014,14 +2014,14 @@ function inferBlock(
2014
operand,
2015
effect,
2016
ValueReason.Other,
2017
- functionEffects
2017
+ functionEffects,
2018
);
2019
}
2020
}
2021
2022
function hasContextRefOperand(
2023
state: InferenceState,
2024
- instrValue: InstructionValue
2024
+ instrValue: InstructionValue,
2025
): boolean {
2026
for (const place of eachInstructionValueOperand(instrValue)) {
2027
if (
@@ -2036,9 +2036,9 @@ function hasContextRefOperand(
2036
2037
export function getFunctionCallSignature(
2038
env: Environment,
2039
- type: Type
2039
+ type: Type,
2040
): FunctionSignature | null {
2041
- if (type.kind !== "Function") {
2041
+ if (type.kind !== 'Function') {
2042
return null;
2043
}
2044
return env.getFunctionSignature(type);
@@ -2054,7 +2054,7 @@ export function getFunctionCallSignature(
2054
*/
2055
function getFunctionEffects(
2056
fn: MethodCall | CallExpression,
2057
- sig: FunctionSignature
2057
+ sig: FunctionSignature,
2058
): Array<Effect> | null {
2059
const results = [];
2060
for (let i = 0; i < fn.args.length; i++) {
@@ -2064,7 +2064,7 @@ function getFunctionEffects(
2064
* Only infer effects when there is a direct mapping positional arg --> positional param
2065
* Otherwise, return null to indicate inference failed
2066
*/
2067
- if (arg.kind === "Identifier") {
2067
+ if (arg.kind === 'Identifier') {
2068
results.push(sig.positionalParams[i]);
2069
} else {
2070
return null;
@@ -2090,10 +2090,10 @@ function getFunctionEffects(
2090
*/
2091
function areArgumentsImmutableAndNonMutating(
2092
state: InferenceState,
2093
- args: MethodCall["args"]
2093
+ args: MethodCall['args'],
2094
): boolean {
2095
for (const arg of args) {
2096
- const place = arg.kind === "Identifier" ? arg : arg.place;
2096
+ const place = arg.kind === 'Identifier' ? arg : arg.place;
2097
const kind = state.kind(place).kind;
2098
switch (kind) {
2099
case ValueKind.Global:
@@ -2113,9 +2113,9 @@ function areArgumentsImmutableAndNonMutating(
2113
const values = state.values(place);
2114
for (const value of values) {
2115
if (
2116
- value.kind === "FunctionExpression" &&
2117
- value.loweredFunc.func.params.some((param) => {
2118
- const place = param.kind === "Identifier" ? param : param.place;
2116
+ value.kind === 'FunctionExpression' &&
2117
+ value.loweredFunc.func.params.some(param => {
2118
+ const place = param.kind === 'Identifier' ? param : param.place;
2119
const range = place.identifier.mutableRange;
2120
return range.end > range.start + 1;
2121
})
@@ -2130,20 +2130,20 @@ function areArgumentsImmutableAndNonMutating(
2130
2131
function getWriteErrorReason(abstractValue: AbstractValue): string {
2132
if (abstractValue.reason.has(ValueReason.Global)) {
2133
- return "Writing to a variable defined outside a component or hook is not allowed. Consider using an effect";
2133
+ return 'Writing to a variable defined outside a component or hook is not allowed. Consider using an effect';
2134
} else if (abstractValue.reason.has(ValueReason.JsxCaptured)) {
2135
- return "Updating a value used previously in JSX is not allowed. Consider moving the mutation before the JSX";
2135
+ return 'Updating a value used previously in JSX is not allowed. Consider moving the mutation before the JSX';
2136
} else if (abstractValue.reason.has(ValueReason.Context)) {
2137
return `Mutating a value returned from 'useContext()', which should not be mutated`;
2138
} else if (abstractValue.reason.has(ValueReason.KnownReturnSignature)) {
2139
- return "Mutating a value returned from a function whose return value should not be mutated";
2139
+ return 'Mutating a value returned from a function whose return value should not be mutated';
2140
} else if (abstractValue.reason.has(ValueReason.ReactiveFunctionArgument)) {
2141
- return "Mutating component props or hook arguments is not allowed. Consider using a local variable instead";
2141
+ return 'Mutating component props or hook arguments is not allowed. Consider using a local variable instead';
2142
} else if (abstractValue.reason.has(ValueReason.State)) {
2143
return "Mutating a value returned from 'useState()', which should not be mutated. Use the setter function to update instead";
2144
} else if (abstractValue.reason.has(ValueReason.ReducerState)) {
2145
return "Mutating a value returned from 'useReducer()', which should not be mutated. Use the dispatch function to update instead";
2146
} else {
2147
- return "This mutates a variable that React considers immutable";
2147
+ return 'This mutates a variable that React considers immutable';
2148
}
2149
}
compiler/packages/babel-plugin-react-compiler/src/Inference/InferTryCatchAliases.ts
+6
-6
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { BlockId, HIRFunction, Identifier } from "../HIR";
9
-import DisjointSet from "../Utils/DisjointSet";
8
+import {BlockId, HIRFunction, Identifier} from '../HIR';
9
+import DisjointSet from '../Utils/DisjointSet';
10
11
/*
12
* Any values created within a try/catch block could be aliased to the try handler.
@@ -16,19 +16,19 @@ import DisjointSet from "../Utils/DisjointSet";
16
*/
17
export function inferTryCatchAliases(
18
fn: HIRFunction,
19
- aliases: DisjointSet<Identifier>
19
+ aliases: DisjointSet<Identifier>,
20
): void {
21
const handlerParams: Map<BlockId, Identifier> = new Map();
22
for (const [_, block] of fn.body.blocks) {
23
if (
24
- block.terminal.kind === "try" &&
24
+ block.terminal.kind === 'try' &&
25
block.terminal.handlerBinding !== null
26
) {
27
handlerParams.set(
28
block.terminal.handler,
29
- block.terminal.handlerBinding.identifier
29
+ block.terminal.handlerBinding.identifier,
30
);
31
- } else if (block.terminal.kind === "maybe-throw") {
31
+ } else if (block.terminal.kind === 'maybe-throw') {
32
const handlerParam = handlerParams.get(block.terminal.handler);
33
if (handlerParam === undefined) {
34
/*
compiler/packages/babel-plugin-react-compiler/src/Inference/InlineImmediatelyInvokedFunctionExpressions.ts
+19
-19
@@ -22,10 +22,10 @@ import {
22
makeType,
23
promoteTemporary,
24
reversePostorderBlocks,
25
-} from "../HIR";
26
-import { markInstructionIds, markPredecessors } from "../HIR/HIRBuilder";
27
-import { eachInstructionValueOperand } from "../HIR/visitors";
28
-import { retainWhere } from "../Utils/utils";
25
+} from '../HIR';
26
+import {markInstructionIds, markPredecessors} from '../HIR/HIRBuilder';
27
+import {eachInstructionValueOperand} from '../HIR/visitors';
28
+import {retainWhere} from '../Utils/utils';
29
30
/*
31
* Inlines immediately invoked function expressions (IIFEs) to allow more fine-grained memoization
@@ -72,7 +72,7 @@ import { retainWhere } from "../Utils/utils";
72
* block (code following the CallExpression).
73
*/
74
export function inlineImmediatelyInvokedFunctionExpressions(
75
- fn: HIRFunction
75
+ fn: HIRFunction,
76
): void {
77
// Track all function expressions that are assigned to a temporary
78
const functions = new Map<IdentifierId, FunctionExpression>();
@@ -91,13 +91,13 @@ export function inlineImmediatelyInvokedFunctionExpressions(
91
for (let ii = 0; ii < block.instructions.length; ii++) {
92
const instr = block.instructions[ii]!;
93
switch (instr.value.kind) {
94
- case "FunctionExpression": {
94
+ case 'FunctionExpression': {
95
if (instr.lvalue.identifier.name === null) {
96
functions.set(instr.lvalue.identifier.id, instr.value);
97
}
98
break;
99
}
100
- case "CallExpression": {
100
+ case 'CallExpression': {
101
if (instr.value.args.length !== 0) {
102
// We don't support inlining when there are arguments
103
continue;
@@ -146,7 +146,7 @@ export function inlineImmediatelyInvokedFunctionExpressions(
146
const newTerminal: LabelTerminal = {
147
block: body.loweredFunc.func.body.entry,
148
id: makeInstructionId(0),
149
- kind: "label",
149
+ kind: 'label',
150
fallthrough: continuationBlockId,
151
loc: block.terminal.loc,
152
};
@@ -193,7 +193,7 @@ export function inlineImmediatelyInvokedFunctionExpressions(
193
for (const [, block] of fn.body.blocks) {
194
retainWhere(
195
block.instructions,
196
- (instr) => !inlinedFunctions.has(instr.lvalue.identifier.id)
196
+ instr => !inlinedFunctions.has(instr.lvalue.identifier.id),
197
);
198
}
199
@@ -216,10 +216,10 @@ function rewriteBlock(
216
env: Environment,
217
block: BasicBlock,
218
returnTarget: BlockId,
219
- returnValue: Place
219
+ returnValue: Place,
220
): void {
221
- const { terminal } = block;
222
- if (terminal.kind !== "return") {
221
+ const {terminal} = block;
222
+ if (terminal.kind !== 'return') {
223
return;
224
}
225
block.instructions.push({
@@ -238,20 +238,20 @@ function rewriteBlock(
238
type: makeType(),
239
loc: terminal.loc,
240
},
241
- kind: "Identifier",
241
+ kind: 'Identifier',
242
reactive: false,
243
loc: terminal.loc,
244
},
245
value: {
246
- kind: "StoreLocal",
247
- lvalue: { kind: InstructionKind.Reassign, place: { ...returnValue } },
246
+ kind: 'StoreLocal',
247
+ lvalue: {kind: InstructionKind.Reassign, place: {...returnValue}},
248
value: terminal.value,
249
type: null,
250
loc: terminal.loc,
251
},
252
});
253
block.terminal = {
254
- kind: "goto",
254
+ kind: 'goto',
255
block: returnTarget,
256
id: makeInstructionId(0),
257
variant: GotoVariant.Break,
@@ -262,7 +262,7 @@ function rewriteBlock(
262
function declareTemporary(
263
env: Environment,
264
block: BasicBlock,
265
- result: Place
265
+ result: Place,
266
): void {
267
block.instructions.push({
268
id: makeInstructionId(0),
@@ -280,12 +280,12 @@ function declareTemporary(
280
type: makeType(),
281
loc: result.loc,
282
},
283
- kind: "Identifier",
283
+ kind: 'Identifier',
284
reactive: false,
285
loc: GeneratedSource,
286
},
287
value: {
288
- kind: "DeclareLocal",
288
+ kind: 'DeclareLocal',
289
lvalue: {
290
place: result,
291
kind: InstructionKind.Let,
compiler/packages/babel-plugin-react-compiler/src/Inference/index.ts
+6
-6
@@ -5,9 +5,9 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-export { default as analyseFunctions } from "./AnalyseFunctions";
9
-export { dropManualMemoization } from "./DropManualMemoization";
10
-export { inferMutableRanges } from "./InferMutableRanges";
11
-export { inferReactivePlaces } from "./InferReactivePlaces";
12
-export { default as inferReferenceEffects } from "./InferReferenceEffects";
13
-export { inlineImmediatelyInvokedFunctionExpressions } from "./InlineImmediatelyInvokedFunctionExpressions";
8
+export {default as analyseFunctions} from './AnalyseFunctions';
9
+export {dropManualMemoization} from './DropManualMemoization';
10
+export {inferMutableRanges} from './InferMutableRanges';
11
+export {inferReactivePlaces} from './InferReactivePlaces';
12
+export {default as inferReferenceEffects} from './InferReferenceEffects';
13
+export {inlineImmediatelyInvokedFunctionExpressions} from './InlineImmediatelyInvokedFunctionExpressions';
compiler/packages/babel-plugin-react-compiler/src/Optimization/ConstantPropagation.ts
+111
-111
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { isValidIdentifier } from "@babel/types";
9
-import { CompilerError } from "../CompilerError";
8
+import {isValidIdentifier} from '@babel/types';
9
+import {CompilerError} from '../CompilerError';
10
import {
11
Environment,
12
GotoVariant,
@@ -24,13 +24,13 @@ import {
24
markPredecessors,
25
mergeConsecutiveBlocks,
26
reversePostorderBlocks,
27
-} from "../HIR";
27
+} from '../HIR';
28
import {
29
removeDeadDoWhileStatements,
30
removeUnnecessaryTryCatch,
31
removeUnreachableForUpdates,
32
-} from "../HIR/HIRBuilder";
33
-import { eliminateRedundantPhi } from "../SSA";
32
+} from '../HIR/HIRBuilder';
33
+import {eliminateRedundantPhi} from '../SSA';
34
35
/*
36
* Applies constant propagation/folding to the given function. The approach is
@@ -105,7 +105,7 @@ function constantPropagationImpl(fn: HIRFunction, constants: Constants): void {
105
106
function applyConstantPropagation(
107
fn: HIRFunction,
108
- constants: Constants
108
+ constants: Constants,
109
): boolean {
110
let hasChanges = false;
111
for (const [, block] of fn.body.blocks) {
@@ -122,7 +122,7 @@ function applyConstantPropagation(
122
}
123
124
for (let i = 0; i < block.instructions.length; i++) {
125
- if (block.kind === "sequence" && i === block.instructions.length - 1) {
125
+ if (block.kind === 'sequence' && i === block.instructions.length - 1) {
126
/*
127
* evaluating the last value of a value block can break order of evaluation,
128
* skip these instructions
@@ -138,15 +138,15 @@ function applyConstantPropagation(
138
139
const terminal = block.terminal;
140
switch (terminal.kind) {
141
- case "if": {
141
+ case 'if': {
142
const testValue = read(constants, terminal.test);
143
- if (testValue !== null && testValue.kind === "Primitive") {
143
+ if (testValue !== null && testValue.kind === 'Primitive') {
144
hasChanges = true;
145
const targetBlockId = testValue.value
146
? terminal.consequent
147
: terminal.alternate;
148
block.terminal = {
149
- kind: "goto",
149
+ kind: 'goto',
150
variant: GotoVariant.Break,
151
block: targetBlockId,
152
id: terminal.id,
@@ -188,9 +188,9 @@ function evaluatePhi(phi: Phi, constants: Constants): Constant | null {
188
}
189
190
switch (operandValue.kind) {
191
- case "Primitive": {
192
- CompilerError.invariant(value.kind === "Primitive", {
193
- reason: "value kind expected to be Primitive",
191
+ case 'Primitive': {
192
+ CompilerError.invariant(value.kind === 'Primitive', {
193
+ reason: 'value kind expected to be Primitive',
194
loc: null,
195
suggestions: null,
196
});
@@ -201,9 +201,9 @@ function evaluatePhi(phi: Phi, constants: Constants): Constant | null {
201
}
202
break;
203
}
204
- case "LoadGlobal": {
205
- CompilerError.invariant(value.kind === "LoadGlobal", {
206
- reason: "value kind expected to be LoadGlobal",
204
+ case 'LoadGlobal': {
205
+ CompilerError.invariant(value.kind === 'LoadGlobal', {
206
+ reason: 'value kind expected to be LoadGlobal',
207
loc: null,
208
suggestions: null,
209
});
@@ -225,26 +225,26 @@ function evaluatePhi(phi: Phi, constants: Constants): Constant | null {
225
function evaluateInstruction(
226
env: Environment,
227
constants: Constants,
228
- instr: Instruction
228
+ instr: Instruction,
229
): Constant | null {
230
const value = instr.value;
231
switch (value.kind) {
232
- case "Primitive": {
232
+ case 'Primitive': {
233
return value;
234
}
235
- case "LoadGlobal": {
235
+ case 'LoadGlobal': {
236
return value;
237
}
238
- case "ComputedLoad": {
238
+ case 'ComputedLoad': {
239
const property = read(constants, value.property);
240
if (
241
property !== null &&
242
- property.kind === "Primitive" &&
243
- typeof property.value === "string" &&
242
+ property.kind === 'Primitive' &&
243
+ typeof property.value === 'string' &&
244
isValidIdentifier(property.value)
245
) {
246
const nextValue: InstructionValue = {
247
- kind: "PropertyLoad",
247
+ kind: 'PropertyLoad',
248
loc: value.loc,
249
property: property.value,
250
object: value.object,
@@ -253,16 +253,16 @@ function evaluateInstruction(
253
}
254
return null;
255
}
256
- case "ComputedStore": {
256
+ case 'ComputedStore': {
257
const property = read(constants, value.property);
258
if (
259
property !== null &&
260
- property.kind === "Primitive" &&
261
- typeof property.value === "string" &&
260
+ property.kind === 'Primitive' &&
261
+ typeof property.value === 'string' &&
262
isValidIdentifier(property.value)
263
) {
264
const nextValue: InstructionValue = {
265
- kind: "PropertyStore",
265
+ kind: 'PropertyStore',
266
loc: value.loc,
267
property: property.value,
268
object: value.object,
@@ -272,18 +272,18 @@ function evaluateInstruction(
272
}
273
return null;
274
}
275
- case "PostfixUpdate": {
275
+ case 'PostfixUpdate': {
276
const previous = read(constants, value.value);
277
if (
278
previous !== null &&
279
- previous.kind === "Primitive" &&
280
- typeof previous.value === "number"
279
+ previous.kind === 'Primitive' &&
280
+ typeof previous.value === 'number'
281
) {
282
const next =
283
- value.operation === "++" ? previous.value + 1 : previous.value - 1;
283
+ value.operation === '++' ? previous.value + 1 : previous.value - 1;
284
// Store the updated value
285
constants.set(value.lvalue.identifier.id, {
286
- kind: "Primitive",
286
+ kind: 'Primitive',
287
value: next,
288
loc: value.loc,
289
});
@@ -292,17 +292,17 @@ function evaluateInstruction(
292
}
293
return null;
294
}
295
- case "PrefixUpdate": {
295
+ case 'PrefixUpdate': {
296
const previous = read(constants, value.value);
297
if (
298
previous !== null &&
299
- previous.kind === "Primitive" &&
300
- typeof previous.value === "number"
299
+ previous.kind === 'Primitive' &&
300
+ typeof previous.value === 'number'
301
) {
302
const next: Primitive = {
303
- kind: "Primitive",
303
+ kind: 'Primitive',
304
value:
305
- value.operation === "++" ? previous.value + 1 : previous.value - 1,
305
+ value.operation === '++' ? previous.value + 1 : previous.value - 1,
306
loc: value.loc,
307
};
308
// Store and return the updated value
@@ -311,13 +311,13 @@ function evaluateInstruction(
311
}
312
return null;
313
}
314
- case "UnaryExpression": {
314
+ case 'UnaryExpression': {
315
switch (value.operator) {
316
- case "!": {
316
+ case '!': {
317
const operand = read(constants, value.value);
318
- if (operand !== null && operand.kind === "Primitive") {
318
+ if (operand !== null && operand.kind === 'Primitive') {
319
const result: Primitive = {
320
- kind: "Primitive",
320
+ kind: 'Primitive',
321
value: !operand.value,
322
loc: value.loc,
323
};
@@ -330,135 +330,135 @@ function evaluateInstruction(
330
return null;
331
}
332
}
333
- case "BinaryExpression": {
333
+ case 'BinaryExpression': {
334
const lhsValue = read(constants, value.left);
335
const rhsValue = read(constants, value.right);
336
if (
337
lhsValue !== null &&
338
rhsValue !== null &&
339
- lhsValue.kind === "Primitive" &&
340
- rhsValue.kind === "Primitive"
339
+ lhsValue.kind === 'Primitive' &&
340
+ rhsValue.kind === 'Primitive'
341
) {
342
const lhs = lhsValue.value;
343
const rhs = rhsValue.value;
344
let result: Primitive | null = null;
345
switch (value.operator) {
346
- case "+": {
347
- if (typeof lhs === "number" && typeof rhs === "number") {
348
- result = { kind: "Primitive", value: lhs + rhs, loc: value.loc };
349
- } else if (typeof lhs === "string" && typeof rhs === "string") {
350
- result = { kind: "Primitive", value: lhs + rhs, loc: value.loc };
346
+ case '+': {
347
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
348
+ result = {kind: 'Primitive', value: lhs + rhs, loc: value.loc};
349
+ } else if (typeof lhs === 'string' && typeof rhs === 'string') {
350
+ result = {kind: 'Primitive', value: lhs + rhs, loc: value.loc};
351
}
352
break;
353
}
354
- case "-": {
355
- if (typeof lhs === "number" && typeof rhs === "number") {
356
- result = { kind: "Primitive", value: lhs - rhs, loc: value.loc };
354
+ case '-': {
355
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
356
+ result = {kind: 'Primitive', value: lhs - rhs, loc: value.loc};
357
}
358
break;
359
}
360
- case "*": {
361
- if (typeof lhs === "number" && typeof rhs === "number") {
362
- result = { kind: "Primitive", value: lhs * rhs, loc: value.loc };
360
+ case '*': {
361
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
362
+ result = {kind: 'Primitive', value: lhs * rhs, loc: value.loc};
363
}
364
break;
365
}
366
- case "/": {
367
- if (typeof lhs === "number" && typeof rhs === "number") {
368
- result = { kind: "Primitive", value: lhs / rhs, loc: value.loc };
366
+ case '/': {
367
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
368
+ result = {kind: 'Primitive', value: lhs / rhs, loc: value.loc};
369
}
370
break;
371
}
372
- case "|": {
373
- if (typeof lhs === "number" && typeof rhs === "number") {
374
- result = { kind: "Primitive", value: lhs | rhs, loc: value.loc };
372
+ case '|': {
373
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
374
+ result = {kind: 'Primitive', value: lhs | rhs, loc: value.loc};
375
}
376
break;
377
}
378
- case "&": {
379
- if (typeof lhs === "number" && typeof rhs === "number") {
380
- result = { kind: "Primitive", value: lhs & rhs, loc: value.loc };
378
+ case '&': {
379
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
380
+ result = {kind: 'Primitive', value: lhs & rhs, loc: value.loc};
381
}
382
break;
383
}
384
- case "^": {
385
- if (typeof lhs === "number" && typeof rhs === "number") {
386
- result = { kind: "Primitive", value: lhs ^ rhs, loc: value.loc };
384
+ case '^': {
385
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
386
+ result = {kind: 'Primitive', value: lhs ^ rhs, loc: value.loc};
387
}
388
break;
389
}
390
- case "<<": {
391
- if (typeof lhs === "number" && typeof rhs === "number") {
392
- result = { kind: "Primitive", value: lhs << rhs, loc: value.loc };
390
+ case '<<': {
391
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
392
+ result = {kind: 'Primitive', value: lhs << rhs, loc: value.loc};
393
}
394
break;
395
}
396
- case ">>": {
397
- if (typeof lhs === "number" && typeof rhs === "number") {
398
- result = { kind: "Primitive", value: lhs >> rhs, loc: value.loc };
396
+ case '>>': {
397
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
398
+ result = {kind: 'Primitive', value: lhs >> rhs, loc: value.loc};
399
}
400
break;
401
}
402
- case ">>>": {
403
- if (typeof lhs === "number" && typeof rhs === "number") {
402
+ case '>>>': {
403
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
404
result = {
405
- kind: "Primitive",
405
+ kind: 'Primitive',
406
value: lhs >>> rhs,
407
loc: value.loc,
408
};
409
}
410
break;
411
}
412
- case "%": {
413
- if (typeof lhs === "number" && typeof rhs === "number") {
414
- result = { kind: "Primitive", value: lhs % rhs, loc: value.loc };
412
+ case '%': {
413
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
414
+ result = {kind: 'Primitive', value: lhs % rhs, loc: value.loc};
415
}
416
break;
417
}
418
- case "**": {
419
- if (typeof lhs === "number" && typeof rhs === "number") {
420
- result = { kind: "Primitive", value: lhs ** rhs, loc: value.loc };
418
+ case '**': {
419
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
420
+ result = {kind: 'Primitive', value: lhs ** rhs, loc: value.loc};
421
}
422
break;
423
}
424
- case "<": {
425
- if (typeof lhs === "number" && typeof rhs === "number") {
426
- result = { kind: "Primitive", value: lhs < rhs, loc: value.loc };
424
+ case '<': {
425
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
426
+ result = {kind: 'Primitive', value: lhs < rhs, loc: value.loc};
427
}
428
break;
429
}
430
- case "<=": {
431
- if (typeof lhs === "number" && typeof rhs === "number") {
432
- result = { kind: "Primitive", value: lhs <= rhs, loc: value.loc };
430
+ case '<=': {
431
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
432
+ result = {kind: 'Primitive', value: lhs <= rhs, loc: value.loc};
433
}
434
break;
435
}
436
- case ">": {
437
- if (typeof lhs === "number" && typeof rhs === "number") {
438
- result = { kind: "Primitive", value: lhs > rhs, loc: value.loc };
436
+ case '>': {
437
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
438
+ result = {kind: 'Primitive', value: lhs > rhs, loc: value.loc};
439
}
440
break;
441
}
442
- case ">=": {
443
- if (typeof lhs === "number" && typeof rhs === "number") {
444
- result = { kind: "Primitive", value: lhs >= rhs, loc: value.loc };
442
+ case '>=': {
443
+ if (typeof lhs === 'number' && typeof rhs === 'number') {
444
+ result = {kind: 'Primitive', value: lhs >= rhs, loc: value.loc};
445
}
446
break;
447
}
448
- case "==": {
449
- result = { kind: "Primitive", value: lhs == rhs, loc: value.loc };
448
+ case '==': {
449
+ result = {kind: 'Primitive', value: lhs == rhs, loc: value.loc};
450
break;
451
}
452
- case "===": {
453
- result = { kind: "Primitive", value: lhs === rhs, loc: value.loc };
452
+ case '===': {
453
+ result = {kind: 'Primitive', value: lhs === rhs, loc: value.loc};
454
break;
455
}
456
- case "!=": {
457
- result = { kind: "Primitive", value: lhs != rhs, loc: value.loc };
456
+ case '!=': {
457
+ result = {kind: 'Primitive', value: lhs != rhs, loc: value.loc};
458
break;
459
}
460
- case "!==": {
461
- result = { kind: "Primitive", value: lhs !== rhs, loc: value.loc };
460
+ case '!==': {
461
+ result = {kind: 'Primitive', value: lhs !== rhs, loc: value.loc};
462
break;
463
}
464
default: {
@@ -472,16 +472,16 @@ function evaluateInstruction(
472
}
473
return null;
474
}
475
- case "PropertyLoad": {
475
+ case 'PropertyLoad': {
476
const objectValue = read(constants, value.object);
477
if (objectValue !== null) {
478
if (
479
- objectValue.kind === "Primitive" &&
480
- typeof objectValue.value === "string" &&
481
- value.property === "length"
479
+ objectValue.kind === 'Primitive' &&
480
+ typeof objectValue.value === 'string' &&
481
+ value.property === 'length'
482
) {
483
const result: InstructionValue = {
484
- kind: "Primitive",
484
+ kind: 'Primitive',
485
value: objectValue.value.length,
486
loc: value.loc,
487
};
@@ -491,22 +491,22 @@ function evaluateInstruction(
491
}
492
return null;
493
}
494
- case "LoadLocal": {
494
+ case 'LoadLocal': {
495
const placeValue = read(constants, value.place);
496
if (placeValue !== null) {
497
instr.value = placeValue;
498
}
499
return placeValue;
500
}
501
- case "StoreLocal": {
501
+ case 'StoreLocal': {
502
const placeValue = read(constants, value.value);
503
if (placeValue !== null) {
504
constants.set(value.lvalue.place.identifier.id, placeValue);
505
}
506
return placeValue;
507
}
508
- case "ObjectMethod":
509
- case "FunctionExpression": {
508
+ case 'ObjectMethod':
509
+ case 'FunctionExpression': {
510
constantPropagationImpl(value.loweredFunc.func, constants);
511
return null;
512
}
compiler/packages/babel-plugin-react-compiler/src/Optimization/DeadCodeElimination.ts
+63
-63
@@ -15,13 +15,13 @@ import {
15
InstructionKind,
16
InstructionValue,
17
ObjectPattern,
18
-} from "../HIR";
18
+} from '../HIR';
19
import {
20
eachInstructionValueOperand,
21
eachPatternOperand,
22
eachTerminalOperand,
23
-} from "../HIR/visitors";
24
-import { assertExhaustive, retainWhere } from "../Utils/utils";
23
+} from '../HIR/visitors';
24
+import {assertExhaustive, retainWhere} from '../Utils/utils';
25
26
/*
27
* Implements dead-code elimination, eliminating instructions whose values are unused.
@@ -46,13 +46,13 @@ export function deadCodeElimination(fn: HIRFunction): void {
46
block.phis.delete(phi);
47
}
48
}
49
- retainWhere(block.instructions, (instr) =>
50
- state.isIdOrNameUsed(instr.lvalue.identifier)
49
+ retainWhere(block.instructions, instr =>
50
+ state.isIdOrNameUsed(instr.lvalue.identifier),
51
);
52
// Rewrite retained instructions
53
for (let i = 0; i < block.instructions.length; i++) {
54
const isBlockValue =
55
- block.kind !== "block" && i === block.instructions.length - 1;
55
+ block.kind !== 'block' && i === block.instructions.length - 1;
56
if (!isBlockValue) {
57
rewriteInstruction(block.instructions[i], state);
58
}
@@ -122,7 +122,7 @@ function findReferencedIdentifiers(fn: HIRFunction): State {
122
for (let i = block.instructions.length - 1; i >= 0; i--) {
123
const instr = block.instructions[i]!;
124
const isBlockValue =
125
- block.kind !== "block" && i === block.instructions.length - 1;
125
+ block.kind !== 'block' && i === block.instructions.length - 1;
126
127
if (isBlockValue) {
128
/**
@@ -140,7 +140,7 @@ function findReferencedIdentifiers(fn: HIRFunction): State {
140
) {
141
state.reference(instr.lvalue.identifier);
142
143
- if (instr.value.kind === "StoreLocal") {
143
+ if (instr.value.kind === 'StoreLocal') {
144
/*
145
* If this is a Let/Const declaration, mark the initializer as referenced
146
* only if the ssa'ed lval is also referenced
@@ -171,25 +171,25 @@ function findReferencedIdentifiers(fn: HIRFunction): State {
171
}
172
173
function rewriteInstruction(instr: Instruction, state: State): void {
174
- if (instr.value.kind === "Destructure") {
174
+ if (instr.value.kind === 'Destructure') {
175
// Remove unused lvalues
176
switch (instr.value.lvalue.pattern.kind) {
177
- case "ArrayPattern": {
177
+ case 'ArrayPattern': {
178
/*
179
* For arrays, we can only eliminate unused items from the end of the array,
180
* so we iterate from the end and break once we find a used item. Note that
181
* we already know at least one item is used, from the pruneableValue check.
182
*/
183
- let nextItems: ArrayPattern["items"] | null = null;
183
+ let nextItems: ArrayPattern['items'] | null = null;
184
const originalItems = instr.value.lvalue.pattern.items;
185
for (let i = originalItems.length - 1; i >= 0; i--) {
186
const item = originalItems[i];
187
- if (item.kind === "Identifier") {
187
+ if (item.kind === 'Identifier') {
188
if (state.isIdOrNameUsed(item.identifier)) {
189
nextItems = originalItems.slice(0, i + 1);
190
break;
191
}
192
- } else if (item.kind === "Spread") {
192
+ } else if (item.kind === 'Spread') {
193
if (state.isIdOrNameUsed(item.place.identifier)) {
194
nextItems = originalItems.slice(0, i + 1);
195
break;
@@ -201,7 +201,7 @@ function rewriteInstruction(instr: Instruction, state: State): void {
201
}
202
break;
203
}
204
- case "ObjectPattern": {
204
+ case 'ObjectPattern': {
205
/*
206
* For objects we can prune any unused properties so long as there is no used rest element
207
* (`const {x, ...y} = z`). If a rest element exists and is used, then nothing can be pruned
@@ -209,9 +209,9 @@ function rewriteInstruction(instr: Instruction, state: State): void {
209
* In the `const {x, ...y} = z` example, removing the `x` property would mean that `y` now
210
* has an `x` property, changing the semantics.
211
*/
212
- let nextProperties: ObjectPattern["properties"] | null = null;
212
+ let nextProperties: ObjectPattern['properties'] | null = null;
213
for (const property of instr.value.lvalue.pattern.properties) {
214
- if (property.kind === "ObjectProperty") {
214
+ if (property.kind === 'ObjectProperty') {
215
if (state.isIdOrNameUsed(property.place.identifier)) {
216
nextProperties ??= [];
217
nextProperties.push(property);
@@ -233,11 +233,11 @@ function rewriteInstruction(instr: Instruction, state: State): void {
233
instr.value.lvalue.pattern,
234
`Unexpected pattern kind '${
235
(instr.value.lvalue.pattern as any).kind
236
- }'`
236
+ }'`,
237
);
238
}
239
}
240
- } else if (instr.value.kind === "StoreLocal") {
240
+ } else if (instr.value.kind === 'StoreLocal') {
241
if (
242
instr.value.lvalue.kind !== InstructionKind.Reassign &&
243
!state.isIdUsed(instr.value.lvalue.place.identifier)
@@ -249,7 +249,7 @@ function rewriteInstruction(instr: Instruction, state: State): void {
249
* that the initializer value can be DCE'd
250
*/
251
instr.value = {
252
- kind: "DeclareLocal",
252
+ kind: 'DeclareLocal',
253
lvalue: instr.value.lvalue,
254
type: instr.value.type,
255
loc: instr.value.loc,
@@ -264,11 +264,11 @@ function rewriteInstruction(instr: Instruction, state: State): void {
264
*/
265
function pruneableValue(value: InstructionValue, state: State): boolean {
266
switch (value.kind) {
267
- case "DeclareLocal": {
267
+ case 'DeclareLocal': {
268
// Declarations are pruneable only if the named variable is never read later
269
return !state.isIdOrNameUsed(value.lvalue.place.identifier);
270
}
271
- case "StoreLocal": {
271
+ case 'StoreLocal': {
272
if (value.lvalue.kind === InstructionKind.Reassign) {
273
// Reassignments can be pruned if the specific instance being assigned is never read
274
return !state.isIdUsed(value.lvalue.place.identifier);
@@ -276,7 +276,7 @@ function pruneableValue(value: InstructionValue, state: State): boolean {
276
// Declarations are pruneable only if the named variable is never read later
277
return !state.isIdOrNameUsed(value.lvalue.place.identifier);
278
}
279
- case "Destructure": {
279
+ case 'Destructure': {
280
let isIdOrNameUsed = false;
281
let isIdUsed = false;
282
for (const place of eachPatternOperand(value.lvalue.pattern)) {
@@ -295,23 +295,23 @@ function pruneableValue(value: InstructionValue, state: State): boolean {
295
return !isIdOrNameUsed;
296
}
297
}
298
- case "PostfixUpdate":
299
- case "PrefixUpdate": {
298
+ case 'PostfixUpdate':
299
+ case 'PrefixUpdate': {
300
// Updates are pruneable if the specific instance instance being assigned is never read
301
return !state.isIdUsed(value.lvalue.identifier);
302
}
303
- case "Debugger": {
303
+ case 'Debugger': {
304
// explicitly retain debugger statements to not break debugging workflows
305
return false;
306
}
307
- case "Await":
308
- case "CallExpression":
309
- case "ComputedDelete":
310
- case "ComputedStore":
311
- case "PropertyDelete":
312
- case "MethodCall":
313
- case "PropertyStore":
314
- case "StoreGlobal": {
307
+ case 'Await':
308
+ case 'CallExpression':
309
+ case 'ComputedDelete':
310
+ case 'ComputedStore':
311
+ case 'PropertyDelete':
312
+ case 'MethodCall':
313
+ case 'PropertyStore':
314
+ case 'StoreGlobal': {
315
/*
316
* Mutating instructions are not safe to prune.
317
* TODO: we could be more precise and make this conditional on whether
@@ -319,15 +319,15 @@ function pruneableValue(value: InstructionValue, state: State): boolean {
319
*/
320
return false;
321
}
322
- case "NewExpression":
323
- case "UnsupportedNode":
324
- case "TaggedTemplateExpression": {
322
+ case 'NewExpression':
323
+ case 'UnsupportedNode':
324
+ case 'TaggedTemplateExpression': {
325
// Potentially safe to prune, since they should just be creating new values
326
return false;
327
}
328
- case "GetIterator":
329
- case "NextPropertyOf":
330
- case "IteratorNext": {
328
+ case 'GetIterator':
329
+ case 'NextPropertyOf':
330
+ case 'IteratorNext': {
331
/*
332
* Technically a IteratorNext/NextPropertyOf will never be unused because it's
333
* always used later by another StoreLocal or Destructure instruction, but conceptually
@@ -335,13 +335,13 @@ function pruneableValue(value: InstructionValue, state: State): boolean {
335
*/
336
return false;
337
}
338
- case "LoadContext":
339
- case "DeclareContext":
340
- case "StoreContext": {
338
+ case 'LoadContext':
339
+ case 'DeclareContext':
340
+ case 'StoreContext': {
341
return false;
342
}
343
- case "StartMemoize":
344
- case "FinishMemoize": {
343
+ case 'StartMemoize':
344
+ case 'FinishMemoize': {
345
/**
346
* This instruction is used by the @enablePreserveExistingMemoizationGuarantees feature
347
* to preserve information about memoization semantics in the original code. We can't
@@ -349,31 +349,31 @@ function pruneableValue(value: InstructionValue, state: State): boolean {
349
*/
350
return false;
351
}
352
- case "RegExpLiteral":
353
- case "MetaProperty":
354
- case "LoadGlobal":
355
- case "ArrayExpression":
356
- case "BinaryExpression":
357
- case "ComputedLoad":
358
- case "ObjectMethod":
359
- case "FunctionExpression":
360
- case "LoadLocal":
361
- case "JsxExpression":
362
- case "JsxFragment":
363
- case "JSXText":
364
- case "ObjectExpression":
365
- case "Primitive":
366
- case "PropertyLoad":
367
- case "TemplateLiteral":
368
- case "TypeCastExpression":
369
- case "UnaryExpression": {
352
+ case 'RegExpLiteral':
353
+ case 'MetaProperty':
354
+ case 'LoadGlobal':
355
+ case 'ArrayExpression':
356
+ case 'BinaryExpression':
357
+ case 'ComputedLoad':
358
+ case 'ObjectMethod':
359
+ case 'FunctionExpression':
360
+ case 'LoadLocal':
361
+ case 'JsxExpression':
362
+ case 'JsxFragment':
363
+ case 'JSXText':
364
+ case 'ObjectExpression':
365
+ case 'Primitive':
366
+ case 'PropertyLoad':
367
+ case 'TemplateLiteral':
368
+ case 'TypeCastExpression':
369
+ case 'UnaryExpression': {
370
// Definitely safe to prune since they are read-only
371
return true;
372
}
373
default: {
374
assertExhaustive(
375
value,
376
- `Unexepcted value kind \`${(value as any).kind}\``
376
+ `Unexepcted value kind \`${(value as any).kind}\``,
377
);
378
}
379
}
compiler/packages/babel-plugin-react-compiler/src/Optimization/InstructionReordering.ts
+43
-43
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "..";
8
+import {CompilerError} from '..';
9
import {
10
BasicBlock,
11
Environment,
@@ -18,15 +18,15 @@ import {
18
isExpressionBlockKind,
19
makeInstructionId,
20
markInstructionIds,
21
-} from "../HIR";
22
-import { printInstruction } from "../HIR/PrintHIR";
21
+} from '../HIR';
22
+import {printInstruction} from '../HIR/PrintHIR';
23
import {
24
eachInstructionLValue,
25
eachInstructionValueLValue,
26
eachInstructionValueOperand,
27
eachTerminalOperand,
28
-} from "../HIR/visitors";
29
-import { getOrInsertWith } from "../Utils/utils";
28
+} from '../HIR/visitors';
29
+import {getOrInsertWith} from '../Utils/utils';
30
31
/**
32
* This pass implements conservative instruction reordering to move instructions closer to
@@ -80,8 +80,8 @@ export function instructionReordering(fn: HIRFunction): void {
80
reason: `InstructionReordering: expected all reorderable nodes to have been emitted`,
81
loc:
82
[...shared.values()]
83
- .map((node) => node.instruction?.loc)
84
- .filter((loc) => loc != null)[0] ?? GeneratedSource,
83
+ .map(node => node.instruction?.loc)
84
+ .filter(loc => loc != null)[0] ?? GeneratedSource,
85
});
86
markInstructionIds(fn.body);
87
}
@@ -113,11 +113,11 @@ function findReferencedRangeOfTemporaries(fn: HIRFunction): References {
113
function reference(
114
instr: InstructionId,
115
place: Place,
116
- kind: ReferenceKind
116
+ kind: ReferenceKind,
117
): void {
118
if (
119
place.identifier.name !== null &&
120
- place.identifier.name.kind === "named"
120
+ place.identifier.name.kind === 'named'
121
) {
122
if (kind === ReferenceKind.Write) {
123
const name = place.identifier.name.value;
@@ -127,7 +127,7 @@ function findReferencedRangeOfTemporaries(fn: HIRFunction): References {
127
} else {
128
lastAssignments.set(
129
name,
130
- makeInstructionId(Math.max(previous, instr))
130
+ makeInstructionId(Math.max(previous, instr)),
131
);
132
}
133
}
@@ -154,7 +154,7 @@ function findReferencedRangeOfTemporaries(fn: HIRFunction): References {
154
singleUseIdentifiers: new Set(
155
[...singleUseIdentifiers]
156
.filter(([, count]) => count === 1)
157
- .map(([id]) => id)
157
+ .map(([id]) => id),
158
),
159
lastAssignments,
160
};
@@ -164,13 +164,13 @@ function reorderBlock(
164
env: Environment,
165
block: BasicBlock,
166
shared: Nodes,
167
- references: References
167
+ references: References,
168
): void {
169
const locals: Nodes = new Map();
170
const named: Map<string, IdentifierId> = new Map();
171
let previous: IdentifierId | null = null;
172
for (const instr of block.instructions) {
173
- const { lvalue, value } = instr;
173
+ const {lvalue, value} = instr;
174
// Get or create a node for this lvalue
175
const reorderability = getReorderability(instr, references);
176
const node = getOrInsertWith(
@@ -182,7 +182,7 @@ function reorderBlock(
182
dependencies: new Set(),
183
reorderability,
184
depth: null,
185
- }) as Node
185
+ }) as Node,
186
);
187
/**
188
* Ensure non-reoderable instructions have their order retained by
@@ -198,8 +198,8 @@ function reorderBlock(
198
* Establish dependencies on operands
199
*/
200
for (const operand of eachInstructionValueOperand(value)) {
201
- const { name, id } = operand.identifier;
202
- if (name !== null && name.kind === "named") {
201
+ const {name, id} = operand.identifier;
202
+ if (name !== null && name.kind === 'named') {
203
// Serialize all accesses to named variables
204
const previous = named.get(name.value);
205
if (previous !== undefined) {
@@ -225,11 +225,11 @@ function reorderBlock(
225
instruction: null,
226
dependencies: new Set(),
227
depth: null,
228
- }) as Node
228
+ }) as Node,
229
);
230
lvalueNode.dependencies.add(lvalue.identifier.id);
231
const name = lvalueOperand.identifier.name;
232
- if (name !== null && name.kind === "named") {
232
+ if (name !== null && name.kind === 'named') {
233
const previous = named.get(name.value);
234
if (previous !== undefined) {
235
node.dependencies.add(previous);
@@ -272,14 +272,14 @@ function reorderBlock(
272
locals,
273
shared,
274
seen,
275
- block.instructions.at(-1)!.lvalue.identifier.id
275
+ block.instructions.at(-1)!.lvalue.identifier.id,
276
);
277
emit(
278
env,
279
locals,
280
shared,
281
nextInstructions,
282
- block.instructions.at(-1)!.lvalue.identifier.id
282
+ block.instructions.at(-1)!.lvalue.identifier.id,
283
);
284
}
285
/*
@@ -307,7 +307,7 @@ function reorderBlock(
307
node.instruction != null
308
? `Instruction [${node.instruction.id}] was not emitted yet but is not reorderable`
309
: `Lvalue $${id} was not emitted yet but is not reorderable`,
310
- }
310
+ },
311
);
312
313
DEBUG && console.log(`save shared: $${id}`);
@@ -358,7 +358,7 @@ function reorderBlock(
358
DEBUG && console.log(`save shared: $${id}`);
359
shared.set(id, node);
360
} else {
361
- DEBUG && console.log("leftover");
361
+ DEBUG && console.log('leftover');
362
DEBUG && print(env, locals, shared, seen, id);
363
emit(env, locals, shared, nextInstructions, id);
364
}
@@ -392,10 +392,10 @@ function print(
392
shared: Nodes,
393
seen: Set<IdentifierId>,
394
id: IdentifierId,
395
- depth: number = 0
395
+ depth: number = 0,
396
): void {
397
if (seen.has(id)) {
398
- DEBUG && console.log(`${"| ".repeat(depth)}$${id} <skipped>`);
398
+ DEBUG && console.log(`${'| '.repeat(depth)}$${id} <skipped>`);
399
return;
400
}
401
seen.add(id);
@@ -414,20 +414,20 @@ function print(
414
}
415
DEBUG &&
416
console.log(
417
- `${"| ".repeat(depth)}$${id} ${printNode(node)} deps=[${deps
418
- .map((x) => `$${x}`)
419
- .join(", ")}] depth=${node.depth}`
417
+ `${'| '.repeat(depth)}$${id} ${printNode(node)} deps=[${deps
418
+ .map(x => `$${x}`)
419
+ .join(', ')}] depth=${node.depth}`,
420
);
421
}
422
423
function printNode(node: Node): string {
424
- const { instruction } = node;
424
+ const {instruction} = node;
425
if (instruction === null) {
426
- return "<lvalue-only>";
426
+ return '<lvalue-only>';
427
}
428
switch (instruction.value.kind) {
429
- case "FunctionExpression":
430
- case "ObjectMethod": {
429
+ case 'FunctionExpression':
430
+ case 'ObjectMethod': {
431
return `[${instruction.id}] ${instruction.value.kind}`;
432
}
433
default: {
@@ -441,7 +441,7 @@ function emit(
441
locals: Nodes,
442
shared: Nodes,
443
instructions: Array<Instruction>,
444
- id: IdentifierId
444
+ id: IdentifierId,
445
): void {
446
const node = locals.get(id) ?? shared.get(id);
447
if (node == null) {
@@ -469,22 +469,22 @@ enum Reorderability {
469
}
470
function getReorderability(
471
instr: Instruction,
472
- references: References
472
+ references: References,
473
): Reorderability {
474
switch (instr.value.kind) {
475
- case "JsxExpression":
476
- case "JsxFragment":
477
- case "JSXText":
478
- case "LoadGlobal":
479
- case "Primitive":
480
- case "TemplateLiteral":
481
- case "BinaryExpression":
482
- case "UnaryExpression": {
475
+ case 'JsxExpression':
476
+ case 'JsxFragment':
477
+ case 'JSXText':
478
+ case 'LoadGlobal':
479
+ case 'Primitive':
480
+ case 'TemplateLiteral':
481
+ case 'BinaryExpression':
482
+ case 'UnaryExpression': {
483
return Reorderability.Reorderable;
484
}
485
- case "LoadLocal": {
485
+ case 'LoadLocal': {
486
const name = instr.value.place.identifier.name;
487
- if (name !== null && name.kind === "named") {
487
+ if (name !== null && name.kind === 'named') {
488
const lastAssignment = references.lastAssignments.get(name.value);
489
if (
490
lastAssignment !== undefined &&
compiler/packages/babel-plugin-react-compiler/src/Optimization/OutlineFunctions.ts
+7
-7
@@ -5,23 +5,23 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { HIRFunction } from "../HIR";
8
+import {HIRFunction} from '../HIR';
9
10
export function outlineFunctions(fn: HIRFunction): void {
11
for (const [, block] of fn.body.blocks) {
12
for (const instr of block.instructions) {
13
- const { value } = instr;
13
+ const {value} = instr;
14
15
if (
16
- value.kind === "FunctionExpression" ||
17
- value.kind === "ObjectMethod"
16
+ value.kind === 'FunctionExpression' ||
17
+ value.kind === 'ObjectMethod'
18
) {
19
// Recurse in case there are inner functions which can be outlined
20
outlineFunctions(value.loweredFunc.func);
21
}
22
23
if (
24
- value.kind === "FunctionExpression" &&
24
+ value.kind === 'FunctionExpression' &&
25
value.loweredFunc.dependencies.length === 0 &&
26
value.loweredFunc.func.context.length === 0 &&
27
// TODO: handle outlining named functions
@@ -34,9 +34,9 @@ export function outlineFunctions(fn: HIRFunction): void {
34
35
fn.env.outlineFunction(loweredFunc, null);
36
instr.value = {
37
- kind: "LoadGlobal",
37
+ kind: 'LoadGlobal',
38
binding: {
39
- kind: "Global",
39
+ kind: 'Global',
40
name: id.value,
41
},
42
loc: value.loc,
compiler/packages/babel-plugin-react-compiler/src/Optimization/PruneMaybeThrows.ts
+11
-11
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "..";
8
+import {CompilerError} from '..';
9
import {
10
BlockId,
11
GeneratedSource,
@@ -16,14 +16,14 @@ import {
16
assertTerminalSuccessorsExist,
17
mergeConsecutiveBlocks,
18
reversePostorderBlocks,
19
-} from "../HIR";
19
+} from '../HIR';
20
import {
21
markInstructionIds,
22
removeDeadDoWhileStatements,
23
removeUnnecessaryTryCatch,
24
removeUnreachableForUpdates,
25
-} from "../HIR/HIRBuilder";
26
-import { printIdentifier } from "../HIR/PrintHIR";
25
+} from '../HIR/HIRBuilder';
26
+import {printIdentifier} from '../HIR/PrintHIR';
27
28
/*
29
* This pass prunes `maybe-throw` terminals for blocks that can provably *never* throw.
@@ -74,17 +74,17 @@ function pruneMaybeThrowsImpl(fn: HIRFunction): Map<BlockId, BlockId> | null {
74
const terminalMapping = new Map<BlockId, BlockId>();
75
for (const [_, block] of fn.body.blocks) {
76
const terminal = block.terminal;
77
- if (terminal.kind !== "maybe-throw") {
77
+ if (terminal.kind !== 'maybe-throw') {
78
continue;
79
}
80
- const canThrow = block.instructions.some((instr) =>
81
- instructionMayThrow(instr)
80
+ const canThrow = block.instructions.some(instr =>
81
+ instructionMayThrow(instr),
82
);
83
if (!canThrow) {
84
const source = terminalMapping.get(block.id) ?? block.id;
85
terminalMapping.set(terminal.continuation, source);
86
block.terminal = {
87
- kind: "goto",
87
+ kind: 'goto',
88
block: terminal.continuation,
89
variant: GotoVariant.Break,
90
id: terminal.id,
@@ -97,9 +97,9 @@ function pruneMaybeThrowsImpl(fn: HIRFunction): Map<BlockId, BlockId> | null {
97
98
function instructionMayThrow(instr: Instruction): boolean {
99
switch (instr.value.kind) {
100
- case "Primitive":
101
- case "ArrayExpression":
102
- case "ObjectExpression": {
100
+ case 'Primitive':
101
+ case 'ArrayExpression':
102
+ case 'ObjectExpression': {
103
return false;
104
}
105
default: {
compiler/packages/babel-plugin-react-compiler/src/Optimization/index.ts
+3
-3
@@ -5,6 +5,6 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-export { constantPropagation } from "./ConstantPropagation";
9
-export { deadCodeElimination } from "./DeadCodeElimination";
10
-export { pruneMaybeThrows } from "./PruneMaybeThrows";
8
+export {constantPropagation} from './ConstantPropagation';
9
+export {deadCodeElimination} from './DeadCodeElimination';
10
+export {pruneMaybeThrows} from './PruneMaybeThrows';
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/AlignMethodCallScopes.ts
+8
-8
@@ -10,8 +10,8 @@ import {
10
IdentifierId,
11
ReactiveScope,
12
makeInstructionId,
13
-} from "../HIR";
14
-import DisjointSet from "../Utils/DisjointSet";
13
+} from '../HIR';
14
+import DisjointSet from '../Utils/DisjointSet';
15
16
/**
17
* Ensures that method call instructions have scopes such that either:
@@ -24,8 +24,8 @@ export function alignMethodCallScopes(fn: HIRFunction): void {
24
25
for (const [, block] of fn.body.blocks) {
26
for (const instr of block.instructions) {
27
- const { lvalue, value } = instr;
28
- if (value.kind === "MethodCall") {
27
+ const {lvalue, value} = instr;
28
+ if (value.kind === 'MethodCall') {
29
const lvalueScope = lvalue.identifier.scope;
30
const propertyScope = value.property.identifier.scope;
31
if (lvalueScope !== null) {
@@ -44,8 +44,8 @@ export function alignMethodCallScopes(fn: HIRFunction): void {
44
scopeMapping.set(value.property.identifier.id, null);
45
}
46
} else if (
47
- value.kind === "FunctionExpression" ||
48
- value.kind === "ObjectMethod"
47
+ value.kind === 'FunctionExpression' ||
48
+ value.kind === 'ObjectMethod'
49
) {
50
alignMethodCallScopes(value.loweredFunc.func);
51
}
@@ -57,10 +57,10 @@ export function alignMethodCallScopes(fn: HIRFunction): void {
57
return;
58
}
59
root.range.start = makeInstructionId(
60
- Math.min(scope.range.start, root.range.start)
60
+ Math.min(scope.range.start, root.range.start),
61
);
62
root.range.end = makeInstructionId(
63
- Math.max(scope.range.end, root.range.end)
63
+ Math.max(scope.range.end, root.range.end),
64
);
65
});
66
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/AlignObjectMethodScopes.ts
+15
-15
@@ -5,16 +5,16 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "..";
8
+import {CompilerError} from '..';
9
import {
10
GeneratedSource,
11
HIRFunction,
12
Identifier,
13
ReactiveScope,
14
makeInstructionId,
15
-} from "../HIR";
16
-import { eachInstructionValueOperand } from "../HIR/visitors";
17
-import DisjointSet from "../Utils/DisjointSet";
15
+} from '../HIR';
16
+import {eachInstructionValueOperand} from '../HIR/visitors';
17
+import DisjointSet from '../Utils/DisjointSet';
18
19
/**
20
* Align scopes of object method values to that of their enclosing object expressions.
@@ -27,10 +27,10 @@ function findScopesToMerge(fn: HIRFunction): DisjointSet<ReactiveScope> {
27
const mergeScopesBuilder = new DisjointSet<ReactiveScope>();
28
29
for (const [_, block] of fn.body.blocks) {
30
- for (const { lvalue, value } of block.instructions) {
31
- if (value.kind === "ObjectMethod") {
30
+ for (const {lvalue, value} of block.instructions) {
31
+ if (value.kind === 'ObjectMethod') {
32
objectMethodDecls.add(lvalue.identifier);
33
- } else if (value.kind === "ObjectExpression") {
33
+ } else if (value.kind === 'ObjectExpression') {
34
for (const operand of eachInstructionValueOperand(value)) {
35
if (objectMethodDecls.has(operand.identifier)) {
36
const operandScope = operand.identifier.scope;
@@ -40,10 +40,10 @@ function findScopesToMerge(fn: HIRFunction): DisjointSet<ReactiveScope> {
40
operandScope != null && lvalueScope != null,
41
{
42
reason:
43
- "Internal error: Expected all ObjectExpressions and ObjectMethods to have non-null scope.",
43
+ 'Internal error: Expected all ObjectExpressions and ObjectMethods to have non-null scope.',
44
suggestions: null,
45
loc: GeneratedSource,
46
- }
46
+ },
47
);
48
mergeScopesBuilder.union([operandScope, lvalueScope]);
49
}
@@ -57,10 +57,10 @@ function findScopesToMerge(fn: HIRFunction): DisjointSet<ReactiveScope> {
57
export function alignObjectMethodScopes(fn: HIRFunction): void {
58
// Handle inner functions: we assume that Scopes are disjoint across functions
59
for (const [_, block] of fn.body.blocks) {
60
- for (const { value } of block.instructions) {
60
+ for (const {value} of block.instructions) {
61
if (
62
- value.kind === "ObjectMethod" ||
63
- value.kind === "FunctionExpression"
62
+ value.kind === 'ObjectMethod' ||
63
+ value.kind === 'FunctionExpression'
64
) {
65
alignObjectMethodScopes(value.loweredFunc.func);
66
}
@@ -74,10 +74,10 @@ export function alignObjectMethodScopes(fn: HIRFunction): void {
74
for (const [scope, root] of scopeGroupsMap) {
75
if (scope !== root) {
76
root.range.start = makeInstructionId(
77
- Math.min(scope.range.start, root.range.start)
77
+ Math.min(scope.range.start, root.range.start),
78
);
79
root.range.end = makeInstructionId(
80
- Math.max(scope.range.end, root.range.end)
80
+ Math.max(scope.range.end, root.range.end),
81
);
82
}
83
}
@@ -87,7 +87,7 @@ export function alignObjectMethodScopes(fn: HIRFunction): void {
87
*/
88
for (const [_, block] of fn.body.blocks) {
89
for (const {
90
- lvalue: { identifier },
90
+ lvalue: {identifier},
91
} of block.instructions) {
92
if (identifier.scope != null) {
93
const root = scopeGroupsMap.get(identifier.scope);
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/AlignReactiveScopesToBlockScopes.ts
+9
-9
@@ -14,9 +14,9 @@ import {
14
ReactiveScope,
15
ScopeId,
16
makeInstructionId,
17
-} from "../HIR/HIR";
18
-import { getPlaceScope } from "./BuildReactiveBlocks";
19
-import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors";
17
+} from '../HIR/HIR';
18
+import {getPlaceScope} from './BuildReactiveBlocks';
19
+import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
20
21
/*
22
* Note: this is the 2nd of 4 passes that determine how to break a function into discrete
@@ -84,10 +84,10 @@ class Visitor extends ReactiveFunctionVisitor<Context> {
84
85
override visitInstruction(instr: ReactiveInstruction, state: Context): void {
86
switch (instr.value.kind) {
87
- case "OptionalExpression":
88
- case "SequenceExpression":
89
- case "ConditionalExpression":
90
- case "LogicalExpression": {
87
+ case 'OptionalExpression':
88
+ case 'SequenceExpression':
89
+ case 'ConditionalExpression':
90
+ case 'LogicalExpression': {
91
const prevScopeCount = state.currentScopes().length;
92
this.traverseInstruction(instr, state);
93
@@ -105,7 +105,7 @@ class Visitor extends ReactiveFunctionVisitor<Context> {
105
for (let i = prevScopeCount; i < scopes.length; i++) {
106
const scope = scopes[i];
107
scope.scope.range.start = makeInstructionId(
108
- Math.min(instr.id, scope.scope.range.start)
108
+ Math.min(instr.id, scope.scope.range.start),
109
);
110
}
111
break;
@@ -123,7 +123,7 @@ class Visitor extends ReactiveFunctionVisitor<Context> {
123
}
124
}
125
126
-type PendingReactiveScope = { active: boolean; scope: ReactiveScope };
126
+type PendingReactiveScope = {active: boolean; scope: ReactiveScope};
127
128
class Context {
129
/*
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/AlignReactiveScopesToBlockScopesHIR.ts
+27
-27
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "..";
8
+import {CompilerError} from '..';
9
import {
10
BlockId,
11
HIRFunction,
@@ -14,16 +14,16 @@ import {
14
Place,
15
ReactiveScope,
16
makeInstructionId,
17
-} from "../HIR/HIR";
17
+} from '../HIR/HIR';
18
import {
19
eachInstructionLValue,
20
eachInstructionValueOperand,
21
eachTerminalOperand,
22
mapTerminalSuccessors,
23
terminalFallthrough,
24
-} from "../HIR/visitors";
25
-import { retainWhere_Set } from "../Utils/utils";
26
-import { getPlaceScope } from "./BuildReactiveBlocks";
24
+} from '../HIR/visitors';
25
+import {retainWhere_Set} from '../Utils/utils';
26
+import {getPlaceScope} from './BuildReactiveBlocks';
27
28
type InstructionRange = MutableRange;
29
/*
@@ -80,7 +80,7 @@ export function alignReactiveScopesToBlockScopesHIR(fn: HIRFunction): void {
80
function recordPlace(
81
id: InstructionId,
82
place: Place,
83
- node: ValueBlockNode | null
83
+ node: ValueBlockNode | null,
84
): void {
85
if (place.identifier.scope !== null) {
86
placeScopes.set(place, place.identifier.scope);
@@ -91,7 +91,7 @@ export function alignReactiveScopesToBlockScopesHIR(fn: HIRFunction): void {
91
return;
92
}
93
activeScopes.add(scope);
94
- node?.children.push({ kind: "scope", scope, id });
94
+ node?.children.push({kind: 'scope', scope, id});
95
96
if (seen.has(scope)) {
97
return;
@@ -99,17 +99,17 @@ export function alignReactiveScopesToBlockScopesHIR(fn: HIRFunction): void {
99
seen.add(scope);
100
if (node != null && node.valueRange !== null) {
101
scope.range.start = makeInstructionId(
102
- Math.min(node.valueRange.start, scope.range.start)
102
+ Math.min(node.valueRange.start, scope.range.start),
103
);
104
scope.range.end = makeInstructionId(
105
- Math.max(node.valueRange.end, scope.range.end)
105
+ Math.max(node.valueRange.end, scope.range.end),
106
);
107
}
108
}
109
110
for (const [, block] of fn.body.blocks) {
111
const startingId = block.instructions[0]?.id ?? block.terminal.id;
112
- retainWhere_Set(activeScopes, (scope) => scope.range.end > startingId);
112
+ retainWhere_Set(activeScopes, scope => scope.range.end > startingId);
113
const top = activeBlockFallthroughRanges.at(-1);
114
if (top?.fallthrough === block.id) {
115
activeBlockFallthroughRanges.pop();
@@ -120,12 +120,12 @@ export function alignReactiveScopesToBlockScopesHIR(fn: HIRFunction): void {
120
*/
121
for (const scope of activeScopes) {
122
scope.range.start = makeInstructionId(
123
- Math.min(scope.range.start, top.range.start)
123
+ Math.min(scope.range.start, top.range.start),
124
);
125
}
126
}
127
128
- const { instructions, terminal } = block;
128
+ const {instructions, terminal} = block;
129
const node = valueBlockNodes.get(block.id) ?? null;
130
for (const instr of instructions) {
131
for (const lvalue of eachInstructionLValue(instr)) {
@@ -152,7 +152,7 @@ export function alignReactiveScopesToBlockScopesHIR(fn: HIRFunction): void {
152
for (const scope of activeScopes) {
153
if (scope.range.end > terminal.id) {
154
scope.range.end = makeInstructionId(
155
- Math.max(scope.range.end, nextId)
155
+ Math.max(scope.range.end, nextId),
156
);
157
}
158
}
@@ -169,7 +169,7 @@ export function alignReactiveScopesToBlockScopesHIR(fn: HIRFunction): void {
169
});
170
171
CompilerError.invariant(!valueBlockNodes.has(fallthrough), {
172
- reason: "Expect hir blocks to have unique fallthroughs",
172
+ reason: 'Expect hir blocks to have unique fallthroughs',
173
loc: terminal.loc,
174
});
175
if (node != null) {
@@ -185,22 +185,22 @@ export function alignReactiveScopesToBlockScopesHIR(fn: HIRFunction): void {
185
* TODO: add a variant of eachTerminalSuccessor() that visits _all_ successors, not
186
* just those that are direct successors for normal control-flow ordering.
187
*/
188
- mapTerminalSuccessors(terminal, (successor) => {
188
+ mapTerminalSuccessors(terminal, successor => {
189
if (valueBlockNodes.has(successor)) {
190
return successor;
191
}
192
193
const successorBlock = fn.body.blocks.get(successor)!;
194
- if (successorBlock.kind === "block" || successorBlock.kind === "catch") {
194
+ if (successorBlock.kind === 'block' || successorBlock.kind === 'catch') {
195
/*
196
* we need the block kind check here because the do..while terminal's
197
* successor is a block, and try's successor is a catch block
198
*/
199
} else if (
200
node == null ||
201
- terminal.kind === "ternary" ||
202
- terminal.kind === "logical" ||
203
- terminal.kind === "optional"
201
+ terminal.kind === 'ternary' ||
202
+ terminal.kind === 'logical' ||
203
+ terminal.kind === 'optional'
204
) {
205
/**
206
* Create a new node whenever we transition from non-value -> value block.
@@ -232,7 +232,7 @@ export function alignReactiveScopesToBlockScopesHIR(fn: HIRFunction): void {
232
valueRange = node.valueRange;
233
}
234
const childNode: ValueBlockNode = {
235
- kind: "node",
235
+ kind: 'node',
236
id: terminal.id,
237
children: [],
238
valueRange,
@@ -249,13 +249,13 @@ export function alignReactiveScopesToBlockScopesHIR(fn: HIRFunction): void {
249
}
250
251
type ValueBlockNode = {
252
- kind: "node";
252
+ kind: 'node';
253
id: InstructionId;
254
valueRange: MutableRange;
255
children: Array<ValueBlockNode | ReactiveScopeNode>;
256
};
257
type ReactiveScopeNode = {
258
- kind: "scope";
258
+ kind: 'scope';
259
id: InstructionId;
260
scope: ReactiveScope;
261
};
@@ -263,17 +263,17 @@ type ReactiveScopeNode = {
263
function _debug(node: ValueBlockNode): string {
264
const buf: Array<string> = [];
265
_printNode(node, buf, 0);
266
- return buf.join("\n");
266
+ return buf.join('\n');
267
}
268
function _printNode(
269
node: ValueBlockNode | ReactiveScopeNode,
270
out: Array<string>,
271
- depth: number = 0
271
+ depth: number = 0,
272
): void {
273
- let prefix = " ".repeat(depth);
274
- if (node.kind === "scope") {
273
+ let prefix = ' '.repeat(depth);
274
+ if (node.kind === 'scope') {
275
out.push(
276
- `${prefix}[${node.id}] @${node.scope.id} [${node.scope.range.start}:${node.scope.range.end}]`
276
+ `${prefix}[${node.id}] @${node.scope.id} [${node.scope.range.start}:${node.scope.range.end}]`,
277
);
278
} else {
279
let range = ` (range=[${node.valueRange.start}:${node.valueRange.end}])`;
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/AssertScopeInstructionsWithinScope.ts
+9
-9
@@ -5,17 +5,17 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { visitReactiveFunction } from ".";
9
-import { CompilerError } from "..";
8
+import {visitReactiveFunction} from '.';
9
+import {CompilerError} from '..';
10
import {
11
InstructionId,
12
Place,
13
ReactiveFunction,
14
ReactiveScopeBlock,
15
ScopeId,
16
-} from "../HIR";
17
-import { getPlaceScope } from "./BuildReactiveBlocks";
18
-import { ReactiveFunctionVisitor } from "./visitors";
16
+} from '../HIR';
17
+import {getPlaceScope} from './BuildReactiveBlocks';
18
+import {ReactiveFunctionVisitor} from './visitors';
19
20
/*
21
* Internal validation pass that checks all the instructions involved in creating
@@ -41,14 +41,14 @@ import { ReactiveFunctionVisitor } from "./visitors";
41
* against compiler coding mistakes in earlier passes.
42
*/
43
export function assertScopeInstructionsWithinScopes(
44
- fn: ReactiveFunction
44
+ fn: ReactiveFunction,
45
): void {
46
const existingScopes = new Set<ScopeId>();
47
visitReactiveFunction(fn, new FindAllScopesVisitor(), existingScopes);
48
visitReactiveFunction(
49
fn,
50
new CheckInstructionsAgainstScopesVisitor(),
51
- existingScopes
51
+ existingScopes,
52
);
53
}
54
@@ -67,7 +67,7 @@ class CheckInstructionsAgainstScopesVisitor extends ReactiveFunctionVisitor<
67
override visitPlace(
68
id: InstructionId,
69
place: Place,
70
- state: Set<ScopeId>
70
+ state: Set<ScopeId>,
71
): void {
72
const scope = getPlaceScope(id, place);
73
if (
@@ -84,7 +84,7 @@ class CheckInstructionsAgainstScopesVisitor extends ReactiveFunctionVisitor<
84
description: `Instruction [${id}] is part of scope @${scope.id}, but that scope has already completed.`,
85
loc: place.loc,
86
reason:
87
- "Encountered an instruction that should be part of a scope, but where that scope has already completed",
87
+ 'Encountered an instruction that should be part of a scope, but where that scope has already completed',
88
suggestions: null,
89
});
90
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/AssertWellFormedBreakTargets.ts
+6
-6
@@ -5,9 +5,9 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "..";
9
-import { BlockId, ReactiveFunction, ReactiveTerminalStatement } from "../HIR";
10
-import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors";
8
+import {CompilerError} from '..';
9
+import {BlockId, ReactiveFunction, ReactiveTerminalStatement} from '../HIR';
10
+import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
11
12
/**
13
* Assert that all break/continue targets reference existent labels.
@@ -19,15 +19,15 @@ export function assertWellFormedBreakTargets(fn: ReactiveFunction): void {
19
class Visitor extends ReactiveFunctionVisitor<Set<BlockId>> {
20
override visitTerminal(
21
stmt: ReactiveTerminalStatement,
22
- seenLabels: Set<BlockId>
22
+ seenLabels: Set<BlockId>,
23
): void {
24
if (stmt.label != null) {
25
seenLabels.add(stmt.label.id);
26
}
27
const terminal = stmt.terminal;
28
- if (terminal.kind === "break" || terminal.kind === "continue") {
28
+ if (terminal.kind === 'break' || terminal.kind === 'continue') {
29
CompilerError.invariant(seenLabels.has(terminal.target), {
30
- reason: "Unexpected break to invalid label",
30
+ reason: 'Unexpected break to invalid label',
31
loc: stmt.terminal.loc,
32
});
33
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/BuildReactiveBlocks.ts
+30
-30
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
8
+import {CompilerError} from '../CompilerError';
9
import {
10
BlockId,
11
InstructionId,
@@ -17,10 +17,10 @@ import {
17
ReactiveScopeBlock,
18
ReactiveStatement,
19
ScopeId,
20
-} from "../HIR";
21
-import { eachInstructionLValue } from "../HIR/visitors";
22
-import { assertExhaustive } from "../Utils/utils";
23
-import { eachReactiveValueOperand, mapTerminalBlocks } from "./visitors";
20
+} from '../HIR';
21
+import {eachInstructionLValue} from '../HIR/visitors';
22
+import {assertExhaustive} from '../Utils/utils';
23
+import {eachReactiveValueOperand, mapTerminalBlocks} from './visitors';
24
25
/*
26
* Note: this is the 4th of 4 passes that determine how to break a function into discrete
@@ -63,7 +63,7 @@ class Context {
63
64
append(
65
stmt: ReactiveStatement,
66
- label: { id: BlockId; implicit: boolean } | null
66
+ label: {id: BlockId; implicit: boolean} | null,
67
): void {
68
this.#builders.at(-1)!.append(stmt, label);
69
}
@@ -74,7 +74,7 @@ class Context {
74
fn();
75
const popped = this.#builders.pop();
76
CompilerError.invariant(popped === builder, {
77
- reason: "Expected push/pop to be called 1:1",
77
+ reason: 'Expected push/pop to be called 1:1',
78
description: null,
79
loc: null,
80
suggestions: null,
@@ -86,23 +86,23 @@ class Context {
86
class Builder {
87
#instructions: ReactiveBlock;
88
#stack: Array<
89
- | { kind: "scope"; block: ReactiveScopeBlock }
90
- | { kind: "block"; block: ReactiveBlock }
89
+ | {kind: 'scope'; block: ReactiveScopeBlock}
90
+ | {kind: 'block'; block: ReactiveBlock}
91
>;
92
93
constructor() {
94
const block: ReactiveBlock = [];
95
this.#instructions = block;
96
- this.#stack = [{ kind: "block", block }];
96
+ this.#stack = [{kind: 'block', block}];
97
}
98
99
append(
100
item: ReactiveStatement,
101
- label: { id: BlockId; implicit: boolean } | null
101
+ label: {id: BlockId; implicit: boolean} | null,
102
): void {
103
if (label !== null) {
104
- CompilerError.invariant(item.kind === "terminal", {
105
- reason: "Only terminals may have a label",
104
+ CompilerError.invariant(item.kind === 'terminal', {
105
+ reason: 'Only terminals may have a label',
106
description: null,
107
loc: null,
108
suggestions: null,
@@ -114,25 +114,25 @@ class Builder {
114
115
startScope(scope: ReactiveScope): void {
116
const block: ReactiveScopeBlock = {
117
- kind: "scope",
117
+ kind: 'scope',
118
scope,
119
instructions: [],
120
};
121
this.append(block, null);
122
this.#instructions = block.instructions;
123
- this.#stack.push({ kind: "scope", block });
123
+ this.#stack.push({kind: 'scope', block});
124
}
125
126
visitId(id: InstructionId): void {
127
for (let i = 0; i < this.#stack.length; i++) {
128
const entry = this.#stack[i]!;
129
- if (entry.kind === "scope" && id >= entry.block.scope.range.end) {
129
+ if (entry.kind === 'scope' && id >= entry.block.scope.range.end) {
130
this.#stack.length = i;
131
break;
132
}
133
}
134
const last = this.#stack[this.#stack.length - 1]!;
135
- if (last.kind === "block") {
135
+ if (last.kind === 'block') {
136
this.#instructions = last.block;
137
} else {
138
this.#instructions = last.block.instructions;
@@ -148,8 +148,8 @@ class Builder {
148
* );
149
*/
150
const first = this.#stack[0]!;
151
- CompilerError.invariant(first.kind === "block", {
152
- reason: "Expected first stack item to be a basic block",
151
+ CompilerError.invariant(first.kind === 'block', {
152
+ reason: 'Expected first stack item to be a basic block',
153
description: null,
154
loc: null,
155
suggestions: null,
@@ -161,7 +161,7 @@ class Builder {
161
function visitBlock(context: Context, block: ReactiveBlock): void {
162
for (const stmt of block) {
163
switch (stmt.kind) {
164
- case "instruction": {
164
+ case 'instruction': {
165
context.visitId(stmt.instruction.id);
166
const scope = getInstructionScope(stmt.instruction);
167
if (scope !== null) {
@@ -170,12 +170,12 @@ function visitBlock(context: Context, block: ReactiveBlock): void {
170
context.append(stmt, null);
171
break;
172
}
173
- case "terminal": {
173
+ case 'terminal': {
174
const id = stmt.terminal.id;
175
if (id !== null) {
176
context.visitId(id);
177
}
178
- mapTerminalBlocks(stmt.terminal, (block) => {
178
+ mapTerminalBlocks(stmt.terminal, block => {
179
return context.enter(() => {
180
visitBlock(context, block);
181
});
@@ -183,10 +183,10 @@ function visitBlock(context: Context, block: ReactiveBlock): void {
183
context.append(stmt, stmt.label);
184
break;
185
}
186
- case "pruned-scope":
187
- case "scope": {
186
+ case 'pruned-scope':
187
+ case 'scope': {
188
CompilerError.invariant(false, {
189
- reason: "Expected the function to not have scopes already assigned",
189
+ reason: 'Expected the function to not have scopes already assigned',
190
description: null,
191
loc: null,
192
suggestions: null,
@@ -195,7 +195,7 @@ function visitBlock(context: Context, block: ReactiveBlock): void {
195
default: {
196
assertExhaustive(
197
stmt,
198
- `Unexpected statement kind \`${(stmt as any).kind}\``
198
+ `Unexpected statement kind \`${(stmt as any).kind}\``,
199
);
200
}
201
}
@@ -203,12 +203,12 @@ function visitBlock(context: Context, block: ReactiveBlock): void {
203
}
204
205
export function getInstructionScope(
206
- instr: ReactiveInstruction
206
+ instr: ReactiveInstruction,
207
): ReactiveScope | null {
208
CompilerError.invariant(instr.lvalue !== null, {
209
reason:
210
- "Expected lvalues to not be null when assigning scopes. " +
211
- "Pruning lvalues too early can result in missing scope information.",
210
+ 'Expected lvalues to not be null when assigning scopes. ' +
211
+ 'Pruning lvalues too early can result in missing scope information.',
212
description: null,
213
loc: instr.loc,
214
suggestions: null,
@@ -230,7 +230,7 @@ export function getInstructionScope(
230
231
export function getPlaceScope(
232
id: InstructionId,
233
- place: Place
233
+ place: Place,
234
): ReactiveScope | null {
235
const scope = place.identifier.scope;
236
if (scope !== null && isScopeActive(scope, id)) {
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/BuildReactiveFunction.ts
+175
-185
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
8
+import {CompilerError} from '../CompilerError';
9
import {
10
BasicBlock,
11
BlockId,
@@ -15,7 +15,7 @@ import {
15
Place,
16
ReactiveBlock,
17
SourceLocation,
18
-} from "../HIR";
18
+} from '../HIR';
19
import {
20
HIRFunction,
21
ReactiveBreakTerminal,
@@ -28,8 +28,8 @@ import {
28
ReactiveTernaryValue,
29
ReactiveValue,
30
Terminal,
31
-} from "../HIR/HIR";
32
-import { assertExhaustive } from "../Utils/utils";
31
+} from '../HIR/HIR';
32
+import {assertExhaustive} from '../Utils/utils';
33
34
/*
35
* Converts from HIR (lower-level CFG) to ReactiveFunction, a tree representation
@@ -76,7 +76,7 @@ class Driver {
76
this.cx.emitted.add(block.id);
77
for (const instruction of block.instructions) {
78
blockValue.push({
79
- kind: "instruction",
79
+ kind: 'instruction',
80
instruction,
81
});
82
}
@@ -84,11 +84,11 @@ class Driver {
84
const terminal = block.terminal;
85
const scheduleIds = [];
86
switch (terminal.kind) {
87
- case "return": {
87
+ case 'return': {
88
blockValue.push({
89
- kind: "terminal",
89
+ kind: 'terminal',
90
terminal: {
91
- kind: "return",
91
+ kind: 'return',
92
loc: terminal.loc,
93
value: terminal.value,
94
id: terminal.id,
@@ -97,11 +97,11 @@ class Driver {
97
});
98
break;
99
}
100
- case "throw": {
100
+ case 'throw': {
101
blockValue.push({
102
- kind: "terminal",
102
+ kind: 'terminal',
103
terminal: {
104
- kind: "throw",
104
+ kind: 'throw',
105
loc: terminal.loc,
106
value: terminal.value,
107
id: terminal.id,
@@ -110,7 +110,7 @@ class Driver {
110
});
111
break;
112
}
113
- case "if": {
113
+ case 'if': {
114
const fallthroughId =
115
this.cx.reachable(terminal.fallthrough) &&
116
!this.cx.isScheduled(terminal.fallthrough)
@@ -122,7 +122,7 @@ class Driver {
122
: null;
123
124
if (fallthroughId !== null) {
125
- const scheduleId = this.cx.schedule(fallthroughId, "if");
125
+ const scheduleId = this.cx.schedule(fallthroughId, 'if');
126
scheduleIds.push(scheduleId);
127
}
128
@@ -134,7 +134,7 @@ class Driver {
134
});
135
} else {
136
consequent = this.traverseBlock(
137
- this.cx.ir.blocks.get(terminal.consequent)!
137
+ this.cx.ir.blocks.get(terminal.consequent)!,
138
);
139
}
140
@@ -152,9 +152,9 @@ class Driver {
152
153
this.cx.unscheduleAll(scheduleIds);
154
blockValue.push({
155
- kind: "terminal",
155
+ kind: 'terminal',
156
terminal: {
157
- kind: "if",
157
+ kind: 'if',
158
loc: terminal.loc,
159
test: terminal.test,
160
consequent: consequent ?? this.emptyBlock(),
@@ -174,14 +174,14 @@ class Driver {
174
}
175
break;
176
}
177
- case "switch": {
177
+ case 'switch': {
178
const fallthroughId =
179
this.cx.reachable(terminal.fallthrough) &&
180
!this.cx.isScheduled(terminal.fallthrough)
181
? terminal.fallthrough
182
: null;
183
if (fallthroughId !== null) {
184
- const scheduleId = this.cx.schedule(fallthroughId, "switch");
184
+ const scheduleId = this.cx.schedule(fallthroughId, 'switch');
185
scheduleIds.push(scheduleId);
186
}
187
@@ -201,20 +201,20 @@ class Driver {
201
return;
202
} else {
203
consequent = this.traverseBlock(
204
- this.cx.ir.blocks.get(case_.block)!
204
+ this.cx.ir.blocks.get(case_.block)!,
205
);
206
- const scheduleId = this.cx.schedule(case_.block, "case");
206
+ const scheduleId = this.cx.schedule(case_.block, 'case');
207
scheduleIds.push(scheduleId);
208
}
209
- cases.push({ test, block: consequent });
209
+ cases.push({test, block: consequent});
210
});
211
cases.reverse();
212
213
this.cx.unscheduleAll(scheduleIds);
214
blockValue.push({
215
- kind: "terminal",
215
+ kind: 'terminal',
216
terminal: {
217
- kind: "switch",
217
+ kind: 'switch',
218
loc: terminal.loc,
219
test: terminal.test,
220
cases,
@@ -233,7 +233,7 @@ class Driver {
233
}
234
break;
235
}
236
- case "do-while": {
236
+ case 'do-while': {
237
const fallthroughId = !this.cx.isScheduled(terminal.fallthrough)
238
? terminal.fallthrough
239
: null;
@@ -245,7 +245,7 @@ class Driver {
245
const scheduleId = this.cx.scheduleLoop(
246
terminal.fallthrough,
247
terminal.test,
248
- terminal.loop
248
+ terminal.loop,
249
);
250
scheduleIds.push(scheduleId);
251
@@ -261,14 +261,14 @@ class Driver {
261
262
const testValue = this.visitValueBlock(
263
terminal.test,
264
- terminal.loc
264
+ terminal.loc,
265
).value;
266
267
this.cx.unscheduleAll(scheduleIds);
268
blockValue.push({
269
- kind: "terminal",
269
+ kind: 'terminal',
270
terminal: {
271
- kind: "do-while",
271
+ kind: 'do-while',
272
loc: terminal.loc,
273
test: testValue,
274
loop: loopBody,
@@ -287,7 +287,7 @@ class Driver {
287
}
288
break;
289
}
290
- case "while": {
290
+ case 'while': {
291
const fallthroughId =
292
this.cx.reachable(terminal.fallthrough) &&
293
!this.cx.isScheduled(terminal.fallthrough)
@@ -301,13 +301,13 @@ class Driver {
301
const scheduleId = this.cx.scheduleLoop(
302
terminal.fallthrough,
303
terminal.test,
304
- terminal.loop
304
+ terminal.loop,
305
);
306
scheduleIds.push(scheduleId);
307
308
const testValue = this.visitValueBlock(
309
terminal.test,
310
- terminal.loc
310
+ terminal.loc,
311
).value;
312
313
let loopBody: ReactiveBlock;
@@ -322,9 +322,9 @@ class Driver {
322
323
this.cx.unscheduleAll(scheduleIds);
324
blockValue.push({
325
- kind: "terminal",
325
+ kind: 'terminal',
326
terminal: {
327
- kind: "while",
327
+ kind: 'while',
328
loc: terminal.loc,
329
test: testValue,
330
loop: loopBody,
@@ -343,7 +343,7 @@ class Driver {
343
}
344
break;
345
}
346
- case "for": {
346
+ case 'for': {
347
const loopId =
348
!this.cx.isScheduled(terminal.loop) &&
349
terminal.loop !== terminal.fallthrough
@@ -357,29 +357,29 @@ class Driver {
357
const scheduleId = this.cx.scheduleLoop(
358
terminal.fallthrough,
359
terminal.update ?? terminal.test,
360
- terminal.loop
360
+ terminal.loop,
361
);
362
scheduleIds.push(scheduleId);
363
364
const init = this.visitValueBlock(terminal.init, terminal.loc);
365
const initBlock = this.cx.ir.blocks.get(init.block)!;
366
let initValue = init.value;
367
- if (initValue.kind === "SequenceExpression") {
367
+ if (initValue.kind === 'SequenceExpression') {
368
const last = initBlock.instructions.at(-1)!;
369
initValue.instructions.push(last);
370
initValue.value = {
371
- kind: "Primitive",
371
+ kind: 'Primitive',
372
value: undefined,
373
loc: terminal.loc,
374
};
375
} else {
376
initValue = {
377
- kind: "SequenceExpression",
377
+ kind: 'SequenceExpression',
378
instructions: [initBlock.instructions.at(-1)!],
379
id: terminal.id,
380
loc: terminal.loc,
381
value: {
382
- kind: "Primitive",
382
+ kind: 'Primitive',
383
value: undefined,
384
loc: terminal.loc,
385
},
@@ -388,7 +388,7 @@ class Driver {
388
389
const testValue = this.visitValueBlock(
390
terminal.test,
391
- terminal.loc
391
+ terminal.loc,
392
).value;
393
394
const updateValue =
@@ -408,9 +408,9 @@ class Driver {
408
409
this.cx.unscheduleAll(scheduleIds);
410
blockValue.push({
411
- kind: "terminal",
411
+ kind: 'terminal',
412
terminal: {
413
- kind: "for",
413
+ kind: 'for',
414
loc: terminal.loc,
415
init: initValue,
416
test: testValue,
@@ -419,16 +419,14 @@ class Driver {
419
id: terminal.id,
420
},
421
label:
422
- fallthroughId == null
423
- ? null
424
- : { id: fallthroughId, implicit: false },
422
+ fallthroughId == null ? null : {id: fallthroughId, implicit: false},
423
});
424
if (fallthroughId !== null) {
425
this.visitBlock(this.cx.ir.blocks.get(fallthroughId)!, blockValue);
426
}
427
break;
428
}
431
- case "for-of": {
429
+ case 'for-of': {
430
const loopId =
431
!this.cx.isScheduled(terminal.loop) &&
432
terminal.loop !== terminal.fallthrough
@@ -442,29 +440,29 @@ class Driver {
440
const scheduleId = this.cx.scheduleLoop(
441
terminal.fallthrough,
442
terminal.init,
445
- terminal.loop
443
+ terminal.loop,
444
);
445
scheduleIds.push(scheduleId);
446
447
const init = this.visitValueBlock(terminal.init, terminal.loc);
448
const initBlock = this.cx.ir.blocks.get(init.block)!;
449
let initValue = init.value;
452
- if (initValue.kind === "SequenceExpression") {
450
+ if (initValue.kind === 'SequenceExpression') {
451
const last = initBlock.instructions.at(-1)!;
452
initValue.instructions.push(last);
453
initValue.value = {
456
- kind: "Primitive",
454
+ kind: 'Primitive',
455
value: undefined,
456
loc: terminal.loc,
457
};
458
} else {
459
initValue = {
462
- kind: "SequenceExpression",
460
+ kind: 'SequenceExpression',
461
instructions: [initBlock.instructions.at(-1)!],
462
id: terminal.id,
463
loc: terminal.loc,
464
value: {
467
- kind: "Primitive",
465
+ kind: 'Primitive',
466
value: undefined,
467
loc: terminal.loc,
468
},
@@ -474,22 +472,22 @@ class Driver {
472
const test = this.visitValueBlock(terminal.test, terminal.loc);
473
const testBlock = this.cx.ir.blocks.get(test.block)!;
474
let testValue = test.value;
477
- if (testValue.kind === "SequenceExpression") {
475
+ if (testValue.kind === 'SequenceExpression') {
476
const last = testBlock.instructions.at(-1)!;
477
testValue.instructions.push(last);
478
testValue.value = {
481
- kind: "Primitive",
479
+ kind: 'Primitive',
480
value: undefined,
481
loc: terminal.loc,
482
};
483
} else {
484
testValue = {
487
- kind: "SequenceExpression",
485
+ kind: 'SequenceExpression',
486
instructions: [testBlock.instructions.at(-1)!],
487
id: terminal.id,
488
loc: terminal.loc,
489
value: {
492
- kind: "Primitive",
490
+ kind: 'Primitive',
491
value: undefined,
492
loc: terminal.loc,
493
},
@@ -508,9 +506,9 @@ class Driver {
506
507
this.cx.unscheduleAll(scheduleIds);
508
blockValue.push({
511
- kind: "terminal",
509
+ kind: 'terminal',
510
terminal: {
513
- kind: "for-of",
511
+ kind: 'for-of',
512
loc: terminal.loc,
513
init: initValue,
514
test: testValue,
@@ -518,16 +516,14 @@ class Driver {
516
id: terminal.id,
517
},
518
label:
521
- fallthroughId == null
522
- ? null
523
- : { id: fallthroughId, implicit: false },
519
+ fallthroughId == null ? null : {id: fallthroughId, implicit: false},
520
});
521
if (fallthroughId !== null) {
522
this.visitBlock(this.cx.ir.blocks.get(fallthroughId)!, blockValue);
523
}
524
break;
525
}
530
- case "for-in": {
526
+ case 'for-in': {
527
const loopId =
528
!this.cx.isScheduled(terminal.loop) &&
529
terminal.loop !== terminal.fallthrough
@@ -541,29 +537,29 @@ class Driver {
537
const scheduleId = this.cx.scheduleLoop(
538
terminal.fallthrough,
539
terminal.init,
544
- terminal.loop
540
+ terminal.loop,
541
);
542
scheduleIds.push(scheduleId);
543
544
const init = this.visitValueBlock(terminal.init, terminal.loc);
545
const initBlock = this.cx.ir.blocks.get(init.block)!;
546
let initValue = init.value;
551
- if (initValue.kind === "SequenceExpression") {
547
+ if (initValue.kind === 'SequenceExpression') {
548
const last = initBlock.instructions.at(-1)!;
549
initValue.instructions.push(last);
550
initValue.value = {
555
- kind: "Primitive",
551
+ kind: 'Primitive',
552
value: undefined,
553
loc: terminal.loc,
554
};
555
} else {
556
initValue = {
561
- kind: "SequenceExpression",
557
+ kind: 'SequenceExpression',
558
instructions: [initBlock.instructions.at(-1)!],
559
id: terminal.id,
560
loc: terminal.loc,
561
value: {
566
- kind: "Primitive",
562
+ kind: 'Primitive',
563
value: undefined,
564
loc: terminal.loc,
565
},
@@ -582,38 +578,36 @@ class Driver {
578
579
this.cx.unscheduleAll(scheduleIds);
580
blockValue.push({
585
- kind: "terminal",
581
+ kind: 'terminal',
582
terminal: {
587
- kind: "for-in",
583
+ kind: 'for-in',
584
loc: terminal.loc,
585
init: initValue,
586
loop: loopBody,
587
id: terminal.id,
588
},
589
label:
594
- fallthroughId == null
595
- ? null
596
- : { id: fallthroughId, implicit: false },
590
+ fallthroughId == null ? null : {id: fallthroughId, implicit: false},
591
});
592
if (fallthroughId !== null) {
593
this.visitBlock(this.cx.ir.blocks.get(fallthroughId)!, blockValue);
594
}
595
break;
596
}
603
- case "branch": {
597
+ case 'branch': {
598
let consequent: ReactiveBlock | null = null;
599
if (this.cx.isScheduled(terminal.consequent)) {
600
const break_ = this.visitBreak(
601
terminal.consequent,
602
terminal.id,
609
- terminal.loc
603
+ terminal.loc,
604
);
605
if (break_ !== null) {
606
consequent = [break_];
607
}
608
} else {
609
consequent = this.traverseBlock(
616
- this.cx.ir.blocks.get(terminal.consequent)!
610
+ this.cx.ir.blocks.get(terminal.consequent)!,
611
);
612
}
613
@@ -625,14 +619,14 @@ class Driver {
619
});
620
} else {
621
alternate = this.traverseBlock(
628
- this.cx.ir.blocks.get(terminal.alternate)!
622
+ this.cx.ir.blocks.get(terminal.alternate)!,
623
);
624
}
625
626
blockValue.push({
633
- kind: "terminal",
627
+ kind: 'terminal',
628
terminal: {
635
- kind: "if",
629
+ kind: 'if',
630
loc: terminal.loc,
631
test: terminal.test,
632
consequent: consequent ?? this.emptyBlock(),
@@ -644,14 +638,14 @@ class Driver {
638
639
break;
640
}
647
- case "label": {
641
+ case 'label': {
642
const fallthroughId =
643
this.cx.reachable(terminal.fallthrough) &&
644
!this.cx.isScheduled(terminal.fallthrough)
645
? terminal.fallthrough
646
: null;
647
if (fallthroughId !== null) {
654
- const scheduleId = this.cx.schedule(fallthroughId, "if");
648
+ const scheduleId = this.cx.schedule(fallthroughId, 'if');
649
scheduleIds.push(scheduleId);
650
}
651
@@ -667,17 +661,15 @@ class Driver {
661
662
this.cx.unscheduleAll(scheduleIds);
663
blockValue.push({
670
- kind: "terminal",
664
+ kind: 'terminal',
665
terminal: {
672
- kind: "label",
666
+ kind: 'label',
667
loc: terminal.loc,
668
block,
669
id: terminal.id,
670
},
671
label:
678
- fallthroughId == null
679
- ? null
680
- : { id: fallthroughId, implicit: false },
672
+ fallthroughId == null ? null : {id: fallthroughId, implicit: false},
673
});
674
if (fallthroughId !== null) {
675
this.visitBlock(this.cx.ir.blocks.get(fallthroughId)!, blockValue);
@@ -685,24 +677,24 @@ class Driver {
677
678
break;
679
}
688
- case "sequence":
689
- case "optional":
690
- case "ternary":
691
- case "logical": {
680
+ case 'sequence':
681
+ case 'optional':
682
+ case 'ternary':
683
+ case 'logical': {
684
const fallthroughId =
685
terminal.fallthrough !== null &&
686
!this.cx.isScheduled(terminal.fallthrough)
687
? terminal.fallthrough
688
: null;
689
if (fallthroughId !== null) {
698
- const scheduleId = this.cx.schedule(fallthroughId, "if");
690
+ const scheduleId = this.cx.schedule(fallthroughId, 'if');
691
scheduleIds.push(scheduleId);
692
}
693
702
- const { place, value } = this.visitValueBlockTerminal(terminal);
694
+ const {place, value} = this.visitValueBlockTerminal(terminal);
695
this.cx.unscheduleAll(scheduleIds);
696
blockValue.push({
705
- kind: "instruction",
697
+ kind: 'instruction',
698
instruction: {
699
id: terminal.id,
700
lvalue: place,
@@ -716,13 +708,13 @@ class Driver {
708
}
709
break;
710
}
719
- case "goto": {
711
+ case 'goto': {
712
switch (terminal.variant) {
713
case GotoVariant.Break: {
714
const break_ = this.visitBreak(
715
terminal.block,
716
terminal.id,
725
- terminal.loc
717
+ terminal.loc,
718
);
719
if (break_ !== null) {
720
blockValue.push(break_);
@@ -733,7 +725,7 @@ class Driver {
725
const continue_ = this.visitContinue(
726
terminal.block,
727
terminal.id,
736
- terminal.loc
728
+ terminal.loc,
729
);
730
if (continue_ !== null) {
731
blockValue.push(continue_);
@@ -746,13 +738,13 @@ class Driver {
738
default: {
739
assertExhaustive(
740
terminal.variant,
749
- `Unexpected goto variant \`${terminal.variant}\``
741
+ `Unexpected goto variant \`${terminal.variant}\``,
742
);
743
}
744
}
745
break;
746
}
755
- case "maybe-throw": {
747
+ case 'maybe-throw': {
748
/*
749
* ReactiveFunction does not explicit model maybe-throw semantics,
750
* so these terminals flatten away
@@ -760,39 +752,37 @@ class Driver {
752
if (!this.cx.isScheduled(terminal.continuation)) {
753
this.visitBlock(
754
this.cx.ir.blocks.get(terminal.continuation)!,
763
- blockValue
755
+ blockValue,
756
);
757
}
758
break;
759
}
768
- case "try": {
760
+ case 'try': {
761
const fallthroughId =
762
this.cx.reachable(terminal.fallthrough) &&
763
!this.cx.isScheduled(terminal.fallthrough)
764
? terminal.fallthrough
765
: null;
766
if (fallthroughId !== null) {
775
- const scheduleId = this.cx.schedule(fallthroughId, "if");
767
+ const scheduleId = this.cx.schedule(fallthroughId, 'if');
768
scheduleIds.push(scheduleId);
769
}
770
this.cx.scheduleCatchHandler(terminal.handler);
771
772
const block = this.traverseBlock(
781
- this.cx.ir.blocks.get(terminal.block)!
773
+ this.cx.ir.blocks.get(terminal.block)!,
774
);
775
const handler = this.traverseBlock(
784
- this.cx.ir.blocks.get(terminal.handler)!
776
+ this.cx.ir.blocks.get(terminal.handler)!,
777
);
778
779
this.cx.unscheduleAll(scheduleIds);
780
blockValue.push({
789
- kind: "terminal",
781
+ kind: 'terminal',
782
label:
791
- fallthroughId == null
792
- ? null
793
- : { id: fallthroughId, implicit: false },
783
+ fallthroughId == null ? null : {id: fallthroughId, implicit: false},
784
terminal: {
795
- kind: "try",
785
+ kind: 'try',
786
loc: terminal.loc,
787
block,
788
handlerBinding: terminal.handlerBinding,
@@ -806,13 +796,13 @@ class Driver {
796
}
797
break;
798
}
809
- case "pruned-scope":
810
- case "scope": {
799
+ case 'pruned-scope':
800
+ case 'scope': {
801
const fallthroughId = !this.cx.isScheduled(terminal.fallthrough)
802
? terminal.fallthrough
803
: null;
804
if (fallthroughId !== null) {
815
- const scheduleId = this.cx.schedule(fallthroughId, "if");
805
+ const scheduleId = this.cx.schedule(fallthroughId, 'if');
806
scheduleIds.push(scheduleId);
807
this.cx.scopeFallthroughs.add(fallthroughId);
808
}
@@ -839,37 +829,37 @@ class Driver {
829
830
break;
831
}
842
- case "unreachable": {
832
+ case 'unreachable': {
833
// noop
834
break;
835
}
846
- case "unsupported": {
836
+ case 'unsupported': {
837
CompilerError.invariant(false, {
848
- reason: "Unexpected unsupported terminal",
838
+ reason: 'Unexpected unsupported terminal',
839
description: null,
840
loc: terminal.loc,
841
suggestions: null,
842
});
843
}
844
default: {
855
- assertExhaustive(terminal, "Unexpected terminal");
845
+ assertExhaustive(terminal, 'Unexpected terminal');
846
}
847
}
848
}
849
850
visitValueBlock(
851
id: BlockId,
862
- loc: SourceLocation
863
- ): { block: BlockId; value: ReactiveValue; place: Place; id: InstructionId } {
852
+ loc: SourceLocation,
853
+ ): {block: BlockId; value: ReactiveValue; place: Place; id: InstructionId} {
854
const defaultBlock = this.cx.ir.blocks.get(id)!;
865
- if (defaultBlock.terminal.kind === "branch") {
855
+ if (defaultBlock.terminal.kind === 'branch') {
856
const instructions = defaultBlock.instructions;
857
if (instructions.length === 0) {
858
return {
859
block: defaultBlock.id,
860
place: defaultBlock.terminal.test,
861
value: {
872
- kind: "LoadLocal",
862
+ kind: 'LoadLocal',
863
place: defaultBlock.terminal.test,
864
loc: defaultBlock.terminal.test.loc,
865
},
@@ -882,11 +872,11 @@ class Driver {
872
defaultBlock.terminal.test.identifier.id,
873
{
874
reason:
885
- "Expected branch block to end in an instruction that sets the test value",
875
+ 'Expected branch block to end in an instruction that sets the test value',
876
description: null,
877
loc: instr.lvalue.loc,
878
suggestions: null,
889
- }
879
+ },
880
);
881
return {
882
block: defaultBlock.id,
@@ -897,7 +887,7 @@ class Driver {
887
} else {
888
const instr = defaultBlock.instructions.at(-1)!;
889
const sequence: ReactiveSequenceValue = {
900
- kind: "SequenceExpression",
890
+ kind: 'SequenceExpression',
891
instructions: defaultBlock.instructions.slice(0, -1),
892
id: instr.id,
893
value: instr.value,
@@ -910,11 +900,11 @@ class Driver {
900
id: defaultBlock.terminal.id,
901
};
902
}
913
- } else if (defaultBlock.terminal.kind === "goto") {
903
+ } else if (defaultBlock.terminal.kind === 'goto') {
904
const instructions = defaultBlock.instructions;
905
if (instructions.length === 0) {
906
CompilerError.invariant(false, {
917
- reason: "Expected goto value block to have at least one instruction",
907
+ reason: 'Expected goto value block to have at least one instruction',
908
description: null,
909
loc: null,
910
suggestions: null,
@@ -933,12 +923,12 @@ class Driver {
923
* StoreLocal for temporaries — any named/promoted values must be used
924
* elsewhere and aren't safe to prune.
925
*/
936
- value.kind === "StoreLocal" &&
926
+ value.kind === 'StoreLocal' &&
927
value.lvalue.place.identifier.name === null
928
) {
929
place = value.lvalue.place;
930
value = {
941
- kind: "LoadLocal",
931
+ kind: 'LoadLocal',
932
place: value.value,
933
loc: value.value.loc,
934
};
@@ -963,18 +953,18 @@ class Driver {
953
* StoreLocal for temporaries — any named/promoted values must be used
954
* elsewhere and aren't safe to prune.
955
*/
966
- value.kind === "StoreLocal" &&
956
+ value.kind === 'StoreLocal' &&
957
value.lvalue.place.identifier.name === null
958
) {
959
place = value.lvalue.place;
960
value = {
971
- kind: "LoadLocal",
961
+ kind: 'LoadLocal',
962
place: value.value,
963
loc: value.value.loc,
964
};
965
}
966
const sequence: ReactiveSequenceValue = {
977
- kind: "SequenceExpression",
967
+ kind: 'SequenceExpression',
968
instructions: defaultBlock.instructions.slice(0, -1),
969
id: instr.id,
970
value,
@@ -997,7 +987,7 @@ class Driver {
987
const final = this.visitValueBlock(init.fallthrough, loc);
988
// Stitch the two together...
989
const sequence: ReactiveSequenceValue = {
1000
- kind: "SequenceExpression",
990
+ kind: 'SequenceExpression',
991
instructions: [
992
...defaultBlock.instructions,
993
{
@@ -1027,7 +1017,7 @@ class Driver {
1017
id: InstructionId;
1018
} {
1019
switch (terminal.kind) {
1030
- case "sequence": {
1020
+ case 'sequence': {
1021
const block = this.visitValueBlock(terminal.block, terminal.loc);
1022
return {
1023
value: block.value,
@@ -1036,10 +1026,10 @@ class Driver {
1026
id: terminal.id,
1027
};
1028
}
1039
- case "optional": {
1029
+ case 'optional': {
1030
const test = this.visitValueBlock(terminal.test, terminal.loc);
1031
const testBlock = this.cx.ir.blocks.get(test.block)!;
1042
- if (testBlock.terminal.kind !== "branch") {
1032
+ if (testBlock.terminal.kind !== 'branch') {
1033
CompilerError.throwTodo({
1034
reason: `Unexpected terminal kind \`${testBlock.terminal.kind}\` for optional test block`,
1035
description: null,
@@ -1049,10 +1039,10 @@ class Driver {
1039
}
1040
const consequent = this.visitValueBlock(
1041
testBlock.terminal.consequent,
1052
- terminal.loc
1042
+ terminal.loc,
1043
);
1044
const call: ReactiveSequenceValue = {
1055
- kind: "SequenceExpression",
1045
+ kind: 'SequenceExpression',
1046
instructions: [
1047
{
1048
id: test.id,
@@ -1066,9 +1056,9 @@ class Driver {
1056
loc: terminal.loc,
1057
};
1058
return {
1069
- place: { ...consequent.place },
1059
+ place: {...consequent.place},
1060
value: {
1071
- kind: "OptionalExpression",
1061
+ kind: 'OptionalExpression',
1062
optional: terminal.optional,
1063
value: call,
1064
id: terminal.id,
@@ -1078,10 +1068,10 @@ class Driver {
1068
id: terminal.id,
1069
};
1070
}
1081
- case "logical": {
1071
+ case 'logical': {
1072
const test = this.visitValueBlock(terminal.test, terminal.loc);
1073
const testBlock = this.cx.ir.blocks.get(test.block)!;
1084
- if (testBlock.terminal.kind !== "branch") {
1074
+ if (testBlock.terminal.kind !== 'branch') {
1075
CompilerError.throwTodo({
1076
reason: `Unexpected terminal kind \`${testBlock.terminal.kind}\` for logical test block`,
1077
description: null,
@@ -1092,10 +1082,10 @@ class Driver {
1082
1083
const leftFinal = this.visitValueBlock(
1084
testBlock.terminal.consequent,
1095
- terminal.loc
1085
+ terminal.loc,
1086
);
1087
const left: ReactiveSequenceValue = {
1098
- kind: "SequenceExpression",
1088
+ kind: 'SequenceExpression',
1089
instructions: [
1090
{
1091
id: test.id,
@@ -1110,26 +1100,26 @@ class Driver {
1100
};
1101
const right = this.visitValueBlock(
1102
testBlock.terminal.alternate,
1113
- terminal.loc
1103
+ terminal.loc,
1104
);
1105
const value: ReactiveLogicalValue = {
1116
- kind: "LogicalExpression",
1106
+ kind: 'LogicalExpression',
1107
operator: terminal.operator,
1108
left: left,
1109
right: right.value,
1110
loc: terminal.loc,
1111
};
1112
return {
1123
- place: { ...leftFinal.place },
1113
+ place: {...leftFinal.place},
1114
value,
1115
fallthrough: terminal.fallthrough,
1116
id: terminal.id,
1117
};
1118
}
1129
- case "ternary": {
1119
+ case 'ternary': {
1120
const test = this.visitValueBlock(terminal.test, terminal.loc);
1121
const testBlock = this.cx.ir.blocks.get(test.block)!;
1132
- if (testBlock.terminal.kind !== "branch") {
1122
+ if (testBlock.terminal.kind !== 'branch') {
1123
CompilerError.throwTodo({
1124
reason: `Unexpected terminal kind \`${testBlock.terminal.kind}\` for ternary test block`,
1125
description: null,
@@ -1139,14 +1129,14 @@ class Driver {
1129
}
1130
const consequent = this.visitValueBlock(
1131
testBlock.terminal.consequent,
1142
- terminal.loc
1132
+ terminal.loc,
1133
);
1134
const alternate = this.visitValueBlock(
1135
testBlock.terminal.alternate,
1146
- terminal.loc
1136
+ terminal.loc,
1137
);
1138
const value: ReactiveTernaryValue = {
1149
- kind: "ConditionalExpression",
1139
+ kind: 'ConditionalExpression',
1140
test: test.value,
1141
consequent: consequent.value,
1142
alternate: alternate.value,
@@ -1154,13 +1144,13 @@ class Driver {
1144
};
1145
1146
return {
1157
- place: { ...consequent.place },
1147
+ place: {...consequent.place},
1148
value,
1149
fallthrough: terminal.fallthrough,
1150
id: terminal.id,
1151
};
1152
}
1163
- case "maybe-throw": {
1153
+ case 'maybe-throw': {
1154
CompilerError.throwTodo({
1155
reason: `Support value blocks (conditional, logical, optional chaining, etc) within a try/catch statement`,
1156
description: null,
@@ -1168,7 +1158,7 @@ class Driver {
1158
suggestions: null,
1159
});
1160
}
1171
- case "label": {
1161
+ case 'label': {
1162
CompilerError.throwTodo({
1163
reason: `Support labeled statements combined with value blocks (conditional, logical, optional chaining, etc)`,
1164
description: null,
@@ -1194,28 +1184,28 @@ class Driver {
1184
visitBreak(
1185
block: BlockId,
1186
id: InstructionId,
1197
- loc: SourceLocation
1187
+ loc: SourceLocation,
1188
): ReactiveTerminalStatement<ReactiveBreakTerminal> | null {
1189
const target = this.cx.getBreakTarget(block);
1190
if (target === null) {
1191
CompilerError.invariant(false, {
1202
- reason: "Expected a break target",
1192
+ reason: 'Expected a break target',
1193
description: null,
1194
loc: null,
1195
suggestions: null,
1196
});
1197
}
1198
if (this.cx.scopeFallthroughs.has(target.block)) {
1209
- CompilerError.invariant(target.type === "implicit", {
1210
- reason: "Expected reactive scope to implicitly break to fallthrough",
1199
+ CompilerError.invariant(target.type === 'implicit', {
1200
+ reason: 'Expected reactive scope to implicitly break to fallthrough',
1201
loc,
1202
});
1203
return null;
1204
}
1205
return {
1216
- kind: "terminal",
1206
+ kind: 'terminal',
1207
terminal: {
1218
- kind: "break",
1208
+ kind: 'break',
1209
loc,
1210
target: target.block,
1211
id,
@@ -1228,7 +1218,7 @@ class Driver {
1218
visitContinue(
1219
block: BlockId,
1220
id: InstructionId,
1231
- loc: SourceLocation
1221
+ loc: SourceLocation,
1222
): ReactiveTerminalStatement<ReactiveContinueTerminal> {
1223
const target = this.cx.getContinueTarget(block);
1224
CompilerError.invariant(target !== null, {
@@ -1239,9 +1229,9 @@ class Driver {
1229
});
1230
1231
return {
1242
- kind: "terminal",
1232
+ kind: 'terminal',
1233
terminal: {
1244
- kind: "continue",
1234
+ kind: 'continue',
1235
loc,
1236
target: target.block,
1237
id,
@@ -1297,14 +1287,14 @@ class Context {
1287
1288
reachable(id: BlockId): boolean {
1289
const block = this.ir.blocks.get(id)!;
1300
- return block.terminal.kind !== "unreachable";
1290
+ return block.terminal.kind !== 'unreachable';
1291
}
1292
1293
/*
1294
* Record that the given block will be emitted (eg by the codegen of a parent node)
1295
* so that child nodes can avoid re-emitting it.
1296
*/
1307
- schedule(block: BlockId, type: "if" | "switch" | "case"): number {
1297
+ schedule(block: BlockId, type: 'if' | 'switch' | 'case'): number {
1298
const id = this.#nextScheduleId++;
1299
CompilerError.invariant(!this.#scheduled.has(block), {
1300
reason: `Break block is already scheduled: bb${block}`,
@@ -1313,14 +1303,14 @@ class Context {
1303
suggestions: null,
1304
});
1305
this.#scheduled.add(block);
1316
- this.#controlFlowStack.push({ block, id, type });
1306
+ this.#controlFlowStack.push({block, id, type});
1307
return id;
1308
}
1309
1310
scheduleLoop(
1311
fallthroughBlock: BlockId,
1312
continueBlock: BlockId,
1323
- loopBlock: BlockId | null
1313
+ loopBlock: BlockId | null,
1314
): number {
1315
const id = this.#nextScheduleId++;
1316
const ownsBlock = !this.#scheduled.has(fallthroughBlock);
@@ -1342,7 +1332,7 @@ class Context {
1332
block: fallthroughBlock,
1333
ownsBlock,
1334
id,
1345
- type: "loop",
1335
+ type: 'loop',
1336
continueBlock,
1337
loopBlock,
1338
ownsLoop,
@@ -1354,15 +1344,15 @@ class Context {
1344
unschedule(scheduleId: number): void {
1345
const last = this.#controlFlowStack.pop();
1346
CompilerError.invariant(last !== undefined && last.id === scheduleId, {
1357
- reason: "Can only unschedule the last target",
1347
+ reason: 'Can only unschedule the last target',
1348
description: null,
1349
loc: null,
1350
suggestions: null,
1351
});
1362
- if (last.type !== "loop" || last.ownsBlock !== null) {
1352
+ if (last.type !== 'loop' || last.ownsBlock !== null) {
1353
this.#scheduled.delete(last.block);
1354
}
1365
- if (last.type === "loop") {
1355
+ if (last.type === 'loop') {
1356
this.#scheduled.delete(last.continueBlock);
1357
if (last.ownsLoop && last.loopBlock !== null) {
1358
this.#scheduled.delete(last.loopBlock);
@@ -1404,32 +1394,32 @@ class Context {
1394
const target = this.#controlFlowStack[i]!;
1395
if (target.block === block) {
1396
let type: ReactiveTerminalTargetKind;
1407
- if (target.type === "loop") {
1397
+ if (target.type === 'loop') {
1398
/*
1399
* breaking out of a loop requires an explicit break,
1400
* but only requires a label if breaking past the innermost loop.
1401
*/
1412
- type = hasPrecedingLoop ? "labeled" : "unlabeled";
1402
+ type = hasPrecedingLoop ? 'labeled' : 'unlabeled';
1403
} else if (i === this.#controlFlowStack.length - 1) {
1404
/*
1405
* breaking to the last break point, which is where control will transfer
1406
* implicitly
1407
*/
1418
- type = "implicit";
1408
+ type = 'implicit';
1409
} else {
1410
// breaking somewhere else requires an explicit break
1421
- type = "labeled";
1411
+ type = 'labeled';
1412
}
1413
return {
1414
block: target.block,
1415
type,
1416
};
1417
}
1428
- hasPrecedingLoop ||= target.type === "loop";
1418
+ hasPrecedingLoop ||= target.type === 'loop';
1419
}
1420
1421
CompilerError.invariant(false, {
1432
- reason: "Expected a break target",
1422
+ reason: 'Expected a break target',
1423
description: null,
1424
loc: null,
1425
suggestions: null,
@@ -1447,53 +1437,53 @@ class Context {
1437
* The returned 'block' value should be used as the label if necessary.
1438
*/
1439
getContinueTarget(
1450
- block: BlockId
1451
- ): { block: BlockId; type: ReactiveTerminalTargetKind } | null {
1440
+ block: BlockId,
1441
+ ): {block: BlockId; type: ReactiveTerminalTargetKind} | null {
1442
let hasPrecedingLoop = false;
1443
for (let i = this.#controlFlowStack.length - 1; i >= 0; i--) {
1444
const target = this.#controlFlowStack[i]!;
1455
- if (target.type == "loop" && target.continueBlock === block) {
1445
+ if (target.type == 'loop' && target.continueBlock === block) {
1446
let type: ReactiveTerminalTargetKind;
1447
if (hasPrecedingLoop) {
1448
/*
1449
* continuing to a loop that is not the innermost loop always requires
1450
* a label
1451
*/
1462
- type = "labeled";
1452
+ type = 'labeled';
1453
} else if (i === this.#controlFlowStack.length - 1) {
1454
/*
1455
* continuing to the last break point, which is where control will
1456
* transfer to naturally
1457
*/
1468
- type = "implicit";
1458
+ type = 'implicit';
1459
} else {
1460
/*
1461
* the continue is inside some conditional logic, requires an explicit
1462
* continue
1463
*/
1474
- type = "unlabeled";
1464
+ type = 'unlabeled';
1465
}
1466
return {
1467
block: target.block,
1468
type,
1469
};
1470
}
1481
- hasPrecedingLoop ||= target.type === "loop";
1471
+ hasPrecedingLoop ||= target.type === 'loop';
1472
}
1473
return null;
1474
}
1475
1476
debugBreakTargets(): Array<ControlFlowTarget> {
1487
- return this.#controlFlowStack.map((target) => ({ ...target }));
1477
+ return this.#controlFlowStack.map(target => ({...target}));
1478
}
1479
}
1480
1481
type ControlFlowTarget =
1492
- | { type: "if"; block: BlockId; id: number }
1493
- | { type: "switch"; block: BlockId; id: number }
1494
- | { type: "case"; block: BlockId; id: number }
1482
+ | {type: 'if'; block: BlockId; id: number}
1483
+ | {type: 'switch'; block: BlockId; id: number}
1484
+ | {type: 'case'; block: BlockId; id: number}
1485
| {
1496
- type: "loop";
1486
+ type: 'loop';
1487
block: BlockId;
1488
ownsBlock: boolean;
1489
continueBlock: BlockId;
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/CodegenReactiveFunction.ts
+500
-499
@@ -5,16 +5,16 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import * as t from "@babel/types";
9
-import { createHmac } from "crypto";
8
+import * as t from '@babel/types';
9
+import {createHmac} from 'crypto';
10
import {
11
pruneHoistedContexts,
12
pruneUnusedLValues,
13
pruneUnusedLabels,
14
renameVariables,
15
-} from ".";
16
-import { CompilerError, ErrorSeverity } from "../CompilerError";
17
-import { Environment, EnvironmentConfig, ExternalFunction } from "../HIR";
15
+} from '.';
16
+import {CompilerError, ErrorSeverity} from '../CompilerError';
17
+import {Environment, EnvironmentConfig, ExternalFunction} from '../HIR';
18
import {
19
ArrayPattern,
20
BlockId,
@@ -41,24 +41,24 @@ import {
41
ValidIdentifierName,
42
getHookKind,
43
makeIdentifierName,
44
-} from "../HIR/HIR";
45
-import { printIdentifier, printPlace } from "../HIR/PrintHIR";
46
-import { eachPatternOperand } from "../HIR/visitors";
47
-import { Err, Ok, Result } from "../Utils/Result";
48
-import { GuardKind } from "../Utils/RuntimeDiagnosticConstants";
49
-import { assertExhaustive } from "../Utils/utils";
50
-import { buildReactiveFunction } from "./BuildReactiveFunction";
51
-import { SINGLE_CHILD_FBT_TAGS } from "./MemoizeFbtAndMacroOperandsInSameScope";
52
-import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors";
53
-import { ReactFunctionType } from "../HIR/Environment";
54
-
55
-export const MEMO_CACHE_SENTINEL = "react.memo_cache_sentinel";
56
-export const EARLY_RETURN_SENTINEL = "react.early_return_sentinel";
44
+} from '../HIR/HIR';
45
+import {printIdentifier, printPlace} from '../HIR/PrintHIR';
46
+import {eachPatternOperand} from '../HIR/visitors';
47
+import {Err, Ok, Result} from '../Utils/Result';
48
+import {GuardKind} from '../Utils/RuntimeDiagnosticConstants';
49
+import {assertExhaustive} from '../Utils/utils';
50
+import {buildReactiveFunction} from './BuildReactiveFunction';
51
+import {SINGLE_CHILD_FBT_TAGS} from './MemoizeFbtAndMacroOperandsInSameScope';
52
+import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
53
+import {ReactFunctionType} from '../HIR/Environment';
54
+
55
+export const MEMO_CACHE_SENTINEL = 'react.memo_cache_sentinel';
56
+export const EARLY_RETURN_SENTINEL = 'react.early_return_sentinel';
57
58
export type CodegenFunction = {
59
- type: "CodegenFunction";
59
+ type: 'CodegenFunction';
60
id: t.Identifier | null;
61
- params: t.FunctionDeclaration["params"];
61
+ params: t.FunctionDeclaration['params'];
62
body: t.BlockStatement;
63
generator: boolean;
64
async: boolean;
@@ -106,14 +106,14 @@ export function codegenFunction(
106
}: {
107
uniqueIdentifiers: Set<string>;
108
fbtOperands: Set<IdentifierId>;
109
- }
109
+ },
110
): Result<CodegenFunction, CompilerError> {
111
const cx = new Context(
112
fn.env,
113
- fn.id ?? "[[ anonymous ]]",
113
+ fn.id ?? '[[ anonymous ]]',
114
uniqueIdentifiers,
115
fbtOperands,
116
- null
116
+ null,
117
);
118
119
/**
@@ -130,7 +130,7 @@ export function codegenFunction(
130
fn.env.config.enableResetCacheOnSourceFileChanges &&
131
fn.env.code !== null
132
) {
133
- const hash = createHmac("sha256", fn.env.code).digest("hex");
133
+ const hash = createHmac('sha256', fn.env.code).digest('hex');
134
fastRefreshState = {
135
cacheIndex: cx.nextCacheIndex,
136
hash,
@@ -150,7 +150,7 @@ export function codegenFunction(
150
hookGuard,
151
compiled.body.body,
152
GuardKind.PushHookGuard,
153
- GuardKind.PopHookGuard
153
+ GuardKind.PopHookGuard,
154
),
155
]);
156
}
@@ -161,77 +161,77 @@ export function codegenFunction(
161
162
// The import declaration for `useMemoCache` is inserted in the Babel plugin
163
preface.push(
164
- t.variableDeclaration("const", [
164
+ t.variableDeclaration('const', [
165
t.variableDeclarator(
166
- t.identifier(cx.synthesizeName("$")),
166
+ t.identifier(cx.synthesizeName('$')),
167
t.callExpression(t.identifier(fn.env.useMemoCacheIdentifier), [
168
t.numericLiteral(cacheCount),
169
- ])
169
+ ]),
170
),
171
- ])
171
+ ]),
172
);
173
if (fastRefreshState !== null) {
174
// HMR detection is enabled, emit code to reset the memo cache on source changes
175
- const index = cx.synthesizeName("$i");
175
+ const index = cx.synthesizeName('$i');
176
preface.push(
177
t.ifStatement(
178
t.binaryExpression(
179
- "!==",
179
+ '!==',
180
t.memberExpression(
181
- t.identifier(cx.synthesizeName("$")),
181
+ t.identifier(cx.synthesizeName('$')),
182
t.numericLiteral(fastRefreshState.cacheIndex),
183
- true
183
+ true,
184
),
185
- t.stringLiteral(fastRefreshState.hash)
185
+ t.stringLiteral(fastRefreshState.hash),
186
),
187
t.blockStatement([
188
t.forStatement(
189
- t.variableDeclaration("let", [
189
+ t.variableDeclaration('let', [
190
t.variableDeclarator(t.identifier(index), t.numericLiteral(0)),
191
]),
192
t.binaryExpression(
193
- "<",
193
+ '<',
194
t.identifier(index),
195
- t.numericLiteral(cacheCount)
195
+ t.numericLiteral(cacheCount),
196
),
197
t.assignmentExpression(
198
- "+=",
198
+ '+=',
199
t.identifier(index),
200
- t.numericLiteral(1)
200
+ t.numericLiteral(1),
201
),
202
t.blockStatement([
203
t.expressionStatement(
204
t.assignmentExpression(
205
- "=",
205
+ '=',
206
t.memberExpression(
207
- t.identifier(cx.synthesizeName("$")),
207
+ t.identifier(cx.synthesizeName('$')),
208
t.identifier(index),
209
- true
209
+ true,
210
),
211
t.callExpression(
212
t.memberExpression(
213
- t.identifier("Symbol"),
214
- t.identifier("for")
213
+ t.identifier('Symbol'),
214
+ t.identifier('for'),
215
),
216
- [t.stringLiteral(MEMO_CACHE_SENTINEL)]
217
- )
218
- )
216
+ [t.stringLiteral(MEMO_CACHE_SENTINEL)],
217
+ ),
218
+ ),
219
),
220
- ])
220
+ ]),
221
),
222
t.expressionStatement(
223
t.assignmentExpression(
224
- "=",
224
+ '=',
225
t.memberExpression(
226
- t.identifier(cx.synthesizeName("$")),
226
+ t.identifier(cx.synthesizeName('$')),
227
t.numericLiteral(fastRefreshState.cacheIndex),
228
- true
228
+ true,
229
),
230
- t.stringLiteral(fastRefreshState.hash)
231
- )
230
+ t.stringLiteral(fastRefreshState.hash),
231
+ ),
232
),
233
- ])
234
- )
233
+ ]),
234
+ ),
235
);
236
}
237
compiled.body.body.unshift(...preface);
@@ -249,16 +249,16 @@ export function codegenFunction(
249
emitInstrumentForget.globalGating != null
250
) {
251
gating = t.logicalExpression(
252
- "&&",
252
+ '&&',
253
t.identifier(emitInstrumentForget.globalGating),
254
- t.identifier(emitInstrumentForget.gating.importSpecifierName)
254
+ t.identifier(emitInstrumentForget.gating.importSpecifierName),
255
);
256
} else if (emitInstrumentForget.gating != null) {
257
gating = t.identifier(emitInstrumentForget.gating.importSpecifierName);
258
} else {
259
CompilerError.invariant(emitInstrumentForget.globalGating != null, {
260
reason:
261
- "Bad config not caught! Expected at least one of gating or globalGating",
261
+ 'Bad config not caught! Expected at least one of gating or globalGating',
262
loc: null,
263
suggestions: null,
264
});
@@ -269,15 +269,15 @@ export function codegenFunction(
269
t.expressionStatement(
270
t.callExpression(
271
t.identifier(emitInstrumentForget.fn.importSpecifierName),
272
- [t.stringLiteral(fn.id), t.stringLiteral(fn.env.filename ?? "")]
273
- )
274
- )
272
+ [t.stringLiteral(fn.id), t.stringLiteral(fn.env.filename ?? '')],
273
+ ),
274
+ ),
275
);
276
compiled.body.body.unshift(test);
277
}
278
279
- const outlined: CodegenFunction["outlined"] = [];
280
- for (const { fn: outlinedFunction, type } of cx.env.getOutlinedFunctions()) {
279
+ const outlined: CodegenFunction['outlined'] = [];
280
+ for (const {fn: outlinedFunction, type} of cx.env.getOutlinedFunctions()) {
281
const reactiveFunction = buildReactiveFunction(outlinedFunction);
282
pruneUnusedLabels(reactiveFunction);
283
pruneUnusedLValues(reactiveFunction);
@@ -287,16 +287,16 @@ export function codegenFunction(
287
const codegen = codegenReactiveFunction(
288
new Context(
289
cx.env,
290
- reactiveFunction.id ?? "[[ anonymous ]]",
290
+ reactiveFunction.id ?? '[[ anonymous ]]',
291
identifiers,
292
- cx.fbtOperands
292
+ cx.fbtOperands,
293
),
294
- reactiveFunction
294
+ reactiveFunction,
295
);
296
if (codegen.isErr()) {
297
return codegen;
298
}
299
- outlined.push({ fn: codegen.unwrap(), type });
299
+ outlined.push({fn: codegen.unwrap(), type});
300
}
301
compiled.outlined = outlined;
302
@@ -305,25 +305,23 @@ export function codegenFunction(
305
306
function codegenReactiveFunction(
307
cx: Context,
308
- fn: ReactiveFunction
308
+ fn: ReactiveFunction,
309
): Result<CodegenFunction, CompilerError> {
310
for (const param of fn.params) {
311
- if (param.kind === "Identifier") {
311
+ if (param.kind === 'Identifier') {
312
cx.temp.set(param.identifier.id, null);
313
} else {
314
cx.temp.set(param.place.identifier.id, null);
315
}
316
}
317
318
- const params = fn.params.map((param) => convertParameter(param));
318
+ const params = fn.params.map(param => convertParameter(param));
319
const body: t.BlockStatement = codegenBlock(cx, fn.body);
320
- body.directives = fn.directives.map((d) =>
321
- t.directive(t.directiveLiteral(d))
322
- );
320
+ body.directives = fn.directives.map(d => t.directive(t.directiveLiteral(d)));
321
const statements = body.body;
322
if (statements.length !== 0) {
323
const last = statements[statements.length - 1];
326
- if (last.type === "ReturnStatement" && last.argument == null) {
324
+ if (last.type === 'ReturnStatement' && last.argument == null) {
325
statements.pop();
326
}
327
}
@@ -336,7 +334,7 @@ function codegenReactiveFunction(
334
visitReactiveFunction(fn, countMemoBlockVisitor, undefined);
335
336
return Ok({
339
- type: "CodegenFunction",
337
+ type: 'CodegenFunction',
338
loc: fn.loc,
339
id: fn.id !== null ? t.identifier(fn.id) : null,
340
params,
@@ -372,7 +370,7 @@ class CountMemoBlockVisitor extends ReactiveFunctionVisitor<void> {
370
371
override visitPrunedScope(
372
scopeBlock: PrunedReactiveScopeBlock,
375
- state: void
373
+ state: void,
374
): void {
375
this.prunedMemoBlocks += 1;
376
this.prunedMemoValues += scopeBlock.scope.declarations.size;
@@ -381,9 +379,9 @@ class CountMemoBlockVisitor extends ReactiveFunctionVisitor<void> {
379
}
380
381
function convertParameter(
384
- param: Place | SpreadPattern
382
+ param: Place | SpreadPattern,
383
): t.Identifier | t.RestElement {
386
- if (param.kind === "Identifier") {
384
+ if (param.kind === 'Identifier') {
385
return convertIdentifier(param.identifier);
386
} else {
387
return t.restElement(convertIdentifier(param.place.identifier));
@@ -407,7 +405,7 @@ class Context {
405
fnName: string,
406
uniqueIdentifiers: Set<string>,
407
fbtOperands: Set<IdentifierId>,
410
- temporaries: Temporaries | null = null
408
+ temporaries: Temporaries | null = null,
409
) {
410
this.env = env;
411
this.fnName = fnName;
@@ -456,7 +454,7 @@ function codegenBlock(cx: Context, block: ReactiveBlock): t.BlockStatement {
454
}
455
CompilerError.invariant(temp.get(key)! === value, {
456
loc: null,
459
- reason: "Expected temporary value to be unchanged",
457
+ reason: 'Expected temporary value to be unchanged',
458
description: null,
459
suggestions: null,
460
});
@@ -474,43 +472,46 @@ function codegenBlock(cx: Context, block: ReactiveBlock): t.BlockStatement {
472
*/
473
function codegenBlockNoReset(
474
cx: Context,
477
- block: ReactiveBlock
475
+ block: ReactiveBlock,
476
): t.BlockStatement {
477
const statements: Array<t.Statement> = [];
478
for (const item of block) {
479
switch (item.kind) {
482
- case "instruction": {
480
+ case 'instruction': {
481
const statement = codegenInstructionNullable(cx, item.instruction);
482
if (statement !== null) {
483
statements.push(statement);
484
}
485
break;
486
}
489
- case "pruned-scope": {
487
+ case 'pruned-scope': {
488
const scopeBlock = codegenBlockNoReset(cx, item.instructions);
489
statements.push(...scopeBlock.body);
490
break;
491
}
494
- case "scope": {
492
+ case 'scope': {
493
const temp = new Map(cx.temp);
494
codegenReactiveScope(cx, statements, item.scope, item.instructions);
495
cx.temp = temp;
496
break;
497
}
500
- case "terminal": {
498
+ case 'terminal': {
499
const statement = codegenTerminal(cx, item.terminal);
500
if (statement === null) {
501
break;
502
}
503
if (item.label !== null && !item.label.implicit) {
504
const block =
507
- statement.type === "BlockStatement" && statement.body.length === 1
505
+ statement.type === 'BlockStatement' && statement.body.length === 1
506
? statement.body[0]
507
: statement;
508
statements.push(
511
- t.labeledStatement(t.identifier(codegenLabel(item.label.id)), block)
509
+ t.labeledStatement(
510
+ t.identifier(codegenLabel(item.label.id)),
511
+ block,
512
+ ),
513
);
513
- } else if (statement.type === "BlockStatement") {
514
+ } else if (statement.type === 'BlockStatement') {
515
statements.push(...statement.body);
516
} else {
517
statements.push(statement);
@@ -520,7 +521,7 @@ function codegenBlockNoReset(
521
default: {
522
assertExhaustive(
523
item,
523
- `Unexpected item kind \`${(item as any).kind}\``
524
+ `Unexpected item kind \`${(item as any).kind}\``,
525
);
526
}
527
}
@@ -532,12 +533,12 @@ function wrapCacheDep(cx: Context, value: t.Expression): t.Expression {
533
if (cx.env.config.enableEmitFreeze != null) {
534
// The import declaration for emitFreeze is inserted in the Babel plugin
535
return t.conditionalExpression(
535
- t.identifier("__DEV__"),
536
+ t.identifier('__DEV__'),
537
t.callExpression(
538
t.identifier(cx.env.config.enableEmitFreeze.importSpecifierName),
538
- [value, t.stringLiteral(cx.fnName)]
539
+ [value, t.stringLiteral(cx.fnName)],
540
),
540
- value
541
+ value,
542
);
543
} else {
544
return value;
@@ -548,7 +549,7 @@ function codegenReactiveScope(
549
cx: Context,
550
statements: Array<t.Statement>,
551
scope: ReactiveScope,
551
- block: ReactiveBlock
552
+ block: ReactiveBlock,
553
): void {
554
const cacheStoreStatements: Array<t.Statement> = [];
555
const cacheLoadStatements: Array<t.Statement> = [];
@@ -564,21 +565,21 @@ function codegenReactiveScope(
565
const index = cx.nextCacheIndex;
566
changeExpressionComments.push(printDependencyComment(dep));
567
const comparison = t.binaryExpression(
567
- "!==",
568
+ '!==',
569
t.memberExpression(
569
- t.identifier(cx.synthesizeName("$")),
570
+ t.identifier(cx.synthesizeName('$')),
571
t.numericLiteral(index),
571
- true
572
+ true,
573
),
573
- codegenDependency(cx, dep)
574
+ codegenDependency(cx, dep),
575
);
576
577
if (cx.env.config.enableChangeVariableCodegen) {
578
const changeIdentifier = t.identifier(cx.synthesizeName(`c_${index}`));
579
statements.push(
579
- t.variableDeclaration("const", [
580
+ t.variableDeclaration('const', [
581
t.variableDeclarator(changeIdentifier, comparison),
581
- ])
582
+ ]),
583
);
584
changeExpressions.push(changeIdentifier);
585
} else {
@@ -591,19 +592,19 @@ function codegenReactiveScope(
592
cacheStoreStatements.push(
593
t.expressionStatement(
594
t.assignmentExpression(
594
- "=",
595
+ '=',
596
t.memberExpression(
596
- t.identifier(cx.synthesizeName("$")),
597
+ t.identifier(cx.synthesizeName('$')),
598
t.numericLiteral(index),
598
- true
599
+ true,
600
),
600
- codegenDependency(cx, dep)
601
- )
602
- )
601
+ codegenDependency(cx, dep),
602
+ ),
603
+ ),
604
);
605
}
606
let firstOutputIndex: number | null = null;
606
- for (const [, { identifier }] of scope.declarations) {
607
+ for (const [, {identifier}] of scope.declarations) {
608
const index = cx.nextCacheIndex;
609
if (firstOutputIndex === null) {
610
firstOutputIndex = index;
@@ -612,7 +613,7 @@ function codegenReactiveScope(
613
CompilerError.invariant(identifier.name != null, {
614
reason: `Expected scope declaration identifier to be named`,
615
description: `Declaration \`${printIdentifier(
615
- identifier
616
+ identifier,
617
)}\` is unnamed in scope @${scope.id}`,
618
loc: null,
619
suggestions: null,
@@ -622,10 +623,10 @@ function codegenReactiveScope(
623
outputComments.push(name.name);
624
if (!cx.hasDeclared(identifier)) {
625
statements.push(
625
- t.variableDeclaration("let", [t.variableDeclarator(name)])
626
+ t.variableDeclaration('let', [t.variableDeclarator(name)]),
627
);
628
}
628
- cacheLoads.push({ name, index, value: wrapCacheDep(cx, name) });
629
+ cacheLoads.push({name, index, value: wrapCacheDep(cx, name)});
630
cx.declare(identifier);
631
}
632
for (const reassignment of scope.reassignments) {
@@ -635,7 +636,7 @@ function codegenReactiveScope(
636
}
637
const name = convertIdentifier(reassignment);
638
outputComments.push(name.name);
638
- cacheLoads.push({ name, index, value: wrapCacheDep(cx, name) });
639
+ cacheLoads.push({name, index, value: wrapCacheDep(cx, name)});
640
}
641
642
let testCondition = (changeExpressions as Array<t.Expression>).reduce(
@@ -643,9 +644,9 @@ function codegenReactiveScope(
644
if (acc == null) {
645
return ident;
646
}
646
- return t.logicalExpression("||", acc, ident);
647
+ return t.logicalExpression('||', acc, ident);
648
},
648
- null as t.Expression | null
649
+ null as t.Expression | null,
650
);
651
if (testCondition === null) {
652
CompilerError.invariant(firstOutputIndex !== null, {
@@ -655,16 +656,16 @@ function codegenReactiveScope(
656
suggestions: null,
657
});
658
testCondition = t.binaryExpression(
658
- "===",
659
+ '===',
660
t.memberExpression(
660
- t.identifier(cx.synthesizeName("$")),
661
+ t.identifier(cx.synthesizeName('$')),
662
t.numericLiteral(firstOutputIndex),
662
- true
663
+ true,
664
),
665
t.callExpression(
665
- t.memberExpression(t.identifier("Symbol"), t.identifier("for")),
666
- [t.stringLiteral(MEMO_CACHE_SENTINEL)]
667
- )
666
+ t.memberExpression(t.identifier('Symbol'), t.identifier('for')),
667
+ [t.stringLiteral(MEMO_CACHE_SENTINEL)],
668
+ ),
669
);
670
}
671
@@ -675,12 +676,12 @@ function codegenReactiveScope(
676
reason: `Expected to not have both change detection enabled and memoization disabled`,
677
description: `Incompatible config options`,
678
loc: null,
678
- }
679
+ },
680
);
681
testCondition = t.logicalExpression(
681
- "||",
682
+ '||',
683
testCondition,
683
- t.booleanLiteral(true)
684
+ t.booleanLiteral(true),
685
);
686
}
687
let computationBlock = codegenBlock(cx, block);
@@ -691,8 +692,8 @@ function codegenReactiveScope(
692
changeExpressions.length > 0
693
) {
694
const loc =
694
- typeof scope.loc === "symbol"
695
- ? "unknown location"
695
+ typeof scope.loc === 'symbol'
696
+ ? 'unknown location'
697
: `(${scope.loc.start.line}:${scope.loc.end.line})`;
698
const detectionFunction =
699
cx.env.config.enableChangeDetectionForDebugging.importSpecifierName;
@@ -700,20 +701,20 @@ function codegenReactiveScope(
701
const changeDetectionStatements: Array<t.Statement> = [];
702
const idempotenceDetectionStatements: Array<t.Statement> = [];
703
703
- for (const { name, index, value } of cacheLoads) {
704
+ for (const {name, index, value} of cacheLoads) {
705
const loadName = cx.synthesizeName(`old$${name.name}`);
706
const slot = t.memberExpression(
706
- t.identifier(cx.synthesizeName("$")),
707
+ t.identifier(cx.synthesizeName('$')),
708
t.numericLiteral(index),
708
- true
709
+ true,
710
);
711
cacheStoreStatements.push(
711
- t.expressionStatement(t.assignmentExpression("=", slot, value))
712
+ t.expressionStatement(t.assignmentExpression('=', slot, value)),
713
);
714
cacheLoadOldValueStatements.push(
714
- t.variableDeclaration("let", [
715
+ t.variableDeclaration('let', [
716
t.variableDeclarator(t.identifier(loadName), slot),
716
- ])
717
+ ]),
718
);
719
changeDetectionStatements.push(
720
t.expressionStatement(
@@ -722,10 +723,10 @@ function codegenReactiveScope(
723
t.cloneNode(name, true),
724
t.stringLiteral(name.name),
725
t.stringLiteral(cx.fnName),
725
- t.stringLiteral("cached"),
726
+ t.stringLiteral('cached'),
727
t.stringLiteral(loc),
727
- ])
728
- )
728
+ ]),
729
+ ),
730
);
731
idempotenceDetectionStatements.push(
732
t.expressionStatement(
@@ -734,28 +735,28 @@ function codegenReactiveScope(
735
t.cloneNode(name, true),
736
t.stringLiteral(name.name),
737
t.stringLiteral(cx.fnName),
737
- t.stringLiteral("recomputed"),
738
+ t.stringLiteral('recomputed'),
739
t.stringLiteral(loc),
739
- ])
740
- )
740
+ ]),
741
+ ),
742
);
743
idempotenceDetectionStatements.push(
743
- t.expressionStatement(t.assignmentExpression("=", name, slot))
744
+ t.expressionStatement(t.assignmentExpression('=', name, slot)),
745
);
746
}
746
- const condition = cx.synthesizeName("condition");
747
+ const condition = cx.synthesizeName('condition');
748
const recomputationBlock = t.cloneNode(computationBlock, true);
749
memoStatement = t.blockStatement([
750
...computationBlock.body,
750
- t.variableDeclaration("let", [
751
+ t.variableDeclaration('let', [
752
t.variableDeclarator(t.identifier(condition), testCondition),
753
]),
754
t.ifStatement(
754
- t.unaryExpression("!", t.identifier(condition)),
755
+ t.unaryExpression('!', t.identifier(condition)),
756
t.blockStatement([
757
...cacheLoadOldValueStatements,
758
...changeDetectionStatements,
758
- ])
759
+ ]),
760
),
761
...cacheStoreStatements,
762
t.ifStatement(
@@ -763,43 +764,43 @@ function codegenReactiveScope(
764
t.blockStatement([
765
...recomputationBlock.body,
766
...idempotenceDetectionStatements,
766
- ])
767
+ ]),
768
),
769
]);
770
} else {
770
- for (const { name, index, value } of cacheLoads) {
771
+ for (const {name, index, value} of cacheLoads) {
772
cacheStoreStatements.push(
773
t.expressionStatement(
774
t.assignmentExpression(
774
- "=",
775
+ '=',
776
t.memberExpression(
776
- t.identifier(cx.synthesizeName("$")),
777
+ t.identifier(cx.synthesizeName('$')),
778
t.numericLiteral(index),
778
- true
779
+ true,
780
),
780
- value
781
- )
782
- )
781
+ value,
782
+ ),
783
+ ),
784
);
785
cacheLoadStatements.push(
786
t.expressionStatement(
787
t.assignmentExpression(
787
- "=",
788
+ '=',
789
name,
790
t.memberExpression(
790
- t.identifier(cx.synthesizeName("$")),
791
+ t.identifier(cx.synthesizeName('$')),
792
t.numericLiteral(index),
792
- true
793
- )
794
- )
795
- )
793
+ true,
794
+ ),
795
+ ),
796
+ ),
797
);
798
}
799
computationBlock.body.push(...cacheStoreStatements);
800
memoStatement = t.ifStatement(
801
testCondition,
802
computationBlock,
802
- t.blockStatement(cacheLoadStatements)
803
+ t.blockStatement(cacheLoadStatements),
804
);
805
}
806
@@ -807,47 +808,47 @@ function codegenReactiveScope(
808
if (changeExpressionComments.length) {
809
t.addComment(
810
memoStatement,
810
- "leading",
811
+ 'leading',
812
` check if ${printDelimitedCommentList(
813
changeExpressionComments,
813
- "or"
814
+ 'or',
815
)} changed`,
815
- true
816
+ true,
817
);
818
t.addComment(
819
memoStatement,
819
- "leading",
820
- ` "useMemo" for ${printDelimitedCommentList(outputComments, "and")}:`,
821
- true
820
+ 'leading',
821
+ ` "useMemo" for ${printDelimitedCommentList(outputComments, 'and')}:`,
822
+ true,
823
);
824
} else {
825
t.addComment(
826
memoStatement,
826
- "leading",
827
- " cache value with no dependencies",
828
- true
827
+ 'leading',
828
+ ' cache value with no dependencies',
829
+ true,
830
);
831
t.addComment(
832
memoStatement,
832
- "leading",
833
- ` "useMemo" for ${printDelimitedCommentList(outputComments, "and")}:`,
834
- true
833
+ 'leading',
834
+ ` "useMemo" for ${printDelimitedCommentList(outputComments, 'and')}:`,
835
+ true,
836
);
837
}
838
if (computationBlock.body.length > 0) {
839
t.addComment(
840
computationBlock.body[0]!,
840
- "leading",
841
+ 'leading',
842
` Inputs changed, recompute`,
842
- true
843
+ true,
844
);
845
}
846
if (cacheLoadStatements.length > 0) {
847
t.addComment(
848
cacheLoadStatements[0]!,
848
- "leading",
849
+ 'leading',
850
` Inputs did not change, use cached value`,
850
- true
851
+ true,
852
);
853
}
854
}
@@ -857,68 +858,68 @@ function codegenReactiveScope(
858
if (earlyReturnValue !== null) {
859
CompilerError.invariant(
860
earlyReturnValue.value.name !== null &&
860
- earlyReturnValue.value.name.kind === "named",
861
+ earlyReturnValue.value.name.kind === 'named',
862
{
863
reason: `Expected early return value to be promoted to a named variable`,
864
loc: earlyReturnValue.loc,
865
description: null,
866
suggestions: null,
866
- }
867
+ },
868
);
869
const name: ValidIdentifierName = earlyReturnValue.value.name.value;
870
statements.push(
871
t.ifStatement(
872
t.binaryExpression(
872
- "!==",
873
+ '!==',
874
t.identifier(name),
875
t.callExpression(
875
- t.memberExpression(t.identifier("Symbol"), t.identifier("for")),
876
- [t.stringLiteral(EARLY_RETURN_SENTINEL)]
877
- )
876
+ t.memberExpression(t.identifier('Symbol'), t.identifier('for')),
877
+ [t.stringLiteral(EARLY_RETURN_SENTINEL)],
878
+ ),
879
),
879
- t.blockStatement([t.returnStatement(t.identifier(name))])
880
- )
880
+ t.blockStatement([t.returnStatement(t.identifier(name))]),
881
+ ),
882
);
883
}
884
}
885
886
function codegenTerminal(
887
cx: Context,
887
- terminal: ReactiveTerminal
888
+ terminal: ReactiveTerminal,
889
): t.Statement | null {
890
switch (terminal.kind) {
890
- case "break": {
891
- if (terminal.targetKind === "implicit") {
891
+ case 'break': {
892
+ if (terminal.targetKind === 'implicit') {
893
return null;
894
}
895
return t.breakStatement(
895
- terminal.targetKind === "labeled"
896
+ terminal.targetKind === 'labeled'
897
? t.identifier(codegenLabel(terminal.target))
897
- : null
898
+ : null,
899
);
900
}
900
- case "continue": {
901
- if (terminal.targetKind === "implicit") {
901
+ case 'continue': {
902
+ if (terminal.targetKind === 'implicit') {
903
return null;
904
}
905
return t.continueStatement(
905
- terminal.targetKind === "labeled"
906
+ terminal.targetKind === 'labeled'
907
? t.identifier(codegenLabel(terminal.target))
907
- : null
908
+ : null,
909
);
910
}
910
- case "for": {
911
+ case 'for': {
912
return t.forStatement(
913
codegenForInit(cx, terminal.init),
914
codegenInstructionValueToExpression(cx, terminal.test),
915
terminal.update !== null
916
? codegenInstructionValueToExpression(cx, terminal.update)
917
: null,
917
- codegenBlock(cx, terminal.loop)
918
+ codegenBlock(cx, terminal.loop),
919
);
920
}
920
- case "for-in": {
921
- CompilerError.invariant(terminal.init.kind === "SequenceExpression", {
921
+ case 'for-in': {
922
+ CompilerError.invariant(terminal.init.kind === 'SequenceExpression', {
923
reason: `Expected a sequence expression init for for..in`,
924
description: `Got \`${terminal.init.kind}\` expression instead`,
925
loc: terminal.init.loc,
@@ -926,7 +927,7 @@ function codegenTerminal(
927
});
928
if (terminal.init.instructions.length !== 2) {
929
CompilerError.throwTodo({
929
- reason: "Support non-trivial for..in inits",
930
+ reason: 'Support non-trivial for..in inits',
931
description: null,
932
loc: terminal.init.loc,
933
suggestions: null,
@@ -936,11 +937,11 @@ function codegenTerminal(
937
const iterableItem = terminal.init.instructions[1];
938
let lval: t.LVal;
939
switch (iterableItem.value.kind) {
939
- case "StoreLocal": {
940
+ case 'StoreLocal': {
941
lval = codegenLValue(cx, iterableItem.value.lvalue.place);
942
break;
943
}
943
- case "Destructure": {
944
+ case 'Destructure': {
945
lval = codegenLValue(cx, iterableItem.value.lvalue.pattern);
946
break;
947
}
@@ -952,32 +953,32 @@ function codegenTerminal(
953
suggestions: null,
954
});
955
}
955
- let varDeclKind: "const" | "let";
956
+ let varDeclKind: 'const' | 'let';
957
switch (iterableItem.value.lvalue.kind) {
958
case InstructionKind.Const:
958
- varDeclKind = "const" as const;
959
+ varDeclKind = 'const' as const;
960
break;
961
case InstructionKind.Let:
961
- varDeclKind = "let" as const;
962
+ varDeclKind = 'let' as const;
963
break;
964
case InstructionKind.Reassign:
965
CompilerError.invariant(false, {
966
reason:
966
- "Destructure should never be Reassign as it would be an Object/ArrayPattern",
967
+ 'Destructure should never be Reassign as it would be an Object/ArrayPattern',
968
description: null,
969
loc: iterableItem.loc,
970
suggestions: null,
971
});
972
case InstructionKind.Catch:
973
CompilerError.invariant(false, {
973
- reason: "Unexpected catch variable as for..in collection",
974
+ reason: 'Unexpected catch variable as for..in collection',
975
description: null,
976
loc: iterableItem.loc,
977
suggestions: null,
978
});
979
case InstructionKind.HoistedConst:
980
CompilerError.invariant(false, {
980
- reason: "Unexpected HoistedConst variable in for..in collection",
981
+ reason: 'Unexpected HoistedConst variable in for..in collection',
982
description: null,
983
loc: iterableItem.loc,
984
suggestions: null,
@@ -985,7 +986,7 @@ function codegenTerminal(
986
default:
987
assertExhaustive(
988
iterableItem.value.lvalue.kind,
988
- `Unhandled lvalue kind: ${iterableItem.value.lvalue.kind}`
989
+ `Unhandled lvalue kind: ${iterableItem.value.lvalue.kind}`,
990
);
991
}
992
return t.forInStatement(
@@ -997,24 +998,24 @@ function codegenTerminal(
998
t.variableDeclarator(lval, null),
999
]),
1000
codegenInstructionValueToExpression(cx, iterableCollection.value),
1000
- codegenBlock(cx, terminal.loop)
1001
+ codegenBlock(cx, terminal.loop),
1002
);
1003
}
1003
- case "for-of": {
1004
+ case 'for-of': {
1005
CompilerError.invariant(
1005
- terminal.init.kind === "SequenceExpression" &&
1006
+ terminal.init.kind === 'SequenceExpression' &&
1007
terminal.init.instructions.length === 1 &&
1007
- terminal.init.instructions[0].value.kind === "GetIterator",
1008
+ terminal.init.instructions[0].value.kind === 'GetIterator',
1009
{
1010
reason: `Expected a single-expression sequence expression init for for..of`,
1011
description: `Got \`${terminal.init.kind}\` expression instead`,
1012
loc: terminal.init.loc,
1013
suggestions: null,
1013
- }
1014
+ },
1015
);
1016
const iterableCollection = terminal.init.instructions[0].value;
1017
1017
- CompilerError.invariant(terminal.test.kind === "SequenceExpression", {
1018
+ CompilerError.invariant(terminal.test.kind === 'SequenceExpression', {
1019
reason: `Expected a sequence expression test for for..of`,
1020
description: `Got \`${terminal.init.kind}\` expression instead`,
1021
loc: terminal.test.loc,
@@ -1022,7 +1023,7 @@ function codegenTerminal(
1023
});
1024
if (terminal.test.instructions.length !== 2) {
1025
CompilerError.throwTodo({
1025
- reason: "Support non-trivial for..of inits",
1026
+ reason: 'Support non-trivial for..of inits',
1027
description: null,
1028
loc: terminal.init.loc,
1029
suggestions: null,
@@ -1031,11 +1032,11 @@ function codegenTerminal(
1032
const iterableItem = terminal.test.instructions[1];
1033
let lval: t.LVal;
1034
switch (iterableItem.value.kind) {
1034
- case "StoreLocal": {
1035
+ case 'StoreLocal': {
1036
lval = codegenLValue(cx, iterableItem.value.lvalue.place);
1037
break;
1038
}
1038
- case "Destructure": {
1039
+ case 'Destructure': {
1040
lval = codegenLValue(cx, iterableItem.value.lvalue.pattern);
1041
break;
1042
}
@@ -1047,32 +1048,32 @@ function codegenTerminal(
1048
suggestions: null,
1049
});
1050
}
1050
- let varDeclKind: "const" | "let";
1051
+ let varDeclKind: 'const' | 'let';
1052
switch (iterableItem.value.lvalue.kind) {
1053
case InstructionKind.Const:
1053
- varDeclKind = "const" as const;
1054
+ varDeclKind = 'const' as const;
1055
break;
1056
case InstructionKind.Let:
1056
- varDeclKind = "let" as const;
1057
+ varDeclKind = 'let' as const;
1058
break;
1059
case InstructionKind.Reassign:
1060
CompilerError.invariant(false, {
1061
reason:
1061
- "Destructure should never be Reassign as it would be an Object/ArrayPattern",
1062
+ 'Destructure should never be Reassign as it would be an Object/ArrayPattern',
1063
description: null,
1064
loc: iterableItem.loc,
1065
suggestions: null,
1066
});
1067
case InstructionKind.Catch:
1068
CompilerError.invariant(false, {
1068
- reason: "Unexpected catch variable as for..of collection",
1069
+ reason: 'Unexpected catch variable as for..of collection',
1070
description: null,
1071
loc: iterableItem.loc,
1072
suggestions: null,
1073
});
1074
case InstructionKind.HoistedConst:
1075
CompilerError.invariant(false, {
1075
- reason: "Unexpected HoistedConst variable in for..of collection",
1076
+ reason: 'Unexpected HoistedConst variable in for..of collection',
1077
description: null,
1078
loc: iterableItem.loc,
1079
suggestions: null,
@@ -1080,7 +1081,7 @@ function codegenTerminal(
1081
default:
1082
assertExhaustive(
1083
iterableItem.value.lvalue.kind,
1083
- `Unhandled lvalue kind: ${iterableItem.value.lvalue.kind}`
1084
+ `Unhandled lvalue kind: ${iterableItem.value.lvalue.kind}`,
1085
);
1086
}
1087
return t.forOfStatement(
@@ -1092,10 +1093,10 @@ function codegenTerminal(
1093
t.variableDeclarator(lval, null),
1094
]),
1095
codegenInstructionValueToExpression(cx, iterableCollection),
1095
- codegenBlock(cx, terminal.loop)
1096
+ codegenBlock(cx, terminal.loop),
1097
);
1098
}
1098
- case "if": {
1099
+ case 'if': {
1100
const test = codegenPlaceToExpression(cx, terminal.test);
1101
const consequent = codegenBlock(cx, terminal.consequent);
1102
let alternate: t.Statement | null = null;
@@ -1107,42 +1108,42 @@ function codegenTerminal(
1108
}
1109
return t.ifStatement(test, consequent, alternate);
1110
}
1110
- case "return": {
1111
+ case 'return': {
1112
const value = codegenPlaceToExpression(cx, terminal.value);
1112
- if (value.type === "Identifier" && value.name === "undefined") {
1113
+ if (value.type === 'Identifier' && value.name === 'undefined') {
1114
// Use implicit undefined
1115
return t.returnStatement();
1116
}
1117
return t.returnStatement(value);
1118
}
1118
- case "switch": {
1119
+ case 'switch': {
1120
return t.switchStatement(
1121
codegenPlaceToExpression(cx, terminal.test),
1121
- terminal.cases.map((case_) => {
1122
+ terminal.cases.map(case_ => {
1123
const test =
1124
case_.test !== null
1125
? codegenPlaceToExpression(cx, case_.test)
1126
: null;
1127
const block = codegenBlock(cx, case_.block!);
1128
return t.switchCase(test, [block]);
1128
- })
1129
+ }),
1130
);
1131
}
1131
- case "throw": {
1132
+ case 'throw': {
1133
return t.throwStatement(codegenPlaceToExpression(cx, terminal.value));
1134
}
1134
- case "do-while": {
1135
+ case 'do-while': {
1136
const test = codegenInstructionValueToExpression(cx, terminal.test);
1137
return t.doWhileStatement(test, codegenBlock(cx, terminal.loop));
1138
}
1138
- case "while": {
1139
+ case 'while': {
1140
const test = codegenInstructionValueToExpression(cx, terminal.test);
1141
return t.whileStatement(test, codegenBlock(cx, terminal.loop));
1142
}
1142
- case "label": {
1143
+ case 'label': {
1144
return codegenBlock(cx, terminal.block);
1145
}
1145
- case "try": {
1146
+ case 'try': {
1147
let catchParam = null;
1148
if (terminal.handlerBinding !== null) {
1149
catchParam = convertIdentifier(terminal.handlerBinding.identifier);
@@ -1150,13 +1151,13 @@ function codegenTerminal(
1151
}
1152
return t.tryStatement(
1153
codegenBlock(cx, terminal.block),
1153
- t.catchClause(catchParam, codegenBlock(cx, terminal.handler))
1154
+ t.catchClause(catchParam, codegenBlock(cx, terminal.handler)),
1155
);
1156
}
1157
default: {
1158
assertExhaustive(
1159
terminal,
1159
- `Unexpected terminal kind \`${(terminal as any).kind}\``
1160
+ `Unexpected terminal kind \`${(terminal as any).kind}\``,
1161
);
1162
}
1163
}
@@ -1164,30 +1165,30 @@ function codegenTerminal(
1165
1166
function codegenInstructionNullable(
1167
cx: Context,
1167
- instr: ReactiveInstruction
1168
+ instr: ReactiveInstruction,
1169
): t.Statement | null {
1170
if (
1170
- instr.value.kind === "StoreLocal" ||
1171
- instr.value.kind === "StoreContext" ||
1172
- instr.value.kind === "Destructure" ||
1173
- instr.value.kind === "DeclareLocal" ||
1174
- instr.value.kind === "DeclareContext"
1171
+ instr.value.kind === 'StoreLocal' ||
1172
+ instr.value.kind === 'StoreContext' ||
1173
+ instr.value.kind === 'Destructure' ||
1174
+ instr.value.kind === 'DeclareLocal' ||
1175
+ instr.value.kind === 'DeclareContext'
1176
) {
1177
let kind: InstructionKind = instr.value.lvalue.kind;
1178
let lvalue: Place | Pattern;
1179
let value: t.Expression | null;
1179
- if (instr.value.kind === "StoreLocal") {
1180
+ if (instr.value.kind === 'StoreLocal') {
1181
kind = cx.hasDeclared(instr.value.lvalue.place.identifier)
1182
? InstructionKind.Reassign
1183
: kind;
1184
lvalue = instr.value.lvalue.place;
1185
value = codegenPlaceToExpression(cx, instr.value.value);
1185
- } else if (instr.value.kind === "StoreContext") {
1186
+ } else if (instr.value.kind === 'StoreContext') {
1187
lvalue = instr.value.lvalue.place;
1188
value = codegenPlaceToExpression(cx, instr.value.value);
1189
} else if (
1189
- instr.value.kind === "DeclareLocal" ||
1190
- instr.value.kind === "DeclareContext"
1190
+ instr.value.kind === 'DeclareLocal' ||
1191
+ instr.value.kind === 'DeclareContext'
1192
) {
1193
if (cx.hasDeclared(instr.value.lvalue.place.identifier)) {
1194
return null;
@@ -1213,7 +1214,7 @@ function codegenInstructionNullable(
1214
if (hasReasign && hasDeclaration) {
1215
CompilerError.invariant(false, {
1216
reason:
1216
- "Encountered a destructuring operation where some identifiers are already declared (reassignments) but others are not (declarations)",
1217
+ 'Encountered a destructuring operation where some identifiers are already declared (reassignments) but others are not (declarations)',
1218
description: null,
1219
loc: instr.loc,
1220
suggestions: null,
@@ -1231,7 +1232,7 @@ function codegenInstructionNullable(
1232
loc: instr.value.loc,
1233
suggestions: null,
1234
});
1234
- return createVariableDeclaration(instr.loc, "const", [
1235
+ return createVariableDeclaration(instr.loc, 'const', [
1236
t.variableDeclarator(codegenLValue(cx, lvalue), value),
1237
]);
1238
}
@@ -1242,30 +1243,30 @@ function codegenInstructionNullable(
1243
loc: instr.value.loc,
1244
suggestions: null,
1245
});
1245
- return createVariableDeclaration(instr.loc, "let", [
1246
+ return createVariableDeclaration(instr.loc, 'let', [
1247
t.variableDeclarator(codegenLValue(cx, lvalue), value),
1248
]);
1249
}
1250
case InstructionKind.Reassign: {
1251
CompilerError.invariant(value !== null, {
1251
- reason: "Expected a value for reassignment",
1252
+ reason: 'Expected a value for reassignment',
1253
description: null,
1254
loc: instr.value.loc,
1255
suggestions: null,
1256
});
1257
const expr = t.assignmentExpression(
1257
- "=",
1258
+ '=',
1259
codegenLValue(cx, lvalue),
1259
- value
1260
+ value,
1261
);
1262
if (instr.lvalue !== null) {
1262
- if (instr.value.kind !== "StoreContext") {
1263
+ if (instr.value.kind !== 'StoreContext') {
1264
cx.temp.set(instr.lvalue.identifier.id, expr);
1265
return null;
1266
} else {
1267
// Handle chained reassignments for context variables
1268
const statement = codegenInstruction(cx, instr, expr);
1268
- if (statement.type === "EmptyStatement") {
1269
+ if (statement.type === 'EmptyStatement') {
1270
return null;
1271
}
1272
return statement;
@@ -1280,7 +1281,7 @@ function codegenInstructionNullable(
1281
case InstructionKind.HoistedConst: {
1282
CompilerError.invariant(false, {
1283
reason:
1283
- "Expected HoistedConsts to have been pruned in PruneHoistedContexts",
1284
+ 'Expected HoistedConsts to have been pruned in PruneHoistedContexts',
1285
description: null,
1286
loc: instr.loc,
1287
suggestions: null,
@@ -1291,15 +1292,15 @@ function codegenInstructionNullable(
1292
}
1293
}
1294
} else if (
1294
- instr.value.kind === "StartMemoize" ||
1295
- instr.value.kind === "FinishMemoize"
1295
+ instr.value.kind === 'StartMemoize' ||
1296
+ instr.value.kind === 'FinishMemoize'
1297
) {
1298
return null;
1298
- } else if (instr.value.kind === "Debugger") {
1299
+ } else if (instr.value.kind === 'Debugger') {
1300
return t.debuggerStatement();
1300
- } else if (instr.value.kind === "ObjectMethod") {
1301
+ } else if (instr.value.kind === 'ObjectMethod') {
1302
CompilerError.invariant(instr.lvalue, {
1302
- reason: "Expected object methods to have a temp lvalue",
1303
+ reason: 'Expected object methods to have a temp lvalue',
1304
loc: null,
1305
suggestions: null,
1306
});
@@ -1308,7 +1309,7 @@ function codegenInstructionNullable(
1309
} else {
1310
const value = codegenInstructionValue(cx, instr.value);
1311
const statement = codegenInstruction(cx, instr, value);
1311
- if (statement.type === "EmptyStatement") {
1312
+ if (statement.type === 'EmptyStatement') {
1313
return null;
1314
}
1315
return statement;
@@ -1317,11 +1318,11 @@ function codegenInstructionNullable(
1318
1319
function codegenForInit(
1320
cx: Context,
1320
- init: ReactiveValue
1321
+ init: ReactiveValue,
1322
): t.Expression | t.VariableDeclaration | null {
1322
- if (init.kind === "SequenceExpression") {
1323
+ if (init.kind === 'SequenceExpression') {
1324
for (const instr of init.instructions) {
1324
- if (instr.value.kind === "DeclareContext") {
1325
+ if (instr.value.kind === 'DeclareContext') {
1326
CompilerError.throwTodo({
1327
reason: `Support for loops where the index variable is a context variable`,
1328
loc: instr.loc,
@@ -1336,31 +1337,31 @@ function codegenForInit(
1337
1338
const body = codegenBlock(
1339
cx,
1339
- init.instructions.map((instruction) => ({
1340
- kind: "instruction",
1340
+ init.instructions.map(instruction => ({
1341
+ kind: 'instruction',
1342
instruction,
1342
- }))
1343
+ })),
1344
).body;
1345
const declarators: Array<t.VariableDeclarator> = [];
1345
- let kind: "let" | "const" = "const";
1346
- body.forEach((instr) => {
1346
+ let kind: 'let' | 'const' = 'const';
1347
+ body.forEach(instr => {
1348
CompilerError.invariant(
1348
- instr.type === "VariableDeclaration" &&
1349
- (instr.kind === "let" || instr.kind === "const"),
1349
+ instr.type === 'VariableDeclaration' &&
1350
+ (instr.kind === 'let' || instr.kind === 'const'),
1351
{
1351
- reason: "Expected a variable declaration",
1352
+ reason: 'Expected a variable declaration',
1353
loc: init.loc,
1354
description: `Got ${instr.type}`,
1355
suggestions: null,
1355
- }
1356
+ },
1357
);
1357
- if (instr.kind === "let") {
1358
- kind = "let";
1358
+ if (instr.kind === 'let') {
1359
+ kind = 'let';
1360
}
1361
declarators.push(...instr.declarations);
1362
});
1363
CompilerError.invariant(declarators.length > 0, {
1363
- reason: "Expected a variable declaration",
1364
+ reason: 'Expected a variable declaration',
1365
loc: init.loc,
1366
description: null,
1367
suggestions: null,
@@ -1384,12 +1385,12 @@ function printDependencyComment(dependency: ReactiveScopeDependency): string {
1385
1386
function printDelimitedCommentList(
1387
items: Array<string>,
1387
- finalCompletion: string
1388
+ finalCompletion: string,
1389
): string {
1390
if (items.length === 2) {
1391
return items.join(` ${finalCompletion} `);
1392
} else if (items.length <= 1) {
1392
- return items.join("");
1393
+ return items.join('');
1394
}
1395
1396
let output = [];
@@ -1403,12 +1404,12 @@ function printDelimitedCommentList(
1404
output.push(item);
1405
}
1406
}
1406
- return output.join("");
1407
+ return output.join('');
1408
}
1409
1410
function codegenDependency(
1411
cx: Context,
1411
- dependency: ReactiveScopeDependency
1412
+ dependency: ReactiveScopeDependency,
1413
): t.Expression {
1414
let object: t.Expression = convertIdentifier(dependency.identifier);
1415
if (dependency.path !== null) {
@@ -1420,7 +1421,7 @@ function codegenDependency(
1421
}
1422
1423
function withLoc<T extends (...args: Array<any>) => t.Node>(
1423
- fn: T
1424
+ fn: T,
1425
): (
1426
loc: SourceLocation | null | undefined,
1427
...args: Parameters<T>
@@ -1461,20 +1462,20 @@ function createHookGuard(
1462
guard: ExternalFunction,
1463
stmts: Array<t.Statement>,
1464
before: GuardKind,
1464
- after: GuardKind
1465
+ after: GuardKind,
1466
): t.TryStatement {
1467
function createHookGuardImpl(kind: number): t.ExpressionStatement {
1468
return t.expressionStatement(
1469
t.callExpression(t.identifier(guard.importSpecifierName), [
1470
t.numericLiteral(kind),
1470
- ])
1471
+ ]),
1472
);
1473
}
1474
1475
return t.tryStatement(
1476
t.blockStatement([createHookGuardImpl(before), ...stmts]),
1477
null,
1477
- t.blockStatement([createHookGuardImpl(after)])
1478
+ t.blockStatement([createHookGuardImpl(after)]),
1479
);
1480
}
1481
@@ -1502,7 +1503,7 @@ function createCallExpression(
1503
callee: t.Expression,
1504
args: Array<t.Expression | t.SpreadElement>,
1505
loc: SourceLocation | null,
1505
- isHook: boolean
1506
+ isHook: boolean,
1507
): t.CallExpression {
1508
const callExpr = t.callExpression(callee, args);
1509
if (loc != null && loc != GeneratedSource) {
@@ -1519,9 +1520,9 @@ function createCallExpression(
1520
hookGuard,
1521
[t.returnStatement(callExpr)],
1522
GuardKind.AllowHook,
1522
- GuardKind.DisallowHook
1523
+ GuardKind.DisallowHook,
1524
),
1524
- ])
1525
+ ]),
1526
);
1527
return t.callExpression(iife, []);
1528
} else {
@@ -1538,7 +1539,7 @@ function codegenLabel(id: BlockId): string {
1539
function codegenInstruction(
1540
cx: Context,
1541
instr: ReactiveInstruction,
1541
- value: t.Expression | t.JSXText
1542
+ value: t.Expression | t.JSXText,
1543
): t.Statement {
1544
if (t.isStatement(value)) {
1545
return value;
@@ -1556,16 +1557,16 @@ function codegenInstruction(
1557
return createExpressionStatement(
1558
instr.loc,
1559
t.assignmentExpression(
1559
- "=",
1560
+ '=',
1561
convertIdentifier(instr.lvalue.identifier),
1561
- expressionValue
1562
- )
1562
+ expressionValue,
1563
+ ),
1564
);
1565
} else {
1565
- return createVariableDeclaration(instr.loc, "const", [
1566
+ return createVariableDeclaration(instr.loc, 'const', [
1567
t.variableDeclarator(
1568
convertIdentifier(instr.lvalue.identifier),
1568
- expressionValue
1569
+ expressionValue,
1570
),
1571
]);
1572
}
@@ -1573,9 +1574,9 @@ function codegenInstruction(
1574
}
1575
1576
function convertValueToExpression(
1576
- value: t.JSXText | t.Expression
1577
+ value: t.JSXText | t.Expression,
1578
): t.Expression {
1578
- if (value.type === "JSXText") {
1579
+ if (value.type === 'JSXText') {
1580
return createStringLiteral(value.loc, value.value);
1581
}
1582
return value;
@@ -1583,7 +1584,7 @@ function convertValueToExpression(
1584
1585
function codegenInstructionValueToExpression(
1586
cx: Context,
1586
- instrValue: ReactiveValue
1587
+ instrValue: ReactiveValue,
1588
): t.Expression {
1589
const value = codegenInstructionValue(cx, instrValue);
1590
return convertValueToExpression(value);
@@ -1591,15 +1592,15 @@ function codegenInstructionValueToExpression(
1592
1593
function codegenInstructionValue(
1594
cx: Context,
1594
- instrValue: ReactiveValue
1595
+ instrValue: ReactiveValue,
1596
): t.Expression | t.JSXText {
1597
let value: t.Expression | t.JSXText;
1598
switch (instrValue.kind) {
1598
- case "ArrayExpression": {
1599
- const elements = instrValue.elements.map((element) => {
1600
- if (element.kind === "Identifier") {
1599
+ case 'ArrayExpression': {
1600
+ const elements = instrValue.elements.map(element => {
1601
+ if (element.kind === 'Identifier') {
1602
return codegenPlaceToExpression(cx, element);
1602
- } else if (element.kind === "Spread") {
1603
+ } else if (element.kind === 'Spread') {
1604
return t.spreadElement(codegenPlaceToExpression(cx, element.place));
1605
} else {
1606
return null;
@@ -1608,62 +1609,62 @@ function codegenInstructionValue(
1609
value = t.arrayExpression(elements);
1610
break;
1611
}
1611
- case "BinaryExpression": {
1612
+ case 'BinaryExpression': {
1613
const left = codegenPlaceToExpression(cx, instrValue.left);
1614
const right = codegenPlaceToExpression(cx, instrValue.right);
1615
value = createBinaryExpression(
1616
instrValue.loc,
1617
instrValue.operator,
1618
left,
1618
- right
1619
+ right,
1620
);
1621
break;
1622
}
1622
- case "UnaryExpression": {
1623
+ case 'UnaryExpression': {
1624
value = t.unaryExpression(
1624
- instrValue.operator as "throw", // todo
1625
- codegenPlaceToExpression(cx, instrValue.value)
1625
+ instrValue.operator as 'throw', // todo
1626
+ codegenPlaceToExpression(cx, instrValue.value),
1627
);
1628
break;
1629
}
1629
- case "Primitive": {
1630
+ case 'Primitive': {
1631
value = codegenValue(cx, instrValue.loc, instrValue.value);
1632
break;
1633
}
1633
- case "CallExpression": {
1634
+ case 'CallExpression': {
1635
if (cx.env.config.enableForest) {
1636
const callee = codegenPlaceToExpression(cx, instrValue.callee);
1636
- const args = instrValue.args.map((arg) => codegenArgument(cx, arg));
1637
+ const args = instrValue.args.map(arg => codegenArgument(cx, arg));
1638
value = t.callExpression(callee, args);
1639
if (instrValue.typeArguments != null) {
1640
value.typeArguments = t.typeParameterInstantiation(
1640
- instrValue.typeArguments
1641
+ instrValue.typeArguments,
1642
);
1643
}
1644
break;
1645
}
1646
const isHook = getHookKind(cx.env, instrValue.callee.identifier) != null;
1647
const callee = codegenPlaceToExpression(cx, instrValue.callee);
1647
- const args = instrValue.args.map((arg) => codegenArgument(cx, arg));
1648
+ const args = instrValue.args.map(arg => codegenArgument(cx, arg));
1649
value = createCallExpression(
1650
cx.env.config,
1651
callee,
1652
args,
1653
instrValue.loc,
1653
- isHook
1654
+ isHook,
1655
);
1656
break;
1657
}
1657
- case "OptionalExpression": {
1658
+ case 'OptionalExpression': {
1659
const optionalValue = codegenInstructionValueToExpression(
1660
cx,
1660
- instrValue.value
1661
+ instrValue.value,
1662
);
1663
switch (optionalValue.type) {
1663
- case "OptionalCallExpression":
1664
- case "CallExpression": {
1664
+ case 'OptionalCallExpression':
1665
+ case 'CallExpression': {
1666
CompilerError.invariant(t.isExpression(optionalValue.callee), {
1666
- reason: "v8 intrinsics are validated during lowering",
1667
+ reason: 'v8 intrinsics are validated during lowering',
1668
description: null,
1669
loc: optionalValue.callee.loc ?? null,
1670
suggestions: null,
@@ -1671,15 +1672,15 @@ function codegenInstructionValue(
1672
value = t.optionalCallExpression(
1673
optionalValue.callee,
1674
optionalValue.arguments,
1674
- instrValue.optional
1675
+ instrValue.optional,
1676
);
1677
break;
1678
}
1678
- case "OptionalMemberExpression":
1679
- case "MemberExpression": {
1679
+ case 'OptionalMemberExpression':
1680
+ case 'MemberExpression': {
1681
const property = optionalValue.property;
1682
CompilerError.invariant(t.isExpression(property), {
1682
- reason: "Private names are validated during lowering",
1683
+ reason: 'Private names are validated during lowering',
1684
description: null,
1685
loc: property.loc ?? null,
1686
suggestions: null,
@@ -1688,14 +1689,14 @@ function codegenInstructionValue(
1689
optionalValue.object,
1690
property,
1691
optionalValue.computed,
1691
- instrValue.optional
1692
+ instrValue.optional,
1693
);
1694
break;
1695
}
1696
default: {
1697
CompilerError.invariant(false, {
1698
reason:
1698
- "Expected an optional value to resolve to a call expression or member expression",
1699
+ 'Expected an optional value to resolve to a call expression or member expression',
1700
description: `Got a \`${optionalValue.type}\``,
1701
loc: instrValue.loc,
1702
suggestions: null,
@@ -1704,7 +1705,7 @@ function codegenInstructionValue(
1705
}
1706
break;
1707
}
1707
- case "MethodCall": {
1708
+ case 'MethodCall': {
1709
const isHook =
1710
getHookKind(cx.env, instrValue.property.identifier) != null;
1711
const memberExpr = codegenPlaceToExpression(cx, instrValue.property);
@@ -1713,68 +1714,68 @@ function codegenInstructionValue(
1714
t.isOptionalMemberExpression(memberExpr),
1715
{
1716
reason:
1716
- "[Codegen] Internal error: MethodCall::property must be an unpromoted + unmemoized MemberExpression. " +
1717
+ '[Codegen] Internal error: MethodCall::property must be an unpromoted + unmemoized MemberExpression. ' +
1718
`Got a \`${memberExpr.type}\``,
1719
description: null,
1720
loc: memberExpr.loc ?? null,
1721
suggestions: null,
1721
- }
1722
+ },
1723
);
1724
CompilerError.invariant(
1725
t.isNodesEquivalent(
1726
memberExpr.object,
1726
- codegenPlaceToExpression(cx, instrValue.receiver)
1727
+ codegenPlaceToExpression(cx, instrValue.receiver),
1728
),
1729
{
1730
reason:
1730
- "[Codegen] Internal error: Forget should always generate MethodCall::property " +
1731
- "as a MemberExpression of MethodCall::receiver",
1731
+ '[Codegen] Internal error: Forget should always generate MethodCall::property ' +
1732
+ 'as a MemberExpression of MethodCall::receiver',
1733
description: null,
1734
loc: memberExpr.loc ?? null,
1735
suggestions: null,
1735
- }
1736
+ },
1737
);
1737
- const args = instrValue.args.map((arg) => codegenArgument(cx, arg));
1738
+ const args = instrValue.args.map(arg => codegenArgument(cx, arg));
1739
value = createCallExpression(
1740
cx.env.config,
1741
memberExpr,
1742
args,
1743
instrValue.loc,
1743
- isHook
1744
+ isHook,
1745
);
1746
break;
1747
}
1747
- case "NewExpression": {
1748
+ case 'NewExpression': {
1749
const callee = codegenPlaceToExpression(cx, instrValue.callee);
1749
- const args = instrValue.args.map((arg) => codegenArgument(cx, arg));
1750
+ const args = instrValue.args.map(arg => codegenArgument(cx, arg));
1751
value = t.newExpression(callee, args);
1752
break;
1753
}
1753
- case "ObjectExpression": {
1754
+ case 'ObjectExpression': {
1755
const properties = [];
1756
for (const property of instrValue.properties) {
1756
- if (property.kind === "ObjectProperty") {
1757
+ if (property.kind === 'ObjectProperty') {
1758
const key = codegenObjectPropertyKey(cx, property.key);
1759
1760
switch (property.type) {
1760
- case "property": {
1761
+ case 'property': {
1762
const value = codegenPlaceToExpression(cx, property.place);
1763
properties.push(
1764
t.objectProperty(
1765
key,
1766
value,
1766
- property.key.kind === "computed",
1767
- key.type === "Identifier" &&
1768
- value.type === "Identifier" &&
1769
- value.name === key.name
1770
- )
1767
+ property.key.kind === 'computed',
1768
+ key.type === 'Identifier' &&
1769
+ value.type === 'Identifier' &&
1770
+ value.name === key.name,
1771
+ ),
1772
);
1773
break;
1774
}
1774
- case "method": {
1775
+ case 'method': {
1776
const method = cx.objectMethods.get(property.place.identifier.id);
1777
CompilerError.invariant(method, {
1777
- reason: "Expected ObjectMethod instruction",
1778
+ reason: 'Expected ObjectMethod instruction',
1779
loc: null,
1780
suggestions: null,
1781
});
@@ -1785,12 +1786,12 @@ function codegenInstructionValue(
1786
const fn = codegenReactiveFunction(
1787
new Context(
1788
cx.env,
1788
- reactiveFunction.id ?? "[[ anonymous ]]",
1789
+ reactiveFunction.id ?? '[[ anonymous ]]',
1790
cx.uniqueIdentifiers,
1791
cx.fbtOperands,
1791
- cx.temp
1792
+ cx.temp,
1793
),
1793
- reactiveFunction
1794
+ reactiveFunction,
1795
).unwrap();
1796
1797
/*
@@ -1798,11 +1799,11 @@ function codegenInstructionValue(
1799
* https://github.com/babel/babel/blob/v7.7.4/packages/babel-types/src/definitions/core.js#L599-L603
1800
*/
1801
const babelNode = t.objectMethod(
1801
- "method",
1802
+ 'method',
1803
key,
1804
fn.params,
1805
fn.body,
1805
- false
1806
+ false,
1807
);
1808
babelNode.async = fn.async;
1809
babelNode.generator = fn.generator;
@@ -1812,49 +1813,49 @@ function codegenInstructionValue(
1813
default:
1814
assertExhaustive(
1815
property.type,
1815
- `Unexpected property type: ${property.type}`
1816
+ `Unexpected property type: ${property.type}`,
1817
);
1818
}
1819
} else {
1820
properties.push(
1820
- t.spreadElement(codegenPlaceToExpression(cx, property.place))
1821
+ t.spreadElement(codegenPlaceToExpression(cx, property.place)),
1822
);
1823
}
1824
}
1825
value = t.objectExpression(properties);
1826
break;
1827
}
1827
- case "JSXText": {
1828
+ case 'JSXText': {
1829
value = createJsxText(instrValue.loc, instrValue.value);
1830
break;
1831
}
1831
- case "JsxExpression": {
1832
+ case 'JsxExpression': {
1833
const attributes: Array<t.JSXAttribute | t.JSXSpreadAttribute> = [];
1834
for (const attribute of instrValue.props) {
1835
attributes.push(codegenJsxAttribute(cx, attribute));
1836
}
1837
let tagValue =
1837
- instrValue.tag.kind === "Identifier"
1838
+ instrValue.tag.kind === 'Identifier'
1839
? codegenPlaceToExpression(cx, instrValue.tag)
1840
: t.stringLiteral(instrValue.tag.name);
1841
let tag: t.JSXIdentifier | t.JSXNamespacedName | t.JSXMemberExpression;
1841
- if (tagValue.type === "Identifier") {
1842
+ if (tagValue.type === 'Identifier') {
1843
tag = createJsxIdentifier(instrValue.tag.loc, tagValue.name);
1843
- } else if (tagValue.type === "MemberExpression") {
1844
+ } else if (tagValue.type === 'MemberExpression') {
1845
tag = convertMemberExpressionToJsx(tagValue);
1846
} else {
1846
- CompilerError.invariant(tagValue.type === "StringLiteral", {
1847
+ CompilerError.invariant(tagValue.type === 'StringLiteral', {
1848
reason: `Expected JSX tag to be an identifier or string, got \`${tagValue.type}\``,
1849
description: null,
1850
loc: tagValue.loc ?? null,
1851
suggestions: null,
1852
});
1852
- if (tagValue.value.indexOf(":") >= 0) {
1853
- const [namespace, name] = tagValue.value.split(":", 2);
1853
+ if (tagValue.value.indexOf(':') >= 0) {
1854
+ const [namespace, name] = tagValue.value.split(':', 2);
1855
tag = createJsxNamespacedName(
1856
instrValue.tag.loc,
1857
createJsxIdentifier(instrValue.tag.loc, namespace),
1857
- createJsxIdentifier(instrValue.tag.loc, name)
1858
+ createJsxIdentifier(instrValue.tag.loc, name),
1859
);
1860
} else {
1861
tag = createJsxIdentifier(instrValue.loc, tagValue.value);
@@ -1862,22 +1863,22 @@ function codegenInstructionValue(
1863
}
1864
let children;
1865
if (
1865
- tagValue.type === "StringLiteral" &&
1866
+ tagValue.type === 'StringLiteral' &&
1867
SINGLE_CHILD_FBT_TAGS.has(tagValue.value)
1868
) {
1869
CompilerError.invariant(instrValue.children != null, {
1870
loc: instrValue.loc,
1870
- reason: "Expected fbt element to have children",
1871
+ reason: 'Expected fbt element to have children',
1872
suggestions: null,
1873
description: null,
1874
});
1874
- children = instrValue.children.map((child) =>
1875
- codegenJsxFbtChildElement(cx, child)
1875
+ children = instrValue.children.map(child =>
1876
+ codegenJsxFbtChildElement(cx, child),
1877
);
1878
} else {
1879
children =
1880
instrValue.children !== null
1880
- ? instrValue.children.map((child) => codegenJsxElement(cx, child))
1881
+ ? instrValue.children.map(child => codegenJsxElement(cx, child))
1882
: [];
1883
}
1884
value = createJsxElement(
@@ -1886,25 +1887,25 @@ function codegenInstructionValue(
1887
instrValue.openingLoc,
1888
tag,
1889
attributes,
1889
- instrValue.children === null
1890
+ instrValue.children === null,
1891
),
1892
instrValue.children !== null
1893
? createJsxClosingElement(instrValue.closingLoc, tag)
1894
: null,
1895
children,
1895
- instrValue.children === null
1896
+ instrValue.children === null,
1897
);
1898
break;
1899
}
1899
- case "JsxFragment": {
1900
+ case 'JsxFragment': {
1901
value = t.jsxFragment(
1902
t.jsxOpeningFragment(),
1903
t.jsxClosingFragment(),
1903
- instrValue.children.map((child) => codegenJsxElement(cx, child))
1904
+ instrValue.children.map(child => codegenJsxElement(cx, child)),
1905
);
1906
break;
1907
}
1907
- case "UnsupportedNode": {
1908
+ case 'UnsupportedNode': {
1909
const node = instrValue.node;
1910
if (!t.isExpression(node)) {
1911
return node as any; // TODO handle statements, jsx fragments
@@ -1912,18 +1913,18 @@ function codegenInstructionValue(
1913
value = node;
1914
break;
1915
}
1915
- case "PropertyStore": {
1916
+ case 'PropertyStore': {
1917
value = t.assignmentExpression(
1917
- "=",
1918
+ '=',
1919
t.memberExpression(
1920
codegenPlaceToExpression(cx, instrValue.object),
1920
- t.identifier(instrValue.property)
1921
+ t.identifier(instrValue.property),
1922
),
1922
- codegenPlaceToExpression(cx, instrValue.value)
1923
+ codegenPlaceToExpression(cx, instrValue.value),
1924
);
1925
break;
1926
}
1926
- case "PropertyLoad": {
1927
+ case 'PropertyLoad': {
1928
const object = codegenPlaceToExpression(cx, instrValue.object);
1929
/*
1930
* We currently only lower single chains of optional memberexpr.
@@ -1932,55 +1933,55 @@ function codegenInstructionValue(
1933
value = t.memberExpression(
1934
object,
1935
t.identifier(instrValue.property),
1935
- undefined
1936
+ undefined,
1937
);
1938
break;
1939
}
1939
- case "PropertyDelete": {
1940
+ case 'PropertyDelete': {
1941
value = t.unaryExpression(
1941
- "delete",
1942
+ 'delete',
1943
t.memberExpression(
1944
codegenPlaceToExpression(cx, instrValue.object),
1944
- t.identifier(instrValue.property)
1945
- )
1945
+ t.identifier(instrValue.property),
1946
+ ),
1947
);
1948
break;
1949
}
1949
- case "ComputedStore": {
1950
+ case 'ComputedStore': {
1951
value = t.assignmentExpression(
1951
- "=",
1952
+ '=',
1953
t.memberExpression(
1954
codegenPlaceToExpression(cx, instrValue.object),
1955
codegenPlaceToExpression(cx, instrValue.property),
1955
- true
1956
+ true,
1957
),
1957
- codegenPlaceToExpression(cx, instrValue.value)
1958
+ codegenPlaceToExpression(cx, instrValue.value),
1959
);
1960
break;
1961
}
1961
- case "ComputedLoad": {
1962
+ case 'ComputedLoad': {
1963
const object = codegenPlaceToExpression(cx, instrValue.object);
1964
const property = codegenPlaceToExpression(cx, instrValue.property);
1965
value = t.memberExpression(object, property, true);
1966
break;
1967
}
1967
- case "ComputedDelete": {
1968
+ case 'ComputedDelete': {
1969
value = t.unaryExpression(
1969
- "delete",
1970
+ 'delete',
1971
t.memberExpression(
1972
codegenPlaceToExpression(cx, instrValue.object),
1973
codegenPlaceToExpression(cx, instrValue.property),
1973
- true
1974
- )
1974
+ true,
1975
+ ),
1976
);
1977
break;
1978
}
1978
- case "LoadLocal":
1979
- case "LoadContext": {
1979
+ case 'LoadLocal':
1980
+ case 'LoadContext': {
1981
value = codegenPlaceToExpression(cx, instrValue.place);
1982
break;
1983
}
1983
- case "FunctionExpression": {
1984
+ case 'FunctionExpression': {
1985
const loweredFunc = instrValue.loweredFunc.func;
1986
const reactiveFunction = buildReactiveFunction(loweredFunc);
1987
pruneUnusedLabels(reactiveFunction);
@@ -1989,18 +1990,18 @@ function codegenInstructionValue(
1990
const fn = codegenReactiveFunction(
1991
new Context(
1992
cx.env,
1992
- reactiveFunction.id ?? "[[ anonymous ]]",
1993
+ reactiveFunction.id ?? '[[ anonymous ]]',
1994
cx.uniqueIdentifiers,
1995
cx.fbtOperands,
1995
- cx.temp
1996
+ cx.temp,
1997
),
1997
- reactiveFunction
1998
+ reactiveFunction,
1999
).unwrap();
1999
- if (instrValue.expr.type === "ArrowFunctionExpression") {
2000
+ if (instrValue.expr.type === 'ArrowFunctionExpression') {
2001
let body: t.BlockStatement | t.Expression = fn.body;
2002
if (body.body.length === 1 && loweredFunc.directives.length == 0) {
2003
const stmt = body.body[0]!;
2003
- if (stmt.type === "ReturnStatement" && stmt.argument != null) {
2004
+ if (stmt.type === 'ReturnStatement' && stmt.argument != null) {
2005
body = stmt.argument;
2006
}
2007
}
@@ -2012,61 +2013,61 @@ function codegenInstructionValue(
2013
fn.params,
2014
fn.body,
2015
fn.generator,
2015
- fn.async
2016
+ fn.async,
2017
);
2018
}
2019
break;
2020
}
2020
- case "TaggedTemplateExpression": {
2021
+ case 'TaggedTemplateExpression': {
2022
value = createTaggedTemplateExpression(
2023
instrValue.loc,
2024
codegenPlaceToExpression(cx, instrValue.tag),
2024
- t.templateLiteral([t.templateElement(instrValue.value)], [])
2025
+ t.templateLiteral([t.templateElement(instrValue.value)], []),
2026
);
2027
break;
2028
}
2028
- case "TypeCastExpression": {
2029
+ case 'TypeCastExpression': {
2030
if (t.isTSType(instrValue.typeAnnotation)) {
2031
value = t.tsAsExpression(
2032
codegenPlaceToExpression(cx, instrValue.value),
2032
- instrValue.typeAnnotation
2033
+ instrValue.typeAnnotation,
2034
);
2035
} else {
2036
value = t.typeCastExpression(
2037
codegenPlaceToExpression(cx, instrValue.value),
2037
- t.typeAnnotation(instrValue.typeAnnotation)
2038
+ t.typeAnnotation(instrValue.typeAnnotation),
2039
);
2040
}
2041
break;
2042
}
2042
- case "LogicalExpression": {
2043
+ case 'LogicalExpression': {
2044
value = createLogicalExpression(
2045
instrValue.loc,
2046
instrValue.operator,
2047
codegenInstructionValueToExpression(cx, instrValue.left),
2047
- codegenInstructionValueToExpression(cx, instrValue.right)
2048
+ codegenInstructionValueToExpression(cx, instrValue.right),
2049
);
2050
break;
2051
}
2051
- case "ConditionalExpression": {
2052
+ case 'ConditionalExpression': {
2053
value = createConditionalExpression(
2054
instrValue.loc,
2055
codegenInstructionValueToExpression(cx, instrValue.test),
2056
codegenInstructionValueToExpression(cx, instrValue.consequent),
2056
- codegenInstructionValueToExpression(cx, instrValue.alternate)
2057
+ codegenInstructionValueToExpression(cx, instrValue.alternate),
2058
);
2059
break;
2060
}
2060
- case "SequenceExpression": {
2061
+ case 'SequenceExpression': {
2062
const body = codegenBlockNoReset(
2063
cx,
2063
- instrValue.instructions.map((instruction) => ({
2064
- kind: "instruction",
2064
+ instrValue.instructions.map(instruction => ({
2065
+ kind: 'instruction',
2066
instruction,
2066
- }))
2067
+ })),
2068
).body;
2068
- const expressions = body.map((stmt) => {
2069
- if (stmt.type === "ExpressionStatement") {
2069
+ const expressions = body.map(stmt => {
2070
+ if (stmt.type === 'ExpressionStatement') {
2071
return stmt.expression;
2072
} else {
2073
if (t.isVariableDeclaration(stmt)) {
@@ -2101,62 +2102,62 @@ function codegenInstructionValue(
2102
}
2103
break;
2104
}
2104
- case "TemplateLiteral": {
2105
+ case 'TemplateLiteral': {
2106
value = createTemplateLiteral(
2107
instrValue.loc,
2107
- instrValue.quasis.map((q) => t.templateElement(q)),
2108
- instrValue.subexprs.map((p) => codegenPlaceToExpression(cx, p))
2108
+ instrValue.quasis.map(q => t.templateElement(q)),
2109
+ instrValue.subexprs.map(p => codegenPlaceToExpression(cx, p)),
2110
);
2111
break;
2112
}
2112
- case "LoadGlobal": {
2113
+ case 'LoadGlobal': {
2114
value = t.identifier(instrValue.binding.name);
2115
break;
2116
}
2116
- case "RegExpLiteral": {
2117
+ case 'RegExpLiteral': {
2118
value = t.regExpLiteral(instrValue.pattern, instrValue.flags);
2119
break;
2120
}
2120
- case "MetaProperty": {
2121
+ case 'MetaProperty': {
2122
value = t.metaProperty(
2123
t.identifier(instrValue.meta),
2123
- t.identifier(instrValue.property)
2124
+ t.identifier(instrValue.property),
2125
);
2126
break;
2127
}
2127
- case "Await": {
2128
+ case 'Await': {
2129
value = t.awaitExpression(codegenPlaceToExpression(cx, instrValue.value));
2130
break;
2131
}
2131
- case "GetIterator": {
2132
+ case 'GetIterator': {
2133
value = codegenPlaceToExpression(cx, instrValue.collection);
2134
break;
2135
}
2135
- case "IteratorNext": {
2136
+ case 'IteratorNext': {
2137
value = codegenPlaceToExpression(cx, instrValue.iterator);
2138
break;
2139
}
2139
- case "NextPropertyOf": {
2140
+ case 'NextPropertyOf': {
2141
value = codegenPlaceToExpression(cx, instrValue.value);
2142
break;
2143
}
2143
- case "PostfixUpdate": {
2144
+ case 'PostfixUpdate': {
2145
value = t.updateExpression(
2146
instrValue.operation,
2147
codegenPlaceToExpression(cx, instrValue.lvalue),
2147
- false
2148
+ false,
2149
);
2150
break;
2151
}
2151
- case "PrefixUpdate": {
2152
+ case 'PrefixUpdate': {
2153
value = t.updateExpression(
2154
instrValue.operation,
2155
codegenPlaceToExpression(cx, instrValue.lvalue),
2155
- true
2156
+ true,
2157
);
2158
break;
2159
}
2159
- case "StoreLocal": {
2160
+ case 'StoreLocal': {
2161
CompilerError.invariant(
2162
instrValue.lvalue.kind === InstructionKind.Reassign,
2163
{
@@ -2164,32 +2165,32 @@ function codegenInstructionValue(
2165
description: null,
2166
loc: instrValue.loc,
2167
suggestions: null,
2167
- }
2168
+ },
2169
);
2170
value = t.assignmentExpression(
2170
- "=",
2171
+ '=',
2172
codegenLValue(cx, instrValue.lvalue.place),
2172
- codegenPlaceToExpression(cx, instrValue.value)
2173
+ codegenPlaceToExpression(cx, instrValue.value),
2174
);
2175
break;
2176
}
2176
- case "StoreGlobal": {
2177
+ case 'StoreGlobal': {
2178
value = t.assignmentExpression(
2178
- "=",
2179
+ '=',
2180
t.identifier(instrValue.name),
2180
- codegenPlaceToExpression(cx, instrValue.value)
2181
+ codegenPlaceToExpression(cx, instrValue.value),
2182
);
2183
break;
2184
}
2184
- case "ReactiveFunctionValue":
2185
- case "StartMemoize":
2186
- case "FinishMemoize":
2187
- case "Debugger":
2188
- case "DeclareLocal":
2189
- case "DeclareContext":
2190
- case "Destructure":
2191
- case "ObjectMethod":
2192
- case "StoreContext": {
2185
+ case 'ReactiveFunctionValue':
2186
+ case 'StartMemoize':
2187
+ case 'FinishMemoize':
2188
+ case 'Debugger':
2189
+ case 'DeclareLocal':
2190
+ case 'DeclareContext':
2191
+ case 'Destructure':
2192
+ case 'ObjectMethod':
2193
+ case 'StoreContext': {
2194
CompilerError.invariant(false, {
2195
reason: `Unexpected ${instrValue.kind} in codegenInstructionValue`,
2196
description: null,
@@ -2200,7 +2201,7 @@ function codegenInstructionValue(
2201
default: {
2202
assertExhaustive(
2203
instrValue,
2203
- `Unexpected instruction value kind \`${(instrValue as any).kind}\``
2204
+ `Unexpected instruction value kind \`${(instrValue as any).kind}\``,
2205
);
2206
}
2207
}
@@ -2222,25 +2223,25 @@ const STRING_REQUIRES_EXPR_CONTAINER_PATTERN =
2223
/[\u{0000}-\u{001F}\u{007F}\u{0080}-\u{FFFF}]|"/u;
2224
function codegenJsxAttribute(
2225
cx: Context,
2225
- attribute: JsxAttribute
2226
+ attribute: JsxAttribute,
2227
): t.JSXAttribute | t.JSXSpreadAttribute {
2228
switch (attribute.kind) {
2228
- case "JsxAttribute": {
2229
+ case 'JsxAttribute': {
2230
let propName: t.JSXIdentifier | t.JSXNamespacedName;
2230
- if (attribute.name.indexOf(":") === -1) {
2231
+ if (attribute.name.indexOf(':') === -1) {
2232
propName = createJsxIdentifier(attribute.place.loc, attribute.name);
2233
} else {
2233
- const [namespace, name] = attribute.name.split(":", 2);
2234
+ const [namespace, name] = attribute.name.split(':', 2);
2235
propName = createJsxNamespacedName(
2236
attribute.place.loc,
2237
createJsxIdentifier(attribute.place.loc, namespace),
2237
- createJsxIdentifier(attribute.place.loc, name)
2238
+ createJsxIdentifier(attribute.place.loc, name),
2239
);
2240
}
2241
const innerValue = codegenPlaceToExpression(cx, attribute.place);
2242
let value;
2243
switch (innerValue.type) {
2243
- case "StringLiteral": {
2244
+ case 'StringLiteral': {
2245
value = innerValue;
2246
if (
2247
STRING_REQUIRES_EXPR_CONTAINER_PATTERN.test(value.value) &&
@@ -2263,15 +2264,15 @@ function codegenJsxAttribute(
2264
}
2265
return createJsxAttribute(attribute.place.loc, propName, value);
2266
}
2266
- case "JsxSpreadAttribute": {
2267
+ case 'JsxSpreadAttribute': {
2268
return t.jsxSpreadAttribute(
2268
- codegenPlaceToExpression(cx, attribute.argument)
2269
+ codegenPlaceToExpression(cx, attribute.argument),
2270
);
2271
}
2272
default: {
2273
assertExhaustive(
2274
attribute,
2274
- `Unexpected attribute kind \`${(attribute as any).kind}\``
2275
+ `Unexpected attribute kind \`${(attribute as any).kind}\``,
2276
);
2277
}
2278
}
@@ -2280,7 +2281,7 @@ function codegenJsxAttribute(
2281
const JSX_TEXT_CHILD_REQUIRES_EXPR_CONTAINER_PATTERN = /[<>&]/;
2282
function codegenJsxElement(
2283
cx: Context,
2283
- place: Place
2284
+ place: Place,
2285
):
2286
| t.JSXText
2287
| t.JSXExpressionContainer
@@ -2289,17 +2290,17 @@ function codegenJsxElement(
2290
| t.JSXFragment {
2291
const value = codegenPlace(cx, place);
2292
switch (value.type) {
2292
- case "JSXText": {
2293
+ case 'JSXText': {
2294
if (JSX_TEXT_CHILD_REQUIRES_EXPR_CONTAINER_PATTERN.test(value.value)) {
2295
return createJsxExpressionContainer(
2296
place.loc,
2296
- createStringLiteral(place.loc, value.value)
2297
+ createStringLiteral(place.loc, value.value),
2298
);
2299
}
2300
return createJsxText(place.loc, value.value);
2301
}
2301
- case "JSXElement":
2302
- case "JSXFragment": {
2302
+ case 'JSXElement':
2303
+ case 'JSXFragment': {
2304
return value;
2305
}
2306
default: {
@@ -2310,7 +2311,7 @@ function codegenJsxElement(
2311
2312
function codegenJsxFbtChildElement(
2313
cx: Context,
2313
- place: Place
2314
+ place: Place,
2315
):
2316
| t.JSXText
2317
| t.JSXExpressionContainer
@@ -2320,8 +2321,8 @@ function codegenJsxFbtChildElement(
2321
const value = codegenPlace(cx, place);
2322
switch (value.type) {
2323
// fbt:param only allows JSX element or expression container as children
2323
- case "JSXText":
2324
- case "JSXElement": {
2324
+ case 'JSXText':
2325
+ case 'JSXElement': {
2326
return value;
2327
}
2328
default: {
@@ -2331,21 +2332,21 @@ function codegenJsxFbtChildElement(
2332
}
2333
2334
function convertMemberExpressionToJsx(
2334
- expr: t.MemberExpression
2335
+ expr: t.MemberExpression,
2336
): t.JSXMemberExpression {
2336
- CompilerError.invariant(expr.property.type === "Identifier", {
2337
- reason: "Expected JSX member expression property to be a string",
2337
+ CompilerError.invariant(expr.property.type === 'Identifier', {
2338
+ reason: 'Expected JSX member expression property to be a string',
2339
description: null,
2340
loc: expr.loc ?? null,
2341
suggestions: null,
2342
});
2343
const property = t.jsxIdentifier(expr.property.name);
2343
- if (expr.object.type === "Identifier") {
2344
+ if (expr.object.type === 'Identifier') {
2345
return t.jsxMemberExpression(t.jsxIdentifier(expr.object.name), property);
2346
} else {
2346
- CompilerError.invariant(expr.object.type === "MemberExpression", {
2347
+ CompilerError.invariant(expr.object.type === 'MemberExpression', {
2348
reason:
2348
- "Expected JSX member expression to be an identifier or nested member expression",
2349
+ 'Expected JSX member expression to be an identifier or nested member expression',
2350
description: null,
2351
loc: expr.object.loc ?? null,
2352
suggestions: null,
@@ -2357,19 +2358,19 @@ function convertMemberExpressionToJsx(
2358
2359
function codegenObjectPropertyKey(
2360
cx: Context,
2360
- key: ObjectPropertyKey
2361
+ key: ObjectPropertyKey,
2362
): t.Expression {
2363
switch (key.kind) {
2363
- case "string": {
2364
+ case 'string': {
2365
return t.stringLiteral(key.name);
2366
}
2366
- case "identifier": {
2367
+ case 'identifier': {
2368
return t.identifier(key.name);
2369
}
2369
- case "computed": {
2370
+ case 'computed': {
2371
const expr = codegenPlace(cx, key.name);
2372
CompilerError.invariant(t.isExpression(expr), {
2372
- reason: "Expected object property key to be an expression",
2373
+ reason: 'Expected object property key to be an expression',
2374
description: null,
2375
loc: key.name.loc,
2376
suggestions: null,
@@ -2381,9 +2382,9 @@ function codegenObjectPropertyKey(
2382
2383
function codegenArrayPattern(
2384
cx: Context,
2384
- pattern: ArrayPattern
2385
+ pattern: ArrayPattern,
2386
): t.ArrayPattern {
2386
- const hasHoles = !pattern.items.every((e) => e.kind !== "Hole");
2387
+ const hasHoles = !pattern.items.every(e => e.kind !== 'Hole');
2388
if (hasHoles) {
2389
const result = t.arrayPattern([]);
2390
/*
@@ -2398,7 +2399,7 @@ function codegenArrayPattern(
2399
* https://github.com/babel/babel/blob/v7.23.0/packages/babel-types/src/definitions/core.ts#L1306-L1311
2400
*/
2401
for (const item of pattern.items) {
2401
- if (item.kind === "Hole") {
2402
+ if (item.kind === 'Hole') {
2403
result.elements.push(null);
2404
} else {
2405
result.elements.push(codegenLValue(cx, item));
@@ -2407,54 +2408,54 @@ function codegenArrayPattern(
2408
return result;
2409
} else {
2410
return t.arrayPattern(
2410
- pattern.items.map((item) => {
2411
- if (item.kind === "Hole") {
2411
+ pattern.items.map(item => {
2412
+ if (item.kind === 'Hole') {
2413
return null;
2414
}
2415
return codegenLValue(cx, item);
2415
- })
2416
+ }),
2417
);
2418
}
2419
}
2420
2421
function codegenLValue(
2422
cx: Context,
2422
- pattern: Pattern | Place | SpreadPattern
2423
+ pattern: Pattern | Place | SpreadPattern,
2424
): t.ArrayPattern | t.ObjectPattern | t.RestElement | t.Identifier {
2425
switch (pattern.kind) {
2425
- case "ArrayPattern": {
2426
+ case 'ArrayPattern': {
2427
return codegenArrayPattern(cx, pattern);
2428
}
2428
- case "ObjectPattern": {
2429
+ case 'ObjectPattern': {
2430
return t.objectPattern(
2430
- pattern.properties.map((property) => {
2431
- if (property.kind === "ObjectProperty") {
2431
+ pattern.properties.map(property => {
2432
+ if (property.kind === 'ObjectProperty') {
2433
const key = codegenObjectPropertyKey(cx, property.key);
2434
const value = codegenLValue(cx, property.place);
2435
return t.objectProperty(
2436
key,
2437
value,
2437
- property.key.kind === "computed",
2438
- key.type === "Identifier" &&
2439
- value.type === "Identifier" &&
2440
- value.name === key.name
2438
+ property.key.kind === 'computed',
2439
+ key.type === 'Identifier' &&
2440
+ value.type === 'Identifier' &&
2441
+ value.name === key.name,
2442
);
2443
} else {
2444
return t.restElement(codegenLValue(cx, property.place));
2445
}
2445
- })
2446
+ }),
2447
);
2448
}
2448
- case "Spread": {
2449
+ case 'Spread': {
2450
return t.restElement(codegenLValue(cx, pattern.place));
2451
}
2451
- case "Identifier": {
2452
+ case 'Identifier': {
2453
return convertIdentifier(pattern.identifier);
2454
}
2455
default: {
2456
assertExhaustive(
2457
pattern,
2457
- `Unexpected pattern kind \`${(pattern as any).kind}\``
2458
+ `Unexpected pattern kind \`${(pattern as any).kind}\``,
2459
);
2460
}
2461
}
@@ -2463,28 +2464,28 @@ function codegenLValue(
2464
function codegenValue(
2465
cx: Context,
2466
loc: SourceLocation,
2466
- value: boolean | number | string | null | undefined
2467
+ value: boolean | number | string | null | undefined,
2468
): t.Expression {
2468
- if (typeof value === "number") {
2469
+ if (typeof value === 'number') {
2470
return t.numericLiteral(value);
2470
- } else if (typeof value === "boolean") {
2471
+ } else if (typeof value === 'boolean') {
2472
return t.booleanLiteral(value);
2472
- } else if (typeof value === "string") {
2473
+ } else if (typeof value === 'string') {
2474
return createStringLiteral(loc, value);
2475
} else if (value === null) {
2476
return t.nullLiteral();
2477
} else if (value === undefined) {
2477
- return t.identifier("undefined");
2478
+ return t.identifier('undefined');
2479
} else {
2479
- assertExhaustive(value, "Unexpected primitive value kind");
2480
+ assertExhaustive(value, 'Unexpected primitive value kind');
2481
}
2482
}
2483
2484
function codegenArgument(
2485
cx: Context,
2485
- arg: Place | SpreadPattern
2486
+ arg: Place | SpreadPattern,
2487
): t.Expression | t.SpreadElement {
2487
- if (arg.kind === "Identifier") {
2488
+ if (arg.kind === 'Identifier') {
2489
return codegenPlaceToExpression(cx, arg);
2490
} else {
2491
return t.spreadElement(codegenPlaceToExpression(cx, arg.place));
@@ -2504,7 +2505,7 @@ function codegenPlace(cx: Context, place: Place): t.Expression | t.JSXText {
2505
CompilerError.invariant(place.identifier.name !== null || tmp !== undefined, {
2506
reason: `[Codegen] No value found for temporary`,
2507
description: `Value for '${printPlace(
2507
- place
2508
+ place,
2509
)}' was not set in the codegen context`,
2510
loc: place.loc,
2511
suggestions: null,
@@ -2516,13 +2517,13 @@ function codegenPlace(cx: Context, place: Place): t.Expression | t.JSXText {
2517
2518
function convertIdentifier(identifier: Identifier): t.Identifier {
2519
CompilerError.invariant(
2519
- identifier.name !== null && identifier.name.kind === "named",
2520
+ identifier.name !== null && identifier.name.kind === 'named',
2521
{
2522
reason: `Expected temporaries to be promoted to named identifiers in an earlier pass`,
2523
loc: GeneratedSource,
2524
description: `identifier ${identifier.id} is unnamed`,
2525
suggestions: null,
2525
- }
2526
+ },
2527
);
2528
return t.identifier(identifier.name.value);
2529
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/CollectReactiveIdentifiers.ts
+6
-6
@@ -12,8 +12,8 @@ import {
12
PrunedReactiveScopeBlock,
13
ReactiveFunction,
14
isPrimitiveType,
15
-} from "../HIR/HIR";
16
-import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors";
15
+} from '../HIR/HIR';
16
+import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
17
18
class Visitor extends ReactiveFunctionVisitor<Set<IdentifierId>> {
19
/*
@@ -23,7 +23,7 @@ class Visitor extends ReactiveFunctionVisitor<Set<IdentifierId>> {
23
override visitLValue(
24
id: InstructionId,
25
lvalue: Place,
26
- state: Set<IdentifierId>
26
+ state: Set<IdentifierId>,
27
): void {
28
this.visitPlace(id, lvalue, state);
29
}
@@ -36,7 +36,7 @@ class Visitor extends ReactiveFunctionVisitor<Set<IdentifierId>> {
36
override visitPlace(
37
_id: InstructionId,
38
place: Place,
39
- state: Set<IdentifierId>
39
+ state: Set<IdentifierId>,
40
): void {
41
if (place.reactive) {
42
state.add(place.identifier.id);
@@ -45,7 +45,7 @@ class Visitor extends ReactiveFunctionVisitor<Set<IdentifierId>> {
45
46
override visitPrunedScope(
47
scopeBlock: PrunedReactiveScopeBlock,
48
- state: Set<IdentifierId>
48
+ state: Set<IdentifierId>,
49
): void {
50
this.traversePrunedScope(scopeBlock, state);
51
@@ -62,7 +62,7 @@ class Visitor extends ReactiveFunctionVisitor<Set<IdentifierId>> {
62
* in `InferReactivePlaces`.
63
*/
64
export function collectReactiveIdentifiers(
65
- fn: ReactiveFunction
65
+ fn: ReactiveFunction,
66
): Set<IdentifierId> {
67
const visitor = new Visitor();
68
const state = new Set<IdentifierId>();
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/CollectReferencedGlobals.ts
+7
-7
@@ -5,9 +5,9 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { visitReactiveFunction } from ".";
9
-import { InstructionId, Place, ReactiveFunction, ReactiveValue } from "../HIR";
10
-import { ReactiveFunctionVisitor } from "./visitors";
8
+import {visitReactiveFunction} from '.';
9
+import {InstructionId, Place, ReactiveFunction, ReactiveValue} from '../HIR';
10
+import {ReactiveFunctionVisitor} from './visitors';
11
12
/**
13
* Returns a set of unique globals (by name) that are referenced transitively within the function.
@@ -22,12 +22,12 @@ class Visitor extends ReactiveFunctionVisitor<Set<string>> {
22
override visitValue(
23
id: InstructionId,
24
value: ReactiveValue,
25
- state: Set<string>
25
+ state: Set<string>,
26
): void {
27
this.traverseValue(id, value, state);
28
- if (value.kind === "FunctionExpression" || value.kind === "ObjectMethod") {
28
+ if (value.kind === 'FunctionExpression' || value.kind === 'ObjectMethod') {
29
this.visitHirFunction(value.loweredFunc.func, state);
30
- } else if (value.kind === "LoadGlobal") {
30
+ } else if (value.kind === 'LoadGlobal') {
31
state.add(value.binding.name);
32
}
33
}
@@ -36,7 +36,7 @@ class Visitor extends ReactiveFunctionVisitor<Set<string>> {
36
_id: InstructionId,
37
_dependencies: Array<Place>,
38
fn: ReactiveFunction,
39
- state: Set<string>
39
+ state: Set<string>,
40
): void {
41
visitReactiveFunction(fn, this, state);
42
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/DeriveMinimalDependencies.ts
+42
-44
@@ -5,10 +5,10 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
9
-import { Identifier, ReactiveScopeDependency } from "../HIR";
10
-import { printIdentifier } from "../HIR/PrintHIR";
11
-import { assertExhaustive } from "../Utils/utils";
8
+import {CompilerError} from '../CompilerError';
9
+import {Identifier, ReactiveScopeDependency} from '../HIR';
10
+import {printIdentifier} from '../HIR/PrintHIR';
11
+import {assertExhaustive} from '../Utils/utils';
12
13
/*
14
* We need to understand optional member expressions only when determining
@@ -69,7 +69,7 @@ export class ReactiveScopeDependencyTree {
69
}
70
71
add(dep: ReactiveScopePropertyDependency, inConditional: boolean): void {
72
- const { path, optionalPath } = dep;
72
+ const {path, optionalPath} = dep;
73
let currNode = this.#getOrCreateRoot(dep.identifier);
74
75
const accessType = inConditional
@@ -111,7 +111,7 @@ export class ReactiveScopeDependencyTree {
111
let currChild = getOrMakeProperty(currNode, property);
112
currChild.accessType = merge(
113
currChild.accessType,
114
- PropertyAccessType.ConditionalAccess
114
+ PropertyAccessType.ConditionalAccess,
115
);
116
currNode = currChild;
117
}
@@ -119,7 +119,7 @@ export class ReactiveScopeDependencyTree {
119
// The final node should be marked as a conditional dependency.
120
currNode.accessType = merge(
121
currNode.accessType,
122
- PropertyAccessType.ConditionalDependency
122
+ PropertyAccessType.ConditionalDependency,
123
);
124
}
125
}
@@ -130,15 +130,15 @@ export class ReactiveScopeDependencyTree {
130
const deps = deriveMinimalDependenciesInSubtree(rootNode);
131
CompilerError.invariant(
132
deps.every(
133
- (dep) => dep.accessType === PropertyAccessType.UnconditionalDependency
133
+ dep => dep.accessType === PropertyAccessType.UnconditionalDependency,
134
),
135
{
136
reason:
137
- "[PropagateScopeDependencies] All dependencies must be reduced to unconditional dependencies.",
137
+ '[PropagateScopeDependencies] All dependencies must be reduced to unconditional dependencies.',
138
description: null,
139
loc: null,
140
suggestions: null,
141
- }
141
+ },
142
);
143
144
for (const dep of deps) {
@@ -155,10 +155,10 @@ export class ReactiveScopeDependencyTree {
155
addDepsFromInnerScope(
156
depsFromInnerScope: ReactiveScopeDependencyTree,
157
innerScopeInConditionalWithinParent: boolean,
158
- checkValidDepIdFn: (dep: ReactiveScopeDependency) => boolean
158
+ checkValidDepIdFn: (dep: ReactiveScopeDependency) => boolean,
159
): void {
160
for (const [id, otherRoot] of depsFromInnerScope.#roots) {
161
- if (!checkValidDepIdFn({ identifier: id, path: [] })) {
161
+ if (!checkValidDepIdFn({identifier: id, path: []})) {
162
continue;
163
}
164
let currRoot = this.#getOrCreateRoot(id);
@@ -172,17 +172,17 @@ export class ReactiveScopeDependencyTree {
172
}
173
174
promoteDepsFromExhaustiveConditionals(
175
- trees: Array<ReactiveScopeDependencyTree>
175
+ trees: Array<ReactiveScopeDependencyTree>,
176
): void {
177
CompilerError.invariant(trees.length > 1, {
178
- reason: "Expected trees to be at least 2 elements long.",
178
+ reason: 'Expected trees to be at least 2 elements long.',
179
description: null,
180
loc: null,
181
suggestions: null,
182
});
183
184
for (const [id, root] of this.#roots) {
185
- const nodesForRootId = mapNonNull(trees, (tree) => {
185
+ const nodesForRootId = mapNonNull(trees, tree => {
186
const node = tree.#roots.get(id);
187
if (node != null && isUnconditional(node.accessType)) {
188
return node;
@@ -193,7 +193,7 @@ export class ReactiveScopeDependencyTree {
193
if (nodesForRootId) {
194
addSubtreeIntersection(
195
root.properties,
196
- nodesForRootId.map((root) => root.properties)
196
+ nodesForRootId.map(root => root.properties),
197
);
198
}
199
}
@@ -209,11 +209,11 @@ export class ReactiveScopeDependencyTree {
209
210
for (const [rootId, rootNode] of this.#roots.entries()) {
211
const rootResults = printSubtree(rootNode, includeAccesses).map(
212
- (result) => `${printIdentifier(rootId)}.${result}`
212
+ result => `${printIdentifier(rootId)}.${result}`,
213
);
214
res.push(rootResults);
215
}
216
- return res.flat().join("\n");
216
+ return res.flat().join('\n');
217
}
218
}
219
@@ -237,10 +237,10 @@ export class ReactiveScopeDependencyTree {
237
* ```
238
*/
239
enum PropertyAccessType {
240
- ConditionalAccess = "ConditionalAccess",
241
- UnconditionalAccess = "UnconditionalAccess",
242
- ConditionalDependency = "ConditionalDependency",
243
- UnconditionalDependency = "UnconditionalDependency",
240
+ ConditionalAccess = 'ConditionalAccess',
241
+ UnconditionalAccess = 'UnconditionalAccess',
242
+ ConditionalDependency = 'ConditionalDependency',
243
+ UnconditionalDependency = 'UnconditionalDependency',
244
}
245
246
const MIN_ACCESS_TYPE = PropertyAccessType.ConditionalAccess;
@@ -259,7 +259,7 @@ function isDependency(access: PropertyAccessType): boolean {
259
260
function merge(
261
access1: PropertyAccessType,
262
- access2: PropertyAccessType
262
+ access2: PropertyAccessType,
263
): PropertyAccessType {
264
const resultIsUnconditional =
265
isUnconditional(access1) || isUnconditional(access2);
@@ -318,17 +318,17 @@ const promoteCondResult = [
318
* @returns a minimal list of dependencies in this subtree.
319
*/
320
function deriveMinimalDependenciesInSubtree(
321
- dep: DependencyNode
321
+ dep: DependencyNode,
322
): Array<ReduceResultNode> {
323
const results: Array<ReduceResultNode> = [];
324
for (const [childName, childNode] of dep.properties) {
325
const childResult = deriveMinimalDependenciesInSubtree(childNode).map(
326
- ({ relativePath, accessType }) => {
326
+ ({relativePath, accessType}) => {
327
return {
328
relativePath: [childName, ...relativePath],
329
accessType,
330
};
331
- }
331
+ },
332
);
333
results.push(...childResult);
334
}
@@ -340,8 +340,8 @@ function deriveMinimalDependenciesInSubtree(
340
case PropertyAccessType.UnconditionalAccess: {
341
if (
342
results.every(
343
- ({ accessType }) =>
344
- accessType === PropertyAccessType.UnconditionalDependency
343
+ ({accessType}) =>
344
+ accessType === PropertyAccessType.UnconditionalDependency,
345
)
346
) {
347
// all children are unconditional dependencies, return them to preserve granularity
@@ -358,8 +358,8 @@ function deriveMinimalDependenciesInSubtree(
358
case PropertyAccessType.ConditionalDependency: {
359
if (
360
results.every(
361
- ({ accessType }) =>
362
- accessType === PropertyAccessType.ConditionalDependency
361
+ ({accessType}) =>
362
+ accessType === PropertyAccessType.ConditionalDependency,
363
)
364
) {
365
/*
@@ -379,7 +379,7 @@ function deriveMinimalDependenciesInSubtree(
379
default: {
380
assertExhaustive(
381
dep.accessType,
382
- "[PropgateScopeDependencies] Unhandled access type!"
382
+ '[PropgateScopeDependencies] Unhandled access type!',
383
);
384
}
385
}
@@ -395,7 +395,7 @@ function demoteSubtreeToConditional(subtree: DependencyNode): void {
395
396
let node;
397
while ((node = stack.pop()) !== undefined) {
398
- const { accessType, properties } = node;
398
+ const {accessType, properties} = node;
399
if (!isUnconditional(accessType)) {
400
// A conditionally accessed node should not have unconditional children
401
continue;
@@ -435,7 +435,7 @@ function demoteSubtreeToConditional(subtree: DependencyNode): void {
435
function addSubtree(
436
currNode: DependencyNode,
437
otherNode: DependencyNode,
438
- demoteOtherNode: boolean
438
+ demoteOtherNode: boolean,
439
): void {
440
let otherType = otherNode.accessType;
441
if (demoteOtherNode) {
@@ -488,11 +488,11 @@ function addSubtree(
488
*/
489
function addSubtreeIntersection(
490
currProperties: Map<string, DependencyNode>,
491
- otherProperties: Array<Map<string, DependencyNode>>
491
+ otherProperties: Array<Map<string, DependencyNode>>,
492
): void {
493
CompilerError.invariant(otherProperties.length > 1, {
494
reason:
495
- "[DeriveMinimalDependencies] Expected otherProperties to be at least 2 elements long.",
495
+ '[DeriveMinimalDependencies] Expected otherProperties to be at least 2 elements long.',
496
description: null,
497
loc: null,
498
suggestions: null,
@@ -506,7 +506,7 @@ function addSubtreeIntersection(
506
*/
507
508
for (const [propertyName, currNode] of currProperties) {
509
- const otherNodes = mapNonNull(otherProperties, (properties) => {
509
+ const otherNodes = mapNonNull(otherProperties, properties => {
510
const node = properties.get(propertyName);
511
if (node != null && isUnconditional(node.accessType)) {
512
return node;
@@ -522,10 +522,10 @@ function addSubtreeIntersection(
522
if (otherNodes) {
523
addSubtreeIntersection(
524
currNode.properties,
525
- otherNodes.map((node) => node.properties)
525
+ otherNodes.map(node => node.properties),
526
);
527
528
- const isDep = otherNodes.some((tree) => isDependency(tree.accessType));
528
+ const isDep = otherNodes.some(tree => isDependency(tree.accessType));
529
const externalAccessType = isDep
530
? PropertyAccessType.UnconditionalDependency
531
: PropertyAccessType.UnconditionalAccess;
@@ -536,7 +536,7 @@ function addSubtreeIntersection(
536
537
function printSubtree(
538
node: DependencyNode,
539
- includeAccesses: boolean
539
+ includeAccesses: boolean,
540
): Array<string> {
541
const results: Array<string> = [];
542
for (const [propertyName, propertyNode] of node.properties) {
@@ -544,16 +544,14 @@ function printSubtree(
544
results.push(`${propertyName} (${propertyNode.accessType})`);
545
}
546
const propertyResults = printSubtree(propertyNode, includeAccesses);
547
- results.push(
548
- ...propertyResults.map((result) => `${propertyName}.${result}`)
549
- );
547
+ results.push(...propertyResults.map(result => `${propertyName}.${result}`));
548
}
549
return results;
550
}
551
552
function getOrMakeProperty(
553
node: DependencyNode,
556
- property: string
554
+ property: string,
555
): DependencyNode {
556
let child = node.properties.get(property);
557
if (child == null) {
@@ -568,7 +566,7 @@ function getOrMakeProperty(
566
567
function mapNonNull<T extends NonNullable<V>, V, U>(
568
arr: Array<U>,
571
- fn: (arg0: U) => T | undefined | null
569
+ fn: (arg0: U) => T | undefined | null,
570
): Array<T> | null {
571
const result = [];
572
for (let i = 0; i < arr.length; i++) {
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/ExtractScopeDeclarationsFromDestructuring.ts
+14
-14
@@ -16,13 +16,13 @@ import {
16
ReactiveScopeBlock,
17
ReactiveStatement,
18
promoteTemporary,
19
-} from "../HIR";
20
-import { eachPatternOperand, mapPatternOperands } from "../HIR/visitors";
19
+} from '../HIR';
20
+import {eachPatternOperand, mapPatternOperands} from '../HIR/visitors';
21
import {
22
ReactiveFunctionTransform,
23
Transformed,
24
visitReactiveFunction,
25
-} from "./visitors";
25
+} from './visitors';
26
27
/*
28
* Destructuring statements may sometimes define some variables which are declared by the scope,
@@ -74,7 +74,7 @@ import {
74
*
75
*/
76
export function extractScopeDeclarationsFromDestructuring(
77
- fn: ReactiveFunction
77
+ fn: ReactiveFunction,
78
): void {
79
const state = new State(fn.env);
80
visitReactiveFunction(fn, new Visitor(), state);
@@ -99,34 +99,34 @@ class Visitor extends ReactiveFunctionTransform<State> {
99
100
override transformInstruction(
101
instruction: ReactiveInstruction,
102
- state: State
102
+ state: State,
103
): Transformed<ReactiveStatement> {
104
this.visitInstruction(instruction, state);
105
106
- if (instruction.value.kind === "Destructure") {
106
+ if (instruction.value.kind === 'Destructure') {
107
const transformed = transformDestructuring(
108
state,
109
instruction,
110
- instruction.value
110
+ instruction.value,
111
);
112
if (transformed) {
113
return {
114
- kind: "replace-many",
115
- value: transformed.map((instruction) => ({
116
- kind: "instruction",
114
+ kind: 'replace-many',
115
+ value: transformed.map(instruction => ({
116
+ kind: 'instruction',
117
instruction,
118
})),
119
};
120
}
121
}
122
- return { kind: "keep" };
122
+ return {kind: 'keep'};
123
}
124
}
125
126
function transformDestructuring(
127
state: State,
128
instr: ReactiveInstruction,
129
- destructure: Destructure
129
+ destructure: Destructure,
130
): null | Array<ReactiveInstruction> {
131
let reassigned: Set<IdentifierId> = new Set();
132
let hasDeclaration = false;
@@ -146,7 +146,7 @@ function transformDestructuring(
146
*/
147
const instructions: Array<ReactiveInstruction> = [];
148
const renamed: Map<Place, Place> = new Map();
149
- mapPatternOperands(destructure.lvalue.pattern, (place) => {
149
+ mapPatternOperands(destructure.lvalue.pattern, place => {
150
if (!reassigned.has(place.identifier.id)) {
151
return place;
152
}
@@ -169,7 +169,7 @@ function transformDestructuring(
169
id: instr.id,
170
lvalue: null,
171
value: {
172
- kind: "StoreLocal",
172
+ kind: 'StoreLocal',
173
lvalue: {
174
kind: InstructionKind.Reassign,
175
place: original,
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/FlattenReactiveLoops.ts
+22
-22
@@ -11,13 +11,13 @@ import {
11
ReactiveStatement,
12
ReactiveTerminal,
13
ReactiveTerminalStatement,
14
-} from "../HIR/HIR";
15
-import { assertExhaustive } from "../Utils/utils";
14
+} from '../HIR/HIR';
15
+import {assertExhaustive} from '../Utils/utils';
16
import {
17
ReactiveFunctionTransform,
18
Transformed,
19
visitReactiveFunction,
20
-} from "./visitors";
20
+} from './visitors';
21
22
/*
23
* Given a reactive function, flattens any scopes contained within a loop construct.
@@ -30,53 +30,53 @@ export function flattenReactiveLoops(fn: ReactiveFunction): void {
30
class Transform extends ReactiveFunctionTransform<boolean> {
31
override transformScope(
32
scope: ReactiveScopeBlock,
33
- isWithinLoop: boolean
33
+ isWithinLoop: boolean,
34
): Transformed<ReactiveStatement> {
35
this.visitScope(scope, isWithinLoop);
36
if (isWithinLoop) {
37
return {
38
- kind: "replace",
38
+ kind: 'replace',
39
value: {
40
- kind: "pruned-scope",
40
+ kind: 'pruned-scope',
41
scope: scope.scope,
42
instructions: scope.instructions,
43
},
44
};
45
} else {
46
- return { kind: "keep" };
46
+ return {kind: 'keep'};
47
}
48
}
49
50
override visitTerminal(
51
stmt: ReactiveTerminalStatement<ReactiveTerminal>,
52
- isWithinLoop: boolean
52
+ isWithinLoop: boolean,
53
): void {
54
switch (stmt.terminal.kind) {
55
// Loop terminals flatten nested scopes
56
- case "do-while":
57
- case "while":
58
- case "for":
59
- case "for-of":
60
- case "for-in": {
56
+ case 'do-while':
57
+ case 'while':
58
+ case 'for':
59
+ case 'for-of':
60
+ case 'for-in': {
61
this.traverseTerminal(stmt, true);
62
break;
63
}
64
// Non-loop terminals passthrough is contextual, inherits the parent isWithinScope
65
- case "try":
66
- case "label":
67
- case "break":
68
- case "continue":
69
- case "if":
70
- case "return":
71
- case "switch":
72
- case "throw": {
65
+ case 'try':
66
+ case 'label':
67
+ case 'break':
68
+ case 'continue':
69
+ case 'if':
70
+ case 'return':
71
+ case 'switch':
72
+ case 'throw': {
73
this.traverseTerminal(stmt, isWithinLoop);
74
break;
75
}
76
default: {
77
assertExhaustive(
78
stmt.terminal,
79
- `Unexpected terminal kind \`${(stmt.terminal as any).kind}\``
79
+ `Unexpected terminal kind \`${(stmt.terminal as any).kind}\``,
80
);
81
}
82
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/FlattenReactiveLoopsHIR.ts
+28
-28
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { BlockId, HIRFunction, PrunedScopeTerminal } from "../HIR";
9
-import { assertExhaustive, retainWhere } from "../Utils/utils";
8
+import {BlockId, HIRFunction, PrunedScopeTerminal} from '../HIR';
9
+import {assertExhaustive, retainWhere} from '../Utils/utils';
10
11
/**
12
* Prunes any reactive scopes that are within a loop (for, while, etc). We don't yet
@@ -18,21 +18,21 @@ import { assertExhaustive, retainWhere } from "../Utils/utils";
18
export function flattenReactiveLoopsHIR(fn: HIRFunction): void {
19
const activeLoops = Array<BlockId>();
20
for (const [, block] of fn.body.blocks) {
21
- retainWhere(activeLoops, (id) => id !== block.id);
22
- const { terminal } = block;
21
+ retainWhere(activeLoops, id => id !== block.id);
22
+ const {terminal} = block;
23
switch (terminal.kind) {
24
- case "do-while":
25
- case "for":
26
- case "for-in":
27
- case "for-of":
28
- case "while": {
24
+ case 'do-while':
25
+ case 'for':
26
+ case 'for-in':
27
+ case 'for-of':
28
+ case 'while': {
29
activeLoops.push(terminal.fallthrough);
30
break;
31
}
32
- case "scope": {
32
+ case 'scope': {
33
if (activeLoops.length !== 0) {
34
block.terminal = {
35
- kind: "pruned-scope",
35
+ kind: 'pruned-scope',
36
block: terminal.block,
37
fallthrough: terminal.fallthrough,
38
id: terminal.id,
@@ -42,28 +42,28 @@ export function flattenReactiveLoopsHIR(fn: HIRFunction): void {
42
}
43
break;
44
}
45
- case "branch":
46
- case "goto":
47
- case "if":
48
- case "label":
49
- case "logical":
50
- case "maybe-throw":
51
- case "optional":
52
- case "pruned-scope":
53
- case "return":
54
- case "sequence":
55
- case "switch":
56
- case "ternary":
57
- case "throw":
58
- case "try":
59
- case "unreachable":
60
- case "unsupported": {
45
+ case 'branch':
46
+ case 'goto':
47
+ case 'if':
48
+ case 'label':
49
+ case 'logical':
50
+ case 'maybe-throw':
51
+ case 'optional':
52
+ case 'pruned-scope':
53
+ case 'return':
54
+ case 'sequence':
55
+ case 'switch':
56
+ case 'ternary':
57
+ case 'throw':
58
+ case 'try':
59
+ case 'unreachable':
60
+ case 'unsupported': {
61
break;
62
}
63
default: {
64
assertExhaustive(
65
terminal,
66
- `Unexpected terminal kind \`${(terminal as any).kind}\``
66
+ `Unexpected terminal kind \`${(terminal as any).kind}\``,
67
);
68
}
69
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/FlattenScopesWithHooksOrUse.ts
+10
-10
@@ -14,12 +14,12 @@ import {
14
ReactiveValue,
15
getHookKind,
16
isUseOperator,
17
-} from "../HIR";
17
+} from '../HIR';
18
import {
19
ReactiveFunctionTransform,
20
Transformed,
21
visitReactiveFunction,
22
-} from "./visitors";
22
+} from './visitors';
23
24
/**
25
* For simplicity the majority of compiler passes do not treat hooks specially. However, hooks are different
@@ -57,7 +57,7 @@ type State = {
57
class Transform extends ReactiveFunctionTransform<State> {
58
override transformScope(
59
scope: ReactiveScopeBlock,
60
- outerState: State
60
+ outerState: State,
61
): Transformed<ReactiveStatement> {
62
const innerState: State = {
63
env: outerState.env,
@@ -72,7 +72,7 @@ class Transform extends ReactiveFunctionTransform<State> {
72
* flatten it away
73
*/
74
return {
75
- kind: "replace-many",
75
+ kind: 'replace-many',
76
value: scope.instructions,
77
};
78
}
@@ -81,26 +81,26 @@ class Transform extends ReactiveFunctionTransform<State> {
81
* mark it as pruned
82
*/
83
return {
84
- kind: "replace",
84
+ kind: 'replace',
85
value: {
86
- kind: "pruned-scope",
86
+ kind: 'pruned-scope',
87
scope: scope.scope,
88
instructions: scope.instructions,
89
},
90
};
91
} else {
92
- return { kind: "keep" };
92
+ return {kind: 'keep'};
93
}
94
}
95
96
override visitValue(
97
id: InstructionId,
98
value: ReactiveValue,
99
- state: State
99
+ state: State,
100
): void {
101
this.traverseValue(id, value, state);
102
switch (value.kind) {
103
- case "CallExpression": {
103
+ case 'CallExpression': {
104
if (
105
getHookKind(state.env, value.callee.identifier) != null ||
106
isUseOperator(value.callee.identifier)
@@ -109,7 +109,7 @@ class Transform extends ReactiveFunctionTransform<State> {
109
}
110
break;
111
}
112
- case "MethodCall": {
112
+ case 'MethodCall': {
113
if (
114
getHookKind(state.env, value.property.identifier) != null ||
115
isUseOperator(value.property.identifier)
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/FlattenScopesWithHooksOrUseHIR.ts
+15
-15
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "..";
8
+import {CompilerError} from '..';
9
import {
10
BlockId,
11
HIRFunction,
@@ -14,8 +14,8 @@ import {
14
ReactiveScope,
15
getHookKind,
16
isUseOperator,
17
-} from "../HIR";
18
-import { retainWhere } from "../Utils/utils";
17
+} from '../HIR';
18
+import {retainWhere} from '../Utils/utils';
19
20
/**
21
* For simplicity the majority of compiler passes do not treat hooks specially. However, hooks are different
@@ -39,31 +39,31 @@ import { retainWhere } from "../Utils/utils";
39
* to ensure the hook call does not inadvertently become conditional.
40
*/
41
export function flattenScopesWithHooksOrUseHIR(fn: HIRFunction): void {
42
- const activeScopes: Array<{ block: BlockId; scope: ReactiveScope }> = [];
42
+ const activeScopes: Array<{block: BlockId; scope: ReactiveScope}> = [];
43
const prune: Array<BlockId> = [];
44
45
for (const [, block] of fn.body.blocks) {
46
const firstId = block.instructions[0]?.id ?? block.terminal.id;
47
- retainWhere(activeScopes, (current) => current.scope.range.end > firstId);
47
+ retainWhere(activeScopes, current => current.scope.range.end > firstId);
48
49
for (const instr of block.instructions) {
50
- const { value } = instr;
50
+ const {value} = instr;
51
switch (value.kind) {
52
- case "MethodCall":
53
- case "CallExpression": {
52
+ case 'MethodCall':
53
+ case 'CallExpression': {
54
const callee =
55
- value.kind === "MethodCall" ? value.property : value.callee;
55
+ value.kind === 'MethodCall' ? value.property : value.callee;
56
if (
57
getHookKind(fn.env, callee.identifier) != null ||
58
isUseOperator(callee.identifier)
59
) {
60
- prune.push(...activeScopes.map((entry) => entry.block));
60
+ prune.push(...activeScopes.map(entry => entry.block));
61
activeScopes.length = 0;
62
}
63
}
64
}
65
}
66
- if (block.terminal.kind === "scope") {
66
+ if (block.terminal.kind === 'scope') {
67
activeScopes.push({
68
block: block.id,
69
scope: block.terminal.scope,
@@ -74,7 +74,7 @@ export function flattenScopesWithHooksOrUseHIR(fn: HIRFunction): void {
74
for (const id of prune) {
75
const block = fn.body.blocks.get(id)!;
76
const terminal = block.terminal;
77
- CompilerError.invariant(terminal.kind === "scope", {
77
+ CompilerError.invariant(terminal.kind === 'scope', {
78
reason: `Expected block to have a scope terminal`,
79
description: `Expected block bb${block.id} to end in a scope terminal`,
80
loc: terminal.loc,
@@ -82,7 +82,7 @@ export function flattenScopesWithHooksOrUseHIR(fn: HIRFunction): void {
82
const body = fn.body.blocks.get(terminal.block)!;
83
if (
84
body.instructions.length === 1 &&
85
- body.terminal.kind === "goto" &&
85
+ body.terminal.kind === 'goto' &&
86
body.terminal.block === terminal.fallthrough
87
) {
88
/*
@@ -91,7 +91,7 @@ export function flattenScopesWithHooksOrUseHIR(fn: HIRFunction): void {
91
* flattening
92
*/
93
block.terminal = {
94
- kind: "label",
94
+ kind: 'label',
95
block: terminal.block,
96
fallthrough: terminal.fallthrough,
97
id: terminal.id,
@@ -101,7 +101,7 @@ export function flattenScopesWithHooksOrUseHIR(fn: HIRFunction): void {
101
}
102
103
block.terminal = {
104
- kind: "pruned-scope",
104
+ kind: 'pruned-scope',
105
block: terminal.block,
106
fallthrough: terminal.fallthrough,
107
id: terminal.id,
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/InferReactiveScopeVariables.ts
+63
-63
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError, SourceLocation } from "..";
9
-import { Environment } from "../HIR";
8
+import {CompilerError, SourceLocation} from '..';
9
+import {Environment} from '../HIR';
10
import {
11
GeneratedSource,
12
HIRFunction,
@@ -15,15 +15,15 @@ import {
15
Place,
16
ReactiveScope,
17
makeInstructionId,
18
-} from "../HIR/HIR";
18
+} from '../HIR/HIR';
19
import {
20
doesPatternContainSpreadElement,
21
eachInstructionOperand,
22
eachPatternOperand,
23
-} from "../HIR/visitors";
24
-import DisjointSet from "../Utils/DisjointSet";
25
-import { logHIRFunction } from "../Utils/logger";
26
-import { assertExhaustive } from "../Utils/utils";
23
+} from '../HIR/visitors';
24
+import DisjointSet from '../Utils/DisjointSet';
25
+import {logHIRFunction} from '../Utils/logger';
26
+import {assertExhaustive} from '../Utils/utils';
27
28
/*
29
* Note: this is the 1st of 4 passes that determine how to break a function into discrete
@@ -118,11 +118,11 @@ export function inferReactiveScopeVariables(fn: HIRFunction): void {
118
scope.range.start = identifier.mutableRange.start;
119
} else if (identifier.mutableRange.start !== 0) {
120
scope.range.start = makeInstructionId(
121
- Math.min(scope.range.start, identifier.mutableRange.start)
121
+ Math.min(scope.range.start, identifier.mutableRange.start),
122
);
123
}
124
scope.range.end = makeInstructionId(
125
- Math.max(scope.range.end, identifier.mutableRange.end)
125
+ Math.max(scope.range.end, identifier.mutableRange.end),
126
);
127
scope.loc = mergeLocation(scope.loc, identifier.loc);
128
}
@@ -136,7 +136,7 @@ export function inferReactiveScopeVariables(fn: HIRFunction): void {
136
maxInstruction = makeInstructionId(Math.max(maxInstruction, instr.id));
137
}
138
maxInstruction = makeInstructionId(
139
- Math.max(maxInstruction, block.terminal.id)
139
+ Math.max(maxInstruction, block.terminal.id),
140
);
141
}
142
@@ -153,7 +153,7 @@ export function inferReactiveScopeVariables(fn: HIRFunction): void {
153
scope.range.end > maxInstruction + 1
154
) {
155
// Make it easier to debug why the error occurred
156
- logHIRFunction("InferReactiveScopeVariables (invalid scope)", fn);
156
+ logHIRFunction('InferReactiveScopeVariables (invalid scope)', fn);
157
CompilerError.invariant(false, {
158
reason: `Invalid mutable range for scope`,
159
loc: GeneratedSource,
@@ -185,76 +185,76 @@ function mergeLocation(l: SourceLocation, r: SourceLocation): SourceLocation {
185
}
186
187
// Is the operand mutable at this given instruction
188
-export function isMutable({ id }: Instruction, place: Place): boolean {
188
+export function isMutable({id}: Instruction, place: Place): boolean {
189
const range = place.identifier.mutableRange;
190
return id >= range.start && id < range.end;
191
}
192
193
function mayAllocate(env: Environment, instruction: Instruction): boolean {
194
- const { value } = instruction;
194
+ const {value} = instruction;
195
switch (value.kind) {
196
- case "Destructure": {
196
+ case 'Destructure': {
197
return doesPatternContainSpreadElement(value.lvalue.pattern);
198
}
199
- case "PostfixUpdate":
200
- case "PrefixUpdate":
201
- case "Await":
202
- case "DeclareLocal":
203
- case "DeclareContext":
204
- case "StoreLocal":
205
- case "LoadGlobal":
206
- case "MetaProperty":
207
- case "TypeCastExpression":
208
- case "LoadLocal":
209
- case "LoadContext":
210
- case "StoreContext":
211
- case "PropertyDelete":
212
- case "ComputedLoad":
213
- case "ComputedDelete":
214
- case "JSXText":
215
- case "TemplateLiteral":
216
- case "Primitive":
217
- case "GetIterator":
218
- case "IteratorNext":
219
- case "NextPropertyOf":
220
- case "Debugger":
221
- case "StartMemoize":
222
- case "FinishMemoize":
223
- case "UnaryExpression":
224
- case "BinaryExpression":
225
- case "PropertyLoad":
226
- case "StoreGlobal": {
199
+ case 'PostfixUpdate':
200
+ case 'PrefixUpdate':
201
+ case 'Await':
202
+ case 'DeclareLocal':
203
+ case 'DeclareContext':
204
+ case 'StoreLocal':
205
+ case 'LoadGlobal':
206
+ case 'MetaProperty':
207
+ case 'TypeCastExpression':
208
+ case 'LoadLocal':
209
+ case 'LoadContext':
210
+ case 'StoreContext':
211
+ case 'PropertyDelete':
212
+ case 'ComputedLoad':
213
+ case 'ComputedDelete':
214
+ case 'JSXText':
215
+ case 'TemplateLiteral':
216
+ case 'Primitive':
217
+ case 'GetIterator':
218
+ case 'IteratorNext':
219
+ case 'NextPropertyOf':
220
+ case 'Debugger':
221
+ case 'StartMemoize':
222
+ case 'FinishMemoize':
223
+ case 'UnaryExpression':
224
+ case 'BinaryExpression':
225
+ case 'PropertyLoad':
226
+ case 'StoreGlobal': {
227
return false;
228
}
229
- case "CallExpression":
230
- case "MethodCall": {
231
- return instruction.lvalue.identifier.type.kind !== "Primitive";
229
+ case 'CallExpression':
230
+ case 'MethodCall': {
231
+ return instruction.lvalue.identifier.type.kind !== 'Primitive';
232
}
233
- case "RegExpLiteral":
234
- case "PropertyStore":
235
- case "ComputedStore":
236
- case "ArrayExpression":
237
- case "JsxExpression":
238
- case "JsxFragment":
239
- case "NewExpression":
240
- case "ObjectExpression":
241
- case "UnsupportedNode":
242
- case "ObjectMethod":
243
- case "FunctionExpression":
244
- case "TaggedTemplateExpression": {
233
+ case 'RegExpLiteral':
234
+ case 'PropertyStore':
235
+ case 'ComputedStore':
236
+ case 'ArrayExpression':
237
+ case 'JsxExpression':
238
+ case 'JsxFragment':
239
+ case 'NewExpression':
240
+ case 'ObjectExpression':
241
+ case 'UnsupportedNode':
242
+ case 'ObjectMethod':
243
+ case 'FunctionExpression':
244
+ case 'TaggedTemplateExpression': {
245
return true;
246
}
247
default: {
248
assertExhaustive(
249
value,
250
- `Unexpected value kind \`${(value as any).kind}\``
250
+ `Unexpected value kind \`${(value as any).kind}\``,
251
);
252
}
253
}
254
}
255
256
export function findDisjointMutableValues(
257
- fn: HIRFunction
257
+ fn: HIRFunction,
258
): DisjointSet<Identifier> {
259
const scopeIdentifiers = new DisjointSet<Identifier>();
260
for (const [_, block] of fn.body.blocks) {
@@ -286,8 +286,8 @@ export function findDisjointMutableValues(
286
operands.push(instr.lvalue!.identifier);
287
}
288
if (
289
- instr.value.kind === "StoreLocal" ||
290
- instr.value.kind === "StoreContext"
289
+ instr.value.kind === 'StoreLocal' ||
290
+ instr.value.kind === 'StoreContext'
291
) {
292
if (
293
instr.value.lvalue.place.identifier.mutableRange.end >
@@ -301,7 +301,7 @@ export function findDisjointMutableValues(
301
) {
302
operands.push(instr.value.value.identifier);
303
}
304
- } else if (instr.value.kind === "Destructure") {
304
+ } else if (instr.value.kind === 'Destructure') {
305
for (const place of eachPatternOperand(instr.value.lvalue.pattern)) {
306
if (
307
place.identifier.mutableRange.end >
@@ -316,7 +316,7 @@ export function findDisjointMutableValues(
316
) {
317
operands.push(instr.value.value.identifier);
318
}
319
- } else if (instr.value.kind === "MethodCall") {
319
+ } else if (instr.value.kind === 'MethodCall') {
320
for (const operand of eachInstructionOperand(instr)) {
321
if (
322
isMutable(instr, operand) &&
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/MemoizeFbtAndMacroOperandsInSameScope.ts
+29
-29
@@ -11,8 +11,8 @@ import {
11
makeInstructionId,
12
Place,
13
ReactiveValue,
14
-} from "../HIR";
15
-import { eachReactiveValueOperand } from "./visitors";
14
+} from '../HIR';
15
+import {eachReactiveValueOperand} from './visitors';
16
17
/**
18
* This pass supports the `fbt` translation system (https://facebook.github.io/fbt/)
@@ -40,7 +40,7 @@ import { eachReactiveValueOperand } from "./visitors";
40
* `customMacros` environment configuration.
41
*/
42
export function memoizeFbtAndMacroOperandsInSameScope(
43
- fn: HIRFunction
43
+ fn: HIRFunction,
44
): Set<IdentifierId> {
45
const fbtMacroTags = new Set([
46
...FBT_TAGS,
@@ -58,30 +58,30 @@ export function memoizeFbtAndMacroOperandsInSameScope(
58
}
59
60
export const FBT_TAGS: Set<string> = new Set([
61
- "fbt",
62
- "fbt:param",
63
- "fbs",
64
- "fbs:param",
61
+ 'fbt',
62
+ 'fbt:param',
63
+ 'fbs',
64
+ 'fbs:param',
65
]);
66
export const SINGLE_CHILD_FBT_TAGS: Set<string> = new Set([
67
- "fbt:param",
68
- "fbs:param",
67
+ 'fbt:param',
68
+ 'fbs:param',
69
]);
70
71
function visit(
72
fn: HIRFunction,
73
fbtMacroTags: Set<string>,
74
- fbtValues: Set<IdentifierId>
74
+ fbtValues: Set<IdentifierId>,
75
): void {
76
for (const [, block] of fn.body.blocks) {
77
for (const instruction of block.instructions) {
78
- const { lvalue, value } = instruction;
78
+ const {lvalue, value} = instruction;
79
if (lvalue === null) {
80
continue;
81
}
82
if (
83
- value.kind === "Primitive" &&
84
- typeof value.value === "string" &&
83
+ value.kind === 'Primitive' &&
84
+ typeof value.value === 'string' &&
85
fbtMacroTags.has(value.value)
86
) {
87
/*
@@ -90,7 +90,7 @@ function visit(
90
*/
91
fbtValues.add(lvalue.identifier.id);
92
} else if (
93
- value.kind === "LoadGlobal" &&
93
+ value.kind === 'LoadGlobal' &&
94
fbtMacroTags.has(value.binding.name)
95
) {
96
// Record references to `fbt` as a global
@@ -113,8 +113,8 @@ function visit(
113
fbtScope.range.start = makeInstructionId(
114
Math.min(
115
fbtScope.range.start,
116
- operand.identifier.mutableRange.start
117
- )
116
+ operand.identifier.mutableRange.start,
117
+ ),
118
);
119
fbtValues.add(operand.identifier.id);
120
}
@@ -139,8 +139,8 @@ function visit(
139
fbtScope.range.start = makeInstructionId(
140
Math.min(
141
fbtScope.range.start,
142
- operand.identifier.mutableRange.start
143
- )
142
+ operand.identifier.mutableRange.start,
143
+ ),
144
);
145
146
/*
@@ -158,7 +158,7 @@ function visit(
158
for (const operand of eachReactiveValueOperand(value)) {
159
if (
160
operand.identifier.name !== null &&
161
- operand.identifier.name.kind === "named"
161
+ operand.identifier.name.kind === 'named'
162
) {
163
/*
164
* named identifiers were already locals, we only have to force temporaries
@@ -172,8 +172,8 @@ function visit(
172
fbtScope.range.start = makeInstructionId(
173
Math.min(
174
fbtScope.range.start,
175
- operand.identifier.mutableRange.start
176
- )
175
+ operand.identifier.mutableRange.start,
176
+ ),
177
);
178
}
179
}
@@ -183,33 +183,33 @@ function visit(
183
184
function isFbtCallExpression(
185
fbtValues: Set<IdentifierId>,
186
- value: ReactiveValue
186
+ value: ReactiveValue,
187
): boolean {
188
return (
189
- value.kind === "CallExpression" && fbtValues.has(value.callee.identifier.id)
189
+ value.kind === 'CallExpression' && fbtValues.has(value.callee.identifier.id)
190
);
191
}
192
193
function isFbtJsxExpression(
194
fbtMacroTags: Set<string>,
195
fbtValues: Set<IdentifierId>,
196
- value: ReactiveValue
196
+ value: ReactiveValue,
197
): boolean {
198
return (
199
- value.kind === "JsxExpression" &&
200
- ((value.tag.kind === "Identifier" &&
199
+ value.kind === 'JsxExpression' &&
200
+ ((value.tag.kind === 'Identifier' &&
201
fbtValues.has(value.tag.identifier.id)) ||
202
- (value.tag.kind === "BuiltinTag" && fbtMacroTags.has(value.tag.name)))
202
+ (value.tag.kind === 'BuiltinTag' && fbtMacroTags.has(value.tag.name)))
203
);
204
}
205
206
function isFbtJsxChild(
207
fbtValues: Set<IdentifierId>,
208
lvalue: Place | null,
209
- value: ReactiveValue
209
+ value: ReactiveValue,
210
): boolean {
211
return (
212
- (value.kind === "JsxExpression" || value.kind === "JsxFragment") &&
212
+ (value.kind === 'JsxExpression' || value.kind === 'JsxFragment') &&
213
lvalue !== null &&
214
fbtValues.has(lvalue.identifier.id)
215
);
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/MergeOverlappingReactiveScopes.ts
+17
-17
@@ -14,11 +14,11 @@ import {
14
ReactiveInstruction,
15
ReactiveScope,
16
ScopeId,
17
-} from "../HIR";
18
-import DisjointSet from "../Utils/DisjointSet";
19
-import { retainWhere } from "../Utils/utils";
20
-import { getPlaceScope } from "./BuildReactiveBlocks";
21
-import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors";
17
+} from '../HIR';
18
+import DisjointSet from '../Utils/DisjointSet';
19
+import {retainWhere} from '../Utils/utils';
20
+import {getPlaceScope} from './BuildReactiveBlocks';
21
+import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
22
23
/*
24
* Note: this is the 3rd of 4 passes that determine how to break a function into discrete
@@ -120,12 +120,12 @@ class Visitor extends ReactiveFunctionVisitor<Context> {
120
}
121
override visitInstruction(
122
instruction: ReactiveInstruction,
123
- state: Context
123
+ state: Context,
124
): void {
125
if (
126
- instruction.value.kind === "ConditionalExpression" ||
127
- instruction.value.kind === "LogicalExpression" ||
128
- instruction.value.kind === "OptionalExpression"
126
+ instruction.value.kind === 'ConditionalExpression' ||
127
+ instruction.value.kind === 'LogicalExpression' ||
128
+ instruction.value.kind === 'OptionalExpression'
129
) {
130
state.enter(() => {
131
super.visitInstruction(instruction, state);
@@ -154,7 +154,7 @@ class Context {
154
155
visitId(id: InstructionId): void {
156
const currentBlock = this.scopes[this.scopes.length - 1]!;
157
- retainWhere(currentBlock.scopes, (pending) => {
157
+ retainWhere(currentBlock.scopes, pending => {
158
if (pending.scope.range.end > id) {
159
return true;
160
} else {
@@ -175,7 +175,7 @@ class Context {
175
if (!this.seenScopes.has(scope.id)) {
176
this.seenScopes.add(scope.id);
177
currentBlock.seen.add(scope.id);
178
- currentBlock.scopes.push({ shadowedBy: null, scope });
178
+ currentBlock.scopes.push({shadowedBy: null, scope});
179
return;
180
}
181
// Scope has already been seen, find it in the current block or a parent
@@ -186,7 +186,7 @@ class Context {
186
* scopes that cross control-flow boundaries are merged with overlapping
187
* scopes
188
*/
189
- this.joinedScopes.union([scope, ...nextBlock.scopes.map((s) => s.scope)]);
189
+ this.joinedScopes.union([scope, ...nextBlock.scopes.map(s => s.scope)]);
190
index--;
191
if (index < 0) {
192
/*
@@ -213,7 +213,7 @@ class Context {
213
* }
214
*/
215
currentBlock.seen.add(scope.id);
216
- currentBlock.scopes.push({ shadowedBy: null, scope });
216
+ currentBlock.scopes.push({shadowedBy: null, scope});
217
return;
218
}
219
nextBlock = this.scopes[index]!;
@@ -240,7 +240,7 @@ class Context {
240
* a scope relative to its eventual post-merge mutable range
241
*/
242
const end = makeInstructionId(
243
- Math.max(current.scope.range.end, scope.range.end)
243
+ Math.max(current.scope.range.end, scope.range.end),
244
);
245
current.scope.range.end = end;
246
scope.range.end = end;
@@ -250,7 +250,7 @@ class Context {
250
}
251
if (!currentBlock.seen.has(scope.id)) {
252
currentBlock.seen.add(scope.id);
253
- currentBlock.scopes.push({ shadowedBy: null, scope });
253
+ currentBlock.scopes.push({shadowedBy: null, scope});
254
}
255
}
256
@@ -264,10 +264,10 @@ class Context {
264
this.joinedScopes.forEach((scope, groupScope) => {
265
if (scope !== groupScope) {
266
groupScope.range.start = makeInstructionId(
267
- Math.min(groupScope.range.start, scope.range.start)
267
+ Math.min(groupScope.range.start, scope.range.start),
268
);
269
groupScope.range.end = makeInstructionId(
270
- Math.max(groupScope.range.end, scope.range.end)
270
+ Math.max(groupScope.range.end, scope.range.end),
271
);
272
}
273
});
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/MergeReactiveScopesThatInvalidateTogether.ts
+54
-54
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "..";
8
+import {CompilerError} from '..';
9
import {
10
IdentifierId,
11
InstructionId,
@@ -20,22 +20,22 @@ import {
20
ReactiveStatement,
21
Type,
22
makeInstructionId,
23
-} from "../HIR";
23
+} from '../HIR';
24
import {
25
BuiltInArrayId,
26
BuiltInFunctionId,
27
BuiltInJsxId,
28
BuiltInObjectId,
29
-} from "../HIR/ObjectShape";
30
-import { eachInstructionLValue } from "../HIR/visitors";
31
-import { assertExhaustive } from "../Utils/utils";
32
-import { printReactiveScopeSummary } from "./PrintReactiveFunction";
29
+} from '../HIR/ObjectShape';
30
+import {eachInstructionLValue} from '../HIR/visitors';
31
+import {assertExhaustive} from '../Utils/utils';
32
+import {printReactiveScopeSummary} from './PrintReactiveFunction';
33
import {
34
ReactiveFunctionTransform,
35
ReactiveFunctionVisitor,
36
Transformed,
37
visitReactiveFunction,
38
-} from "./visitors";
38
+} from './visitors';
39
40
/*
41
* The primary goal of this pass is to reduce memoization overhead, specifically:
@@ -82,7 +82,7 @@ import {
82
* better to flatten.
83
*/
84
export function mergeReactiveScopesThatInvalidateTogether(
85
- fn: ReactiveFunction
85
+ fn: ReactiveFunction,
86
): void {
87
const lastUsageVisitor = new FindLastUsageVisitor();
88
visitReactiveFunction(fn, lastUsageVisitor, undefined);
@@ -119,22 +119,22 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
119
120
override transformScope(
121
scopeBlock: ReactiveScopeBlock,
122
- state: ReactiveScopeDependencies | null
122
+ state: ReactiveScopeDependencies | null,
123
): Transformed<ReactiveStatement> {
124
this.visitScope(scopeBlock, scopeBlock.scope.dependencies);
125
if (
126
state !== null &&
127
areEqualDependencies(state, scopeBlock.scope.dependencies)
128
) {
129
- return { kind: "replace-many", value: scopeBlock.instructions };
129
+ return {kind: 'replace-many', value: scopeBlock.instructions};
130
} else {
131
- return { kind: "keep" };
131
+ return {kind: 'keep'};
132
}
133
}
134
135
override visitBlock(
136
block: ReactiveBlock,
137
- state: ReactiveScopeDependencies | null
137
+ state: ReactiveScopeDependencies | null,
138
): void {
139
// Pass 1: visit nested blocks to potentially merge their scopes
140
this.traverseBlock(block, state);
@@ -152,7 +152,7 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
152
CompilerError.invariant(current !== null, {
153
loc: null,
154
reason:
155
- "MergeConsecutiveScopes: expected current scope to be non-null if reset()",
155
+ 'MergeConsecutiveScopes: expected current scope to be non-null if reset()',
156
suggestions: null,
157
description: null,
158
});
@@ -164,37 +164,37 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
164
for (let i = 0; i < block.length; i++) {
165
const instr = block[i]!;
166
switch (instr.kind) {
167
- case "terminal": {
167
+ case 'terminal': {
168
// For now we don't merge across terminals
169
if (current !== null) {
170
log(
171
- `Reset scope @${current.block.scope.id} from terminal [${instr.terminal.id}]`
171
+ `Reset scope @${current.block.scope.id} from terminal [${instr.terminal.id}]`,
172
);
173
reset();
174
}
175
break;
176
}
177
- case "pruned-scope": {
177
+ case 'pruned-scope': {
178
// For now we don't merge across pruned scopes
179
if (current !== null) {
180
log(
181
- `Reset scope @${current.block.scope.id} from pruned scope @${instr.scope.id}`
181
+ `Reset scope @${current.block.scope.id} from pruned scope @${instr.scope.id}`,
182
);
183
reset();
184
}
185
break;
186
}
187
- case "instruction": {
187
+ case 'instruction': {
188
switch (instr.instruction.value.kind) {
189
- case "BinaryExpression":
190
- case "ComputedLoad":
191
- case "JSXText":
192
- case "LoadGlobal":
193
- case "LoadLocal":
194
- case "Primitive":
195
- case "PropertyLoad":
196
- case "TemplateLiteral":
197
- case "UnaryExpression": {
189
+ case 'BinaryExpression':
190
+ case 'ComputedLoad':
191
+ case 'JSXText':
192
+ case 'LoadGlobal':
193
+ case 'LoadLocal':
194
+ case 'Primitive':
195
+ case 'PropertyLoad':
196
+ case 'TemplateLiteral':
197
+ case 'UnaryExpression': {
198
/*
199
* We can merge two scopes if there are intervening instructions, but:
200
* - Only if the instructions are simple and it's okay to make them
@@ -208,7 +208,7 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
208
}
209
break;
210
}
211
- case "StoreLocal": {
211
+ case 'StoreLocal': {
212
/**
213
* It's safe to have intervening StoreLocal instructions _if_ they are const
214
* and the last usage of the variable is at or before the next scope. This is
@@ -222,13 +222,13 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
222
instr.instruction.value.lvalue.kind === InstructionKind.Const
223
) {
224
for (const lvalue of eachInstructionLValue(
225
- instr.instruction
225
+ instr.instruction,
226
)) {
227
current.lvalues.add(lvalue.identifier.id);
228
}
229
} else {
230
log(
231
- `Reset scope @${current.block.scope.id} from StoreLocal in [${instr.instruction.id}]`
231
+ `Reset scope @${current.block.scope.id} from StoreLocal in [${instr.instruction.id}]`,
232
);
233
reset();
234
}
@@ -239,7 +239,7 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
239
// Other instructions are known to prevent merging, so we reset the scope if present
240
if (current !== null) {
241
log(
242
- `Reset scope @${current.block.scope.id} from instruction [${instr.instruction.id}]`
242
+ `Reset scope @${current.block.scope.id} from instruction [${instr.instruction.id}]`,
243
);
244
reset();
245
}
@@ -247,23 +247,23 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
247
}
248
break;
249
}
250
- case "scope": {
250
+ case 'scope': {
251
if (
252
current !== null &&
253
canMergeScopes(current.block, instr) &&
254
areLValuesLastUsedByScope(
255
instr.scope,
256
current.lvalues,
257
- this.lastUsage
257
+ this.lastUsage,
258
)
259
) {
260
// The current and next scopes can merge!
261
log(
262
- `Can merge scope @${current.block.scope.id} with @${instr.scope.id}`
262
+ `Can merge scope @${current.block.scope.id} with @${instr.scope.id}`,
263
);
264
// Update the merged scope's range
265
current.block.scope.range.end = makeInstructionId(
266
- Math.max(current.block.scope.range.end, instr.scope.range.end)
266
+ Math.max(current.block.scope.range.end, instr.scope.range.end),
267
);
268
// Add declarations
269
for (const [key, value] of instr.scope.declarations) {
@@ -287,7 +287,7 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
287
* inputs change, so it is not a candidate for future merging
288
*/
289
log(
290
- ` but scope @${instr.scope.id} doesnt guaranteed invalidate so it cannot merge further`
290
+ ` but scope @${instr.scope.id} doesnt guaranteed invalidate so it cannot merge further`,
291
);
292
reset();
293
}
@@ -296,7 +296,7 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
296
if (current !== null) {
297
// Reset if necessary
298
log(
299
- `Reset scope @${current.block.scope.id}, not mergeable with subsequent scope @${instr.scope.id}`
299
+ `Reset scope @${current.block.scope.id}, not mergeable with subsequent scope @${instr.scope.id}`,
300
);
301
reset();
302
}
@@ -310,7 +310,7 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
310
};
311
} else {
312
log(
313
- `scope @${instr.scope.id} doesnt guaranteed invalidate so it cannot merge further`
313
+ `scope @${instr.scope.id} doesnt guaranteed invalidate so it cannot merge further`,
314
);
315
}
316
}
@@ -319,7 +319,7 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
319
default: {
320
assertExhaustive(
321
instr,
322
- `Unexpected instruction kind \`${(instr as any).kind}\``
322
+ `Unexpected instruction kind \`${(instr as any).kind}\``,
323
);
324
}
325
}
@@ -332,7 +332,7 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
332
for (const entry of merged) {
333
log(
334
printReactiveScopeSummary(entry.block.scope) +
335
- ` from=${entry.from} to=${entry.to}`
335
+ ` from=${entry.from} to=${entry.to}`,
336
);
337
}
338
}
@@ -350,10 +350,10 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
350
index = entry.from;
351
}
352
const mergedScope = block[entry.from]!;
353
- CompilerError.invariant(mergedScope.kind === "scope", {
353
+ CompilerError.invariant(mergedScope.kind === 'scope', {
354
loc: null,
355
reason:
356
- "MergeConsecutiveScopes: Expected scope starting index to be a scope",
356
+ 'MergeConsecutiveScopes: Expected scope starting index to be a scope',
357
description: null,
358
suggestions: null,
359
});
@@ -361,7 +361,7 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
361
index++;
362
while (index < entry.to) {
363
const instr = block[index++]!;
364
- if (instr.kind === "scope") {
364
+ if (instr.kind === 'scope') {
365
mergedScope.instructions.push(...instr.instructions);
366
mergedScope.scope.merged.add(instr.scope.id);
367
} else {
@@ -383,7 +383,7 @@ class Transform extends ReactiveFunctionTransform<ReactiveScopeDependencies | nu
383
*/
384
function updateScopeDeclarations(
385
scope: ReactiveScope,
386
- lastUsage: Map<IdentifierId, InstructionId>
386
+ lastUsage: Map<IdentifierId, InstructionId>,
387
): void {
388
for (const [key] of scope.declarations) {
389
const lastUsedAt = lastUsage.get(key)!;
@@ -401,7 +401,7 @@ function updateScopeDeclarations(
401
function areLValuesLastUsedByScope(
402
scope: ReactiveScope,
403
lvalues: Set<IdentifierId>,
404
- lastUsage: Map<IdentifierId, InstructionId>
404
+ lastUsage: Map<IdentifierId, InstructionId>,
405
): boolean {
406
for (const lvalue of lvalues) {
407
const lastUsedAt = lastUsage.get(lvalue)!;
@@ -415,7 +415,7 @@ function areLValuesLastUsedByScope(
415
416
function canMergeScopes(
417
current: ReactiveScopeBlock,
418
- next: ReactiveScopeBlock
418
+ next: ReactiveScopeBlock,
419
): boolean {
420
// Don't merge scopes with reassignments
421
if (
@@ -444,18 +444,18 @@ function canMergeScopes(
444
if (
445
areEqualDependencies(
446
new Set(
447
- [...current.scope.declarations.values()].map((declaration) => ({
447
+ [...current.scope.declarations.values()].map(declaration => ({
448
identifier: declaration.identifier,
449
path: [],
450
- }))
450
+ })),
451
),
452
- next.scope.dependencies
452
+ next.scope.dependencies,
453
) ||
454
(next.scope.dependencies.size !== 0 &&
455
[...next.scope.dependencies].every(
456
- (dep) =>
456
+ dep =>
457
current.scope.declarations.has(dep.identifier.id) &&
458
- isAlwaysInvalidatingType(dep.identifier.type)
458
+ isAlwaysInvalidatingType(dep.identifier.type),
459
))
460
) {
461
log(` outputs of prev are input to current`);
@@ -468,7 +468,7 @@ function canMergeScopes(
468
}
469
470
function isAlwaysInvalidatingType(type: Type): boolean {
471
- if (type.kind === "Object") {
471
+ if (type.kind === 'Object') {
472
switch (type.shapeId) {
473
case BuiltInArrayId:
474
case BuiltInObjectId:
@@ -483,7 +483,7 @@ function isAlwaysInvalidatingType(type: Type): boolean {
483
484
function areEqualDependencies(
485
a: Set<ReactiveScopeDependency>,
486
- b: Set<ReactiveScopeDependency>
486
+ b: Set<ReactiveScopeDependency>,
487
): boolean {
488
if (a.size !== b.size) {
489
return false;
@@ -529,6 +529,6 @@ function scopeIsEligibleForMerging(scopeBlock: ReactiveScopeBlock): boolean {
529
return true;
530
}
531
return [...scopeBlock.scope.declarations].some(([, decl]) =>
532
- isAlwaysInvalidatingType(decl.identifier.type)
532
+ isAlwaysInvalidatingType(decl.identifier.type),
533
);
534
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PrintReactiveFunction.ts
+87
-87
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
8
+import {CompilerError} from '../CompilerError';
9
import {
10
PrunedReactiveScopeBlock,
11
ReactiveFunction,
@@ -15,23 +15,23 @@ import {
15
ReactiveStatement,
16
ReactiveTerminal,
17
ReactiveValue,
18
-} from "../HIR/HIR";
18
+} from '../HIR/HIR';
19
import {
20
printFunction,
21
printIdentifier,
22
printInstructionValue,
23
printPlace,
24
printType,
25
-} from "../HIR/PrintHIR";
26
-import { assertExhaustive } from "../Utils/utils";
25
+} from '../HIR/PrintHIR';
26
+import {assertExhaustive} from '../Utils/utils';
27
28
export function printReactiveFunctionWithOutlined(
29
- fn: ReactiveFunction
29
+ fn: ReactiveFunction,
30
): string {
31
const writer = new Writer();
32
writeReactiveFunction(fn, writer);
33
for (const outlined of fn.env.getOutlinedFunctions()) {
34
- writer.writeLine("\nfunction " + printFunction(outlined.fn));
34
+ writer.writeLine('\nfunction ' + printFunction(outlined.fn));
35
}
36
return writer.complete();
37
}
@@ -43,81 +43,81 @@ export function printReactiveFunction(fn: ReactiveFunction): string {
43
}
44
45
function writeReactiveFunction(fn: ReactiveFunction, writer: Writer): void {
46
- writer.writeLine(`function ${fn.id !== null ? fn.id : "<unknown>"}(`);
46
+ writer.writeLine(`function ${fn.id !== null ? fn.id : '<unknown>'}(`);
47
writer.indented(() => {
48
for (const param of fn.params) {
49
- if (param.kind === "Identifier") {
49
+ if (param.kind === 'Identifier') {
50
writer.writeLine(`${printPlace(param)},`);
51
} else {
52
writer.writeLine(`...${printPlace(param.place)},`);
53
}
54
}
55
});
56
- writer.writeLine(") {");
56
+ writer.writeLine(') {');
57
writeReactiveInstructions(writer, fn.body);
58
- writer.writeLine("}");
58
+ writer.writeLine('}');
59
}
60
61
export function printReactiveScopeSummary(scope: ReactiveScope): string {
62
const items = [];
63
// If the scope has a return value it needs a label
64
- items.push("scope");
64
+ items.push('scope');
65
items.push(`@${scope.id}`);
66
items.push(`[${scope.range.start}:${scope.range.end}]`);
67
items.push(
68
`dependencies=[${Array.from(scope.dependencies)
69
- .map((dep) => printDependency(dep))
70
- .join(", ")}]`
69
+ .map(dep => printDependency(dep))
70
+ .join(', ')}]`,
71
);
72
items.push(
73
`declarations=[${Array.from(scope.declarations)
74
.map(([, decl]) =>
75
- printIdentifier({ ...decl.identifier, scope: decl.scope })
75
+ printIdentifier({...decl.identifier, scope: decl.scope}),
76
)
77
- .join(", ")}]`
77
+ .join(', ')}]`,
78
);
79
items.push(
80
- `reassignments=[${Array.from(scope.reassignments).map((reassign) =>
81
- printIdentifier(reassign)
82
- )}]`
80
+ `reassignments=[${Array.from(scope.reassignments).map(reassign =>
81
+ printIdentifier(reassign),
82
+ )}]`,
83
);
84
if (scope.earlyReturnValue !== null) {
85
items.push(
86
`earlyReturn={id: ${printIdentifier(
87
- scope.earlyReturnValue.value
88
- )}, label: ${scope.earlyReturnValue.label}}}`
87
+ scope.earlyReturnValue.value,
88
+ )}, label: ${scope.earlyReturnValue.label}}}`,
89
);
90
}
91
- return items.join(" ");
91
+ return items.join(' ');
92
}
93
94
export function writeReactiveBlock(
95
writer: Writer,
96
- block: ReactiveScopeBlock
96
+ block: ReactiveScopeBlock,
97
): void {
98
writer.writeLine(`${printReactiveScopeSummary(block.scope)} {`);
99
writeReactiveInstructions(writer, block.instructions);
100
- writer.writeLine("}");
100
+ writer.writeLine('}');
101
}
102
103
export function writePrunedScope(
104
writer: Writer,
105
- block: PrunedReactiveScopeBlock
105
+ block: PrunedReactiveScopeBlock,
106
): void {
107
writer.writeLine(`<pruned> ${printReactiveScopeSummary(block.scope)} {`);
108
writeReactiveInstructions(writer, block.instructions);
109
- writer.writeLine("}");
109
+ writer.writeLine('}');
110
}
111
112
export function printDependency(dependency: ReactiveScopeDependency): string {
113
const identifier =
114
printIdentifier(dependency.identifier) +
115
printType(dependency.identifier.type);
116
- return `${identifier}${dependency.path.map((prop) => `.${prop}`).join("")}`;
116
+ return `${identifier}${dependency.path.map(prop => `.${prop}`).join('')}`;
117
}
118
119
export function printReactiveInstructions(
120
- instructions: Array<ReactiveStatement>
120
+ instructions: Array<ReactiveStatement>,
121
): string {
122
const writer = new Writer();
123
writeReactiveInstructions(writer, instructions);
@@ -126,7 +126,7 @@ export function printReactiveInstructions(
126
127
export function writeReactiveInstructions(
128
writer: Writer,
129
- instructions: Array<ReactiveStatement>
129
+ instructions: Array<ReactiveStatement>,
130
): void {
131
writer.indented(() => {
132
for (const instr of instructions) {
@@ -137,11 +137,11 @@ export function writeReactiveInstructions(
137
138
function writeReactiveInstruction(
139
writer: Writer,
140
- instr: ReactiveStatement
140
+ instr: ReactiveStatement,
141
): void {
142
switch (instr.kind) {
143
- case "instruction": {
144
- const { instruction } = instr;
143
+ case 'instruction': {
144
+ const {instruction} = instr;
145
const id = `[${instruction.id}]`;
146
147
if (instruction.lvalue !== null) {
@@ -155,15 +155,15 @@ function writeReactiveInstruction(
155
}
156
break;
157
}
158
- case "scope": {
158
+ case 'scope': {
159
writeReactiveBlock(writer, instr);
160
break;
161
}
162
- case "pruned-scope": {
162
+ case 'pruned-scope': {
163
writePrunedScope(writer, instr);
164
break;
165
}
166
- case "terminal": {
166
+ case 'terminal': {
167
if (instr.label !== null) {
168
writer.write(`bb${instr.label.id}: `);
169
}
@@ -173,7 +173,7 @@ function writeReactiveInstruction(
173
default: {
174
assertExhaustive(
175
instr,
176
- `Unexpected terminal kind \`${(instr as any).kind}\``
176
+ `Unexpected terminal kind \`${(instr as any).kind}\``,
177
);
178
}
179
}
@@ -187,7 +187,7 @@ export function printReactiveValue(value: ReactiveValue): string {
187
188
function writeReactiveValue(writer: Writer, value: ReactiveValue): void {
189
switch (value.kind) {
190
- case "ConditionalExpression": {
190
+ case 'ConditionalExpression': {
191
writer.writeLine(`Ternary `);
192
writer.indented(() => {
193
writeReactiveValue(writer, value.test);
@@ -203,7 +203,7 @@ function writeReactiveValue(writer: Writer, value: ReactiveValue): void {
203
writer.newline();
204
break;
205
}
206
- case "LogicalExpression": {
206
+ case 'LogicalExpression': {
207
writer.writeLine(`Logical`);
208
writer.indented(() => {
209
writeReactiveValue(writer, value.left);
@@ -213,15 +213,15 @@ function writeReactiveValue(writer: Writer, value: ReactiveValue): void {
213
writer.newline();
214
break;
215
}
216
- case "SequenceExpression": {
216
+ case 'SequenceExpression': {
217
writer.writeLine(`Sequence`);
218
writer.indented(() => {
219
writer.indented(() => {
220
- value.instructions.forEach((instr) =>
220
+ value.instructions.forEach(instr =>
221
writeReactiveInstruction(writer, {
222
- kind: "instruction",
222
+ kind: 'instruction',
223
instruction: instr,
224
- })
224
+ }),
225
);
226
writer.write(`[${value.id}] `);
227
writeReactiveValue(writer, value.value);
@@ -230,7 +230,7 @@ function writeReactiveValue(writer: Writer, value: ReactiveValue): void {
230
writer.newline();
231
break;
232
}
233
- case "OptionalExpression": {
233
+ case 'OptionalExpression': {
234
writer.append(`OptionalExpression optional=${value.optional}`);
235
writer.newline();
236
writer.indented(() => {
@@ -241,7 +241,7 @@ function writeReactiveValue(writer: Writer, value: ReactiveValue): void {
241
}
242
default: {
243
const printed = printInstructionValue(value);
244
- const lines = printed.split("\n");
244
+ const lines = printed.split('\n');
245
if (lines.length === 1) {
246
writer.writeLine(printed);
247
} else {
@@ -257,130 +257,130 @@ function writeReactiveValue(writer: Writer, value: ReactiveValue): void {
257
258
function writeTerminal(writer: Writer, terminal: ReactiveTerminal): void {
259
switch (terminal.kind) {
260
- case "break": {
260
+ case 'break': {
261
const id = terminal.id !== null ? `[${terminal.id}]` : [];
262
writer.writeLine(
263
- `${id} break bb${terminal.target} (${terminal.targetKind})`
263
+ `${id} break bb${terminal.target} (${terminal.targetKind})`,
264
);
265
266
break;
267
}
268
- case "continue": {
268
+ case 'continue': {
269
const id = `[${terminal.id}]`;
270
writer.writeLine(
271
- `${id} continue bb${terminal.target} (${terminal.targetKind})`
271
+ `${id} continue bb${terminal.target} (${terminal.targetKind})`,
272
);
273
break;
274
}
275
- case "do-while": {
275
+ case 'do-while': {
276
writer.writeLine(`[${terminal.id}] do-while {`);
277
writeReactiveInstructions(writer, terminal.loop);
278
- writer.writeLine("} (");
278
+ writer.writeLine('} (');
279
writer.indented(() => {
280
writeReactiveValue(writer, terminal.test);
281
});
282
- writer.writeLine(")");
282
+ writer.writeLine(')');
283
break;
284
}
285
- case "while": {
285
+ case 'while': {
286
writer.writeLine(`[${terminal.id}] while (`);
287
writer.indented(() => {
288
writeReactiveValue(writer, terminal.test);
289
});
290
- writer.writeLine(") {");
290
+ writer.writeLine(') {');
291
writeReactiveInstructions(writer, terminal.loop);
292
- writer.writeLine("}");
292
+ writer.writeLine('}');
293
break;
294
}
295
- case "if": {
296
- const { test, consequent, alternate } = terminal;
295
+ case 'if': {
296
+ const {test, consequent, alternate} = terminal;
297
writer.writeLine(`[${terminal.id}] if (${printPlace(test)}) {`);
298
writeReactiveInstructions(writer, consequent);
299
if (alternate !== null) {
300
- writer.writeLine("} else {");
300
+ writer.writeLine('} else {');
301
writeReactiveInstructions(writer, alternate);
302
}
303
- writer.writeLine("}");
303
+ writer.writeLine('}');
304
break;
305
}
306
- case "switch": {
306
+ case 'switch': {
307
writer.writeLine(
308
- `[${terminal.id}] switch (${printPlace(terminal.test)}) {`
308
+ `[${terminal.id}] switch (${printPlace(terminal.test)}) {`,
309
);
310
writer.indented(() => {
311
for (const case_ of terminal.cases) {
312
let prefix =
313
- case_.test !== null ? `case ${printPlace(case_.test)}` : "default";
313
+ case_.test !== null ? `case ${printPlace(case_.test)}` : 'default';
314
writer.writeLine(`${prefix}: {`);
315
writer.indented(() => {
316
const block = case_.block;
317
CompilerError.invariant(block != null, {
318
- reason: "Expected case to have a block",
318
+ reason: 'Expected case to have a block',
319
description: null,
320
loc: case_.test?.loc ?? null,
321
suggestions: null,
322
});
323
writeReactiveInstructions(writer, block);
324
});
325
- writer.writeLine("}");
325
+ writer.writeLine('}');
326
}
327
});
328
- writer.writeLine("}");
328
+ writer.writeLine('}');
329
break;
330
}
331
- case "for": {
331
+ case 'for': {
332
writer.writeLine(`[${terminal.id}] for (`);
333
writer.indented(() => {
334
writeReactiveValue(writer, terminal.init);
335
- writer.writeLine(";");
335
+ writer.writeLine(';');
336
writeReactiveValue(writer, terminal.test);
337
- writer.writeLine(";");
337
+ writer.writeLine(';');
338
if (terminal.update !== null) {
339
writeReactiveValue(writer, terminal.update);
340
}
341
});
342
- writer.writeLine(") {");
342
+ writer.writeLine(') {');
343
writeReactiveInstructions(writer, terminal.loop);
344
- writer.writeLine("}");
344
+ writer.writeLine('}');
345
break;
346
}
347
- case "for-of": {
347
+ case 'for-of': {
348
writer.writeLine(`[${terminal.id}] for-of (`);
349
writer.indented(() => {
350
writeReactiveValue(writer, terminal.init);
351
- writer.writeLine(";");
351
+ writer.writeLine(';');
352
writeReactiveValue(writer, terminal.test);
353
});
354
- writer.writeLine(") {");
354
+ writer.writeLine(') {');
355
writeReactiveInstructions(writer, terminal.loop);
356
- writer.writeLine("}");
356
+ writer.writeLine('}');
357
break;
358
}
359
- case "for-in": {
359
+ case 'for-in': {
360
writer.writeLine(`[${terminal.id}] for-in (`);
361
writer.indented(() => {
362
writeReactiveValue(writer, terminal.init);
363
});
364
- writer.writeLine(") {");
364
+ writer.writeLine(') {');
365
writeReactiveInstructions(writer, terminal.loop);
366
- writer.writeLine("}");
366
+ writer.writeLine('}');
367
break;
368
}
369
- case "throw": {
369
+ case 'throw': {
370
writer.writeLine(`[${terminal.id}] throw ${printPlace(terminal.value)}`);
371
break;
372
}
373
- case "return": {
373
+ case 'return': {
374
writer.writeLine(`[${terminal.id}] return ${printPlace(terminal.value)}`);
375
break;
376
}
377
- case "label": {
378
- writer.writeLine("{");
377
+ case 'label': {
378
+ writer.writeLine('{');
379
writeReactiveInstructions(writer, terminal.block);
380
- writer.writeLine("}");
380
+ writer.writeLine('}');
381
break;
382
}
383
- case "try": {
383
+ case 'try': {
384
writer.writeLine(`[${terminal.id}] try {`);
385
writeReactiveInstructions(writer, terminal.block);
386
writer.write(`} catch `);
@@ -390,7 +390,7 @@ function writeTerminal(writer: Writer, terminal: ReactiveTerminal): void {
390
writer.writeLine(`{`);
391
}
392
writeReactiveInstructions(writer, terminal.handler);
393
- writer.writeLine("}");
393
+ writer.writeLine('}');
394
break;
395
}
396
default:
@@ -403,9 +403,9 @@ export class Writer {
403
#line: string;
404
#depth: number;
405
406
- constructor({ depth }: { depth: number } = { depth: 0 }) {
406
+ constructor({depth}: {depth: number} = {depth: 0}) {
407
this.#depth = Math.max(depth, 0);
408
- this.#line = "";
408
+ this.#line = '';
409
}
410
411
complete(): string {
@@ -413,7 +413,7 @@ export class Writer {
413
if (line.length > 0) {
414
this.#out.push(line);
415
}
416
- return this.#out.join("\n");
416
+ return this.#out.join('\n');
417
}
418
419
append(s: string): void {
@@ -425,13 +425,13 @@ export class Writer {
425
if (line.length > 0) {
426
this.#out.push(line);
427
}
428
- this.#line = "";
428
+ this.#line = '';
429
}
430
431
write(s: string): void {
432
if (this.#line.length === 0 && this.#depth > 0) {
433
// indent before writing
434
- this.#line = " ".repeat(this.#depth);
434
+ this.#line = ' '.repeat(this.#depth);
435
}
436
this.#line += s;
437
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PromoteUsedTemporaries.ts
+16
-16
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
9
-import { GeneratedSource } from "../HIR";
8
+import {CompilerError} from '../CompilerError';
9
+import {GeneratedSource} from '../HIR';
10
import {
11
Identifier,
12
IdentifierId,
@@ -19,14 +19,14 @@ import {
19
ScopeId,
20
promoteTemporary,
21
promoteTemporaryJsxTag,
22
-} from "../HIR/HIR";
23
-import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors";
22
+} from '../HIR/HIR';
23
+import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
24
25
class Visitor extends ReactiveFunctionVisitor<State> {
26
override visitScope(scopeBlock: ReactiveScopeBlock, state: State): void {
27
this.traverseScope(scopeBlock, state);
28
for (const dep of scopeBlock.scope.dependencies) {
29
- const { identifier } = dep;
29
+ const {identifier} = dep;
30
if (identifier.name == null) {
31
promoteIdentifier(identifier, state);
32
}
@@ -47,7 +47,7 @@ class Visitor extends ReactiveFunctionVisitor<State> {
47
48
override visitPrunedScope(
49
scopeBlock: PrunedReactiveScopeBlock,
50
- state: State
50
+ state: State,
51
): void {
52
this.traversePrunedScope(scopeBlock, state);
53
for (const [, declaration] of scopeBlock.scope.declarations) {
@@ -69,10 +69,10 @@ class Visitor extends ReactiveFunctionVisitor<State> {
69
override visitValue(
70
id: InstructionId,
71
value: ReactiveValue,
72
- state: State
72
+ state: State,
73
): void {
74
this.traverseValue(id, value, state);
75
- if (value.kind === "FunctionExpression" || value.kind === "ObjectMethod") {
75
+ if (value.kind === 'FunctionExpression' || value.kind === 'ObjectMethod') {
76
this.visitHirFunction(value.loweredFunc.func, state);
77
}
78
}
@@ -81,10 +81,10 @@ class Visitor extends ReactiveFunctionVisitor<State> {
81
_id: InstructionId,
82
_dependencies: Array<Place>,
83
fn: ReactiveFunction,
84
- state: State
84
+ state: State,
85
): void {
86
for (const operand of fn.params) {
87
- const place = operand.kind === "Identifier" ? operand : operand.place;
87
+ const place = operand.kind === 'Identifier' ? operand : operand.place;
88
if (place.identifier.name === null) {
89
promoteIdentifier(place.identifier, state);
90
}
@@ -98,7 +98,7 @@ type State = {
98
tags: JsxExpressionTags;
99
pruned: Map<
100
IdentifierId,
101
- { activeScopes: Array<ScopeId>; usedOutsideScope: boolean }
101
+ {activeScopes: Array<ScopeId>; usedOutsideScope: boolean}
102
>; // true if referenced within another scope, false if only accessed outside of scopes
103
};
104
@@ -120,17 +120,17 @@ class CollectPromotableTemporaries extends ReactiveFunctionVisitor<State> {
120
override visitValue(
121
id: InstructionId,
122
value: ReactiveValue,
123
- state: State
123
+ state: State,
124
): void {
125
this.traverseValue(id, value, state);
126
- if (value.kind === "JsxExpression" && value.tag.kind === "Identifier") {
126
+ if (value.kind === 'JsxExpression' && value.tag.kind === 'Identifier') {
127
state.tags.add(value.tag.identifier.id);
128
}
129
}
130
131
override visitPrunedScope(
132
scopeBlock: PrunedReactiveScopeBlock,
133
- state: State
133
+ state: State,
134
): void {
135
for (const [id] of scopeBlock.scope.declarations) {
136
state.pruned.set(id, {
@@ -154,7 +154,7 @@ export function promoteUsedTemporaries(fn: ReactiveFunction): void {
154
};
155
visitReactiveFunction(fn, new CollectPromotableTemporaries(), state);
156
for (const operand of fn.params) {
157
- const place = operand.kind === "Identifier" ? operand : operand.place;
157
+ const place = operand.kind === 'Identifier' ? operand : operand.place;
158
if (place.identifier.name === null) {
159
promoteIdentifier(place.identifier, state);
160
}
@@ -165,7 +165,7 @@ export function promoteUsedTemporaries(fn: ReactiveFunction): void {
165
function promoteIdentifier(identifier: Identifier, state: State): void {
166
CompilerError.invariant(identifier.name === null, {
167
reason:
168
- "promoteTemporary: Expected to be called only for temporary variables",
168
+ 'promoteTemporary: Expected to be called only for temporary variables',
169
description: null,
170
loc: GeneratedSource,
171
suggestions: null,
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PropagateEarlyReturns.ts
+41
-41
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { visitReactiveFunction } from ".";
9
-import { Effect } from "..";
8
+import {visitReactiveFunction} from '.';
9
+import {Effect} from '..';
10
import {
11
Environment,
12
GeneratedSource,
@@ -18,10 +18,10 @@ import {
18
ReactiveTerminalStatement,
19
makeInstructionId,
20
promoteTemporary,
21
-} from "../HIR";
22
-import { createTemporaryPlace } from "../HIR/HIRBuilder";
23
-import { EARLY_RETURN_SENTINEL } from "./CodegenReactiveFunction";
24
-import { ReactiveFunctionTransform, Transformed } from "./visitors";
21
+} from '../HIR';
22
+import {createTemporaryPlace} from '../HIR/HIRBuilder';
23
+import {EARLY_RETURN_SENTINEL} from './CodegenReactiveFunction';
24
+import {ReactiveFunctionTransform, Transformed} from './visitors';
25
26
/**
27
* This pass ensures that reactive blocks honor the control flow behavior of the
@@ -119,7 +119,7 @@ type State = {
119
* Store early return information to bubble it back up to the outermost
120
* reactive scope
121
*/
122
- earlyReturnValue: ReactiveScope["earlyReturnValue"];
122
+ earlyReturnValue: ReactiveScope['earlyReturnValue'];
123
};
124
125
class Transform extends ReactiveFunctionTransform<State> {
@@ -131,7 +131,7 @@ class Transform extends ReactiveFunctionTransform<State> {
131
132
override visitScope(
133
scopeBlock: ReactiveScopeBlock,
134
- parentState: State
134
+ parentState: State,
135
): void {
136
/**
137
* Exit early if an earlier pass has already created an early return,
@@ -165,56 +165,56 @@ class Transform extends ReactiveFunctionTransform<State> {
165
const argTemp = createTemporaryPlace(this.env, loc);
166
scopeBlock.instructions = [
167
{
168
- kind: "instruction",
168
+ kind: 'instruction',
169
instruction: {
170
id: makeInstructionId(0),
171
loc,
172
- lvalue: { ...symbolTemp },
172
+ lvalue: {...symbolTemp},
173
value: {
174
- kind: "LoadGlobal",
174
+ kind: 'LoadGlobal',
175
binding: {
176
- kind: "Global",
177
- name: "Symbol",
176
+ kind: 'Global',
177
+ name: 'Symbol',
178
},
179
loc,
180
},
181
},
182
},
183
{
184
- kind: "instruction",
184
+ kind: 'instruction',
185
instruction: {
186
id: makeInstructionId(0),
187
loc,
188
- lvalue: { ...forTemp },
188
+ lvalue: {...forTemp},
189
value: {
190
- kind: "PropertyLoad",
191
- object: { ...symbolTemp },
192
- property: "for",
190
+ kind: 'PropertyLoad',
191
+ object: {...symbolTemp},
192
+ property: 'for',
193
loc,
194
},
195
},
196
},
197
{
198
- kind: "instruction",
198
+ kind: 'instruction',
199
instruction: {
200
id: makeInstructionId(0),
201
loc,
202
- lvalue: { ...argTemp },
202
+ lvalue: {...argTemp},
203
value: {
204
- kind: "Primitive",
204
+ kind: 'Primitive',
205
value: EARLY_RETURN_SENTINEL,
206
loc,
207
},
208
},
209
},
210
{
211
- kind: "instruction",
211
+ kind: 'instruction',
212
instruction: {
213
id: makeInstructionId(0),
214
loc,
215
- lvalue: { ...sentinelTemp },
215
+ lvalue: {...sentinelTemp},
216
value: {
217
- kind: "MethodCall",
217
+ kind: 'MethodCall',
218
receiver: symbolTemp,
219
property: forTemp,
220
args: [argTemp],
@@ -223,37 +223,37 @@ class Transform extends ReactiveFunctionTransform<State> {
223
},
224
},
225
{
226
- kind: "instruction",
226
+ kind: 'instruction',
227
instruction: {
228
id: makeInstructionId(0),
229
loc,
230
lvalue: null,
231
value: {
232
- kind: "StoreLocal",
232
+ kind: 'StoreLocal',
233
loc,
234
type: null,
235
lvalue: {
236
kind: InstructionKind.Let,
237
place: {
238
- kind: "Identifier",
238
+ kind: 'Identifier',
239
effect: Effect.ConditionallyMutate,
240
loc,
241
reactive: true,
242
identifier: earlyReturnValue.value,
243
},
244
},
245
- value: { ...sentinelTemp },
245
+ value: {...sentinelTemp},
246
},
247
},
248
},
249
{
250
- kind: "terminal",
250
+ kind: 'terminal',
251
label: {
252
id: earlyReturnValue.label,
253
implicit: false,
254
},
255
terminal: {
256
- kind: "label",
256
+ kind: 'label',
257
id: makeInstructionId(0),
258
loc: GeneratedSource,
259
block: instructions,
@@ -272,11 +272,11 @@ class Transform extends ReactiveFunctionTransform<State> {
272
273
override transformTerminal(
274
stmt: ReactiveTerminalStatement,
275
- state: State
275
+ state: State,
276
): Transformed<ReactiveStatement> {
277
- if (state.withinReactiveScope && stmt.terminal.kind === "return") {
277
+ if (state.withinReactiveScope && stmt.terminal.kind === 'return') {
278
const loc = stmt.terminal.value.loc;
279
- let earlyReturnValue: ReactiveScope["earlyReturnValue"];
279
+ let earlyReturnValue: ReactiveScope['earlyReturnValue'];
280
if (state.earlyReturnValue !== null) {
281
earlyReturnValue = state.earlyReturnValue;
282
} else {
@@ -290,22 +290,22 @@ class Transform extends ReactiveFunctionTransform<State> {
290
}
291
state.earlyReturnValue = earlyReturnValue;
292
return {
293
- kind: "replace-many",
293
+ kind: 'replace-many',
294
value: [
295
{
296
- kind: "instruction",
296
+ kind: 'instruction',
297
instruction: {
298
id: makeInstructionId(0),
299
loc,
300
lvalue: null,
301
value: {
302
- kind: "StoreLocal",
302
+ kind: 'StoreLocal',
303
loc,
304
type: null,
305
lvalue: {
306
kind: InstructionKind.Reassign,
307
place: {
308
- kind: "Identifier",
308
+ kind: 'Identifier',
309
identifier: earlyReturnValue.value,
310
effect: Effect.Capture,
311
loc,
@@ -317,13 +317,13 @@ class Transform extends ReactiveFunctionTransform<State> {
317
},
318
},
319
{
320
- kind: "terminal",
320
+ kind: 'terminal',
321
label: null,
322
terminal: {
323
- kind: "break",
323
+ kind: 'break',
324
id: makeInstructionId(0),
325
loc,
326
- targetKind: "labeled",
326
+ targetKind: 'labeled',
327
target: earlyReturnValue.label,
328
},
329
},
@@ -331,6 +331,6 @@ class Transform extends ReactiveFunctionTransform<State> {
331
};
332
}
333
this.traverseTerminal(stmt, state);
334
- return { kind: "keep" };
334
+ return {kind: 'keep'};
335
}
336
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PropagateScopeDependencies.ts
+84
-89
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
8
+import {CompilerError} from '../CompilerError';
9
import {
10
BlockId,
11
GeneratedSource,
@@ -27,18 +27,15 @@ import {
27
ReactiveTerminalStatement,
28
ReactiveValue,
29
ScopeId,
30
-} from "../HIR/HIR";
31
-import {
32
- eachInstructionValueOperand,
33
- eachPatternOperand,
34
-} from "../HIR/visitors";
35
-import { empty, Stack } from "../Utils/Stack";
36
-import { assertExhaustive } from "../Utils/utils";
30
+} from '../HIR/HIR';
31
+import {eachInstructionValueOperand, eachPatternOperand} from '../HIR/visitors';
32
+import {empty, Stack} from '../Utils/Stack';
33
+import {assertExhaustive} from '../Utils/utils';
34
import {
35
ReactiveScopeDependencyTree,
36
ReactiveScopePropertyDependency,
40
-} from "./DeriveMinimalDependencies";
41
-import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors";
37
+} from './DeriveMinimalDependencies';
38
+import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
39
40
/*
41
* Infers the dependencies of each scope to include variables whose values
@@ -55,7 +52,7 @@ export function propagateScopeDependencies(fn: ReactiveFunction): void {
52
53
const context = new Context(escapingTemporaries.usedOutsideDeclaringScope);
54
for (const param of fn.params) {
58
- if (param.kind === "Identifier") {
55
+ if (param.kind === 'Identifier') {
56
context.declare(param.identifier, {
57
id: makeInstructionId(0),
58
scope: empty(),
@@ -70,7 +67,7 @@ export function propagateScopeDependencies(fn: ReactiveFunction): void {
67
visitReactiveFunction(
68
fn,
69
new PropagationVisitor(fn.env.config.enableTreatFunctionDepsAsConditional),
73
- context
70
+ context,
71
);
72
}
73
@@ -88,7 +85,7 @@ class FindPromotedTemporaries extends ReactiveFunctionVisitor<TemporariesUsedOut
85
86
override visitScope(
87
scope: ReactiveScopeBlock,
91
- state: TemporariesUsedOutsideDefiningScope
88
+ state: TemporariesUsedOutsideDefiningScope,
89
): void {
90
this.scopes.push(scope.scope.id);
91
this.traverseScope(scope, state);
@@ -97,7 +94,7 @@ class FindPromotedTemporaries extends ReactiveFunctionVisitor<TemporariesUsedOut
94
95
override visitInstruction(
96
instruction: ReactiveInstruction,
100
- state: TemporariesUsedOutsideDefiningScope
97
+ state: TemporariesUsedOutsideDefiningScope,
98
): void {
99
// Visit all places first, then record temporaries which may need to be promoted
100
this.traverseInstruction(instruction, state);
@@ -107,9 +104,9 @@ class FindPromotedTemporaries extends ReactiveFunctionVisitor<TemporariesUsedOut
104
return;
105
}
106
switch (instruction.value.kind) {
110
- case "LoadLocal":
111
- case "LoadContext":
112
- case "PropertyLoad": {
107
+ case 'LoadLocal':
108
+ case 'LoadContext':
109
+ case 'PropertyLoad': {
110
state.declarations.set(instruction.lvalue.identifier.id, scope);
111
break;
112
}
@@ -122,7 +119,7 @@ class FindPromotedTemporaries extends ReactiveFunctionVisitor<TemporariesUsedOut
119
override visitPlace(
120
_id: InstructionId,
121
place: Place,
125
- state: TemporariesUsedOutsideDefiningScope
122
+ state: TemporariesUsedOutsideDefiningScope,
123
): void {
124
const declaringScope = state.declarations.get(place.identifier.id);
125
if (declaringScope === undefined) {
@@ -164,7 +161,7 @@ class PoisonState {
161
constructor(
162
poisonedBlocks: Set<BlockId>,
163
poisonedScopes: Set<ScopeId>,
167
- isPoisoned: boolean
164
+ isPoisoned: boolean,
165
) {
166
this.poisonedBlocks = poisonedBlocks;
167
this.poisonedScopes = poisonedScopes;
@@ -175,7 +172,7 @@ class PoisonState {
172
return new PoisonState(
173
new Set(this.poisonedBlocks),
174
new Set(this.poisonedScopes),
178
- this.isPoisoned
175
+ this.isPoisoned,
176
);
177
}
178
@@ -183,7 +180,7 @@ class PoisonState {
180
const copy = new PoisonState(
181
this.poisonedBlocks,
182
this.poisonedScopes,
186
- this.isPoisoned
183
+ this.isPoisoned,
184
);
185
this.poisonedBlocks = other.poisonedBlocks;
186
this.poisonedScopes = other.poisonedScopes;
@@ -193,7 +190,7 @@ class PoisonState {
190
191
merge(
192
others: Array<PoisonState>,
196
- currentScope: ScopeTraversalState | null
193
+ currentScope: ScopeTraversalState | null,
194
): void {
195
for (const other of others) {
196
for (const id of other.poisonedBlocks) {
@@ -212,9 +209,7 @@ class PoisonState {
209
this.isPoisoned = true;
210
return;
211
} else if (
215
- currentScope.ownBlocks.find((blockId) =>
216
- this.poisonedBlocks.has(blockId)
217
- )
212
+ currentScope.ownBlocks.find(blockId => this.poisonedBlocks.has(blockId))
213
) {
214
this.isPoisoned = true;
215
return;
@@ -233,7 +228,7 @@ class PoisonState {
228
*/
229
addPoisonTarget(
230
target: BlockId | null,
236
- activeScopes: Stack<ScopeTraversalState>
231
+ activeScopes: Stack<ScopeTraversalState>,
232
): void {
233
const currentScope = activeScopes.value;
234
if (target == null && currentScope != null) {
@@ -255,7 +250,7 @@ class PoisonState {
250
this.poisonedBlocks.add(target);
251
if (
252
!this.isPoisoned &&
258
- currentScope?.ownBlocks.find((blockId) => blockId === target)
253
+ currentScope?.ownBlocks.find(blockId => blockId === target)
254
) {
255
this.isPoisoned = true;
256
}
@@ -269,7 +264,7 @@ class PoisonState {
264
*/
265
removeMaybePoisonedScope(
266
id: ScopeId,
272
- currentScope: ScopeTraversalState | null
267
+ currentScope: ScopeTraversalState | null,
268
): void {
269
this.poisonedScopes.delete(id);
270
this.#invalidate(currentScope);
@@ -277,7 +272,7 @@ class PoisonState {
272
273
removeMaybePoisonedBlock(
274
id: BlockId,
280
- currentScope: ScopeTraversalState | null
275
+ currentScope: ScopeTraversalState | null,
276
): void {
277
this.poisonedBlocks.delete(id);
278
this.#invalidate(currentScope);
@@ -365,7 +360,7 @@ class Context {
360
this.#dependencies.addDepsFromInnerScope(
361
scopedDependencies,
362
this.#inConditionalWithinScope || this.isPoisoned,
368
- this.#checkValidDependency.bind(this)
363
+ this.#checkValidDependency.bind(this),
364
);
365
366
if (prevDepsInConditional != null) {
@@ -373,7 +368,7 @@ class Context {
368
prevDepsInConditional.addDepsFromInnerScope(
369
this.#depsInCurrentConditional,
370
true,
376
- this.#checkValidDependency.bind(this)
371
+ this.#checkValidDependency.bind(this),
372
);
373
this.#depsInCurrentConditional = prevDepsInConditional;
374
}
@@ -428,13 +423,13 @@ class Context {
423
* @param depsInConditionals
424
*/
425
promoteDepsFromExhaustiveConditionals(
431
- depsInConditionals: Array<ReactiveScopeDependencyTree>
426
+ depsInConditionals: Array<ReactiveScopeDependencyTree>,
427
): void {
428
this.#dependencies.promoteDepsFromExhaustiveConditionals(
434
- depsInConditionals
429
+ depsInConditionals,
430
);
431
this.#depsInCurrentConditional.promoteDepsFromExhaustiveConditionals(
437
- depsInConditionals
432
+ depsInConditionals,
433
);
434
}
435
@@ -462,7 +457,7 @@ class Context {
457
#getProperty(
458
object: Place,
459
property: string,
465
- isConditional: boolean
460
+ isConditional: boolean,
461
): ReactiveScopePropertyDependency {
462
const resolvedObject = this.resolveTemporary(object);
463
const resolvedDependency = this.#properties.get(resolvedObject.identifier);
@@ -513,7 +508,7 @@ class Context {
508
// ref.current access is not a valid dep
509
if (
510
isUseRefType(maybeDependency.identifier) &&
516
- maybeDependency.path.at(0) === "current"
511
+ maybeDependency.path.at(0) === 'current'
512
) {
513
return false;
514
}
@@ -553,7 +548,7 @@ class Context {
548
if (this.#scopes === null) {
549
return false;
550
}
556
- return this.#scopes.find((state) => state.value === scope);
551
+ return this.#scopes.find(state => state.value === scope);
552
}
553
554
get currentScope(): Stack<ScopeTraversalState> {
@@ -579,7 +574,7 @@ class Context {
574
if (resolved.identifier.name === null) {
575
const propertyDependency = this.#properties.get(resolved.identifier);
576
if (propertyDependency !== undefined) {
582
- dependency = { ...propertyDependency };
577
+ dependency = {...propertyDependency};
578
}
579
}
580
this.visitDependency(dependency);
@@ -604,13 +599,13 @@ class Context {
599
* (all other decls e.g. `let x;` should be initialized in BuildHIR)
600
*/
601
const originalDeclaration = this.#declarations.get(
607
- maybeDependency.identifier.id
602
+ maybeDependency.identifier.id,
603
);
604
if (
605
originalDeclaration !== undefined &&
606
originalDeclaration.scope.value !== null
607
) {
613
- originalDeclaration.scope.each((scope) => {
608
+ originalDeclaration.scope.each(scope => {
609
if (!this.#isScopeActive(scope.value)) {
610
scope.value.declarations.set(maybeDependency.identifier.id, {
611
identifier: maybeDependency.identifier,
@@ -629,7 +624,7 @@ class Context {
624
*/
625
this.#dependencies.add(
626
maybeDependency,
632
- this.#inConditionalWithinScope || isPoisoned
627
+ this.#inConditionalWithinScope || isPoisoned,
628
);
629
}
630
}
@@ -643,9 +638,9 @@ class Context {
638
if (
639
currentScope != null &&
640
!Array.from(currentScope.reassignments).some(
646
- (identifier) => identifier.id === place.identifier.id
641
+ identifier => identifier.id === place.identifier.id,
642
) &&
648
- this.#checkValidDependency({ identifier: place.identifier, path: [] })
643
+ this.#checkValidDependency({identifier: place.identifier, path: []})
644
) {
645
currentScope.reassignments.add(place.identifier);
646
}
@@ -664,7 +659,7 @@ class Context {
659
currentScope.ownBlocks = currentScope.ownBlocks.pop();
660
661
CompilerError.invariant(last != null && last === id, {
667
- reason: "[PropagateScopeDependencies] Misformed block stack",
662
+ reason: '[PropagateScopeDependencies] Misformed block stack',
663
loc: GeneratedSource,
664
});
665
}
@@ -690,7 +685,7 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
685
686
override visitPrunedScope(
687
scopeBlock: PrunedReactiveScopeBlock,
693
- context: Context
688
+ context: Context,
689
): void {
690
/*
691
* NOTE: we explicitly throw away the deps, we only enter() the scope to record its
@@ -703,9 +698,9 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
698
699
override visitInstruction(
700
instruction: ReactiveInstruction,
706
- context: Context
701
+ context: Context,
702
): void {
708
- const { id, value, lvalue } = instruction;
703
+ const {id, value, lvalue} = instruction;
704
this.visitInstructionValue(context, id, value, lvalue);
705
if (lvalue == null) {
706
return;
@@ -719,19 +714,19 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
714
visitReactiveValue(
715
context: Context,
716
id: InstructionId,
722
- value: ReactiveValue
717
+ value: ReactiveValue,
718
): void {
719
switch (value.kind) {
725
- case "OptionalExpression": {
720
+ case 'OptionalExpression': {
721
const inner = value.value;
722
/*
723
* OptionalExpression value is a SequenceExpression where the instructions
724
* represent the code prior to the `?` and the final value represents the
725
* conditional code that follows.
726
*/
732
- CompilerError.invariant(inner.kind === "SequenceExpression", {
727
+ CompilerError.invariant(inner.kind === 'SequenceExpression', {
728
reason:
734
- "Expected OptionalExpression value to be a SequenceExpression",
729
+ 'Expected OptionalExpression value to be a SequenceExpression',
730
description: `Found a \`${value.kind}\``,
731
loc: value.loc,
732
suggestions: null,
@@ -746,14 +741,14 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
741
});
742
break;
743
}
749
- case "LogicalExpression": {
744
+ case 'LogicalExpression': {
745
this.visitReactiveValue(context, id, value.left);
746
context.enterConditional(() => {
747
this.visitReactiveValue(context, id, value.right);
748
});
749
break;
750
}
756
- case "ConditionalExpression": {
751
+ case 'ConditionalExpression': {
752
this.visitReactiveValue(context, id, value.test);
753
754
const consequentDeps = context.enterConditional(() => {
@@ -768,14 +763,14 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
763
]);
764
break;
765
}
771
- case "SequenceExpression": {
766
+ case 'SequenceExpression': {
767
for (const instr of value.instructions) {
768
this.visitInstruction(instr, context);
769
}
770
this.visitInstructionValue(context, id, value.value, null);
771
break;
772
}
778
- case "FunctionExpression": {
773
+ case 'FunctionExpression': {
774
if (this.enableTreatFunctionDepsAsConditional) {
775
context.enterConditional(() => {
776
for (const operand of eachInstructionValueOperand(value)) {
@@ -789,7 +784,7 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
784
}
785
break;
786
}
792
- case "ReactiveFunctionValue": {
787
+ case 'ReactiveFunctionValue': {
788
CompilerError.invariant(false, {
789
reason: `Unexpected ReactiveFunctionValue`,
790
loc: value.loc,
@@ -809,9 +804,9 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
804
context: Context,
805
id: InstructionId,
806
value: ReactiveValue,
812
- lvalue: Place | null
807
+ lvalue: Place | null,
808
): void {
814
- if (value.kind === "LoadLocal" && lvalue !== null) {
809
+ if (value.kind === 'LoadLocal' && lvalue !== null) {
810
if (
811
value.place.identifier.name !== null &&
812
lvalue.identifier.name === null &&
@@ -821,13 +816,13 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
816
} else {
817
context.visitOperand(value.place);
818
}
824
- } else if (value.kind === "PropertyLoad") {
819
+ } else if (value.kind === 'PropertyLoad') {
820
if (lvalue !== null && !context.isUsedOutsideDeclaringScope(lvalue)) {
821
context.declareProperty(lvalue, value.object, value.property);
822
} else {
823
context.visitProperty(value.object, value.property);
824
}
830
- } else if (value.kind === "StoreLocal") {
825
+ } else if (value.kind === 'StoreLocal') {
826
context.visitOperand(value.value);
827
if (value.lvalue.kind === InstructionKind.Reassign) {
828
context.visitReassignment(value.lvalue.place);
@@ -837,8 +832,8 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
832
scope: context.currentScope,
833
});
834
} else if (
840
- value.kind === "DeclareLocal" ||
841
- value.kind === "DeclareContext"
835
+ value.kind === 'DeclareLocal' ||
836
+ value.kind === 'DeclareContext'
837
) {
838
/*
839
* Some variables may be declared and never initialized. We need
@@ -856,7 +851,7 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
851
id,
852
scope: context.currentScope,
853
});
859
- } else if (value.kind === "Destructure") {
854
+ } else if (value.kind === 'Destructure') {
855
context.visitOperand(value.value);
856
for (const place of eachPatternOperand(value.lvalue.pattern)) {
857
if (value.lvalue.kind === InstructionKind.Reassign) {
@@ -878,16 +873,16 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
873
}
874
const terminal = stmt.terminal;
875
switch (terminal.kind) {
881
- case "continue":
882
- case "break": {
876
+ case 'continue':
877
+ case 'break': {
878
context.poisonState.addPoisonTarget(
879
terminal.target,
885
- context.currentScope
880
+ context.currentScope,
881
);
882
break;
883
}
889
- case "throw":
890
- case "return": {
884
+ case 'throw':
885
+ case 'return': {
886
context.poisonState.addPoisonTarget(null, context.currentScope);
887
break;
888
}
@@ -901,24 +896,24 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
896
897
override visitTerminal(
898
stmt: ReactiveTerminalStatement,
904
- context: Context
899
+ context: Context,
900
): void {
901
this.enterTerminal(stmt, context);
902
const terminal = stmt.terminal;
903
switch (terminal.kind) {
909
- case "break":
910
- case "continue": {
904
+ case 'break':
905
+ case 'continue': {
906
break;
907
}
913
- case "return": {
908
+ case 'return': {
909
context.visitOperand(terminal.value);
910
break;
911
}
917
- case "throw": {
912
+ case 'throw': {
913
context.visitOperand(terminal.value);
914
break;
915
}
921
- case "for": {
916
+ case 'for': {
917
this.visitReactiveValue(context, terminal.id, terminal.init);
918
this.visitReactiveValue(context, terminal.id, terminal.test);
919
context.enterConditional(() => {
@@ -929,37 +924,37 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
924
});
925
break;
926
}
932
- case "for-of": {
927
+ case 'for-of': {
928
this.visitReactiveValue(context, terminal.id, terminal.init);
929
context.enterConditional(() => {
930
this.visitBlock(terminal.loop, context);
931
});
932
break;
933
}
939
- case "for-in": {
934
+ case 'for-in': {
935
this.visitReactiveValue(context, terminal.id, terminal.init);
936
context.enterConditional(() => {
937
this.visitBlock(terminal.loop, context);
938
});
939
break;
940
}
946
- case "do-while": {
941
+ case 'do-while': {
942
this.visitBlock(terminal.loop, context);
943
context.enterConditional(() => {
944
this.visitReactiveValue(context, terminal.id, terminal.test);
945
});
946
break;
947
}
953
- case "while": {
948
+ case 'while': {
949
this.visitReactiveValue(context, terminal.id, terminal.test);
950
context.enterConditional(() => {
951
this.visitBlock(terminal.loop, context);
952
});
953
break;
954
}
960
- case "if": {
955
+ case 'if': {
956
context.visitOperand(terminal.test);
962
- const { consequent, alternate } = terminal;
957
+ const {consequent, alternate} = terminal;
958
/*
959
* Consequent and alternate branches are mutually exclusive,
960
* so we save and restore the poison state here.
@@ -975,13 +970,13 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
970
});
971
context.poisonState.merge(
972
[ifPoisonState],
978
- context.currentScope.value
973
+ context.currentScope.value,
974
);
975
context.promoteDepsFromExhaustiveConditionals([depsInIf, depsInElse]);
976
}
977
break;
978
}
984
- case "switch": {
979
+ case 'switch': {
980
context.visitOperand(terminal.test);
981
const isDefaultOnly =
982
terminal.cases.length === 1 && terminal.cases[0].test == null;
@@ -1004,7 +999,7 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
999
* CFG representation for fallthrough. This is safe. It only
1000
* reduces granularity of dependencies.
1001
*/
1007
- for (const { test, block } of terminal.cases) {
1002
+ for (const {test, block} of terminal.cases) {
1003
if (test !== null) {
1004
context.visitOperand(test);
1005
} else {
@@ -1012,12 +1007,12 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
1007
}
1008
if (block !== undefined) {
1009
mutExPoisonStates.push(
1015
- context.poisonState.take(prevPoisonState.clone())
1010
+ context.poisonState.take(prevPoisonState.clone()),
1011
);
1012
depsInCases.push(
1013
context.enterConditional(() => {
1014
this.visitBlock(block, context);
1020
- })
1015
+ }),
1016
);
1017
}
1018
}
@@ -1026,15 +1021,15 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
1021
}
1022
context.poisonState.merge(
1023
mutExPoisonStates,
1029
- context.currentScope.value
1024
+ context.currentScope.value,
1025
);
1026
break;
1027
}
1033
- case "label": {
1028
+ case 'label': {
1029
this.visitBlock(terminal.block, context);
1030
break;
1031
}
1037
- case "try": {
1032
+ case 'try': {
1033
this.visitBlock(terminal.block, context);
1034
this.visitBlock(terminal.handler, context);
1035
break;
@@ -1042,7 +1037,7 @@ class PropagationVisitor extends ReactiveFunctionVisitor<Context> {
1037
default: {
1038
assertExhaustive(
1039
terminal,
1045
- `Unexpected terminal kind \`${(terminal as any).kind}\``
1040
+ `Unexpected terminal kind \`${(terminal as any).kind}\``,
1041
);
1042
}
1043
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PruneAllReactiveScopes.ts
+4
-4
@@ -9,12 +9,12 @@ import {
9
ReactiveFunction,
10
ReactiveScopeBlock,
11
ReactiveStatement,
12
-} from "../HIR/HIR";
12
+} from '../HIR/HIR';
13
import {
14
ReactiveFunctionTransform,
15
Transformed,
16
visitReactiveFunction,
17
-} from "./visitors";
17
+} from './visitors';
18
19
/*
20
* Removes *all* reactive scopes. Intended for experimentation only, to allow
@@ -28,9 +28,9 @@ export function pruneAllReactiveScopes(fn: ReactiveFunction): void {
28
class Transform extends ReactiveFunctionTransform<void> {
29
override transformScope(
30
scopeBlock: ReactiveScopeBlock,
31
- state: void
31
+ state: void,
32
): Transformed<ReactiveStatement> {
33
this.visitScope(scopeBlock, state);
34
- return { kind: "replace-many", value: scopeBlock.instructions };
34
+ return {kind: 'replace-many', value: scopeBlock.instructions};
35
}
36
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PruneAlwaysInvalidatingScopes.ts
+16
-20
@@ -5,18 +5,14 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import {
9
- ReactiveFunctionTransform,
10
- Transformed,
11
- visitReactiveFunction,
12
-} from ".";
8
+import {ReactiveFunctionTransform, Transformed, visitReactiveFunction} from '.';
9
import {
10
Identifier,
11
ReactiveFunction,
12
ReactiveInstruction,
13
ReactiveScopeBlock,
14
ReactiveStatement,
19
-} from "../HIR";
15
+} from '../HIR';
16
17
/**
18
* Some instructions will *always* produce a new value, and unless memoized will *always*
@@ -38,17 +34,17 @@ class Transform extends ReactiveFunctionTransform<boolean> {
34
35
override transformInstruction(
36
instruction: ReactiveInstruction,
41
- withinScope: boolean
37
+ withinScope: boolean,
38
): Transformed<ReactiveStatement> {
39
this.visitInstruction(instruction, withinScope);
40
45
- const { lvalue, value } = instruction;
41
+ const {lvalue, value} = instruction;
42
switch (value.kind) {
47
- case "ArrayExpression":
48
- case "ObjectExpression":
49
- case "JsxExpression":
50
- case "JsxFragment":
51
- case "NewExpression": {
43
+ case 'ArrayExpression':
44
+ case 'ObjectExpression':
45
+ case 'JsxExpression':
46
+ case 'JsxFragment':
47
+ case 'NewExpression': {
48
if (lvalue !== null) {
49
this.alwaysInvalidatingValues.add(lvalue.identifier);
50
if (!withinScope) {
@@ -57,7 +53,7 @@ class Transform extends ReactiveFunctionTransform<boolean> {
53
}
54
break;
55
}
60
- case "StoreLocal": {
56
+ case 'StoreLocal': {
57
if (this.alwaysInvalidatingValues.has(value.value.identifier)) {
58
this.alwaysInvalidatingValues.add(value.lvalue.place.identifier);
59
}
@@ -66,7 +62,7 @@ class Transform extends ReactiveFunctionTransform<boolean> {
62
}
63
break;
64
}
69
- case "LoadLocal": {
65
+ case 'LoadLocal': {
66
if (
67
lvalue !== null &&
68
this.alwaysInvalidatingValues.has(value.place.identifier)
@@ -82,12 +78,12 @@ class Transform extends ReactiveFunctionTransform<boolean> {
78
break;
79
}
80
}
85
- return { kind: "keep" };
81
+ return {kind: 'keep'};
82
}
83
84
override transformScope(
85
scopeBlock: ReactiveScopeBlock,
90
- _withinScope: boolean
86
+ _withinScope: boolean,
87
): Transformed<ReactiveStatement> {
88
this.visitScope(scopeBlock, true);
89
@@ -108,15 +104,15 @@ class Transform extends ReactiveFunctionTransform<boolean> {
104
}
105
}
106
return {
111
- kind: "replace",
107
+ kind: 'replace',
108
value: {
113
- kind: "pruned-scope",
109
+ kind: 'pruned-scope',
110
scope: scopeBlock.scope,
111
instructions: scopeBlock.instructions,
112
},
113
};
114
}
115
}
120
- return { kind: "keep" };
116
+ return {kind: 'keep'};
117
}
118
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PruneHoistedContexts.ts
+11
-11
@@ -11,12 +11,12 @@ import {
11
ReactiveFunction,
12
ReactiveInstruction,
13
ReactiveStatement,
14
-} from "../HIR";
14
+} from '../HIR';
15
import {
16
ReactiveFunctionTransform,
17
Transformed,
18
visitReactiveFunction,
19
-} from "./visitors";
19
+} from './visitors';
20
21
/*
22
* Prunes DeclareContexts lowered for HoistedConsts, and transforms any references back to its
@@ -32,25 +32,25 @@ type HoistedIdentifiers = Set<Identifier>;
32
class Visitor extends ReactiveFunctionTransform<HoistedIdentifiers> {
33
override transformInstruction(
34
instruction: ReactiveInstruction,
35
- state: HoistedIdentifiers
35
+ state: HoistedIdentifiers,
36
): Transformed<ReactiveStatement> {
37
this.visitInstruction(instruction, state);
38
if (
39
- instruction.value.kind === "DeclareContext" &&
40
- instruction.value.lvalue.kind === "HoistedConst"
39
+ instruction.value.kind === 'DeclareContext' &&
40
+ instruction.value.lvalue.kind === 'HoistedConst'
41
) {
42
state.add(instruction.value.lvalue.place.identifier);
43
- return { kind: "remove" };
43
+ return {kind: 'remove'};
44
}
45
46
if (
47
- instruction.value.kind === "StoreContext" &&
47
+ instruction.value.kind === 'StoreContext' &&
48
state.has(instruction.value.lvalue.place.identifier)
49
) {
50
return {
51
- kind: "replace",
51
+ kind: 'replace',
52
value: {
53
- kind: "instruction",
53
+ kind: 'instruction',
54
instruction: {
55
...instruction,
56
value: {
@@ -60,13 +60,13 @@ class Visitor extends ReactiveFunctionTransform<HoistedIdentifiers> {
60
kind: InstructionKind.Const,
61
},
62
type: null,
63
- kind: "StoreLocal",
63
+ kind: 'StoreLocal',
64
},
65
},
66
},
67
};
68
}
69
70
- return { kind: "keep" };
70
+ return {kind: 'keep'};
71
}
72
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PruneInitializationDependencies.ts
+49
-49
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
8
+import {CompilerError} from '../CompilerError';
9
import {
10
Environment,
11
Identifier,
@@ -20,11 +20,11 @@ import {
20
getHookKind,
21
isUseRefType,
22
isUseStateType,
23
-} from "../HIR";
24
-import { eachCallArgument, eachInstructionLValue } from "../HIR/visitors";
25
-import DisjointSet from "../Utils/DisjointSet";
26
-import { assertExhaustive } from "../Utils/utils";
27
-import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors";
23
+} from '../HIR';
24
+import {eachCallArgument, eachInstructionLValue} from '../HIR/visitors';
25
+import DisjointSet from '../Utils/DisjointSet';
26
+import {assertExhaustive} from '../Utils/utils';
27
+import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
28
29
/**
30
* This pass is built based on the observation by @jbrown215 that arguments
@@ -57,7 +57,7 @@ import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors";
57
* from the block.
58
*/
59
60
-type CreateUpdate = "Create" | "Update" | "Unknown";
60
+type CreateUpdate = 'Create' | 'Update' | 'Unknown';
61
62
type KindMap = Map<IdentifierId, CreateUpdate>;
63
@@ -70,7 +70,7 @@ class Visitor extends ReactiveFunctionVisitor<CreateUpdate> {
70
constructor(
71
env: Environment,
72
aliases: DisjointSet<IdentifierId>,
73
- paths: Map<IdentifierId, Map<string, IdentifierId>>
73
+ paths: Map<IdentifierId, Map<string, IdentifierId>>,
74
) {
75
super();
76
this.aliases = aliases;
@@ -80,16 +80,16 @@ class Visitor extends ReactiveFunctionVisitor<CreateUpdate> {
80
81
join(values: Array<CreateUpdate>): CreateUpdate {
82
function join2(l: CreateUpdate, r: CreateUpdate): CreateUpdate {
83
- if (l === "Update" || r === "Update") {
84
- return "Update";
85
- } else if (l === "Create" || r === "Create") {
86
- return "Create";
87
- } else if (l === "Unknown" || r === "Unknown") {
88
- return "Unknown";
83
+ if (l === 'Update' || r === 'Update') {
84
+ return 'Update';
85
+ } else if (l === 'Create' || r === 'Create') {
86
+ return 'Create';
87
+ } else if (l === 'Unknown' || r === 'Unknown') {
88
+ return 'Unknown';
89
}
90
assertExhaustive(r, `Unhandled variable kind ${r}`);
91
}
92
- return values.reduce(join2, "Unknown");
92
+ return values.reduce(join2, 'Unknown');
93
}
94
95
isCreateOnlyHook(id: Identifier): boolean {
@@ -99,11 +99,11 @@ class Visitor extends ReactiveFunctionVisitor<CreateUpdate> {
99
override visitPlace(
100
_: InstructionId,
101
place: Place,
102
- state: CreateUpdate
102
+ state: CreateUpdate,
103
): void {
104
this.map.set(
105
place.identifier.id,
106
- this.join([state, this.map.get(place.identifier.id) ?? "Unknown"])
106
+ this.join([state, this.map.get(place.identifier.id) ?? 'Unknown']),
107
);
108
}
109
@@ -114,17 +114,17 @@ class Visitor extends ReactiveFunctionVisitor<CreateUpdate> {
114
override visitInstruction(instruction: ReactiveInstruction): void {
115
const state = this.join(
116
[...eachInstructionLValue(instruction)].map(
117
- (operand) => this.map.get(operand.identifier.id) ?? "Unknown"
118
- )
117
+ operand => this.map.get(operand.identifier.id) ?? 'Unknown',
118
+ ),
119
);
120
121
const visitCallOrMethodNonArgs = (): void => {
122
switch (instruction.value.kind) {
123
- case "CallExpression": {
123
+ case 'CallExpression': {
124
this.visitPlace(instruction.id, instruction.value.callee, state);
125
break;
126
}
127
- case "MethodCall": {
127
+ case 'MethodCall': {
128
this.visitPlace(instruction.id, instruction.value.property, state);
129
this.visitPlace(instruction.id, instruction.value.receiver, state);
130
break;
@@ -135,11 +135,11 @@ class Visitor extends ReactiveFunctionVisitor<CreateUpdate> {
135
const isHook = (): boolean => {
136
let callee = null;
137
switch (instruction.value.kind) {
138
- case "CallExpression": {
138
+ case 'CallExpression': {
139
callee = instruction.value.callee.identifier;
140
break;
141
}
142
- case "MethodCall": {
142
+ case 'MethodCall': {
143
callee = instruction.value.property.identifier;
144
break;
145
}
@@ -148,18 +148,18 @@ class Visitor extends ReactiveFunctionVisitor<CreateUpdate> {
148
};
149
150
switch (instruction.value.kind) {
151
- case "CallExpression":
152
- case "MethodCall": {
151
+ case 'CallExpression':
152
+ case 'MethodCall': {
153
if (
154
instruction.lvalue &&
155
this.isCreateOnlyHook(instruction.lvalue.identifier)
156
) {
157
- [...eachCallArgument(instruction.value.args)].forEach((operand) =>
158
- this.visitPlace(instruction.id, operand, "Create")
157
+ [...eachCallArgument(instruction.value.args)].forEach(operand =>
158
+ this.visitPlace(instruction.id, operand, 'Create'),
159
);
160
visitCallOrMethodNonArgs();
161
} else {
162
- this.traverseInstruction(instruction, isHook() ? "Update" : state);
162
+ this.traverseInstruction(instruction, isHook() ? 'Update' : state);
163
}
164
break;
165
}
@@ -173,17 +173,17 @@ class Visitor extends ReactiveFunctionVisitor<CreateUpdate> {
173
const state = this.join(
174
[
175
...scope.scope.declarations.keys(),
176
- ...[...scope.scope.reassignments.values()].map((ident) => ident.id),
177
- ].map((id) => this.map.get(id) ?? "Unknown")
176
+ ...[...scope.scope.reassignments.values()].map(ident => ident.id),
177
+ ].map(id => this.map.get(id) ?? 'Unknown'),
178
);
179
super.visitScope(scope, state);
180
- [...scope.scope.dependencies].forEach((ident) => {
180
+ [...scope.scope.dependencies].forEach(ident => {
181
let target: undefined | IdentifierId =
182
this.aliases.find(ident.identifier.id) ?? ident.identifier.id;
183
- ident.path.forEach((key) => {
183
+ ident.path.forEach(key => {
184
target &&= this.paths.get(target)?.get(key);
185
});
186
- if (target && this.map.get(target) === "Create") {
186
+ if (target && this.map.get(target) === 'Create') {
187
scope.scope.dependencies.delete(ident);
188
}
189
});
@@ -191,9 +191,9 @@ class Visitor extends ReactiveFunctionVisitor<CreateUpdate> {
191
192
override visitTerminal(
193
stmt: ReactiveTerminalStatement,
194
- state: CreateUpdate
194
+ state: CreateUpdate,
195
): void {
196
- CompilerError.invariant(state !== "Create", {
196
+ CompilerError.invariant(state !== 'Create', {
197
reason: "Visiting a terminal statement with state 'Create'",
198
loc: stmt.terminal.loc,
199
});
@@ -204,24 +204,24 @@ class Visitor extends ReactiveFunctionVisitor<CreateUpdate> {
204
_id: InstructionId,
205
_dependencies: Array<Place>,
206
fn: ReactiveFunction,
207
- state: CreateUpdate
207
+ state: CreateUpdate,
208
): void {
209
visitReactiveFunction(fn, this, state);
210
}
211
}
212
213
export default function pruneInitializationDependencies(
214
- fn: ReactiveFunction
214
+ fn: ReactiveFunction,
215
): void {
216
const [aliases, paths] = getAliases(fn);
217
- visitReactiveFunction(fn, new Visitor(fn.env, aliases, paths), "Update");
217
+ visitReactiveFunction(fn, new Visitor(fn.env, aliases, paths), 'Update');
218
}
219
220
function update(
221
map: Map<IdentifierId, Map<string, IdentifierId>>,
222
key: IdentifierId,
223
path: string,
224
- value: IdentifierId
224
+ value: IdentifierId,
225
): void {
226
const inner = map.get(key) ?? new Map();
227
inner.set(path, value);
@@ -234,43 +234,43 @@ class AliasVisitor extends ReactiveFunctionVisitor {
234
235
override visitInstruction(instr: ReactiveInstruction): void {
236
if (
237
- instr.value.kind === "StoreLocal" ||
238
- instr.value.kind === "StoreContext"
237
+ instr.value.kind === 'StoreLocal' ||
238
+ instr.value.kind === 'StoreContext'
239
) {
240
this.scopeIdentifiers.union([
241
instr.value.lvalue.place.identifier.id,
242
instr.value.value.identifier.id,
243
]);
244
} else if (
245
- instr.value.kind === "LoadLocal" ||
246
- instr.value.kind === "LoadContext"
245
+ instr.value.kind === 'LoadLocal' ||
246
+ instr.value.kind === 'LoadContext'
247
) {
248
instr.lvalue &&
249
this.scopeIdentifiers.union([
250
instr.lvalue.identifier.id,
251
instr.value.place.identifier.id,
252
]);
253
- } else if (instr.value.kind === "PropertyLoad") {
253
+ } else if (instr.value.kind === 'PropertyLoad') {
254
instr.lvalue &&
255
update(
256
this.scopePaths,
257
instr.value.object.identifier.id,
258
instr.value.property,
259
- instr.lvalue.identifier.id
259
+ instr.lvalue.identifier.id,
260
);
261
- } else if (instr.value.kind === "PropertyStore") {
261
+ } else if (instr.value.kind === 'PropertyStore') {
262
update(
263
this.scopePaths,
264
instr.value.object.identifier.id,
265
instr.value.property,
266
- instr.value.value.identifier.id
266
+ instr.value.value.identifier.id,
267
);
268
}
269
}
270
}
271
272
function getAliases(
273
- fn: ReactiveFunction
273
+ fn: ReactiveFunction,
274
): [DisjointSet<IdentifierId>, Map<IdentifierId, Map<string, IdentifierId>>] {
275
const visitor = new AliasVisitor();
276
visitReactiveFunction(fn, visitor, null);
@@ -282,7 +282,7 @@ function getAliases(
282
scopePaths,
283
disjoint.find(key) ?? key,
284
path,
285
- disjoint.find(id) ?? id
285
+ disjoint.find(id) ?? id,
286
);
287
}
288
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PruneNonEscapingScopes.ts
+137
-137
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
8
+import {CompilerError} from '../CompilerError';
9
import {
10
Environment,
11
IdentifierId,
@@ -22,17 +22,17 @@ import {
22
ScopeId,
23
getHookKind,
24
isMutableEffect,
25
-} from "../HIR";
26
-import { getFunctionCallSignature } from "../Inference/InferReferenceEffects";
27
-import { assertExhaustive } from "../Utils/utils";
28
-import { getPlaceScope } from "./BuildReactiveBlocks";
25
+} from '../HIR';
26
+import {getFunctionCallSignature} from '../Inference/InferReferenceEffects';
27
+import {assertExhaustive} from '../Utils/utils';
28
+import {getPlaceScope} from './BuildReactiveBlocks';
29
import {
30
ReactiveFunctionTransform,
31
ReactiveFunctionVisitor,
32
Transformed,
33
eachReactiveValueOperand,
34
visitReactiveFunction,
35
-} from "./visitors";
35
+} from './visitors';
36
37
/*
38
* This pass prunes reactive scopes that are not necessary to bound downstream computation.
@@ -114,7 +114,7 @@ export function pruneNonEscapingScopes(fn: ReactiveFunction): void {
114
*/
115
const state = new State(fn.env);
116
for (const param of fn.params) {
117
- if (param.kind === "Identifier") {
117
+ if (param.kind === 'Identifier') {
118
state.declare(param.identifier.id);
119
} else {
120
state.declare(param.place.identifier.id);
@@ -146,19 +146,19 @@ export type MemoizationOptions = {
146
// Describes how to determine whether a value should be memoized, relative to dependees and dependencies
147
enum MemoizationLevel {
148
// The value should be memoized if it escapes
149
- Memoized = "Memoized",
149
+ Memoized = 'Memoized',
150
/*
151
* Values that are memoized if their dependencies are memoized (used for logical/ternary and
152
* other expressions that propagate dependencies wo changing them)
153
*/
154
- Conditional = "Conditional",
154
+ Conditional = 'Conditional',
155
/*
156
* Values that cannot be compared with Object.is, but which by default don't need to be memoized
157
* unless forced
158
*/
159
- Unmemoized = "Unmemoized",
159
+ Unmemoized = 'Unmemoized',
160
// The value will never be memoized: used for values that can be cheaply compared w Object.is
161
- Never = "Never",
161
+ Never = 'Never',
162
}
163
164
/*
@@ -167,7 +167,7 @@ enum MemoizationLevel {
167
*/
168
function joinAliases(
169
kind1: MemoizationLevel,
170
- kind2: MemoizationLevel
170
+ kind2: MemoizationLevel,
171
): MemoizationLevel {
172
if (
173
kind1 === MemoizationLevel.Memoized ||
@@ -240,21 +240,21 @@ class State {
240
visitOperand(
241
id: InstructionId,
242
place: Place,
243
- identifier: IdentifierId
243
+ identifier: IdentifierId,
244
): void {
245
const scope = getPlaceScope(id, place);
246
if (scope !== null) {
247
let node = this.scopes.get(scope.id);
248
if (node === undefined) {
249
node = {
250
- dependencies: [...scope.dependencies].map((dep) => dep.identifier.id),
250
+ dependencies: [...scope.dependencies].map(dep => dep.identifier.id),
251
seen: false,
252
};
253
this.scopes.set(scope.id, node);
254
}
255
const identifierNode = this.identifiers.get(identifier);
256
CompilerError.invariant(identifierNode !== undefined, {
257
- reason: "Expected identifier to be initialized",
257
+ reason: 'Expected identifier to be initialized',
258
description: null,
259
loc: place.loc,
260
suggestions: null,
@@ -318,7 +318,7 @@ function computeMemoizedIdentifiers(state: State): Set<IdentifierId> {
318
function forceMemoizeScopeDependencies(id: ScopeId): void {
319
const node = state.scopes.get(id);
320
CompilerError.invariant(node !== undefined, {
321
- reason: "Expected a node for all scopes",
321
+ reason: 'Expected a node for all scopes',
322
description: null,
323
loc: null,
324
suggestions: null,
@@ -358,19 +358,19 @@ function computeMemoizationInputs(
358
env: Environment,
359
value: ReactiveValue,
360
lvalue: Place | null,
361
- options: MemoizationOptions
361
+ options: MemoizationOptions,
362
): {
363
// can optionally return a custom set of lvalues per instruction
364
lvalues: Array<LValueMemoization>;
365
rvalues: Array<Place>;
366
} {
367
switch (value.kind) {
368
- case "ConditionalExpression": {
368
+ case 'ConditionalExpression': {
369
return {
370
// Only need to memoize if the rvalues are memoized
371
lvalues:
372
lvalue !== null
373
- ? [{ place: lvalue, level: MemoizationLevel.Conditional }]
373
+ ? [{place: lvalue, level: MemoizationLevel.Conditional}]
374
: [],
375
rvalues: [
376
// Conditionals do not alias their test value.
@@ -381,12 +381,12 @@ function computeMemoizationInputs(
381
],
382
};
383
}
384
- case "LogicalExpression": {
384
+ case 'LogicalExpression': {
385
return {
386
// Only need to memoize if the rvalues are memoized
387
lvalues:
388
lvalue !== null
389
- ? [{ place: lvalue, level: MemoizationLevel.Conditional }]
389
+ ? [{place: lvalue, level: MemoizationLevel.Conditional}]
390
: [],
391
rvalues: [
392
...computeMemoizationInputs(env, value.left, null, options).rvalues,
@@ -394,12 +394,12 @@ function computeMemoizationInputs(
394
],
395
};
396
}
397
- case "SequenceExpression": {
397
+ case 'SequenceExpression': {
398
return {
399
// Only need to memoize if the rvalues are memoized
400
lvalues:
401
lvalue !== null
402
- ? [{ place: lvalue, level: MemoizationLevel.Conditional }]
402
+ ? [{place: lvalue, level: MemoizationLevel.Conditional}]
403
: [],
404
/*
405
* Only the final value of the sequence is a true rvalue:
@@ -410,13 +410,13 @@ function computeMemoizationInputs(
410
.rvalues,
411
};
412
}
413
- case "JsxExpression": {
413
+ case 'JsxExpression': {
414
const operands: Array<Place> = [];
415
- if (value.tag.kind === "Identifier") {
415
+ if (value.tag.kind === 'Identifier') {
416
operands.push(value.tag);
417
}
418
for (const prop of value.props) {
419
- if (prop.kind === "JsxAttribute") {
419
+ if (prop.kind === 'JsxAttribute') {
420
operands.push(prop.place);
421
} else {
422
operands.push(prop.argument);
@@ -435,11 +435,11 @@ function computeMemoizationInputs(
435
* JSX elements themselves are not memoized unless forced to
436
* avoid breaking downstream memoization
437
*/
438
- lvalues: lvalue !== null ? [{ place: lvalue, level }] : [],
438
+ lvalues: lvalue !== null ? [{place: lvalue, level}] : [],
439
rvalues: operands,
440
};
441
}
442
- case "JsxFragment": {
442
+ case 'JsxFragment': {
443
const level = options.memoizeJsxElements
444
? MemoizationLevel.Memoized
445
: MemoizationLevel.Unmemoized;
@@ -448,89 +448,89 @@ function computeMemoizationInputs(
448
* JSX elements themselves are not memoized unless forced to
449
* avoid breaking downstream memoization
450
*/
451
- lvalues: lvalue !== null ? [{ place: lvalue, level }] : [],
451
+ lvalues: lvalue !== null ? [{place: lvalue, level}] : [],
452
rvalues: value.children,
453
};
454
}
455
- case "NextPropertyOf":
456
- case "StartMemoize":
457
- case "FinishMemoize":
458
- case "Debugger":
459
- case "ComputedDelete":
460
- case "PropertyDelete":
461
- case "LoadGlobal":
462
- case "MetaProperty":
463
- case "TemplateLiteral":
464
- case "Primitive":
465
- case "JSXText":
466
- case "BinaryExpression":
467
- case "UnaryExpression": {
455
+ case 'NextPropertyOf':
456
+ case 'StartMemoize':
457
+ case 'FinishMemoize':
458
+ case 'Debugger':
459
+ case 'ComputedDelete':
460
+ case 'PropertyDelete':
461
+ case 'LoadGlobal':
462
+ case 'MetaProperty':
463
+ case 'TemplateLiteral':
464
+ case 'Primitive':
465
+ case 'JSXText':
466
+ case 'BinaryExpression':
467
+ case 'UnaryExpression': {
468
const level = options.forceMemoizePrimitives
469
? MemoizationLevel.Memoized
470
: MemoizationLevel.Never;
471
return {
472
// All of these instructions return a primitive value and never need to be memoized
473
- lvalues: lvalue !== null ? [{ place: lvalue, level }] : [],
473
+ lvalues: lvalue !== null ? [{place: lvalue, level}] : [],
474
rvalues: [],
475
};
476
}
477
- case "Await":
478
- case "TypeCastExpression": {
477
+ case 'Await':
478
+ case 'TypeCastExpression': {
479
return {
480
// Indirection for the inner value, memoized if the value is
481
lvalues:
482
lvalue !== null
483
- ? [{ place: lvalue, level: MemoizationLevel.Conditional }]
483
+ ? [{place: lvalue, level: MemoizationLevel.Conditional}]
484
: [],
485
rvalues: [value.value],
486
};
487
}
488
- case "IteratorNext": {
488
+ case 'IteratorNext': {
489
return {
490
// Indirection for the inner value, memoized if the value is
491
lvalues:
492
lvalue !== null
493
- ? [{ place: lvalue, level: MemoizationLevel.Conditional }]
493
+ ? [{place: lvalue, level: MemoizationLevel.Conditional}]
494
: [],
495
rvalues: [value.iterator, value.collection],
496
};
497
}
498
- case "GetIterator": {
498
+ case 'GetIterator': {
499
return {
500
// Indirection for the inner value, memoized if the value is
501
lvalues:
502
lvalue !== null
503
- ? [{ place: lvalue, level: MemoizationLevel.Conditional }]
503
+ ? [{place: lvalue, level: MemoizationLevel.Conditional}]
504
: [],
505
rvalues: [value.collection],
506
};
507
}
508
- case "LoadLocal": {
508
+ case 'LoadLocal': {
509
return {
510
// Indirection for the inner value, memoized if the value is
511
lvalues:
512
lvalue !== null
513
- ? [{ place: lvalue, level: MemoizationLevel.Conditional }]
513
+ ? [{place: lvalue, level: MemoizationLevel.Conditional}]
514
: [],
515
rvalues: [value.place],
516
};
517
}
518
- case "LoadContext": {
518
+ case 'LoadContext': {
519
return {
520
// Should never be pruned
521
lvalues:
522
lvalue !== null
523
- ? [{ place: lvalue, level: MemoizationLevel.Conditional }]
523
+ ? [{place: lvalue, level: MemoizationLevel.Conditional}]
524
: [],
525
rvalues: [value.place],
526
};
527
}
528
- case "DeclareContext": {
528
+ case 'DeclareContext': {
529
const lvalues = [
530
- { place: value.lvalue.place, level: MemoizationLevel.Memoized },
530
+ {place: value.lvalue.place, level: MemoizationLevel.Memoized},
531
];
532
if (lvalue !== null) {
533
- lvalues.push({ place: lvalue, level: MemoizationLevel.Unmemoized });
533
+ lvalues.push({place: lvalue, level: MemoizationLevel.Unmemoized});
534
}
535
return {
536
lvalues,
@@ -538,25 +538,25 @@ function computeMemoizationInputs(
538
};
539
}
540
541
- case "DeclareLocal": {
541
+ case 'DeclareLocal': {
542
const lvalues = [
543
- { place: value.lvalue.place, level: MemoizationLevel.Unmemoized },
543
+ {place: value.lvalue.place, level: MemoizationLevel.Unmemoized},
544
];
545
if (lvalue !== null) {
546
- lvalues.push({ place: lvalue, level: MemoizationLevel.Unmemoized });
546
+ lvalues.push({place: lvalue, level: MemoizationLevel.Unmemoized});
547
}
548
return {
549
lvalues,
550
rvalues: [],
551
};
552
}
553
- case "PrefixUpdate":
554
- case "PostfixUpdate": {
553
+ case 'PrefixUpdate':
554
+ case 'PostfixUpdate': {
555
const lvalues = [
556
- { place: value.lvalue, level: MemoizationLevel.Conditional },
556
+ {place: value.lvalue, level: MemoizationLevel.Conditional},
557
];
558
if (lvalue !== null) {
559
- lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional });
559
+ lvalues.push({place: lvalue, level: MemoizationLevel.Conditional});
560
}
561
return {
562
// Indirection for the inner value, memoized if the value is
@@ -564,12 +564,12 @@ function computeMemoizationInputs(
564
rvalues: [value.value],
565
};
566
}
567
- case "StoreLocal": {
567
+ case 'StoreLocal': {
568
const lvalues = [
569
- { place: value.lvalue.place, level: MemoizationLevel.Conditional },
569
+ {place: value.lvalue.place, level: MemoizationLevel.Conditional},
570
];
571
if (lvalue !== null) {
572
- lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional });
572
+ lvalues.push({place: lvalue, level: MemoizationLevel.Conditional});
573
}
574
return {
575
// Indirection for the inner value, memoized if the value is
@@ -577,13 +577,13 @@ function computeMemoizationInputs(
577
rvalues: [value.value],
578
};
579
}
580
- case "StoreContext": {
580
+ case 'StoreContext': {
581
// Should never be pruned
582
const lvalues = [
583
- { place: value.lvalue.place, level: MemoizationLevel.Memoized },
583
+ {place: value.lvalue.place, level: MemoizationLevel.Memoized},
584
];
585
if (lvalue !== null) {
586
- lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional });
586
+ lvalues.push({place: lvalue, level: MemoizationLevel.Conditional});
587
}
588
589
return {
@@ -591,10 +591,10 @@ function computeMemoizationInputs(
591
rvalues: [value.value],
592
};
593
}
594
- case "StoreGlobal": {
594
+ case 'StoreGlobal': {
595
const lvalues = [];
596
if (lvalue !== null) {
597
- lvalues.push({ place: lvalue, level: MemoizationLevel.Unmemoized });
597
+ lvalues.push({place: lvalue, level: MemoizationLevel.Unmemoized});
598
}
599
600
return {
@@ -602,11 +602,11 @@ function computeMemoizationInputs(
602
rvalues: [value.value],
603
};
604
}
605
- case "Destructure": {
605
+ case 'Destructure': {
606
// Indirection for the inner value, memoized if the value is
607
const lvalues = [];
608
if (lvalue !== null) {
609
- lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional });
609
+ lvalues.push({place: lvalue, level: MemoizationLevel.Conditional});
610
}
611
lvalues.push(...computePatternLValues(value.lvalue.pattern));
612
return {
@@ -614,14 +614,14 @@ function computeMemoizationInputs(
614
rvalues: [value.value],
615
};
616
}
617
- case "ComputedLoad":
618
- case "PropertyLoad": {
617
+ case 'ComputedLoad':
618
+ case 'PropertyLoad': {
619
const level = options.forceMemoizePrimitives
620
? MemoizationLevel.Memoized
621
: MemoizationLevel.Conditional;
622
return {
623
// Indirection for the inner value, memoized if the value is
624
- lvalues: lvalue !== null ? [{ place: lvalue, level }] : [],
624
+ lvalues: lvalue !== null ? [{place: lvalue, level}] : [],
625
/*
626
* Only the object is aliased to the result, and the result only needs to be
627
* memoized if the object is
@@ -629,27 +629,27 @@ function computeMemoizationInputs(
629
rvalues: [value.object],
630
};
631
}
632
- case "ComputedStore": {
632
+ case 'ComputedStore': {
633
/*
634
* The object being stored to acts as an lvalue (it aliases the value), but
635
* the computed key is not aliased
636
*/
637
const lvalues = [
638
- { place: value.object, level: MemoizationLevel.Conditional },
638
+ {place: value.object, level: MemoizationLevel.Conditional},
639
];
640
if (lvalue !== null) {
641
- lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional });
641
+ lvalues.push({place: lvalue, level: MemoizationLevel.Conditional});
642
}
643
return {
644
lvalues,
645
rvalues: [value.value],
646
};
647
}
648
- case "OptionalExpression": {
648
+ case 'OptionalExpression': {
649
// Indirection for the inner value, memoized if the value is
650
const lvalues = [];
651
if (lvalue !== null) {
652
- lvalues.push({ place: lvalue, level: MemoizationLevel.Conditional });
652
+ lvalues.push({place: lvalue, level: MemoizationLevel.Conditional});
653
}
654
return {
655
lvalues: lvalues,
@@ -658,15 +658,15 @@ function computeMemoizationInputs(
658
],
659
};
660
}
661
- case "CallExpression": {
661
+ case 'CallExpression': {
662
const signature = getFunctionCallSignature(
663
env,
664
- value.callee.identifier.type
664
+ value.callee.identifier.type,
665
);
666
const operands = [...eachReactiveValueOperand(value)];
667
let lvalues = [];
668
if (lvalue !== null) {
669
- lvalues.push({ place: lvalue, level: MemoizationLevel.Memoized });
669
+ lvalues.push({place: lvalue, level: MemoizationLevel.Memoized});
670
}
671
if (signature?.noAlias === true) {
672
return {
@@ -676,23 +676,23 @@ function computeMemoizationInputs(
676
}
677
lvalues.push(
678
...operands
679
- .filter((operand) => isMutableEffect(operand.effect, operand.loc))
680
- .map((place) => ({ place, level: MemoizationLevel.Memoized }))
679
+ .filter(operand => isMutableEffect(operand.effect, operand.loc))
680
+ .map(place => ({place, level: MemoizationLevel.Memoized})),
681
);
682
return {
683
lvalues,
684
rvalues: operands,
685
};
686
}
687
- case "MethodCall": {
687
+ case 'MethodCall': {
688
const signature = getFunctionCallSignature(
689
env,
690
- value.property.identifier.type
690
+ value.property.identifier.type,
691
);
692
const operands = [...eachReactiveValueOperand(value)];
693
let lvalues = [];
694
if (lvalue !== null) {
695
- lvalues.push({ place: lvalue, level: MemoizationLevel.Memoized });
695
+ lvalues.push({place: lvalue, level: MemoizationLevel.Memoized});
696
}
697
if (signature?.noAlias === true) {
698
return {
@@ -702,39 +702,39 @@ function computeMemoizationInputs(
702
}
703
lvalues.push(
704
...operands
705
- .filter((operand) => isMutableEffect(operand.effect, operand.loc))
706
- .map((place) => ({ place, level: MemoizationLevel.Memoized }))
705
+ .filter(operand => isMutableEffect(operand.effect, operand.loc))
706
+ .map(place => ({place, level: MemoizationLevel.Memoized})),
707
);
708
return {
709
lvalues,
710
rvalues: operands,
711
};
712
}
713
- case "RegExpLiteral":
714
- case "ObjectMethod":
715
- case "FunctionExpression":
716
- case "TaggedTemplateExpression":
717
- case "ArrayExpression":
718
- case "NewExpression":
719
- case "ObjectExpression":
720
- case "PropertyStore": {
713
+ case 'RegExpLiteral':
714
+ case 'ObjectMethod':
715
+ case 'FunctionExpression':
716
+ case 'TaggedTemplateExpression':
717
+ case 'ArrayExpression':
718
+ case 'NewExpression':
719
+ case 'ObjectExpression':
720
+ case 'PropertyStore': {
721
/*
722
* All of these instructions may produce new values which must be memoized if
723
* reachable from a return value. Any mutable rvalue may alias any other rvalue
724
*/
725
const operands = [...eachReactiveValueOperand(value)];
726
const lvalues = operands
727
- .filter((operand) => isMutableEffect(operand.effect, operand.loc))
728
- .map((place) => ({ place, level: MemoizationLevel.Memoized }));
727
+ .filter(operand => isMutableEffect(operand.effect, operand.loc))
728
+ .map(place => ({place, level: MemoizationLevel.Memoized}));
729
if (lvalue !== null) {
730
- lvalues.push({ place: lvalue, level: MemoizationLevel.Memoized });
730
+ lvalues.push({place: lvalue, level: MemoizationLevel.Memoized});
731
}
732
return {
733
lvalues,
734
rvalues: operands,
735
};
736
}
737
- case "ReactiveFunctionValue": {
737
+ case 'ReactiveFunctionValue': {
738
CompilerError.invariant(false, {
739
reason: `Unexpected ReactiveFunctionValue node`,
740
description: null,
@@ -742,7 +742,7 @@ function computeMemoizationInputs(
742
suggestions: null,
743
});
744
}
745
- case "UnsupportedNode": {
745
+ case 'UnsupportedNode': {
746
CompilerError.invariant(false, {
747
reason: `Unexpected unsupported node`,
748
description: null,
@@ -753,7 +753,7 @@ function computeMemoizationInputs(
753
default: {
754
assertExhaustive(
755
value,
756
- `Unexpected value kind \`${(value as any).kind}\``
756
+ `Unexpected value kind \`${(value as any).kind}\``,
757
);
758
}
759
}
@@ -762,19 +762,19 @@ function computeMemoizationInputs(
762
function computePatternLValues(pattern: Pattern): Array<LValueMemoization> {
763
const lvalues: Array<LValueMemoization> = [];
764
switch (pattern.kind) {
765
- case "ArrayPattern": {
765
+ case 'ArrayPattern': {
766
for (const item of pattern.items) {
767
- if (item.kind === "Identifier") {
768
- lvalues.push({ place: item, level: MemoizationLevel.Conditional });
769
- } else if (item.kind === "Spread") {
770
- lvalues.push({ place: item.place, level: MemoizationLevel.Memoized });
767
+ if (item.kind === 'Identifier') {
768
+ lvalues.push({place: item, level: MemoizationLevel.Conditional});
769
+ } else if (item.kind === 'Spread') {
770
+ lvalues.push({place: item.place, level: MemoizationLevel.Memoized});
771
}
772
}
773
break;
774
}
775
- case "ObjectPattern": {
775
+ case 'ObjectPattern': {
776
for (const property of pattern.properties) {
777
- if (property.kind === "ObjectProperty") {
777
+ if (property.kind === 'ObjectProperty') {
778
lvalues.push({
779
place: property.place,
780
level: MemoizationLevel.Conditional,
@@ -791,7 +791,7 @@ function computePatternLValues(pattern: Pattern): Array<LValueMemoization> {
791
default: {
792
assertExhaustive(
793
pattern,
794
- `Unexpected pattern kind \`${(pattern as any).kind}\``
794
+ `Unexpected pattern kind \`${(pattern as any).kind}\``,
795
);
796
}
797
}
@@ -817,7 +817,7 @@ class CollectDependenciesVisitor extends ReactiveFunctionVisitor<State> {
817
818
override visitInstruction(
819
instruction: ReactiveInstruction,
820
- state: State
820
+ state: State,
821
): void {
822
this.traverseInstruction(instruction, state);
823
@@ -826,7 +826,7 @@ class CollectDependenciesVisitor extends ReactiveFunctionVisitor<State> {
826
this.env,
827
instruction.value,
828
instruction.lvalue,
829
- this.options
829
+ this.options,
830
);
831
832
// Associate all the rvalues with the instruction's scope if it has one
@@ -837,7 +837,7 @@ class CollectDependenciesVisitor extends ReactiveFunctionVisitor<State> {
837
}
838
839
// Add the operands as dependencies of all lvalues.
840
- for (const { place: lvalue, level } of aliasing.lvalues) {
840
+ for (const {place: lvalue, level} of aliasing.lvalues) {
841
const lvalueId =
842
state.definitions.get(lvalue.identifier.id) ?? lvalue.identifier.id;
843
let node = state.identifiers.get(lvalueId);
@@ -868,23 +868,23 @@ class CollectDependenciesVisitor extends ReactiveFunctionVisitor<State> {
868
state.visitOperand(instruction.id, lvalue, lvalueId);
869
}
870
871
- if (instruction.value.kind === "LoadLocal" && instruction.lvalue !== null) {
871
+ if (instruction.value.kind === 'LoadLocal' && instruction.lvalue !== null) {
872
state.definitions.set(
873
instruction.lvalue.identifier.id,
874
- instruction.value.place.identifier.id
874
+ instruction.value.place.identifier.id,
875
);
876
} else if (
877
- instruction.value.kind === "CallExpression" ||
878
- instruction.value.kind === "MethodCall"
877
+ instruction.value.kind === 'CallExpression' ||
878
+ instruction.value.kind === 'MethodCall'
879
) {
880
let callee =
881
- instruction.value.kind === "CallExpression"
881
+ instruction.value.kind === 'CallExpression'
882
? instruction.value.callee
883
: instruction.value.property;
884
if (getHookKind(state.env, callee.identifier) != null) {
885
const signature = getFunctionCallSignature(
886
this.env,
887
- callee.identifier.type
887
+ callee.identifier.type,
888
);
889
/*
890
* Hook values are assumed to escape by default since they can be inputs
@@ -896,7 +896,7 @@ class CollectDependenciesVisitor extends ReactiveFunctionVisitor<State> {
896
return;
897
}
898
for (const operand of instruction.value.args) {
899
- const place = operand.kind === "Spread" ? operand.place : operand;
899
+ const place = operand.kind === 'Spread' ? operand.place : operand;
900
state.escapingValues.add(place.identifier.id);
901
}
902
}
@@ -905,11 +905,11 @@ class CollectDependenciesVisitor extends ReactiveFunctionVisitor<State> {
905
906
override visitTerminal(
907
stmt: ReactiveTerminalStatement<ReactiveTerminal>,
908
- state: State
908
+ state: State,
909
): void {
910
this.traverseTerminal(stmt, state);
911
912
- if (stmt.terminal.kind === "return") {
912
+ if (stmt.terminal.kind === 'return') {
913
state.escapingValues.add(stmt.terminal.value.identifier.id);
914
}
915
}
@@ -923,7 +923,7 @@ class PruneScopesTransform extends ReactiveFunctionTransform<
923
924
override transformScope(
925
scopeBlock: ReactiveScopeBlock,
926
- state: Set<IdentifierId>
926
+ state: Set<IdentifierId>,
927
): Transformed<ReactiveStatement> {
928
this.visitScope(scopeBlock, state);
929
@@ -941,22 +941,22 @@ class PruneScopesTransform extends ReactiveFunctionTransform<
941
scopeBlock.scope.reassignments.size === 0) ||
942
scopeBlock.scope.earlyReturnValue !== null
943
) {
944
- return { kind: "keep" };
944
+ return {kind: 'keep'};
945
}
946
947
const hasMemoizedOutput =
948
- Array.from(scopeBlock.scope.declarations.keys()).some((id) =>
949
- state.has(id)
948
+ Array.from(scopeBlock.scope.declarations.keys()).some(id =>
949
+ state.has(id),
950
) ||
951
- Array.from(scopeBlock.scope.reassignments).some((identifier) =>
952
- state.has(identifier.id)
951
+ Array.from(scopeBlock.scope.reassignments).some(identifier =>
952
+ state.has(identifier.id),
953
);
954
if (hasMemoizedOutput) {
955
- return { kind: "keep" };
955
+ return {kind: 'keep'};
956
} else {
957
this.prunedScopes.add(scopeBlock.scope.id);
958
return {
959
- kind: "replace-many",
959
+ kind: 'replace-many',
960
value: scopeBlock.instructions,
961
};
962
}
@@ -964,7 +964,7 @@ class PruneScopesTransform extends ReactiveFunctionTransform<
964
965
override transformInstruction(
966
instruction: ReactiveInstruction,
967
- state: Set<IdentifierId>
967
+ state: Set<IdentifierId>,
968
): Transformed<ReactiveStatement> {
969
this.traverseInstruction(instruction, state);
970
@@ -973,7 +973,7 @@ class PruneScopesTransform extends ReactiveFunctionTransform<
973
* need to be memoized. Remove associated `Memoize` instructions so that
974
* we don't report false positives on "missing" memoization of these values.
975
*/
976
- if (instruction.value.kind === "FinishMemoize") {
976
+ if (instruction.value.kind === 'FinishMemoize') {
977
const identifier = instruction.value.decl.identifier;
978
if (
979
identifier.scope !== null &&
@@ -983,6 +983,6 @@ class PruneScopesTransform extends ReactiveFunctionTransform<
983
}
984
}
985
986
- return { kind: "keep" };
986
+ return {kind: 'keep'};
987
}
988
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PruneNonReactiveDependencies.ts
+12
-12
@@ -11,10 +11,10 @@ import {
11
ReactiveInstruction,
12
ReactiveScopeBlock,
13
isStableType,
14
-} from "../HIR";
15
-import { eachPatternOperand } from "../HIR/visitors";
16
-import { collectReactiveIdentifiers } from "./CollectReactiveIdentifiers";
17
-import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors";
14
+} from '../HIR';
15
+import {eachPatternOperand} from '../HIR/visitors';
16
+import {collectReactiveIdentifiers} from './CollectReactiveIdentifiers';
17
+import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
18
19
/*
20
* PropagateScopeDependencies infers dependencies without considering whether dependencies
@@ -32,19 +32,19 @@ type ReactiveIdentifiers = Set<IdentifierId>;
32
class Visitor extends ReactiveFunctionVisitor<ReactiveIdentifiers> {
33
override visitInstruction(
34
instruction: ReactiveInstruction,
35
- state: ReactiveIdentifiers
35
+ state: ReactiveIdentifiers,
36
): void {
37
this.traverseInstruction(instruction, state);
38
39
- const { lvalue, value } = instruction;
39
+ const {lvalue, value} = instruction;
40
switch (value.kind) {
41
- case "LoadLocal": {
41
+ case 'LoadLocal': {
42
if (lvalue !== null && state.has(value.place.identifier.id)) {
43
state.add(lvalue.identifier.id);
44
}
45
break;
46
}
47
- case "StoreLocal": {
47
+ case 'StoreLocal': {
48
if (state.has(value.value.identifier.id)) {
49
state.add(value.lvalue.place.identifier.id);
50
if (lvalue !== null) {
@@ -53,7 +53,7 @@ class Visitor extends ReactiveFunctionVisitor<ReactiveIdentifiers> {
53
}
54
break;
55
}
56
- case "Destructure": {
56
+ case 'Destructure': {
57
if (state.has(value.value.identifier.id)) {
58
for (const lvalue of eachPatternOperand(value.lvalue.pattern)) {
59
if (isStableType(lvalue.identifier)) {
@@ -67,7 +67,7 @@ class Visitor extends ReactiveFunctionVisitor<ReactiveIdentifiers> {
67
}
68
break;
69
}
70
- case "PropertyLoad": {
70
+ case 'PropertyLoad': {
71
if (
72
lvalue !== null &&
73
state.has(value.object.identifier.id) &&
@@ -77,7 +77,7 @@ class Visitor extends ReactiveFunctionVisitor<ReactiveIdentifiers> {
77
}
78
break;
79
}
80
- case "ComputedLoad": {
80
+ case 'ComputedLoad': {
81
if (
82
lvalue !== null &&
83
(state.has(value.object.identifier.id) ||
@@ -92,7 +92,7 @@ class Visitor extends ReactiveFunctionVisitor<ReactiveIdentifiers> {
92
93
override visitScope(
94
scopeBlock: ReactiveScopeBlock,
95
- state: ReactiveIdentifiers
95
+ state: ReactiveIdentifiers,
96
): void {
97
this.traverseScope(scopeBlock, state);
98
for (const dep of scopeBlock.scope.dependencies) {
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PruneTemporaryLValues.ts
+3
-3
@@ -11,8 +11,8 @@ import {
11
Place,
12
ReactiveFunction,
13
ReactiveInstruction,
14
-} from "../HIR/HIR";
15
-import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors";
14
+} from '../HIR/HIR';
15
+import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
16
17
/*
18
* Nulls out lvalues for temporary variables that are never accessed later. This only
@@ -34,7 +34,7 @@ class Visitor extends ReactiveFunctionVisitor<LValues> {
34
}
35
override visitInstruction(
36
instruction: ReactiveInstruction,
37
- state: LValues
37
+ state: LValues,
38
): void {
39
this.traverseInstruction(instruction, state);
40
if (
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PruneUnusedLabels.ts
+11
-11
@@ -10,12 +10,12 @@ import {
10
ReactiveFunction,
11
ReactiveStatement,
12
ReactiveTerminalStatement,
13
-} from "../HIR/HIR";
13
+} from '../HIR/HIR';
14
import {
15
ReactiveFunctionTransform,
16
Transformed,
17
visitReactiveFunction,
18
-} from "./visitors";
18
+} from './visitors';
19
20
/*
21
* Flattens labeled terminals where the label is not reachable, and
@@ -31,36 +31,36 @@ type Labels = Set<BlockId>;
31
class Transform extends ReactiveFunctionTransform<Labels> {
32
override transformTerminal(
33
stmt: ReactiveTerminalStatement,
34
- state: Labels
34
+ state: Labels,
35
): Transformed<ReactiveStatement> {
36
this.traverseTerminal(stmt, state);
37
- const { terminal } = stmt;
37
+ const {terminal} = stmt;
38
if (
39
- (terminal.kind === "break" || terminal.kind === "continue") &&
40
- terminal.targetKind === "labeled"
39
+ (terminal.kind === 'break' || terminal.kind === 'continue') &&
40
+ terminal.targetKind === 'labeled'
41
) {
42
state.add(terminal.target);
43
}
44
// Is this terminal reachable via a break/continue to its label?
45
const isReachableLabel = stmt.label !== null && state.has(stmt.label.id);
46
- if (stmt.terminal.kind === "label" && !isReachableLabel) {
46
+ if (stmt.terminal.kind === 'label' && !isReachableLabel) {
47
// Flatten labeled terminals where the label isn't necessary
48
const block = [...stmt.terminal.block];
49
const last = block.at(-1);
50
if (
51
last !== undefined &&
52
- last.kind === "terminal" &&
53
- last.terminal.kind === "break" &&
52
+ last.kind === 'terminal' &&
53
+ last.terminal.kind === 'break' &&
54
last.terminal.target === null
55
) {
56
block.pop();
57
}
58
- return { kind: "replace-many", value: block };
58
+ return {kind: 'replace-many', value: block};
59
} else {
60
if (!isReachableLabel && stmt.label != null) {
61
stmt.label.implicit = true;
62
}
63
- return { kind: "keep" };
63
+ return {kind: 'keep'};
64
}
65
}
66
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/PruneUnusedScopes.ts
+8
-8
@@ -10,12 +10,12 @@ import {
10
ReactiveScopeBlock,
11
ReactiveStatement,
12
ReactiveTerminalStatement,
13
-} from "../HIR/HIR";
13
+} from '../HIR/HIR';
14
import {
15
ReactiveFunctionTransform,
16
Transformed,
17
visitReactiveFunction,
18
-} from "./visitors";
18
+} from './visitors';
19
20
// Converts scopes without outputs into regular blocks.
21
export function pruneUnusedScopes(fn: ReactiveFunction): void {
@@ -31,15 +31,15 @@ type State = {
31
class Transform extends ReactiveFunctionTransform<State> {
32
override visitTerminal(stmt: ReactiveTerminalStatement, state: State): void {
33
this.traverseTerminal(stmt, state);
34
- if (stmt.terminal.kind === "return") {
34
+ if (stmt.terminal.kind === 'return') {
35
state.hasReturnStatement = true;
36
}
37
}
38
override transformScope(
39
scopeBlock: ReactiveScopeBlock,
40
- _state: State
40
+ _state: State,
41
): Transformed<ReactiveStatement> {
42
- const scopeState: State = { hasReturnStatement: false };
42
+ const scopeState: State = {hasReturnStatement: false};
43
this.visitScope(scopeBlock, scopeState);
44
if (
45
!scopeState.hasReturnStatement &&
@@ -52,15 +52,15 @@ class Transform extends ReactiveFunctionTransform<State> {
52
!hasOwnDeclaration(scopeBlock))
53
) {
54
return {
55
- kind: "replace",
55
+ kind: 'replace',
56
value: {
57
- kind: "pruned-scope",
57
+ kind: 'pruned-scope',
58
scope: scopeBlock.scope,
59
instructions: scopeBlock.instructions,
60
},
61
};
62
} else {
63
- return { kind: "keep" };
63
+ return {kind: 'keep'};
64
}
65
}
66
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/RenameVariables.ts
+11
-11
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
8
+import {CompilerError} from '../CompilerError';
9
import {
10
Identifier,
11
IdentifierId,
@@ -21,9 +21,9 @@ import {
21
isPromotedJsxTemporary,
22
isPromotedTemporary,
23
makeIdentifierName,
24
-} from "../HIR/HIR";
25
-import { collectReferencedGlobals } from "./CollectReferencedGlobals";
26
-import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors";
24
+} from '../HIR/HIR';
25
+import {collectReferencedGlobals} from './CollectReferencedGlobals';
26
+import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
27
28
/**
29
* Ensures that each named variable in the given function has a unique name
@@ -55,11 +55,11 @@ export function renameVariables(fn: ReactiveFunction): Set<string> {
55
function renameVariablesImpl(
56
fn: ReactiveFunction,
57
visitor: Visitor,
58
- scopes: Scopes
58
+ scopes: Scopes,
59
): void {
60
scopes.enter(() => {
61
for (const param of fn.params) {
62
- if (param.kind === "Identifier") {
62
+ if (param.kind === 'Identifier') {
63
scopes.visit(param.identifier);
64
} else {
65
scopes.visit(param.place.identifier);
@@ -87,7 +87,7 @@ class Visitor extends ReactiveFunctionVisitor<Scopes> {
87
88
override visitPrunedScope(
89
scopeBlock: PrunedReactiveScopeBlock,
90
- state: Scopes
90
+ state: Scopes,
91
): void {
92
this.traverseBlock(scopeBlock.instructions, state);
93
}
@@ -102,10 +102,10 @@ class Visitor extends ReactiveFunctionVisitor<Scopes> {
102
override visitValue(
103
id: InstructionId,
104
value: ReactiveValue,
105
- state: Scopes
105
+ state: Scopes,
106
): void {
107
this.traverseValue(id, value, state);
108
- if (value.kind === "FunctionExpression" || value.kind === "ObjectMethod") {
108
+ if (value.kind === 'FunctionExpression' || value.kind === 'ObjectMethod') {
109
this.visitHirFunction(value.loweredFunc.func, state);
110
}
111
}
@@ -114,7 +114,7 @@ class Visitor extends ReactiveFunctionVisitor<Scopes> {
114
_id: InstructionId,
115
_dependencies: Array<Place>,
116
_fn: ReactiveFunction,
117
- _state: Scopes
117
+ _state: Scopes,
118
): void {
119
renameVariablesImpl(_fn, this, _state);
120
}
@@ -180,7 +180,7 @@ class Scopes {
180
fn();
181
const last = this.#stack.pop();
182
CompilerError.invariant(last === next, {
183
- reason: "Mismatch push/pop calls",
183
+ reason: 'Mismatch push/pop calls',
184
description: null,
185
loc: null,
186
suggestions: null,
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/StabilizeBlockIds.ts
+11
-11
@@ -4,9 +4,9 @@ import {
4
ReactiveScopeBlock,
5
ReactiveTerminalStatement,
6
makeBlockId,
7
-} from "../HIR";
8
-import { getOrInsertDefault } from "../Utils/utils";
9
-import { ReactiveFunctionVisitor, visitReactiveFunction } from "./visitors";
7
+} from '../HIR';
8
+import {getOrInsertDefault} from '../Utils/utils';
9
+import {ReactiveFunctionVisitor, visitReactiveFunction} from './visitors';
10
11
export function stabilizeBlockIds(fn: ReactiveFunction): void {
12
const referenced: Set<BlockId> = new Set();
@@ -22,7 +22,7 @@ export function stabilizeBlockIds(fn: ReactiveFunction): void {
22
23
class CollectReferencedLabels extends ReactiveFunctionVisitor<Set<BlockId>> {
24
override visitScope(scope: ReactiveScopeBlock, state: Set<BlockId>): void {
25
- const { earlyReturnValue } = scope.scope;
25
+ const {earlyReturnValue} = scope.scope;
26
if (earlyReturnValue != null) {
27
state.add(earlyReturnValue.label);
28
}
@@ -30,7 +30,7 @@ class CollectReferencedLabels extends ReactiveFunctionVisitor<Set<BlockId>> {
30
}
31
override visitTerminal(
32
stmt: ReactiveTerminalStatement,
33
- state: Set<BlockId>
33
+ state: Set<BlockId>,
34
): void {
35
if (stmt.label != null) {
36
if (!stmt.label.implicit) {
@@ -44,14 +44,14 @@ class CollectReferencedLabels extends ReactiveFunctionVisitor<Set<BlockId>> {
44
class RewriteBlockIds extends ReactiveFunctionVisitor<Map<BlockId, BlockId>> {
45
override visitScope(
46
scope: ReactiveScopeBlock,
47
- state: Map<BlockId, BlockId>
47
+ state: Map<BlockId, BlockId>,
48
): void {
49
- const { earlyReturnValue } = scope.scope;
49
+ const {earlyReturnValue} = scope.scope;
50
if (earlyReturnValue != null) {
51
const rewrittenId = getOrInsertDefault(
52
state,
53
earlyReturnValue.label,
54
- state.size
54
+ state.size,
55
);
56
earlyReturnValue.label = makeBlockId(rewrittenId);
57
}
@@ -59,7 +59,7 @@ class RewriteBlockIds extends ReactiveFunctionVisitor<Map<BlockId, BlockId>> {
59
}
60
override visitTerminal(
61
stmt: ReactiveTerminalStatement,
62
- state: Map<BlockId, BlockId>
62
+ state: Map<BlockId, BlockId>,
63
): void {
64
if (stmt.label != null) {
65
const rewrittenId = getOrInsertDefault(state, stmt.label.id, state.size);
@@ -67,11 +67,11 @@ class RewriteBlockIds extends ReactiveFunctionVisitor<Map<BlockId, BlockId>> {
67
}
68
69
const terminal = stmt.terminal;
70
- if (terminal.kind === "break" || terminal.kind === "continue") {
70
+ if (terminal.kind === 'break' || terminal.kind === 'continue') {
71
const rewrittenId = getOrInsertDefault(
72
state,
73
terminal.target,
74
- state.size
74
+ state.size,
75
);
76
terminal.target = makeBlockId(rewrittenId);
77
}
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/index.ts
+28
-31
@@ -5,39 +5,36 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-export { alignObjectMethodScopes } from "./AlignObjectMethodScopes";
9
-export { alignReactiveScopesToBlockScopes } from "./AlignReactiveScopesToBlockScopes";
10
-export { assertScopeInstructionsWithinScopes } from "./AssertScopeInstructionsWithinScope";
11
-export { assertWellFormedBreakTargets } from "./AssertWellFormedBreakTargets";
12
-export { buildReactiveBlocks } from "./BuildReactiveBlocks";
13
-export { buildReactiveFunction } from "./BuildReactiveFunction";
14
-export {
15
- codegenFunction,
16
- type CodegenFunction,
17
-} from "./CodegenReactiveFunction";
18
-export { extractScopeDeclarationsFromDestructuring } from "./ExtractScopeDeclarationsFromDestructuring";
19
-export { flattenReactiveLoops } from "./FlattenReactiveLoops";
20
-export { flattenScopesWithHooksOrUse } from "./FlattenScopesWithHooksOrUse";
21
-export { inferReactiveScopeVariables } from "./InferReactiveScopeVariables";
22
-export { memoizeFbtAndMacroOperandsInSameScope as memoizeFbtOperandsInSameScope } from "./MemoizeFbtAndMacroOperandsInSameScope";
23
-export { mergeOverlappingReactiveScopes } from "./MergeOverlappingReactiveScopes";
24
-export { mergeReactiveScopesThatInvalidateTogether } from "./MergeReactiveScopesThatInvalidateTogether";
25
-export { printReactiveFunction } from "./PrintReactiveFunction";
26
-export { promoteUsedTemporaries } from "./PromoteUsedTemporaries";
27
-export { propagateEarlyReturns } from "./PropagateEarlyReturns";
28
-export { propagateScopeDependencies } from "./PropagateScopeDependencies";
29
-export { pruneAllReactiveScopes } from "./PruneAllReactiveScopes";
30
-export { pruneHoistedContexts } from "./PruneHoistedContexts";
31
-export { pruneNonEscapingScopes } from "./PruneNonEscapingScopes";
32
-export { pruneNonReactiveDependencies } from "./PruneNonReactiveDependencies";
33
-export { pruneTemporaryLValues as pruneUnusedLValues } from "./PruneTemporaryLValues";
34
-export { pruneUnusedLabels } from "./PruneUnusedLabels";
35
-export { pruneUnusedScopes } from "./PruneUnusedScopes";
36
-export { renameVariables } from "./RenameVariables";
37
-export { stabilizeBlockIds } from "./StabilizeBlockIds";
8
+export {alignObjectMethodScopes} from './AlignObjectMethodScopes';
9
+export {alignReactiveScopesToBlockScopes} from './AlignReactiveScopesToBlockScopes';
10
+export {assertScopeInstructionsWithinScopes} from './AssertScopeInstructionsWithinScope';
11
+export {assertWellFormedBreakTargets} from './AssertWellFormedBreakTargets';
12
+export {buildReactiveBlocks} from './BuildReactiveBlocks';
13
+export {buildReactiveFunction} from './BuildReactiveFunction';
14
+export {codegenFunction, type CodegenFunction} from './CodegenReactiveFunction';
15
+export {extractScopeDeclarationsFromDestructuring} from './ExtractScopeDeclarationsFromDestructuring';
16
+export {flattenReactiveLoops} from './FlattenReactiveLoops';
17
+export {flattenScopesWithHooksOrUse} from './FlattenScopesWithHooksOrUse';
18
+export {inferReactiveScopeVariables} from './InferReactiveScopeVariables';
19
+export {memoizeFbtAndMacroOperandsInSameScope as memoizeFbtOperandsInSameScope} from './MemoizeFbtAndMacroOperandsInSameScope';
20
+export {mergeOverlappingReactiveScopes} from './MergeOverlappingReactiveScopes';
21
+export {mergeReactiveScopesThatInvalidateTogether} from './MergeReactiveScopesThatInvalidateTogether';
22
+export {printReactiveFunction} from './PrintReactiveFunction';
23
+export {promoteUsedTemporaries} from './PromoteUsedTemporaries';
24
+export {propagateEarlyReturns} from './PropagateEarlyReturns';
25
+export {propagateScopeDependencies} from './PropagateScopeDependencies';
26
+export {pruneAllReactiveScopes} from './PruneAllReactiveScopes';
27
+export {pruneHoistedContexts} from './PruneHoistedContexts';
28
+export {pruneNonEscapingScopes} from './PruneNonEscapingScopes';
29
+export {pruneNonReactiveDependencies} from './PruneNonReactiveDependencies';
30
+export {pruneTemporaryLValues as pruneUnusedLValues} from './PruneTemporaryLValues';
31
+export {pruneUnusedLabels} from './PruneUnusedLabels';
32
+export {pruneUnusedScopes} from './PruneUnusedScopes';
33
+export {renameVariables} from './RenameVariables';
34
+export {stabilizeBlockIds} from './StabilizeBlockIds';
35
export {
36
ReactiveFunctionTransform,
37
eachReactiveValueOperand,
38
visitReactiveFunction,
39
type Transformed,
43
-} from "./visitors";
40
+} from './visitors';
compiler/packages/babel-plugin-react-compiler/src/ReactiveScopes/visitors.ts
+127
-127
@@ -18,18 +18,18 @@ import {
18
ReactiveTerminal,
19
ReactiveTerminalStatement,
20
ReactiveValue,
21
-} from "../HIR/HIR";
21
+} from '../HIR/HIR';
22
import {
23
eachInstructionLValue,
24
eachInstructionValueOperand,
25
eachTerminalOperand,
26
-} from "../HIR/visitors";
27
-import { assertExhaustive } from "../Utils/utils";
26
+} from '../HIR/visitors';
27
+import {assertExhaustive} from '../Utils/utils';
28
29
export function visitReactiveFunction<TState>(
30
fn: ReactiveFunction,
31
visitor: ReactiveFunctionVisitor<TState>,
32
- state: TState
32
+ state: TState,
33
): void {
34
visitor.visitBlock(fn.body, state);
35
}
@@ -43,7 +43,7 @@ export class ReactiveFunctionVisitor<TState = void> {
43
_id: InstructionId,
44
_dependencies: Array<Place>,
45
_fn: ReactiveFunction,
46
- _state: TState
46
+ _state: TState,
47
): void {}
48
49
visitValue(id: InstructionId, value: ReactiveValue, state: TState): void {
@@ -51,34 +51,34 @@ export class ReactiveFunctionVisitor<TState = void> {
51
}
52
traverseValue(id: InstructionId, value: ReactiveValue, state: TState): void {
53
switch (value.kind) {
54
- case "OptionalExpression": {
54
+ case 'OptionalExpression': {
55
this.visitValue(id, value.value, state);
56
break;
57
}
58
- case "LogicalExpression": {
58
+ case 'LogicalExpression': {
59
this.visitValue(id, value.left, state);
60
this.visitValue(id, value.right, state);
61
break;
62
}
63
- case "ConditionalExpression": {
63
+ case 'ConditionalExpression': {
64
this.visitValue(id, value.test, state);
65
this.visitValue(id, value.consequent, state);
66
this.visitValue(id, value.alternate, state);
67
break;
68
}
69
- case "SequenceExpression": {
69
+ case 'SequenceExpression': {
70
for (const instr of value.instructions) {
71
this.visitInstruction(instr, state);
72
}
73
this.visitValue(value.id, value.value, state);
74
break;
75
}
76
- case "ReactiveFunctionValue": {
76
+ case 'ReactiveFunctionValue': {
77
this.visitReactiveFunctionValue(
78
id,
79
value.dependencies,
80
value.fn,
81
- state
81
+ state,
82
);
83
break;
84
}
@@ -105,24 +105,24 @@ export class ReactiveFunctionVisitor<TState = void> {
105
this.traverseTerminal(stmt, state);
106
}
107
traverseTerminal(stmt: ReactiveTerminalStatement, state: TState): void {
108
- const { terminal } = stmt;
108
+ const {terminal} = stmt;
109
if (terminal.id !== null) {
110
this.visitID(terminal.id, state);
111
}
112
switch (terminal.kind) {
113
- case "break":
114
- case "continue": {
113
+ case 'break':
114
+ case 'continue': {
115
break;
116
}
117
- case "return": {
117
+ case 'return': {
118
this.visitPlace(terminal.id, terminal.value, state);
119
break;
120
}
121
- case "throw": {
121
+ case 'throw': {
122
this.visitPlace(terminal.id, terminal.value, state);
123
break;
124
}
125
- case "for": {
125
+ case 'for': {
126
this.visitValue(terminal.id, terminal.init, state);
127
this.visitValue(terminal.id, terminal.test, state);
128
this.visitBlock(terminal.loop, state);
@@ -131,28 +131,28 @@ export class ReactiveFunctionVisitor<TState = void> {
131
}
132
break;
133
}
134
- case "for-of": {
134
+ case 'for-of': {
135
this.visitValue(terminal.id, terminal.init, state);
136
this.visitValue(terminal.id, terminal.test, state);
137
this.visitBlock(terminal.loop, state);
138
break;
139
}
140
- case "for-in": {
140
+ case 'for-in': {
141
this.visitValue(terminal.id, terminal.init, state);
142
this.visitBlock(terminal.loop, state);
143
break;
144
}
145
- case "do-while": {
145
+ case 'do-while': {
146
this.visitBlock(terminal.loop, state);
147
this.visitValue(terminal.id, terminal.test, state);
148
break;
149
}
150
- case "while": {
150
+ case 'while': {
151
this.visitValue(terminal.id, terminal.test, state);
152
this.visitBlock(terminal.loop, state);
153
break;
154
}
155
- case "if": {
155
+ case 'if': {
156
this.visitPlace(terminal.id, terminal.test, state);
157
this.visitBlock(terminal.consequent, state);
158
if (terminal.alternate !== null) {
@@ -160,7 +160,7 @@ export class ReactiveFunctionVisitor<TState = void> {
160
}
161
break;
162
}
163
- case "switch": {
163
+ case 'switch': {
164
this.visitPlace(terminal.id, terminal.test, state);
165
for (const case_ of terminal.cases) {
166
if (case_.test !== null) {
@@ -172,11 +172,11 @@ export class ReactiveFunctionVisitor<TState = void> {
172
}
173
break;
174
}
175
- case "label": {
175
+ case 'label': {
176
this.visitBlock(terminal.block, state);
177
break;
178
}
179
- case "try": {
179
+ case 'try': {
180
this.visitBlock(terminal.block, state);
181
this.visitBlock(terminal.handler, state);
182
break;
@@ -184,7 +184,7 @@ export class ReactiveFunctionVisitor<TState = void> {
184
default: {
185
assertExhaustive(
186
terminal,
187
- `Unexpected terminal kind \`${(terminal as any).kind}\``
187
+ `Unexpected terminal kind \`${(terminal as any).kind}\``,
188
);
189
}
190
}
@@ -202,7 +202,7 @@ export class ReactiveFunctionVisitor<TState = void> {
202
}
203
traversePrunedScope(
204
scopeBlock: PrunedReactiveScopeBlock,
205
- state: TState
205
+ state: TState,
206
): void {
207
this.visitBlock(scopeBlock.instructions, state);
208
}
@@ -213,26 +213,26 @@ export class ReactiveFunctionVisitor<TState = void> {
213
traverseBlock(block: ReactiveBlock, state: TState): void {
214
for (const instr of block) {
215
switch (instr.kind) {
216
- case "instruction": {
216
+ case 'instruction': {
217
this.visitInstruction(instr.instruction, state);
218
break;
219
}
220
- case "scope": {
220
+ case 'scope': {
221
this.visitScope(instr, state);
222
break;
223
}
224
- case "pruned-scope": {
224
+ case 'pruned-scope': {
225
this.visitPrunedScope(instr, state);
226
break;
227
}
228
- case "terminal": {
228
+ case 'terminal': {
229
this.visitTerminal(instr, state);
230
break;
231
}
232
default: {
233
assertExhaustive(
234
instr,
235
- `Unexpected instruction kind \`${(instr as any).kind}\``
235
+ `Unexpected instruction kind \`${(instr as any).kind}\``,
236
);
237
}
238
}
@@ -241,15 +241,15 @@ export class ReactiveFunctionVisitor<TState = void> {
241
242
visitHirFunction(fn: HIRFunction, state: TState): void {
243
for (const param of fn.params) {
244
- const place = param.kind === "Identifier" ? param : param.place;
244
+ const place = param.kind === 'Identifier' ? param : param.place;
245
this.visitParam(place, state);
246
}
247
for (const [, block] of fn.body.blocks) {
248
for (const instr of block.instructions) {
249
this.visitInstruction(instr, state);
250
if (
251
- instr.value.kind === "FunctionExpression" ||
252
- instr.value.kind === "ObjectMethod"
251
+ instr.value.kind === 'FunctionExpression' ||
252
+ instr.value.kind === 'ObjectMethod'
253
) {
254
this.visitHirFunction(instr.value.loweredFunc.func, state);
255
}
@@ -262,14 +262,14 @@ export class ReactiveFunctionVisitor<TState = void> {
262
}
263
264
export type TransformedValue =
265
- | { kind: "keep" }
266
- | { kind: "replace"; value: ReactiveValue };
265
+ | {kind: 'keep'}
266
+ | {kind: 'replace'; value: ReactiveValue};
267
268
export type Transformed<T> =
269
- | { kind: "remove" }
270
- | { kind: "keep" }
271
- | { kind: "replace"; value: T }
272
- | { kind: "replace-many"; value: Array<T> };
269
+ | {kind: 'remove'}
270
+ | {kind: 'keep'}
271
+ | {kind: 'replace'; value: T}
272
+ | {kind: 'replace-many'; value: Array<T>};
273
274
export class ReactiveFunctionTransform<
275
TState = void,
@@ -280,48 +280,48 @@ export class ReactiveFunctionTransform<
280
const instr = block[i]!;
281
let transformed: Transformed<ReactiveStatement>;
282
switch (instr.kind) {
283
- case "instruction": {
283
+ case 'instruction': {
284
transformed = this.transformInstruction(instr.instruction, state);
285
break;
286
}
287
- case "scope": {
287
+ case 'scope': {
288
transformed = this.transformScope(instr, state);
289
break;
290
}
291
- case "pruned-scope": {
291
+ case 'pruned-scope': {
292
transformed = this.transformPrunedScope(instr, state);
293
break;
294
}
295
- case "terminal": {
295
+ case 'terminal': {
296
transformed = this.transformTerminal(instr, state);
297
break;
298
}
299
default: {
300
assertExhaustive(
301
instr,
302
- `Unexpected instruction kind \`${(instr as any).kind}\``
302
+ `Unexpected instruction kind \`${(instr as any).kind}\``,
303
);
304
}
305
}
306
switch (transformed.kind) {
307
- case "keep": {
307
+ case 'keep': {
308
if (nextBlock !== null) {
309
nextBlock.push(instr);
310
}
311
break;
312
}
313
- case "remove": {
313
+ case 'remove': {
314
if (nextBlock === null) {
315
nextBlock = block.slice(0, i);
316
}
317
break;
318
}
319
- case "replace": {
319
+ case 'replace': {
320
nextBlock ??= block.slice(0, i);
321
nextBlock.push(transformed.value);
322
break;
323
}
324
- case "replace-many": {
324
+ case 'replace-many': {
325
nextBlock ??= block.slice(0, i);
326
nextBlock.push(...transformed.value);
327
break;
@@ -336,112 +336,112 @@ export class ReactiveFunctionTransform<
336
337
transformInstruction(
338
instruction: ReactiveInstruction,
339
- state: TState
339
+ state: TState,
340
): Transformed<ReactiveStatement> {
341
this.visitInstruction(instruction, state);
342
- return { kind: "keep" };
342
+ return {kind: 'keep'};
343
}
344
345
transformTerminal(
346
stmt: ReactiveTerminalStatement,
347
- state: TState
347
+ state: TState,
348
): Transformed<ReactiveStatement> {
349
this.visitTerminal(stmt, state);
350
- return { kind: "keep" };
350
+ return {kind: 'keep'};
351
}
352
353
transformScope(
354
scope: ReactiveScopeBlock,
355
- state: TState
355
+ state: TState,
356
): Transformed<ReactiveStatement> {
357
this.visitScope(scope, state);
358
- return { kind: "keep" };
358
+ return {kind: 'keep'};
359
}
360
361
transformPrunedScope(
362
scope: PrunedReactiveScopeBlock,
363
- state: TState
363
+ state: TState,
364
): Transformed<ReactiveStatement> {
365
this.visitPrunedScope(scope, state);
366
- return { kind: "keep" };
366
+ return {kind: 'keep'};
367
}
368
369
transformValue(
370
id: InstructionId,
371
value: ReactiveValue,
372
- state: TState
372
+ state: TState,
373
): TransformedValue {
374
this.visitValue(id, value, state);
375
- return { kind: "keep" };
375
+ return {kind: 'keep'};
376
}
377
378
transformReactiveFunctionValue(
379
id: InstructionId,
380
dependencies: Array<Place>,
381
fn: ReactiveFunction,
382
- state: TState
383
- ): { kind: "keep" } | { kind: "replace"; value: ReactiveFunction } {
382
+ state: TState,
383
+ ): {kind: 'keep'} | {kind: 'replace'; value: ReactiveFunction} {
384
this.visitReactiveFunctionValue(id, dependencies, fn, state);
385
- return { kind: "keep" };
385
+ return {kind: 'keep'};
386
}
387
388
override traverseValue(
389
id: InstructionId,
390
value: ReactiveValue,
391
- state: TState
391
+ state: TState,
392
): void {
393
switch (value.kind) {
394
- case "OptionalExpression": {
394
+ case 'OptionalExpression': {
395
const nextValue = this.transformValue(id, value.value, state);
396
- if (nextValue.kind === "replace") {
396
+ if (nextValue.kind === 'replace') {
397
value.value = nextValue.value;
398
}
399
break;
400
}
401
- case "LogicalExpression": {
401
+ case 'LogicalExpression': {
402
const left = this.transformValue(id, value.left, state);
403
- if (left.kind === "replace") {
403
+ if (left.kind === 'replace') {
404
value.left = left.value;
405
}
406
const right = this.transformValue(id, value.right, state);
407
- if (right.kind === "replace") {
407
+ if (right.kind === 'replace') {
408
value.right = right.value;
409
}
410
break;
411
}
412
- case "ConditionalExpression": {
412
+ case 'ConditionalExpression': {
413
const test = this.transformValue(id, value.test, state);
414
- if (test.kind === "replace") {
414
+ if (test.kind === 'replace') {
415
value.test = test.value;
416
}
417
const consequent = this.transformValue(id, value.consequent, state);
418
- if (consequent.kind === "replace") {
418
+ if (consequent.kind === 'replace') {
419
value.consequent = consequent.value;
420
}
421
const alternate = this.transformValue(id, value.alternate, state);
422
- if (alternate.kind === "replace") {
422
+ if (alternate.kind === 'replace') {
423
value.alternate = alternate.value;
424
}
425
break;
426
}
427
- case "SequenceExpression": {
427
+ case 'SequenceExpression': {
428
for (const instr of value.instructions) {
429
this.visitInstruction(instr, state);
430
}
431
const nextValue = this.transformValue(value.id, value.value, state);
432
- if (nextValue.kind === "replace") {
432
+ if (nextValue.kind === 'replace') {
433
value.value = nextValue.value;
434
}
435
break;
436
}
437
- case "ReactiveFunctionValue": {
437
+ case 'ReactiveFunctionValue': {
438
const nextValue = this.transformReactiveFunctionValue(
439
id,
440
value.dependencies,
441
value.fn,
442
- state
442
+ state,
443
);
444
- if (nextValue.kind === "replace") {
444
+ if (nextValue.kind === 'replace') {
445
value.fn = nextValue.value;
446
}
447
break;
@@ -456,7 +456,7 @@ export class ReactiveFunctionTransform<
456
457
override traverseInstruction(
458
instruction: ReactiveInstruction,
459
- state: TState
459
+ state: TState,
460
): void {
461
this.visitID(instruction.id, state);
462
for (const operand of eachInstructionLValue(instruction)) {
@@ -465,93 +465,93 @@ export class ReactiveFunctionTransform<
465
const nextValue = this.transformValue(
466
instruction.id,
467
instruction.value,
468
- state
468
+ state,
469
);
470
- if (nextValue.kind === "replace") {
470
+ if (nextValue.kind === 'replace') {
471
instruction.value = nextValue.value;
472
}
473
}
474
475
override traverseTerminal(
476
stmt: ReactiveTerminalStatement,
477
- state: TState
477
+ state: TState,
478
): void {
479
- const { terminal } = stmt;
479
+ const {terminal} = stmt;
480
if (terminal.id !== null) {
481
this.visitID(terminal.id, state);
482
}
483
switch (terminal.kind) {
484
- case "break":
485
- case "continue": {
484
+ case 'break':
485
+ case 'continue': {
486
break;
487
}
488
- case "return": {
488
+ case 'return': {
489
this.visitPlace(terminal.id, terminal.value, state);
490
break;
491
}
492
- case "throw": {
492
+ case 'throw': {
493
this.visitPlace(terminal.id, terminal.value, state);
494
break;
495
}
496
- case "for": {
496
+ case 'for': {
497
const init = this.transformValue(terminal.id, terminal.init, state);
498
- if (init.kind === "replace") {
498
+ if (init.kind === 'replace') {
499
terminal.init = init.value;
500
}
501
const test = this.transformValue(terminal.id, terminal.test, state);
502
- if (test.kind === "replace") {
502
+ if (test.kind === 'replace') {
503
terminal.test = test.value;
504
}
505
if (terminal.update !== null) {
506
const update = this.transformValue(
507
terminal.id,
508
terminal.update,
509
- state
509
+ state,
510
);
511
- if (update.kind === "replace") {
511
+ if (update.kind === 'replace') {
512
terminal.update = update.value;
513
}
514
}
515
this.visitBlock(terminal.loop, state);
516
break;
517
}
518
- case "for-of": {
518
+ case 'for-of': {
519
const init = this.transformValue(terminal.id, terminal.init, state);
520
- if (init.kind === "replace") {
520
+ if (init.kind === 'replace') {
521
terminal.init = init.value;
522
}
523
const test = this.transformValue(terminal.id, terminal.test, state);
524
- if (test.kind === "replace") {
524
+ if (test.kind === 'replace') {
525
terminal.test = test.value;
526
}
527
this.visitBlock(terminal.loop, state);
528
break;
529
}
530
- case "for-in": {
530
+ case 'for-in': {
531
const init = this.transformValue(terminal.id, terminal.init, state);
532
- if (init.kind === "replace") {
532
+ if (init.kind === 'replace') {
533
terminal.init = init.value;
534
}
535
this.visitBlock(terminal.loop, state);
536
break;
537
}
538
- case "do-while": {
538
+ case 'do-while': {
539
this.visitBlock(terminal.loop, state);
540
const test = this.transformValue(terminal.id, terminal.test, state);
541
- if (test.kind === "replace") {
541
+ if (test.kind === 'replace') {
542
terminal.test = test.value;
543
}
544
break;
545
}
546
- case "while": {
546
+ case 'while': {
547
const test = this.transformValue(terminal.id, terminal.test, state);
548
- if (test.kind === "replace") {
548
+ if (test.kind === 'replace') {
549
terminal.test = test.value;
550
}
551
this.visitBlock(terminal.loop, state);
552
break;
553
}
554
- case "if": {
554
+ case 'if': {
555
this.visitPlace(terminal.id, terminal.test, state);
556
this.visitBlock(terminal.consequent, state);
557
if (terminal.alternate !== null) {
@@ -559,7 +559,7 @@ export class ReactiveFunctionTransform<
559
}
560
break;
561
}
562
- case "switch": {
562
+ case 'switch': {
563
this.visitPlace(terminal.id, terminal.test, state);
564
for (const case_ of terminal.cases) {
565
if (case_.test !== null) {
@@ -571,11 +571,11 @@ export class ReactiveFunctionTransform<
571
}
572
break;
573
}
574
- case "label": {
574
+ case 'label': {
575
this.visitBlock(terminal.block, state);
576
break;
577
}
578
- case "try": {
578
+ case 'try': {
579
this.visitBlock(terminal.block, state);
580
if (terminal.handlerBinding !== null) {
581
this.visitPlace(terminal.id, terminal.handlerBinding, state);
@@ -586,7 +586,7 @@ export class ReactiveFunctionTransform<
586
default: {
587
assertExhaustive(
588
terminal,
589
- `Unexpected terminal kind \`${(terminal as any).kind}\``
589
+ `Unexpected terminal kind \`${(terminal as any).kind}\``,
590
);
591
}
592
}
@@ -594,32 +594,32 @@ export class ReactiveFunctionTransform<
594
}
595
596
export function* eachReactiveValueOperand(
597
- instrValue: ReactiveValue
597
+ instrValue: ReactiveValue,
598
): Iterable<Place> {
599
switch (instrValue.kind) {
600
- case "OptionalExpression": {
600
+ case 'OptionalExpression': {
601
yield* eachReactiveValueOperand(instrValue.value);
602
break;
603
}
604
- case "LogicalExpression": {
604
+ case 'LogicalExpression': {
605
yield* eachReactiveValueOperand(instrValue.left);
606
yield* eachReactiveValueOperand(instrValue.right);
607
break;
608
}
609
- case "SequenceExpression": {
609
+ case 'SequenceExpression': {
610
for (const instr of instrValue.instructions) {
611
yield* eachReactiveValueOperand(instr.value);
612
}
613
yield* eachReactiveValueOperand(instrValue.value);
614
break;
615
}
616
- case "ConditionalExpression": {
616
+ case 'ConditionalExpression': {
617
yield* eachReactiveValueOperand(instrValue.test);
618
yield* eachReactiveValueOperand(instrValue.consequent);
619
yield* eachReactiveValueOperand(instrValue.alternate);
620
break;
621
}
622
- case "ReactiveFunctionValue": {
622
+ case 'ReactiveFunctionValue': {
623
yield* instrValue.dependencies;
624
break;
625
}
@@ -631,40 +631,40 @@ export function* eachReactiveValueOperand(
631
632
export function mapTerminalBlocks(
633
terminal: ReactiveTerminal,
634
- fn: (block: ReactiveBlock) => ReactiveBlock
634
+ fn: (block: ReactiveBlock) => ReactiveBlock,
635
): void {
636
switch (terminal.kind) {
637
- case "break":
638
- case "continue":
639
- case "return":
640
- case "throw": {
637
+ case 'break':
638
+ case 'continue':
639
+ case 'return':
640
+ case 'throw': {
641
break;
642
}
643
- case "for": {
643
+ case 'for': {
644
terminal.loop = fn(terminal.loop);
645
break;
646
}
647
- case "for-of": {
647
+ case 'for-of': {
648
terminal.loop = fn(terminal.loop);
649
break;
650
}
651
- case "for-in": {
651
+ case 'for-in': {
652
terminal.loop = fn(terminal.loop);
653
break;
654
}
655
- case "do-while":
656
- case "while": {
655
+ case 'do-while':
656
+ case 'while': {
657
terminal.loop = fn(terminal.loop);
658
break;
659
}
660
- case "if": {
660
+ case 'if': {
661
terminal.consequent = fn(terminal.consequent);
662
if (terminal.alternate !== null) {
663
terminal.alternate = fn(terminal.alternate);
664
}
665
break;
666
}
667
- case "switch": {
667
+ case 'switch': {
668
for (const case_ of terminal.cases) {
669
if (case_.block !== undefined) {
670
case_.block = fn(case_.block);
@@ -672,11 +672,11 @@ export function mapTerminalBlocks(
672
}
673
break;
674
}
675
- case "label": {
675
+ case 'label': {
676
terminal.block = fn(terminal.block);
677
break;
678
}
679
- case "try": {
679
+ case 'try': {
680
terminal.block = fn(terminal.block);
681
terminal.handler = fn(terminal.handler);
682
break;
@@ -684,7 +684,7 @@ export function mapTerminalBlocks(
684
default: {
685
assertExhaustive(
686
terminal,
687
- `Unexpected terminal kind \`${(terminal as any).kind}\``
687
+ `Unexpected terminal kind \`${(terminal as any).kind}\``,
688
);
689
}
690
}
compiler/packages/babel-plugin-react-compiler/src/SSA/EliminateRedundantPhi.ts
+11
-11
@@ -5,13 +5,13 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
9
-import { BlockId, HIRFunction, Identifier, Place } from "../HIR/HIR";
8
+import {CompilerError} from '../CompilerError';
9
+import {BlockId, HIRFunction, Identifier, Place} from '../HIR/HIR';
10
import {
11
eachInstructionLValue,
12
eachInstructionOperand,
13
eachTerminalOperand,
14
-} from "../HIR/visitors";
14
+} from '../HIR/visitors';
15
16
/*
17
* Pass to eliminate redundant phi nodes:
@@ -29,7 +29,7 @@ import {
29
*/
30
export function eliminateRedundantPhi(
31
fn: HIRFunction,
32
- sharedRewrites?: Map<Identifier, Identifier>
32
+ sharedRewrites?: Map<Identifier, Identifier>,
33
): void {
34
const ir = fn.body;
35
const rewrites: Map<Identifier, Identifier> =
@@ -72,7 +72,7 @@ export function eliminateRedundantPhi(
72
Array.from(phi.operands).map(([block, id]) => [
73
block,
74
rewrites.get(id) ?? id,
75
- ])
75
+ ]),
76
);
77
// Find if the phi can be eliminated
78
let same: Identifier | null = null;
@@ -98,7 +98,7 @@ export function eliminateRedundantPhi(
98
}
99
}
100
CompilerError.invariant(same !== null, {
101
- reason: "Expected phis to be non-empty",
101
+ reason: 'Expected phis to be non-empty',
102
description: null,
103
loc: null,
104
suggestions: null,
@@ -117,10 +117,10 @@ export function eliminateRedundantPhi(
117
}
118
119
if (
120
- instr.value.kind === "FunctionExpression" ||
121
- instr.value.kind === "ObjectMethod"
120
+ instr.value.kind === 'FunctionExpression' ||
121
+ instr.value.kind === 'ObjectMethod'
122
) {
123
- const { context } = instr.value.loweredFunc.func;
123
+ const {context} = instr.value.loweredFunc.func;
124
for (const place of context) {
125
rewritePlace(place, rewrites);
126
}
@@ -135,7 +135,7 @@ export function eliminateRedundantPhi(
135
}
136
137
// Rewrite all terminal operands
138
- const { terminal } = block;
138
+ const {terminal} = block;
139
for (const place of eachTerminalOperand(terminal)) {
140
rewritePlace(place, rewrites);
141
}
@@ -150,7 +150,7 @@ export function eliminateRedundantPhi(
150
151
function rewritePlace(
152
place: Place,
153
- rewrites: Map<Identifier, Identifier>
153
+ rewrites: Map<Identifier, Identifier>,
154
): void {
155
const rewrite = rewrites.get(place.identifier);
156
if (rewrite != null) {
compiler/packages/babel-plugin-react-compiler/src/SSA/EnterSSA.ts
+26
-26
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
9
-import { Environment } from "../HIR/Environment";
8
+import {CompilerError} from '../CompilerError';
9
+import {Environment} from '../HIR/Environment';
10
import {
11
BasicBlock,
12
BlockId,
@@ -17,14 +17,14 @@ import {
17
makeType,
18
Phi,
19
Place,
20
-} from "../HIR/HIR";
21
-import { printIdentifier } from "../HIR/PrintHIR";
20
+} from '../HIR/HIR';
21
+import {printIdentifier} from '../HIR/PrintHIR';
22
import {
23
eachTerminalSuccessor,
24
mapInstructionLValues,
25
mapInstructionOperands,
26
mapTerminalOperands,
27
-} from "../HIR/visitors";
27
+} from '../HIR/visitors';
28
29
type IncompletePhi = {
30
oldId: Identifier;
@@ -68,7 +68,7 @@ class SSABuilder {
68
69
state(): State {
70
CompilerError.invariant(this.#current !== null, {
71
- reason: "we need to be in a block to access state!",
71
+ reason: 'we need to be in a block to access state!',
72
description: null,
73
loc: null,
74
suggestions: null,
@@ -156,7 +156,7 @@ class SSABuilder {
156
* for now.
157
*/
158
const newId = this.makeId(oldId);
159
- state.incompletePhis.push({ oldId, newId });
159
+ state.incompletePhis.push({oldId, newId});
160
state.defs.set(oldId, newId);
161
return newId;
162
}
@@ -188,7 +188,7 @@ class SSABuilder {
188
}
189
190
const phi: Phi = {
191
- kind: "Phi",
191
+ kind: 'Phi',
192
id: newId,
193
operands: predDefs,
194
type: makeType(),
@@ -224,14 +224,14 @@ class SSABuilder {
224
for (const incompletePhi of state.incompletePhis) {
225
text.push(
226
` iphi \$${printIdentifier(
227
- incompletePhi.newId
228
- )} = \$${printIdentifier(incompletePhi.oldId)}`
227
+ incompletePhi.newId,
228
+ )} = \$${printIdentifier(incompletePhi.oldId)}`,
229
);
230
}
231
}
232
233
text.push(`current block: bb${this.#current?.id}`);
234
- console.log(text.join("\n"));
234
+ console.log(text.join('\n'));
235
}
236
}
237
@@ -243,7 +243,7 @@ export default function enterSSA(func: HIRFunction): void {
243
function enterSSAImpl(
244
func: HIRFunction,
245
builder: SSABuilder,
246
- rootEntry: BlockId
246
+ rootEntry: BlockId,
247
): void {
248
const visitedBlocks: Set<BasicBlock> = new Set();
249
for (const [blockId, block] of func.body.blocks) {
@@ -266,12 +266,12 @@ function enterSSAImpl(
266
loc: func.loc,
267
suggestions: null,
268
});
269
- func.params = func.params.map((param) => {
270
- if (param.kind === "Identifier") {
269
+ func.params = func.params.map(param => {
270
+ if (param.kind === 'Identifier') {
271
return builder.definePlace(param);
272
} else {
273
return {
274
- kind: "Spread",
274
+ kind: 'Spread',
275
place: builder.definePlace(param.place),
276
};
277
}
@@ -279,18 +279,18 @@ function enterSSAImpl(
279
}
280
281
for (const instr of block.instructions) {
282
- mapInstructionOperands(instr, (place) => builder.getPlace(place));
283
- mapInstructionLValues(instr, (lvalue) => builder.definePlace(lvalue));
282
+ mapInstructionOperands(instr, place => builder.getPlace(place));
283
+ mapInstructionLValues(instr, lvalue => builder.definePlace(lvalue));
284
285
if (
286
- instr.value.kind === "FunctionExpression" ||
287
- instr.value.kind === "ObjectMethod"
286
+ instr.value.kind === 'FunctionExpression' ||
287
+ instr.value.kind === 'ObjectMethod'
288
) {
289
const loweredFunc = instr.value.loweredFunc.func;
290
const entry = loweredFunc.body.blocks.get(loweredFunc.body.entry)!;
291
CompilerError.invariant(entry.preds.size === 0, {
292
reason:
293
- "Expected function expression entry block to have zero predecessors",
293
+ 'Expected function expression entry block to have zero predecessors',
294
description: null,
295
loc: null,
296
suggestions: null,
@@ -298,15 +298,15 @@ function enterSSAImpl(
298
entry.preds.add(blockId);
299
builder.defineFunction(loweredFunc);
300
builder.enter(() => {
301
- loweredFunc.context = loweredFunc.context.map((p) =>
302
- builder.getPlace(p)
301
+ loweredFunc.context = loweredFunc.context.map(p =>
302
+ builder.getPlace(p),
303
);
304
- loweredFunc.params = loweredFunc.params.map((param) => {
305
- if (param.kind === "Identifier") {
304
+ loweredFunc.params = loweredFunc.params.map(param => {
305
+ if (param.kind === 'Identifier') {
306
return builder.definePlace(param);
307
} else {
308
return {
309
- kind: "Spread",
309
+ kind: 'Spread',
310
place: builder.definePlace(param.place),
311
};
312
}
@@ -317,7 +317,7 @@ function enterSSAImpl(
317
}
318
}
319
320
- mapTerminalOperands(block.terminal, (place) => builder.getPlace(place));
320
+ mapTerminalOperands(block.terminal, place => builder.getPlace(place));
321
for (const outputId of eachTerminalSuccessor(block.terminal)) {
322
const output = func.body.blocks.get(outputId)!;
323
let count;
compiler/packages/babel-plugin-react-compiler/src/SSA/LeaveSSA.ts
+48
-48
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
8
+import {CompilerError} from '../CompilerError';
9
import {
10
BasicBlock,
11
BlockId,
@@ -16,8 +16,8 @@ import {
16
LValuePattern,
17
Phi,
18
Place,
19
-} from "../HIR/HIR";
20
-import { printIdentifier, printPlace } from "../HIR/PrintHIR";
19
+} from '../HIR/HIR';
20
+import {printIdentifier, printPlace} from '../HIR/PrintHIR';
21
import {
22
eachInstructionLValue,
23
eachInstructionValueOperand,
@@ -25,7 +25,7 @@ import {
25
eachTerminalOperand,
26
eachTerminalSuccessor,
27
terminalFallthrough,
28
-} from "../HIR/visitors";
28
+} from '../HIR/visitors';
29
30
/*
31
* Removes SSA form by converting all phis into explicit bindings and assignments. There are two main categories
@@ -93,11 +93,11 @@ export function leaveSSA(fn: HIRFunction): void {
93
// Maps identifier names to their original declaration.
94
const declarations: Map<
95
string,
96
- { lvalue: LValue | LValuePattern; place: Place }
96
+ {lvalue: LValue | LValuePattern; place: Place}
97
> = new Map();
98
99
for (const param of fn.params) {
100
- let place: Place = param.kind === "Identifier" ? param : param.place;
100
+ let place: Place = param.kind === 'Identifier' ? param : param.place;
101
if (place.identifier.name !== null) {
102
declarations.set(place.identifier.name.value, {
103
lvalue: {
@@ -141,8 +141,8 @@ export function leaveSSA(fn: HIRFunction): void {
141
* Iterate the instructions and perform any rewrites as well as promoting SSA variables to
142
* `let` or `reassign` where possible.
143
*/
144
- const { lvalue, value } = instr;
145
- if (value.kind === "DeclareLocal") {
144
+ const {lvalue, value} = instr;
145
+ if (value.kind === 'DeclareLocal') {
146
const name = value.lvalue.place.identifier.name;
147
if (name !== null) {
148
CompilerError.invariant(!declarations.has(name.value), {
@@ -157,8 +157,8 @@ export function leaveSSA(fn: HIRFunction): void {
157
});
158
}
159
} else if (
160
- value.kind === "PrefixUpdate" ||
161
- value.kind === "PostfixUpdate"
160
+ value.kind === 'PrefixUpdate' ||
161
+ value.kind === 'PostfixUpdate'
162
) {
163
CompilerError.invariant(value.lvalue.identifier.name !== null, {
164
reason: `Expected update expression to be applied to a named variable`,
@@ -167,7 +167,7 @@ export function leaveSSA(fn: HIRFunction): void {
167
suggestions: null,
168
});
169
const originalLVal = declarations.get(
170
- value.lvalue.identifier.name.value
170
+ value.lvalue.identifier.name.value,
171
);
172
CompilerError.invariant(originalLVal !== undefined, {
173
reason: `Expected update expression to be applied to a previously defined variable`,
@@ -176,10 +176,10 @@ export function leaveSSA(fn: HIRFunction): void {
176
suggestions: null,
177
});
178
originalLVal.lvalue.kind = InstructionKind.Let;
179
- } else if (value.kind === "StoreLocal") {
179
+ } else if (value.kind === 'StoreLocal') {
180
if (value.lvalue.place.identifier.name != null) {
181
const originalLVal = declarations.get(
182
- value.lvalue.place.identifier.name.value
182
+ value.lvalue.place.identifier.name.value,
183
);
184
if (
185
originalLVal === undefined ||
@@ -187,14 +187,14 @@ export function leaveSSA(fn: HIRFunction): void {
187
) {
188
CompilerError.invariant(
189
originalLVal !== undefined ||
190
- block.kind === "block" ||
191
- block.kind === "catch",
190
+ block.kind === 'block' ||
191
+ block.kind === 'catch',
192
{
193
reason: `TODO: Handle reassignment in a value block where the original declaration was removed by dead code elimination (DCE)`,
194
description: null,
195
loc: value.lvalue.place.loc,
196
suggestions: null,
197
- }
197
+ },
198
);
199
declarations.set(value.lvalue.place.identifier.name.value, {
200
lvalue: value.lvalue,
@@ -212,7 +212,7 @@ export function leaveSSA(fn: HIRFunction): void {
212
} else if (rewrites.has(value.lvalue.place.identifier)) {
213
value.lvalue.kind = InstructionKind.Const;
214
}
215
- } else if (value.kind === "Destructure") {
215
+ } else if (value.kind === 'Destructure') {
216
let kind: InstructionKind | null = null;
217
for (const place of eachPatternOperand(value.lvalue.pattern)) {
218
if (place.identifier.name == null) {
@@ -221,11 +221,11 @@ export function leaveSSA(fn: HIRFunction): void {
221
{
222
reason: `Expected consistent kind for destructuring`,
223
description: `other places were \`${kind}\` but '${printPlace(
224
- place
224
+ place,
225
)}' is const`,
226
loc: place.loc,
227
suggestions: null,
228
- }
228
+ },
229
);
230
kind = InstructionKind.Const;
231
} else {
@@ -235,13 +235,13 @@ export function leaveSSA(fn: HIRFunction): void {
235
originalLVal.lvalue === value.lvalue
236
) {
237
CompilerError.invariant(
238
- originalLVal !== undefined || block.kind !== "value",
238
+ originalLVal !== undefined || block.kind !== 'value',
239
{
240
reason: `TODO: Handle reassignment in a value block where the original declaration was removed by dead code elimination (DCE)`,
241
description: null,
242
loc: place.loc,
243
suggestions: null,
244
- }
244
+ },
245
);
246
declarations.set(place.identifier.name.value, {
247
lvalue: value.lvalue,
@@ -252,11 +252,11 @@ export function leaveSSA(fn: HIRFunction): void {
252
{
253
reason: `Expected consistent kind for destructuring`,
254
description: `Other places were \`${kind}\` but '${printPlace(
255
- place
255
+ place,
256
)}' is const`,
257
loc: place.loc,
258
suggestions: null,
259
- }
259
+ },
260
);
261
kind = InstructionKind.Const;
262
} else {
@@ -265,11 +265,11 @@ export function leaveSSA(fn: HIRFunction): void {
265
{
266
reason: `Expected consistent kind for destructuring`,
267
description: `Other places were \`${kind}\` but '${printPlace(
268
- place
268
+ place,
269
)}' is reassigned`,
270
loc: place.loc,
271
suggestions: null,
272
- }
272
+ },
273
);
274
kind = InstructionKind.Reassign;
275
originalLVal.lvalue.kind = InstructionKind.Let;
@@ -277,7 +277,7 @@ export function leaveSSA(fn: HIRFunction): void {
277
}
278
}
279
CompilerError.invariant(kind !== null, {
280
- reason: "Expected at least one operand",
280
+ reason: 'Expected at least one operand',
281
description: null,
282
loc: null,
283
suggestions: null,
@@ -308,9 +308,9 @@ export function leaveSSA(fn: HIRFunction): void {
308
function pushPhis(phiBlock: BasicBlock): void {
309
for (const phi of phiBlock.phis) {
310
if (phi.id.name === null) {
311
- rewritePhis.push({ phi, block: phiBlock });
311
+ rewritePhis.push({phi, block: phiBlock});
312
} else {
313
- reassignmentPhis.push({ phi, block: phiBlock });
313
+ reassignmentPhis.push({phi, block: phiBlock});
314
}
315
}
316
}
@@ -319,7 +319,7 @@ export function leaveSSA(fn: HIRFunction): void {
319
const fallthrough = fn.body.blocks.get(fallthroughId)!;
320
pushPhis(fallthrough);
321
}
322
- if (terminal.kind === "while" || terminal.kind === "for") {
322
+ if (terminal.kind === 'while' || terminal.kind === 'for') {
323
const test = fn.body.blocks.get(terminal.test)!;
324
pushPhis(test);
325
@@ -327,16 +327,16 @@ export function leaveSSA(fn: HIRFunction): void {
327
pushPhis(loop);
328
}
329
if (
330
- terminal.kind === "for" ||
331
- terminal.kind === "for-of" ||
332
- terminal.kind === "for-in"
330
+ terminal.kind === 'for' ||
331
+ terminal.kind === 'for-of' ||
332
+ terminal.kind === 'for-in'
333
) {
334
let init = fn.body.blocks.get(terminal.init)!;
335
pushPhis(init);
336
337
// The first block after the end of the init
338
let initContinuation =
339
- terminal.kind === "for" ? terminal.test : terminal.loop;
339
+ terminal.kind === 'for' ? terminal.test : terminal.loop;
340
/*
341
* To avoid generating a let binding for the initializer prior to the loop,
342
* check to see if the for declares an iterator variable.
@@ -350,13 +350,13 @@ export function leaveSSA(fn: HIRFunction): void {
350
const block = fn.body.blocks.get(blockId)!;
351
for (const instr of block.instructions) {
352
if (
353
- instr.value.kind === "StoreLocal" &&
353
+ instr.value.kind === 'StoreLocal' &&
354
instr.value.lvalue.kind !== InstructionKind.Reassign
355
) {
356
const value = instr.value;
357
if (value.lvalue.place.identifier.name !== null) {
358
const originalLVal = declarations.get(
359
- value.lvalue.place.identifier.name.value
359
+ value.lvalue.place.identifier.name.value,
360
);
361
if (originalLVal === undefined) {
362
declarations.set(value.lvalue.place.identifier.name.value, {
@@ -370,19 +370,19 @@ export function leaveSSA(fn: HIRFunction): void {
370
}
371
372
switch (block.terminal.kind) {
373
- case "maybe-throw": {
373
+ case 'maybe-throw': {
374
queue.push(block.terminal.continuation);
375
break;
376
}
377
- case "goto": {
377
+ case 'goto': {
378
queue.push(block.terminal.block);
379
break;
380
}
381
- case "branch":
382
- case "logical":
383
- case "optional":
384
- case "ternary":
385
- case "label": {
381
+ case 'branch':
382
+ case 'logical':
383
+ case 'optional':
384
+ case 'ternary':
385
+ case 'label': {
386
for (const successor of eachTerminalSuccessor(block.terminal)) {
387
queue.push(successor);
388
}
@@ -394,13 +394,13 @@ export function leaveSSA(fn: HIRFunction): void {
394
}
395
}
396
397
- if (terminal.kind === "for" && terminal.update !== null) {
397
+ if (terminal.kind === 'for' && terminal.update !== null) {
398
const update = fn.body.blocks.get(terminal.update)!;
399
pushPhis(update);
400
}
401
}
402
403
- for (const { phi, block: phiBlock } of reassignmentPhis) {
403
+ for (const {phi, block: phiBlock} of reassignmentPhis) {
404
/*
405
* In some cases one of the phi operands can be defined *before* the let binding
406
* we will generate. For example, a variable that is only rebound in one branch of
@@ -429,7 +429,7 @@ export function leaveSSA(fn: HIRFunction): void {
429
* a new Let binding
430
*/
431
CompilerError.invariant(phi.id.name != null, {
432
- reason: "Expected reassignment phis to have a name",
432
+ reason: 'Expected reassignment phis to have a name',
433
description: null,
434
loc: null,
435
suggestions: null,
@@ -437,7 +437,7 @@ export function leaveSSA(fn: HIRFunction): void {
437
const declaration = declarations.get(phi.id.name.value);
438
CompilerError.invariant(declaration != null, {
439
loc: null,
440
- reason: "Expected a declaration for all variables",
440
+ reason: 'Expected a declaration for all variables',
441
description: `${printIdentifier(phi.id)} in block bb${phiBlock.id}`,
442
suggestions: null,
443
});
@@ -461,7 +461,7 @@ export function leaveSSA(fn: HIRFunction): void {
461
* we pick one of the operands as the canonical id, and rewrite all references to the other
462
* operands and the phi to reference this canonical id.
463
*/
464
- for (const { phi } of rewritePhis) {
464
+ for (const {phi} of rewritePhis) {
465
let canonicalId = rewrites.get(phi.id);
466
if (canonicalId === undefined) {
467
canonicalId = phi.id;
@@ -497,7 +497,7 @@ export function leaveSSA(fn: HIRFunction): void {
497
function rewritePlace(
498
place: Place,
499
rewrites: Map<Identifier, Identifier>,
500
- declarations: Map<string, { lvalue: LValue | LValuePattern; place: Place }>
500
+ declarations: Map<string, {lvalue: LValue | LValuePattern; place: Place}>,
501
): void {
502
const prevIdentifier = place.identifier;
503
const nextIdentifier = rewrites.get(prevIdentifier);
compiler/packages/babel-plugin-react-compiler/src/SSA/index.ts
+3
-3
@@ -5,6 +5,6 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-export { eliminateRedundantPhi } from "./EliminateRedundantPhi";
9
-export { default as enterSSA } from "./EnterSSA";
10
-export { leaveSSA } from "./LeaveSSA";
8
+export {eliminateRedundantPhi} from './EliminateRedundantPhi';
9
+export {default as enterSSA} from './EnterSSA';
10
+export {leaveSSA} from './LeaveSSA';
compiler/packages/babel-plugin-react-compiler/src/TypeInference/InferTypes.ts
+136
-136
@@ -5,10 +5,10 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import * as t from "@babel/types";
9
-import { CompilerError } from "../CompilerError";
10
-import { Environment } from "../HIR";
11
-import { lowerType } from "../HIR/BuildHIR";
8
+import * as t from '@babel/types';
9
+import {CompilerError} from '../CompilerError';
10
+import {Environment} from '../HIR';
11
+import {lowerType} from '../HIR/BuildHIR';
12
import {
13
HIRFunction,
14
Identifier,
@@ -20,7 +20,7 @@ import {
20
typeEquals,
21
TypeId,
22
TypeVar,
23
-} from "../HIR/HIR";
23
+} from '../HIR/HIR';
24
import {
25
BuiltInArrayId,
26
BuiltInFunctionId,
@@ -29,28 +29,28 @@ import {
29
BuiltInPropsId,
30
BuiltInRefValueId,
31
BuiltInUseRefId,
32
-} from "../HIR/ObjectShape";
33
-import { eachInstructionLValue, eachInstructionOperand } from "../HIR/visitors";
34
-import { assertExhaustive } from "../Utils/utils";
32
+} from '../HIR/ObjectShape';
33
+import {eachInstructionLValue, eachInstructionOperand} from '../HIR/visitors';
34
+import {assertExhaustive} from '../Utils/utils';
35
36
-function isPrimitiveBinaryOp(op: t.BinaryExpression["operator"]): boolean {
36
+function isPrimitiveBinaryOp(op: t.BinaryExpression['operator']): boolean {
37
switch (op) {
38
- case "+":
39
- case "-":
40
- case "/":
41
- case "%":
42
- case "*":
43
- case "**":
44
- case "&":
45
- case "|":
46
- case ">>":
47
- case "<<":
48
- case "^":
49
- case ">":
50
- case "<":
51
- case ">=":
52
- case "<=":
53
- case "|>":
38
+ case '+':
39
+ case '-':
40
+ case '/':
41
+ case '%':
42
+ case '*':
43
+ case '**':
44
+ case '&':
45
+ case '|':
46
+ case '>>':
47
+ case '<<':
48
+ case '^':
49
+ case '>':
50
+ case '<':
51
+ case '>=':
52
+ case '<=':
53
+ case '|>':
54
return true;
55
default:
56
return false;
@@ -77,12 +77,12 @@ function apply(func: HIRFunction, unifier: Unifier): void {
77
for (const place of eachInstructionOperand(instr)) {
78
place.identifier.type = unifier.get(place.identifier.type);
79
}
80
- const { lvalue, value } = instr;
80
+ const {lvalue, value} = instr;
81
lvalue.identifier.type = unifier.get(lvalue.identifier.type);
82
83
if (
84
- value.kind === "FunctionExpression" ||
85
- value.kind === "ObjectMethod"
84
+ value.kind === 'FunctionExpression' ||
85
+ value.kind === 'ObjectMethod'
86
) {
87
apply(value.loweredFunc.func, unifier);
88
}
@@ -103,19 +103,19 @@ function equation(left: Type, right: Type): TypeEquation {
103
}
104
105
function* generate(
106
- func: HIRFunction
106
+ func: HIRFunction,
107
): Generator<TypeEquation, void, undefined> {
108
- if (func.env.fnType === "Component") {
108
+ if (func.env.fnType === 'Component') {
109
const [props, ref] = func.params;
110
- if (props && props.kind === "Identifier") {
110
+ if (props && props.kind === 'Identifier') {
111
yield equation(props.identifier.type, {
112
- kind: "Object",
112
+ kind: 'Object',
113
shapeId: BuiltInPropsId,
114
});
115
}
116
- if (ref && ref.kind === "Identifier") {
116
+ if (ref && ref.kind === 'Identifier') {
117
yield equation(ref.identifier.type, {
118
- kind: "Object",
118
+ kind: 'Object',
119
shapeId: BuiltInUseRefId,
120
});
121
}
@@ -125,8 +125,8 @@ function* generate(
125
for (const [_, block] of func.body.blocks) {
126
for (const phi of block.phis) {
127
yield equation(phi.type, {
128
- kind: "Phi",
129
- operands: [...phi.operands.values()].map((id) => id.type),
128
+ kind: 'Phi',
129
+ operands: [...phi.operands.values()].map(id => id.type),
130
});
131
}
132
@@ -139,56 +139,56 @@ function* generate(
139
function setName(
140
names: Map<IdentifierId, string>,
141
id: IdentifierId,
142
- name: Identifier
142
+ name: Identifier,
143
): void {
144
- if (name.name?.kind === "named") {
144
+ if (name.name?.kind === 'named') {
145
names.set(id, name.name.value);
146
}
147
}
148
149
function getName(names: Map<IdentifierId, string>, id: IdentifierId): string {
150
- return names.get(id) ?? "";
150
+ return names.get(id) ?? '';
151
}
152
153
function* generateInstructionTypes(
154
env: Environment,
155
names: Map<IdentifierId, string>,
156
- instr: Instruction
156
+ instr: Instruction,
157
): Generator<TypeEquation, void, undefined> {
158
- const { lvalue, value } = instr;
158
+ const {lvalue, value} = instr;
159
const left = lvalue.identifier.type;
160
161
switch (value.kind) {
162
- case "TemplateLiteral":
163
- case "JSXText":
164
- case "Primitive": {
165
- yield equation(left, { kind: "Primitive" });
162
+ case 'TemplateLiteral':
163
+ case 'JSXText':
164
+ case 'Primitive': {
165
+ yield equation(left, {kind: 'Primitive'});
166
break;
167
}
168
169
- case "UnaryExpression": {
170
- yield equation(left, { kind: "Primitive" });
169
+ case 'UnaryExpression': {
170
+ yield equation(left, {kind: 'Primitive'});
171
break;
172
}
173
174
- case "LoadLocal": {
174
+ case 'LoadLocal': {
175
setName(names, lvalue.identifier.id, value.place.identifier);
176
yield equation(left, value.place.identifier.type);
177
break;
178
}
179
180
// We intentionally do not infer types for context variables
181
- case "DeclareContext":
182
- case "StoreContext":
183
- case "LoadContext": {
181
+ case 'DeclareContext':
182
+ case 'StoreContext':
183
+ case 'LoadContext': {
184
break;
185
}
186
187
- case "StoreLocal": {
187
+ case 'StoreLocal': {
188
if (env.config.enableUseTypeAnnotations) {
189
yield equation(
190
value.lvalue.place.identifier.type,
191
- value.value.identifier.type
191
+ value.value.identifier.type,
192
);
193
const valueType =
194
value.type === null ? makeType() : lowerType(value.type);
@@ -198,35 +198,35 @@ function* generateInstructionTypes(
198
yield equation(left, value.value.identifier.type);
199
yield equation(
200
value.lvalue.place.identifier.type,
201
- value.value.identifier.type
201
+ value.value.identifier.type,
202
);
203
}
204
break;
205
}
206
207
- case "StoreGlobal": {
207
+ case 'StoreGlobal': {
208
yield equation(left, value.value.identifier.type);
209
break;
210
}
211
212
- case "BinaryExpression": {
212
+ case 'BinaryExpression': {
213
if (isPrimitiveBinaryOp(value.operator)) {
214
- yield equation(value.left.identifier.type, { kind: "Primitive" });
215
- yield equation(value.right.identifier.type, { kind: "Primitive" });
214
+ yield equation(value.left.identifier.type, {kind: 'Primitive'});
215
+ yield equation(value.right.identifier.type, {kind: 'Primitive'});
216
}
217
- yield equation(left, { kind: "Primitive" });
217
+ yield equation(left, {kind: 'Primitive'});
218
break;
219
}
220
221
- case "PostfixUpdate":
222
- case "PrefixUpdate": {
223
- yield equation(value.value.identifier.type, { kind: "Primitive" });
224
- yield equation(value.lvalue.identifier.type, { kind: "Primitive" });
225
- yield equation(left, { kind: "Primitive" });
221
+ case 'PostfixUpdate':
222
+ case 'PrefixUpdate': {
223
+ yield equation(value.value.identifier.type, {kind: 'Primitive'});
224
+ yield equation(value.lvalue.identifier.type, {kind: 'Primitive'});
225
+ yield equation(left, {kind: 'Primitive'});
226
break;
227
}
228
229
- case "LoadGlobal": {
229
+ case 'LoadGlobal': {
230
const globalType = env.getGlobalDeclaration(value.binding);
231
if (globalType) {
232
yield equation(left, globalType);
@@ -234,43 +234,43 @@ function* generateInstructionTypes(
234
break;
235
}
236
237
- case "CallExpression": {
237
+ case 'CallExpression': {
238
/*
239
* TODO: callee could be a hook or a function, so this type equation isn't correct.
240
* We should change Hook to a subtype of Function or change unifier logic.
241
* (see https://github.com/facebook/react-forget/pull/1427)
242
*/
243
yield equation(value.callee.identifier.type, {
244
- kind: "Function",
244
+ kind: 'Function',
245
shapeId: null,
246
return: left,
247
});
248
break;
249
}
250
251
- case "ObjectExpression": {
251
+ case 'ObjectExpression': {
252
for (const property of value.properties) {
253
if (
254
- property.kind === "ObjectProperty" &&
255
- property.key.kind === "computed"
254
+ property.kind === 'ObjectProperty' &&
255
+ property.key.kind === 'computed'
256
) {
257
yield equation(property.key.name.identifier.type, {
258
- kind: "Primitive",
258
+ kind: 'Primitive',
259
});
260
}
261
}
262
- yield equation(left, { kind: "Object", shapeId: BuiltInObjectId });
262
+ yield equation(left, {kind: 'Object', shapeId: BuiltInObjectId});
263
break;
264
}
265
266
- case "ArrayExpression": {
267
- yield equation(left, { kind: "Object", shapeId: BuiltInArrayId });
266
+ case 'ArrayExpression': {
267
+ yield equation(left, {kind: 'Object', shapeId: BuiltInArrayId});
268
break;
269
}
270
271
- case "PropertyLoad": {
271
+ case 'PropertyLoad': {
272
yield equation(left, {
273
- kind: "Property",
273
+ kind: 'Property',
274
objectType: value.object.identifier.type,
275
objectName: getName(names, value.object.identifier.id),
276
propertyName: value.property,
@@ -278,10 +278,10 @@ function* generateInstructionTypes(
278
break;
279
}
280
281
- case "MethodCall": {
281
+ case 'MethodCall': {
282
const returnType = makeType();
283
yield equation(value.property.identifier.type, {
284
- kind: "Function",
284
+ kind: 'Function',
285
return: returnType,
286
shapeId: null,
287
});
@@ -290,16 +290,16 @@ function* generateInstructionTypes(
290
break;
291
}
292
293
- case "Destructure": {
293
+ case 'Destructure': {
294
const pattern = value.lvalue.pattern;
295
- if (pattern.kind === "ArrayPattern") {
295
+ if (pattern.kind === 'ArrayPattern') {
296
for (let i = 0; i < pattern.items.length; i++) {
297
const item = pattern.items[i];
298
- if (item.kind === "Identifier") {
298
+ if (item.kind === 'Identifier') {
299
// To simulate tuples we use properties with `String(<index>)`, eg "0".
300
const propertyName = String(i);
301
yield equation(item.identifier.type, {
302
- kind: "Property",
302
+ kind: 'Property',
303
objectType: value.value.identifier.type,
304
objectName: getName(names, value.value.identifier.id),
305
propertyName,
@@ -310,13 +310,13 @@ function* generateInstructionTypes(
310
}
311
} else {
312
for (const property of pattern.properties) {
313
- if (property.kind === "ObjectProperty") {
313
+ if (property.kind === 'ObjectProperty') {
314
if (
315
- property.key.kind === "identifier" ||
316
- property.key.kind === "string"
315
+ property.key.kind === 'identifier' ||
316
+ property.key.kind === 'string'
317
) {
318
yield equation(property.place.identifier.type, {
319
- kind: "Property",
319
+ kind: 'Property',
320
objectType: value.value.identifier.type,
321
objectName: getName(names, value.value.identifier.id),
322
propertyName: property.key.name,
@@ -328,7 +328,7 @@ function* generateInstructionTypes(
328
break;
329
}
330
331
- case "TypeCastExpression": {
331
+ case 'TypeCastExpression': {
332
if (env.config.enableUseTypeAnnotations) {
333
yield equation(value.type, value.value.identifier.type);
334
yield equation(left, value.type);
@@ -338,49 +338,49 @@ function* generateInstructionTypes(
338
break;
339
}
340
341
- case "PropertyDelete":
342
- case "ComputedDelete": {
343
- yield equation(left, { kind: "Primitive" });
341
+ case 'PropertyDelete':
342
+ case 'ComputedDelete': {
343
+ yield equation(left, {kind: 'Primitive'});
344
break;
345
}
346
347
- case "FunctionExpression": {
347
+ case 'FunctionExpression': {
348
yield* generate(value.loweredFunc.func);
349
- yield equation(left, { kind: "Object", shapeId: BuiltInFunctionId });
349
+ yield equation(left, {kind: 'Object', shapeId: BuiltInFunctionId});
350
break;
351
}
352
353
- case "NextPropertyOf": {
354
- yield equation(left, { kind: "Primitive" });
353
+ case 'NextPropertyOf': {
354
+ yield equation(left, {kind: 'Primitive'});
355
break;
356
}
357
358
- case "ObjectMethod": {
358
+ case 'ObjectMethod': {
359
yield* generate(value.loweredFunc.func);
360
- yield equation(left, { kind: "ObjectMethod" });
360
+ yield equation(left, {kind: 'ObjectMethod'});
361
break;
362
}
363
364
- case "JsxExpression":
365
- case "JsxFragment": {
366
- yield equation(left, { kind: "Object", shapeId: BuiltInJsxId });
364
+ case 'JsxExpression':
365
+ case 'JsxFragment': {
366
+ yield equation(left, {kind: 'Object', shapeId: BuiltInJsxId});
367
break;
368
}
369
- case "PropertyStore":
370
- case "DeclareLocal":
371
- case "NewExpression":
372
- case "RegExpLiteral":
373
- case "MetaProperty":
374
- case "ComputedStore":
375
- case "ComputedLoad":
376
- case "TaggedTemplateExpression":
377
- case "Await":
378
- case "GetIterator":
379
- case "IteratorNext":
380
- case "UnsupportedNode":
381
- case "Debugger":
382
- case "FinishMemoize":
383
- case "StartMemoize": {
369
+ case 'PropertyStore':
370
+ case 'DeclareLocal':
371
+ case 'NewExpression':
372
+ case 'RegExpLiteral':
373
+ case 'MetaProperty':
374
+ case 'ComputedStore':
375
+ case 'ComputedLoad':
376
+ case 'TaggedTemplateExpression':
377
+ case 'Await':
378
+ case 'GetIterator':
379
+ case 'IteratorNext':
380
+ case 'UnsupportedNode':
381
+ case 'Debugger':
382
+ case 'FinishMemoize':
383
+ case 'StartMemoize': {
384
break;
385
}
386
default:
@@ -398,17 +398,17 @@ class Unifier {
398
}
399
400
unify(tA: Type, tB: Type): void {
401
- if (tB.kind === "Property") {
401
+ if (tB.kind === 'Property') {
402
if (
403
this.env.config.enableTreatRefLikeIdentifiersAsRefs &&
404
isRefLikeName(tB)
405
) {
406
this.unify(tB.objectType, {
407
- kind: "Object",
407
+ kind: 'Object',
408
shapeId: BuiltInUseRefId,
409
});
410
this.unify(tA, {
411
- kind: "Object",
411
+ kind: 'Object',
412
shapeId: BuiltInRefValueId,
413
});
414
return;
@@ -416,7 +416,7 @@ class Unifier {
416
const objectType = this.get(tB.objectType);
417
const propertyType = this.env.getPropertyType(
418
objectType,
419
- tB.propertyName
419
+ tB.propertyName,
420
);
421
if (propertyType !== null) {
422
this.unify(tA, propertyType);
@@ -432,24 +432,24 @@ class Unifier {
432
return;
433
}
434
435
- if (tA.kind === "Type") {
435
+ if (tA.kind === 'Type') {
436
this.bindVariableTo(tA, tB);
437
return;
438
}
439
440
- if (tB.kind === "Type") {
440
+ if (tB.kind === 'Type') {
441
this.bindVariableTo(tB, tA);
442
return;
443
}
444
445
- if (tB.kind === "Function" && tA.kind === "Function") {
445
+ if (tB.kind === 'Function' && tA.kind === 'Function') {
446
this.unify(tA.return, tB.return);
447
return;
448
}
449
}
450
451
bindVariableTo(v: TypeVar, type: Type): void {
452
- if (type.kind === "Poly") {
452
+ if (type.kind === 'Poly') {
453
// Ignore PolyType, since we don't support polymorphic types correctly.
454
return;
455
}
@@ -459,16 +459,16 @@ class Unifier {
459
return;
460
}
461
462
- if (type.kind === "Type" && this.substitutions.has(type.id)) {
462
+ if (type.kind === 'Type' && this.substitutions.has(type.id)) {
463
this.unify(v, this.substitutions.get(type.id)!);
464
return;
465
}
466
467
- if (type.kind === "Phi") {
468
- const operands = new Set(type.operands.map((i) => this.get(i).kind));
467
+ if (type.kind === 'Phi') {
468
+ const operands = new Set(type.operands.map(i => this.get(i).kind));
469
470
CompilerError.invariant(operands.size > 0, {
471
- reason: "there should be at least one operand",
471
+ reason: 'there should be at least one operand',
472
description: null,
473
loc: null,
474
suggestions: null,
@@ -476,14 +476,14 @@ class Unifier {
476
const kind = operands.values().next().value;
477
478
// there's only one unique type and it's not a type var
479
- if (operands.size === 1 && kind !== "Type") {
479
+ if (operands.size === 1 && kind !== 'Type') {
480
this.unify(v, type.operands[0]);
481
return;
482
}
483
}
484
485
if (this.occursCheck(v, type)) {
486
- throw new Error("cycle detected");
486
+ throw new Error('cycle detected');
487
}
488
489
this.substitutions.set(v.id, type);
@@ -492,15 +492,15 @@ class Unifier {
492
occursCheck(v: TypeVar, type: Type): boolean {
493
if (typeEquals(v, type)) return true;
494
495
- if (type.kind === "Type" && this.substitutions.has(type.id)) {
495
+ if (type.kind === 'Type' && this.substitutions.has(type.id)) {
496
return this.occursCheck(v, this.substitutions.get(type.id)!);
497
}
498
499
- if (type.kind === "Phi") {
500
- return type.operands.some((o) => this.occursCheck(v, o));
499
+ if (type.kind === 'Phi') {
500
+ return type.operands.some(o => this.occursCheck(v, o));
501
}
502
503
- if (type.kind === "Function") {
503
+ if (type.kind === 'Function') {
504
return this.occursCheck(v, type.return);
505
}
506
@@ -508,14 +508,14 @@ class Unifier {
508
}
509
510
get(type: Type): Type {
511
- if (type.kind === "Type") {
511
+ if (type.kind === 'Type') {
512
if (this.substitutions.has(type.id)) {
513
return this.get(this.substitutions.get(type.id)!);
514
}
515
}
516
517
- if (type.kind === "Phi") {
518
- return { kind: "Phi", operands: type.operands.map((o) => this.get(o)) };
517
+ if (type.kind === 'Phi') {
518
+ return {kind: 'Phi', operands: type.operands.map(o => this.get(o))};
519
}
520
521
return type;
@@ -525,5 +525,5 @@ class Unifier {
525
const RefLikeNameRE = /^(?:[a-zA-Z$_][a-zA-Z$_0-9]*)Ref$|^ref$/;
526
527
function isRefLikeName(t: PropType): boolean {
528
- return RefLikeNameRE.test(t.objectName) && t.propertyName === "current";
528
+ return RefLikeNameRE.test(t.objectName) && t.propertyName === 'current';
529
}
compiler/packages/babel-plugin-react-compiler/src/TypeInference/index.ts
+1
-1
@@ -5,4 +5,4 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-export { inferTypes } from "./InferTypes";
8
+export {inferTypes} from './InferTypes';
compiler/packages/babel-plugin-react-compiler/src/Utils/ComponentDeclaration.ts
+4
-4
@@ -5,20 +5,20 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import * as t from "@babel/types";
8
+import * as t from '@babel/types';
9
10
export type ComponentDeclaration = t.FunctionDeclaration & {
11
__componentDeclaration: boolean;
12
};
13
14
export function isComponentDeclaration(
15
- node: t.FunctionDeclaration
15
+ node: t.FunctionDeclaration,
16
): node is ComponentDeclaration {
17
- return Object.prototype.hasOwnProperty.call(node, "__componentDeclaration");
17
+ return Object.prototype.hasOwnProperty.call(node, '__componentDeclaration');
18
}
19
20
export function parseComponentDeclaration(
21
- node: t.FunctionDeclaration
21
+ node: t.FunctionDeclaration,
22
): ComponentDeclaration | null {
23
return isComponentDeclaration(node) ? node : null;
24
}
compiler/packages/babel-plugin-react-compiler/src/Utils/DisjointSet.ts
+2
-2
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
8
+import {CompilerError} from '../CompilerError';
9
10
// Represents items which form disjoint sets.
11
export default class DisjointSet<T> {
@@ -19,7 +19,7 @@ export default class DisjointSet<T> {
19
union(items: Array<T>): void {
20
const first = items.shift();
21
CompilerError.invariant(first != null, {
22
- reason: "Expected set to be non-empty",
22
+ reason: 'Expected set to be non-empty',
23
description: null,
24
loc: null,
25
suggestions: null,
compiler/packages/babel-plugin-react-compiler/src/Utils/HookDeclaration.ts
+4
-4
@@ -5,20 +5,20 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import * as t from "@babel/types";
8
+import * as t from '@babel/types';
9
10
export type HookDeclaration = t.FunctionDeclaration & {
11
__hookDeclaration: boolean;
12
};
13
14
export function isHookDeclaration(
15
- node: t.FunctionDeclaration
15
+ node: t.FunctionDeclaration,
16
): node is HookDeclaration {
17
- return Object.prototype.hasOwnProperty.call(node, "__hookDeclaration");
17
+ return Object.prototype.hasOwnProperty.call(node, '__hookDeclaration');
18
}
19
20
export function parseHookDeclaration(
21
- node: t.FunctionDeclaration
21
+ node: t.FunctionDeclaration,
22
): HookDeclaration | null {
23
return isHookDeclaration(node) ? node : null;
24
}
compiler/packages/babel-plugin-react-compiler/src/Utils/Stack.ts
+1
-1
@@ -104,7 +104,7 @@ class Empty<T> implements StackInterface<T> {
104
return null;
105
}
106
print(_: (node: T) => string): string {
107
- return "";
107
+ return '';
108
}
109
}
110
compiler/packages/babel-plugin-react-compiler/src/Utils/logger.ts
+14
-14
@@ -5,13 +5,13 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import generate from "@babel/generator";
9
-import * as t from "@babel/types";
10
-import chalk from "chalk";
11
-import { HIR, HIRFunction, ReactiveFunction } from "../HIR/HIR";
12
-import { printFunctionWithOutlined, printHIR } from "../HIR/PrintHIR";
13
-import { CodegenFunction } from "../ReactiveScopes";
14
-import { printReactiveFunctionWithOutlined } from "../ReactiveScopes/PrintReactiveFunction";
8
+import generate from '@babel/generator';
9
+import * as t from '@babel/types';
10
+import chalk from 'chalk';
11
+import {HIR, HIRFunction, ReactiveFunction} from '../HIR/HIR';
12
+import {printFunctionWithOutlined, printHIR} from '../HIR/PrintHIR';
13
+import {CodegenFunction} from '../ReactiveScopes';
14
+import {printReactiveFunctionWithOutlined} from '../ReactiveScopes/PrintReactiveFunction';
15
16
let ENABLED: boolean = false;
17
@@ -48,23 +48,23 @@ export function logCodegenFunction(step: string, fn: CodegenFunction): void {
48
fn.params,
49
fn.body,
50
fn.generator,
51
- fn.async
51
+ fn.async,
52
);
53
const ast = generate(node);
54
printed = ast.code;
55
} catch (e) {
56
let errMsg: string;
57
if (
58
- typeof e === "object" &&
58
+ typeof e === 'object' &&
59
e != null &&
60
- "message" in e &&
61
- typeof e.message === "string"
60
+ 'message' in e &&
61
+ typeof e.message === 'string'
62
) {
63
errMsg = e.message.toString();
64
} else {
65
- errMsg = "[empty]";
65
+ errMsg = '[empty]';
66
}
67
- console.log("Error formatting AST: " + errMsg);
67
+ console.log('Error formatting AST: ' + errMsg);
68
}
69
if (printed === null) {
70
return;
@@ -105,6 +105,6 @@ export function logReactiveFunction(step: string, fn: ReactiveFunction): void {
105
export function log(fn: () => string): void {
106
if (ENABLED) {
107
const message = fn();
108
- process.stdout.write(message.trim() + "\n\n");
108
+ process.stdout.write(message.trim() + '\n\n');
109
}
110
}
compiler/packages/babel-plugin-react-compiler/src/Utils/todo.ts
+3
-3
@@ -6,14 +6,14 @@
6
*/
7
8
export default function todo(message: string): never {
9
- throw new Error("TODO: " + message);
9
+ throw new Error('TODO: ' + message);
10
}
11
12
export function todoInvariant(
13
condition: unknown,
14
- message: string
14
+ message: string,
15
): asserts condition {
16
if (!condition) {
17
- throw new Error("TODO: " + message);
17
+ throw new Error('TODO: ' + message);
18
}
19
}
compiler/packages/babel-plugin-react-compiler/src/Utils/utils.ts
+8
-8
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { NodePath } from "@babel/traverse";
8
+import {NodePath} from '@babel/traverse';
9
10
/*
11
* Trigger an exhaustivess check in TypeScript and throw at runtime.
@@ -33,7 +33,7 @@ export function assertExhaustive(_: never, errorMsg: string): never {
33
// Modifies @param array in place, retaining only the items where the predicate returns true.
34
export function retainWhere<T>(
35
array: Array<T>,
36
- predicate: (item: T) => boolean
36
+ predicate: (item: T) => boolean,
37
): void {
38
let writeIndex = 0;
39
for (let readIndex = 0; readIndex < array.length; readIndex++) {
@@ -47,7 +47,7 @@ export function retainWhere<T>(
47
48
export function retainWhere_Set<T>(
49
items: Set<T>,
50
- predicate: (item: T) => boolean
50
+ predicate: (item: T) => boolean,
51
): void {
52
for (const item of items) {
53
if (!predicate(item)) {
@@ -59,7 +59,7 @@ export function retainWhere_Set<T>(
59
export function getOrInsertWith<U, V>(
60
m: Map<U, V>,
61
key: U,
62
- makeDefault: () => V
62
+ makeDefault: () => V,
63
): V {
64
if (m.has(key)) {
65
return m.get(key) as V;
@@ -73,7 +73,7 @@ export function getOrInsertWith<U, V>(
73
export function getOrInsertDefault<U, V>(
74
m: Map<U, V>,
75
key: U,
76
- defaultValue: V
76
+ defaultValue: V,
77
): V {
78
if (m.has(key)) {
79
return m.get(key) as V;
@@ -94,13 +94,13 @@ export function Set_union<T>(a: Set<T>, b: Set<T>): Set<T> {
94
}
95
96
export function nonNull<T extends NonNullable<U>, U>(
97
- value: T | null | undefined
97
+ value: T | null | undefined,
98
): value is T {
99
return value != null;
100
}
101
102
export function hasNode<T>(
103
- input: NodePath<T | null | undefined>
103
+ input: NodePath<T | null | undefined>,
104
): input is NodePath<NonNullable<T>> {
105
/*
106
* Internal babel is on an older version that does not have hasNode (v7.17)
@@ -112,7 +112,7 @@ export function hasNode<T>(
112
113
export function hasOwnProperty<T>(
114
obj: T,
115
- key: string | number | symbol
115
+ key: string | number | symbol,
116
): key is keyof T {
117
return Object.prototype.hasOwnProperty.call(obj, key);
118
}
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateContextVariableLValues.ts
+33
-36
@@ -5,13 +5,10 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "..";
9
-import { HIRFunction, IdentifierId, Place } from "../HIR";
10
-import { printPlace } from "../HIR/PrintHIR";
11
-import {
12
- eachInstructionValueLValue,
13
- eachPatternOperand,
14
-} from "../HIR/visitors";
8
+import {CompilerError} from '..';
9
+import {HIRFunction, IdentifierId, Place} from '../HIR';
10
+import {printPlace} from '../HIR/PrintHIR';
11
+import {eachInstructionValueLValue, eachPatternOperand} from '../HIR/visitors';
12
13
/**
14
* Validates that all store/load references to a given named identifier align with the
@@ -25,46 +22,46 @@ export function validateContextVariableLValues(fn: HIRFunction): void {
22
23
function validateContextVariableLValuesImpl(
24
fn: HIRFunction,
28
- identifierKinds: IdentifierKinds
25
+ identifierKinds: IdentifierKinds,
26
): void {
27
for (const [, block] of fn.body.blocks) {
28
for (const instr of block.instructions) {
32
- const { value } = instr;
29
+ const {value} = instr;
30
switch (value.kind) {
34
- case "DeclareContext":
35
- case "StoreContext": {
36
- visit(identifierKinds, value.lvalue.place, "context");
31
+ case 'DeclareContext':
32
+ case 'StoreContext': {
33
+ visit(identifierKinds, value.lvalue.place, 'context');
34
break;
35
}
39
- case "LoadContext": {
40
- visit(identifierKinds, value.place, "context");
36
+ case 'LoadContext': {
37
+ visit(identifierKinds, value.place, 'context');
38
break;
39
}
43
- case "StoreLocal":
44
- case "DeclareLocal": {
45
- visit(identifierKinds, value.lvalue.place, "local");
40
+ case 'StoreLocal':
41
+ case 'DeclareLocal': {
42
+ visit(identifierKinds, value.lvalue.place, 'local');
43
break;
44
}
48
- case "LoadLocal": {
49
- visit(identifierKinds, value.place, "local");
45
+ case 'LoadLocal': {
46
+ visit(identifierKinds, value.place, 'local');
47
break;
48
}
52
- case "PostfixUpdate":
53
- case "PrefixUpdate": {
54
- visit(identifierKinds, value.lvalue, "local");
49
+ case 'PostfixUpdate':
50
+ case 'PrefixUpdate': {
51
+ visit(identifierKinds, value.lvalue, 'local');
52
break;
53
}
57
- case "Destructure": {
54
+ case 'Destructure': {
55
for (const lvalue of eachPatternOperand(value.lvalue.pattern)) {
59
- visit(identifierKinds, lvalue, "destructure");
56
+ visit(identifierKinds, lvalue, 'destructure');
57
}
58
break;
59
}
63
- case "ObjectMethod":
64
- case "FunctionExpression": {
60
+ case 'ObjectMethod':
61
+ case 'FunctionExpression': {
62
validateContextVariableLValuesImpl(
63
value.loweredFunc.func,
67
- identifierKinds
64
+ identifierKinds,
65
);
66
break;
67
}
@@ -72,7 +69,7 @@ function validateContextVariableLValuesImpl(
69
for (const _ of eachInstructionValueLValue(value)) {
70
CompilerError.throwTodo({
71
reason:
75
- "ValidateContextVariableLValues: unhandled instruction variant",
72
+ 'ValidateContextVariableLValues: unhandled instruction variant',
73
loc: value.loc,
74
description: `Handle '${value.kind} lvalues`,
75
suggestions: null,
@@ -86,23 +83,23 @@ function validateContextVariableLValuesImpl(
83
84
type IdentifierKinds = Map<
85
IdentifierId,
89
- { place: Place; kind: "local" | "context" | "destructure" }
86
+ {place: Place; kind: 'local' | 'context' | 'destructure'}
87
>;
88
89
function visit(
90
identifiers: IdentifierKinds,
91
place: Place,
95
- kind: "local" | "context" | "destructure"
92
+ kind: 'local' | 'context' | 'destructure',
93
): void {
94
const prev = identifiers.get(place.identifier.id);
95
if (prev !== undefined) {
99
- const wasContext = prev.kind === "context";
100
- const isContext = kind === "context";
96
+ const wasContext = prev.kind === 'context';
97
+ const isContext = kind === 'context';
98
if (wasContext !== isContext) {
102
- if (prev.kind === "destructure" || kind === "destructure") {
99
+ if (prev.kind === 'destructure' || kind === 'destructure') {
100
CompilerError.throwTodo({
101
reason: `Support destructuring of context variables`,
105
- loc: kind === "destructure" ? place.loc : prev.place.loc,
102
+ loc: kind === 'destructure' ? place.loc : prev.place.loc,
103
description: null,
104
suggestions: null,
105
});
@@ -112,11 +109,11 @@ function visit(
109
reason: `Expected all references to a variable to be consistently local or context references`,
110
loc: place.loc,
111
description: `Identifier ${printPlace(
115
- place
112
+ place,
113
)} is referenced as a ${kind} variable, but was previously referenced as a ${prev} variable`,
114
suggestions: null,
115
});
116
}
117
}
121
- identifiers.set(place.identifier.id, { place, kind });
118
+ identifiers.set(place.identifier.id, {place, kind});
119
}
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateHooksUsage.ts
+45
-45
@@ -5,27 +5,27 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import * as t from "@babel/types";
8
+import * as t from '@babel/types';
9
import {
10
CompilerError,
11
CompilerErrorDetail,
12
ErrorSeverity,
13
-} from "../CompilerError";
14
-import { computeUnconditionalBlocks } from "../HIR/ComputeUnconditionalBlocks";
15
-import { isHookName } from "../HIR/Environment";
13
+} from '../CompilerError';
14
+import {computeUnconditionalBlocks} from '../HIR/ComputeUnconditionalBlocks';
15
+import {isHookName} from '../HIR/Environment';
16
import {
17
HIRFunction,
18
IdentifierId,
19
Place,
20
SourceLocation,
21
getHookKind,
22
-} from "../HIR/HIR";
22
+} from '../HIR/HIR';
23
import {
24
eachInstructionLValue,
25
eachInstructionOperand,
26
eachTerminalOperand,
27
-} from "../HIR/visitors";
28
-import { assertExhaustive } from "../Utils/utils";
27
+} from '../HIR/visitors';
28
+import {assertExhaustive} from '../Utils/utils';
29
30
/**
31
* Represents the possible kinds of value which may be stored at a given Place during
@@ -34,7 +34,7 @@ import { assertExhaustive } from "../Utils/utils";
34
*/
35
enum Kind {
36
// A potential/known hook which was already used in an invalid way
37
- Error = "Error",
37
+ Error = 'Error',
38
39
/*
40
* A known hook. Sources include:
@@ -44,7 +44,7 @@ enum Kind {
44
* - PropertyLoad, ComputedLoad, and Destructuring instructions
45
* where the object is a Global and the property name is hook-like
46
*/
47
- KnownHook = "KnownHook",
47
+ KnownHook = 'KnownHook',
48
49
/*
50
* A potential hook. Sources include:
@@ -53,13 +53,13 @@ enum Kind {
53
* where the object is a potential hook or the property name
54
* is hook-like
55
*/
56
- PotentialHook = "PotentialHook",
56
+ PotentialHook = 'PotentialHook',
57
58
// LoadGlobal values whose type was not inferred as a hook
59
- Global = "Global",
59
+ Global = 'Global',
60
61
// All other values, ie local variables
62
- Local = "Local",
62
+ Local = 'Local',
63
}
64
65
function joinKinds(a: Kind, b: Kind): Kind {
@@ -95,9 +95,9 @@ export function validateHooksUsage(fn: HIRFunction): void {
95
96
function recordError(
97
loc: SourceLocation,
98
- errorDetail: CompilerErrorDetail
98
+ errorDetail: CompilerErrorDetail,
99
): void {
100
- if (typeof loc === "symbol") {
100
+ if (typeof loc === 'symbol') {
101
errors.pushErrorDetail(errorDetail);
102
} else {
103
errorsByPlace.set(loc, errorDetail);
@@ -109,9 +109,9 @@ export function validateHooksUsage(fn: HIRFunction): void {
109
setKind(place, Kind.Error);
110
111
const reason =
112
- "Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)";
112
+ 'Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)';
113
const previousError =
114
- typeof place.loc !== "symbol" ? errorsByPlace.get(place.loc) : undefined;
114
+ typeof place.loc !== 'symbol' ? errorsByPlace.get(place.loc) : undefined;
115
116
/*
117
* In some circumstances such as optional calls, we may first encounter a "hook may not be referenced as normal values" error.
@@ -126,41 +126,41 @@ export function validateHooksUsage(fn: HIRFunction): void {
126
loc: place.loc,
127
severity: ErrorSeverity.InvalidReact,
128
suggestions: null,
129
- })
129
+ }),
130
);
131
}
132
}
133
function recordInvalidHookUsageError(place: Place): void {
134
const previousError =
135
- typeof place.loc !== "symbol" ? errorsByPlace.get(place.loc) : undefined;
135
+ typeof place.loc !== 'symbol' ? errorsByPlace.get(place.loc) : undefined;
136
if (previousError === undefined) {
137
recordError(
138
place.loc,
139
new CompilerErrorDetail({
140
description: null,
141
reason:
142
- "Hooks may not be referenced as normal values, they must be called. See https://react.dev/reference/rules/react-calls-components-and-hooks#never-pass-around-hooks-as-regular-values",
142
+ 'Hooks may not be referenced as normal values, they must be called. See https://react.dev/reference/rules/react-calls-components-and-hooks#never-pass-around-hooks-as-regular-values',
143
loc: place.loc,
144
severity: ErrorSeverity.InvalidReact,
145
suggestions: null,
146
- })
146
+ }),
147
);
148
}
149
}
150
function recordDynamicHookUsageError(place: Place): void {
151
const previousError =
152
- typeof place.loc !== "symbol" ? errorsByPlace.get(place.loc) : undefined;
152
+ typeof place.loc !== 'symbol' ? errorsByPlace.get(place.loc) : undefined;
153
if (previousError === undefined) {
154
recordError(
155
place.loc,
156
new CompilerErrorDetail({
157
description: null,
158
reason:
159
- "Hooks must be the same function on every render, but this value may change over time to a different function. See https://react.dev/reference/rules/react-calls-components-and-hooks#dont-dynamically-use-hooks",
159
+ 'Hooks must be the same function on every render, but this value may change over time to a different function. See https://react.dev/reference/rules/react-calls-components-and-hooks#dont-dynamically-use-hooks',
160
loc: place.loc,
161
severity: ErrorSeverity.InvalidReact,
162
suggestions: null,
163
- })
163
+ }),
164
);
165
}
166
}
@@ -190,7 +190,7 @@ export function validateHooksUsage(fn: HIRFunction): void {
190
}
191
192
for (const param of fn.params) {
193
- const place = param.kind === "Identifier" ? param : param.place;
193
+ const place = param.kind === 'Identifier' ? param : param.place;
194
const kind = getKindForPlace(place);
195
setKind(place, kind);
196
}
@@ -217,7 +217,7 @@ export function validateHooksUsage(fn: HIRFunction): void {
217
}
218
for (const instr of block.instructions) {
219
switch (instr.value.kind) {
220
- case "LoadGlobal": {
220
+ case 'LoadGlobal': {
221
/*
222
* Globals are the one source of known hooks: they are either
223
* directly a hook, or infer a Global kind from which knownhooks
@@ -230,31 +230,31 @@ export function validateHooksUsage(fn: HIRFunction): void {
230
}
231
break;
232
}
233
- case "LoadContext":
234
- case "LoadLocal": {
233
+ case 'LoadContext':
234
+ case 'LoadLocal': {
235
visitPlace(instr.value.place);
236
const kind = getKindForPlace(instr.value.place);
237
setKind(instr.lvalue, kind);
238
break;
239
}
240
- case "StoreLocal":
241
- case "StoreContext": {
240
+ case 'StoreLocal':
241
+ case 'StoreContext': {
242
visitPlace(instr.value.value);
243
const kind = joinKinds(
244
getKindForPlace(instr.value.value),
245
- getKindForPlace(instr.value.lvalue.place)
245
+ getKindForPlace(instr.value.lvalue.place),
246
);
247
setKind(instr.value.lvalue.place, kind);
248
setKind(instr.lvalue, kind);
249
break;
250
}
251
- case "ComputedLoad": {
251
+ case 'ComputedLoad': {
252
visitPlace(instr.value.object);
253
const kind = getKindForPlace(instr.value.object);
254
setKind(instr.lvalue, joinKinds(getKindForPlace(instr.lvalue), kind));
255
break;
256
}
257
- case "PropertyLoad": {
257
+ case 'PropertyLoad': {
258
const objectKind = getKindForPlace(instr.value.object);
259
const isHookProperty = isHookName(instr.value.property);
260
let kind: Kind;
@@ -311,7 +311,7 @@ export function validateHooksUsage(fn: HIRFunction): void {
311
setKind(instr.lvalue, kind);
312
break;
313
}
314
- case "CallExpression": {
314
+ case 'CallExpression': {
315
const calleeKind = getKindForPlace(instr.value.callee);
316
const isHookCallee =
317
calleeKind === Kind.KnownHook || calleeKind === Kind.PotentialHook;
@@ -331,7 +331,7 @@ export function validateHooksUsage(fn: HIRFunction): void {
331
}
332
break;
333
}
334
- case "MethodCall": {
334
+ case 'MethodCall': {
335
const calleeKind = getKindForPlace(instr.value.property);
336
const isHookCallee =
337
calleeKind === Kind.KnownHook || calleeKind === Kind.PotentialHook;
@@ -351,7 +351,7 @@ export function validateHooksUsage(fn: HIRFunction): void {
351
}
352
break;
353
}
354
- case "Destructure": {
354
+ case 'Destructure': {
355
visitPlace(instr.value.value);
356
const objectKind = getKindForPlace(instr.value.value);
357
for (const lvalue of eachInstructionLValue(instr)) {
@@ -383,7 +383,7 @@ export function validateHooksUsage(fn: HIRFunction): void {
383
default: {
384
assertExhaustive(
385
objectKind,
386
- `Unexpected kind \`${objectKind}\``
386
+ `Unexpected kind \`${objectKind}\``,
387
);
388
}
389
}
@@ -391,8 +391,8 @@ export function validateHooksUsage(fn: HIRFunction): void {
391
}
392
break;
393
}
394
- case "ObjectMethod":
395
- case "FunctionExpression": {
394
+ case 'ObjectMethod':
395
+ case 'FunctionExpression': {
396
visitFunctionExpression(errors, instr.value.loweredFunc.func);
397
break;
398
}
@@ -429,15 +429,15 @@ function visitFunctionExpression(errors: CompilerError, fn: HIRFunction): void {
429
for (const [, block] of fn.body.blocks) {
430
for (const instr of block.instructions) {
431
switch (instr.value.kind) {
432
- case "ObjectMethod":
433
- case "FunctionExpression": {
432
+ case 'ObjectMethod':
433
+ case 'FunctionExpression': {
434
visitFunctionExpression(errors, instr.value.loweredFunc.func);
435
break;
436
}
437
- case "MethodCall":
438
- case "CallExpression": {
437
+ case 'MethodCall':
438
+ case 'CallExpression': {
439
const callee =
440
- instr.value.kind === "CallExpression"
440
+ instr.value.kind === 'CallExpression'
441
? instr.value.callee
442
: instr.value.property;
443
const hookKind = getHookKind(fn.env, callee.identifier);
@@ -446,11 +446,11 @@ function visitFunctionExpression(errors: CompilerError, fn: HIRFunction): void {
446
new CompilerErrorDetail({
447
severity: ErrorSeverity.InvalidReact,
448
reason:
449
- "Hooks must be called at the top level in the body of a function component or custom hook, and may not be called within function expressions. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)",
449
+ 'Hooks must be called at the top level in the body of a function component or custom hook, and may not be called within function expressions. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning)',
450
loc: callee.loc,
451
description: `Cannot call ${hookKind} within a function component`,
452
suggestions: null,
453
- })
453
+ }),
454
);
455
}
456
break;
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateLocalsNotReassignedAfterRender.ts
+24
-24
@@ -5,12 +5,12 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError, Effect } from "..";
9
-import { HIRFunction, IdentifierId, Place } from "../HIR";
8
+import {CompilerError, Effect} from '..';
9
+import {HIRFunction, IdentifierId, Place} from '../HIR';
10
import {
11
eachInstructionValueOperand,
12
eachTerminalOperand,
13
-} from "../HIR/visitors";
13
+} from '../HIR/visitors';
14
15
/**
16
* Validates that local variables cannot be reassigned after render.
@@ -23,17 +23,17 @@ export function validateLocalsNotReassignedAfterRender(fn: HIRFunction): void {
23
fn,
24
contextVariables,
25
false,
26
- false
26
+ false,
27
);
28
if (reassignment !== null) {
29
CompilerError.throwInvalidReact({
30
reason:
31
- "Reassigning a variable after render has completed can cause inconsistent behavior on subsequent renders. Consider using state instead",
31
+ 'Reassigning a variable after render has completed can cause inconsistent behavior on subsequent renders. Consider using state instead',
32
description:
33
reassignment.identifier.name !== null &&
34
- reassignment.identifier.name.kind === "named"
34
+ reassignment.identifier.name.kind === 'named'
35
? `Variable \`${reassignment.identifier.name.value}\` cannot be reassigned after render`
36
- : "",
36
+ : '',
37
loc: reassignment.loc,
38
});
39
}
@@ -43,26 +43,26 @@ function getContextReassignment(
43
fn: HIRFunction,
44
contextVariables: Set<IdentifierId>,
45
isFunctionExpression: boolean,
46
- isAsync: boolean
46
+ isAsync: boolean,
47
): Place | null {
48
const reassigningFunctions = new Map<IdentifierId, Place>();
49
for (const [, block] of fn.body.blocks) {
50
for (const instr of block.instructions) {
51
- const { lvalue, value } = instr;
51
+ const {lvalue, value} = instr;
52
switch (value.kind) {
53
- case "FunctionExpression":
54
- case "ObjectMethod": {
53
+ case 'FunctionExpression':
54
+ case 'ObjectMethod': {
55
let reassignment = getContextReassignment(
56
value.loweredFunc.func,
57
contextVariables,
58
true,
59
- isAsync || value.loweredFunc.func.async
59
+ isAsync || value.loweredFunc.func.async,
60
);
61
if (reassignment === null) {
62
// If the function itself doesn't reassign, does one of its dependencies?
63
for (const operand of eachInstructionValueOperand(value)) {
64
const reassignmentFromOperand = reassigningFunctions.get(
65
- operand.identifier.id
65
+ operand.identifier.id,
66
);
67
if (reassignmentFromOperand !== undefined) {
68
reassignment = reassignmentFromOperand;
@@ -75,12 +75,12 @@ function getContextReassignment(
75
if (isAsync || value.loweredFunc.func.async) {
76
CompilerError.throwInvalidReact({
77
reason:
78
- "Reassigning a variable in an async function can cause inconsistent behavior on subsequent renders. Consider using state instead",
78
+ 'Reassigning a variable in an async function can cause inconsistent behavior on subsequent renders. Consider using state instead',
79
description:
80
reassignment.identifier.name !== null &&
81
- reassignment.identifier.name.kind === "named"
81
+ reassignment.identifier.name.kind === 'named'
82
? `Variable \`${reassignment.identifier.name.value}\` cannot be reassigned after render`
83
- : "",
83
+ : '',
84
loc: reassignment.loc,
85
});
86
}
@@ -88,35 +88,35 @@ function getContextReassignment(
88
}
89
break;
90
}
91
- case "StoreLocal": {
91
+ case 'StoreLocal': {
92
const reassignment = reassigningFunctions.get(
93
- value.value.identifier.id
93
+ value.value.identifier.id,
94
);
95
if (reassignment !== undefined) {
96
reassigningFunctions.set(
97
value.lvalue.place.identifier.id,
98
- reassignment
98
+ reassignment,
99
);
100
reassigningFunctions.set(lvalue.identifier.id, reassignment);
101
}
102
break;
103
}
104
- case "LoadLocal": {
104
+ case 'LoadLocal': {
105
const reassignment = reassigningFunctions.get(
106
- value.place.identifier.id
106
+ value.place.identifier.id,
107
);
108
if (reassignment !== undefined) {
109
reassigningFunctions.set(lvalue.identifier.id, reassignment);
110
}
111
break;
112
}
113
- case "DeclareContext": {
113
+ case 'DeclareContext': {
114
if (!isFunctionExpression) {
115
contextVariables.add(value.lvalue.place.identifier.id);
116
}
117
break;
118
}
119
- case "StoreContext": {
119
+ case 'StoreContext': {
120
if (isFunctionExpression) {
121
if (contextVariables.has(value.lvalue.place.identifier.id)) {
122
return value.lvalue.place;
@@ -137,7 +137,7 @@ function getContextReassignment(
137
loc: operand.loc,
138
});
139
const reassignment = reassigningFunctions.get(
140
- operand.identifier.id
140
+ operand.identifier.id,
141
);
142
if (
143
reassignment !== undefined &&
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateMemoizedEffectDependencies.ts
+10
-10
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError, ErrorSeverity } from "..";
8
+import {CompilerError, ErrorSeverity} from '..';
9
import {
10
Identifier,
11
Instruction,
@@ -16,12 +16,12 @@ import {
16
isUseEffectHookType,
17
isUseInsertionEffectHookType,
18
isUseLayoutEffectHookType,
19
-} from "../HIR";
20
-import { isMutable } from "../ReactiveScopes/InferReactiveScopeVariables";
19
+} from '../HIR';
20
+import {isMutable} from '../ReactiveScopes/InferReactiveScopeVariables';
21
import {
22
ReactiveFunctionVisitor,
23
visitReactiveFunction,
24
-} from "../ReactiveScopes/visitors";
24
+} from '../ReactiveScopes/visitors';
25
26
/**
27
* Validates that all known effect dependencies are memoized. The algorithm checks two things:
@@ -60,7 +60,7 @@ class Visitor extends ReactiveFunctionVisitor<CompilerError> {
60
61
override visitScope(
62
scopeBlock: ReactiveScopeBlock,
63
- state: CompilerError
63
+ state: CompilerError,
64
): void {
65
this.traverseScope(scopeBlock, state);
66
@@ -88,26 +88,26 @@ class Visitor extends ReactiveFunctionVisitor<CompilerError> {
88
89
override visitInstruction(
90
instruction: ReactiveInstruction,
91
- state: CompilerError
91
+ state: CompilerError,
92
): void {
93
this.traverseInstruction(instruction, state);
94
if (
95
- instruction.value.kind === "CallExpression" &&
95
+ instruction.value.kind === 'CallExpression' &&
96
isEffectHook(instruction.value.callee.identifier) &&
97
instruction.value.args.length >= 2
98
) {
99
const deps = instruction.value.args[1]!;
100
if (
101
- deps.kind === "Identifier" &&
101
+ deps.kind === 'Identifier' &&
102
(isMutable(instruction as Instruction, deps) ||
103
isUnmemoized(deps.identifier, this.scopes))
104
) {
105
state.push({
106
reason:
107
- "React Compiler has skipped optimizing this component because the effect dependencies could not be memoized. Unmemoized effect dependencies can trigger an infinite loop or other unexpected behavior",
107
+ 'React Compiler has skipped optimizing this component because the effect dependencies could not be memoized. Unmemoized effect dependencies can trigger an infinite loop or other unexpected behavior',
108
description: null,
109
severity: ErrorSeverity.CannotPreserveMemoization,
110
- loc: typeof instruction.loc !== "symbol" ? instruction.loc : null,
110
+ loc: typeof instruction.loc !== 'symbol' ? instruction.loc : null,
111
suggestions: null,
112
});
113
}
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateNoCapitalizedCalls.ts
+10
-10
@@ -4,9 +4,9 @@
4
* This source code is licensed under the MIT license found in the
5
* LICENSE file in the root directory of this source tree.
6
*/
7
-import { CompilerError, EnvironmentConfig } from "..";
8
-import { HIRFunction, IdentifierId } from "../HIR";
9
-import { DEFAULT_GLOBALS } from "../HIR/Globals";
7
+import {CompilerError, EnvironmentConfig} from '..';
8
+import {HIRFunction, IdentifierId} from '../HIR';
9
+import {DEFAULT_GLOBALS} from '../HIR/Globals';
10
11
export function validateNoCapitalizedCalls(fn: HIRFunction): void {
12
const envConfig: EnvironmentConfig = fn.env.config;
@@ -29,13 +29,13 @@ export function validateNoCapitalizedCalls(fn: HIRFunction): void {
29
const capitalLoadGlobals = new Map<IdentifierId, string>();
30
const capitalizedProperties = new Map<IdentifierId, string>();
31
const reason =
32
- "Capitalized functions are reserved for components, which must be invoked with JSX. If this is a component, render it with JSX. Otherwise, ensure that it has no hook calls and rename it to begin with a lowercase letter. Alternatively, if you know for a fact that this function is not a component, you can allowlist it via the compiler config";
32
+ 'Capitalized functions are reserved for components, which must be invoked with JSX. If this is a component, render it with JSX. Otherwise, ensure that it has no hook calls and rename it to begin with a lowercase letter. Alternatively, if you know for a fact that this function is not a component, you can allowlist it via the compiler config';
33
for (const [, block] of fn.body.blocks) {
34
- for (const { lvalue, value } of block.instructions) {
34
+ for (const {lvalue, value} of block.instructions) {
35
switch (value.kind) {
36
- case "LoadGlobal": {
36
+ case 'LoadGlobal': {
37
if (
38
- value.binding.name != "" &&
38
+ value.binding.name != '' &&
39
/^[A-Z]/.test(value.binding.name) &&
40
// We don't want to flag CONSTANTS()
41
!(value.binding.name.toUpperCase() === value.binding.name) &&
@@ -46,7 +46,7 @@ export function validateNoCapitalizedCalls(fn: HIRFunction): void {
46
47
break;
48
}
49
- case "CallExpression": {
49
+ case 'CallExpression': {
50
const calleeIdentifier = value.callee.identifier.id;
51
const calleeName = capitalLoadGlobals.get(calleeIdentifier);
52
if (calleeName != null) {
@@ -59,14 +59,14 @@ export function validateNoCapitalizedCalls(fn: HIRFunction): void {
59
}
60
break;
61
}
62
- case "PropertyLoad": {
62
+ case 'PropertyLoad': {
63
// Start conservative and disallow all capitalized method calls
64
if (/^[A-Z]/.test(value.property)) {
65
capitalizedProperties.set(lvalue.identifier.id, value.property);
66
}
67
break;
68
}
69
- case "MethodCall": {
69
+ case 'MethodCall': {
70
const propertyIdentifier = value.property.identifier.id;
71
const propertyName = capitalizedProperties.get(propertyIdentifier);
72
if (propertyName != null) {
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateNoRefAccesInRender.ts
+39
-39
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError, ErrorSeverity } from "../CompilerError";
8
+import {CompilerError, ErrorSeverity} from '../CompilerError';
9
import {
10
HIRFunction,
11
IdentifierId,
@@ -13,14 +13,14 @@ import {
13
SourceLocation,
14
isRefValueType,
15
isUseRefType,
16
-} from "../HIR";
17
-import { printPlace } from "../HIR/PrintHIR";
16
+} from '../HIR';
17
+import {printPlace} from '../HIR/PrintHIR';
18
import {
19
eachInstructionValueOperand,
20
eachTerminalOperand,
21
-} from "../HIR/visitors";
22
-import { Err, Ok, Result } from "../Utils/Result";
23
-import { isEffectHook } from "./ValidateMemoizedEffectDependencies";
21
+} from '../HIR/visitors';
22
+import {Err, Ok, Result} from '../Utils/Result';
23
+import {isEffectHook} from './ValidateMemoizedEffectDependencies';
24
25
/**
26
* Validates that a function does not access a ref value during render. This includes a partial check
@@ -49,23 +49,23 @@ export function validateNoRefAccessInRender(fn: HIRFunction): void {
49
50
function validateNoRefAccessInRenderImpl(
51
fn: HIRFunction,
52
- refAccessingFunctions: Set<IdentifierId>
52
+ refAccessingFunctions: Set<IdentifierId>,
53
): Result<void, CompilerError> {
54
const errors = new CompilerError();
55
for (const [, block] of fn.body.blocks) {
56
for (const instr of block.instructions) {
57
switch (instr.value.kind) {
58
- case "JsxExpression":
59
- case "JsxFragment": {
58
+ case 'JsxExpression':
59
+ case 'JsxFragment': {
60
for (const operand of eachInstructionValueOperand(instr.value)) {
61
if (isRefValueType(operand.identifier)) {
62
errors.push({
63
severity: ErrorSeverity.InvalidReact,
64
reason:
65
- "Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef)",
65
+ 'Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef)',
66
loc: operand.loc,
67
description: `Cannot access ref value at ${printPlace(
68
- operand
68
+ operand,
69
)}`,
70
suggestions: null,
71
});
@@ -73,41 +73,41 @@ function validateNoRefAccessInRenderImpl(
73
}
74
break;
75
}
76
- case "PropertyLoad": {
76
+ case 'PropertyLoad': {
77
break;
78
}
79
- case "LoadLocal": {
79
+ case 'LoadLocal': {
80
if (refAccessingFunctions.has(instr.value.place.identifier.id)) {
81
refAccessingFunctions.add(instr.lvalue.identifier.id);
82
}
83
break;
84
}
85
- case "StoreLocal": {
85
+ case 'StoreLocal': {
86
if (refAccessingFunctions.has(instr.value.value.identifier.id)) {
87
refAccessingFunctions.add(instr.value.lvalue.place.identifier.id);
88
refAccessingFunctions.add(instr.lvalue.identifier.id);
89
}
90
break;
91
}
92
- case "ObjectMethod":
93
- case "FunctionExpression": {
92
+ case 'ObjectMethod':
93
+ case 'FunctionExpression': {
94
if (
95
/*
96
* check if the function expression accesses a ref *or* some other
97
* function which accesses a ref
98
*/
99
[...eachInstructionValueOperand(instr.value)].some(
100
- (operand) =>
100
+ operand =>
101
isRefValueType(operand.identifier) ||
102
- refAccessingFunctions.has(operand.identifier.id)
102
+ refAccessingFunctions.has(operand.identifier.id),
103
) ||
104
// check for cases where .current is accessed through an aliased ref
105
- ([...eachInstructionValueOperand(instr.value)].some((operand) =>
106
- isUseRefType(operand.identifier)
105
+ ([...eachInstructionValueOperand(instr.value)].some(operand =>
106
+ isUseRefType(operand.identifier),
107
) &&
108
validateNoRefAccessInRenderImpl(
109
instr.value.loweredFunc.func,
110
- refAccessingFunctions
110
+ refAccessingFunctions,
111
).isErr())
112
) {
113
// This function expression unconditionally accesses a ref
@@ -115,20 +115,20 @@ function validateNoRefAccessInRenderImpl(
115
}
116
break;
117
}
118
- case "MethodCall": {
118
+ case 'MethodCall': {
119
if (!isEffectHook(instr.value.property.identifier)) {
120
for (const operand of eachInstructionValueOperand(instr.value)) {
121
validateNoRefAccess(
122
errors,
123
refAccessingFunctions,
124
operand,
125
- operand.loc
125
+ operand.loc,
126
);
127
}
128
}
129
break;
130
}
131
- case "CallExpression": {
131
+ case 'CallExpression': {
132
const callee = instr.value.callee;
133
const isUseEffect = isEffectHook(callee.identifier);
134
if (!isUseEffect) {
@@ -137,7 +137,7 @@ function validateNoRefAccessInRenderImpl(
137
errors.push({
138
severity: ErrorSeverity.InvalidReact,
139
reason:
140
- "This function accesses a ref value (the `current` property), which may not be accessed during render. (https://react.dev/reference/react/useRef)",
140
+ 'This function accesses a ref value (the `current` property), which may not be accessed during render. (https://react.dev/reference/react/useRef)',
141
loc: callee.loc,
142
description: `Function ${printPlace(callee)} accesses a ref`,
143
suggestions: null,
@@ -148,33 +148,33 @@ function validateNoRefAccessInRenderImpl(
148
errors,
149
refAccessingFunctions,
150
operand,
151
- operand.loc
151
+ operand.loc,
152
);
153
}
154
}
155
break;
156
}
157
- case "ObjectExpression":
158
- case "ArrayExpression": {
157
+ case 'ObjectExpression':
158
+ case 'ArrayExpression': {
159
for (const operand of eachInstructionValueOperand(instr.value)) {
160
validateNoRefAccess(
161
errors,
162
refAccessingFunctions,
163
operand,
164
- operand.loc
164
+ operand.loc,
165
);
166
}
167
break;
168
}
169
- case "PropertyDelete":
170
- case "PropertyStore":
171
- case "ComputedDelete":
172
- case "ComputedStore": {
169
+ case 'PropertyDelete':
170
+ case 'PropertyStore':
171
+ case 'ComputedDelete':
172
+ case 'ComputedStore': {
173
validateNoRefAccess(
174
errors,
175
refAccessingFunctions,
176
instr.value.object,
177
- instr.loc
177
+ instr.loc,
178
);
179
for (const operand of eachInstructionValueOperand(instr.value)) {
180
if (operand === instr.value.object) {
@@ -207,7 +207,7 @@ function validateNoRefAccessInRenderImpl(
207
function validateNoRefValueAccess(
208
errors: CompilerError,
209
refAccessingFunctions: Set<IdentifierId>,
210
- operand: Place
210
+ operand: Place,
211
): void {
212
if (
213
isRefValueType(operand.identifier) ||
@@ -216,7 +216,7 @@ function validateNoRefValueAccess(
216
errors.push({
217
severity: ErrorSeverity.InvalidReact,
218
reason:
219
- "Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef)",
219
+ 'Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef)',
220
loc: operand.loc,
221
description: `Cannot access ref value at ${printPlace(operand)}`,
222
suggestions: null,
@@ -228,7 +228,7 @@ function validateNoRefAccess(
228
errors: CompilerError,
229
refAccessingFunctions: Set<IdentifierId>,
230
operand: Place,
231
- loc: SourceLocation
231
+ loc: SourceLocation,
232
): void {
233
if (
234
isRefValueType(operand.identifier) ||
@@ -238,11 +238,11 @@ function validateNoRefAccess(
238
errors.push({
239
severity: ErrorSeverity.InvalidReact,
240
reason:
241
- "Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef)",
241
+ 'Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef)',
242
loc: loc,
243
description:
244
operand.identifier.name !== null &&
245
- operand.identifier.name.kind === "named"
245
+ operand.identifier.name.kind === 'named'
246
? `Cannot access ref value \`${operand.identifier.name.value}\``
247
: null,
248
suggestions: null,
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateNoSetStateInRender.ts
+21
-21
@@ -5,11 +5,11 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError, ErrorSeverity } from "../CompilerError";
9
-import { HIRFunction, IdentifierId, Place, isSetStateType } from "../HIR";
10
-import { computeUnconditionalBlocks } from "../HIR/ComputeUnconditionalBlocks";
11
-import { eachInstructionValueOperand } from "../HIR/visitors";
12
-import { Err, Ok, Result } from "../Utils/Result";
8
+import {CompilerError, ErrorSeverity} from '../CompilerError';
9
+import {HIRFunction, IdentifierId, Place, isSetStateType} from '../HIR';
10
+import {computeUnconditionalBlocks} from '../HIR/ComputeUnconditionalBlocks';
11
+import {eachInstructionValueOperand} from '../HIR/visitors';
12
+import {Err, Ok, Result} from '../Utils/Result';
13
14
/**
15
* Validates that the given function does not have an infinite update loop
@@ -46,7 +46,7 @@ export function validateNoSetStateInRender(fn: HIRFunction): void {
46
47
function validateNoSetStateInRenderImpl(
48
fn: HIRFunction,
49
- unconditionalSetStateFunctions: Set<IdentifierId>
49
+ unconditionalSetStateFunctions: Set<IdentifierId>,
50
): Result<void, CompilerError> {
51
const unconditionalBlocks = computeUnconditionalBlocks(fn);
52
@@ -55,42 +55,42 @@ function validateNoSetStateInRenderImpl(
55
if (unconditionalBlocks.has(block.id)) {
56
for (const instr of block.instructions) {
57
switch (instr.value.kind) {
58
- case "LoadLocal": {
58
+ case 'LoadLocal': {
59
if (
60
unconditionalSetStateFunctions.has(
61
- instr.value.place.identifier.id
61
+ instr.value.place.identifier.id,
62
)
63
) {
64
unconditionalSetStateFunctions.add(instr.lvalue.identifier.id);
65
}
66
break;
67
}
68
- case "StoreLocal": {
68
+ case 'StoreLocal': {
69
if (
70
unconditionalSetStateFunctions.has(
71
- instr.value.value.identifier.id
71
+ instr.value.value.identifier.id,
72
)
73
) {
74
unconditionalSetStateFunctions.add(
75
- instr.value.lvalue.place.identifier.id
75
+ instr.value.lvalue.place.identifier.id,
76
);
77
unconditionalSetStateFunctions.add(instr.lvalue.identifier.id);
78
}
79
break;
80
}
81
- case "ObjectMethod":
82
- case "FunctionExpression": {
81
+ case 'ObjectMethod':
82
+ case 'FunctionExpression': {
83
if (
84
// faster-path to check if the function expression references a setState
85
[...eachInstructionValueOperand(instr.value)].some(
86
- (operand) =>
86
+ operand =>
87
isSetStateType(operand.identifier) ||
88
- unconditionalSetStateFunctions.has(operand.identifier.id)
88
+ unconditionalSetStateFunctions.has(operand.identifier.id),
89
) &&
90
// if yes, does it unconditonally call it?
91
validateNoSetStateInRenderImpl(
92
instr.value.loweredFunc.func,
93
- unconditionalSetStateFunctions
93
+ unconditionalSetStateFunctions,
94
).isErr()
95
) {
96
// This function expression unconditionally calls a setState
@@ -98,11 +98,11 @@ function validateNoSetStateInRenderImpl(
98
}
99
break;
100
}
101
- case "CallExpression": {
101
+ case 'CallExpression': {
102
validateNonSetState(
103
errors,
104
unconditionalSetStateFunctions,
105
- instr.value.callee
105
+ instr.value.callee,
106
);
107
break;
108
}
@@ -121,7 +121,7 @@ function validateNoSetStateInRenderImpl(
121
function validateNonSetState(
122
errors: CompilerError,
123
unconditionalSetStateFunctions: Set<IdentifierId>,
124
- operand: Place
124
+ operand: Place,
125
): void {
126
if (
127
isSetStateType(operand.identifier) ||
@@ -129,10 +129,10 @@ function validateNonSetState(
129
) {
130
errors.push({
131
reason:
132
- "This is an unconditional set state during render, which will trigger an infinite loop. (https://react.dev/reference/react/useState)",
132
+ 'This is an unconditional set state during render, which will trigger an infinite loop. (https://react.dev/reference/react/useState)',
133
description: null,
134
severity: ErrorSeverity.InvalidReact,
135
- loc: typeof operand.loc !== "symbol" ? operand.loc : null,
135
+ loc: typeof operand.loc !== 'symbol' ? operand.loc : null,
136
suggestions: null,
137
});
138
}
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidatePreservedManualMemoization.ts
+62
-62
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError, Effect, ErrorSeverity } from "..";
8
+import {CompilerError, Effect, ErrorSeverity} from '..';
9
import {
10
GeneratedSource,
11
Identifier,
@@ -21,15 +21,15 @@ import {
21
ReactiveValue,
22
ScopeId,
23
SourceLocation,
24
-} from "../HIR";
25
-import { printManualMemoDependency } from "../HIR/PrintHIR";
26
-import { eachInstructionValueOperand } from "../HIR/visitors";
27
-import { collectMaybeMemoDependencies } from "../Inference/DropManualMemoization";
28
-import { isMutable } from "../ReactiveScopes/InferReactiveScopeVariables";
24
+} from '../HIR';
25
+import {printManualMemoDependency} from '../HIR/PrintHIR';
26
+import {eachInstructionValueOperand} from '../HIR/visitors';
27
+import {collectMaybeMemoDependencies} from '../Inference/DropManualMemoization';
28
+import {isMutable} from '../ReactiveScopes/InferReactiveScopeVariables';
29
import {
30
ReactiveFunctionVisitor,
31
visitReactiveFunction,
32
-} from "../ReactiveScopes/visitors";
32
+} from '../ReactiveScopes/visitors';
33
34
/**
35
* Validates that all explicit manual memoization (useMemo/useCallback) was accurately
@@ -100,12 +100,12 @@ type VisitorState = {
100
101
function prettyPrintScopeDependency(val: ReactiveScopeDependency): string {
102
let rootStr;
103
- if (val.identifier.name?.kind === "named") {
103
+ if (val.identifier.name?.kind === 'named') {
104
rootStr = val.identifier.name.value;
105
} else {
106
- rootStr = "[unnamed]";
106
+ rootStr = '[unnamed]';
107
}
108
- return `${rootStr}${val.path.length > 0 ? "." : ""}${val.path.join(".")}`;
108
+ return `${rootStr}${val.path.length > 0 ? '.' : ''}${val.path.join('.')}`;
109
}
110
111
enum CompareDependencyResult {
@@ -118,37 +118,37 @@ enum CompareDependencyResult {
118
119
function merge(
120
a: CompareDependencyResult,
121
- b: CompareDependencyResult
121
+ b: CompareDependencyResult,
122
): CompareDependencyResult {
123
return Math.max(a, b);
124
}
125
126
function getCompareDependencyResultDescription(
127
- result: CompareDependencyResult
127
+ result: CompareDependencyResult,
128
): string {
129
switch (result) {
130
case CompareDependencyResult.Ok:
131
- return "dependencies equal";
131
+ return 'dependencies equal';
132
case CompareDependencyResult.RootDifference:
133
case CompareDependencyResult.PathDifference:
134
- return "inferred different dependency than source";
134
+ return 'inferred different dependency than source';
135
case CompareDependencyResult.RefAccessDifference:
136
- return "differences in ref.current access";
136
+ return 'differences in ref.current access';
137
case CompareDependencyResult.Subpath:
138
- return "inferred less specific property than source";
138
+ return 'inferred less specific property than source';
139
}
140
}
141
142
function compareDeps(
143
inferred: ManualMemoDependency,
144
- source: ManualMemoDependency
144
+ source: ManualMemoDependency,
145
): CompareDependencyResult {
146
const rootsEqual =
147
- (inferred.root.kind === "Global" &&
148
- source.root.kind === "Global" &&
147
+ (inferred.root.kind === 'Global' &&
148
+ source.root.kind === 'Global' &&
149
inferred.root.identifierName === source.root.identifierName) ||
150
- (inferred.root.kind === "NamedLocal" &&
151
- source.root.kind === "NamedLocal" &&
150
+ (inferred.root.kind === 'NamedLocal' &&
151
+ source.root.kind === 'NamedLocal' &&
152
inferred.root.value.identifier.id === source.root.value.identifier.id);
153
if (!rootsEqual) {
154
return CompareDependencyResult.RootDifference;
@@ -166,14 +166,14 @@ function compareDeps(
166
isSubpath &&
167
(source.path.length === inferred.path.length ||
168
(inferred.path.length >= source.path.length &&
169
- !inferred.path.includes("current")))
169
+ !inferred.path.includes('current')))
170
) {
171
return CompareDependencyResult.Ok;
172
} else {
173
if (isSubpath) {
174
if (
175
- source.path.includes("current") ||
176
- inferred.path.includes("current")
175
+ source.path.includes('current') ||
176
+ inferred.path.includes('current')
177
) {
178
return CompareDependencyResult.RefAccessDifference;
179
} else {
@@ -208,7 +208,7 @@ function validateInferredDep(
208
declsWithinMemoBlock: Set<IdentifierId>,
209
validDepsInMemoBlock: Array<ManualMemoDependency>,
210
errorState: CompilerError,
211
- memoLocation: SourceLocation
211
+ memoLocation: SourceLocation,
212
): void {
213
let normalizedDep: ManualMemoDependency;
214
const maybeNormalizedRoot = temporaries.get(dep.identifier.id);
@@ -218,17 +218,17 @@ function validateInferredDep(
218
path: [...maybeNormalizedRoot.path, ...dep.path],
219
};
220
} else {
221
- CompilerError.invariant(dep.identifier.name?.kind === "named", {
221
+ CompilerError.invariant(dep.identifier.name?.kind === 'named', {
222
reason:
223
- "ValidatePreservedManualMemoization: expected scope dependency to be named",
223
+ 'ValidatePreservedManualMemoization: expected scope dependency to be named',
224
loc: GeneratedSource,
225
suggestions: null,
226
});
227
normalizedDep = {
228
root: {
229
- kind: "NamedLocal",
229
+ kind: 'NamedLocal',
230
value: {
231
- kind: "Identifier",
231
+ kind: 'Identifier',
232
identifier: dep.identifier,
233
loc: GeneratedSource,
234
effect: Effect.Read,
@@ -240,7 +240,7 @@ function validateInferredDep(
240
}
241
for (const decl of declsWithinMemoBlock) {
242
if (
243
- normalizedDep.root.kind === "NamedLocal" &&
243
+ normalizedDep.root.kind === 'NamedLocal' &&
244
decl === normalizedDep.root.value.identifier.id
245
) {
246
return;
@@ -258,16 +258,16 @@ function validateInferredDep(
258
errorState.push({
259
severity: ErrorSeverity.CannotPreserveMemoization,
260
reason:
261
- "React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected",
261
+ 'React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. The inferred dependencies did not match the manually specified dependencies, which could cause the value to change more or less frequently than expected',
262
description: DEBUG
263
? `The inferred dependency was \`${prettyPrintScopeDependency(
264
- dep
264
+ dep,
265
)}\`, but the source dependencies were [${validDepsInMemoBlock
266
- .map((dep) => printManualMemoDependency(dep, true))
267
- .join(", ")}]. Detail: ${
266
+ .map(dep => printManualMemoDependency(dep, true))
267
+ .join(', ')}]. Detail: ${
268
errorDiagnostic
269
? getCompareDependencyResultDescription(errorDiagnostic)
270
- : "none"
270
+ : 'none'
271
}`
272
: null,
273
loc: memoLocation,
@@ -288,46 +288,46 @@ class Visitor extends ReactiveFunctionVisitor<VisitorState> {
288
*/
289
recordDepsInValue(
290
value: ReactiveValue,
291
- state: VisitorState
291
+ state: VisitorState,
292
): ManualMemoDependency | null {
293
switch (value.kind) {
294
- case "SequenceExpression": {
294
+ case 'SequenceExpression': {
295
for (const instr of value.instructions) {
296
this.visitInstruction(instr, state);
297
}
298
const result = this.recordDepsInValue(value.value, state);
299
return result;
300
}
301
- case "OptionalExpression": {
301
+ case 'OptionalExpression': {
302
return this.recordDepsInValue(value.value, state);
303
}
304
- case "ReactiveFunctionValue": {
304
+ case 'ReactiveFunctionValue': {
305
CompilerError.throwTodo({
306
reason:
307
- "Handle ReactiveFunctionValue in ValidatePreserveManualMemoization",
307
+ 'Handle ReactiveFunctionValue in ValidatePreserveManualMemoization',
308
loc: value.loc,
309
});
310
}
311
- case "ConditionalExpression": {
311
+ case 'ConditionalExpression': {
312
this.recordDepsInValue(value.test, state);
313
this.recordDepsInValue(value.consequent, state);
314
this.recordDepsInValue(value.alternate, state);
315
return null;
316
}
317
- case "LogicalExpression": {
317
+ case 'LogicalExpression': {
318
this.recordDepsInValue(value.left, state);
319
this.recordDepsInValue(value.right, state);
320
return null;
321
}
322
default: {
323
const dep = collectMaybeMemoDependencies(value, this.temporaries);
324
- if (value.kind === "StoreLocal" || value.kind === "StoreContext") {
324
+ if (value.kind === 'StoreLocal' || value.kind === 'StoreContext') {
325
const storeTarget = value.lvalue.place;
326
state.manualMemoState?.decls.add(storeTarget.identifier.id);
327
- if (storeTarget.identifier.name?.kind === "named" && dep == null) {
327
+ if (storeTarget.identifier.name?.kind === 'named' && dep == null) {
328
const dep: ManualMemoDependency = {
329
root: {
330
- kind: "NamedLocal",
330
+ kind: 'NamedLocal',
331
value: storeTarget,
332
},
333
path: [],
@@ -343,13 +343,13 @@ class Visitor extends ReactiveFunctionVisitor<VisitorState> {
343
344
recordTemporaries(instr: ReactiveInstruction, state: VisitorState): void {
345
const temporaries = this.temporaries;
346
- const { value } = instr;
346
+ const {value} = instr;
347
const lvalId = instr.lvalue?.identifier.id;
348
if (lvalId != null && temporaries.has(lvalId)) {
349
return;
350
}
351
const isNamedLocal =
352
- lvalId != null && instr.lvalue?.identifier.name?.kind === "named";
352
+ lvalId != null && instr.lvalue?.identifier.name?.kind === 'named';
353
if (isNamedLocal && state.manualMemoState != null) {
354
state.manualMemoState.decls.add(lvalId);
355
}
@@ -361,8 +361,8 @@ class Visitor extends ReactiveFunctionVisitor<VisitorState> {
361
} else if (isNamedLocal) {
362
temporaries.set(lvalId, {
363
root: {
364
- kind: "NamedLocal",
365
- value: { ...(instr.lvalue as Place) },
364
+ kind: 'NamedLocal',
365
+ value: {...(instr.lvalue as Place)},
366
},
367
path: [],
368
});
@@ -372,7 +372,7 @@ class Visitor extends ReactiveFunctionVisitor<VisitorState> {
372
373
override visitScope(
374
scopeBlock: ReactiveScopeBlock,
375
- state: VisitorState
375
+ state: VisitorState,
376
): void {
377
this.traverseScope(scopeBlock, state);
378
@@ -387,7 +387,7 @@ class Visitor extends ReactiveFunctionVisitor<VisitorState> {
387
state.manualMemoState.decls,
388
state.manualMemoState.depsFromSource,
389
state.errors,
390
- state.manualMemoState.loc
390
+ state.manualMemoState.loc,
391
);
392
}
393
}
@@ -416,20 +416,20 @@ class Visitor extends ReactiveFunctionVisitor<VisitorState> {
416
417
override visitInstruction(
418
instruction: ReactiveInstruction,
419
- state: VisitorState
419
+ state: VisitorState,
420
): void {
421
/**
422
* We don't invoke traverseInstructions because `recordDepsInValue`
423
* recursively visits ReactiveValues and instructions
424
*/
425
this.recordTemporaries(instruction, state);
426
- if (instruction.value.kind === "StartMemoize") {
426
+ if (instruction.value.kind === 'StartMemoize') {
427
let depsFromSource: Array<ManualMemoDependency> | null = null;
428
if (instruction.value.deps != null) {
429
depsFromSource = instruction.value.deps;
430
}
431
CompilerError.invariant(state.manualMemoState == null, {
432
- reason: "Unexpected nested StartMemoize instructions",
432
+ reason: 'Unexpected nested StartMemoize instructions',
433
description: `Bad manual memoization ids: ${state.manualMemoState?.manualMemoId}, ${instruction.value.manualMemoId}`,
434
loc: instruction.value.loc,
435
suggestions: null,
@@ -442,26 +442,26 @@ class Visitor extends ReactiveFunctionVisitor<VisitorState> {
442
manualMemoId: instruction.value.manualMemoId,
443
};
444
}
445
- if (instruction.value.kind === "FinishMemoize") {
445
+ if (instruction.value.kind === 'FinishMemoize') {
446
CompilerError.invariant(
447
state.manualMemoState != null &&
448
state.manualMemoState.manualMemoId === instruction.value.manualMemoId,
449
{
450
- reason: "Unexpected mismatch between StartMemoize and FinishMemoize",
450
+ reason: 'Unexpected mismatch between StartMemoize and FinishMemoize',
451
description: `Encountered StartMemoize id=${state.manualMemoState?.manualMemoId} followed by FinishMemoize id=${instruction.value.manualMemoId}`,
452
loc: instruction.value.loc,
453
suggestions: null,
454
- }
454
+ },
455
);
456
state.manualMemoState = null;
457
}
458
459
- const isDep = instruction.value.kind === "StartMemoize";
459
+ const isDep = instruction.value.kind === 'StartMemoize';
460
const isDecl =
461
- instruction.value.kind === "FinishMemoize" && !instruction.value.pruned;
461
+ instruction.value.kind === 'FinishMemoize' && !instruction.value.pruned;
462
if (isDep || isDecl) {
463
for (const value of eachInstructionValueOperand(
464
- instruction.value as InstructionValue
464
+ instruction.value as InstructionValue,
465
)) {
466
if (
467
isMutable(instruction as Instruction, value) ||
@@ -469,10 +469,10 @@ class Visitor extends ReactiveFunctionVisitor<VisitorState> {
469
) {
470
state.errors.push({
471
reason:
472
- "React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. This value may be mutated later, which could cause the value to change unexpectedly",
472
+ 'React Compiler has skipped optimizing this component because the existing manual memoization could not be preserved. This value may be mutated later, which could cause the value to change unexpectedly',
473
description: null,
474
severity: ErrorSeverity.CannotPreserveMemoization,
475
- loc: typeof instruction.loc !== "symbol" ? instruction.loc : null,
475
+ loc: typeof instruction.loc !== 'symbol' ? instruction.loc : null,
476
suggestions: null,
477
});
478
}
compiler/packages/babel-plugin-react-compiler/src/Validation/ValidateUseMemo.ts
+15
-15
@@ -5,41 +5,41 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "..";
9
-import { FunctionExpression, HIRFunction, IdentifierId } from "../HIR";
8
+import {CompilerError} from '..';
9
+import {FunctionExpression, HIRFunction, IdentifierId} from '../HIR';
10
11
export function validateUseMemo(fn: HIRFunction): void {
12
const useMemos = new Set<IdentifierId>();
13
const react = new Set<IdentifierId>();
14
const functions = new Map<IdentifierId, FunctionExpression>();
15
for (const [, block] of fn.body.blocks) {
16
- for (const { lvalue, value } of block.instructions) {
16
+ for (const {lvalue, value} of block.instructions) {
17
switch (value.kind) {
18
- case "LoadGlobal": {
19
- if (value.binding.name === "useMemo") {
18
+ case 'LoadGlobal': {
19
+ if (value.binding.name === 'useMemo') {
20
useMemos.add(lvalue.identifier.id);
21
- } else if (value.binding.name === "React") {
21
+ } else if (value.binding.name === 'React') {
22
react.add(lvalue.identifier.id);
23
}
24
break;
25
}
26
- case "PropertyLoad": {
26
+ case 'PropertyLoad': {
27
if (react.has(value.object.identifier.id)) {
28
- if (value.property === "useMemo") {
28
+ if (value.property === 'useMemo') {
29
useMemos.add(lvalue.identifier.id);
30
}
31
}
32
break;
33
}
34
- case "FunctionExpression": {
34
+ case 'FunctionExpression': {
35
functions.set(lvalue.identifier.id, value);
36
break;
37
}
38
- case "MethodCall":
39
- case "CallExpression": {
38
+ case 'MethodCall':
39
+ case 'CallExpression': {
40
// Is the function being called useMemo, with at least 1 argument?
41
const callee =
42
- value.kind === "CallExpression"
42
+ value.kind === 'CallExpression'
43
? value.callee.identifier.id
44
: value.property.identifier.id;
45
const isUseMemo = useMemos.has(callee);
@@ -52,7 +52,7 @@ export function validateUseMemo(fn: HIRFunction): void {
52
* expression, validate the function
53
*/
54
const [arg] = value.args;
55
- if (arg.kind !== "Identifier") {
55
+ if (arg.kind !== 'Identifier') {
56
continue;
57
}
58
const body = functions.get(arg.identifier.id);
@@ -62,7 +62,7 @@ export function validateUseMemo(fn: HIRFunction): void {
62
63
if (body.loweredFunc.func.params.length > 0) {
64
CompilerError.throwInvalidReact({
65
- reason: "useMemo callbacks may not accept any arguments",
65
+ reason: 'useMemo callbacks may not accept any arguments',
66
description: null,
67
loc: body.loc,
68
suggestions: null,
@@ -72,7 +72,7 @@ export function validateUseMemo(fn: HIRFunction): void {
72
if (body.loweredFunc.func.async || body.loweredFunc.func.generator) {
73
CompilerError.throwInvalidReact({
74
reason:
75
- "useMemo callbacks may not be async or generator functions",
75
+ 'useMemo callbacks may not be async or generator functions',
76
description: null,
77
loc: body.loc,
78
suggestions: null,
compiler/packages/babel-plugin-react-compiler/src/Validation/index.ts
+8
-8
@@ -5,11 +5,11 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-export { validateContextVariableLValues } from "./ValidateContextVariableLValues";
9
-export { validateHooksUsage } from "./ValidateHooksUsage";
10
-export { validateMemoizedEffectDependencies } from "./ValidateMemoizedEffectDependencies";
11
-export { validateNoCapitalizedCalls } from "./ValidateNoCapitalizedCalls";
12
-export { validateNoRefAccessInRender } from "./ValidateNoRefAccesInRender";
13
-export { validateNoSetStateInRender } from "./ValidateNoSetStateInRender";
14
-export { validatePreservedManualMemoization } from "./ValidatePreservedManualMemoization";
15
-export { validateUseMemo } from "./ValidateUseMemo";
8
+export {validateContextVariableLValues} from './ValidateContextVariableLValues';
9
+export {validateHooksUsage} from './ValidateHooksUsage';
10
+export {validateMemoizedEffectDependencies} from './ValidateMemoizedEffectDependencies';
11
+export {validateNoCapitalizedCalls} from './ValidateNoCapitalizedCalls';
12
+export {validateNoRefAccessInRender} from './ValidateNoRefAccesInRender';
13
+export {validateNoSetStateInRender} from './ValidateNoSetStateInRender';
14
+export {validatePreservedManualMemoization} from './ValidatePreservedManualMemoization';
15
+export {validateUseMemo} from './ValidateUseMemo';
compiler/packages/babel-plugin-react-compiler/src/__tests__/DisjointSet-test.ts
+11
-11
@@ -5,14 +5,14 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import DisjointSet from "../Utils/DisjointSet";
8
+import DisjointSet from '../Utils/DisjointSet';
9
10
type TestIdentifier = {
11
id: number;
12
name: string;
13
};
14
15
-describe("DisjointSet", () => {
15
+describe('DisjointSet', () => {
16
let identifierId = 0;
17
function makeIdentifier(name: string): TestIdentifier {
18
return {
@@ -22,16 +22,16 @@ describe("DisjointSet", () => {
22
}
23
24
function makeIdentifiers(...names: string[]): TestIdentifier[] {
25
- return names.map((name) => makeIdentifier(name));
25
+ return names.map(name => makeIdentifier(name));
26
}
27
28
beforeEach(() => {
29
identifierId = 0;
30
});
31
32
- it(".find - finds the correct group which the item is associated with", () => {
32
+ it('.find - finds the correct group which the item is associated with', () => {
33
const identifiers = new DisjointSet<TestIdentifier>();
34
- const [x, y, z] = makeIdentifiers("x", "y", "z");
34
+ const [x, y, z] = makeIdentifiers('x', 'y', 'z');
35
36
identifiers.union([x]);
37
identifiers.union([y, x]);
@@ -41,15 +41,15 @@ describe("DisjointSet", () => {
41
expect(identifiers.find(z)).toBe(null);
42
});
43
44
- it(".size - returns 0 when empty", () => {
44
+ it('.size - returns 0 when empty', () => {
45
const identifiers = new DisjointSet<TestIdentifier>();
46
47
expect(identifiers.size).toBe(0);
48
});
49
50
- it(".size - returns the correct size when non-empty", () => {
50
+ it('.size - returns the correct size when non-empty', () => {
51
const identifiers = new DisjointSet<TestIdentifier>();
52
- const [x, y] = makeIdentifiers("x", "y", "z");
52
+ const [x, y] = makeIdentifiers('x', 'y', 'z');
53
54
identifiers.union([x]);
55
identifiers.union([y, x]);
@@ -57,9 +57,9 @@ describe("DisjointSet", () => {
57
expect(identifiers.size).toBe(2);
58
});
59
60
- it(".buildSets - returns non-overlapping sets", () => {
60
+ it('.buildSets - returns non-overlapping sets', () => {
61
const identifiers = new DisjointSet<TestIdentifier>();
62
- const [a, b, c, x, y, z] = makeIdentifiers("a", "b", "c", "x", "y", "z");
62
+ const [a, b, c, x, y, z] = makeIdentifiers('a', 'b', 'c', 'x', 'y', 'z');
63
64
identifiers.union([a]);
65
identifiers.union([b, a]);
@@ -107,7 +107,7 @@ describe("DisjointSet", () => {
107
// Regression test for issue #933
108
it("`forEach` doesn't infinite loop when there are cycles", () => {
109
const identifiers = new DisjointSet<TestIdentifier>();
110
- const [x, y, z] = makeIdentifiers("x", "y", "z");
110
+ const [x, y, z] = makeIdentifiers('x', 'y', 'z');
111
112
identifiers.union([x]);
113
identifiers.union([y, x]);
compiler/packages/babel-plugin-react-compiler/src/__tests__/Logger-test.ts
+30
-30
@@ -5,12 +5,12 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import * as t from "@babel/types";
9
-import invariant from "invariant";
10
-import { runBabelPluginReactCompiler } from "../Babel/RunReactCompilerBabelPlugin";
11
-import type { Logger, LoggerEvent } from "../Entrypoint";
8
+import * as t from '@babel/types';
9
+import invariant from 'invariant';
10
+import {runBabelPluginReactCompiler} from '../Babel/RunReactCompilerBabelPlugin';
11
+import type {Logger, LoggerEvent} from '../Entrypoint';
12
13
-it("logs succesful compilation", () => {
13
+it('logs succesful compilation', () => {
14
const logs: [string | null, LoggerEvent][] = [];
15
const logger: Logger = {
16
logEvent(filename, event) {
@@ -19,22 +19,22 @@ it("logs succesful compilation", () => {
19
};
20
21
const _ = runBabelPluginReactCompiler(
22
- "function Component(props) { return <div>{props}</div> }",
23
- "test.js",
24
- "flow",
25
- { logger, panicThreshold: "all_errors" }
22
+ 'function Component(props) { return <div>{props}</div> }',
23
+ 'test.js',
24
+ 'flow',
25
+ {logger, panicThreshold: 'all_errors'},
26
);
27
28
const [filename, event] = logs.at(0)!;
29
- expect(filename).toContain("test.js");
30
- expect(event.kind).toEqual("CompileSuccess");
31
- invariant(event.kind === "CompileSuccess", "typescript be smarter");
32
- expect(event.fnName).toEqual("Component");
33
- expect(event.fnLoc?.end).toEqual({ column: 55, index: 55, line: 1 });
34
- expect(event.fnLoc?.start).toEqual({ column: 0, index: 0, line: 1 });
29
+ expect(filename).toContain('test.js');
30
+ expect(event.kind).toEqual('CompileSuccess');
31
+ invariant(event.kind === 'CompileSuccess', 'typescript be smarter');
32
+ expect(event.fnName).toEqual('Component');
33
+ expect(event.fnLoc?.end).toEqual({column: 55, index: 55, line: 1});
34
+ expect(event.fnLoc?.start).toEqual({column: 0, index: 0, line: 1});
35
});
36
37
-it("logs failed compilation", () => {
37
+it('logs failed compilation', () => {
38
const logs: [string | null, LoggerEvent][] = [];
39
const logger: Logger = {
40
logEvent(filename, event) {
@@ -44,26 +44,26 @@ it("logs failed compilation", () => {
44
45
expect(() => {
46
runBabelPluginReactCompiler(
47
- "function Component(props) { props.foo = 1; return <div>{props}</div> }",
48
- "test.js",
49
- "flow",
50
- { logger, panicThreshold: "all_errors" }
47
+ 'function Component(props) { props.foo = 1; return <div>{props}</div> }',
48
+ 'test.js',
49
+ 'flow',
50
+ {logger, panicThreshold: 'all_errors'},
51
);
52
}).toThrow();
53
54
const [filename, event] = logs.at(0)!;
55
- expect(filename).toContain("test.js");
56
- expect(event.kind).toEqual("CompileError");
57
- invariant(event.kind === "CompileError", "typescript be smarter");
55
+ expect(filename).toContain('test.js');
56
+ expect(event.kind).toEqual('CompileError');
57
+ invariant(event.kind === 'CompileError', 'typescript be smarter');
58
59
- expect(event.detail.severity).toEqual("InvalidReact");
59
+ expect(event.detail.severity).toEqual('InvalidReact');
60
//@ts-ignore
61
- const { start, end, identifierName } = event.detail.loc as t.SourceLocation;
62
- expect(start).toEqual({ column: 28, index: 28, line: 1 });
63
- expect(end).toEqual({ column: 33, index: 33, line: 1 });
64
- expect(identifierName).toEqual("props");
61
+ const {start, end, identifierName} = event.detail.loc as t.SourceLocation;
62
+ expect(start).toEqual({column: 28, index: 28, line: 1});
63
+ expect(end).toEqual({column: 33, index: 33, line: 1});
64
+ expect(identifierName).toEqual('props');
65
66
// Make sure event.fnLoc is different from event.detail.loc
67
- expect(event.fnLoc?.start).toEqual({ column: 0, index: 0, line: 1 });
68
- expect(event.fnLoc?.end).toEqual({ column: 70, index: 70, line: 1 });
67
+ expect(event.fnLoc?.start).toEqual({column: 0, index: 0, line: 1});
68
+ expect(event.fnLoc?.end).toEqual({column: 70, index: 70, line: 1});
69
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/Result-test.ts
+56
-58
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { CompilerError } from "../CompilerError";
9
-import { Err, Ok, Result } from "../Utils/Result";
8
+import {CompilerError} from '../CompilerError';
9
+import {Err, Ok, Result} from '../Utils/Result';
10
11
function addMax10(a: number, b: number): Result<number, string> {
12
const n = a + b;
@@ -14,133 +14,131 @@ function addMax10(a: number, b: number): Result<number, string> {
14
}
15
16
function onlyFoo(foo: string): Result<string, string> {
17
- return foo === "foo" ? Ok(foo) : Err(foo);
17
+ return foo === 'foo' ? Ok(foo) : Err(foo);
18
}
19
20
class CustomDummyError extends Error {}
21
22
-describe("Result", () => {
23
- test(".map", () => {
24
- expect(addMax10(1, 1).map((n) => n * 2)).toEqual(Ok(4));
25
- expect(addMax10(10, 10).map((n) => n * 2)).toEqual(Err("20 is too high"));
22
+describe('Result', () => {
23
+ test('.map', () => {
24
+ expect(addMax10(1, 1).map(n => n * 2)).toEqual(Ok(4));
25
+ expect(addMax10(10, 10).map(n => n * 2)).toEqual(Err('20 is too high'));
26
});
27
28
- test(".mapErr", () => {
29
- expect(addMax10(1, 1).mapErr((e) => `not a number: ${e}`)).toEqual(Ok(2));
30
- expect(addMax10(10, 10).mapErr((e) => `couldn't add: ${e}`)).toEqual(
31
- Err("couldn't add: 20 is too high")
28
+ test('.mapErr', () => {
29
+ expect(addMax10(1, 1).mapErr(e => `not a number: ${e}`)).toEqual(Ok(2));
30
+ expect(addMax10(10, 10).mapErr(e => `couldn't add: ${e}`)).toEqual(
31
+ Err("couldn't add: 20 is too high"),
32
);
33
});
34
35
- test(".mapOr", () => {
36
- expect(onlyFoo("foo").mapOr(42, (v) => v.length)).toEqual(3);
37
- expect(onlyFoo("bar").mapOr(42, (v) => v.length)).toEqual(42);
35
+ test('.mapOr', () => {
36
+ expect(onlyFoo('foo').mapOr(42, v => v.length)).toEqual(3);
37
+ expect(onlyFoo('bar').mapOr(42, v => v.length)).toEqual(42);
38
});
39
40
- test(".mapOrElse", () => {
40
+ test('.mapOrElse', () => {
41
expect(
42
- onlyFoo("foo").mapOrElse(
42
+ onlyFoo('foo').mapOrElse(
43
() => 42,
44
- (v) => v.length
45
- )
44
+ v => v.length,
45
+ ),
46
).toEqual(3);
47
expect(
48
- onlyFoo("bar").mapOrElse(
48
+ onlyFoo('bar').mapOrElse(
49
() => 42,
50
- (v) => v.length
51
- )
50
+ v => v.length,
51
+ ),
52
).toEqual(42);
53
});
54
55
- test(".andThen", () => {
56
- expect(addMax10(1, 1).andThen((n) => Ok(n * 2))).toEqual(Ok(4));
57
- expect(addMax10(10, 10).andThen((n) => Ok(n * 2))).toEqual(
58
- Err("20 is too high")
55
+ test('.andThen', () => {
56
+ expect(addMax10(1, 1).andThen(n => Ok(n * 2))).toEqual(Ok(4));
57
+ expect(addMax10(10, 10).andThen(n => Ok(n * 2))).toEqual(
58
+ Err('20 is too high'),
59
);
60
});
61
62
- test(".and", () => {
62
+ test('.and', () => {
63
expect(addMax10(1, 1).and(Ok(4))).toEqual(Ok(4));
64
- expect(addMax10(10, 10).and(Ok(4))).toEqual(Err("20 is too high"));
65
- expect(addMax10(1, 1).and(Err("hehe"))).toEqual(Err("hehe"));
66
- expect(addMax10(10, 10).and(Err("hehe"))).toEqual(Err("20 is too high"));
64
+ expect(addMax10(10, 10).and(Ok(4))).toEqual(Err('20 is too high'));
65
+ expect(addMax10(1, 1).and(Err('hehe'))).toEqual(Err('hehe'));
66
+ expect(addMax10(10, 10).and(Err('hehe'))).toEqual(Err('20 is too high'));
67
});
68
69
- test(".or", () => {
69
+ test('.or', () => {
70
expect(addMax10(1, 1).or(Ok(4))).toEqual(Ok(2));
71
expect(addMax10(10, 10).or(Ok(4))).toEqual(Ok(4));
72
- expect(addMax10(1, 1).or(Err("hehe"))).toEqual(Ok(2));
73
- expect(addMax10(10, 10).or(Err("hehe"))).toEqual(Err("hehe"));
72
+ expect(addMax10(1, 1).or(Err('hehe'))).toEqual(Ok(2));
73
+ expect(addMax10(10, 10).or(Err('hehe'))).toEqual(Err('hehe'));
74
});
75
76
- test(".orElse", () => {
77
- expect(addMax10(1, 1).orElse((str) => Err(str.toUpperCase()))).toEqual(
78
- Ok(2)
79
- );
80
- expect(addMax10(10, 10).orElse((str) => Err(str.toUpperCase()))).toEqual(
81
- Err("20 IS TOO HIGH")
76
+ test('.orElse', () => {
77
+ expect(addMax10(1, 1).orElse(str => Err(str.toUpperCase()))).toEqual(Ok(2));
78
+ expect(addMax10(10, 10).orElse(str => Err(str.toUpperCase()))).toEqual(
79
+ Err('20 IS TOO HIGH'),
80
);
81
});
82
85
- test(".isOk", () => {
83
+ test('.isOk', () => {
84
expect(addMax10(1, 1).isOk()).toBeTruthy();
85
expect(addMax10(10, 10).isOk()).toBeFalsy();
86
});
87
90
- test(".isErr", () => {
88
+ test('.isErr', () => {
89
expect(addMax10(1, 1).isErr()).toBeFalsy();
90
expect(addMax10(10, 10).isErr()).toBeTruthy();
91
});
92
95
- test(".expect", () => {
96
- expect(addMax10(1, 1).expect("a number under 10")).toEqual(2);
93
+ test('.expect', () => {
94
+ expect(addMax10(1, 1).expect('a number under 10')).toEqual(2);
95
expect(() => {
98
- addMax10(10, 10).expect("a number under 10");
96
+ addMax10(10, 10).expect('a number under 10');
97
}).toThrowErrorMatchingInlineSnapshot(
100
- `"a number under 10: 20 is too high"`
98
+ `"a number under 10: 20 is too high"`,
99
);
100
});
101
104
- test(".expectErr", () => {
102
+ test('.expectErr', () => {
103
expect(() => {
106
- addMax10(1, 1).expectErr("a number under 10");
104
+ addMax10(1, 1).expectErr('a number under 10');
105
}).toThrowErrorMatchingInlineSnapshot(`"a number under 10: 2"`);
108
- expect(addMax10(10, 10).expectErr("a number under 10")).toEqual(
109
- "20 is too high"
106
+ expect(addMax10(10, 10).expectErr('a number under 10')).toEqual(
107
+ '20 is too high',
108
);
109
});
110
113
- test(".unwrap", () => {
111
+ test('.unwrap', () => {
112
expect(addMax10(1, 1).unwrap()).toEqual(2);
113
expect(() => {
114
addMax10(10, 10).unwrap();
115
}).toThrowErrorMatchingInlineSnapshot(
118
- `"Can't unwrap \`Err\` to \`Ok\`: 20 is too high"`
116
+ `"Can't unwrap \`Err\` to \`Ok\`: 20 is too high"`,
117
);
118
expect(() => {
121
- Err(new CustomDummyError("oops")).unwrap();
119
+ Err(new CustomDummyError('oops')).unwrap();
120
}).toThrowErrorMatchingInlineSnapshot(`"oops"`);
121
});
122
125
- test(".unwrapOr", () => {
123
+ test('.unwrapOr', () => {
124
expect(addMax10(1, 1).unwrapOr(4)).toEqual(2);
125
expect(addMax10(10, 10).unwrapOr(4)).toEqual(4);
126
});
127
130
- test(".unwrapOrElse", () => {
128
+ test('.unwrapOrElse', () => {
129
expect(addMax10(1, 1).unwrapOrElse(() => 4)).toEqual(2);
132
- expect(addMax10(10, 10).unwrapOrElse((s) => s.length)).toEqual(14);
130
+ expect(addMax10(10, 10).unwrapOrElse(s => s.length)).toEqual(14);
131
});
132
135
- test(".unwrapErr", () => {
133
+ test('.unwrapErr', () => {
134
expect(() => {
135
addMax10(1, 1).unwrapErr();
136
}).toThrowErrorMatchingInlineSnapshot(
139
- `"Can't unwrap \`Ok\` to \`Err\`: 2"`
137
+ `"Can't unwrap \`Ok\` to \`Err\`: 2"`,
138
);
141
- expect(addMax10(10, 10).unwrapErr()).toEqual("20 is too high");
139
+ expect(addMax10(10, 10).unwrapErr()).toEqual('20 is too high');
140
expect(() => {
143
- Ok(new CustomDummyError("oops")).unwrapErr();
141
+ Ok(new CustomDummyError('oops')).unwrapErr();
142
}).toThrowErrorMatchingInlineSnapshot(`"oops"`);
143
});
144
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/e2e/constant-prop.e2e.js
+15
-17
@@ -5,17 +5,17 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import * as React from "react";
9
-import { render } from "@testing-library/react";
8
+import * as React from 'react';
9
+import {render} from '@testing-library/react';
10
11
-globalThis.constantValue = "global test value";
11
+globalThis.constantValue = 'global test value';
12
13
-test("literal-constant-propagation", () => {
13
+test('literal-constant-propagation', () => {
14
function Component() {
15
- const x = "test value 1";
15
+ const x = 'test value 1';
16
return <div>{x}</div>;
17
}
18
- const { asFragment, rerender } = render(<Component />);
18
+ const {asFragment, rerender} = render(<Component />);
19
20
expect(asFragment()).toMatchInlineSnapshot(`
21
<DocumentFragment>
@@ -36,13 +36,13 @@ test("literal-constant-propagation", () => {
36
`);
37
});
38
39
-test("global-constant-propagation", () => {
39
+test('global-constant-propagation', () => {
40
function Component() {
41
const x = constantValue;
42
43
return <div>{x}</div>;
44
}
45
- const { asFragment, rerender } = render(<Component />);
45
+ const {asFragment, rerender} = render(<Component />);
46
47
expect(asFragment()).toMatchInlineSnapshot(`
48
<DocumentFragment>
@@ -63,13 +63,13 @@ test("global-constant-propagation", () => {
63
`);
64
});
65
66
-test("lambda-constant-propagation", () => {
66
+test('lambda-constant-propagation', () => {
67
function Component() {
68
- const x = "test value 1";
68
+ const x = 'test value 1';
69
const getDiv = () => <div>{x}</div>;
70
return getDiv();
71
}
72
- const { asFragment, rerender } = render(<Component />);
72
+ const {asFragment, rerender} = render(<Component />);
73
74
expect(asFragment()).toMatchInlineSnapshot(`
75
<DocumentFragment>
@@ -90,9 +90,9 @@ test("lambda-constant-propagation", () => {
90
`);
91
});
92
93
-test("lambda-constant-propagation-of-phi-node", () => {
94
- function Component({ noopCallback }) {
95
- const x = "test value 1";
93
+test('lambda-constant-propagation-of-phi-node', () => {
94
+ function Component({noopCallback}) {
95
+ const x = 'test value 1';
96
if (constantValue) {
97
noopCallback();
98
}
@@ -105,9 +105,7 @@ test("lambda-constant-propagation-of-phi-node", () => {
105
return getDiv();
106
}
107
108
- const { asFragment, rerender } = render(
109
- <Component noopCallback={() => {}} />
110
- );
108
+ const {asFragment, rerender} = render(<Component noopCallback={() => {}} />);
109
110
expect(asFragment()).toMatchInlineSnapshot(`
111
<DocumentFragment>
compiler/packages/babel-plugin-react-compiler/src/__tests__/e2e/hello.e2e.js
+9
-9
@@ -5,12 +5,12 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import * as React from "react";
9
-import { render } from "@testing-library/react";
10
-import { expectLogsAndClear, log } from "./expectLogs";
8
+import * as React from 'react';
9
+import {render} from '@testing-library/react';
10
+import {expectLogsAndClear, log} from './expectLogs';
11
12
-function Hello({ name }) {
13
- const items = [1, 2, 3].map((item) => {
12
+function Hello({name}) {
13
+ const items = [1, 2, 3].map(item => {
14
log(`recomputing ${item}`);
15
return <div key={item}>Item {item}</div>;
16
});
@@ -22,8 +22,8 @@ function Hello({ name }) {
22
);
23
}
24
25
-test("hello", () => {
26
- const { asFragment, rerender } = render(<Hello name="World" />);
25
+test('hello', () => {
26
+ const {asFragment, rerender} = render(<Hello name="World" />);
27
28
expect(asFragment()).toMatchInlineSnapshot(`
29
<DocumentFragment>
@@ -45,7 +45,7 @@ test("hello", () => {
45
</DocumentFragment>
46
`);
47
48
- expectLogsAndClear(["recomputing 1", "recomputing 2", "recomputing 3"]);
48
+ expectLogsAndClear(['recomputing 1', 'recomputing 2', 'recomputing 3']);
49
50
rerender(<Hello name="Universe" />);
51
@@ -70,6 +70,6 @@ test("hello", () => {
70
`);
71
72
expectLogsAndClear(
73
- __FORGET__ ? [] : ["recomputing 1", "recomputing 2", "recomputing 3"]
73
+ __FORGET__ ? [] : ['recomputing 1', 'recomputing 2', 'recomputing 3']
74
);
75
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/e2e/update-button.e2e.js
+8
-8
@@ -5,16 +5,16 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { render } from "@testing-library/react";
9
-import * as React from "react";
8
+import {render} from '@testing-library/react';
9
+import * as React from 'react';
10
11
-function Button({ label }) {
11
+function Button({label}) {
12
const theme = useTheme();
13
const style = computeStyle(theme);
14
return <button color={style}>{label}</button>;
15
}
16
17
-let currentTheme = "light";
17
+let currentTheme = 'light';
18
function useTheme() {
19
return currentTheme;
20
}
@@ -22,11 +22,11 @@ function useTheme() {
22
let styleComputations = 0;
23
function computeStyle(theme) {
24
styleComputations++;
25
- return theme === "light" ? "white" : "black";
25
+ return theme === 'light' ? 'white' : 'black';
26
}
27
28
-test("update-button", () => {
29
- const { asFragment, rerender } = render(<Button label="Click me" />);
28
+test('update-button', () => {
29
+ const {asFragment, rerender} = render(<Button label="Click me" />);
30
expect(asFragment()).toMatchInlineSnapshot(`
31
<DocumentFragment>
32
<button
@@ -51,7 +51,7 @@ test("update-button", () => {
51
</DocumentFragment>
52
`);
53
54
- currentTheme = "dark";
54
+ currentTheme = 'dark';
55
rerender(<Button label="Click again" />);
56
expect(asFragment()).toMatchInlineSnapshot(`
57
<DocumentFragment>
compiler/packages/babel-plugin-react-compiler/src/__tests__/e2e/update-expressions.e2e.js
+5
-5
@@ -5,9 +5,9 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { render, screen, fireEvent } from "@testing-library/react";
9
-import * as React from "react";
10
-import { expectLogsAndClear, log } from "./expectLogs";
8
+import {render, screen, fireEvent} from '@testing-library/react';
9
+import * as React from 'react';
10
+import {expectLogsAndClear, log} from './expectLogs';
11
12
function Counter(props) {
13
let value = props.value;
@@ -27,8 +27,8 @@ function Counter(props) {
27
return <span>{value}</span>;
28
}
29
30
-test("use-state", async () => {
31
- const { asFragment, rerender } = render(<Counter value={0} />);
30
+test('use-state', async () => {
31
+ const {asFragment, rerender} = render(<Counter value={0} />);
32
expect(asFragment()).toMatchInlineSnapshot(`
33
<DocumentFragment>
34
<span>
compiler/packages/babel-plugin-react-compiler/src/__tests__/e2e/use-state.e2e.js
+11
-11
@@ -5,10 +5,10 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { render, screen, fireEvent } from "@testing-library/react";
9
-import * as React from "react";
10
-import { useState } from "react";
11
-import { expectLogsAndClear, log } from "./expectLogs";
8
+import {render, screen, fireEvent} from '@testing-library/react';
9
+import * as React from 'react';
10
+import {useState} from 'react';
11
+import {expectLogsAndClear, log} from './expectLogs';
12
13
function Counter() {
14
let [state, setState] = useState(0);
@@ -23,13 +23,13 @@ function Counter() {
23
);
24
}
25
26
-function Title({ text }) {
26
+function Title({text}) {
27
log(`rendering: ${text}`);
28
return <h1>{text}</h1>;
29
}
30
31
-test("use-state", async () => {
32
- const { asFragment } = render(<Counter />);
31
+test('use-state', async () => {
32
+ const {asFragment} = render(<Counter />);
33
34
expect(asFragment()).toMatchInlineSnapshot(`
35
<DocumentFragment>
@@ -49,10 +49,10 @@ test("use-state", async () => {
49
</DocumentFragment>
50
`);
51
52
- expectLogsAndClear(["rendering: Counter"]);
52
+ expectLogsAndClear(['rendering: Counter']);
53
54
- fireEvent.click(screen.getByTestId("button"));
55
- await screen.findByText("1");
54
+ fireEvent.click(screen.getByTestId('button'));
55
+ await screen.findByText('1');
56
57
- expectLogsAndClear(__FORGET__ ? [] : ["rendering: Counter"]);
57
+ expectLogsAndClear(__FORGET__ ? [] : ['rendering: Counter']);
58
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/envConfig-test.ts
+11
-11
@@ -5,35 +5,35 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { Effect, validateEnvironmentConfig } from "..";
9
-import { ValueKind } from "../HIR";
8
+import {Effect, validateEnvironmentConfig} from '..';
9
+import {ValueKind} from '../HIR';
10
11
-describe("parseConfigPragma()", () => {
12
- it("passing null throws", () => {
11
+describe('parseConfigPragma()', () => {
12
+ it('passing null throws', () => {
13
expect(() => validateEnvironmentConfig(null as any)).toThrow();
14
});
15
16
// tests that the error message remains useful
17
- it("passing incorrect value throws", () => {
17
+ it('passing incorrect value throws', () => {
18
expect(() => {
19
validateEnvironmentConfig({
20
validateHooksUsage: 1,
21
} as any);
22
}).toThrowErrorMatchingInlineSnapshot(
23
- `"InvalidConfig: Could not validate environment config. Update React Compiler config to fix the error. Validation error: Expected boolean, received number at "validateHooksUsage""`
23
+ `"InvalidConfig: Could not validate environment config. Update React Compiler config to fix the error. Validation error: Expected boolean, received number at "validateHooksUsage""`,
24
);
25
});
26
27
- it("can parse stringy enums", () => {
27
+ it('can parse stringy enums', () => {
28
const stringyHook = {
29
- effectKind: "freeze",
30
- valueKind: "frozen",
29
+ effectKind: 'freeze',
30
+ valueKind: 'frozen',
31
};
32
const env = {
33
- customHooks: new Map([["useFoo", stringyHook]]),
33
+ customHooks: new Map([['useFoo', stringyHook]]),
34
};
35
const validatedEnv = validateEnvironmentConfig(env as any);
36
- const validatedHook = validatedEnv.customHooks.get("useFoo");
36
+ const validatedHook = validatedEnv.customHooks.get('useFoo');
37
expect(validatedHook?.effectKind).toBe(Effect.Freeze);
38
expect(validatedHook?.valueKind).toBe(ValueKind.Frozen);
39
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/alias-capture-in-method-receiver-and-mutate.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeObject_Primitives, mutate } from "shared-runtime";
5
+import {makeObject_Primitives, mutate} from 'shared-runtime';
6
7
function Component() {
8
// a's mutable range should be the same as x's mutable range,
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/alias-capture-in-method-receiver-and-mutate.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { makeObject_Primitives, mutate } from "shared-runtime";
1
+import {makeObject_Primitives, mutate} from 'shared-runtime';
2
3
function Component() {
4
// a's mutable range should be the same as x's mutable range,
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/alias-computed-load.expect.md
+2
-2
@@ -3,10 +3,10 @@
3
4
```javascript
5
function component(a) {
6
- let x = { a };
6
+ let x = {a};
7
let y = {};
8
9
- y.x = x["a"];
9
+ y.x = x['a'];
10
mutate(y);
11
return x;
12
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/alias-computed-load.js
+2
-2
@@ -1,8 +1,8 @@
1
function component(a) {
2
- let x = { a };
2
+ let x = {a};
3
let y = {};
4
5
- y.x = x["a"];
5
+ y.x = x['a'];
6
mutate(y);
7
return x;
8
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scope-starts-within-cond.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { mutate } from "shared-runtime";
5
+import {mutate} from 'shared-runtime';
6
7
/**
8
* Similar fixture to `align-scopes-nested-block-structure`, but
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scope-starts-within-cond.ts
+1
-1
@@ -1,4 +1,4 @@
1
-import { mutate } from "shared-runtime";
1
+import {mutate} from 'shared-runtime';
2
3
/**
4
* Similar fixture to `align-scopes-nested-block-structure`, but
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-iife-return-modified-later-logical.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { getNull } from "shared-runtime";
5
+import {getNull} from 'shared-runtime';
6
7
function Component(props) {
8
const items = (() => {
@@ -14,7 +14,7 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ a: {} }],
17
+ params: [{a: {}}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-iife-return-modified-later-logical.ts
+2
-2
@@ -1,4 +1,4 @@
1
-import { getNull } from "shared-runtime";
1
+import {getNull} from 'shared-runtime';
2
3
function Component(props) {
4
const items = (() => {
@@ -10,5 +10,5 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ a: {} }],
13
+ params: [{a: {}}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-nested-block-structure.expect.md
+8
-8
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { mutate } from "shared-runtime";
5
+import {mutate} from 'shared-runtime';
6
/**
7
* Fixture showing that it's not sufficient to only align direct scoped
8
* accesses of a block-fallthrough pair.
@@ -42,7 +42,7 @@ import { mutate } from "shared-runtime";
42
* │return s; │◄──┘
43
* └───────────┘
44
*/
45
-function useFoo({ cond1, cond2 }) {
45
+function useFoo({cond1, cond2}) {
46
let s = null;
47
if (cond1) {
48
s = {};
@@ -59,13 +59,13 @@ function useFoo({ cond1, cond2 }) {
59
60
export const FIXTURE_ENTRYPOINT = {
61
fn: useFoo,
62
- params: [{ cond1: true, cond2: false }],
62
+ params: [{cond1: true, cond2: false}],
63
sequentialRenders: [
64
- { cond1: true, cond2: false },
65
- { cond1: true, cond2: false },
66
- { cond1: true, cond2: true },
67
- { cond1: true, cond2: true },
68
- { cond1: false, cond2: true },
64
+ {cond1: true, cond2: false},
65
+ {cond1: true, cond2: false},
66
+ {cond1: true, cond2: true},
67
+ {cond1: true, cond2: true},
68
+ {cond1: false, cond2: true},
69
],
70
};
71
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-nested-block-structure.ts
+8
-8
@@ -1,4 +1,4 @@
1
-import { mutate } from "shared-runtime";
1
+import {mutate} from 'shared-runtime';
2
/**
3
* Fixture showing that it's not sufficient to only align direct scoped
4
* accesses of a block-fallthrough pair.
@@ -38,7 +38,7 @@ import { mutate } from "shared-runtime";
38
* │return s; │◄──┘
39
* └───────────┘
40
*/
41
-function useFoo({ cond1, cond2 }) {
41
+function useFoo({cond1, cond2}) {
42
let s = null;
43
if (cond1) {
44
s = {};
@@ -55,12 +55,12 @@ function useFoo({ cond1, cond2 }) {
55
56
export const FIXTURE_ENTRYPOINT = {
57
fn: useFoo,
58
- params: [{ cond1: true, cond2: false }],
58
+ params: [{cond1: true, cond2: false}],
59
sequentialRenders: [
60
- { cond1: true, cond2: false },
61
- { cond1: true, cond2: false },
62
- { cond1: true, cond2: true },
63
- { cond1: true, cond2: true },
64
- { cond1: false, cond2: true },
60
+ {cond1: true, cond2: false},
61
+ {cond1: true, cond2: false},
62
+ {cond1: true, cond2: true},
63
+ {cond1: true, cond2: true},
64
+ {cond1: false, cond2: true},
65
],
66
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-reactive-scope-overlaps-if.expect.md
+7
-7
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function useFoo({ cond }) {
5
+function useFoo({cond}) {
6
let items: any = {};
7
b0: {
8
if (cond) {
@@ -19,13 +19,13 @@ function useFoo({ cond }) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: useFoo,
22
- params: [{ cond: true }],
22
+ params: [{cond: true}],
23
sequentialRenders: [
24
- { cond: true },
25
- { cond: true },
26
- { cond: false },
27
- { cond: false },
28
- { cond: true },
24
+ {cond: true},
25
+ {cond: true},
26
+ {cond: false},
27
+ {cond: false},
28
+ {cond: true},
29
],
30
};
31
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-reactive-scope-overlaps-if.ts
+7
-7
@@ -1,4 +1,4 @@
1
-function useFoo({ cond }) {
1
+function useFoo({cond}) {
2
let items: any = {};
3
b0: {
4
if (cond) {
@@ -15,12 +15,12 @@ function useFoo({ cond }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: useFoo,
18
- params: [{ cond: true }],
18
+ params: [{cond: true}],
19
sequentialRenders: [
20
- { cond: true },
21
- { cond: true },
22
- { cond: false },
23
- { cond: false },
24
- { cond: true },
20
+ {cond: true},
21
+ {cond: true},
22
+ {cond: false},
23
+ {cond: false},
24
+ {cond: true},
25
],
26
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-reactive-scope-overlaps-label.expect.md
+7
-7
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { arrayPush } from "shared-runtime";
5
+import {arrayPush} from 'shared-runtime';
6
7
-function useFoo({ cond, value }) {
7
+function useFoo({cond, value}) {
8
let items;
9
label: {
10
items = [];
@@ -19,12 +19,12 @@ function useFoo({ cond, value }) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: useFoo,
22
- params: [{ cond: true, value: 2 }],
22
+ params: [{cond: true, value: 2}],
23
sequentialRenders: [
24
- { cond: true, value: 2 },
25
- { cond: true, value: 2 },
26
- { cond: true, value: 3 },
27
- { cond: false, value: 3 },
24
+ {cond: true, value: 2},
25
+ {cond: true, value: 2},
26
+ {cond: true, value: 3},
27
+ {cond: false, value: 3},
28
],
29
};
30
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-reactive-scope-overlaps-label.ts
+7
-7
@@ -1,6 +1,6 @@
1
-import { arrayPush } from "shared-runtime";
1
+import {arrayPush} from 'shared-runtime';
2
3
-function useFoo({ cond, value }) {
3
+function useFoo({cond, value}) {
4
let items;
5
label: {
6
items = [];
@@ -15,11 +15,11 @@ function useFoo({ cond, value }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: useFoo,
18
- params: [{ cond: true, value: 2 }],
18
+ params: [{cond: true, value: 2}],
19
sequentialRenders: [
20
- { cond: true, value: 2 },
21
- { cond: true, value: 2 },
22
- { cond: true, value: 3 },
23
- { cond: false, value: 3 },
20
+ {cond: true, value: 2},
21
+ {cond: true, value: 2},
22
+ {cond: true, value: 3},
23
+ {cond: false, value: 3},
24
],
25
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-reactive-scope-overlaps-try.expect.md
+4
-4
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { arrayPush, mutate } from "shared-runtime";
5
+import {arrayPush, mutate} from 'shared-runtime';
6
7
-function useFoo({ value }) {
7
+function useFoo({value}) {
8
let items = null;
9
try {
10
// Mutable range of `items` begins here, but its reactive scope block
@@ -20,8 +20,8 @@ function useFoo({ value }) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: useFoo,
23
- params: [{ value: 2 }],
24
- sequentialRenders: [{ value: 2 }, { value: 2 }, { value: 3 }],
23
+ params: [{value: 2}],
24
+ sequentialRenders: [{value: 2}, {value: 2}, {value: 3}],
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-reactive-scope-overlaps-try.ts
+4
-4
@@ -1,6 +1,6 @@
1
-import { arrayPush, mutate } from "shared-runtime";
1
+import {arrayPush, mutate} from 'shared-runtime';
2
3
-function useFoo({ value }) {
3
+function useFoo({value}) {
4
let items = null;
5
try {
6
// Mutable range of `items` begins here, but its reactive scope block
@@ -16,6 +16,6 @@ function useFoo({ value }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: useFoo,
19
- params: [{ value: 2 }],
20
- sequentialRenders: [{ value: 2 }, { value: 2 }, { value: 3 }],
19
+ params: [{value: 2}],
20
+ sequentialRenders: [{value: 2}, {value: 2}, {value: 3}],
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-trycatch-nested-overlapping-range.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { CONST_TRUE, makeObject_Primitives } from "shared-runtime";
5
+import {CONST_TRUE, makeObject_Primitives} from 'shared-runtime';
6
7
function Foo() {
8
try {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-trycatch-nested-overlapping-range.ts
+1
-1
@@ -1,4 +1,4 @@
1
-import { CONST_TRUE, makeObject_Primitives } from "shared-runtime";
1
+import {CONST_TRUE, makeObject_Primitives} from 'shared-runtime';
2
3
function Foo() {
4
try {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-within-nested-valueblock-in-array.expect.md
+5
-5
@@ -4,7 +4,7 @@
4
```javascript
5
// @enableReactiveScopesInHIR:false
6
7
-import { Stringify, identity, makeArray, mutate } from "shared-runtime";
7
+import {Stringify, identity, makeArray, mutate} from 'shared-runtime';
8
9
/**
10
* Here, identity('foo') is an immutable allocating instruction.
@@ -16,12 +16,12 @@ import { Stringify, identity, makeArray, mutate } from "shared-runtime";
16
* (e.g. `cond1 ? <>: null`). The HIR version of alignScopesToBlocks
17
* handles this correctly.
18
*/
19
-function Foo({ cond1, cond2 }) {
20
- const arr = makeArray<any>({ a: 2 }, 2, []);
19
+function Foo({cond1, cond2}) {
20
+ const arr = makeArray<any>({a: 2}, 2, []);
21
22
return cond1 ? (
23
<>
24
- <div>{identity("foo")}</div>
24
+ <div>{identity('foo')}</div>
25
<Stringify value={cond2 ? arr.map(mutate) : null} />
26
</>
27
) : null;
@@ -29,7 +29,7 @@ function Foo({ cond1, cond2 }) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: Foo,
32
- params: [{ cond1: true, cond2: true }],
32
+ params: [{cond1: true, cond2: true}],
33
};
34
35
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/align-scopes-within-nested-valueblock-in-array.tsx
+5
-5
@@ -1,6 +1,6 @@
1
// @enableReactiveScopesInHIR:false
2
3
-import { Stringify, identity, makeArray, mutate } from "shared-runtime";
3
+import {Stringify, identity, makeArray, mutate} from 'shared-runtime';
4
5
/**
6
* Here, identity('foo') is an immutable allocating instruction.
@@ -12,12 +12,12 @@ import { Stringify, identity, makeArray, mutate } from "shared-runtime";
12
* (e.g. `cond1 ? <>: null`). The HIR version of alignScopesToBlocks
13
* handles this correctly.
14
*/
15
-function Foo({ cond1, cond2 }) {
16
- const arr = makeArray<any>({ a: 2 }, 2, []);
15
+function Foo({cond1, cond2}) {
16
+ const arr = makeArray<any>({a: 2}, 2, []);
17
18
return cond1 ? (
19
<>
20
- <div>{identity("foo")}</div>
20
+ <div>{identity('foo')}</div>
21
<Stringify value={cond2 ? arr.map(mutate) : null} />
22
</>
23
) : null;
@@ -25,5 +25,5 @@ function Foo({ cond1, cond2 }) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Foo,
28
- params: [{ cond1: true, cond2: true }],
28
+ params: [{cond1: true, cond2: true}],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allocating-logical-expression-instruction-scope.expect.md
+2
-2
@@ -7,11 +7,11 @@
7
* The only scoped value we currently infer in this program is the
8
* PropertyLoad `data?.toString`.
9
*/
10
-import { useFragment } from "shared-runtime";
10
+import {useFragment} from 'shared-runtime';
11
12
function Foo() {
13
const data = useFragment();
14
- return [data?.toString() || ""];
14
+ return [data?.toString() || ''];
15
}
16
17
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allocating-logical-expression-instruction-scope.ts
+2
-2
@@ -3,11 +3,11 @@
3
* The only scoped value we currently infer in this program is the
4
* PropertyLoad `data?.toString`.
5
*/
6
-import { useFragment } from "shared-runtime";
6
+import {useFragment} from 'shared-runtime';
7
8
function Foo() {
9
const data = useFragment();
10
- return [data?.toString() || ""];
10
+ return [data?.toString() || ''];
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allocating-primitive-as-dep-nested-scope.expect.md
+6
-6
@@ -6,7 +6,7 @@
6
// that Forget should memoize it.
7
// Correctness:
8
9
-import { identity, mutate, setProperty } from "shared-runtime";
9
+import {identity, mutate, setProperty} from 'shared-runtime';
10
11
// - y depends on either bar(props.b) or bar(props.b) + 1
12
function AllocatingPrimitiveAsDepNested(props) {
@@ -19,16 +19,16 @@ function AllocatingPrimitiveAsDepNested(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: AllocatingPrimitiveAsDepNested,
22
- params: [{ a: 1, b: 2 }],
22
+ params: [{a: 1, b: 2}],
23
sequentialRenders: [
24
// change b
25
- { a: 1, b: 3 },
25
+ {a: 1, b: 3},
26
// change b
27
- { a: 1, b: 4 },
27
+ {a: 1, b: 4},
28
// change a
29
- { a: 2, b: 4 },
29
+ {a: 2, b: 4},
30
// change a
31
- { a: 3, b: 4 },
31
+ {a: 3, b: 4},
32
],
33
};
34
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allocating-primitive-as-dep-nested-scope.js
+6
-6
@@ -2,7 +2,7 @@
2
// that Forget should memoize it.
3
// Correctness:
4
5
-import { identity, mutate, setProperty } from "shared-runtime";
5
+import {identity, mutate, setProperty} from 'shared-runtime';
6
7
// - y depends on either bar(props.b) or bar(props.b) + 1
8
function AllocatingPrimitiveAsDepNested(props) {
@@ -15,15 +15,15 @@ function AllocatingPrimitiveAsDepNested(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: AllocatingPrimitiveAsDepNested,
18
- params: [{ a: 1, b: 2 }],
18
+ params: [{a: 1, b: 2}],
19
sequentialRenders: [
20
// change b
21
- { a: 1, b: 3 },
21
+ {a: 1, b: 3},
22
// change b
23
- { a: 1, b: 4 },
23
+ {a: 1, b: 4},
24
// change a
25
- { a: 2, b: 4 },
25
+ {a: 2, b: 4},
26
// change a
27
- { a: 3, b: 4 },
27
+ {a: 3, b: 4},
28
],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-global-mutation-in-effect-indirect-usecallback.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useCallback, useEffect, useState } from "react";
6
+import {useCallback, useEffect, useState} from 'react';
7
8
let someGlobal = {};
9
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-global-mutation-in-effect-indirect-usecallback.js
+1
-1
@@ -1,5 +1,5 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useCallback, useEffect, useState } from "react";
2
+import {useCallback, useEffect, useState} from 'react';
3
4
let someGlobal = {};
5
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-global-mutation-in-effect-indirect.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useEffect, useState } from "react";
5
+import {useEffect, useState} from 'react';
6
7
let someGlobal = {};
8
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-global-mutation-in-effect-indirect.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { useEffect, useState } from "react";
1
+import {useEffect, useState} from 'react';
2
3
let someGlobal = {};
4
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-global-mutation-unused-usecallback.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useCallback, useEffect, useState } from "react";
5
+import {useCallback, useEffect, useState} from 'react';
6
7
function Component() {
8
const callback = useCallback(() => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-global-mutation-unused-usecallback.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { useCallback, useEffect, useState } from "react";
1
+import {useCallback, useEffect, useState} from 'react';
2
3
function Component() {
4
const callback = useCallback(() => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-global-reassignment-in-effect-indirect.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useEffect, useState } from "react";
5
+import {useEffect, useState} from 'react';
6
7
let someGlobal = false;
8
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-global-reassignment-in-effect-indirect.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { useEffect, useState } from "react";
1
+import {useEffect, useState} from 'react';
2
3
let someGlobal = false;
4
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-global-reassignment-in-effect.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useEffect, useState } from "react";
5
+import {useEffect, useState} from 'react';
6
7
let someGlobal = false;
8
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-global-reassignment-in-effect.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { useEffect, useState } from "react";
1
+import {useEffect, useState} from 'react';
2
3
let someGlobal = false;
4
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-modify-global-in-callback-jsx.expect.md
+9
-9
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-import { useMemo } from "react";
5
+import {useMemo} from 'react';
6
7
-const someGlobal = { value: 0 };
7
+const someGlobal = {value: 0};
8
9
-function Component({ value }) {
9
+function Component({value}) {
10
const onClick = () => {
11
someGlobal.value = value;
12
};
@@ -17,13 +17,13 @@ function Component({ value }) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ value: 0 }],
20
+ params: [{value: 0}],
21
sequentialRenders: [
22
- { value: 1 },
23
- { value: 1 },
24
- { value: 42 },
25
- { value: 42 },
26
- { value: 0 },
22
+ {value: 1},
23
+ {value: 1},
24
+ {value: 42},
25
+ {value: 42},
26
+ {value: 0},
27
],
28
};
29
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-modify-global-in-callback-jsx.js
+9
-9
@@ -1,8 +1,8 @@
1
-import { useMemo } from "react";
1
+import {useMemo} from 'react';
2
3
-const someGlobal = { value: 0 };
3
+const someGlobal = {value: 0};
4
5
-function Component({ value }) {
5
+function Component({value}) {
6
const onClick = () => {
7
someGlobal.value = value;
8
};
@@ -13,12 +13,12 @@ function Component({ value }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ value: 0 }],
16
+ params: [{value: 0}],
17
sequentialRenders: [
18
- { value: 1 },
19
- { value: 1 },
20
- { value: 42 },
21
- { value: 42 },
22
- { value: 0 },
18
+ {value: 1},
19
+ {value: 1},
20
+ {value: 42},
21
+ {value: 42},
22
+ {value: 0},
23
],
24
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-mutate-global-in-effect-fixpoint.expect.md
+3
-3
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { useEffect, useState } from "react";
5
+import {useEffect, useState} from 'react';
6
7
-let someGlobal = { value: null };
7
+let someGlobal = {value: null};
8
9
function Component() {
10
const [state, setState] = useState(someGlobal);
@@ -20,7 +20,7 @@ function Component() {
20
// capture into a separate variable that is not a context variable.
21
const y = x;
22
useEffect(() => {
23
- y.value = "hello";
23
+ y.value = 'hello';
24
}, []);
25
26
useEffect(() => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-mutate-global-in-effect-fixpoint.js
+3
-3
@@ -1,6 +1,6 @@
1
-import { useEffect, useState } from "react";
1
+import {useEffect, useState} from 'react';
2
3
-let someGlobal = { value: null };
3
+let someGlobal = {value: null};
4
5
function Component() {
6
const [state, setState] = useState(someGlobal);
@@ -16,7 +16,7 @@ function Component() {
16
// capture into a separate variable that is not a context variable.
17
const y = x;
18
useEffect(() => {
19
- y.value = "hello";
19
+ y.value = 'hello';
20
}, []);
21
22
useEffect(() => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-mutating-ref-in-callback-passed-to-jsx-indirect.expect.md
+2
-2
@@ -3,14 +3,14 @@
3
4
```javascript
5
// @validateRefAccessDuringRender
6
-import { useRef } from "react";
6
+import {useRef} from 'react';
7
8
function Component() {
9
const ref = useRef(null);
10
11
const setRef = () => {
12
if (ref.current !== null) {
13
- ref.current = "";
13
+ ref.current = '';
14
}
15
};
16
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-mutating-ref-in-callback-passed-to-jsx-indirect.tsx
+2
-2
@@ -1,12 +1,12 @@
1
// @validateRefAccessDuringRender
2
-import { useRef } from "react";
2
+import {useRef} from 'react';
3
4
function Component() {
5
const ref = useRef(null);
6
7
const setRef = () => {
8
if (ref.current !== null) {
9
- ref.current = "";
9
+ ref.current = '';
10
}
11
};
12
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-mutating-ref-in-callback-passed-to-jsx.expect.md
+2
-2
@@ -3,14 +3,14 @@
3
4
```javascript
5
// @validateRefAccessDuringRender
6
-import { useRef } from "react";
6
+import {useRef} from 'react';
7
8
function Component() {
9
const ref = useRef(null);
10
11
const onClick = () => {
12
if (ref.current !== null) {
13
- ref.current = "";
13
+ ref.current = '';
14
}
15
};
16
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-mutating-ref-in-callback-passed-to-jsx.tsx
+2
-2
@@ -1,12 +1,12 @@
1
// @validateRefAccessDuringRender
2
-import { useRef } from "react";
2
+import {useRef} from 'react';
3
4
function Component() {
5
const ref = useRef(null);
6
7
const onClick = () => {
8
if (ref.current !== null) {
9
- ref.current = "";
9
+ ref.current = '';
10
}
11
};
12
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-mutating-ref-property-in-callback-passed-to-jsx-indirect.expect.md
+2
-2
@@ -3,14 +3,14 @@
3
4
```javascript
5
// @validateRefAccessDuringRender
6
-import { useRef } from "react";
6
+import {useRef} from 'react';
7
8
function Component() {
9
const ref = useRef(null);
10
11
const setRef = () => {
12
if (ref.current !== null) {
13
- ref.current.value = "";
13
+ ref.current.value = '';
14
}
15
};
16
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-mutating-ref-property-in-callback-passed-to-jsx-indirect.tsx
+2
-2
@@ -1,12 +1,12 @@
1
// @validateRefAccessDuringRender
2
-import { useRef } from "react";
2
+import {useRef} from 'react';
3
4
function Component() {
5
const ref = useRef(null);
6
7
const setRef = () => {
8
if (ref.current !== null) {
9
- ref.current.value = "";
9
+ ref.current.value = '';
10
}
11
};
12
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-mutating-ref-property-in-callback-passed-to-jsx.expect.md
+2
-2
@@ -3,14 +3,14 @@
3
4
```javascript
5
// @validateRefAccessDuringRender
6
-import { useRef } from "react";
6
+import {useRef} from 'react';
7
8
function Component() {
9
const ref = useRef(null);
10
11
const onClick = () => {
12
if (ref.current !== null) {
13
- ref.current.value = "";
13
+ ref.current.value = '';
14
}
15
};
16
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-mutating-ref-property-in-callback-passed-to-jsx.tsx
+2
-2
@@ -1,12 +1,12 @@
1
// @validateRefAccessDuringRender
2
-import { useRef } from "react";
2
+import {useRef} from 'react';
3
4
function Component() {
5
const ref = useRef(null);
6
7
const onClick = () => {
8
if (ref.current !== null) {
9
- ref.current.value = "";
9
+ ref.current.value = '';
10
}
11
};
12
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-ref-access-in-effect-indirect.expect.md
+3
-3
@@ -3,13 +3,13 @@
3
4
```javascript
5
// @validateRefAccessDuringRender
6
-import { useCallback, useEffect, useRef, useState } from "react";
6
+import {useCallback, useEffect, useRef, useState} from 'react';
7
8
function Component() {
9
const ref = useRef(null);
10
const [state, setState] = useState(false);
11
const setRef = useCallback(() => {
12
- ref.current = "Ok";
12
+ ref.current = 'Ok';
13
}, []);
14
15
useEffect(() => {
@@ -26,7 +26,7 @@ function Component() {
26
return <Child key={String(state)} ref={ref} />;
27
}
28
29
-function Child({ ref }) {
29
+function Child({ref}) {
30
// This violates the rules of React, so we access the ref in a child
31
// component
32
return ref.current;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-ref-access-in-effect-indirect.js
+3
-3
@@ -1,11 +1,11 @@
1
// @validateRefAccessDuringRender
2
-import { useCallback, useEffect, useRef, useState } from "react";
2
+import {useCallback, useEffect, useRef, useState} from 'react';
3
4
function Component() {
5
const ref = useRef(null);
6
const [state, setState] = useState(false);
7
const setRef = useCallback(() => {
8
- ref.current = "Ok";
8
+ ref.current = 'Ok';
9
}, []);
10
11
useEffect(() => {
@@ -22,7 +22,7 @@ function Component() {
22
return <Child key={String(state)} ref={ref} />;
23
}
24
25
-function Child({ ref }) {
25
+function Child({ref}) {
26
// This violates the rules of React, so we access the ref in a child
27
// component
28
return ref.current;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-ref-access-in-effect.expect.md
+3
-3
@@ -3,13 +3,13 @@
3
4
```javascript
5
// @validateRefAccessDuringRender
6
-import { useEffect, useRef, useState } from "react";
6
+import {useEffect, useRef, useState} from 'react';
7
8
function Component() {
9
const ref = useRef(null);
10
const [state, setState] = useState(false);
11
useEffect(() => {
12
- ref.current = "Ok";
12
+ ref.current = 'Ok';
13
}, []);
14
15
useEffect(() => {
@@ -22,7 +22,7 @@ function Component() {
22
return <Child key={String(state)} ref={ref} />;
23
}
24
25
-function Child({ ref }) {
25
+function Child({ref}) {
26
// This violates the rules of React, so we access the ref in a child
27
// component
28
return ref.current;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-ref-access-in-effect.js
+3
-3
@@ -1,11 +1,11 @@
1
// @validateRefAccessDuringRender
2
-import { useEffect, useRef, useState } from "react";
2
+import {useEffect, useRef, useState} from 'react';
3
4
function Component() {
5
const ref = useRef(null);
6
const [state, setState] = useState(false);
7
useEffect(() => {
8
- ref.current = "Ok";
8
+ ref.current = 'Ok';
9
}, []);
10
11
useEffect(() => {
@@ -18,7 +18,7 @@ function Component() {
18
return <Child key={String(state)} ref={ref} />;
19
}
20
21
-function Child({ ref }) {
21
+function Child({ref}) {
22
// This violates the rules of React, so we access the ref in a child
23
// component
24
return ref.current;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-ref-access-in-unused-callback-nested.expect.md
+3
-3
@@ -3,14 +3,14 @@
3
4
```javascript
5
// @validateRefAccessDuringRender
6
-import { useEffect, useRef, useState } from "react";
6
+import {useEffect, useRef, useState} from 'react';
7
8
function Component() {
9
const ref = useRef(null);
10
const [state, setState] = useState(false);
11
useEffect(() => {
12
const callback = () => {
13
- ref.current = "Ok";
13
+ ref.current = 'Ok';
14
};
15
}, []);
16
@@ -24,7 +24,7 @@ function Component() {
24
return <Child key={String(state)} ref={ref} />;
25
}
26
27
-function Child({ ref }) {
27
+function Child({ref}) {
28
// This violates the rules of React, so we access the ref in a child
29
// component
30
return ref.current;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/allow-ref-access-in-unused-callback-nested.js
+3
-3
@@ -1,12 +1,12 @@
1
// @validateRefAccessDuringRender
2
-import { useEffect, useRef, useState } from "react";
2
+import {useEffect, useRef, useState} from 'react';
3
4
function Component() {
5
const ref = useRef(null);
6
const [state, setState] = useState(false);
7
useEffect(() => {
8
const callback = () => {
9
- ref.current = "Ok";
9
+ ref.current = 'Ok';
10
};
11
}, []);
12
@@ -20,7 +20,7 @@ function Component() {
20
return <Child key={String(state)} ref={ref} />;
21
}
22
23
-function Child({ ref }) {
23
+function Child({ref}) {
24
// This violates the rules of React, so we access the ref in a child
25
// component
26
return ref.current;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-access-assignment.expect.md
+7
-7
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function Component({ a, b, c }) {
5
+function Component({a, b, c}) {
6
const x = [a];
7
const y = [null, b];
8
const z = [[], [], [c]];
@@ -13,13 +13,13 @@ function Component({ a, b, c }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ a: 1, b: 20, c: 300 }],
16
+ params: [{a: 1, b: 20, c: 300}],
17
sequentialRenders: [
18
- { a: 2, b: 20, c: 300 },
19
- { a: 3, b: 20, c: 300 },
20
- { a: 3, b: 21, c: 300 },
21
- { a: 3, b: 22, c: 300 },
22
- { a: 3, b: 22, c: 301 },
18
+ {a: 2, b: 20, c: 300},
19
+ {a: 3, b: 20, c: 300},
20
+ {a: 3, b: 21, c: 300},
21
+ {a: 3, b: 22, c: 300},
22
+ {a: 3, b: 22, c: 301},
23
],
24
};
25
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-access-assignment.js
+7
-7
@@ -1,4 +1,4 @@
1
-function Component({ a, b, c }) {
1
+function Component({a, b, c}) {
2
const x = [a];
3
const y = [null, b];
4
const z = [[], [], [c]];
@@ -9,12 +9,12 @@ function Component({ a, b, c }) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: [{ a: 1, b: 20, c: 300 }],
12
+ params: [{a: 1, b: 20, c: 300}],
13
sequentialRenders: [
14
- { a: 2, b: 20, c: 300 },
15
- { a: 3, b: 20, c: 300 },
16
- { a: 3, b: 21, c: 300 },
17
- { a: 3, b: 22, c: 300 },
18
- { a: 3, b: 22, c: 301 },
14
+ {a: 2, b: 20, c: 300},
15
+ {a: 3, b: 20, c: 300},
16
+ {a: 3, b: 21, c: 300},
17
+ {a: 3, b: 22, c: 300},
18
+ {a: 3, b: 22, c: 301},
19
],
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-concat-should-capture.expect.md
+5
-5
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { mutate } from "shared-runtime";
5
+import {mutate} from 'shared-runtime';
6
7
/**
8
* Fixture showing why `concat` needs to capture both the callee and rest args.
@@ -11,8 +11,8 @@ import { mutate } from "shared-runtime";
11
* - Observe that it's technically valid to separately memoize the array arr1
12
* itself.
13
*/
14
-function Foo({ inputNum }) {
15
- const arr1: Array<number | object> = [{ a: 1 }, {}];
14
+function Foo({inputNum}) {
15
+ const arr1: Array<number | object> = [{a: 1}, {}];
16
const arr2 = arr1.concat([1, inputNum]);
17
mutate(arr2[0]);
18
return arr2;
@@ -20,8 +20,8 @@ function Foo({ inputNum }) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: Foo,
23
- params: [{ inputNum: 2 }],
24
- sequentialRenders: [{ inputNum: 2 }, { inputNum: 3 }],
23
+ params: [{inputNum: 2}],
24
+ sequentialRenders: [{inputNum: 2}, {inputNum: 3}],
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-concat-should-capture.ts
+5
-5
@@ -1,4 +1,4 @@
1
-import { mutate } from "shared-runtime";
1
+import {mutate} from 'shared-runtime';
2
3
/**
4
* Fixture showing why `concat` needs to capture both the callee and rest args.
@@ -7,8 +7,8 @@ import { mutate } from "shared-runtime";
7
* - Observe that it's technically valid to separately memoize the array arr1
8
* itself.
9
*/
10
-function Foo({ inputNum }) {
11
- const arr1: Array<number | object> = [{ a: 1 }, {}];
10
+function Foo({inputNum}) {
11
+ const arr1: Array<number | object> = [{a: 1}, {}];
12
const arr2 = arr1.concat([1, inputNum]);
13
mutate(arr2[0]);
14
return arr2;
@@ -16,6 +16,6 @@ function Foo({ inputNum }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Foo,
19
- params: [{ inputNum: 2 }],
20
- sequentialRenders: [{ inputNum: 2 }, { inputNum: 3 }],
19
+ params: [{inputNum: 2}],
20
+ sequentialRenders: [{inputNum: 2}, {inputNum: 3}],
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-expression-spread.expect.md
+2
-2
@@ -3,13 +3,13 @@
3
4
```javascript
5
function Component(props) {
6
- const x = [0, ...props.foo, null, ...props.bar, "z"];
6
+ const x = [0, ...props.foo, null, ...props.bar, 'z'];
7
return x;
8
}
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: [{ foo: [1, 2, 3], bar: [4, 5, 6] }],
12
+ params: [{foo: [1, 2, 3], bar: [4, 5, 6]}],
13
isComponent: false,
14
};
15
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-expression-spread.js
+2
-2
@@ -1,10 +1,10 @@
1
function Component(props) {
2
- const x = [0, ...props.foo, null, ...props.bar, "z"];
2
+ const x = [0, ...props.foo, null, ...props.bar, 'z'];
3
return x;
4
}
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: Component,
8
- params: [{ foo: [1, 2, 3], bar: [4, 5, 6] }],
8
+ params: [{foo: [1, 2, 3], bar: [4, 5, 6]}],
9
isComponent: false,
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-join.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
function Component(props) {
6
const x = [{}, [], props.value];
7
- const y = x.join(() => "this closure gets stringified, not called");
7
+ const y = x.join(() => 'this closure gets stringified, not called');
8
foo(y);
9
return [x, y];
10
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-join.js
+1
-1
@@ -1,6 +1,6 @@
1
function Component(props) {
2
const x = [{}, [], props.value];
3
- const y = x.join(() => "this closure gets stringified, not called");
3
+ const y = x.join(() => 'this closure gets stringified, not called');
4
foo(y);
5
return [x, y];
6
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-captures-receiver-noAlias.expect.md
+3
-3
@@ -4,15 +4,15 @@
4
```javascript
5
function Component(props) {
6
// This item is part of the receiver, should be memoized
7
- const item = { a: props.a };
7
+ const item = {a: props.a};
8
const items = [item];
9
- const mapped = items.map((item) => item);
9
+ const mapped = items.map(item => item);
10
return mapped;
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ a: { id: 42 } }],
15
+ params: [{a: {id: 42}}],
16
isComponent: false,
17
};
18
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-captures-receiver-noAlias.js
+3
-3
@@ -1,13 +1,13 @@
1
function Component(props) {
2
// This item is part of the receiver, should be memoized
3
- const item = { a: props.a };
3
+ const item = {a: props.a};
4
const items = [item];
5
- const mapped = items.map((item) => item);
5
+ const mapped = items.map(item => item);
6
return mapped;
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: [{ a: { id: 42 } }],
11
+ params: [{a: {id: 42}}],
12
isComponent: false,
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-frozen-array-noAlias.expect.md
+1
-1
@@ -5,7 +5,7 @@
5
function Component(props) {
6
const x = [];
7
<dif>{x}</dif>;
8
- const y = x.map((item) => item);
8
+ const y = x.map(item => item);
9
return [x, y];
10
}
11
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-frozen-array-noAlias.js
+1
-1
@@ -1,7 +1,7 @@
1
function Component(props) {
2
const x = [];
3
<dif>{x}</dif>;
4
- const y = x.map((item) => item);
4
+ const y = x.map(item => item);
5
return [x, y];
6
}
7
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-frozen-array.expect.md
+1
-1
@@ -5,7 +5,7 @@
5
function Component(props) {
6
const x = [];
7
<dif>{x}</dif>;
8
- const y = x.map((item) => item);
8
+ const y = x.map(item => item);
9
return [x, y];
10
}
11
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-frozen-array.js
+1
-1
@@ -1,7 +1,7 @@
1
function Component(props) {
2
const x = [];
3
<dif>{x}</dif>;
4
- const y = x.map((item) => item);
4
+ const y = x.map(item => item);
5
return [x, y];
6
}
7
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-mutable-array-mutating-lambda-noAlias.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
function Component(props) {
6
const x = [];
7
- const y = x.map((item) => {
7
+ const y = x.map(item => {
8
item.updated = true;
9
return item;
10
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-mutable-array-mutating-lambda-noAlias.js
+1
-1
@@ -1,6 +1,6 @@
1
function Component(props) {
2
const x = [];
3
- const y = x.map((item) => {
3
+ const y = x.map(item => {
4
item.updated = true;
5
return item;
6
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-mutable-array-mutating-lambda.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
function Component(props) {
6
const x = [];
7
- const y = x.map((item) => {
7
+ const y = x.map(item => {
8
item.updated = true;
9
return item;
10
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-mutable-array-mutating-lambda.js
+1
-1
@@ -1,6 +1,6 @@
1
function Component(props) {
2
const x = [];
3
- const y = x.map((item) => {
3
+ const y = x.map(item => {
4
item.updated = true;
5
return item;
6
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-mutable-array-non-mutating-lambda-mutated-result.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
function Component(props) {
6
const x = [{}];
7
- const y = x.map((item) => {
7
+ const y = x.map(item => {
8
return item;
9
});
10
y[0].flag = true;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-mutable-array-non-mutating-lambda-mutated-result.js
+1
-1
@@ -1,6 +1,6 @@
1
function Component(props) {
2
const x = [{}];
3
- const y = x.map((item) => {
3
+ const y = x.map(item => {
4
return item;
5
});
6
y[0].flag = true;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-noAlias-escaping-function.expect.md
+2
-2
@@ -3,14 +3,14 @@
3
4
```javascript
5
function Component(props) {
6
- const f = (item) => item;
6
+ const f = item => item;
7
const x = [...props.items].map(f); // `f` doesn't escape here...
8
return [x, f]; // ...but it does here so it's memoized
9
}
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ items: [{ id: 1 }] }],
13
+ params: [{items: [{id: 1}]}],
14
isComponent: false,
15
};
16
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-map-noAlias-escaping-function.js
+2
-2
@@ -1,11 +1,11 @@
1
function Component(props) {
2
- const f = (item) => item;
2
+ const f = item => item;
3
const x = [...props.items].map(f); // `f` doesn't escape here...
4
return [x, f]; // ...but it does here so it's memoized
5
}
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: [{ items: [{ id: 1 }] }],
9
+ params: [{items: [{id: 1}]}],
10
isComponent: false,
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-pattern-params.expect.md
+3
-3
@@ -3,14 +3,14 @@
3
4
```javascript
5
function component([a, b]) {
6
- let y = { a };
7
- let z = { b };
6
+ let y = {a};
7
+ let z = {b};
8
return [y, z];
9
}
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: component,
13
- params: [["val1", "val2"]],
13
+ params: [['val1', 'val2']],
14
isComponent: false,
15
};
16
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-pattern-params.js
+3
-3
@@ -1,11 +1,11 @@
1
function component([a, b]) {
2
- let y = { a };
3
- let z = { b };
2
+ let y = {a};
3
+ let z = {b};
4
return [y, z];
5
}
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: component,
9
- params: [["val1", "val2"]],
9
+ params: [['val1', 'val2']],
10
isComponent: false,
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-properties.expect.md
+3
-3
@@ -3,15 +3,15 @@
3
4
```javascript
5
function Component(props) {
6
- const a = [props.a, props.b, "hello"];
6
+ const a = [props.a, props.b, 'hello'];
7
const x = a.length;
8
const y = a.push;
9
- return { a, x, y, z: a.concat };
9
+ return {a, x, y, z: a.concat};
10
}
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ a: [1, 2], b: 2 }],
14
+ params: [{a: [1, 2], b: 2}],
15
isComponent: false,
16
};
17
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-properties.js
+3
-3
@@ -1,12 +1,12 @@
1
function Component(props) {
2
- const a = [props.a, props.b, "hello"];
2
+ const a = [props.a, props.b, 'hello'];
3
const x = a.length;
4
const y = a.push;
5
- return { a, x, y, z: a.concat };
5
+ return {a, x, y, z: a.concat};
6
}
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: [{ a: [1, 2], b: 2 }],
10
+ params: [{a: [1, 2], b: 2}],
11
isComponent: false,
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-property-call.expect.md
+3
-3
@@ -3,16 +3,16 @@
3
4
```javascript
5
function Component(props) {
6
- const a = [props.a, props.b, "hello"];
6
+ const a = [props.a, props.b, 'hello'];
7
const x = a.push(42);
8
const y = a.at(props.c);
9
10
- return { a, x, y };
10
+ return {a, x, y};
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ a: 1, b: 2, c: 0 }],
15
+ params: [{a: 1, b: 2, c: 0}],
16
isComponent: false,
17
};
18
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-property-call.js
+3
-3
@@ -1,13 +1,13 @@
1
function Component(props) {
2
- const a = [props.a, props.b, "hello"];
2
+ const a = [props.a, props.b, 'hello'];
3
const x = a.push(42);
4
const y = a.at(props.c);
5
6
- return { a, x, y };
6
+ return {a, x, y};
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: [{ a: 1, b: 2, c: 0 }],
11
+ params: [{a: 1, b: 2, c: 0}],
12
isComponent: false,
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-push-effect.expect.md
+1
-1
@@ -7,7 +7,7 @@
7
// - mutate on receiver
8
function Component(props) {
9
const x = foo(props.x);
10
- const y = { y: props.y };
10
+ const y = {y: props.y};
11
const arr = [];
12
arr.push({});
13
arr.push(x, y);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/array-push-effect.js
+1
-1
@@ -3,7 +3,7 @@
3
// - mutate on receiver
4
function Component(props) {
5
const x = foo(props.x);
6
- const y = { y: props.y };
6
+ const y = {y: props.y};
7
const arr = [];
8
arr.push({});
9
arr.push(x, y);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/arrow-expr-directive.expect.md
+3
-3
@@ -3,11 +3,11 @@
3
4
```javascript
5
function Component() {
6
- "use strict";
6
+ 'use strict';
7
let [count, setCount] = React.useState(0);
8
const update = () => {
9
- "worklet";
10
- setCount((count) => count + 1);
9
+ 'worklet';
10
+ setCount(count => count + 1);
11
};
12
return <button onClick={update}>{count}</button>;
13
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/arrow-expr-directive.js
+3
-3
@@ -1,9 +1,9 @@
1
function Component() {
2
- "use strict";
2
+ 'use strict';
3
let [count, setCount] = React.useState(0);
4
const update = () => {
5
- "worklet";
6
- setCount((count) => count + 1);
5
+ 'worklet';
6
+ setCount(count => count + 1);
7
};
8
return <button onClick={update}>{count}</button>;
9
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/arrow-function-one-line-directive.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
function useFoo() {
6
const update = () => {
7
- "worklet";
7
+ 'worklet';
8
return 1;
9
};
10
return update;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/arrow-function-one-line-directive.js
+1
-1
@@ -1,6 +1,6 @@
1
function useFoo() {
2
const update = () => {
3
- "worklet";
3
+ 'worklet';
4
return 1;
5
};
6
return update;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/assignment-expression-computed.expect.md
+2
-2
@@ -6,13 +6,13 @@ function Component(props) {
6
const x = [props.x];
7
const index = 0;
8
x[index] *= 2;
9
- x["0"] += 3;
9
+ x['0'] += 3;
10
return x;
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ x: 2 }],
15
+ params: [{x: 2}],
16
isComponent: false,
17
};
18
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/assignment-expression-computed.js
+2
-2
@@ -2,12 +2,12 @@ function Component(props) {
2
const x = [props.x];
3
const index = 0;
4
x[index] *= 2;
5
- x["0"] += 3;
5
+ x['0'] += 3;
6
return x;
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: [{ x: 2 }],
11
+ params: [{x: 2}],
12
isComponent: false,
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/assignment-expression-nested-path.expect.md
+2
-2
@@ -3,7 +3,7 @@
3
4
```javascript
5
function g(props) {
6
- const a = { b: { c: props.c } };
6
+ const a = {b: {c: props.c}};
7
a.b.c = a.b.c + 1;
8
a.b.c *= 2;
9
return a;
@@ -11,7 +11,7 @@ function g(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: g,
14
- params: [{ c: 2 }],
14
+ params: [{c: 2}],
15
isComponent: false,
16
};
17
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/assignment-expression-nested-path.js
+2
-2
@@ -1,5 +1,5 @@
1
function g(props) {
2
- const a = { b: { c: props.c } };
2
+ const a = {b: {c: props.c}};
3
a.b.c = a.b.c + 1;
4
a.b.c *= 2;
5
return a;
@@ -7,6 +7,6 @@ function g(props) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: g,
10
- params: [{ c: 2 }],
10
+ params: [{c: 2}],
11
isComponent: false,
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/assignment-variations-complex-lvalue.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function g() {
6
- const x = { y: { z: 1 } };
6
+ const x = {y: {z: 1}};
7
x.y.z = x.y.z + 1;
8
x.y.z *= 2;
9
return x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/assignment-variations-complex-lvalue.js
+1
-1
@@ -1,5 +1,5 @@
1
function g() {
2
- const x = { y: { z: 1 } };
2
+ const x = {y: {z: 1}};
3
x.y.z = x.y.z + 1;
4
x.y.z *= 2;
5
return x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/babel-existing-react-import.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useState, useMemo } from "react";
5
+import {useState, useMemo} from 'react';
6
7
function Component(props) {
8
const [x] = useState(0);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/babel-existing-react-import.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { useState, useMemo } from "react";
1
+import {useState, useMemo} from 'react';
2
3
function Component(props) {
4
const [x] = useState(0);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/babel-existing-react-kitchensink-import.expect.md
+2
-2
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import * as React from "react";
6
-import { useState, useMemo } from "react";
5
+import * as React from 'react';
6
+import {useState, useMemo} from 'react';
7
8
function Component(props) {
9
const [x] = useState(0);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/babel-existing-react-kitchensink-import.js
+2
-2
@@ -1,5 +1,5 @@
1
-import * as React from "react";
2
-import { useState, useMemo } from "react";
1
+import * as React from 'react';
2
+import {useState, useMemo} from 'react';
3
4
function Component(props) {
5
const [x] = useState(0);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/babel-existing-react-namespace-import.expect.md
+2
-2
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import * as React from "react";
6
-import { calculateExpensiveNumber } from "shared-runtime";
5
+import * as React from 'react';
6
+import {calculateExpensiveNumber} from 'shared-runtime';
7
8
function Component(props) {
9
const [x] = React.useState(0);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/babel-existing-react-namespace-import.js
+2
-2
@@ -1,5 +1,5 @@
1
-import * as React from "react";
2
-import { calculateExpensiveNumber } from "shared-runtime";
1
+import * as React from 'react';
2
+import {calculateExpensiveNumber} from 'shared-runtime';
3
4
function Component(props) {
5
const [x] = React.useState(0);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/block-scoping-switch-dead-code.expect.md
+1
-1
@@ -19,7 +19,7 @@ function useHook(a, b) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: useHook,
22
- params: [1, "foo"],
22
+ params: [1, 'foo'],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/block-scoping-switch-dead-code.js
+1
-1
@@ -15,5 +15,5 @@ function useHook(a, b) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: useHook,
18
- params: [1, "foo"],
18
+ params: [1, 'foo'],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/block-scoping-switch-variable-scoping.expect.md
+3
-3
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-import { useMemo } from "react";
5
+import {useMemo} from 'react';
6
7
function Component(props) {
8
const outerHandlers = useMemo(() => {
9
- let handlers = { value: props.value };
9
+ let handlers = {value: props.value};
10
switch (props.test) {
11
case true: {
12
console.log(handlers.value);
@@ -22,7 +22,7 @@ function Component(props) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
25
- params: [{ test: true, value: "hello" }],
25
+ params: [{test: true, value: 'hello'}],
26
};
27
28
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/block-scoping-switch-variable-scoping.js
+3
-3
@@ -1,8 +1,8 @@
1
-import { useMemo } from "react";
1
+import {useMemo} from 'react';
2
3
function Component(props) {
4
const outerHandlers = useMemo(() => {
5
- let handlers = { value: props.value };
5
+ let handlers = {value: props.value};
6
switch (props.test) {
7
case true: {
8
console.log(handlers.value);
@@ -18,5 +18,5 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ test: true, value: "hello" }],
21
+ params: [{test: true, value: 'hello'}],
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/bug-codegen-inline-iife.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeArray, print } from "shared-runtime";
5
+import {makeArray, print} from 'shared-runtime';
6
7
/**
8
* Exposes bug involving iife inlining + codegen.
@@ -30,7 +30,7 @@ function useTest() {
30
(function foo() {
31
print(2);
32
return 2;
33
- })()
33
+ })(),
34
);
35
}
36
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/bug-codegen-inline-iife.ts
+2
-2
@@ -1,4 +1,4 @@
1
-import { makeArray, print } from "shared-runtime";
1
+import {makeArray, print} from 'shared-runtime';
2
3
/**
4
* Exposes bug involving iife inlining + codegen.
@@ -26,7 +26,7 @@ function useTest() {
26
(function foo() {
27
print(2);
28
return 2;
29
- })()
29
+ })(),
30
);
31
}
32
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/bug-invalid-hoisting-functionexpr.expect.md
+3
-3
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
/**
8
* We currently hoist the accessed properties of function expressions,
@@ -17,7 +17,7 @@ import { Stringify } from "shared-runtime";
17
* Forget:
18
* (kind: exception) Cannot read properties of null (reading 'prop')
19
*/
20
-function Component({ obj, isObjNull }) {
20
+function Component({obj, isObjNull}) {
21
const callback = () => {
22
if (!isObjNull) {
23
return obj.prop;
@@ -30,7 +30,7 @@ function Component({ obj, isObjNull }) {
30
31
export const FIXTURE_ENTRYPOINT = {
32
fn: Component,
33
- params: [{ obj: null, isObjNull: true }],
33
+ params: [{obj: null, isObjNull: true}],
34
};
35
36
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/bug-invalid-hoisting-functionexpr.tsx
+3
-3
@@ -1,4 +1,4 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
/**
4
* We currently hoist the accessed properties of function expressions,
@@ -13,7 +13,7 @@ import { Stringify } from "shared-runtime";
13
* Forget:
14
* (kind: exception) Cannot read properties of null (reading 'prop')
15
*/
16
-function Component({ obj, isObjNull }) {
16
+function Component({obj, isObjNull}) {
17
const callback = () => {
18
if (!isObjNull) {
19
return obj.prop;
@@ -26,5 +26,5 @@ function Component({ obj, isObjNull }) {
26
27
export const FIXTURE_ENTRYPOINT = {
28
fn: Component,
29
- params: [{ obj: null, isObjNull: true }],
29
+ params: [{obj: null, isObjNull: true}],
30
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capitalized-function-allowlist.expect.md
+2
-2
@@ -3,13 +3,13 @@
3
4
```javascript
5
// @validateNoCapitalizedCalls @hookPattern:".*\b(use[^$]+)$"
6
-import * as React from "react";
6
+import * as React from 'react';
7
const React$useState = React.useState;
8
const THIS_IS_A_CONSTANT = () => {};
9
function Component() {
10
const b = Boolean(true); // OK
11
const n = Number(3); // OK
12
- const s = String("foo"); // OK
12
+ const s = String('foo'); // OK
13
const [state, setState] = React$useState(0); // OK
14
const [state2, setState2] = React.useState(1); // OK
15
const constant = THIS_IS_A_CONSTANT(); // OK
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capitalized-function-allowlist.js
+2
-2
@@ -1,11 +1,11 @@
1
// @validateNoCapitalizedCalls @hookPattern:".*\b(use[^$]+)$"
2
-import * as React from "react";
2
+import * as React from 'react';
3
const React$useState = React.useState;
4
const THIS_IS_A_CONSTANT = () => {};
5
function Component() {
6
const b = Boolean(true); // OK
7
const n = Number(3); // OK
8
- const s = String("foo"); // OK
8
+ const s = String('foo'); // OK
9
const [state, setState] = React$useState(0); // OK
10
const [state2, setState2] = React.useState(1); // OK
11
const constant = THIS_IS_A_CONSTANT(); // OK
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capture-indirect-mutate-alias-iife.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let x = { a };
6
+ let x = {a};
7
(function () {
8
let q = x;
9
(function () {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capture-indirect-mutate-alias-iife.js
+1
-1
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let x = { a };
2
+ let x = {a};
3
(function () {
4
let q = x;
5
(function () {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capture-indirect-mutate-alias.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let x = { a };
6
+ let x = {a};
7
const f0 = function () {
8
let q = x;
9
const f1 = function () {
@@ -18,8 +18,8 @@ function component(a) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: component,
21
- params: ["TodoAdd"],
22
- isComponent: "TodoAdd",
21
+ params: ['TodoAdd'],
22
+ isComponent: 'TodoAdd',
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capture-indirect-mutate-alias.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let x = { a };
2
+ let x = {a};
3
const f0 = function () {
4
let q = x;
5
const f1 = function () {
@@ -14,6 +14,6 @@ function component(a) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: component,
17
- params: ["TodoAdd"],
18
- isComponent: "TodoAdd",
17
+ params: ['TodoAdd'],
18
+ isComponent: 'TodoAdd',
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capture-param-mutate.expect.md
+5
-5
@@ -5,7 +5,7 @@
5
function getNativeLogFunction(level) {
6
return function () {
7
let str;
8
- if (arguments.length === 1 && typeof arguments[0] === "string") {
8
+ if (arguments.length === 1 && typeof arguments[0] === 'string') {
9
str = arguments[0];
10
} else {
11
str = Array.prototype.map
@@ -14,13 +14,13 @@ function getNativeLogFunction(level) {
14
depth: 10,
15
});
16
})
17
- .join(", ");
17
+ .join(', ');
18
}
19
const firstArg = arguments[0];
20
let logLevel = level;
21
if (
22
- typeof firstArg === "string" &&
23
- firstArg.slice(0, 9) === "Warning: " &&
22
+ typeof firstArg === 'string' &&
23
+ firstArg.slice(0, 9) === 'Warning: ' &&
24
logLevel >= LOG_LEVELS.error
25
) {
26
logLevel = LOG_LEVELS.warn;
@@ -34,7 +34,7 @@ function getNativeLogFunction(level) {
34
);
35
}
36
if (groupStack.length) {
37
- str = groupFormat("", str);
37
+ str = groupFormat('', str);
38
}
39
global.nativeLoggingHook(str, logLevel);
40
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capture-param-mutate.js
+5
-5
@@ -1,7 +1,7 @@
1
function getNativeLogFunction(level) {
2
return function () {
3
let str;
4
- if (arguments.length === 1 && typeof arguments[0] === "string") {
4
+ if (arguments.length === 1 && typeof arguments[0] === 'string') {
5
str = arguments[0];
6
} else {
7
str = Array.prototype.map
@@ -10,13 +10,13 @@ function getNativeLogFunction(level) {
10
depth: 10,
11
});
12
})
13
- .join(", ");
13
+ .join(', ');
14
}
15
const firstArg = arguments[0];
16
let logLevel = level;
17
if (
18
- typeof firstArg === "string" &&
19
- firstArg.slice(0, 9) === "Warning: " &&
18
+ typeof firstArg === 'string' &&
19
+ firstArg.slice(0, 9) === 'Warning: ' &&
20
logLevel >= LOG_LEVELS.error
21
) {
22
logLevel = LOG_LEVELS.warn;
@@ -30,7 +30,7 @@ function getNativeLogFunction(level) {
30
);
31
}
32
if (groupStack.length) {
33
- str = groupFormat("", str);
33
+ str = groupFormat('', str);
34
}
35
global.nativeLoggingHook(str, logLevel);
36
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capture-ref-for-later-mutation.expect.md
+6
-6
@@ -2,21 +2,21 @@
2
## Input
3
4
```javascript
5
-import { useRef } from "react";
6
-import { addOne } from "shared-runtime";
5
+import {useRef} from 'react';
6
+import {addOne} from 'shared-runtime';
7
8
function useKeyCommand() {
9
const currentPosition = useRef(0);
10
- const handleKey = (direction) => () => {
10
+ const handleKey = direction => () => {
11
const position = currentPosition.current;
12
- const nextPosition = direction === "left" ? addOne(position) : position;
12
+ const nextPosition = direction === 'left' ? addOne(position) : position;
13
currentPosition.current = nextPosition;
14
};
15
const moveLeft = {
16
- handler: handleKey("left"),
16
+ handler: handleKey('left'),
17
};
18
const moveRight = {
19
- handler: handleKey("right"),
19
+ handler: handleKey('right'),
20
};
21
return [moveLeft, moveRight];
22
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capture-ref-for-later-mutation.tsx
+6
-6
@@ -1,18 +1,18 @@
1
-import { useRef } from "react";
2
-import { addOne } from "shared-runtime";
1
+import {useRef} from 'react';
2
+import {addOne} from 'shared-runtime';
3
4
function useKeyCommand() {
5
const currentPosition = useRef(0);
6
- const handleKey = (direction) => () => {
6
+ const handleKey = direction => () => {
7
const position = currentPosition.current;
8
- const nextPosition = direction === "left" ? addOne(position) : position;
8
+ const nextPosition = direction === 'left' ? addOne(position) : position;
9
currentPosition.current = nextPosition;
10
};
11
const moveLeft = {
12
- handler: handleKey("left"),
12
+ handler: handleKey('left'),
13
};
14
const moveRight = {
15
- handler: handleKey("right"),
15
+ handler: handleKey('right'),
16
};
17
return [moveLeft, moveRight];
18
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capture_mutate-across-fns-iife.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let z = { a };
6
+ let z = {a};
7
(function () {
8
(function () {
9
z.b = 1;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capture_mutate-across-fns-iife.js
+1
-1
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let z = { a };
2
+ let z = {a};
3
(function () {
4
(function () {
5
z.b = 1;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capture_mutate-across-fns.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let z = { a };
6
+ let z = {a};
7
const f0 = function () {
8
const f1 = function () {
9
z.b = 1;
@@ -16,8 +16,8 @@ function component(a) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: component,
19
- params: ["TodoAdd"],
20
- isComponent: "TodoAdd",
19
+ params: ['TodoAdd'],
20
+ isComponent: 'TodoAdd',
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capture_mutate-across-fns.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let z = { a };
2
+ let z = {a};
3
const f0 = function () {
4
const f1 = function () {
5
z.b = 1;
@@ -12,6 +12,6 @@ function component(a) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: component,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-arrow-function-1.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let z = { a };
6
+ let z = {a};
7
let x = () => {
8
console.log(z);
9
};
@@ -12,8 +12,8 @@ function component(a) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: component,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-arrow-function-1.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let z = { a };
2
+ let z = {a};
3
let x = () => {
4
console.log(z);
5
};
@@ -8,6 +8,6 @@ function component(a) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: component,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-fun-alias-captured-mutate-2-iife.expect.md
+5
-5
@@ -2,13 +2,13 @@
2
## Input
3
4
```javascript
5
-import { mutate } from "shared-runtime";
5
+import {mutate} from 'shared-runtime';
6
7
function component(foo, bar) {
8
- let x = { foo };
9
- let y = { bar };
8
+ let x = {foo};
9
+ let y = {bar};
10
(function () {
11
- let a = { y };
11
+ let a = {y};
12
let b = x;
13
a.x = b;
14
})();
@@ -18,7 +18,7 @@ function component(foo, bar) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: component,
21
- params: ["foo", "bar"],
21
+ params: ['foo', 'bar'],
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-fun-alias-captured-mutate-2-iife.js
+5
-5
@@ -1,10 +1,10 @@
1
-import { mutate } from "shared-runtime";
1
+import {mutate} from 'shared-runtime';
2
3
function component(foo, bar) {
4
- let x = { foo };
5
- let y = { bar };
4
+ let x = {foo};
5
+ let y = {bar};
6
(function () {
7
- let a = { y };
7
+ let a = {y};
8
let b = x;
9
a.x = b;
10
})();
@@ -14,5 +14,5 @@ function component(foo, bar) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: component,
17
- params: ["foo", "bar"],
17
+ params: ['foo', 'bar'],
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-fun-alias-captured-mutate-2.expect.md
+3
-3
@@ -3,10 +3,10 @@
3
4
```javascript
5
function component(foo, bar) {
6
- let x = { foo };
7
- let y = { bar };
6
+ let x = {foo};
7
+ let y = {bar};
8
const f0 = function () {
9
- let a = { y };
9
+ let a = {y};
10
let b = x;
11
a.x = b;
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-fun-alias-captured-mutate-2.js
+3
-3
@@ -1,8 +1,8 @@
1
function component(foo, bar) {
2
- let x = { foo };
3
- let y = { bar };
2
+ let x = {foo};
3
+ let y = {bar};
4
const f0 = function () {
5
- let a = { y };
5
+ let a = {y};
6
let b = x;
7
a.x = b;
8
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-fun-alias-captured-mutate-arr-2-iife.expect.md
+4
-4
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-const { mutate } = require("shared-runtime");
5
+const {mutate} = require('shared-runtime');
6
7
function component(foo, bar) {
8
- let x = { foo };
9
- let y = { bar };
8
+ let x = {foo};
9
+ let y = {bar};
10
(function () {
11
let a = [y];
12
let b = x;
@@ -18,7 +18,7 @@ function component(foo, bar) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: component,
21
- params: ["foo", "bar"],
21
+ params: ['foo', 'bar'],
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-fun-alias-captured-mutate-arr-2-iife.js
+4
-4
@@ -1,8 +1,8 @@
1
-const { mutate } = require("shared-runtime");
1
+const {mutate} = require('shared-runtime');
2
3
function component(foo, bar) {
4
- let x = { foo };
5
- let y = { bar };
4
+ let x = {foo};
5
+ let y = {bar};
6
(function () {
7
let a = [y];
8
let b = x;
@@ -14,5 +14,5 @@ function component(foo, bar) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: component,
17
- params: ["foo", "bar"],
17
+ params: ['foo', 'bar'],
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-fun-alias-captured-mutate-arr-2.expect.md
+2
-2
@@ -3,8 +3,8 @@
3
4
```javascript
5
function component(foo, bar) {
6
- let x = { foo };
7
- let y = { bar };
6
+ let x = {foo};
7
+ let y = {bar};
8
const f0 = function () {
9
let a = [y];
10
let b = x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-fun-alias-captured-mutate-arr-2.js
+2
-2
@@ -1,6 +1,6 @@
1
function component(foo, bar) {
2
- let x = { foo };
3
- let y = { bar };
2
+ let x = {foo};
3
+ let y = {bar};
4
const f0 = function () {
5
let a = [y];
6
let b = x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-captured-mutate-arr-iife.expect.md
+4
-4
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-const { mutate } = require("shared-runtime");
5
+const {mutate} = require('shared-runtime');
6
7
function component(foo, bar) {
8
- let x = { foo };
9
- let y = { bar };
8
+ let x = {foo};
9
+ let y = {bar};
10
(function () {
11
let a = [y];
12
let b = x;
@@ -18,7 +18,7 @@ function component(foo, bar) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: component,
21
- params: ["foo", "bar"],
21
+ params: ['foo', 'bar'],
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-captured-mutate-arr-iife.js
+4
-4
@@ -1,8 +1,8 @@
1
-const { mutate } = require("shared-runtime");
1
+const {mutate} = require('shared-runtime');
2
3
function component(foo, bar) {
4
- let x = { foo };
5
- let y = { bar };
4
+ let x = {foo};
5
+ let y = {bar};
6
(function () {
7
let a = [y];
8
let b = x;
@@ -14,5 +14,5 @@ function component(foo, bar) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: component,
17
- params: ["foo", "bar"],
17
+ params: ['foo', 'bar'],
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-captured-mutate-arr.expect.md
+2
-2
@@ -3,8 +3,8 @@
3
4
```javascript
5
function component(foo, bar) {
6
- let x = { foo };
7
- let y = { bar };
6
+ let x = {foo};
7
+ let y = {bar};
8
const f0 = function () {
9
let a = [y];
10
let b = x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-captured-mutate-arr.js
+2
-2
@@ -1,6 +1,6 @@
1
function component(foo, bar) {
2
- let x = { foo };
3
- let y = { bar };
2
+ let x = {foo};
3
+ let y = {bar};
4
const f0 = function () {
5
let a = [y];
6
let b = x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-captured-mutate-iife.expect.md
+5
-5
@@ -2,13 +2,13 @@
2
## Input
3
4
```javascript
5
-const { mutate } = require("shared-runtime");
5
+const {mutate} = require('shared-runtime');
6
7
function component(foo, bar) {
8
- let x = { foo };
9
- let y = { bar };
8
+ let x = {foo};
9
+ let y = {bar};
10
(function () {
11
- let a = { y };
11
+ let a = {y};
12
let b = x;
13
a.x = b;
14
})();
@@ -18,7 +18,7 @@ function component(foo, bar) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: component,
21
- params: ["foo", "bar"],
21
+ params: ['foo', 'bar'],
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-captured-mutate-iife.js
+5
-5
@@ -1,10 +1,10 @@
1
-const { mutate } = require("shared-runtime");
1
+const {mutate} = require('shared-runtime');
2
3
function component(foo, bar) {
4
- let x = { foo };
5
- let y = { bar };
4
+ let x = {foo};
5
+ let y = {bar};
6
(function () {
7
- let a = { y };
7
+ let a = {y};
8
let b = x;
9
a.x = b;
10
})();
@@ -14,5 +14,5 @@ function component(foo, bar) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: component,
17
- params: ["foo", "bar"],
17
+ params: ['foo', 'bar'],
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-captured-mutate.expect.md
+3
-3
@@ -3,10 +3,10 @@
3
4
```javascript
5
function component(foo, bar) {
6
- let x = { foo };
7
- let y = { bar };
6
+ let x = {foo};
7
+ let y = {bar};
8
const f0 = function () {
9
- let a = { y };
9
+ let a = {y};
10
let b = x;
11
a.x = b;
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-captured-mutate.js
+3
-3
@@ -1,8 +1,8 @@
1
function component(foo, bar) {
2
- let x = { foo };
3
- let y = { bar };
2
+ let x = {foo};
3
+ let y = {bar};
4
const f0 = function () {
5
- let a = { y };
5
+ let a = {y};
6
let b = x;
7
a.x = b;
8
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-computed-mutate-iife.expect.md
+4
-4
@@ -2,13 +2,13 @@
2
## Input
3
4
```javascript
5
-const { mutate } = require("shared-runtime");
5
+const {mutate} = require('shared-runtime');
6
7
function component(a) {
8
- let x = { a };
8
+ let x = {a};
9
let y = {};
10
(function () {
11
- y["x"] = x;
11
+ y['x'] = x;
12
})();
13
mutate(y);
14
return y;
@@ -16,7 +16,7 @@ function component(a) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: component,
19
- params: ["foo"],
19
+ params: ['foo'],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-computed-mutate-iife.js
+4
-4
@@ -1,10 +1,10 @@
1
-const { mutate } = require("shared-runtime");
1
+const {mutate} = require('shared-runtime');
2
3
function component(a) {
4
- let x = { a };
4
+ let x = {a};
5
let y = {};
6
(function () {
7
- y["x"] = x;
7
+ y['x'] = x;
8
})();
9
mutate(y);
10
return y;
@@ -12,5 +12,5 @@ function component(a) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: component,
15
- params: ["foo"],
15
+ params: ['foo'],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-computed-mutate.expect.md
+2
-2
@@ -3,10 +3,10 @@
3
4
```javascript
5
function component(a) {
6
- let x = { a };
6
+ let x = {a};
7
let y = {};
8
const f0 = function () {
9
- y["x"] = x;
9
+ y['x'] = x;
10
};
11
f0();
12
mutate(y);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-computed-mutate.js
+2
-2
@@ -1,8 +1,8 @@
1
function component(a) {
2
- let x = { a };
2
+ let x = {a};
3
let y = {};
4
const f0 = function () {
5
- y["x"] = x;
5
+ y['x'] = x;
6
};
7
f0();
8
mutate(y);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-mutate-iife.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-const { mutate } = require("shared-runtime");
5
+const {mutate} = require('shared-runtime');
6
7
function component(a) {
8
- let x = { a };
8
+ let x = {a};
9
let y = {};
10
(function () {
11
y.x = x;
@@ -16,7 +16,7 @@ function component(a) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: component,
19
- params: ["foo"],
19
+ params: ['foo'],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-mutate-iife.js
+3
-3
@@ -1,7 +1,7 @@
1
-const { mutate } = require("shared-runtime");
1
+const {mutate} = require('shared-runtime');
2
3
function component(a) {
4
- let x = { a };
4
+ let x = {a};
5
let y = {};
6
(function () {
7
y.x = x;
@@ -12,5 +12,5 @@ function component(a) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: component,
15
- params: ["foo"],
15
+ params: ['foo'],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-mutate.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let x = { a };
6
+ let x = {a};
7
let y = {};
8
const f0 = function () {
9
y.x = x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-mutate.js
+1
-1
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let x = { a };
2
+ let x = {a};
3
let y = {};
4
const f0 = function () {
5
y.x = x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-receiver-computed-mutate-iife.expect.md
+4
-4
@@ -2,14 +2,14 @@
2
## Input
3
4
```javascript
5
-import { mutate } from "shared-runtime";
5
+import {mutate} from 'shared-runtime';
6
7
function component(a) {
8
- let x = { a };
8
+ let x = {a};
9
let y = {};
10
(function () {
11
let a = y;
12
- a["x"] = x;
12
+ a['x'] = x;
13
})();
14
mutate(y);
15
return y;
@@ -17,7 +17,7 @@ function component(a) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: component,
20
- params: ["foo"],
20
+ params: ['foo'],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-receiver-computed-mutate-iife.js
+4
-4
@@ -1,11 +1,11 @@
1
-import { mutate } from "shared-runtime";
1
+import {mutate} from 'shared-runtime';
2
3
function component(a) {
4
- let x = { a };
4
+ let x = {a};
5
let y = {};
6
(function () {
7
let a = y;
8
- a["x"] = x;
8
+ a['x'] = x;
9
})();
10
mutate(y);
11
return y;
@@ -13,5 +13,5 @@ function component(a) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: component,
16
- params: ["foo"],
16
+ params: ['foo'],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-receiver-computed-mutate.expect.md
+2
-2
@@ -3,11 +3,11 @@
3
4
```javascript
5
function component(a) {
6
- let x = { a };
6
+ let x = {a};
7
let y = {};
8
const f0 = function () {
9
let a = y;
10
- a["x"] = x;
10
+ a['x'] = x;
11
};
12
f0();
13
mutate(y);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-receiver-computed-mutate.js
+2
-2
@@ -1,9 +1,9 @@
1
function component(a) {
2
- let x = { a };
2
+ let x = {a};
3
let y = {};
4
const f0 = function () {
5
let a = y;
6
- a["x"] = x;
6
+ a['x'] = x;
7
};
8
f0();
9
mutate(y);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-receiver-mutate-iife.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-const { mutate } = require("shared-runtime");
5
+const {mutate} = require('shared-runtime');
6
7
function component(a) {
8
- let x = { a };
8
+ let x = {a};
9
let y = {};
10
(function () {
11
let a = y;
@@ -17,7 +17,7 @@ function component(a) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: component,
20
- params: ["foo"],
20
+ params: ['foo'],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-receiver-mutate-iife.js
+3
-3
@@ -1,7 +1,7 @@
1
-const { mutate } = require("shared-runtime");
1
+const {mutate} = require('shared-runtime');
2
3
function component(a) {
4
- let x = { a };
4
+ let x = {a};
5
let y = {};
6
(function () {
7
let a = y;
@@ -13,5 +13,5 @@ function component(a) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: component,
16
- params: ["foo"],
16
+ params: ['foo'],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-receiver-mutate.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let x = { a };
6
+ let x = {a};
7
let y = {};
8
const f0 = function () {
9
let a = y;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-receiver-mutate.js
+1
-1
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let x = { a };
2
+ let x = {a};
3
let y = {};
4
const f0 = function () {
5
let a = y;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-mutate-2.expect.md
+3
-3
@@ -3,8 +3,8 @@
3
4
```javascript
5
function component(a, b) {
6
- let y = { b };
7
- let z = { a };
6
+ let y = {b};
7
+ let z = {a};
8
let x = function () {
9
z.a = 2;
10
y.b;
@@ -15,7 +15,7 @@ function component(a, b) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: component,
18
- params: [{ a: "val1", b: "val2" }],
18
+ params: [{a: 'val1', b: 'val2'}],
19
isComponent: false,
20
};
21
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-mutate-2.js
+3
-3
@@ -1,6 +1,6 @@
1
function component(a, b) {
2
- let y = { b };
3
- let z = { a };
2
+ let y = {b};
3
+ let z = {a};
4
let x = function () {
5
z.a = 2;
6
y.b;
@@ -11,6 +11,6 @@ function component(a, b) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: component,
14
- params: [{ a: "val1", b: "val2" }],
14
+ params: [{a: 'val1', b: 'val2'}],
15
isComponent: false,
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-mutate-3.expect.md
+4
-4
@@ -3,8 +3,8 @@
3
4
```javascript
5
function component(a, b) {
6
- let y = { b };
7
- let z = { a };
6
+ let y = {b};
7
+ let z = {a};
8
let x = function () {
9
z.a = 2;
10
y.b;
@@ -14,8 +14,8 @@ function component(a, b) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: component,
17
- params: ["TodoAdd"],
18
- isComponent: "TodoAdd",
17
+ params: ['TodoAdd'],
18
+ isComponent: 'TodoAdd',
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-mutate-3.js
+4
-4
@@ -1,6 +1,6 @@
1
function component(a, b) {
2
- let y = { b };
3
- let z = { a };
2
+ let y = {b};
3
+ let z = {a};
4
let x = function () {
5
z.a = 2;
6
y.b;
@@ -10,6 +10,6 @@ function component(a, b) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-mutate-nested.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let y = { b: { a } };
6
+ let y = {b: {a}};
7
let x = function () {
8
y.b.a = 2;
9
};
@@ -13,8 +13,8 @@ function component(a) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: component,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-mutate-nested.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let y = { b: { a } };
2
+ let y = {b: {a}};
3
let x = function () {
4
y.b.a = 2;
5
};
@@ -9,6 +9,6 @@ function component(a) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: component,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-mutate.expect.md
+4
-4
@@ -3,8 +3,8 @@
3
4
```javascript
5
function component(a, b) {
6
- let z = { a };
7
- let y = { b };
6
+ let z = {a};
7
+ let y = {b};
8
let x = function () {
9
z.a = 2;
10
console.log(y.b);
@@ -15,8 +15,8 @@ function component(a, b) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: component,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-mutate.js
+4
-4
@@ -1,6 +1,6 @@
1
function component(a, b) {
2
- let z = { a };
3
- let y = { b };
2
+ let z = {a};
3
+ let y = {b};
4
let x = function () {
5
z.a = 2;
6
console.log(y.b);
@@ -11,6 +11,6 @@ function component(a, b) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: component,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-simple-alias-iife.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-const { mutate } = require("shared-runtime");
5
+const {mutate} = require('shared-runtime');
6
7
function component(a) {
8
- let x = { a };
8
+ let x = {a};
9
let y = {};
10
(function () {
11
y = x;
@@ -16,7 +16,7 @@ function component(a) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: component,
19
- params: ["foo"],
19
+ params: ['foo'],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-simple-alias-iife.js
+3
-3
@@ -1,7 +1,7 @@
1
-const { mutate } = require("shared-runtime");
1
+const {mutate} = require('shared-runtime');
2
3
function component(a) {
4
- let x = { a };
4
+ let x = {a};
5
let y = {};
6
(function () {
7
y = x;
@@ -12,5 +12,5 @@ function component(a) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: component,
15
- params: ["foo"],
15
+ params: ['foo'],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-simple-alias.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let x = { a };
6
+ let x = {a};
7
let y = {};
8
const f0 = function () {
9
y = x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-simple-alias.js
+1
-1
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let x = { a };
2
+ let x = {a};
3
let y = {};
4
const f0 = function () {
5
y = x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-1.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let z = { a };
6
+ let z = {a};
7
let x = function () {
8
console.log(z);
9
};
@@ -12,8 +12,8 @@ function component(a) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: component,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-1.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let z = { a };
2
+ let z = {a};
3
let x = function () {
4
console.log(z);
5
};
@@ -8,6 +8,6 @@ function component(a) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: component,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-alias-computed-load-2-iife.expect.md
+1
-1
@@ -14,7 +14,7 @@ function bar(a) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: bar,
17
- params: [["val1", "val2"]],
17
+ params: [['val1', 'val2']],
18
isComponent: false,
19
};
20
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-alias-computed-load-2-iife.js
+1
-1
@@ -10,6 +10,6 @@ function bar(a) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: bar,
13
- params: [["val1", "val2"]],
13
+ params: [['val1', 'val2']],
14
isComponent: false,
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-alias-computed-load-2.expect.md
+1
-1
@@ -15,7 +15,7 @@ function bar(a) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: bar,
18
- params: [["val1", "val2"]],
18
+ params: [['val1', 'val2']],
19
isComponent: false,
20
};
21
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-alias-computed-load-2.js
+1
-1
@@ -11,6 +11,6 @@ function bar(a) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: bar,
14
- params: [["val1", "val2"]],
14
+ params: [['val1', 'val2']],
15
isComponent: false,
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-alias-computed-load-4-iife.expect.md
+1
-1
@@ -14,7 +14,7 @@ function bar(a) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: bar,
17
- params: [{ a: ["val1", "val2"] }],
17
+ params: [{a: ['val1', 'val2']}],
18
isComponent: false,
19
};
20
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-alias-computed-load-4-iife.js
+1
-1
@@ -10,6 +10,6 @@ function bar(a) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: bar,
13
- params: [{ a: ["val1", "val2"] }],
13
+ params: [{a: ['val1', 'val2']}],
14
isComponent: false,
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-alias-computed-load-4.expect.md
+1
-1
@@ -15,7 +15,7 @@ function bar(a) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: bar,
18
- params: [{ a: ["val1", "val2"] }],
18
+ params: [{a: ['val1', 'val2']}],
19
isComponent: false,
20
};
21
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-alias-computed-load-4.js
+1
-1
@@ -11,6 +11,6 @@ function bar(a) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: bar,
14
- params: [{ a: ["val1", "val2"] }],
14
+ params: [{a: ['val1', 'val2']}],
15
isComponent: false,
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-alias-computed-load-iife.expect.md
+1
-1
@@ -14,7 +14,7 @@ function bar(a) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: bar,
17
- params: ["TodoAdd"],
17
+ params: ['TodoAdd'],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-alias-computed-load-iife.js
+1
-1
@@ -10,5 +10,5 @@ function bar(a) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: bar,
13
- params: ["TodoAdd"],
13
+ params: ['TodoAdd'],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-alias-computed-load.expect.md
+2
-2
@@ -15,8 +15,8 @@ function bar(a) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: bar,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-alias-computed-load.js
+2
-2
@@ -11,6 +11,6 @@ function bar(a) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: bar,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-capture-ref-before-rename.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a, b) {
6
- let z = { a };
6
+ let z = {a};
7
(function () {
8
mutate(z);
9
})();
@@ -11,8 +11,8 @@ function component(a, b) {
11
12
{
13
// z is shadowed & renamed but the lambda is unaffected.
14
- let z = { b };
15
- y = { y, z };
14
+ let z = {b};
15
+ y = {y, z};
16
}
17
return y;
18
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-capture-ref-before-rename.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a, b) {
2
- let z = { a };
2
+ let z = {a};
3
(function () {
4
mutate(z);
5
})();
@@ -7,8 +7,8 @@ function component(a, b) {
7
8
{
9
// z is shadowed & renamed but the lambda is unaffected.
10
- let z = { b };
11
- y = { y, z };
10
+ let z = {b};
11
+ y = {y, z};
12
}
13
return y;
14
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-conditional-capture-mutate.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
// @debug
6
function component(a, b) {
7
- let z = { a };
7
+ let z = {a};
8
let y = b;
9
let x = function () {
10
if (y) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-conditional-capture-mutate.js
+1
-1
@@ -1,6 +1,6 @@
1
// @debug
2
function component(a, b) {
3
- let z = { a };
3
+ let z = {a};
4
let y = b;
5
let x = function () {
6
if (y) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-decl.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let t = { a };
6
+ let t = {a};
7
function x() {
8
t.foo();
9
}
@@ -13,8 +13,8 @@ function component(a) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: component,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-decl.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let t = { a };
2
+ let t = {a};
3
function x() {
4
t.foo();
5
}
@@ -9,6 +9,6 @@ function component(a) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: component,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-member-expr-arguments.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
function Foo(props) {
6
const onFoo = useCallback(
7
- (reason) => {
7
+ reason => {
8
log(props.router.location);
9
},
10
[props.router.location]
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-member-expr-arguments.js
+1
-1
@@ -1,6 +1,6 @@
1
function Foo(props) {
2
const onFoo = useCallback(
3
- (reason) => {
3
+ reason => {
4
log(props.router.location);
5
},
6
[props.router.location]
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-member-expr-call.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function component({ mutator }) {
5
+function component({mutator}) {
6
const poke = () => {
7
mutator.poke();
8
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-member-expr-call.js
+1
-1
@@ -1,4 +1,4 @@
1
-function component({ mutator }) {
1
+function component({mutator}) {
2
const poke = () => {
3
mutator.poke();
4
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-renamed-ref.expect.md
+2
-2
@@ -3,9 +3,9 @@
3
4
```javascript
5
function component(a, b) {
6
- let z = { a };
6
+ let z = {a};
7
{
8
- let z = { b };
8
+ let z = {b};
9
(function () {
10
mutate(z);
11
})();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-renamed-ref.js
+2
-2
@@ -1,7 +1,7 @@
1
function component(a, b) {
2
- let z = { a };
2
+ let z = {a};
3
{
4
- let z = { b };
4
+ let z = {b};
5
(function () {
6
mutate(z);
7
})();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-runs-inference.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a, b) {
6
- let z = { a };
6
+ let z = {a};
7
let p = () => <Foo>{z}</Foo>;
8
return p();
9
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-runs-inference.js
+1
-1
@@ -1,5 +1,5 @@
1
function component(a, b) {
2
- let z = { a };
2
+ let z = {a};
3
let p = () => <Foo>{z}</Foo>;
4
return p();
5
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-shadow-captured.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let z = { a };
6
+ let z = {a};
7
let x = function () {
8
let z;
9
mutate(z);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-shadow-captured.js
+1
-1
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let z = { a };
2
+ let z = {a};
3
let x = function () {
4
let z;
5
mutate(z);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-skip-computed-path.expect.md
+4
-4
@@ -3,14 +3,14 @@
3
4
```javascript
5
function StoreLandingUnseenGiftModalContainer(a) {
6
- const giftsSeen = { a };
7
- return ((gift) => (gift.id ? giftsSeen[gift.id] : false))();
6
+ const giftsSeen = {a};
7
+ return (gift => (gift.id ? giftsSeen[gift.id] : false))();
8
}
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: StoreLandingUnseenGiftModalContainer,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-skip-computed-path.js
+4
-4
@@ -1,10 +1,10 @@
1
function StoreLandingUnseenGiftModalContainer(a) {
2
- const giftsSeen = { a };
3
- return ((gift) => (gift.id ? giftsSeen[gift.id] : false))();
2
+ const giftsSeen = {a};
3
+ return (gift => (gift.id ? giftsSeen[gift.id] : false))();
4
}
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: StoreLandingUnseenGiftModalContainer,
8
- params: ["TodoAdd"],
9
- isComponent: "TodoAdd",
8
+ params: ['TodoAdd'],
9
+ isComponent: 'TodoAdd',
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-within-block.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let z = { a };
6
+ let z = {a};
7
let x;
8
{
9
x = function () {
@@ -15,8 +15,8 @@ function component(a) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: component,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-function-within-block.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let z = { a };
2
+ let z = {a};
3
let x;
4
{
5
x = function () {
@@ -11,6 +11,6 @@ function component(a) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: component,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-member-expr.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let z = { a };
6
+ let z = {a};
7
let x = function () {
8
console.log(z.a);
9
};
@@ -12,8 +12,8 @@ function component(a) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: component,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-member-expr.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let z = { a };
2
+ let z = {a};
3
let x = function () {
4
console.log(z.a);
5
};
@@ -8,6 +8,6 @@ function component(a) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: component,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-nested-member-call.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let z = { a: { a } };
6
+ let z = {a: {a}};
7
let x = function () {
8
z.a.a();
9
};
@@ -12,8 +12,8 @@ function component(a) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: component,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-nested-member-call.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let z = { a: { a } };
2
+ let z = {a: {a}};
3
let x = function () {
4
z.a.a();
5
};
@@ -8,6 +8,6 @@ function component(a) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: component,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-nested-member-expr-in-nested-func.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let z = { a: { a } };
6
+ let z = {a: {a}};
7
let x = function () {
8
(function () {
9
console.log(z.a.a);
@@ -14,8 +14,8 @@ function component(a) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: component,
17
- params: ["TodoAdd"],
18
- isComponent: "TodoAdd",
17
+ params: ['TodoAdd'],
18
+ isComponent: 'TodoAdd',
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-nested-member-expr-in-nested-func.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let z = { a: { a } };
2
+ let z = {a: {a}};
3
let x = function () {
4
(function () {
5
console.log(z.a.a);
@@ -10,6 +10,6 @@ function component(a) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-nested-member-expr.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let z = { a: { a } };
6
+ let z = {a: {a}};
7
let x = function () {
8
console.log(z.a.a);
9
};
@@ -12,8 +12,8 @@ function component(a) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: component,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-nested-member-expr.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let z = { a: { a } };
2
+ let z = {a: {a}};
3
let x = function () {
4
console.log(z.a.a);
5
};
@@ -8,6 +8,6 @@ function component(a) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: component,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-reference-changes-type.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let x = { a };
6
+ let x = {a};
7
let y = 1;
8
(function () {
9
y = x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-reference-changes-type.js
+1
-1
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let x = { a };
2
+ let x = {a};
3
let y = 1;
4
(function () {
5
y = x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-variable-in-nested-block.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let z = { a };
6
+ let z = {a};
7
let x = function () {
8
{
9
console.log(z);
@@ -14,8 +14,8 @@ function component(a) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: component,
17
- params: ["TodoAdd"],
18
- isComponent: "TodoAdd",
17
+ params: ['TodoAdd'],
18
+ isComponent: 'TodoAdd',
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-variable-in-nested-block.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let z = { a };
2
+ let z = {a};
3
let x = function () {
4
{
5
console.log(z);
@@ -10,6 +10,6 @@ function component(a) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-variable-in-nested-function.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let z = { a };
6
+ let z = {a};
7
let x = function () {
8
(function () {
9
console.log(z);
@@ -14,8 +14,8 @@ function component(a) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: component,
17
- params: ["TodoAdd"],
18
- isComponent: "TodoAdd",
17
+ params: ['TodoAdd'],
18
+ isComponent: 'TodoAdd',
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-variable-in-nested-function.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let z = { a };
2
+ let z = {a};
3
let x = function () {
4
(function () {
5
console.log(z);
@@ -10,6 +10,6 @@ function component(a) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/chained-assignment-context-variable.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeArray } from "shared-runtime";
5
+import {makeArray} from 'shared-runtime';
6
7
function Component() {
8
let x,
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/chained-assignment-context-variable.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { makeArray } from "shared-runtime";
1
+import {makeArray} from 'shared-runtime';
2
3
function Component() {
4
let x,
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/chained-assignment-expressions.expect.md
+3
-3
@@ -3,9 +3,9 @@
3
4
```javascript
5
function foo() {
6
- const x = { x: 0 };
7
- const y = { z: 0 };
8
- const z = { z: 0 };
6
+ const x = {x: 0};
7
+ const y = {z: 0};
8
+ const z = {z: 0};
9
x.x += y.y *= 1;
10
z.z += y.y *= x.x &= 3;
11
return z;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/chained-assignment-expressions.js
+3
-3
@@ -1,7 +1,7 @@
1
function foo() {
2
- const x = { x: 0 };
3
- const y = { z: 0 };
4
- const z = { z: 0 };
2
+ const x = {x: 0};
3
+ const y = {z: 0};
4
+ const z = {z: 0};
5
x.x += y.y *= 1;
6
z.z += y.y *= x.x &= 3;
7
return z;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/codegen-instrument-forget-gating-test.expect.md
+2
-2
@@ -5,7 +5,7 @@
5
// @instrumentForget @compilationMode(annotation) @gating
6
7
function Bar(props) {
8
- "use forget";
8
+ 'use forget';
9
return <div>{props.bar}</div>;
10
}
11
@@ -14,7 +14,7 @@ function NoForget(props) {
14
}
15
16
function Foo(props) {
17
- "use forget";
17
+ 'use forget';
18
return <Foo>{props.bar}</Foo>;
19
}
20
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/codegen-instrument-forget-gating-test.js
+2
-2
@@ -1,7 +1,7 @@
1
// @instrumentForget @compilationMode(annotation) @gating
2
3
function Bar(props) {
4
- "use forget";
4
+ 'use forget';
5
return <div>{props.bar}</div>;
6
}
7
@@ -10,6 +10,6 @@ function NoForget(props) {
10
}
11
12
function Foo(props) {
13
- "use forget";
13
+ 'use forget';
14
return <Foo>{props.bar}</Foo>;
15
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/codegen-instrument-forget-test.expect.md
+2
-2
@@ -5,7 +5,7 @@
5
// @instrumentForget @compilationMode(annotation)
6
7
function Bar(props) {
8
- "use forget";
8
+ 'use forget';
9
return <div>{props.bar}</div>;
10
}
11
@@ -14,7 +14,7 @@ function NoForget(props) {
14
}
15
16
function Foo(props) {
17
- "use forget";
17
+ 'use forget';
18
return <Foo>{props.bar}</Foo>;
19
}
20
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/codegen-instrument-forget-test.js
+2
-2
@@ -1,7 +1,7 @@
1
// @instrumentForget @compilationMode(annotation)
2
3
function Bar(props) {
4
- "use forget";
4
+ 'use forget';
5
return <div>{props.bar}</div>;
6
}
7
@@ -10,6 +10,6 @@ function NoForget(props) {
10
}
11
12
function Foo(props) {
13
- "use forget";
13
+ 'use forget';
14
return <Foo>{props.bar}</Foo>;
15
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/complex-while.expect.md
+2
-2
@@ -15,8 +15,8 @@ function foo(a, b, c) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: foo,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/complex-while.js
+2
-2
@@ -11,6 +11,6 @@ function foo(a, b, c) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/component-inner-function-with-many-args.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
function Component(props) {
7
const cb = (x, y, z) => x + y + z;
8
@@ -11,7 +11,7 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ id: 0 }],
14
+ params: [{id: 0}],
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/component-inner-function-with-many-args.tsx
+2
-2
@@ -1,4 +1,4 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
function Component(props) {
3
const cb = (x, y, z) => x + y + z;
4
@@ -7,5 +7,5 @@ function Component(props) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: [{ id: 0 }],
10
+ params: [{id: 0}],
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/component.expect.md
+2
-2
@@ -31,8 +31,8 @@ function Component(props) {
31
32
export const FIXTURE_ENTRYPOINT = {
33
fn: Component,
34
- params: ["TodoAdd"],
35
- isComponent: "TodoAdd",
34
+ params: ['TodoAdd'],
35
+ isComponent: 'TodoAdd',
36
};
37
38
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/component.js
+2
-2
@@ -27,6 +27,6 @@ function Component(props) {
27
28
export const FIXTURE_ENTRYPOINT = {
29
fn: Component,
30
- params: ["TodoAdd"],
31
- isComponent: "TodoAdd",
30
+ params: ['TodoAdd'],
31
+ isComponent: 'TodoAdd',
32
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/computed-call-evaluation-order.expect.md
+5
-5
@@ -4,15 +4,15 @@
4
```javascript
5
// Should print A, B, arg, original
6
function Component() {
7
- const changeF = (o) => {
8
- o.f = () => console.log("new");
7
+ const changeF = o => {
8
+ o.f = () => console.log('new');
9
};
10
const x = {
11
- f: () => console.log("original"),
11
+ f: () => console.log('original'),
12
};
13
14
- (console.log("A"), x)[(console.log("B"), "f")](
15
- (changeF(x), console.log("arg"), 1)
14
+ (console.log('A'), x)[(console.log('B'), 'f')](
15
+ (changeF(x), console.log('arg'), 1)
16
);
17
return x;
18
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/computed-call-evaluation-order.js
+5
-5
@@ -1,14 +1,14 @@
1
// Should print A, B, arg, original
2
function Component() {
3
- const changeF = (o) => {
4
- o.f = () => console.log("new");
3
+ const changeF = o => {
4
+ o.f = () => console.log('new');
5
};
6
const x = {
7
- f: () => console.log("original"),
7
+ f: () => console.log('original'),
8
};
9
10
- (console.log("A"), x)[(console.log("B"), "f")](
11
- (changeF(x), console.log("arg"), 1)
10
+ (console.log('A'), x)[(console.log('B'), 'f')](
11
+ (changeF(x), console.log('arg'), 1)
12
);
13
return x;
14
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/computed-store-alias.expect.md
+3
-3
@@ -3,9 +3,9 @@
3
4
```javascript
5
function component(a, b) {
6
- let y = { a };
7
- let x = { b };
8
- x["y"] = y;
6
+ let y = {a};
7
+ let x = {b};
8
+ x['y'] = y;
9
mutate(x);
10
return x;
11
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/computed-store-alias.js
+3
-3
@@ -1,7 +1,7 @@
1
function component(a, b) {
2
- let y = { a };
3
- let x = { b };
4
- x["y"] = y;
2
+ let y = {a};
3
+ let x = {b};
4
+ x['y'] = y;
5
mutate(x);
6
return x;
7
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/concise-arrow-expr.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
function component() {
6
let [x, setX] = useState(0);
7
- const handler = (v) => setX(v);
7
+ const handler = v => setX(v);
8
return <Foo handler={handler}></Foo>;
9
}
10
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/concise-arrow-expr.js
+1
-1
@@ -1,5 +1,5 @@
1
function component() {
2
let [x, setX] = useState(0);
3
- const handler = (v) => setX(v);
3
+ const handler = v => setX(v);
4
return <Foo handler={handler}></Foo>;
5
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/conditional-break-labeled.expect.md
+2
-2
@@ -20,8 +20,8 @@ function Component(props) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
- params: ["TodoAdd"],
24
- isComponent: "TodoAdd",
23
+ params: ['TodoAdd'],
24
+ isComponent: 'TodoAdd',
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/conditional-break-labeled.js
+2
-2
@@ -16,6 +16,6 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: ["TodoAdd"],
20
- isComponent: "TodoAdd",
19
+ params: ['TodoAdd'],
20
+ isComponent: 'TodoAdd',
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/conditional-early-return.expect.md
+1
-1
@@ -58,7 +58,7 @@ function ComponentD(props) {
58
59
export const FIXTURE_ENTRYPOINT = {
60
fn: ComponentA,
61
- params: [{ a: 1, b: false, d: 3 }],
61
+ params: [{a: 1, b: false, d: 3}],
62
};
63
64
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/conditional-early-return.js
+1
-1
@@ -54,5 +54,5 @@ function ComponentD(props) {
54
55
export const FIXTURE_ENTRYPOINT = {
56
fn: ComponentA,
57
- params: [{ a: 1, b: false, d: 3 }],
57
+ params: [{a: 1, b: false, d: 3}],
58
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/conditional-set-state-in-render.expect.md
+2
-2
@@ -19,8 +19,8 @@ function Component(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: ["TodoAdd"],
23
- isComponent: "TodoAdd",
22
+ params: ['TodoAdd'],
23
+ isComponent: 'TodoAdd',
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/conditional-set-state-in-render.js
+2
-2
@@ -15,6 +15,6 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/conflicting-dollar-sign-variable.expect.md
+2
-2
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
function Component(props) {
8
- const $ = identity("jQuery");
8
+ const $ = identity('jQuery');
9
const t0 = identity([$]);
10
return t0;
11
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/conflicting-dollar-sign-variable.js
+2
-2
@@ -1,7 +1,7 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
function Component(props) {
4
- const $ = identity("jQuery");
4
+ const $ = identity('jQuery');
5
const t0 = identity([$]);
6
return t0;
7
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/consecutive-use-memo.expect.md
+5
-5
@@ -2,18 +2,18 @@
2
## Input
3
4
```javascript
5
-import { useMemo } from "react";
6
-import { identity } from "shared-runtime";
5
+import {useMemo} from 'react';
6
+import {identity} from 'shared-runtime';
7
8
-function useHook({ a, b }) {
9
- const valA = useMemo(() => identity({ a }), [a]);
8
+function useHook({a, b}) {
9
+ const valA = useMemo(() => identity({a}), [a]);
10
const valB = useMemo(() => identity([b]), [b]);
11
return [valA, valB];
12
}
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: useHook,
16
- params: [{ a: 2, b: 3 }],
16
+ params: [{a: 2, b: 3}],
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/consecutive-use-memo.ts
+5
-5
@@ -1,13 +1,13 @@
1
-import { useMemo } from "react";
2
-import { identity } from "shared-runtime";
1
+import {useMemo} from 'react';
2
+import {identity} from 'shared-runtime';
3
4
-function useHook({ a, b }) {
5
- const valA = useMemo(() => identity({ a }), [a]);
4
+function useHook({a, b}) {
5
+ const valA = useMemo(() => identity({a}), [a]);
6
const valB = useMemo(() => identity([b]), [b]);
7
return [valA, valB];
8
}
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: useHook,
12
- params: [{ a: 2, b: 3 }],
12
+ params: [{a: 2, b: 3}],
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/console-readonly.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { shallowCopy } from "shared-runtime";
5
+import {shallowCopy} from 'shared-runtime';
6
7
function Component(props) {
8
const x = shallowCopy(props);
@@ -18,7 +18,7 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ a: 1, b: 2 }],
21
+ params: [{a: 1, b: 2}],
22
isComponent: false,
23
};
24
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/console-readonly.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { shallowCopy } from "shared-runtime";
1
+import {shallowCopy} from 'shared-runtime';
2
3
function Component(props) {
4
const x = shallowCopy(props);
@@ -14,6 +14,6 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ a: 1, b: 2 }],
17
+ params: [{a: 1, b: 2}],
18
isComponent: false,
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/const-propagation-phi-nodes.expect.md
+1
-1
@@ -13,7 +13,7 @@ function useFoo(setOne: boolean) {
13
y = 3;
14
z = 5;
15
}
16
- return { x, y, z };
16
+ return {x, y, z};
17
}
18
19
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/const-propagation-phi-nodes.ts
+1
-1
@@ -9,7 +9,7 @@ function useFoo(setOne: boolean) {
9
y = 3;
10
z = 5;
11
}
12
- return { x, y, z };
12
+ return {x, y, z};
13
}
14
15
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-computed.expect.md
+4
-4
@@ -3,17 +3,17 @@
3
4
```javascript
5
function Component(props) {
6
- const index = "foo";
6
+ const index = 'foo';
7
const x = {};
8
- x[index] = x[index] + x["bar"];
8
+ x[index] = x[index] + x['bar'];
9
x[index](props.foo);
10
return x;
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-computed.js
+4
-4
@@ -1,13 +1,13 @@
1
function Component(props) {
2
- const index = "foo";
2
+ const index = 'foo';
3
const x = {};
4
- x[index] = x[index] + x["bar"];
4
+ x[index] = x[index] + x['bar'];
5
x[index](props.foo);
6
return x;
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-prop-across-objectmethod-def.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
// repro for context identifier scoping bug, in which x was
8
// inferred as a context variable.
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-prop-across-objectmethod-def.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
// repro for context identifier scoping bug, in which x was
4
// inferred as a context variable.
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-prop-colliding-identifier.expect.md
+2
-2
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-import { invoke } from "shared-runtime";
5
+import {invoke} from 'shared-runtime';
6
7
function Component() {
8
let x = 2;
9
const fn = () => {
10
- return { x: "value" };
10
+ return {x: 'value'};
11
};
12
invoke(fn);
13
x = 3;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-prop-colliding-identifier.js
+2
-2
@@ -1,9 +1,9 @@
1
-import { invoke } from "shared-runtime";
1
+import {invoke} from 'shared-runtime';
2
3
function Component() {
4
let x = 2;
5
const fn = () => {
6
- return { x: "value" };
6
+ return {x: 'value'};
7
};
8
invoke(fn);
9
x = 3;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-prop-to-object-method.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
function Foo() {
8
const CONSTANT = 1;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-prop-to-object-method.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
function Foo() {
4
const CONSTANT = 1;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagate-global-phis-constant.expect.md
+4
-4
@@ -2,14 +2,14 @@
2
## Input
3
4
```javascript
5
-import { CONST_STRING0, Text } from "shared-runtime";
5
+import {CONST_STRING0, Text} from 'shared-runtime';
6
function useFoo() {
7
- "use no forget";
8
- return { tab: CONST_STRING0 };
7
+ 'use no forget';
8
+ return {tab: CONST_STRING0};
9
}
10
11
function Test() {
12
- const { tab } = useFoo();
12
+ const {tab} = useFoo();
13
const currentTab = tab === CONST_STRING0 ? CONST_STRING0 : CONST_STRING0;
14
15
return <Text value={currentTab} />;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagate-global-phis-constant.js
+4
-4
@@ -1,11 +1,11 @@
1
-import { CONST_STRING0, Text } from "shared-runtime";
1
+import {CONST_STRING0, Text} from 'shared-runtime';
2
function useFoo() {
3
- "use no forget";
4
- return { tab: CONST_STRING0 };
3
+ 'use no forget';
4
+ return {tab: CONST_STRING0};
5
}
6
7
function Test() {
8
- const { tab } = useFoo();
8
+ const {tab} = useFoo();
9
const currentTab = tab === CONST_STRING0 ? CONST_STRING0 : CONST_STRING0;
10
11
return <Text value={currentTab} />;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagate-global-phis.expect.md
+4
-4
@@ -2,15 +2,15 @@
2
## Input
3
4
```javascript
5
-import { CONST_STRING0, CONST_STRING1, Text } from "shared-runtime";
5
+import {CONST_STRING0, CONST_STRING1, Text} from 'shared-runtime';
6
7
function useFoo() {
8
- "use no forget";
9
- return { tab: CONST_STRING1 };
8
+ 'use no forget';
9
+ return {tab: CONST_STRING1};
10
}
11
12
function Test() {
13
- const { tab } = useFoo();
13
+ const {tab} = useFoo();
14
const currentTab = tab === CONST_STRING0 ? CONST_STRING0 : CONST_STRING1;
15
16
return <Text value={currentTab} />;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagate-global-phis.js
+4
-4
@@ -1,12 +1,12 @@
1
-import { CONST_STRING0, CONST_STRING1, Text } from "shared-runtime";
1
+import {CONST_STRING0, CONST_STRING1, Text} from 'shared-runtime';
2
3
function useFoo() {
4
- "use no forget";
5
- return { tab: CONST_STRING1 };
4
+ 'use no forget';
5
+ return {tab: CONST_STRING1};
6
}
7
8
function Test() {
9
- const { tab } = useFoo();
9
+ const {tab} = useFoo();
10
const currentTab = tab === CONST_STRING0 ? CONST_STRING0 : CONST_STRING1;
11
12
return <Text value={currentTab} />;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagation-bit-ops.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
function foo() {
8
return (
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagation-bit-ops.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
function foo() {
4
return (
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagation-phi.expect.md
+2
-2
@@ -18,8 +18,8 @@ function foo(a, b, c) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: foo,
21
- params: ["TodoAdd"],
22
- isComponent: "TodoAdd",
21
+ params: ['TodoAdd'],
22
+ isComponent: 'TodoAdd',
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagation-phi.js
+2
-2
@@ -14,6 +14,6 @@ function foo(a, b, c) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: foo,
17
- params: ["TodoAdd"],
18
- isComponent: "TodoAdd",
17
+ params: ['TodoAdd'],
18
+ isComponent: 'TodoAdd',
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagation-string-concat.expect.md
+2
-2
@@ -3,8 +3,8 @@
3
4
```javascript
5
function foo() {
6
- const a = "a" + "b";
7
- const c = "c";
6
+ const a = 'a' + 'b';
7
+ const c = 'c';
8
return a + c;
9
}
10
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagation-string-concat.js
+2
-2
@@ -1,6 +1,6 @@
1
function foo() {
2
- const a = "a" + "b";
3
- const c = "c";
2
+ const a = 'a' + 'b';
3
+ const c = 'c';
4
return a + c;
5
}
6
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagation-unary.expect.md
+6
-6
@@ -2,15 +2,15 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
function foo() {
8
let _b;
9
const b = true;
10
if (!b) {
11
- _b = "bar";
11
+ _b = 'bar';
12
} else {
13
- _b = "baz";
13
+ _b = 'baz';
14
}
15
16
return (
@@ -22,9 +22,9 @@ function foo() {
22
n1: !1,
23
n2: !2,
24
n3: !-1,
25
- s0: !"",
26
- s1: !"a",
27
- s2: !"ab",
25
+ s0: !'',
26
+ s1: !'a',
27
+ s2: !'ab',
28
u: !undefined,
29
n: !null,
30
}}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagation-unary.js
+6
-6
@@ -1,12 +1,12 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
function foo() {
4
let _b;
5
const b = true;
6
if (!b) {
7
- _b = "bar";
7
+ _b = 'bar';
8
} else {
9
- _b = "baz";
9
+ _b = 'baz';
10
}
11
12
return (
@@ -18,9 +18,9 @@ function foo() {
18
n1: !1,
19
n2: !2,
20
n3: !-1,
21
- s0: !"",
22
- s1: !"a",
23
- s2: !"ab",
21
+ s0: !'',
22
+ s1: !'a',
23
+ s2: !'ab',
24
u: !undefined,
25
n: !null,
26
}}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagation.expect.md
+1
-1
@@ -12,7 +12,7 @@ function foo() {
12
const g = f - e;
13
14
if (g) {
15
- console.log("foo");
15
+ console.log('foo');
16
}
17
18
const h = g;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/constant-propagation.js
+1
-1
@@ -8,7 +8,7 @@ function foo() {
8
const g = f - e;
9
10
if (g) {
11
- console.log("foo");
11
+ console.log('foo');
12
}
13
14
const h = g;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-as-jsx-element-tag.expect.md
+3
-3
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import { useMemo } from "react";
6
-import { Stringify } from "shared-runtime";
5
+import {useMemo} from 'react';
6
+import {Stringify} from 'shared-runtime';
7
8
function Component(props) {
9
let Component = Stringify;
@@ -17,7 +17,7 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ name: "Sathya" }],
20
+ params: [{name: 'Sathya'}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-as-jsx-element-tag.js
+3
-3
@@ -1,5 +1,5 @@
1
-import { useMemo } from "react";
2
-import { Stringify } from "shared-runtime";
1
+import {useMemo} from 'react';
2
+import {Stringify} from 'shared-runtime';
3
4
function Component(props) {
5
let Component = Stringify;
@@ -13,5 +13,5 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ name: "Sathya" }],
16
+ params: [{name: 'Sathya'}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-only-chained-assign.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity, invoke } from "shared-runtime";
5
+import {identity, invoke} from 'shared-runtime';
6
7
function foo() {
8
let x = 2;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-only-chained-assign.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { identity, invoke } from "shared-runtime";
1
+import {identity, invoke} from 'shared-runtime';
2
3
function foo() {
4
let x = 2;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-reactive-explicit-control-flow.expect.md
+4
-4
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { invoke } from "shared-runtime";
5
+import {invoke} from 'shared-runtime';
6
7
-function Component({ shouldReassign }) {
7
+function Component({shouldReassign}) {
8
let x = null;
9
const reassign = () => {
10
if (shouldReassign) {
@@ -17,8 +17,8 @@ function Component({ shouldReassign }) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ shouldReassign: true }],
21
- sequentialRenders: [{ shouldReassign: false }, { shouldReassign: true }],
20
+ params: [{shouldReassign: true}],
21
+ sequentialRenders: [{shouldReassign: false}, {shouldReassign: true}],
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-reactive-explicit-control-flow.js
+4
-4
@@ -1,6 +1,6 @@
1
-import { invoke } from "shared-runtime";
1
+import {invoke} from 'shared-runtime';
2
3
-function Component({ shouldReassign }) {
3
+function Component({shouldReassign}) {
4
let x = null;
5
const reassign = () => {
6
if (shouldReassign) {
@@ -13,6 +13,6 @@ function Component({ shouldReassign }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ shouldReassign: true }],
17
- sequentialRenders: [{ shouldReassign: false }, { shouldReassign: true }],
16
+ params: [{shouldReassign: true}],
17
+ sequentialRenders: [{shouldReassign: false}, {shouldReassign: true}],
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-reactive-implicit-control-flow.expect.md
+4
-4
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-import { conditionalInvoke } from "shared-runtime";
5
+import {conditionalInvoke} from 'shared-runtime';
6
7
// same as context-variable-reactive-explicit-control-flow.js, but make
8
// the control flow implicit
9
10
-function Component({ shouldReassign }) {
10
+function Component({shouldReassign}) {
11
let x = null;
12
const reassign = () => {
13
x = 2;
@@ -18,8 +18,8 @@ function Component({ shouldReassign }) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ shouldReassign: true }],
22
- sequentialRenders: [{ shouldReassign: false }, { shouldReassign: true }],
21
+ params: [{shouldReassign: true}],
22
+ sequentialRenders: [{shouldReassign: false}, {shouldReassign: true}],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-reactive-implicit-control-flow.js
+4
-4
@@ -1,9 +1,9 @@
1
-import { conditionalInvoke } from "shared-runtime";
1
+import {conditionalInvoke} from 'shared-runtime';
2
3
// same as context-variable-reactive-explicit-control-flow.js, but make
4
// the control flow implicit
5
6
-function Component({ shouldReassign }) {
6
+function Component({shouldReassign}) {
7
let x = null;
8
const reassign = () => {
9
x = 2;
@@ -14,6 +14,6 @@ function Component({ shouldReassign }) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ shouldReassign: true }],
18
- sequentialRenders: [{ shouldReassign: false }, { shouldReassign: true }],
17
+ params: [{shouldReassign: true}],
18
+ sequentialRenders: [{shouldReassign: false}, {shouldReassign: true}],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-reassigned-objectmethod.expect.md
+3
-3
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { invoke } from "shared-runtime";
5
+import {invoke} from 'shared-runtime';
6
7
-function Component({ cond }) {
7
+function Component({cond}) {
8
let x = 2;
9
const obj = {
10
method(cond) {
@@ -19,7 +19,7 @@ function Component({ cond }) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: [{ cond: true }],
22
+ params: [{cond: true}],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-reassigned-objectmethod.js
+3
-3
@@ -1,6 +1,6 @@
1
-import { invoke } from "shared-runtime";
1
+import {invoke} from 'shared-runtime';
2
3
-function Component({ cond }) {
3
+function Component({cond}) {
4
let x = 2;
5
const obj = {
6
method(cond) {
@@ -15,5 +15,5 @@ function Component({ cond }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ cond: true }],
18
+ params: [{cond: true}],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-reassigned-outside-of-lambda.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
function Component(props) {
8
let x = null;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-reassigned-outside-of-lambda.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
function Component(props) {
4
let x = null;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-reassigned-reactive-capture.expect.md
+4
-4
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { invoke } from "shared-runtime";
5
+import {invoke} from 'shared-runtime';
6
7
-function Component({ value }) {
7
+function Component({value}) {
8
let x = null;
9
const reassign = () => {
10
x = value;
@@ -15,8 +15,8 @@ function Component({ value }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ value: 2 }],
19
- sequentialRenders: [{ value: 2 }, { value: 4 }],
18
+ params: [{value: 2}],
19
+ sequentialRenders: [{value: 2}, {value: 4}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-reassigned-reactive-capture.js
+4
-4
@@ -1,6 +1,6 @@
1
-import { invoke } from "shared-runtime";
1
+import {invoke} from 'shared-runtime';
2
3
-function Component({ value }) {
3
+function Component({value}) {
4
let x = null;
5
const reassign = () => {
6
x = value;
@@ -11,6 +11,6 @@ function Component({ value }) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ value: 2 }],
15
- sequentialRenders: [{ value: 2 }, { value: 4 }],
14
+ params: [{value: 2}],
15
+ sequentialRenders: [{value: 2}, {value: 4}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-reassigned-two-lambdas.expect.md
+6
-6
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { conditionalInvoke } from "shared-runtime";
5
+import {conditionalInvoke} from 'shared-runtime';
6
7
-function Component({ doReassign1, doReassign2 }) {
7
+function Component({doReassign1, doReassign2}) {
8
let x = {};
9
const reassign1 = () => {
10
x = 2;
@@ -19,11 +19,11 @@ function Component({ doReassign1, doReassign2 }) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: [{ doReassign1: true, doReassign2: true }],
22
+ params: [{doReassign1: true, doReassign2: true}],
23
sequentialRenders: [
24
- { doReassign1: true, doReassign2: true },
25
- { doReassign1: true, doReassign2: false },
26
- { doReassign1: false, doReassign2: false },
24
+ {doReassign1: true, doReassign2: true},
25
+ {doReassign1: true, doReassign2: false},
26
+ {doReassign1: false, doReassign2: false},
27
],
28
};
29
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/context-variable-reassigned-two-lambdas.js
+6
-6
@@ -1,6 +1,6 @@
1
-import { conditionalInvoke } from "shared-runtime";
1
+import {conditionalInvoke} from 'shared-runtime';
2
3
-function Component({ doReassign1, doReassign2 }) {
3
+function Component({doReassign1, doReassign2}) {
4
let x = {};
5
const reassign1 = () => {
6
x = 2;
@@ -15,10 +15,10 @@ function Component({ doReassign1, doReassign2 }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ doReassign1: true, doReassign2: true }],
18
+ params: [{doReassign1: true, doReassign2: true}],
19
sequentialRenders: [
20
- { doReassign1: true, doReassign2: true },
21
- { doReassign1: true, doReassign2: false },
22
- { doReassign1: false, doReassign2: false },
20
+ {doReassign1: true, doReassign2: true},
21
+ {doReassign1: true, doReassign2: false},
22
+ {doReassign1: false, doReassign2: false},
23
],
24
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/controlled-input.expect.md
+2
-2
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { useState } from "react";
5
+import {useState} from 'react';
6
function component() {
7
let [x, setX] = useState(0);
8
- const handler = (event) => setX(event.target.value);
8
+ const handler = event => setX(event.target.value);
9
return <input onChange={handler} value={x} />;
10
}
11
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/controlled-input.js
+2
-2
@@ -1,7 +1,7 @@
1
-import { useState } from "react";
1
+import {useState} from 'react';
2
function component() {
3
let [x, setX] = useState(0);
4
- const handler = (event) => setX(event.target.value);
4
+ const handler = event => setX(event.target.value);
5
return <input onChange={handler} value={x} />;
6
}
7
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/createElement-freeze.expect.md
+4
-4
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-import React from "react";
6
-import { shallowCopy } from "shared-runtime";
5
+import React from 'react';
6
+import {shallowCopy} from 'shared-runtime';
7
8
function Component(props) {
9
- const childProps = { style: { width: props.width } };
10
- const element = React.createElement("div", childProps, ["hello world"]);
9
+ const childProps = {style: {width: props.width}};
10
+ const element = React.createElement('div', childProps, ['hello world']);
11
shallowCopy(childProps); // function that in theory could mutate, we assume not bc createElement freezes
12
return element;
13
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/createElement-freeze.js
+4
-4
@@ -1,9 +1,9 @@
1
-import React from "react";
2
-import { shallowCopy } from "shared-runtime";
1
+import React from 'react';
2
+import {shallowCopy} from 'shared-runtime';
3
4
function Component(props) {
5
- const childProps = { style: { width: props.width } };
6
- const element = React.createElement("div", childProps, ["hello world"]);
5
+ const childProps = {style: {width: props.width}};
6
+ const element = React.createElement('div', childProps, ['hello world']);
7
shallowCopy(childProps); // function that in theory could mutate, we assume not bc createElement freezes
8
return element;
9
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dce-loop.expect.md
+1
-1
@@ -14,7 +14,7 @@ function foo(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: foo,
17
- params: [{ max: 10 }],
17
+ params: [{max: 10}],
18
isComponent: false,
19
};
20
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dce-loop.js
+1
-1
@@ -10,6 +10,6 @@ function foo(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: foo,
13
- params: [{ max: 10 }],
13
+ params: [{max: 10}],
14
isComponent: false,
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dce-unused-const.expect.md
+1
-1
@@ -9,7 +9,7 @@ function Component(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: [{ value: 42 }],
12
+ params: [{value: 42}],
13
};
14
15
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dce-unused-const.js
+1
-1
@@ -5,5 +5,5 @@ function Component(props) {
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: Component,
8
- params: [{ value: 42 }],
8
+ params: [{value: 42}],
9
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dce-unused-postfix-update.expect.md
+1
-1
@@ -11,7 +11,7 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ i: 42 }],
14
+ params: [{i: 42}],
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dce-unused-postfix-update.js
+1
-1
@@ -7,5 +7,5 @@ function Component(props) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: [{ i: 42 }],
10
+ params: [{i: 42}],
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dce-unused-prefix-update.expect.md
+1
-1
@@ -11,7 +11,7 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ i: 42 }],
14
+ params: [{i: 42}],
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dce-unused-prefix-update.js
+1
-1
@@ -7,5 +7,5 @@ function Component(props) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: [{ i: 42 }],
10
+ params: [{i: 42}],
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/debugger-memoized.expect.md
+2
-2
@@ -11,8 +11,8 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/debugger-memoized.js
+2
-2
@@ -7,6 +7,6 @@ function Component(props) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: ["TodoAdd"],
11
- isComponent: "TodoAdd",
10
+ params: ['TodoAdd'],
11
+ isComponent: 'TodoAdd',
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/debugger.expect.md
+2
-2
@@ -16,8 +16,8 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: ["TodoAdd"],
20
- isComponent: "TodoAdd",
19
+ params: ['TodoAdd'],
20
+ isComponent: 'TodoAdd',
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/debugger.js
+2
-2
@@ -12,6 +12,6 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/declare-reassign-variable-in-closure.expect.md
+2
-2
@@ -14,8 +14,8 @@ function Component(p) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: ["TodoAdd"],
18
- isComponent: "TodoAdd",
17
+ params: ['TodoAdd'],
18
+ isComponent: 'TodoAdd',
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/declare-reassign-variable-in-closure.js
+2
-2
@@ -10,6 +10,6 @@ function Component(p) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/default-param-calls-global-function.expect.md
+2
-2
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
-function Component(x = identity([() => {}, true, 42, "hello"])) {
7
+function Component(x = identity([() => {}, true, 42, 'hello'])) {
8
return x;
9
}
10
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/default-param-calls-global-function.js
+2
-2
@@ -1,6 +1,6 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
-function Component(x = identity([() => {}, true, 42, "hello"])) {
3
+function Component(x = identity([() => {}, true, 42, 'hello'])) {
4
return x;
5
}
6
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/default-param-with-reorderable-callback.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function Component(x = () => [-1, true, 42.0, "hello"]) {
5
+function Component(x = () => [-1, true, 42.0, 'hello']) {
6
return x;
7
}
8
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/default-param-with-reorderable-callback.js
+1
-1
@@ -1,4 +1,4 @@
1
-function Component(x = () => [-1, true, 42.0, "hello"]) {
1
+function Component(x = () => [-1, true, 42.0, 'hello']) {
2
return x;
3
}
4
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/delete-computed-property.expect.md
+4
-4
@@ -3,16 +3,16 @@
3
4
```javascript
5
function Component(props) {
6
- const x = { a: props.a, b: props.b };
7
- const key = "b";
6
+ const x = {a: props.a, b: props.b};
7
+ const key = 'b';
8
delete x[key];
9
return x;
10
}
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/delete-computed-property.js
+4
-4
@@ -1,12 +1,12 @@
1
function Component(props) {
2
- const x = { a: props.a, b: props.b };
3
- const key = "b";
2
+ const x = {a: props.a, b: props.b};
3
+ const key = 'b';
4
delete x[key];
5
return x;
6
}
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: ["TodoAdd"],
11
- isComponent: "TodoAdd",
10
+ params: ['TodoAdd'],
11
+ isComponent: 'TodoAdd',
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/delete-property.expect.md
+3
-3
@@ -3,15 +3,15 @@
3
4
```javascript
5
function Component(props) {
6
- const x = { a: props.a, b: props.b };
6
+ const x = {a: props.a, b: props.b};
7
delete x.b;
8
return x;
9
}
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/delete-property.js
+3
-3
@@ -1,11 +1,11 @@
1
function Component(props) {
2
- const x = { a: props.a, b: props.b };
2
+ const x = {a: props.a, b: props.b};
3
delete x.b;
4
return x;
5
}
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dependencies-outputs.expect.md
+2
-2
@@ -19,8 +19,8 @@ function foo(a, b) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: foo,
22
- params: ["TodoAdd"],
23
- isComponent: "TodoAdd",
22
+ params: ['TodoAdd'],
23
+ isComponent: 'TodoAdd',
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dependencies-outputs.js
+2
-2
@@ -15,6 +15,6 @@ function foo(a, b) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: foo,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dependencies.expect.md
+2
-2
@@ -20,8 +20,8 @@ function foo(x, y, z) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: foo,
23
- params: ["TodoAdd"],
24
- isComponent: "TodoAdd",
23
+ params: ['TodoAdd'],
24
+ isComponent: 'TodoAdd',
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dependencies.js
+2
-2
@@ -16,6 +16,6 @@ function foo(x, y, z) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: foo,
19
- params: ["TodoAdd"],
20
- isComponent: "TodoAdd",
19
+ params: ['TodoAdd'],
20
+ isComponent: 'TodoAdd',
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-array-assignment-to-context-var.expect.md
+3
-3
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
function Component(props) {
8
let x;
@@ -11,12 +11,12 @@ function Component(props) {
11
x = identity(props.value[0]);
12
};
13
foo();
14
- return { x };
14
+ return {x};
15
}
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ value: [42] }],
19
+ params: [{value: [42]}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-array-assignment-to-context-var.js
+3
-3
@@ -1,4 +1,4 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
function Component(props) {
4
let x;
@@ -7,10 +7,10 @@ function Component(props) {
7
x = identity(props.value[0]);
8
};
9
foo();
10
- return { x };
10
+ return {x};
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ value: [42] }],
15
+ params: [{value: [42]}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-array-declaration-to-context-var.expect.md
+3
-3
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
function Component(props) {
8
let [x] = props.value;
@@ -10,12 +10,12 @@ function Component(props) {
10
x = identity(props.value[0]);
11
};
12
foo();
13
- return { x };
13
+ return {x};
14
}
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ value: [42] }],
18
+ params: [{value: [42]}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-array-declaration-to-context-var.js
+3
-3
@@ -1,4 +1,4 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
function Component(props) {
4
let [x] = props.value;
@@ -6,10 +6,10 @@ function Component(props) {
6
x = identity(props.value[0]);
7
};
8
foo();
9
- return { x };
9
+ return {x};
10
}
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ value: [42] }],
14
+ params: [{value: [42]}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-capture-global.expect.md
+2
-2
@@ -4,13 +4,13 @@
4
```javascript
5
let someGlobal = {};
6
function component(a) {
7
- let x = { a, someGlobal };
7
+ let x = {a, someGlobal};
8
return x;
9
}
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: component,
13
- params: ["value 1"],
13
+ params: ['value 1'],
14
isComponent: false,
15
};
16
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-capture-global.js
+2
-2
@@ -1,11 +1,11 @@
1
let someGlobal = {};
2
function component(a) {
3
- let x = { a, someGlobal };
3
+ let x = {a, someGlobal};
4
return x;
5
}
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: component,
9
- params: ["value 1"],
9
+ params: ['value 1'],
10
isComponent: false,
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-default-array-with-unary.expect.md
+1
-1
@@ -9,7 +9,7 @@ function Component(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: [{ value: [] }],
12
+ params: [{value: []}],
13
};
14
15
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-default-array-with-unary.js
+1
-1
@@ -5,5 +5,5 @@ function Component(props) {
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: Component,
8
- params: [{ value: [] }],
8
+ params: [{value: []}],
9
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-direct-reassignment.expect.md
+3
-3
@@ -4,7 +4,7 @@
4
```javascript
5
function foo(props) {
6
let x, y;
7
- ({ x, y } = { x: props.a, y: props.b });
7
+ ({x, y} = {x: props.a, y: props.b});
8
console.log(x); // prevent DCE from eliminating `x` altogether
9
x = props.c;
10
return x + y;
@@ -12,8 +12,8 @@ function foo(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: foo,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-direct-reassignment.js
+3
-3
@@ -1,6 +1,6 @@
1
function foo(props) {
2
let x, y;
3
- ({ x, y } = { x: props.a, y: props.b });
3
+ ({x, y} = {x: props.a, y: props.b});
4
console.log(x); // prevent DCE from eliminating `x` altogether
5
x = props.c;
6
return x + y;
@@ -8,6 +8,6 @@ function foo(props) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: foo,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-in-branch-ssa.expect.md
+2
-2
@@ -13,7 +13,7 @@ function useFoo(props: {
13
let z = null;
14
const myList = [];
15
if (props.doDestructure) {
16
- ({ x, y, z } = props);
16
+ ({x, y, z} = props);
17
18
myList.push(z);
19
}
@@ -26,7 +26,7 @@ function useFoo(props: {
26
27
export const FIXTURE_ENTRYPOINT = {
28
fn: useFoo,
29
- params: [{ x: "hello", y: "world", doDestructure: true }],
29
+ params: [{x: 'hello', y: 'world', doDestructure: true}],
30
};
31
32
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-in-branch-ssa.ts
+2
-2
@@ -9,7 +9,7 @@ function useFoo(props: {
9
let z = null;
10
const myList = [];
11
if (props.doDestructure) {
12
- ({ x, y, z } = props);
12
+ ({x, y, z} = props);
13
14
myList.push(z);
15
}
@@ -22,5 +22,5 @@ function useFoo(props: {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: useFoo,
25
- params: [{ x: "hello", y: "world", doDestructure: true }],
25
+ params: [{x: 'hello', y: 'world', doDestructure: true}],
26
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-mixed-property-key-types.expect.md
+1
-5
@@ -3,11 +3,7 @@
3
4
```javascript
5
function foo() {
6
- const {
7
- "data-foo-bar": x,
8
- a: y,
9
- data: z,
10
- } = { "data-foo-bar": 1, a: 2, data: 3 };
6
+ const {'data-foo-bar': x, a: y, data: z} = {'data-foo-bar': 1, a: 2, data: 3};
7
return [x, y, z];
8
}
9
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-mixed-property-key-types.js
+1
-5
@@ -1,9 +1,5 @@
1
function foo() {
2
- const {
3
- "data-foo-bar": x,
4
- a: y,
5
- data: z,
6
- } = { "data-foo-bar": 1, a: 2, data: 3 };
2
+ const {'data-foo-bar': x, a: y, data: z} = {'data-foo-bar': 1, a: 2, data: 3};
3
return [x, y, z];
4
}
5
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-object-assignment-to-context-var.expect.md
+4
-4
@@ -2,21 +2,21 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
function Component(props) {
8
let x;
9
- ({ x } = props);
9
+ ({x} = props);
10
const foo = () => {
11
x = identity(props.x);
12
};
13
foo();
14
- return { x };
14
+ return {x};
15
}
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ x: 42 }],
19
+ params: [{x: 42}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-object-assignment-to-context-var.js
+4
-4
@@ -1,16 +1,16 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
function Component(props) {
4
let x;
5
- ({ x } = props);
5
+ ({x} = props);
6
const foo = () => {
7
x = identity(props.x);
8
};
9
foo();
10
- return { x };
10
+ return {x};
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ x: 42 }],
15
+ params: [{x: 42}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-object-declaration-to-context-var.expect.md
+4
-4
@@ -2,20 +2,20 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
function Component(props) {
8
- let { x } = props;
8
+ let {x} = props;
9
const foo = () => {
10
x = identity(props.x);
11
};
12
foo();
13
- return { x };
13
+ return {x};
14
}
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ x: 42 }],
18
+ params: [{x: 42}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-object-declaration-to-context-var.js
+4
-4
@@ -1,15 +1,15 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
function Component(props) {
4
- let { x } = props;
4
+ let {x} = props;
5
const foo = () => {
6
x = identity(props.x);
7
};
8
foo();
9
- return { x };
9
+ return {x};
10
}
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ x: 42 }],
14
+ params: [{x: 42}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-param-string-literal-key-invalid-identifier.expect.md
+2
-2
@@ -2,13 +2,13 @@
2
## Input
3
4
```javascript
5
-function foo({ "data-foo-bar": dataTestID }) {
5
+function foo({'data-foo-bar': dataTestID}) {
6
return dataTestID;
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: foo,
11
- params: [{ "data-foo-bar": {} }],
11
+ params: [{'data-foo-bar': {}}],
12
isComponent: false,
13
};
14
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-param-string-literal-key-invalid-identifier.js
+2
-2
@@ -1,9 +1,9 @@
1
-function foo({ "data-foo-bar": dataTestID }) {
1
+function foo({'data-foo-bar': dataTestID}) {
2
return dataTestID;
3
}
4
5
export const FIXTURE_ENTRYPOINT = {
6
fn: foo,
7
- params: [{ "data-foo-bar": {} }],
7
+ params: [{'data-foo-bar': {}}],
8
isComponent: false,
9
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-param-string-literal-key.expect.md
+2
-2
@@ -2,13 +2,13 @@
2
## Input
3
4
```javascript
5
-function foo({ data: dataTestID }) {
5
+function foo({data: dataTestID}) {
6
return dataTestID;
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: foo,
11
- params: [{ data: {} }],
11
+ params: [{data: {}}],
12
isComponent: false,
13
};
14
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-param-string-literal-key.js
+2
-2
@@ -1,9 +1,9 @@
1
-function foo({ data: dataTestID }) {
1
+function foo({data: dataTestID}) {
2
return dataTestID;
3
}
4
5
export const FIXTURE_ENTRYPOINT = {
6
fn: foo,
7
- params: [{ data: {} }],
7
+ params: [{data: {}}],
8
isComponent: false,
9
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-string-literal-invalid-identifier-property-key.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function foo() {
6
- const { "data-foo-bar": t } = { "data-foo-bar": 1 };
6
+ const {'data-foo-bar': t} = {'data-foo-bar': 1};
7
return t;
8
}
9
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-string-literal-invalid-identifier-property-key.js
+1
-1
@@ -1,5 +1,5 @@
1
function foo() {
2
- const { "data-foo-bar": t } = { "data-foo-bar": 1 };
2
+ const {'data-foo-bar': t} = {'data-foo-bar': 1};
3
return t;
4
}
5
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-string-literal-property-key.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function foo() {
6
- const { data: t } = { data: 1 };
6
+ const {data: t} = {data: 1};
7
return t;
8
}
9
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructure-string-literal-property-key.js
+1
-1
@@ -1,5 +1,5 @@
1
function foo() {
2
- const { data: t } = { data: 1 };
2
+ const {data: t} = {data: 1};
3
return t;
4
}
5
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-array-default.expect.md
+3
-3
@@ -3,14 +3,14 @@
3
4
```javascript
5
function Component(props) {
6
- const [[x] = ["default"]] = props.y;
6
+ const [[x] = ['default']] = props.y;
7
return x;
8
}
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-array-default.js
+3
-3
@@ -1,10 +1,10 @@
1
function Component(props) {
2
- const [[x] = ["default"]] = props.y;
2
+ const [[x] = ['default']] = props.y;
3
return x;
4
}
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: Component,
8
- params: ["TodoAdd"],
9
- isComponent: "TodoAdd",
8
+ params: ['TodoAdd'],
9
+ isComponent: 'TodoAdd',
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-array-param-default.expect.md
+2
-2
@@ -8,8 +8,8 @@ function Component([a = 2]) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
14
15
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-array-param-default.js
+2
-2
@@ -4,6 +4,6 @@ function Component([a = 2]) {
4
5
export const FIXTURE_ENTRYPOINT = {
6
fn: Component,
7
- params: ["TodoAdd"],
8
- isComponent: "TodoAdd",
7
+ params: ['TodoAdd'],
8
+ isComponent: 'TodoAdd',
9
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-assignment-array-default.expect.md
+3
-3
@@ -5,7 +5,7 @@
5
function Component(props) {
6
let x;
7
if (props.cond) {
8
- [[x] = ["default"]] = props.y;
8
+ [[x] = ['default']] = props.y;
9
} else {
10
x = props.fallback;
11
}
@@ -14,8 +14,8 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: ["TodoAdd"],
18
- isComponent: "TodoAdd",
17
+ params: ['TodoAdd'],
18
+ isComponent: 'TodoAdd',
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-assignment-array-default.js
+3
-3
@@ -1,7 +1,7 @@
1
function Component(props) {
2
let x;
3
if (props.cond) {
4
- [[x] = ["default"]] = props.y;
4
+ [[x] = ['default']] = props.y;
5
} else {
6
x = props.fallback;
7
}
@@ -10,6 +10,6 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-assignment.expect.md
+4
-4
@@ -8,7 +8,7 @@ function foo(a, b, c) {
8
d,
9
[
10
{
11
- e: { f: g },
11
+ e: {f: g},
12
},
13
],
14
] = a;
@@ -18,13 +18,13 @@ function foo(a, b, c) {
18
},
19
o,
20
} = b);
21
- return { d, g, n, o };
21
+ return {d, g, n, o};
22
}
23
24
export const FIXTURE_ENTRYPOINT = {
25
fn: foo,
26
- params: ["TodoAdd"],
27
- isComponent: "TodoAdd",
26
+ params: ['TodoAdd'],
27
+ isComponent: 'TodoAdd',
28
};
29
30
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-assignment.js
+4
-4
@@ -4,7 +4,7 @@ function foo(a, b, c) {
4
d,
5
[
6
{
7
- e: { f: g },
7
+ e: {f: g},
8
},
9
],
10
] = a;
@@ -14,11 +14,11 @@ function foo(a, b, c) {
14
},
15
o,
16
} = b);
17
- return { d, g, n, o };
17
+ return {d, g, n, o};
18
}
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: foo,
22
- params: ["TodoAdd"],
23
- isComponent: "TodoAdd",
22
+ params: ['TodoAdd'],
23
+ isComponent: 'TodoAdd',
24
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-default-at-array-hole.expect.md
+1
-1
@@ -10,7 +10,7 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ value: [, /* hole! */ 3.14] }],
13
+ params: [{value: [, /* hole! */ 3.14]}],
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-default-at-array-hole.js
+1
-1
@@ -6,5 +6,5 @@ function Component(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: [{ value: [, /* hole! */ 3.14] }],
9
+ params: [{value: [, /* hole! */ 3.14]}],
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-default-at-explicit-null.expect.md
+1
-1
@@ -10,7 +10,7 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ value: [null] }],
13
+ params: [{value: [null]}],
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-default-at-explicit-null.js
+1
-1
@@ -6,5 +6,5 @@ function Component(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: [{ value: [null] }],
9
+ params: [{value: [null]}],
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-default-at-explicit-undefined.expect.md
+1
-1
@@ -10,7 +10,7 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ value: [undefined] }],
13
+ params: [{value: [undefined]}],
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-default-at-explicit-undefined.js
+1
-1
@@ -6,5 +6,5 @@ function Component(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: [{ value: [undefined] }],
9
+ params: [{value: [undefined]}],
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-default-past-end-of-array.expect.md
+1
-1
@@ -10,7 +10,7 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ value: [] }],
13
+ params: [{value: []}],
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-default-past-end-of-array.js
+1
-1
@@ -6,5 +6,5 @@ function Component(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: [{ value: [] }],
9
+ params: [{value: []}],
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-mixed-scope-and-local-variables-with-default.expect.md
+7
-7
@@ -2,13 +2,13 @@
2
## Input
3
4
```javascript
5
-import { Stringify, graphql } from "shared-runtime";
5
+import {Stringify, graphql} from 'shared-runtime';
6
7
function useFragment(_arg1, _arg2) {
8
- "use no forget";
8
+ 'use no forget';
9
return {
10
- urls: ["url1", "url2", "url3"],
11
- comments: ["comment1"],
10
+ urls: ['url1', 'url2', 'url3'],
11
+ comments: ['comment1'],
12
};
13
}
14
@@ -22,8 +22,8 @@ function Component(props) {
22
// out of the scope, and the destructure statement ends up turning into
23
// a reassignment, instead of a const declaration. this means we try to
24
// reassign `comments` when there's no declaration for it.
25
- const { media = null, comments = [], urls = [] } = post;
26
- const onClick = (e) => {
25
+ const {media = null, comments = [], urls = []} = post;
26
+ const onClick = e => {
27
if (!comments.length) {
28
return;
29
}
@@ -35,7 +35,7 @@ function Component(props) {
35
36
export const FIXTURE_ENTRYPOINT = {
37
fn: Component,
38
- params: [{ post: {} }],
38
+ params: [{post: {}}],
39
isComponent: true,
40
};
41
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-mixed-scope-and-local-variables-with-default.js
+7
-7
@@ -1,10 +1,10 @@
1
-import { Stringify, graphql } from "shared-runtime";
1
+import {Stringify, graphql} from 'shared-runtime';
2
3
function useFragment(_arg1, _arg2) {
4
- "use no forget";
4
+ 'use no forget';
5
return {
6
- urls: ["url1", "url2", "url3"],
7
- comments: ["comment1"],
6
+ urls: ['url1', 'url2', 'url3'],
7
+ comments: ['comment1'],
8
};
9
}
10
@@ -18,8 +18,8 @@ function Component(props) {
18
// out of the scope, and the destructure statement ends up turning into
19
// a reassignment, instead of a const declaration. this means we try to
20
// reassign `comments` when there's no declaration for it.
21
- const { media = null, comments = [], urls = [] } = post;
22
- const onClick = (e) => {
21
+ const {media = null, comments = [], urls = []} = post;
22
+ const onClick = e => {
23
if (!comments.length) {
24
return;
25
}
@@ -31,6 +31,6 @@ function Component(props) {
31
32
export const FIXTURE_ENTRYPOINT = {
33
fn: Component,
34
- params: [{ post: {} }],
34
+ params: [{post: {}}],
35
isComponent: true,
36
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-mixed-scope-declarations-and-locals.expect.md
+2
-2
@@ -12,8 +12,8 @@ function Component(props) {
12
// out of the scope, and the destructure statement ends up turning into
13
// a reassignment, instead of a const declaration. this means we try to
14
// reassign `comments` when there's no declaration for it.
15
- const { media, comments, urls } = post;
16
- const onClick = (e) => {
15
+ const {media, comments, urls} = post;
16
+ const onClick = e => {
17
if (!comments.length) {
18
return;
19
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-mixed-scope-declarations-and-locals.js
+2
-2
@@ -8,8 +8,8 @@ function Component(props) {
8
// out of the scope, and the destructure statement ends up turning into
9
// a reassignment, instead of a const declaration. this means we try to
10
// reassign `comments` when there's no declaration for it.
11
- const { media, comments, urls } = post;
12
- const onClick = (e) => {
11
+ const {media, comments, urls} = post;
12
+ const onClick = e => {
13
if (!comments.length) {
14
return;
15
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-object-default.expect.md
+3
-3
@@ -3,14 +3,14 @@
3
4
```javascript
5
function Component(props) {
6
- const { x: { y } = { y: "default" } } = props.y;
6
+ const {x: {y} = {y: 'default'}} = props.y;
7
return y;
8
}
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-object-default.js
+3
-3
@@ -1,10 +1,10 @@
1
function Component(props) {
2
- const { x: { y } = { y: "default" } } = props.y;
2
+ const {x: {y} = {y: 'default'}} = props.y;
3
return y;
4
}
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: Component,
8
- params: ["TodoAdd"],
9
- isComponent: "TodoAdd",
8
+ params: ['TodoAdd'],
9
+ isComponent: 'TodoAdd',
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-object-param-default.expect.md
+3
-3
@@ -2,14 +2,14 @@
2
## Input
3
4
```javascript
5
-function Component({ a = 2 }) {
5
+function Component({a = 2}) {
6
return a;
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
14
15
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-object-param-default.js
+3
-3
@@ -1,9 +1,9 @@
1
-function Component({ a = 2 }) {
1
+function Component({a = 2}) {
2
return a;
3
}
4
5
export const FIXTURE_ENTRYPOINT = {
6
fn: Component,
7
- params: ["TodoAdd"],
8
- isComponent: "TodoAdd",
7
+ params: ['TodoAdd'],
8
+ isComponent: 'TodoAdd',
9
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-object-pattern-within-rest.expect.md
+2
-2
@@ -3,13 +3,13 @@
3
4
```javascript
5
function Component(props) {
6
- const [y, ...{ z }] = props.value;
6
+ const [y, ...{z}] = props.value;
7
return [y, z];
8
}
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: [{ value: ["y", { z: "z!" }] }],
12
+ params: [{value: ['y', {z: 'z!'}]}],
13
};
14
15
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-object-pattern-within-rest.js
+2
-2
@@ -1,9 +1,9 @@
1
function Component(props) {
2
- const [y, ...{ z }] = props.value;
2
+ const [y, ...{z}] = props.value;
3
return [y, z];
4
}
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: Component,
8
- params: [{ value: ["y", { z: "z!" }] }],
8
+ params: [{value: ['y', {z: 'z!'}]}],
9
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-property-inference.expect.md
+1
-1
@@ -5,7 +5,7 @@
5
function Component(props) {
6
const x = [];
7
x.push(props.value);
8
- const { length: y } = x;
8
+ const {length: y} = x;
9
foo(y);
10
return [x, y];
11
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-property-inference.js
+1
-1
@@ -1,7 +1,7 @@
1
function Component(props) {
2
const x = [];
3
x.push(props.value);
4
- const { length: y } = x;
4
+ const {length: y} = x;
5
foo(y);
6
return [x, y];
7
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-same-property-identifier-names.expect.md
+3
-3
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
function Component(props) {
8
const {
9
- x: { destructured },
9
+ x: {destructured},
10
sameName: renamed,
11
} = props;
12
const sameName = identity(destructured);
@@ -16,7 +16,7 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ x: { destructured: 0 }, sameName: 2 }],
19
+ params: [{x: {destructured: 0}, sameName: 2}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-same-property-identifier-names.js
+3
-3
@@ -1,8 +1,8 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
function Component(props) {
4
const {
5
- x: { destructured },
5
+ x: {destructured},
6
sameName: renamed,
7
} = props;
8
const sameName = identity(destructured);
@@ -12,5 +12,5 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ x: { destructured: 0 }, sameName: 2 }],
15
+ params: [{x: {destructured: 0}, sameName: 2}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-with-conditional-as-default-value.expect.md
+1
-1
@@ -9,7 +9,7 @@ function Component(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: [{ y: [] }],
12
+ params: [{y: []}],
13
};
14
15
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring-with-conditional-as-default-value.js
+1
-1
@@ -5,5 +5,5 @@ function Component(props) {
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: Component,
8
- params: [{ y: [] }],
8
+ params: [{y: []}],
9
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring.expect.md
+3
-3
@@ -7,7 +7,7 @@ function foo(a, b, c) {
7
d,
8
[
9
{
10
- e: { f },
10
+ e: {f},
11
...g
12
},
13
],
@@ -24,8 +24,8 @@ function foo(a, b, c) {
24
25
export const FIXTURE_ENTRYPOINT = {
26
fn: foo,
27
- params: ["TodoAdd"],
28
- isComponent: "TodoAdd",
27
+ params: ['TodoAdd'],
28
+ isComponent: 'TodoAdd',
29
};
30
31
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/destructuring.js
+3
-3
@@ -3,7 +3,7 @@ function foo(a, b, c) {
3
d,
4
[
5
{
6
- e: { f },
6
+ e: {f},
7
...g
8
},
9
],
@@ -20,6 +20,6 @@ function foo(a, b, c) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: foo,
23
- params: ["TodoAdd"],
24
- isComponent: "TodoAdd",
23
+ params: ['TodoAdd'],
24
+ isComponent: 'TodoAdd',
25
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/do-while-break.expect.md
+2
-2
@@ -11,8 +11,8 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/do-while-break.js
+2
-2
@@ -7,6 +7,6 @@ function Component(props) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: ["TodoAdd"],
11
- isComponent: "TodoAdd",
10
+ params: ['TodoAdd'],
11
+ isComponent: 'TodoAdd',
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/do-while-compound-test.expect.md
+2
-2
@@ -14,8 +14,8 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: ["TodoAdd"],
18
- isComponent: "TodoAdd",
17
+ params: ['TodoAdd'],
18
+ isComponent: 'TodoAdd',
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/do-while-compound-test.js
+2
-2
@@ -10,6 +10,6 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dominator.expect.md
+5
-5
@@ -15,14 +15,14 @@ function Component(props) {
15
x = 3;
16
}
17
label2: switch (props.c) {
18
- case "a": {
18
+ case 'a': {
19
x = 4;
20
break;
21
}
22
- case "b": {
22
+ case 'b': {
23
break label2;
24
}
25
- case "c": {
25
+ case 'c': {
26
x = 5;
27
// intentional fallthrough
28
}
@@ -38,8 +38,8 @@ function Component(props) {
38
39
export const FIXTURE_ENTRYPOINT = {
40
fn: Component,
41
- params: ["TodoAdd"],
42
- isComponent: "TodoAdd",
41
+ params: ['TodoAdd'],
42
+ isComponent: 'TodoAdd',
43
};
44
45
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dominator.js
+5
-5
@@ -11,14 +11,14 @@ function Component(props) {
11
x = 3;
12
}
13
label2: switch (props.c) {
14
- case "a": {
14
+ case 'a': {
15
x = 4;
16
break;
17
}
18
- case "b": {
18
+ case 'b': {
19
break label2;
20
}
21
- case "c": {
21
+ case 'c': {
22
x = 5;
23
// intentional fallthrough
24
}
@@ -34,6 +34,6 @@ function Component(props) {
34
35
export const FIXTURE_ENTRYPOINT = {
36
fn: Component,
37
- params: ["TodoAdd"],
38
- isComponent: "TodoAdd",
37
+ params: ['TodoAdd'],
38
+ isComponent: 'TodoAdd',
39
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dont-merge-if-dep-is-inner-declaration-of-previous-scope.expect.md
+7
-7
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-import { ValidateMemoization } from "shared-runtime";
5
+import {ValidateMemoization} from 'shared-runtime';
6
7
// Achieving Forget's level of memoization precision in this example isn't possible with useMemo
8
// without significantly altering the code, so disable the non-Forget evaluation of this fixture.
9
// @disableNonForgetInSprout
10
-function Component({ a, b, c }) {
10
+function Component({a, b, c}) {
11
const x = [];
12
let y;
13
if (a) {
@@ -30,12 +30,12 @@ function Component({ a, b, c }) {
30
31
export const FIXTURE_ENTRYPOINT = {
32
fn: Component,
33
- params: [{ a: false, b: null, c: 0 }],
33
+ params: [{a: false, b: null, c: 0}],
34
sequentialRenders: [
35
- { a: false, b: null, c: 0 },
36
- { a: false, b: null, c: 1 },
37
- { a: true, b: 0, c: 1 },
38
- { a: true, b: 1, c: 1 },
35
+ {a: false, b: null, c: 0},
36
+ {a: false, b: null, c: 1},
37
+ {a: true, b: 0, c: 1},
38
+ {a: true, b: 1, c: 1},
39
],
40
};
41
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dont-merge-if-dep-is-inner-declaration-of-previous-scope.js
+7
-7
@@ -1,9 +1,9 @@
1
-import { ValidateMemoization } from "shared-runtime";
1
+import {ValidateMemoization} from 'shared-runtime';
2
3
// Achieving Forget's level of memoization precision in this example isn't possible with useMemo
4
// without significantly altering the code, so disable the non-Forget evaluation of this fixture.
5
// @disableNonForgetInSprout
6
-function Component({ a, b, c }) {
6
+function Component({a, b, c}) {
7
const x = [];
8
let y;
9
if (a) {
@@ -26,11 +26,11 @@ function Component({ a, b, c }) {
26
27
export const FIXTURE_ENTRYPOINT = {
28
fn: Component,
29
- params: [{ a: false, b: null, c: 0 }],
29
+ params: [{a: false, b: null, c: 0}],
30
sequentialRenders: [
31
- { a: false, b: null, c: 0 },
32
- { a: false, b: null, c: 1 },
33
- { a: true, b: 0, c: 1 },
34
- { a: true, b: 1, c: 1 },
31
+ {a: false, b: null, c: 0},
32
+ {a: false, b: null, c: 1},
33
+ {a: true, b: 0, c: 1},
34
+ {a: true, b: 1, c: 1},
35
],
36
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dont-merge-overlapping-scopes-store-const-used-later.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { Stringify, makeObject_Primitives } from "shared-runtime";
5
+import {Stringify, makeObject_Primitives} from 'shared-runtime';
6
7
function Component(props) {
8
const array = [props.count];
@@ -14,7 +14,7 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ count: 42 }],
17
+ params: [{count: 42}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dont-merge-overlapping-scopes-store-const-used-later.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { Stringify, makeObject_Primitives } from "shared-runtime";
1
+import {Stringify, makeObject_Primitives} from 'shared-runtime';
2
3
function Component(props) {
4
const array = [props.count];
@@ -10,5 +10,5 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ count: 42 }],
13
+ params: [{count: 42}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dont-merge-overlapping-scopes-with-intermediate-reassignment.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
function Component(props) {
8
let x;
@@ -19,7 +19,7 @@ function Component(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: [{ count: 42 }],
22
+ params: [{count: 42}],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/dont-merge-overlapping-scopes-with-intermediate-reassignment.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
function Component(props) {
4
let x;
@@ -15,5 +15,5 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ count: 42 }],
18
+ params: [{count: 42}],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/drop-methodcall-usecallback.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import * as React from "react";
5
+import * as React from 'react';
6
7
function Component(props) {
8
const onClick = React.useCallback(() => {
@@ -13,7 +13,7 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ value: 42 }],
16
+ params: [{value: 42}],
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/drop-methodcall-usecallback.js
+2
-2
@@ -1,4 +1,4 @@
1
-import * as React from "react";
1
+import * as React from 'react';
2
3
function Component(props) {
4
const onClick = React.useCallback(() => {
@@ -9,5 +9,5 @@ function Component(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: [{ value: 42 }],
12
+ params: [{value: 42}],
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/drop-methodcall-usememo.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import * as React from "react";
5
+import * as React from 'react';
6
7
function Component(props) {
8
const x = React.useMemo(() => {
@@ -15,7 +15,7 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ value: 42 }],
18
+ params: [{value: 42}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/drop-methodcall-usememo.js
+2
-2
@@ -1,4 +1,4 @@
1
-import * as React from "react";
1
+import * as React from 'react';
2
3
function Component(props) {
4
const x = React.useMemo(() => {
@@ -11,5 +11,5 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ value: 42 }],
14
+ params: [{value: 42}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/early-return-nested-early-return-within-reactive-scope.expect.md
+1
-1
@@ -21,7 +21,7 @@ function Component(props) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
- params: [{ cond: true, a: 42, b: 3.14 }],
24
+ params: [{cond: true, a: 42, b: 3.14}],
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/early-return-nested-early-return-within-reactive-scope.js
+1
-1
@@ -17,5 +17,5 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ cond: true, a: 42, b: 3.14 }],
20
+ params: [{cond: true, a: 42, b: 3.14}],
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/early-return-no-declarations-reassignments-dependencies.expect.md
+10
-10
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeArray } from "shared-runtime";
5
+import {makeArray} from 'shared-runtime';
6
7
/**
8
* This fixture tests what happens when a reactive has no declarations (other than an early return),
@@ -25,7 +25,7 @@ function Component(props) {
25
x.push(42);
26
return x;
27
} else {
28
- console.log("fallthrough");
28
+ console.log('fallthrough');
29
}
30
return makeArray(props.a);
31
}
@@ -34,14 +34,14 @@ export const FIXTURE_ENTRYPOINT = {
34
fn: Component,
35
params: [],
36
sequentialRenders: [
37
- { a: 42 },
38
- { a: 42 },
39
- { a: 3.14 },
40
- { a: 3.14 },
41
- { a: 42 },
42
- { a: 3.14 },
43
- { a: 42 },
44
- { a: 3.14 },
37
+ {a: 42},
38
+ {a: 42},
39
+ {a: 3.14},
40
+ {a: 3.14},
41
+ {a: 42},
42
+ {a: 3.14},
43
+ {a: 42},
44
+ {a: 3.14},
45
],
46
};
47
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/early-return-no-declarations-reassignments-dependencies.js
+10
-10
@@ -1,4 +1,4 @@
1
-import { makeArray } from "shared-runtime";
1
+import {makeArray} from 'shared-runtime';
2
3
/**
4
* This fixture tests what happens when a reactive has no declarations (other than an early return),
@@ -21,7 +21,7 @@ function Component(props) {
21
x.push(42);
22
return x;
23
} else {
24
- console.log("fallthrough");
24
+ console.log('fallthrough');
25
}
26
return makeArray(props.a);
27
}
@@ -30,13 +30,13 @@ export const FIXTURE_ENTRYPOINT = {
30
fn: Component,
31
params: [],
32
sequentialRenders: [
33
- { a: 42 },
34
- { a: 42 },
35
- { a: 3.14 },
36
- { a: 3.14 },
37
- { a: 42 },
38
- { a: 3.14 },
39
- { a: 42 },
40
- { a: 3.14 },
33
+ {a: 42},
34
+ {a: 42},
35
+ {a: 3.14},
36
+ {a: 3.14},
37
+ {a: 42},
38
+ {a: 3.14},
39
+ {a: 42},
40
+ {a: 3.14},
41
],
42
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/early-return-within-reactive-scope.expect.md
+9
-9
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeArray } from "shared-runtime";
5
+import {makeArray} from 'shared-runtime';
6
7
function Component(props) {
8
let x = [];
@@ -20,19 +20,19 @@ export const FIXTURE_ENTRYPOINT = {
20
params: [],
21
sequentialRenders: [
22
// pattern 1
23
- { cond: true, a: 42 },
24
- { cond: true, a: 42 },
23
+ {cond: true, a: 42},
24
+ {cond: true, a: 42},
25
// pattern 2
26
- { cond: false, b: 3.14 },
27
- { cond: false, b: 3.14 },
26
+ {cond: false, b: 3.14},
27
+ {cond: false, b: 3.14},
28
// pattern 1
29
- { cond: true, a: 42 },
29
+ {cond: true, a: 42},
30
// pattern 2
31
- { cond: false, b: 3.14 },
31
+ {cond: false, b: 3.14},
32
// pattern 1
33
- { cond: true, a: 42 },
33
+ {cond: true, a: 42},
34
// pattern 2
35
- { cond: false, b: 3.14 },
35
+ {cond: false, b: 3.14},
36
],
37
};
38
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/early-return-within-reactive-scope.js
+9
-9
@@ -1,4 +1,4 @@
1
-import { makeArray } from "shared-runtime";
1
+import {makeArray} from 'shared-runtime';
2
3
function Component(props) {
4
let x = [];
@@ -16,18 +16,18 @@ export const FIXTURE_ENTRYPOINT = {
16
params: [],
17
sequentialRenders: [
18
// pattern 1
19
- { cond: true, a: 42 },
20
- { cond: true, a: 42 },
19
+ {cond: true, a: 42},
20
+ {cond: true, a: 42},
21
// pattern 2
22
- { cond: false, b: 3.14 },
23
- { cond: false, b: 3.14 },
22
+ {cond: false, b: 3.14},
23
+ {cond: false, b: 3.14},
24
// pattern 1
25
- { cond: true, a: 42 },
25
+ {cond: true, a: 42},
26
// pattern 2
27
- { cond: false, b: 3.14 },
27
+ {cond: false, b: 3.14},
28
// pattern 1
29
- { cond: true, a: 42 },
29
+ {cond: true, a: 42},
30
// pattern 2
31
- { cond: false, b: 3.14 },
31
+ {cond: false, b: 3.14},
32
],
33
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/early-return.expect.md
+2
-2
@@ -13,8 +13,8 @@ function MyApp(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: MyApp,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/early-return.js
+2
-2
@@ -9,6 +9,6 @@ function MyApp(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: MyApp,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/empty-catch-statement.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { getNumber } from "shared-runtime";
5
+import {getNumber} from 'shared-runtime';
6
7
function useFoo() {
8
try {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/empty-catch-statement.ts
+1
-1
@@ -1,4 +1,4 @@
1
-import { getNumber } from "shared-runtime";
1
+import {getNumber} from 'shared-runtime';
2
3
function useFoo() {
4
try {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error._todo.computed-lval-in-destructure.expect.md
+3
-3
@@ -4,7 +4,7 @@
4
```javascript
5
function Component(props) {
6
const computedKey = props.key;
7
- const { [computedKey]: x } = props.val;
7
+ const {[computedKey]: x} = props.val;
8
9
return x;
10
}
@@ -17,8 +17,8 @@ function Component(props) {
17
```
18
1 | function Component(props) {
19
2 | const computedKey = props.key;
20
-> 3 | const { [computedKey]: x } = props.val;
21
- | ^^^^^^^^^^^^^^^^ Todo: (BuildHIR::lowerAssignment) Handle computed properties in ObjectPattern (3:3)
20
+> 3 | const {[computedKey]: x} = props.val;
21
+ | ^^^^^^^^^^^^^^^^ Todo: (BuildHIR::lowerAssignment) Handle computed properties in ObjectPattern (3:3)
22
4 |
23
5 | return x;
24
6 | }
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error._todo.computed-lval-in-destructure.js
+1
-1
@@ -1,6 +1,6 @@
1
function Component(props) {
2
const computedKey = props.key;
3
- const { [computedKey]: x } = props.val;
3
+ const {[computedKey]: x} = props.val;
4
5
return x;
6
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.bailout-on-suppression-of-custom-rule.expect.md
+2
-2
@@ -6,7 +6,7 @@
6
7
/* eslint-disable my-app/react-rule */
8
function lowercasecomponent() {
9
- "use forget";
9
+ 'use forget';
10
const x = [];
11
// eslint-disable-next-line my-app/react-rule
12
return <div>{x}</div>;
@@ -26,7 +26,7 @@ function lowercasecomponent() {
26
27
InvalidReact: React Compiler has skipped optimizing this component because one or more React ESLint rules were disabled. React Compiler only works when your components follow all the rules of React, disabling them may result in unexpected or incorrect behavior. eslint-disable-next-line my-app/react-rule (7:7)
28
4 | function lowercasecomponent() {
29
- 5 | "use forget";
29
+ 5 | 'use forget';
30
6 | const x = [];
31
```
32
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.bailout-on-suppression-of-custom-rule.js
+1
-1
@@ -2,7 +2,7 @@
2
3
/* eslint-disable my-app/react-rule */
4
function lowercasecomponent() {
5
- "use forget";
5
+ 'use forget';
6
const x = [];
7
// eslint-disable-next-line my-app/react-rule
8
return <div>{x}</div>;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.codegen-error-on-conflicting-imports.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
// @enableEmitFreeze @instrumentForget
6
7
-let makeReadOnly = "conflicting identifier";
7
+let makeReadOnly = 'conflicting identifier';
8
function useFoo(props) {
9
return foo(props.x);
10
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.codegen-error-on-conflicting-imports.js
+1
-1
@@ -1,6 +1,6 @@
1
// @enableEmitFreeze @instrumentForget
2
3
-let makeReadOnly = "conflicting identifier";
3
+let makeReadOnly = 'conflicting identifier';
4
function useFoo(props) {
5
return foo(props.x);
6
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.dont-hoist-inline-reference.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
function useInvalid() {
7
const x = identity(x);
8
return x;
@@ -19,7 +19,7 @@ export const FIXTURE_ENTRYPOINT = {
19
## Error
20
21
```
22
- 1 | import { identity } from "shared-runtime";
22
+ 1 | import {identity} from 'shared-runtime';
23
2 | function useInvalid() {
24
> 3 | const x = identity(x);
25
| ^^^^^^^^^^^^^^^^^^^^^^ Todo: [hoisting] EnterSSA: Expected identifier to be defined before being used. Identifier x$1 is undefined (3:3)
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.dont-hoist-inline-reference.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
function useInvalid() {
3
const x = identity(x);
4
return x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.gating-use-before-decl.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @gating
6
-import { memo } from "react";
6
+import {memo} from 'react';
7
8
export default memo(Foo);
9
function Foo() {}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.gating-use-before-decl.js
+1
-1
@@ -1,5 +1,5 @@
1
// @gating
2
-import { memo } from "react";
2
+import {memo} from 'react';
3
4
export default memo(Foo);
5
function Foo() {}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.hoisted-function-declaration.expect.md
+2
-2
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let t = { a };
6
+ let t = {a};
7
x(t); // hoisted call
8
function x(p) {
9
p.foo();
@@ -18,7 +18,7 @@ function component(a) {
18
19
```
20
1 | function component(a) {
21
- 2 | let t = { a };
21
+ 2 | let t = {a};
22
> 3 | x(t); // hoisted call
23
| ^^^^ Todo: Unsupported declaration type for hoisting. variable "x" declared with FunctionDeclaration (3:3)
24
4 | function x(p) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.hoisted-function-declaration.js
+1
-1
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let t = { a };
2
+ let t = {a};
3
x(t); // hoisted call
4
function x(p) {
5
p.foo();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.hook-property-load-local-hook.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
function useFoo() {}
6
useFoo.useBar = function () {
7
- return "foo";
7
+ return 'foo';
8
};
9
10
function Foo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.hook-property-load-local-hook.js
+1
-1
@@ -1,6 +1,6 @@
1
function useFoo() {}
2
useFoo.useBar = function () {
3
- return "foo";
3
+ return 'foo';
4
};
5
6
function Foo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-aliased-ref-in-callback-invoked-during-render-.expect.md
+4
-4
@@ -5,12 +5,12 @@
5
// @validateRefAccessDuringRender
6
function Component(props) {
7
const ref = useRef(null);
8
- const renderItem = (item) => {
8
+ const renderItem = item => {
9
const aliasedRef = ref;
10
const current = aliasedRef.current;
11
return <Foo item={item} current={current} />;
12
};
13
- return <Items>{props.items.map((item) => renderItem(item))}</Items>;
13
+ return <Items>{props.items.map(item => renderItem(item))}</Items>;
14
}
15
16
```
@@ -21,8 +21,8 @@ function Component(props) {
21
```
22
7 | return <Foo item={item} current={current} />;
23
8 | };
24
-> 9 | return <Items>{props.items.map((item) => renderItem(item))}</Items>;
25
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^ InvalidReact: Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef) (9:9)
24
+> 9 | return <Items>{props.items.map(item => renderItem(item))}</Items>;
25
+ | ^^^^^^^^^^^^^^^^^^^^^^^^ InvalidReact: Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef) (9:9)
26
10 | }
27
11 |
28
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-aliased-ref-in-callback-invoked-during-render-.js
+2
-2
@@ -1,10 +1,10 @@
1
// @validateRefAccessDuringRender
2
function Component(props) {
3
const ref = useRef(null);
4
- const renderItem = (item) => {
4
+ const renderItem = item => {
5
const aliasedRef = ref;
6
const current = aliasedRef.current;
7
return <Foo item={item} current={current} />;
8
};
9
- return <Items>{props.items.map((item) => renderItem(item))}</Items>;
9
+ return <Items>{props.items.map(item => renderItem(item))}</Items>;
10
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-conditional-call-aliased-hook-import.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useFragment as readFragment } from "shared-runtime";
5
+import {useFragment as readFragment} from 'shared-runtime';
6
7
function Component(props) {
8
let data;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-conditional-call-aliased-hook-import.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { useFragment as readFragment } from "shared-runtime";
1
+import {useFragment as readFragment} from 'shared-runtime';
2
3
function Component(props) {
4
let data;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-conditional-call-aliased-react-hook.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useState as state } from "react";
5
+import {useState as state} from 'react';
6
7
function Component(props) {
8
let s;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-conditional-call-aliased-react-hook.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { useState as state } from "react";
1
+import {useState as state} from 'react';
2
3
function Component(props) {
4
let s;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-conditional-call-non-hook-imported-as-hook.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeArray as useArray } from "other";
5
+import {makeArray as useArray} from 'other';
6
7
function Component(props) {
8
let data;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-conditional-call-non-hook-imported-as-hook.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { makeArray as useArray } from "other";
1
+import {makeArray as useArray} from 'other';
2
3
function Component(props) {
4
let data;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-destructure-assignment-to-global.expect.md
+2
-2
@@ -4,7 +4,7 @@
4
```javascript
5
function useFoo(props) {
6
[x] = props;
7
- return { x };
7
+ return {x};
8
}
9
10
```
@@ -16,7 +16,7 @@ function useFoo(props) {
16
1 | function useFoo(props) {
17
> 2 | [x] = props;
18
| ^ InvalidReact: Unexpected reassignment of a variable which was defined outside of the component. Components and hooks should be pure and side-effect free, but variable reassignment is a form of side-effect. If this variable is used in rendering, use useState instead. (https://react.dev/reference/rules/components-and-hooks-must-be-pure#side-effects-must-run-outside-of-render) (2:2)
19
- 3 | return { x };
19
+ 3 | return {x};
20
4 | }
21
5 |
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-destructure-assignment-to-global.js
+1
-1
@@ -1,4 +1,4 @@
1
function useFoo(props) {
2
[x] = props;
3
- return { x };
3
+ return {x};
4
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-function-expression-mutates-immutable-value.expect.md
+3
-3
@@ -3,8 +3,8 @@
3
4
```javascript
5
function Component(props) {
6
- const [x, setX] = useState({ value: "" });
7
- const onChange = (e) => {
6
+ const [x, setX] = useState({value: ''});
7
+ const onChange = e => {
8
// INVALID! should use copy-on-write and pass the new value
9
x.value = e.target.value;
10
setX(x);
@@ -18,7 +18,7 @@ function Component(props) {
18
## Error
19
20
```
21
- 3 | const onChange = (e) => {
21
+ 3 | const onChange = e => {
22
4 | // INVALID! should use copy-on-write and pass the new value
23
> 5 | x.value = e.target.value;
24
| ^ InvalidReact: Mutating a value returned from 'useState()', which should not be mutated. Use the setter function to update instead. Found mutation of `x` (5:5)
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-function-expression-mutates-immutable-value.js
+2
-2
@@ -1,6 +1,6 @@
1
function Component(props) {
2
- const [x, setX] = useState({ value: "" });
3
- const onChange = (e) => {
2
+ const [x, setX] = useState({value: ''});
3
+ const onChange = e => {
4
// INVALID! should use copy-on-write and pass the new value
5
x.value = e.target.value;
6
setX(x);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-global-reassignment-indirect.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useEffect, useState } from "react";
5
+import {useEffect, useState} from 'react';
6
7
let someGlobal = false;
8
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-global-reassignment-indirect.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { useEffect, useState } from "react";
1
+import {useEffect, useState} from 'react';
2
3
let someGlobal = false;
4
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-mutate-props-in-effect-fixpoint.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useEffect } from "react";
5
+import {useEffect} from 'react';
6
7
function Component(props) {
8
let x = null;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-mutate-props-in-effect-fixpoint.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { useEffect } from "react";
1
+import {useEffect} from 'react';
2
3
function Component(props) {
4
let x = null;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-mutation-in-closure.expect.md
+2
-2
@@ -5,7 +5,7 @@
5
function useInvalidMutation(options) {
6
function test() {
7
foo(options.foo); // error should not point on this line
8
- options.foo = "bar";
8
+ options.foo = 'bar';
9
}
10
return test;
11
}
@@ -18,7 +18,7 @@ function useInvalidMutation(options) {
18
```
19
2 | function test() {
20
3 | foo(options.foo); // error should not point on this line
21
-> 4 | options.foo = "bar";
21
+> 4 | options.foo = 'bar';
22
| ^^^^^^^ InvalidReact: Mutating component props or hook arguments is not allowed. Consider using a local variable instead. Found mutation of `options` (4:4)
23
5 | }
24
6 | return test;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-mutation-in-closure.js
+1
-1
@@ -1,7 +1,7 @@
1
function useInvalidMutation(options) {
2
function test() {
3
foo(options.foo); // error should not point on this line
4
- options.foo = "bar";
4
+ options.foo = 'bar';
5
}
6
return test;
7
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-read-ref-prop-in-render-destructure.expect.md
+2
-2
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @validateRefAccessDuringRender @compilationMode(infer)
6
-function Component({ ref }) {
6
+function Component({ref}) {
7
const value = ref.current;
8
return <div>{value}</div>;
9
}
@@ -14,7 +14,7 @@ function Component({ ref }) {
14
## Error
15
16
```
17
- 2 | function Component({ ref }) {
17
+ 2 | function Component({ref}) {
18
3 | const value = ref.current;
19
> 4 | return <div>{value}</div>;
20
| ^^^^^ InvalidReact: Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef). Cannot access ref value at read $17:TObject<BuiltInRefValue> (4:4)
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-read-ref-prop-in-render-destructure.js
+1
-1
@@ -1,5 +1,5 @@
1
// @validateRefAccessDuringRender @compilationMode(infer)
2
-function Component({ ref }) {
2
+function Component({ref}) {
3
const value = ref.current;
4
return <div>{value}</div>;
5
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-reassign-local-in-hook-return-value.expect.md
+2
-2
@@ -4,7 +4,7 @@
4
```javascript
5
function useFoo() {
6
let x = 0;
7
- return (value) => {
7
+ return value => {
8
x = value;
9
};
10
}
@@ -16,7 +16,7 @@ function useFoo() {
16
17
```
18
2 | let x = 0;
19
- 3 | return (value) => {
19
+ 3 | return value => {
20
> 4 | x = value;
21
| ^ InvalidReact: Reassigning a variable after render has completed can cause inconsistent behavior on subsequent renders. Consider using state instead. Variable `x` cannot be reassigned after render (4:4)
22
5 | };
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-reassign-local-in-hook-return-value.js
+1
-1
@@ -1,6 +1,6 @@
1
function useFoo() {
2
let x = 0;
3
- return (value) => {
3
+ return value => {
4
x = value;
5
};
6
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-reassign-local-variable-in-async-callback.expect.md
+1
-1
@@ -5,7 +5,7 @@
5
function Component() {
6
let value = null;
7
const reassign = async () => {
8
- await foo().then((result) => {
8
+ await foo().then(result => {
9
// Reassigning a local variable in an async function is *always* mutating
10
// after render, so this should error regardless of where this ends up
11
// getting called
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-reassign-local-variable-in-async-callback.js
+1
-1
@@ -1,7 +1,7 @@
1
function Component() {
2
let value = null;
3
const reassign = async () => {
4
- await foo().then((result) => {
4
+ await foo().then(result => {
5
// Reassigning a local variable in an async function is *always* mutating
6
// after render, so this should error regardless of where this ends up
7
// getting called
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-reassign-local-variable-in-effect.expect.md
+9
-9
@@ -2,17 +2,17 @@
2
## Input
3
4
```javascript
5
-import { useEffect } from "react";
5
+import {useEffect} from 'react';
6
7
function Component() {
8
let local;
9
10
- const reassignLocal = (newValue) => {
10
+ const reassignLocal = newValue => {
11
local = newValue;
12
};
13
14
- const onMount = (newValue) => {
15
- reassignLocal("hello");
14
+ const onMount = newValue => {
15
+ reassignLocal('hello');
16
17
if (local === newValue) {
18
// Without React Compiler, `reassignLocal` is freshly created
@@ -20,7 +20,7 @@ function Component() {
20
// such that invoking reassignLocal will reassign the same
21
// binding that we are observing in the if condition, and
22
// we reach this branch
23
- console.log("`local` was updated!");
23
+ console.log('`local` was updated!');
24
} else {
25
// With React Compiler enabled, `reassignLocal` is only created
26
// once, capturing a binding to `local` in that render pass.
@@ -30,7 +30,7 @@ function Component() {
30
//
31
// To protect against this, we disallow reassigning locals from
32
// functions that escape
33
- throw new Error("`local` not updated!");
33
+ throw new Error('`local` not updated!');
34
}
35
};
36
@@ -38,7 +38,7 @@ function Component() {
38
onMount();
39
}, [onMount]);
40
41
- return "ok";
41
+ return 'ok';
42
}
43
44
```
@@ -48,12 +48,12 @@ function Component() {
48
49
```
50
5 |
51
- 6 | const reassignLocal = (newValue) => {
51
+ 6 | const reassignLocal = newValue => {
52
> 7 | local = newValue;
53
| ^^^^^ InvalidReact: Reassigning a variable after render has completed can cause inconsistent behavior on subsequent renders. Consider using state instead. Variable `local` cannot be reassigned after render (7:7)
54
8 | };
55
9 |
56
- 10 | const onMount = (newValue) => {
56
+ 10 | const onMount = newValue => {
57
```
58
59
\ No newline at end of file
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-reassign-local-variable-in-effect.js
+7
-7
@@ -1,14 +1,14 @@
1
-import { useEffect } from "react";
1
+import {useEffect} from 'react';
2
3
function Component() {
4
let local;
5
6
- const reassignLocal = (newValue) => {
6
+ const reassignLocal = newValue => {
7
local = newValue;
8
};
9
10
- const onMount = (newValue) => {
11
- reassignLocal("hello");
10
+ const onMount = newValue => {
11
+ reassignLocal('hello');
12
13
if (local === newValue) {
14
// Without React Compiler, `reassignLocal` is freshly created
@@ -16,7 +16,7 @@ function Component() {
16
// such that invoking reassignLocal will reassign the same
17
// binding that we are observing in the if condition, and
18
// we reach this branch
19
- console.log("`local` was updated!");
19
+ console.log('`local` was updated!');
20
} else {
21
// With React Compiler enabled, `reassignLocal` is only created
22
// once, capturing a binding to `local` in that render pass.
@@ -26,7 +26,7 @@ function Component() {
26
//
27
// To protect against this, we disallow reassigning locals from
28
// functions that escape
29
- throw new Error("`local` not updated!");
29
+ throw new Error('`local` not updated!');
30
}
31
};
32
@@ -34,5 +34,5 @@ function Component() {
34
onMount();
35
}, [onMount]);
36
37
- return "ok";
37
+ return 'ok';
38
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-reassign-local-variable-in-hook-argument.expect.md
+10
-10
@@ -2,18 +2,18 @@
2
## Input
3
4
```javascript
5
-import { useEffect } from "react";
6
-import { useIdentity } from "shared-runtime";
5
+import {useEffect} from 'react';
6
+import {useIdentity} from 'shared-runtime';
7
8
function Component() {
9
let local;
10
11
- const reassignLocal = (newValue) => {
11
+ const reassignLocal = newValue => {
12
local = newValue;
13
};
14
15
- const callback = (newValue) => {
16
- reassignLocal("hello");
15
+ const callback = newValue => {
16
+ reassignLocal('hello');
17
18
if (local === newValue) {
19
// Without React Compiler, `reassignLocal` is freshly created
@@ -21,7 +21,7 @@ function Component() {
21
// such that invoking reassignLocal will reassign the same
22
// binding that we are observing in the if condition, and
23
// we reach this branch
24
- console.log("`local` was updated!");
24
+ console.log('`local` was updated!');
25
} else {
26
// With React Compiler enabled, `reassignLocal` is only created
27
// once, capturing a binding to `local` in that render pass.
@@ -31,7 +31,7 @@ function Component() {
31
//
32
// To protect against this, we disallow reassigning locals from
33
// functions that escape
34
- throw new Error("`local` not updated!");
34
+ throw new Error('`local` not updated!');
35
}
36
};
37
@@ -39,7 +39,7 @@ function Component() {
39
callback();
40
});
41
42
- return "ok";
42
+ return 'ok';
43
}
44
45
```
@@ -49,12 +49,12 @@ function Component() {
49
50
```
51
6 |
52
- 7 | const reassignLocal = (newValue) => {
52
+ 7 | const reassignLocal = newValue => {
53
> 8 | local = newValue;
54
| ^^^^^ InvalidReact: Reassigning a variable after render has completed can cause inconsistent behavior on subsequent renders. Consider using state instead. Variable `local` cannot be reassigned after render (8:8)
55
9 | };
56
10 |
57
- 11 | const callback = (newValue) => {
57
+ 11 | const callback = newValue => {
58
```
59
60
\ No newline at end of file
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-reassign-local-variable-in-hook-argument.js
+8
-8
@@ -1,15 +1,15 @@
1
-import { useEffect } from "react";
2
-import { useIdentity } from "shared-runtime";
1
+import {useEffect} from 'react';
2
+import {useIdentity} from 'shared-runtime';
3
4
function Component() {
5
let local;
6
7
- const reassignLocal = (newValue) => {
7
+ const reassignLocal = newValue => {
8
local = newValue;
9
};
10
11
- const callback = (newValue) => {
12
- reassignLocal("hello");
11
+ const callback = newValue => {
12
+ reassignLocal('hello');
13
14
if (local === newValue) {
15
// Without React Compiler, `reassignLocal` is freshly created
@@ -17,7 +17,7 @@ function Component() {
17
// such that invoking reassignLocal will reassign the same
18
// binding that we are observing in the if condition, and
19
// we reach this branch
20
- console.log("`local` was updated!");
20
+ console.log('`local` was updated!');
21
} else {
22
// With React Compiler enabled, `reassignLocal` is only created
23
// once, capturing a binding to `local` in that render pass.
@@ -27,7 +27,7 @@ function Component() {
27
//
28
// To protect against this, we disallow reassigning locals from
29
// functions that escape
30
- throw new Error("`local` not updated!");
30
+ throw new Error('`local` not updated!');
31
}
32
};
33
@@ -35,5 +35,5 @@ function Component() {
35
callback();
36
});
37
38
- return "ok";
38
+ return 'ok';
39
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-reassign-local-variable-in-jsx-callback.expect.md
+7
-7
@@ -5,12 +5,12 @@
5
function Component() {
6
let local;
7
8
- const reassignLocal = (newValue) => {
8
+ const reassignLocal = newValue => {
9
local = newValue;
10
};
11
12
- const onClick = (newValue) => {
13
- reassignLocal("hello");
12
+ const onClick = newValue => {
13
+ reassignLocal('hello');
14
15
if (local === newValue) {
16
// Without React Compiler, `reassignLocal` is freshly created
@@ -18,7 +18,7 @@ function Component() {
18
// such that invoking reassignLocal will reassign the same
19
// binding that we are observing in the if condition, and
20
// we reach this branch
21
- console.log("`local` was updated!");
21
+ console.log('`local` was updated!');
22
} else {
23
// With React Compiler enabled, `reassignLocal` is only created
24
// once, capturing a binding to `local` in that render pass.
@@ -28,7 +28,7 @@ function Component() {
28
//
29
// To protect against this, we disallow reassigning locals from
30
// functions that escape
31
- throw new Error("`local` not updated!");
31
+ throw new Error('`local` not updated!');
32
}
33
};
34
@@ -42,12 +42,12 @@ function Component() {
42
43
```
44
3 |
45
- 4 | const reassignLocal = (newValue) => {
45
+ 4 | const reassignLocal = newValue => {
46
> 5 | local = newValue;
47
| ^^^^^ InvalidReact: Reassigning a variable after render has completed can cause inconsistent behavior on subsequent renders. Consider using state instead. Variable `local` cannot be reassigned after render (5:5)
48
6 | };
49
7 |
50
- 8 | const onClick = (newValue) => {
50
+ 8 | const onClick = newValue => {
51
```
52
53
\ No newline at end of file
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-reassign-local-variable-in-jsx-callback.js
+5
-5
@@ -1,12 +1,12 @@
1
function Component() {
2
let local;
3
4
- const reassignLocal = (newValue) => {
4
+ const reassignLocal = newValue => {
5
local = newValue;
6
};
7
8
- const onClick = (newValue) => {
9
- reassignLocal("hello");
8
+ const onClick = newValue => {
9
+ reassignLocal('hello');
10
11
if (local === newValue) {
12
// Without React Compiler, `reassignLocal` is freshly created
@@ -14,7 +14,7 @@ function Component() {
14
// such that invoking reassignLocal will reassign the same
15
// binding that we are observing in the if condition, and
16
// we reach this branch
17
- console.log("`local` was updated!");
17
+ console.log('`local` was updated!');
18
} else {
19
// With React Compiler enabled, `reassignLocal` is only created
20
// once, capturing a binding to `local` in that render pass.
@@ -24,7 +24,7 @@ function Component() {
24
//
25
// To protect against this, we disallow reassigning locals from
26
// functions that escape
27
- throw new Error("`local` not updated!");
27
+ throw new Error('`local` not updated!');
28
}
29
};
30
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-ref-in-callback-invoked-during-render.expect.md
+4
-4
@@ -5,11 +5,11 @@
5
// @validateRefAccessDuringRender
6
function Component(props) {
7
const ref = useRef(null);
8
- const renderItem = (item) => {
8
+ const renderItem = item => {
9
const current = ref.current;
10
return <Foo item={item} current={current} />;
11
};
12
- return <Items>{props.items.map((item) => renderItem(item))}</Items>;
12
+ return <Items>{props.items.map(item => renderItem(item))}</Items>;
13
}
14
15
```
@@ -20,8 +20,8 @@ function Component(props) {
20
```
21
6 | return <Foo item={item} current={current} />;
22
7 | };
23
-> 8 | return <Items>{props.items.map((item) => renderItem(item))}</Items>;
24
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^ InvalidReact: Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef) (8:8)
23
+> 8 | return <Items>{props.items.map(item => renderItem(item))}</Items>;
24
+ | ^^^^^^^^^^^^^^^^^^^^^^^^ InvalidReact: Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef) (8:8)
25
9 | }
26
10 |
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-ref-in-callback-invoked-during-render.js
+2
-2
@@ -1,9 +1,9 @@
1
// @validateRefAccessDuringRender
2
function Component(props) {
3
const ref = useRef(null);
4
- const renderItem = (item) => {
4
+ const renderItem = item => {
5
const current = ref.current;
6
return <Foo item={item} current={current} />;
7
};
8
- return <Items>{props.items.map((item) => renderItem(item))}</Items>;
8
+ return <Items>{props.items.map(item => renderItem(item))}</Items>;
9
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-set-and-read-ref-nested-property-during-render.expect.md
+2
-2
@@ -4,7 +4,7 @@
4
```javascript
5
// @validateRefAccessDuringRender
6
function Component(props) {
7
- const ref = useRef({ inner: null });
7
+ const ref = useRef({inner: null});
8
ref.current.inner = props.value;
9
return ref.current.inner;
10
}
@@ -16,7 +16,7 @@ function Component(props) {
16
17
```
18
2 | function Component(props) {
19
- 3 | const ref = useRef({ inner: null });
19
+ 3 | const ref = useRef({inner: null});
20
> 4 | ref.current.inner = props.value;
21
| ^^^^^^^^^^^^^^^^^ InvalidReact: Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef) (4:4)
22
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-set-and-read-ref-nested-property-during-render.js
+1
-1
@@ -1,6 +1,6 @@
1
// @validateRefAccessDuringRender
2
function Component(props) {
3
- const ref = useRef({ inner: null });
3
+ const ref = useRef({inner: null});
4
ref.current.inner = props.value;
5
return ref.current.inner;
6
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-sketchy-code-use-forget.expect.md
+2
-2
@@ -4,7 +4,7 @@
4
```javascript
5
/* eslint-disable react-hooks/rules-of-hooks */
6
function lowercasecomponent() {
7
- "use forget";
7
+ 'use forget';
8
const x = [];
9
// eslint-disable-next-line react-hooks/rules-of-hooks
10
return <div>{x}</div>;
@@ -22,7 +22,7 @@ function lowercasecomponent() {
22
23
InvalidReact: React Compiler has skipped optimizing this component because one or more React ESLint rules were disabled. React Compiler only works when your components follow all the rules of React, disabling them may result in unexpected or incorrect behavior. eslint-disable-next-line react-hooks/rules-of-hooks (5:5)
24
2 | function lowercasecomponent() {
25
- 3 | "use forget";
25
+ 3 | 'use forget';
26
4 | const x = [];
27
```
28
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-sketchy-code-use-forget.js
+1
-1
@@ -1,6 +1,6 @@
1
/* eslint-disable react-hooks/rules-of-hooks */
2
function lowercasecomponent() {
3
- "use forget";
3
+ 'use forget';
4
const x = [];
5
// eslint-disable-next-line react-hooks/rules-of-hooks
6
return <div>{x}</div>;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-unclosed-eslint-suppression.expect.md
+2
-2
@@ -5,7 +5,7 @@
5
// Note: Everything below this is sketchy
6
/* eslint-disable react-hooks/rules-of-hooks */
7
function lowercasecomponent() {
8
- "use forget";
8
+ 'use forget';
9
const x = [];
10
return <div>{x}</div>;
11
}
@@ -42,7 +42,7 @@ function CrimesAgainstReact() {
42
43
InvalidReact: React Compiler has skipped optimizing this component because one or more React ESLint rules were disabled. React Compiler only works when your components follow all the rules of React, disabling them may result in unexpected or incorrect behavior. eslint-disable-next-line react-hooks/rules-of-hooks (25:25)
44
3 | function lowercasecomponent() {
45
- 4 | "use forget";
45
+ 4 | 'use forget';
46
5 | const x = [];
47
```
48
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-unclosed-eslint-suppression.js
+1
-1
@@ -1,7 +1,7 @@
1
// Note: Everything below this is sketchy
2
/* eslint-disable react-hooks/rules-of-hooks */
3
function lowercasecomponent() {
4
- "use forget";
4
+ 'use forget';
5
const x = [];
6
return <div>{x}</div>;
7
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-use-ref-added-to-dep-without-type-info.expect.md
+5
-5
@@ -3,15 +3,15 @@
3
4
```javascript
5
// @validateRefAccessDuringRender
6
-function Foo({ a }) {
6
+function Foo({a}) {
7
const ref = useRef();
8
// type information is lost here as we don't track types of fields
9
- const val = { ref };
9
+ const val = {ref};
10
// without type info, we don't know that val.ref.current is a ref value so we
11
// *would* end up depending on val.ref.current
12
// however, this is an instance of accessing a ref during render and is disallowed
13
// under React's rules, so we reject this input
14
- const x = { a, val: val.ref.current };
14
+ const x = {a, val: val.ref.current};
15
16
return <VideoList videos={x} />;
17
}
@@ -24,8 +24,8 @@ function Foo({ a }) {
24
```
25
3 | const ref = useRef();
26
4 | // type information is lost here as we don't track types of fields
27
-> 5 | const val = { ref };
28
- | ^^^ InvalidReact: Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef) (5:5)
27
+> 5 | const val = {ref};
28
+ | ^^^ InvalidReact: Ref values (the `current` property) may not be accessed during render. (https://react.dev/reference/react/useRef) (5:5)
29
6 | // without type info, we don't know that val.ref.current is a ref value so we
30
7 | // *would* end up depending on val.ref.current
31
8 | // however, this is an instance of accessing a ref during render and is disallowed
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-use-ref-added-to-dep-without-type-info.js
+3
-3
@@ -1,13 +1,13 @@
1
// @validateRefAccessDuringRender
2
-function Foo({ a }) {
2
+function Foo({a}) {
3
const ref = useRef();
4
// type information is lost here as we don't track types of fields
5
- const val = { ref };
5
+ const val = {ref};
6
// without type info, we don't know that val.ref.current is a ref value so we
7
// *would* end up depending on val.ref.current
8
// however, this is an instance of accessing a ref during render and is disallowed
9
// under React's rules, so we reject this input
10
- const x = { a, val: val.ref.current };
10
+ const x = {a, val: val.ref.current};
11
12
return <VideoList videos={x} />;
13
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-useEffect-dep-not-memoized.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @validateMemoizedEffectDependencies
6
-import { useEffect } from "react";
6
+import {useEffect} from 'react';
7
8
function Component(props) {
9
const data = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-useEffect-dep-not-memoized.js
+1
-1
@@ -1,5 +1,5 @@
1
// @validateMemoizedEffectDependencies
2
-import { useEffect } from "react";
2
+import {useEffect} from 'react';
3
4
function Component(props) {
5
const data = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-useInsertionEffect-dep-not-memoized.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @validateMemoizedEffectDependencies
6
-import { useInsertionEffect } from "react";
6
+import {useInsertionEffect} from 'react';
7
8
function Component(props) {
9
const data = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-useInsertionEffect-dep-not-memoized.js
+1
-1
@@ -1,5 +1,5 @@
1
// @validateMemoizedEffectDependencies
2
-import { useInsertionEffect } from "react";
2
+import {useInsertionEffect} from 'react';
3
4
function Component(props) {
5
const data = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-useLayoutEffect-dep-not-memoized.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @validateMemoizedEffectDependencies
6
-import { useLayoutEffect } from "react";
6
+import {useLayoutEffect} from 'react';
7
8
function Component(props) {
9
const data = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-useLayoutEffect-dep-not-memoized.js
+1
-1
@@ -1,5 +1,5 @@
1
// @validateMemoizedEffectDependencies
2
-import { useLayoutEffect } from "react";
2
+import {useLayoutEffect} from 'react';
3
4
function Component(props) {
5
const data = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-useMemo-callback-args.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a, b) {
6
- let x = useMemo((c) => a, []);
6
+ let x = useMemo(c => a, []);
7
return x;
8
}
9
@@ -14,8 +14,8 @@ function component(a, b) {
14
15
```
16
1 | function component(a, b) {
17
-> 2 | let x = useMemo((c) => a, []);
18
- | ^^^^^^^^ InvalidReact: useMemo callbacks may not accept any arguments (2:2)
17
+> 2 | let x = useMemo(c => a, []);
18
+ | ^^^^^^ InvalidReact: useMemo callbacks may not accept any arguments (2:2)
19
3 | return x;
20
4 | }
21
5 |
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-useMemo-callback-args.js
+1
-1
@@ -1,4 +1,4 @@
1
function component(a, b) {
2
- let x = useMemo((c) => a, []);
2
+ let x = useMemo(c => a, []);
3
return x;
4
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-write-but-dont-read-ref-in-render.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @validateRefAccessDuringRender
6
-function useHook({ value }) {
6
+function useHook({value}) {
7
const ref = useRef(null);
8
// Writing to a ref in render is against the rules:
9
ref.current = value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.invalid-write-but-dont-read-ref-in-render.js
+1
-1
@@ -1,5 +1,5 @@
1
// @validateRefAccessDuringRender
2
-function useHook({ value }) {
2
+function useHook({value}) {
3
const ref = useRef(null);
4
// Writing to a ref in render is against the rules:
5
ref.current = value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.modify-state-2.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { useState } from "react";
5
+import {useState} from 'react';
6
7
function Foo() {
8
- const [state, setState] = useState({ foo: { bar: 3 } });
8
+ const [state, setState] = useState({foo: {bar: 3}});
9
const foo = state.foo;
10
foo.bar = 1;
11
return state;
@@ -17,7 +17,7 @@ function Foo() {
17
## Error
18
19
```
20
- 4 | const [state, setState] = useState({ foo: { bar: 3 } });
20
+ 4 | const [state, setState] = useState({foo: {bar: 3}});
21
5 | const foo = state.foo;
22
> 6 | foo.bar = 1;
23
| ^^^ InvalidReact: Mutating a value returned from 'useState()', which should not be mutated. Use the setter function to update instead (6:6)
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.modify-state-2.js
+2
-2
@@ -1,7 +1,7 @@
1
-import { useState } from "react";
1
+import {useState} from 'react';
2
3
function Foo() {
4
- const [state, setState] = useState({ foo: { bar: 3 } });
4
+ const [state, setState] = useState({foo: {bar: 3}});
5
const foo = state.foo;
6
foo.bar = 1;
7
return state;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.modify-state.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useState } from "react";
5
+import {useState} from 'react';
6
7
function Foo() {
8
let [state, setState] = useState({});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.modify-state.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { useState } from "react";
1
+import {useState} from 'react';
2
3
function Foo() {
4
let [state, setState] = useState({});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.modify-useReducer-state.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { useReducer } from "react";
5
+import {useReducer} from 'react';
6
7
function Foo() {
8
- let [state, setState] = useReducer({ foo: 1 });
8
+ let [state, setState] = useReducer({foo: 1});
9
state.foo = 1;
10
return state;
11
}
@@ -17,7 +17,7 @@ function Foo() {
17
18
```
19
3 | function Foo() {
20
- 4 | let [state, setState] = useReducer({ foo: 1 });
20
+ 4 | let [state, setState] = useReducer({foo: 1});
21
> 5 | state.foo = 1;
22
| ^^^^^ InvalidReact: Mutating a value returned from 'useReducer()', which should not be mutated. Use the dispatch function to update instead (5:5)
23
6 | return state;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.modify-useReducer-state.js
+2
-2
@@ -1,7 +1,7 @@
1
-import { useReducer } from "react";
1
+import {useReducer} from 'react';
2
3
function Foo() {
4
- let [state, setState] = useReducer({ foo: 1 });
4
+ let [state, setState] = useReducer({foo: 1});
5
state.foo = 1;
6
return state;
7
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.mutate-captured-arg-separately.expect.md
+2
-2
@@ -8,7 +8,7 @@ function component(a) {
8
m(x);
9
};
10
11
- let x = { a };
11
+ let x = {a};
12
m(x);
13
return y;
14
}
@@ -25,7 +25,7 @@ function component(a) {
25
| ^^^^ Todo: Handle non-const declarations for hoisting. variable "x" declared with let (4:4)
26
5 | };
27
6 |
28
- 7 | let x = { a };
28
+ 7 | let x = {a};
29
```
30
31
\ No newline at end of file
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.mutate-captured-arg-separately.js
+1
-1
@@ -4,7 +4,7 @@ function component(a) {
4
m(x);
5
};
6
7
- let x = { a };
7
+ let x = {a};
8
m(x);
9
return y;
10
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.mutate-function-property.expect.md
+4
-4
@@ -4,9 +4,9 @@
4
```javascript
5
export function ViewModeSelector(props) {
6
const renderIcon = () => <AcceptIcon />;
7
- renderIcon.displayName = "AcceptIcon";
7
+ renderIcon.displayName = 'AcceptIcon';
8
9
- return <Dropdown checkableIndicator={{ children: renderIcon }} />;
9
+ return <Dropdown checkableIndicator={{children: renderIcon}} />;
10
}
11
12
```
@@ -17,10 +17,10 @@ export function ViewModeSelector(props) {
17
```
18
1 | export function ViewModeSelector(props) {
19
2 | const renderIcon = () => <AcceptIcon />;
20
-> 3 | renderIcon.displayName = "AcceptIcon";
20
+> 3 | renderIcon.displayName = 'AcceptIcon';
21
| ^^^^^^^^^^ InvalidReact: This mutates a variable that React considers immutable (3:3)
22
4 |
23
- 5 | return <Dropdown checkableIndicator={{ children: renderIcon }} />;
23
+ 5 | return <Dropdown checkableIndicator={{children: renderIcon}} />;
24
6 | }
25
```
26
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.mutate-function-property.js
+2
-2
@@ -1,6 +1,6 @@
1
export function ViewModeSelector(props) {
2
const renderIcon = () => <AcceptIcon />;
3
- renderIcon.displayName = "AcceptIcon";
3
+ renderIcon.displayName = 'AcceptIcon';
4
5
- return <Dropdown checkableIndicator={{ children: renderIcon }} />;
5
+ return <Dropdown checkableIndicator={{children: renderIcon}} />;
6
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.not-useEffect-external-mutate.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-let x = { a: 42 };
5
+let x = {a: 42};
6
7
function Component(props) {
8
foo(() => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.not-useEffect-external-mutate.js
+1
-1
@@ -1,4 +1,4 @@
1
-let x = { a: 42 };
1
+let x = {a: 42};
2
3
function Component(props) {
4
foo(() => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.ref-like-name-not-Ref.expect.md
+2
-2
@@ -3,10 +3,10 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useCallback, useRef } from "react";
6
+import {useCallback, useRef} from 'react';
7
8
function useCustomRef() {
9
- return useRef({ click: () => {} });
9
+ return useRef({click: () => {}});
10
}
11
12
function Foo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.ref-like-name-not-Ref.js
+2
-2
@@ -1,8 +1,8 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useCallback, useRef } from "react";
2
+import {useCallback, useRef} from 'react';
3
4
function useCustomRef() {
5
- return useRef({ click: () => {} });
5
+ return useRef({click: () => {}});
6
}
7
8
function Foo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.ref-like-name-not-a-ref.expect.md
+2
-2
@@ -3,10 +3,10 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useCallback, useRef } from "react";
6
+import {useCallback, useRef} from 'react';
7
8
function useCustomRef() {
9
- return useRef({ click: () => {} });
9
+ return useRef({click: () => {}});
10
}
11
12
function Foo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.ref-like-name-not-a-ref.js
+2
-2
@@ -1,8 +1,8 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useCallback, useRef } from "react";
2
+import {useCallback, useRef} from 'react';
3
4
function useCustomRef() {
5
- return useRef({ click: () => {} });
5
+ return useRef({click: () => {}});
6
}
7
8
function Foo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-for-await-loops.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-async function Component({ items }) {
5
+async function Component({items}) {
6
const x = [];
7
for await (const item of items) {
8
x.push(item);
@@ -16,7 +16,7 @@ async function Component({ items }) {
16
## Error
17
18
```
19
- 1 | async function Component({ items }) {
19
+ 1 | async function Component({items}) {
20
2 | const x = [];
21
> 3 | for await (const item of items) {
22
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-for-await-loops.js
+1
-1
@@ -1,4 +1,4 @@
1
-async function Component({ items }) {
1
+async function Component({items}) {
2
const x = [];
3
for await (const item of items) {
4
x.push(item);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-for-in-loop-with-context-variable-iterator.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useHook } from "shared-runtime";
5
+import {useHook} from 'shared-runtime';
6
7
function Component(props) {
8
const data = useHook();
@@ -22,7 +22,7 @@ function Component(props) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
25
- params: [{ data: { a: "a", b: true, c: "hello" } }],
25
+ params: [{data: {a: 'a', b: true, c: 'hello'}}],
26
};
27
28
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-for-in-loop-with-context-variable-iterator.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { useHook } from "shared-runtime";
1
+import {useHook} from 'shared-runtime';
2
3
function Component(props) {
4
const data = useHook();
@@ -18,5 +18,5 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ data: { a: "a", b: true, c: "hello" } }],
21
+ params: [{data: {a: 'a', b: true, c: 'hello'}}],
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-for-of-loop-with-context-variable-iterator.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useHook } from "shared-runtime";
5
+import {useHook} from 'shared-runtime';
6
7
function Component(props) {
8
const data = useHook();
@@ -22,7 +22,7 @@ function Component(props) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
25
- params: [{ data: [{ id: "1" }, { id: "2" }] }],
25
+ params: [{data: [{id: '1'}, {id: '2'}]}],
26
};
27
28
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-for-of-loop-with-context-variable-iterator.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { useHook } from "shared-runtime";
1
+import {useHook} from 'shared-runtime';
2
3
function Component(props) {
4
const data = useHook();
@@ -18,5 +18,5 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ data: [{ id: "1" }, { id: "2" }] }],
21
+ params: [{data: [{id: '1'}, {id: '2'}]}],
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-kitchensink.expect.md
+6
-6
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function foo([a, b], { c, d, e = "e" }, f = "f", ...args) {
5
+function foo([a, b], {c, d, e = 'e'}, f = 'f', ...args) {
6
let i = 0;
7
var x = [];
8
@@ -13,8 +13,8 @@ function foo([a, b], { c, d, e = "e" }, f = "f", ...args) {
13
}
14
}
15
16
- const g = { b() {}, c: () => {} };
17
- const { z, aa = "aa" } = useCustom();
16
+ const g = {b() {}, c: () => {}};
17
+ const {z, aa = 'aa'} = useCustom();
18
19
<Button haha={1}></Button>;
20
<Button>{/** empty */}</Button>;
@@ -41,10 +41,10 @@ function foo([a, b], { c, d, e = "e" }, f = "f", ...args) {
41
}
42
for ([v] of [[1], [2]]) {
43
}
44
- for ({ v } of [{ v: 1 }, { v: 2 }]) {
44
+ for ({v} of [{v: 1}, {v: 2}]) {
45
}
46
47
- for (let x in { a: 1 }) {
47
+ for (let x in {a: 1}) {
48
}
49
50
let updateIdentifier = 0;
@@ -79,7 +79,7 @@ let moduleLocal = false;
79
## Error
80
81
```
82
- 1 | function foo([a, b], { c, d, e = "e" }, f = "f", ...args) {
82
+ 1 | function foo([a, b], {c, d, e = 'e'}, f = 'f', ...args) {
83
2 | let i = 0;
84
> 3 | var x = [];
85
| ^^^^^^^^^^^ Todo: (BuildHIR::lowerStatement) Handle var kinds in VariableDeclaration (3:3)
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-kitchensink.js
+5
-5
@@ -1,4 +1,4 @@
1
-function foo([a, b], { c, d, e = "e" }, f = "f", ...args) {
1
+function foo([a, b], {c, d, e = 'e'}, f = 'f', ...args) {
2
let i = 0;
3
var x = [];
4
@@ -9,8 +9,8 @@ function foo([a, b], { c, d, e = "e" }, f = "f", ...args) {
9
}
10
}
11
12
- const g = { b() {}, c: () => {} };
13
- const { z, aa = "aa" } = useCustom();
12
+ const g = {b() {}, c: () => {}};
13
+ const {z, aa = 'aa'} = useCustom();
14
15
<Button haha={1}></Button>;
16
<Button>{/** empty */}</Button>;
@@ -37,10 +37,10 @@ function foo([a, b], { c, d, e = "e" }, f = "f", ...args) {
37
}
38
for ([v] of [[1], [2]]) {
39
}
40
- for ({ v } of [{ v: 1 }, { v: 2 }]) {
40
+ for ({v} of [{v: 1}, {v: 2}]) {
41
}
42
43
- for (let x in { a: 1 }) {
43
+ for (let x in {a: 1}) {
44
}
45
46
let updateIdentifier = 0;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-nested-method-calls-lower-property-load-into-temporary.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeArray } from "shared-runtime";
5
+import {makeArray} from 'shared-runtime';
6
7
function Component(props) {
8
const items = makeArray(0, 1, 2, null, 4, false, 6);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-nested-method-calls-lower-property-load-into-temporary.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { makeArray } from "shared-runtime";
1
+import {makeArray} from 'shared-runtime';
2
3
function Component(props) {
4
const items = makeArray(0, 1, 2, null, 4, false, 6);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-new-target-meta-property.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
function foo() {
8
const nt = new.target;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-new-target-meta-property.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
function foo() {
4
const nt = new.target;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-object-expression-computed-key-modified-during-after-construction-sequence-expr.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity, mutate, mutateAndReturn } from "shared-runtime";
5
+import {identity, mutate, mutateAndReturn} from 'shared-runtime';
6
7
function Component(props) {
8
const key = {};
@@ -15,7 +15,7 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ value: 42 }],
18
+ params: [{value: 42}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-object-expression-computed-key-modified-during-after-construction-sequence-expr.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { identity, mutate, mutateAndReturn } from "shared-runtime";
1
+import {identity, mutate, mutateAndReturn} from 'shared-runtime';
2
3
function Component(props) {
4
const key = {};
@@ -11,5 +11,5 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ value: 42 }],
14
+ params: [{value: 42}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-object-expression-computed-key-modified-during-after-construction.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity, mutate, mutateAndReturn } from "shared-runtime";
5
+import {identity, mutate, mutateAndReturn} from 'shared-runtime';
6
7
function Component(props) {
8
const key = {};
@@ -15,7 +15,7 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ value: 42 }],
18
+ params: [{value: 42}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-object-expression-computed-key-modified-during-after-construction.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { identity, mutate, mutateAndReturn } from "shared-runtime";
1
+import {identity, mutate, mutateAndReturn} from 'shared-runtime';
2
3
function Component(props) {
4
const key = {};
@@ -11,5 +11,5 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ value: 42 }],
14
+ params: [{value: 42}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-object-expression-computed-key-mutate-key-while-constructing-object.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity, mutate, mutateAndReturn } from "shared-runtime";
5
+import {identity, mutate, mutateAndReturn} from 'shared-runtime';
6
7
function Component(props) {
8
const key = {};
@@ -14,7 +14,7 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ value: 42 }],
17
+ params: [{value: 42}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-object-expression-computed-key-mutate-key-while-constructing-object.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { identity, mutate, mutateAndReturn } from "shared-runtime";
1
+import {identity, mutate, mutateAndReturn} from 'shared-runtime';
2
3
function Component(props) {
4
const key = {};
@@ -10,5 +10,5 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ value: 42 }],
13
+ params: [{value: 42}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-object-expression-get-syntax.expect.md
+4
-4
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function Component({ value }) {
5
+function Component({value}) {
6
const object = {
7
get value() {
8
return value;
@@ -13,8 +13,8 @@ function Component({ value }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: foo,
16
- params: [{ value: 0 }],
17
- sequentialRenders: [{ value: 1 }, { value: 2 }],
16
+ params: [{value: 0}],
17
+ sequentialRenders: [{value: 1}, {value: 2}],
18
};
19
20
```
@@ -23,7 +23,7 @@ export const FIXTURE_ENTRYPOINT = {
23
## Error
24
25
```
26
- 1 | function Component({ value }) {
26
+ 1 | function Component({value}) {
27
2 | const object = {
28
> 3 | get value() {
29
| ^^^^^^^^^^^^^
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-object-expression-get-syntax.js
+3
-3
@@ -1,4 +1,4 @@
1
-function Component({ value }) {
1
+function Component({value}) {
2
const object = {
3
get value() {
4
return value;
@@ -9,6 +9,6 @@ function Component({ value }) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: foo,
12
- params: [{ value: 0 }],
13
- sequentialRenders: [{ value: 1 }, { value: 2 }],
12
+ params: [{value: 0}],
13
+ sequentialRenders: [{value: 1}, {value: 2}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-object-expression-set-syntax.expect.md
+2
-2
@@ -15,8 +15,8 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: foo,
18
- params: [{ value: 0 }],
19
- sequentialRenders: [{ value: 1 }, { value: 2 }],
18
+ params: [{value: 0}],
19
+ sequentialRenders: [{value: 1}, {value: 2}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-object-expression-set-syntax.js
+2
-2
@@ -11,6 +11,6 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: [{ value: 0 }],
15
- sequentialRenders: [{ value: 1 }, { value: 2 }],
14
+ params: [{value: 0}],
15
+ sequentialRenders: [{value: 1}, {value: 2}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-optional-call-chain-in-logical-expr.expect.md
+4
-4
@@ -2,16 +2,16 @@
2
## Input
3
4
```javascript
5
-import { useNoAlias } from "shared-runtime";
5
+import {useNoAlias} from 'shared-runtime';
6
7
-function useFoo(props: { value: { x: string; y: string } | null }) {
7
+function useFoo(props: {value: {x: string; y: string} | null}) {
8
const value = props.value;
9
return useNoAlias(value?.x, value?.y) ?? {};
10
}
11
12
export const FIXTURE_ENTRYPONT = {
13
fn: useFoo,
14
- props: [{ value: null }],
14
+ props: [{value: null}],
15
};
16
17
```
@@ -20,7 +20,7 @@ export const FIXTURE_ENTRYPONT = {
20
## Error
21
22
```
23
- 3 | function useFoo(props: { value: { x: string; y: string } | null }) {
23
+ 3 | function useFoo(props: {value: {x: string; y: string} | null}) {
24
4 | const value = props.value;
25
> 5 | return useNoAlias(value?.x, value?.y) ?? {};
26
| ^^^^^^^^ Todo: Unexpected terminal kind `optional` for logical test block (5:5)
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-optional-call-chain-in-logical-expr.ts
+3
-3
@@ -1,11 +1,11 @@
1
-import { useNoAlias } from "shared-runtime";
1
+import {useNoAlias} from 'shared-runtime';
2
3
-function useFoo(props: { value: { x: string; y: string } | null }) {
3
+function useFoo(props: {value: {x: string; y: string} | null}) {
4
const value = props.value;
5
return useNoAlias(value?.x, value?.y) ?? {};
6
}
7
8
export const FIXTURE_ENTRYPONT = {
9
fn: useFoo,
10
- props: [{ value: null }],
10
+ props: [{value: null}],
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-optional-call-chain-in-optional.expect.md
+5
-5
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-function useFoo(props: { value: { x: string; y: string } | null }) {
5
+function useFoo(props: {value: {x: string; y: string} | null}) {
6
const value = props.value;
7
- return createArray(value?.x, value?.y)?.join(", ");
7
+ return createArray(value?.x, value?.y)?.join(', ');
8
}
9
10
function createArray<T>(...args: Array<T>): Array<T> {
@@ -13,7 +13,7 @@ function createArray<T>(...args: Array<T>): Array<T> {
13
14
export const FIXTURE_ENTRYPONT = {
15
fn: useFoo,
16
- props: [{ value: null }],
16
+ props: [{value: null}],
17
};
18
19
```
@@ -22,9 +22,9 @@ export const FIXTURE_ENTRYPONT = {
22
## Error
23
24
```
25
- 1 | function useFoo(props: { value: { x: string; y: string } | null }) {
25
+ 1 | function useFoo(props: {value: {x: string; y: string} | null}) {
26
2 | const value = props.value;
27
-> 3 | return createArray(value?.x, value?.y)?.join(", ");
27
+> 3 | return createArray(value?.x, value?.y)?.join(', ');
28
| ^^^^^^^^ Todo: Unexpected terminal kind `optional` for optional test block (3:3)
29
4 | }
30
5 |
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-optional-call-chain-in-optional.ts
+3
-3
@@ -1,6 +1,6 @@
1
-function useFoo(props: { value: { x: string; y: string } | null }) {
1
+function useFoo(props: {value: {x: string; y: string} | null}) {
2
const value = props.value;
3
- return createArray(value?.x, value?.y)?.join(", ");
3
+ return createArray(value?.x, value?.y)?.join(', ');
4
}
5
6
function createArray<T>(...args: Array<T>): Array<T> {
@@ -9,5 +9,5 @@ function createArray<T>(...args: Array<T>): Array<T> {
9
10
export const FIXTURE_ENTRYPONT = {
11
fn: useFoo,
12
- props: [{ value: null }],
12
+ props: [{value: null}],
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-optional-call-chain-in-ternary.expect.md
+4
-4
@@ -2,16 +2,16 @@
2
## Input
3
4
```javascript
5
-import { useNoAlias } from "shared-runtime";
5
+import {useNoAlias} from 'shared-runtime';
6
7
-function useFoo(props: { value: { x: string; y: string } | null }) {
7
+function useFoo(props: {value: {x: string; y: string} | null}) {
8
const value = props.value;
9
return useNoAlias(value?.x, value?.y) ? {} : null;
10
}
11
12
export const FIXTURE_ENTRYPONT = {
13
fn: useFoo,
14
- props: [{ value: null }],
14
+ props: [{value: null}],
15
};
16
17
```
@@ -20,7 +20,7 @@ export const FIXTURE_ENTRYPONT = {
20
## Error
21
22
```
23
- 3 | function useFoo(props: { value: { x: string; y: string } | null }) {
23
+ 3 | function useFoo(props: {value: {x: string; y: string} | null}) {
24
4 | const value = props.value;
25
> 5 | return useNoAlias(value?.x, value?.y) ? {} : null;
26
| ^^^^^^^^ Todo: Unexpected terminal kind `optional` for ternary test block (5:5)
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-optional-call-chain-in-ternary.ts
+3
-3
@@ -1,11 +1,11 @@
1
-import { useNoAlias } from "shared-runtime";
1
+import {useNoAlias} from 'shared-runtime';
2
3
-function useFoo(props: { value: { x: string; y: string } | null }) {
3
+function useFoo(props: {value: {x: string; y: string} | null}) {
4
const value = props.value;
5
return useNoAlias(value?.x, value?.y) ? {} : null;
6
}
7
8
export const FIXTURE_ENTRYPONT = {
9
fn: useFoo,
10
- props: [{ value: null }],
10
+ props: [{value: null}],
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-reassign-const.expect.md
+5
-5
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
-function Component({ foo }) {
7
+function Component({foo}) {
8
let bar = foo.bar;
9
return (
10
<Stringify
@@ -21,10 +21,10 @@ function Component({ foo }) {
21
## Error
22
23
```
24
- 1 | import { Stringify } from "shared-runtime";
24
+ 1 | import {Stringify} from 'shared-runtime';
25
2 |
26
-> 3 | function Component({ foo }) {
27
- | ^^^ Todo: Support destructuring of context variables (3:3)
26
+> 3 | function Component({foo}) {
27
+ | ^^^ Todo: Support destructuring of context variables (3:3)
28
4 | let bar = foo.bar;
29
5 | return (
30
6 | <Stringify
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-reassign-const.js
+2
-2
@@ -1,6 +1,6 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
-function Component({ foo }) {
3
+function Component({foo}) {
4
let bar = foo.bar;
5
return (
6
<Stringify
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-repro-unmemoized-callback-captured-in-context-variable.expect.md
+8
-8
@@ -3,10 +3,10 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
7
-import { ValidateMemoization, useHook } from "shared-runtime";
6
+import {useMemo} from 'react';
7
+import {ValidateMemoization, useHook} from 'shared-runtime';
8
9
-function UnmemoizedCallbackCapturedInContextVariable({ cond1, cond2 }) {
9
+function UnmemoizedCallbackCapturedInContextVariable({cond1, cond2}) {
10
// The return value is captured by `x` which is a context variable, which
11
// extends a's range to include the call instruction. This prevents the entire
12
// range from being memoized
@@ -35,12 +35,12 @@ function UnmemoizedCallbackCapturedInContextVariable({ cond1, cond2 }) {
35
36
export const FIXTURE_ENTRYPOINT = {
37
fn: UnmemoizedCallbackCapturedInContextVariable,
38
- params: [{ cond1: true, cond2: false }],
38
+ params: [{cond1: true, cond2: false}],
39
sequentialRenders: [
40
- { cond1: true, cond2: true },
41
- { cond1: false, cond2: true },
42
- { cond1: false, cond2: true }, // fails sprout bc memoization is not preserved
43
- { cond1: false, cond2: false },
40
+ {cond1: true, cond2: true},
41
+ {cond1: false, cond2: true},
42
+ {cond1: false, cond2: true}, // fails sprout bc memoization is not preserved
43
+ {cond1: false, cond2: false},
44
],
45
};
46
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-repro-unmemoized-callback-captured-in-context-variable.tsx
+8
-8
@@ -1,8 +1,8 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
3
-import { ValidateMemoization, useHook } from "shared-runtime";
2
+import {useMemo} from 'react';
3
+import {ValidateMemoization, useHook} from 'shared-runtime';
4
5
-function UnmemoizedCallbackCapturedInContextVariable({ cond1, cond2 }) {
5
+function UnmemoizedCallbackCapturedInContextVariable({cond1, cond2}) {
6
// The return value is captured by `x` which is a context variable, which
7
// extends a's range to include the call instruction. This prevents the entire
8
// range from being memoized
@@ -31,11 +31,11 @@ function UnmemoizedCallbackCapturedInContextVariable({ cond1, cond2 }) {
31
32
export const FIXTURE_ENTRYPOINT = {
33
fn: UnmemoizedCallbackCapturedInContextVariable,
34
- params: [{ cond1: true, cond2: false }],
34
+ params: [{cond1: true, cond2: false}],
35
sequentialRenders: [
36
- { cond1: true, cond2: true },
37
- { cond1: false, cond2: true },
38
- { cond1: false, cond2: true }, // fails sprout bc memoization is not preserved
39
- { cond1: false, cond2: false },
36
+ {cond1: true, cond2: true},
37
+ {cond1: false, cond2: true},
38
+ {cond1: false, cond2: true}, // fails sprout bc memoization is not preserved
39
+ {cond1: false, cond2: false},
40
],
41
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-useCallback-accesses-ref-mutated-later-via-function-preserve-memoization.expect.md
+6
-6
@@ -3,12 +3,12 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees
6
-import { useCallback, useRef } from "react";
6
+import {useCallback, useRef} from 'react';
7
8
function Component(props) {
9
- const ref = useRef({ inner: null });
9
+ const ref = useRef({inner: null});
10
11
- const onChange = useCallback((event) => {
11
+ const onChange = useCallback(event => {
12
// The ref should still be mutable here even though function deps are frozen in
13
// @enablePreserveExistingMemoizationGuarantees mode
14
ref.current.inner = event.target.value;
@@ -34,10 +34,10 @@ export const FIXTURE_ENTRYPOINT = {
34
## Error
35
36
```
37
- 5 | const ref = useRef({ inner: null });
37
+ 5 | const ref = useRef({inner: null});
38
6 |
39
-> 7 | const onChange = useCallback((event) => {
40
- | ^^^^^^^^^^^^
39
+> 7 | const onChange = useCallback(event => {
40
+ | ^^^^^^^^^^
41
> 8 | // The ref should still be mutable here even though function deps are frozen in
42
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
43
> 9 | // @enablePreserveExistingMemoizationGuarantees mode
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-useCallback-accesses-ref-mutated-later-via-function-preserve-memoization.js
+3
-3
@@ -1,10 +1,10 @@
1
// @enablePreserveExistingMemoizationGuarantees
2
-import { useCallback, useRef } from "react";
2
+import {useCallback, useRef} from 'react';
3
4
function Component(props) {
5
- const ref = useRef({ inner: null });
5
+ const ref = useRef({inner: null});
6
7
- const onChange = useCallback((event) => {
7
+ const onChange = useCallback(event => {
8
// The ref should still be mutable here even though function deps are frozen in
9
// @enablePreserveExistingMemoizationGuarantees mode
10
ref.current.inner = event.target.value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-useCallback-set-ref-nested-property-ref-modified-later-preserve-memoization.expect.md
+6
-6
@@ -3,12 +3,12 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees
6
-import { useCallback, useRef } from "react";
6
+import {useCallback, useRef} from 'react';
7
8
function Component(props) {
9
- const ref = useRef({ inner: null });
9
+ const ref = useRef({inner: null});
10
11
- const onChange = useCallback((event) => {
11
+ const onChange = useCallback(event => {
12
// The ref should still be mutable here even though function deps are frozen in
13
// @enablePreserveExistingMemoizationGuarantees mode
14
ref.current.inner = event.target.value;
@@ -31,10 +31,10 @@ export const FIXTURE_ENTRYPOINT = {
31
## Error
32
33
```
34
- 5 | const ref = useRef({ inner: null });
34
+ 5 | const ref = useRef({inner: null});
35
6 |
36
-> 7 | const onChange = useCallback((event) => {
37
- | ^^^^^^^^^^^^
36
+> 7 | const onChange = useCallback(event => {
37
+ | ^^^^^^^^^^
38
> 8 | // The ref should still be mutable here even though function deps are frozen in
39
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
40
> 9 | // @enablePreserveExistingMemoizationGuarantees mode
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.todo-useCallback-set-ref-nested-property-ref-modified-later-preserve-memoization.js
+3
-3
@@ -1,10 +1,10 @@
1
// @enablePreserveExistingMemoizationGuarantees
2
-import { useCallback, useRef } from "react";
2
+import {useCallback, useRef} from 'react';
3
4
function Component(props) {
5
- const ref = useRef({ inner: null });
5
+ const ref = useRef({inner: null});
6
7
- const onChange = useCallback((event) => {
7
+ const onChange = useCallback(event => {
8
// The ref should still be mutable here even though function deps are frozen in
9
// @enablePreserveExistingMemoizationGuarantees mode
10
ref.current.inner = event.target.value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.unconditional-set-state-in-render-with-loop-throw.expect.md
+1
-1
@@ -9,7 +9,7 @@ function Component(props) {
9
if (props.cond) {
10
break;
11
} else {
12
- throw new Error("bye!");
12
+ throw new Error('bye!');
13
}
14
}
15
setState(true);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.unconditional-set-state-in-render-with-loop-throw.js
+1
-1
@@ -5,7 +5,7 @@ function Component(props) {
5
if (props.cond) {
6
break;
7
} else {
8
- throw new Error("bye!");
8
+ throw new Error('bye!');
9
}
10
}
11
setState(true);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.useMemo-non-literal-depslist.expect.md
+6
-6
@@ -2,24 +2,24 @@
2
## Input
3
4
```javascript
5
-import { useMemo } from "react";
5
+import {useMemo} from 'react';
6
7
// react-hooks-deps would error on this code (complex expression in depslist),
8
// so Forget could bailout here
9
-function App({ text, hasDeps }) {
9
+function App({text, hasDeps}) {
10
const resolvedText = useMemo(
11
() => {
12
return text.toUpperCase();
13
},
14
- hasDeps ? null : [text] // should be DCE'd
14
+ hasDeps ? null : [text], // should be DCE'd
15
);
16
return resolvedText;
17
}
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: App,
21
- params: ["TodoAdd"],
22
- isComponent: "TodoAdd",
21
+ params: ['TodoAdd'],
22
+ isComponent: 'TodoAdd',
23
};
24
25
```
@@ -30,7 +30,7 @@ export const FIXTURE_ENTRYPOINT = {
30
```
31
8 | return text.toUpperCase();
32
9 | },
33
-> 10 | hasDeps ? null : [text] // should be DCE'd
33
+> 10 | hasDeps ? null : [text], // should be DCE'd
34
| ^^^^^^^^^^^^^^^^^^^^^^^ InvalidReact: Expected the dependency list for useMemo to be an array literal (10:10)
35
11 | );
36
12 | return resolvedText;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.useMemo-non-literal-depslist.ts
+5
-5
@@ -1,19 +1,19 @@
1
-import { useMemo } from "react";
1
+import {useMemo} from 'react';
2
3
// react-hooks-deps would error on this code (complex expression in depslist),
4
// so Forget could bailout here
5
-function App({ text, hasDeps }) {
5
+function App({text, hasDeps}) {
6
const resolvedText = useMemo(
7
() => {
8
return text.toUpperCase();
9
},
10
- hasDeps ? null : [text] // should be DCE'd
10
+ hasDeps ? null : [text], // should be DCE'd
11
);
12
return resolvedText;
13
}
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: App,
17
- params: ["TodoAdd"],
18
- isComponent: "TodoAdd",
17
+ params: ['TodoAdd'],
18
+ isComponent: 'TodoAdd',
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.validate-memoized-effect-deps-invalidated-dep-value.expect.md
+2
-2
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @validateMemoizedEffectDependencies
6
-import { useHook } from "shared-runtime";
6
+import {useHook} from 'shared-runtime';
7
8
function Component(props) {
9
const x = [];
@@ -19,7 +19,7 @@ function Component(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: [{ value: "sathya" }],
22
+ params: [{value: 'sathya'}],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.validate-memoized-effect-deps-invalidated-dep-value.js
+2
-2
@@ -1,5 +1,5 @@
1
// @validateMemoizedEffectDependencies
2
-import { useHook } from "shared-runtime";
2
+import {useHook} from 'shared-runtime';
3
4
function Component(props) {
5
const x = [];
@@ -15,5 +15,5 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ value: "sathya" }],
18
+ params: [{value: 'sathya'}],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.validate-mutate-ref-arg-in-render.expect.md
+1
-1
@@ -10,7 +10,7 @@ function Foo(props, ref) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Foo,
13
- params: [{ bar: "foo" }, { ref: { cuurrent: 1 } }],
13
+ params: [{bar: 'foo'}, {ref: {cuurrent: 1}}],
14
isComponent: true,
15
};
16
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/error.validate-mutate-ref-arg-in-render.js
+1
-1
@@ -6,6 +6,6 @@ function Foo(props, ref) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Foo,
9
- params: [{ bar: "foo" }, { ref: { cuurrent: 1 } }],
9
+ params: [{bar: 'foo'}, {ref: {cuurrent: 1}}],
10
isComponent: true,
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-destructured-rest-element.expect.md
+3
-3
@@ -4,7 +4,7 @@
4
```javascript
5
function Component(props) {
6
// b is an object, must be memoized even though the input is not memoized
7
- const { a, ...b } = props.a;
7
+ const {a, ...b} = props.a;
8
// d is an array, mut be memoized even though the input is not memoized
9
const [c, ...d] = props.c;
10
return <div b={b} d={d}></div>;
@@ -12,8 +12,8 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-destructured-rest-element.js
+3
-3
@@ -1,6 +1,6 @@
1
function Component(props) {
2
// b is an object, must be memoized even though the input is not memoized
3
- const { a, ...b } = props.a;
3
+ const {a, ...b} = props.a;
4
// d is an array, mut be memoized even though the input is not memoized
5
const [c, ...d] = props.c;
6
return <div b={b} d={d}></div>;
@@ -8,6 +8,6 @@ function Component(props) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-jsx-child.expect.md
+2
-2
@@ -16,8 +16,8 @@ function foo(a, b, c) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: foo,
19
- params: ["TodoAdd"],
20
- isComponent: "TodoAdd",
19
+ params: ['TodoAdd'],
20
+ isComponent: 'TodoAdd',
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-jsx-child.js
+2
-2
@@ -12,6 +12,6 @@ function foo(a, b, c) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: foo,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-logical.expect.md
+2
-2
@@ -13,8 +13,8 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-logical.js
+2
-2
@@ -9,6 +9,6 @@ function Component(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-non-escaping-interleaved-allocating-dependency.expect.md
+2
-2
@@ -20,8 +20,8 @@ function Component(props) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
- params: ["TodoAdd"],
24
- isComponent: "TodoAdd",
23
+ params: ['TodoAdd'],
24
+ isComponent: 'TodoAdd',
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-non-escaping-interleaved-allocating-dependency.js
+2
-2
@@ -16,6 +16,6 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: ["TodoAdd"],
20
- isComponent: "TodoAdd",
19
+ params: ['TodoAdd'],
20
+ isComponent: 'TodoAdd',
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-non-escaping-interleaved-allocating-nested-dependency.expect.md
+2
-2
@@ -29,8 +29,8 @@ function Component(props) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: Component,
32
- params: ["TodoAdd"],
33
- isComponent: "TodoAdd",
32
+ params: ['TodoAdd'],
33
+ isComponent: 'TodoAdd',
34
};
35
36
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-non-escaping-interleaved-allocating-nested-dependency.js
+2
-2
@@ -25,6 +25,6 @@ function Component(props) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Component,
28
- params: ["TodoAdd"],
29
- isComponent: "TodoAdd",
28
+ params: ['TodoAdd'],
29
+ isComponent: 'TodoAdd',
30
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-non-escaping-interleaved-primitive-dependency.expect.md
+2
-2
@@ -22,8 +22,8 @@ function Component(props) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
25
- params: ["TodoAdd"],
26
- isComponent: "TodoAdd",
25
+ params: ['TodoAdd'],
26
+ isComponent: 'TodoAdd',
27
};
28
29
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-non-escaping-interleaved-primitive-dependency.js
+2
-2
@@ -18,6 +18,6 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: ["TodoAdd"],
22
- isComponent: "TodoAdd",
21
+ params: ['TodoAdd'],
22
+ isComponent: 'TodoAdd',
23
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-not-conditional-test.expect.md
+2
-2
@@ -10,8 +10,8 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-not-conditional-test.js
+2
-2
@@ -6,6 +6,6 @@ function Component(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-not-if-test.expect.md
+2
-2
@@ -15,8 +15,8 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-not-if-test.js
+2
-2
@@ -11,6 +11,6 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-not-switch-case.expect.md
+2
-2
@@ -15,8 +15,8 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-not-switch-case.js
+2
-2
@@ -11,6 +11,6 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-not-switch-test.expect.md
+2
-2
@@ -15,8 +15,8 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/escape-analysis-not-switch-test.js
+2
-2
@@ -11,6 +11,6 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/existing-variables-with-c-name.expect.md
+2
-2
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import { useMemo, useState } from "react";
6
-import { ValidateMemoization } from "shared-runtime";
5
+import {useMemo, useState} from 'react';
6
+import {ValidateMemoization} from 'shared-runtime';
7
8
function Component(props) {
9
const [state] = useState(0);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/existing-variables-with-c-name.js
+2
-2
@@ -1,5 +1,5 @@
1
-import { useMemo, useState } from "react";
2
-import { ValidateMemoization } from "shared-runtime";
1
+import {useMemo, useState} from 'react';
2
+import {ValidateMemoization} from 'shared-runtime';
3
4
function Component(props) {
5
const [state] = useState(0);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/expression-with-assignment-dynamic.expect.md
+2
-2
@@ -9,8 +9,8 @@ function f(y) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: f,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/expression-with-assignment-dynamic.js
+2
-2
@@ -5,6 +5,6 @@ function f(y) {
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: f,
8
- params: ["TodoAdd"],
9
- isComponent: "TodoAdd",
8
+ params: ['TodoAdd'],
9
+ isComponent: 'TodoAdd',
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/extend-scopes-if.expect.md
+2
-2
@@ -19,8 +19,8 @@ function foo(a, b, c) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: foo,
22
- params: ["TodoAdd"],
23
- isComponent: "TodoAdd",
22
+ params: ['TodoAdd'],
23
+ isComponent: 'TodoAdd',
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/extend-scopes-if.js
+2
-2
@@ -15,6 +15,6 @@ function foo(a, b, c) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: foo,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fast-refresh-dont-refresh-const-changes-prod.expect.md
+3
-3
@@ -3,8 +3,8 @@
3
4
```javascript
5
// @compilationMode(infer)
6
-import { useEffect, useMemo, useState } from "react";
7
-import { ValidateMemoization } from "shared-runtime";
6
+import {useEffect, useMemo, useState} from 'react';
7
+import {ValidateMemoization} from 'shared-runtime';
8
9
let pretendConst = 0;
10
@@ -27,7 +27,7 @@ function Component() {
27
28
// In production mode (no @enableResetCacheOnSourceFileChanges) memo caches are not
29
// reset unless the deps change
30
- const value = useMemo(() => [{ pretendConst }], []);
30
+ const value = useMemo(() => [{pretendConst}], []);
31
32
return <ValidateMemoization inputs={[]} output={value} />;
33
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fast-refresh-dont-refresh-const-changes-prod.js
+3
-3
@@ -1,6 +1,6 @@
1
// @compilationMode(infer)
2
-import { useEffect, useMemo, useState } from "react";
3
-import { ValidateMemoization } from "shared-runtime";
2
+import {useEffect, useMemo, useState} from 'react';
3
+import {ValidateMemoization} from 'shared-runtime';
4
5
let pretendConst = 0;
6
@@ -23,7 +23,7 @@ function Component() {
23
24
// In production mode (no @enableResetCacheOnSourceFileChanges) memo caches are not
25
// reset unless the deps change
26
- const value = useMemo(() => [{ pretendConst }], []);
26
+ const value = useMemo(() => [{pretendConst}], []);
27
28
return <ValidateMemoization inputs={[]} output={value} />;
29
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fast-refresh-refresh-on-const-changes-dev.expect.md
+5
-5
@@ -3,8 +3,8 @@
3
4
```javascript
5
// @compilationMode(infer) @enableResetCacheOnSourceFileChanges
6
-import { useEffect, useMemo, useState } from "react";
7
-import { ValidateMemoization } from "shared-runtime";
6
+import {useEffect, useMemo, useState} from 'react';
7
+import {ValidateMemoization} from 'shared-runtime';
8
9
let pretendConst = 0;
10
@@ -30,7 +30,7 @@ function Component() {
30
// as if value was reactive. However, we don't want to actually treat globals as
31
// reactive (though that would be trivial) since it could change compilation too much
32
// btw dev and prod. Instead, we should reset the cache via a secondary mechanism.
33
- const value = useMemo(() => [{ pretendConst }], [pretendConst]);
33
+ const value = useMemo(() => [{pretendConst}], [pretendConst]);
34
35
return <ValidateMemoization inputs={[pretendConst]} output={value} />;
36
}
@@ -63,12 +63,12 @@ function unsafeUpdateConst() {
63
function Component() {
64
const $ = _c(3);
65
if (
66
- $[0] !== "4bf230b116dd95f382060ad17350e116395e41ed757e51fd074ea0b4ed281272"
66
+ $[0] !== "8d7015668f857996c3d895a7a90e3e16b8a791d5b9cd13f2c76e1c254aeedebb"
67
) {
68
for (let $i = 0; $i < 3; $i += 1) {
69
$[$i] = Symbol.for("react.memo_cache_sentinel");
70
}
71
- $[0] = "4bf230b116dd95f382060ad17350e116395e41ed757e51fd074ea0b4ed281272";
71
+ $[0] = "8d7015668f857996c3d895a7a90e3e16b8a791d5b9cd13f2c76e1c254aeedebb";
72
}
73
useState(_temp);
74
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fast-refresh-refresh-on-const-changes-dev.js
+3
-3
@@ -1,6 +1,6 @@
1
// @compilationMode(infer) @enableResetCacheOnSourceFileChanges
2
-import { useEffect, useMemo, useState } from "react";
3
-import { ValidateMemoization } from "shared-runtime";
2
+import {useEffect, useMemo, useState} from 'react';
3
+import {ValidateMemoization} from 'shared-runtime';
4
5
let pretendConst = 0;
6
@@ -26,7 +26,7 @@ function Component() {
26
// as if value was reactive. However, we don't want to actually treat globals as
27
// reactive (though that would be trivial) since it could change compilation too much
28
// btw dev and prod. Instead, we should reset the cache via a secondary mechanism.
29
- const value = useMemo(() => [{ pretendConst }], [pretendConst]);
29
+ const value = useMemo(() => [{pretendConst}], [pretendConst]);
30
31
return <ValidateMemoization inputs={[pretendConst]} output={value} />;
32
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fast-refresh-reloading.expect.md
+4
-4
@@ -3,8 +3,8 @@
3
4
```javascript
5
// @enableResetCacheOnSourceFileChanges
6
-import { useMemo, useState } from "react";
7
-import { ValidateMemoization } from "shared-runtime";
6
+import {useMemo, useState} from 'react';
7
+import {ValidateMemoization} from 'shared-runtime';
8
9
function Component(props) {
10
const [state, setState] = useState(0);
@@ -30,12 +30,12 @@ import { ValidateMemoization } from "shared-runtime";
30
function Component(props) {
31
const $ = _c(8);
32
if (
33
- $[0] !== "bb6936608c0afe8e313aa547ca09fbc8451f24664284368812127c7e9bc2bca9"
33
+ $[0] !== "20945b0193e529df490847c66111b38d7b02485d5b53d0829ff3b23af87b105c"
34
) {
35
for (let $i = 0; $i < 8; $i += 1) {
36
$[$i] = Symbol.for("react.memo_cache_sentinel");
37
}
38
- $[0] = "bb6936608c0afe8e313aa547ca09fbc8451f24664284368812127c7e9bc2bca9";
38
+ $[0] = "20945b0193e529df490847c66111b38d7b02485d5b53d0829ff3b23af87b105c";
39
}
40
const [state] = useState(0);
41
let t0;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fast-refresh-reloading.js
+2
-2
@@ -1,6 +1,6 @@
1
// @enableResetCacheOnSourceFileChanges
2
-import { useMemo, useState } from "react";
3
-import { ValidateMemoization } from "shared-runtime";
2
+import {useMemo, useState} from 'react';
3
+import {ValidateMemoization} from 'shared-runtime';
4
5
function Component(props) {
6
const [state, setState] = useState(0);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/error.todo-fbt-unknown-enum-value.expect.md
+6
-6
@@ -2,13 +2,13 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
-function Component({ a, b }) {
7
+function Component({a, b}) {
8
return (
9
<fbt desc="Description">
10
- <fbt:enum enum-range={["avalue1", "avalue1"]} value={a} />{" "}
11
- <fbt:enum enum-range={["bvalue1", "bvalue2"]} value={b} />
10
+ <fbt:enum enum-range={['avalue1', 'avalue1']} value={a} />{' '}
11
+ <fbt:enum enum-range={['bvalue1', 'bvalue2']} value={b} />
12
</fbt>
13
);
14
}
@@ -20,8 +20,8 @@ function Component({ a, b }) {
20
21
```
22
5 | <fbt desc="Description">
23
- 6 | <fbt:enum enum-range={["avalue1", "avalue1"]} value={a} />{" "}
24
-> 7 | <fbt:enum enum-range={["bvalue1", "bvalue2"]} value={b} />
23
+ 6 | <fbt:enum enum-range={['avalue1', 'avalue1']} value={a} />{' '}
24
+> 7 | <fbt:enum enum-range={['bvalue1', 'bvalue2']} value={b} />
25
| ^^^^^^^^ Todo: Support <fbt> tags with multiple <fbt:enum> values (7:7)
26
8 | </fbt>
27
9 | );
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/error.todo-fbt-unknown-enum-value.js
+4
-4
@@ -1,10 +1,10 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
-function Component({ a, b }) {
3
+function Component({a, b}) {
4
return (
5
<fbt desc="Description">
6
- <fbt:enum enum-range={["avalue1", "avalue1"]} value={a} />{" "}
7
- <fbt:enum enum-range={["bvalue1", "bvalue2"]} value={b} />
6
+ <fbt:enum enum-range={['avalue1', 'avalue1']} value={a} />{' '}
7
+ <fbt:enum enum-range={['bvalue1', 'bvalue2']} value={b} />
8
</fbt>
9
);
10
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/error.todo-locally-require-fbt.expect.md
+4
-4
@@ -3,9 +3,9 @@
3
4
```javascript
5
function Component(props) {
6
- const fbt = require("fbt");
6
+ const fbt = require('fbt');
7
8
- return <fbt desc="Description">{"Text"}</fbt>;
8
+ return <fbt desc="Description">{'Text'}</fbt>;
9
}
10
11
```
@@ -14,9 +14,9 @@ function Component(props) {
14
## Error
15
16
```
17
- 2 | const fbt = require("fbt");
17
+ 2 | const fbt = require('fbt');
18
3 |
19
-> 4 | return <fbt desc="Description">{"Text"}</fbt>;
19
+> 4 | return <fbt desc="Description">{'Text'}</fbt>;
20
| ^^^ Todo: Support <fbt> tags where 'fbt' is a local variable instead of a global (4:4)
21
5 | }
22
6 |
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/error.todo-locally-require-fbt.js
+2
-2
@@ -1,5 +1,5 @@
1
function Component(props) {
2
- const fbt = require("fbt");
2
+ const fbt = require('fbt');
3
4
- return <fbt desc="Description">{"Text"}</fbt>;
4
+ return <fbt desc="Description">{'Text'}</fbt>;
5
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbs-params.expect.md
+4
-5
@@ -2,17 +2,16 @@
2
## Input
3
4
```javascript
5
-import { fbs } from "fbt";
5
+import {fbs} from 'fbt';
6
7
function Component(props) {
8
return (
9
<div
10
title={
11
- <fbs desc={"Dialog to show to user"}>
11
+ <fbs desc={'Dialog to show to user'}>
12
Hello <fbs:param name="user name">{props.name}</fbs:param>
13
</fbs>
14
- }
15
- >
14
+ }>
15
Hover me
16
</div>
17
);
@@ -20,7 +19,7 @@ function Component(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
23
- params: [{ name: "Sathya" }],
22
+ params: [{name: 'Sathya'}],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbs-params.js
+4
-5
@@ -1,14 +1,13 @@
1
-import { fbs } from "fbt";
1
+import {fbs} from 'fbt';
2
3
function Component(props) {
4
return (
5
<div
6
title={
7
- <fbs desc={"Dialog to show to user"}>
7
+ <fbs desc={'Dialog to show to user'}>
8
Hello <fbs:param name="user name">{props.name}</fbs:param>
9
</fbs>
10
- }
11
- >
10
+ }>
11
Hover me
12
</div>
13
);
@@ -16,5 +15,5 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
19
- params: [{ name: "Sathya" }],
18
+ params: [{name: 'Sathya'}],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-call-complex-param-value.expect.md
+5
-5
@@ -2,20 +2,20 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
6
-import { identity } from "shared-runtime";
5
+import fbt from 'fbt';
6
+import {identity} from 'shared-runtime';
7
8
function Component(props) {
9
const text = fbt(
10
- `Hello, ${fbt.param("(key) name", identity(props.name))}!`,
11
- "(description) Greeting"
10
+ `Hello, ${fbt.param('(key) name', identity(props.name))}!`,
11
+ '(description) Greeting'
12
);
13
return <div>{text}</div>;
14
}
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ name: "Sathya" }],
18
+ params: [{name: 'Sathya'}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-call-complex-param-value.js
+5
-5
@@ -1,15 +1,15 @@
1
-import fbt from "fbt";
2
-import { identity } from "shared-runtime";
1
+import fbt from 'fbt';
2
+import {identity} from 'shared-runtime';
3
4
function Component(props) {
5
const text = fbt(
6
- `Hello, ${fbt.param("(key) name", identity(props.name))}!`,
7
- "(description) Greeting"
6
+ `Hello, ${fbt.param('(key) name', identity(props.name))}!`,
7
+ '(description) Greeting'
8
);
9
return <div>{text}</div>;
10
}
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ name: "Sathya" }],
14
+ params: [{name: 'Sathya'}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-call.expect.md
+4
-4
@@ -2,19 +2,19 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
function Component(props) {
8
const text = fbt(
9
- `${fbt.param("(key) count", props.count)} items`,
10
- "(description) Number of items"
9
+ `${fbt.param('(key) count', props.count)} items`,
10
+ '(description) Number of items'
11
);
12
return <div>{text}</div>;
13
}
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ count: 2 }],
17
+ params: [{count: 2}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-call.js
+4
-4
@@ -1,14 +1,14 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
function Component(props) {
4
const text = fbt(
5
- `${fbt.param("(key) count", props.count)} items`,
6
- "(description) Number of items"
5
+ `${fbt.param('(key) count', props.count)} items`,
6
+ '(description) Number of items'
7
);
8
return <div>{text}</div>;
9
}
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ count: 2 }],
13
+ params: [{count: 2}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-no-whitespace-btw-text-and-param.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
const _ = fbt;
8
-function Component({ value }: { value: string }) {
8
+function Component({value}: {value: string}) {
9
return (
10
<fbt desc="descdesc">
11
Before text<fbt:param name="paramName">{value}</fbt:param>After text
@@ -15,7 +15,7 @@ function Component({ value }: { value: string }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ value: "hello world" }],
18
+ params: [{value: 'hello world'}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-no-whitespace-btw-text-and-param.tsx
+3
-3
@@ -1,7 +1,7 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
const _ = fbt;
4
-function Component({ value }: { value: string }) {
4
+function Component({value}: {value: string}) {
5
return (
6
<fbt desc="descdesc">
7
Before text<fbt:param name="paramName">{value}</fbt:param>After text
@@ -11,5 +11,5 @@ function Component({ value }: { value: string }) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ value: "hello world" }],
14
+ params: [{value: 'hello world'}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-param-with-leading-whitespace.expect.md
+12
-12
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
6
-import { identity } from "shared-runtime";
5
+import fbt from 'fbt';
6
+import {identity} from 'shared-runtime';
7
8
function Component(props) {
9
return (
@@ -11,7 +11,7 @@ function Component(props) {
11
<fbt desc="Title">
12
<fbt:plural count={identity(props.count)} name="count" showCount="yes">
13
vote
14
- </fbt:plural>{" "}
14
+ </fbt:plural>{' '}
15
for <fbt:param name="option"> {props.option}</fbt:param>
16
</fbt>
17
!
@@ -21,16 +21,16 @@ function Component(props) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
- params: [{ count: 42, option: "thing" }],
24
+ params: [{count: 42, option: 'thing'}],
25
sequentialRenders: [
26
- { count: 42, option: "thing" },
27
- { count: 42, option: "thing" },
28
- { count: 1, option: "other" },
29
- { count: 1, option: "other" },
30
- { count: 42, option: "thing" },
31
- { count: 1, option: "other" },
32
- { count: 42, option: "thing" },
33
- { count: 1, option: "other" },
26
+ {count: 42, option: 'thing'},
27
+ {count: 42, option: 'thing'},
28
+ {count: 1, option: 'other'},
29
+ {count: 1, option: 'other'},
30
+ {count: 42, option: 'thing'},
31
+ {count: 1, option: 'other'},
32
+ {count: 42, option: 'thing'},
33
+ {count: 1, option: 'other'},
34
],
35
};
36
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-param-with-leading-whitespace.js
+12
-12
@@ -1,5 +1,5 @@
1
-import fbt from "fbt";
2
-import { identity } from "shared-runtime";
1
+import fbt from 'fbt';
2
+import {identity} from 'shared-runtime';
3
4
function Component(props) {
5
return (
@@ -7,7 +7,7 @@ function Component(props) {
7
<fbt desc="Title">
8
<fbt:plural count={identity(props.count)} name="count" showCount="yes">
9
vote
10
- </fbt:plural>{" "}
10
+ </fbt:plural>{' '}
11
for <fbt:param name="option"> {props.option}</fbt:param>
12
</fbt>
13
!
@@ -17,15 +17,15 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ count: 42, option: "thing" }],
20
+ params: [{count: 42, option: 'thing'}],
21
sequentialRenders: [
22
- { count: 42, option: "thing" },
23
- { count: 42, option: "thing" },
24
- { count: 1, option: "other" },
25
- { count: 1, option: "other" },
26
- { count: 42, option: "thing" },
27
- { count: 1, option: "other" },
28
- { count: 42, option: "thing" },
29
- { count: 1, option: "other" },
22
+ {count: 42, option: 'thing'},
23
+ {count: 42, option: 'thing'},
24
+ {count: 1, option: 'other'},
25
+ {count: 1, option: 'other'},
26
+ {count: 42, option: 'thing'},
27
+ {count: 1, option: 'other'},
28
+ {count: 42, option: 'thing'},
29
+ {count: 1, option: 'other'},
30
],
31
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-param-with-newline.expect.md
+5
-6
@@ -2,16 +2,15 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
function Component(props) {
8
const element = (
9
- <fbt desc={"Dialog to show to user"}>
10
- Hello{" "}
9
+ <fbt desc={'Dialog to show to user'}>
10
+ Hello{' '}
11
<fbt:param
12
name="a really long description
13
- that got split into multiple lines"
14
- >
13
+ that got split into multiple lines">
14
{props.name}
15
</fbt:param>
16
</fbt>
@@ -21,7 +20,7 @@ function Component(props) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
24
- params: [{ name: "Jason" }],
23
+ params: [{name: 'Jason'}],
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-param-with-newline.js
+5
-6
@@ -1,13 +1,12 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
function Component(props) {
4
const element = (
5
- <fbt desc={"Dialog to show to user"}>
6
- Hello{" "}
5
+ <fbt desc={'Dialog to show to user'}>
6
+ Hello{' '}
7
<fbt:param
8
name="a really long description
9
- that got split into multiple lines"
10
- >
9
+ that got split into multiple lines">
10
{props.name}
11
</fbt:param>
12
</fbt>
@@ -17,5 +16,5 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
20
- params: [{ name: "Jason" }],
19
+ params: [{name: 'Jason'}],
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-param-with-quotes.expect.md
+3
-3
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
function Component(props) {
8
const element = (
9
- <fbt desc={"Dialog to show to user"}>
9
+ <fbt desc={'Dialog to show to user'}>
10
Hello <fbt:param name='"user" name'>{props.name}</fbt:param>
11
</fbt>
12
);
@@ -15,7 +15,7 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ name: "Jason" }],
18
+ params: [{name: 'Jason'}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-param-with-quotes.js
+3
-3
@@ -1,8 +1,8 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
function Component(props) {
4
const element = (
5
- <fbt desc={"Dialog to show to user"}>
5
+ <fbt desc={'Dialog to show to user'}>
6
Hello <fbt:param name='"user" name'>{props.name}</fbt:param>
7
</fbt>
8
);
@@ -11,5 +11,5 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ name: "Jason" }],
14
+ params: [{name: 'Jason'}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-param-with-trailing-whitespace.expect.md
+12
-12
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
6
-import { identity } from "shared-runtime";
5
+import fbt from 'fbt';
6
+import {identity} from 'shared-runtime';
7
8
function Component(props) {
9
return (
@@ -11,7 +11,7 @@ function Component(props) {
11
<fbt desc="Title">
12
<fbt:plural count={identity(props.count)} name="count" showCount="yes">
13
vote
14
- </fbt:plural>{" "}
14
+ </fbt:plural>{' '}
15
for <fbt:param name="option">{props.option} </fbt:param>
16
</fbt>
17
!
@@ -21,16 +21,16 @@ function Component(props) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
- params: [{ count: 42, option: "thing" }],
24
+ params: [{count: 42, option: 'thing'}],
25
sequentialRenders: [
26
- { count: 42, option: "thing" },
27
- { count: 42, option: "thing" },
28
- { count: 1, option: "other" },
29
- { count: 1, option: "other" },
30
- { count: 42, option: "thing" },
31
- { count: 1, option: "other" },
32
- { count: 42, option: "thing" },
33
- { count: 1, option: "other" },
26
+ {count: 42, option: 'thing'},
27
+ {count: 42, option: 'thing'},
28
+ {count: 1, option: 'other'},
29
+ {count: 1, option: 'other'},
30
+ {count: 42, option: 'thing'},
31
+ {count: 1, option: 'other'},
32
+ {count: 42, option: 'thing'},
33
+ {count: 1, option: 'other'},
34
],
35
};
36
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-param-with-trailing-whitespace.js
+12
-12
@@ -1,5 +1,5 @@
1
-import fbt from "fbt";
2
-import { identity } from "shared-runtime";
1
+import fbt from 'fbt';
2
+import {identity} from 'shared-runtime';
3
4
function Component(props) {
5
return (
@@ -7,7 +7,7 @@ function Component(props) {
7
<fbt desc="Title">
8
<fbt:plural count={identity(props.count)} name="count" showCount="yes">
9
vote
10
- </fbt:plural>{" "}
10
+ </fbt:plural>{' '}
11
for <fbt:param name="option">{props.option} </fbt:param>
12
</fbt>
13
!
@@ -17,15 +17,15 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ count: 42, option: "thing" }],
20
+ params: [{count: 42, option: 'thing'}],
21
sequentialRenders: [
22
- { count: 42, option: "thing" },
23
- { count: 42, option: "thing" },
24
- { count: 1, option: "other" },
25
- { count: 1, option: "other" },
26
- { count: 42, option: "thing" },
27
- { count: 1, option: "other" },
28
- { count: 42, option: "thing" },
29
- { count: 1, option: "other" },
22
+ {count: 42, option: 'thing'},
23
+ {count: 42, option: 'thing'},
24
+ {count: 1, option: 'other'},
25
+ {count: 1, option: 'other'},
26
+ {count: 42, option: 'thing'},
27
+ {count: 1, option: 'other'},
28
+ {count: 42, option: 'thing'},
29
+ {count: 1, option: 'other'},
30
],
31
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-param-with-unicode.expect.md
+3
-3
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
function Component(props) {
8
const element = (
9
- <fbt desc={"Dialog to show to user"}>
9
+ <fbt desc={'Dialog to show to user'}>
10
Hello <fbt:param name="user name ☺">{props.name}</fbt:param>
11
</fbt>
12
);
@@ -15,7 +15,7 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ name: "Jason" }],
18
+ params: [{name: 'Jason'}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-param-with-unicode.js
+3
-3
@@ -1,8 +1,8 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
function Component(props) {
4
const element = (
5
- <fbt desc={"Dialog to show to user"}>
5
+ <fbt desc={'Dialog to show to user'}>
6
Hello <fbt:param name="user name ☺">{props.name}</fbt:param>
7
</fbt>
8
);
@@ -11,5 +11,5 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ name: "Jason" }],
14
+ params: [{name: 'Jason'}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-params-complex-param-value.expect.md
+2
-2
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
function Component(props) {
8
return (
9
- <fbt desc={"Dialog to show to user"}>
9
+ <fbt desc={'Dialog to show to user'}>
10
Hello <fbt:param name="user name">{capitalize(props.name)}</fbt:param>
11
</fbt>
12
);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-params-complex-param-value.js
+2
-2
@@ -1,8 +1,8 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
function Component(props) {
4
return (
5
- <fbt desc={"Dialog to show to user"}>
5
+ <fbt desc={'Dialog to show to user'}>
6
Hello <fbt:param name="user name">{capitalize(props.name)}</fbt:param>
7
</fbt>
8
);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-params.expect.md
+5
-5
@@ -2,15 +2,15 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
function Component(props) {
8
return (
9
<div>
10
- <fbt desc={"Dialog to show to user"}>
10
+ <fbt desc={'Dialog to show to user'}>
11
Hello <fbt:param name="user name">{props.name}</fbt:param>
12
</fbt>
13
- <fbt desc={"Available actions|response"}>
13
+ <fbt desc={'Available actions|response'}>
14
<fbt:param name="actions|response">{props.actions}</fbt:param>
15
</fbt>
16
</div>
@@ -19,8 +19,8 @@ function Component(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: ["TodoAdd"],
23
- isComponent: "TodoAdd",
22
+ params: ['TodoAdd'],
23
+ isComponent: 'TodoAdd',
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-params.js
+5
-5
@@ -1,12 +1,12 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
function Component(props) {
4
return (
5
<div>
6
- <fbt desc={"Dialog to show to user"}>
6
+ <fbt desc={'Dialog to show to user'}>
7
Hello <fbt:param name="user name">{props.name}</fbt:param>
8
</fbt>
9
- <fbt desc={"Available actions|response"}>
9
+ <fbt desc={'Available actions|response'}>
10
<fbt:param name="actions|response">{props.actions}</fbt:param>
11
</fbt>
12
</div>
@@ -15,6 +15,6 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-preserve-jsxtext.expect.md
+5
-5
@@ -2,17 +2,17 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
function Foo(props) {
8
return (
9
<fbt desc="Some text to be translated">
10
<fbt:enum
11
- enum-range={{ "0": "hello", "1": "goodbye" }}
12
- value={props.value ? "0" : "1"}
13
- />{" "}
11
+ enum-range={{'0': 'hello', '1': 'goodbye'}}
12
+ value={props.value ? '0' : '1'}
13
+ />{' '}
14
<fbt:param name="value">{props.value}</fbt:param>
15
- {", "}
15
+ {', '}
16
</fbt>
17
);
18
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-preserve-jsxtext.js
+5
-5
@@ -1,14 +1,14 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
function Foo(props) {
4
return (
5
<fbt desc="Some text to be translated">
6
<fbt:enum
7
- enum-range={{ "0": "hello", "1": "goodbye" }}
8
- value={props.value ? "0" : "1"}
9
- />{" "}
7
+ enum-range={{'0': 'hello', '1': 'goodbye'}}
8
+ value={props.value ? '0' : '1'}
9
+ />{' '}
10
<fbt:param name="value">{props.value}</fbt:param>
11
- {", "}
11
+ {', '}
12
</fbt>
13
);
14
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-preserve-whitespace.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
const _ = fbt;
8
-function Component({ value }: { value: string }) {
8
+function Component({value}: {value: string}) {
9
return (
10
<fbt desc="descdesc">
11
Before text
@@ -16,7 +16,7 @@ function Component({ value }: { value: string }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ value: "hello world" }],
19
+ params: [{value: 'hello world'}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-preserve-whitespace.tsx
+3
-3
@@ -1,7 +1,7 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
const _ = fbt;
4
-function Component({ value }: { value: string }) {
4
+function Component({value}: {value: string}) {
5
return (
6
<fbt desc="descdesc">
7
Before text
@@ -12,5 +12,5 @@ function Component({ value }: { value: string }) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ value: "hello world" }],
15
+ params: [{value: 'hello world'}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-single-space-btw-param-and-text.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
const _ = fbt;
8
-function Component({ value }: { value: string }) {
8
+function Component({value}: {value: string}) {
9
return (
10
<fbt desc="descdesc">
11
Before text <fbt:param name="paramName">{value}</fbt:param> after text
@@ -15,7 +15,7 @@ function Component({ value }: { value: string }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ value: "hello world" }],
18
+ params: [{value: 'hello world'}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-single-space-btw-param-and-text.tsx
+3
-3
@@ -1,7 +1,7 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
const _ = fbt;
4
-function Component({ value }: { value: string }) {
4
+function Component({value}: {value: string}) {
5
return (
6
<fbt desc="descdesc">
7
Before text <fbt:param name="paramName">{value}</fbt:param> after text
@@ -11,5 +11,5 @@ function Component({ value }: { value: string }) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ value: "hello world" }],
14
+ params: [{value: 'hello world'}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-template-string-same-scope.expect.md
+5
-5
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
6
-import { Stringify } from "shared-runtime";
5
+import fbt from 'fbt';
6
+import {Stringify} from 'shared-runtime';
7
8
export function Component(props) {
9
let count = 0;
@@ -13,9 +13,9 @@ export function Component(props) {
13
return (
14
<Stringify>
15
{fbt(
16
- `for ${fbt.param("count", count)} experiences`,
16
+ `for ${fbt.param('count', count)} experiences`,
17
`Label for the number of items`,
18
- { project: "public" }
18
+ {project: 'public'}
19
)}
20
</Stringify>
21
);
@@ -23,7 +23,7 @@ export function Component(props) {
23
24
export const FIXTURE_ENTRYPOINT = {
25
fn: Component,
26
- params: [{ items: [1, 2, 3] }],
26
+ params: [{items: [1, 2, 3]}],
27
};
28
29
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-template-string-same-scope.js
+5
-5
@@ -1,5 +1,5 @@
1
-import fbt from "fbt";
2
-import { Stringify } from "shared-runtime";
1
+import fbt from 'fbt';
2
+import {Stringify} from 'shared-runtime';
3
4
export function Component(props) {
5
let count = 0;
@@ -9,9 +9,9 @@ export function Component(props) {
9
return (
10
<Stringify>
11
{fbt(
12
- `for ${fbt.param("count", count)} experiences`,
12
+ `for ${fbt.param('count', count)} experiences`,
13
`Label for the number of items`,
14
- { project: "public" }
14
+ {project: 'public'}
15
)}
16
</Stringify>
17
);
@@ -19,5 +19,5 @@ export function Component(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: [{ items: [1, 2, 3] }],
22
+ params: [{items: [1, 2, 3]}],
23
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-to-string.expect.md
+3
-3
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
function Component(props) {
8
const element = (
9
- <fbt desc={"Dialog to show to user"}>
9
+ <fbt desc={'Dialog to show to user'}>
10
Hello <fbt:param name="user name">{props.name}</fbt:param>
11
</fbt>
12
);
@@ -15,7 +15,7 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ name: "Jason" }],
18
+ params: [{name: 'Jason'}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-to-string.js
+3
-3
@@ -1,8 +1,8 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
function Component(props) {
4
const element = (
5
- <fbt desc={"Dialog to show to user"}>
5
+ <fbt desc={'Dialog to show to user'}>
6
Hello <fbt:param name="user name">{props.name}</fbt:param>
7
</fbt>
8
);
@@ -11,5 +11,5 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ name: "Jason" }],
14
+ params: [{name: 'Jason'}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-whitespace-around-param-value.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
const _ = fbt;
8
-function Component({ value }: { value: string }) {
8
+function Component({value}: {value: string}) {
9
return (
10
<fbt desc="descdesc">
11
Before text <fbt:param name="paramName"> {value} </fbt:param> after text
@@ -15,7 +15,7 @@ function Component({ value }: { value: string }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ value: "hello world" }],
18
+ params: [{value: 'hello world'}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-whitespace-around-param-value.tsx
+3
-3
@@ -1,7 +1,7 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
const _ = fbt;
4
-function Component({ value }: { value: string }) {
4
+function Component({value}: {value: string}) {
5
return (
6
<fbt desc="descdesc">
7
Before text <fbt:param name="paramName"> {value} </fbt:param> after text
@@ -11,5 +11,5 @@ function Component({ value }: { value: string }) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ value: "hello world" }],
14
+ params: [{value: 'hello world'}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-whitespace-within-text.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
const _ = fbt;
8
-function Component({ value }: { value: string }) {
8
+function Component({value}: {value: string}) {
9
return (
10
<fbt desc="descdesc">
11
Before text <fbt:param name="paramName">{value}</fbt:param> after text
@@ -17,7 +17,7 @@ function Component({ value }: { value: string }) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ value: "hello world" }],
20
+ params: [{value: 'hello world'}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbt-whitespace-within-text.tsx
+3
-3
@@ -1,7 +1,7 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
const _ = fbt;
4
-function Component({ value }: { value: string }) {
4
+function Component({value}: {value: string}) {
5
return (
6
<fbt desc="descdesc">
7
Before text <fbt:param name="paramName">{value}</fbt:param> after text
@@ -13,5 +13,5 @@ function Component({ value }: { value: string }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ value: "hello world" }],
16
+ params: [{value: 'hello world'}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbtparam-text-must-use-expression-container.expect.md
+2
-2
@@ -2,14 +2,14 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
function Component(props) {
8
return (
9
<Foo
10
value={
11
<fbt desc="Description of the parameter">
12
- <fbt:param name="value">{"0"}</fbt:param>%
12
+ <fbt:param name="value">{'0'}</fbt:param>%
13
</fbt>
14
}
15
/>
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbtparam-text-must-use-expression-container.js
+2
-2
@@ -1,11 +1,11 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
function Component(props) {
4
return (
5
<Foo
6
value={
7
<fbt desc="Description of the parameter">
8
- <fbt:param name="value">{"0"}</fbt:param>%
8
+ <fbt:param name="value">{'0'}</fbt:param>%
9
</fbt>
10
}
11
/>
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbtparam-with-jsx-element-content.expect.md
+2
-2
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
5
+import fbt from 'fbt';
6
7
-function Component({ name, data, icon }) {
7
+function Component({name, data, icon}) {
8
return (
9
<Text type="body4">
10
<fbt desc="Lorem ipsum">
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbtparam-with-jsx-element-content.js
+2
-2
@@ -1,6 +1,6 @@
1
-import fbt from "fbt";
1
+import fbt from 'fbt';
2
3
-function Component({ name, data, icon }) {
3
+function Component({name, data, icon}) {
4
return (
5
<Text type="body4">
6
<fbt desc="Lorem ipsum">
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbtparam-with-jsx-fragment-value.expect.md
+2
-2
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
6
-import { identity } from "shared-runtime";
5
+import fbt from 'fbt';
6
+import {identity} from 'shared-runtime';
7
8
function Component(props) {
9
return (
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/fbtparam-with-jsx-fragment-value.js
+2
-2
@@ -1,5 +1,5 @@
1
-import fbt from "fbt";
2
-import { identity } from "shared-runtime";
1
+import fbt from 'fbt';
2
+import {identity} from 'shared-runtime';
3
4
function Component(props) {
5
return (
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/lambda-with-fbt.expect.md
+4
-4
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-import { fbt } from "fbt";
5
+import {fbt} from 'fbt';
6
7
function Component() {
8
const buttonLabel = () => {
9
if (!someCondition) {
10
- return <fbt desc="My label">{"Purchase as a gift"}</fbt>;
10
+ return <fbt desc="My label">{'Purchase as a gift'}</fbt>;
11
} else if (
12
!iconOnly &&
13
showPrice &&
@@ -15,14 +15,14 @@ function Component() {
15
) {
16
return (
17
<fbt desc="Gift button's label">
18
- {"Gift | "}
18
+ {'Gift | '}
19
<fbt:param name="price">
20
{item?.current_gift_offer?.price?.formatted}
21
</fbt:param>
22
</fbt>
23
);
24
} else if (!iconOnly && !showPrice) {
25
- return <fbt desc="Gift button's label">{"Gift"}</fbt>;
25
+ return <fbt desc="Gift button's label">{'Gift'}</fbt>;
26
}
27
};
28
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/fbt/lambda-with-fbt.js
+4
-4
@@ -1,9 +1,9 @@
1
-import { fbt } from "fbt";
1
+import {fbt} from 'fbt';
2
3
function Component() {
4
const buttonLabel = () => {
5
if (!someCondition) {
6
- return <fbt desc="My label">{"Purchase as a gift"}</fbt>;
6
+ return <fbt desc="My label">{'Purchase as a gift'}</fbt>;
7
} else if (
8
!iconOnly &&
9
showPrice &&
@@ -11,14 +11,14 @@ function Component() {
11
) {
12
return (
13
<fbt desc="Gift button's label">
14
- {"Gift | "}
14
+ {'Gift | '}
15
<fbt:param name="price">
16
{item?.current_gift_offer?.price?.formatted}
17
</fbt:param>
18
</fbt>
19
);
20
} else if (!iconOnly && !showPrice) {
21
- return <fbt desc="Gift button's label">{"Gift"}</fbt>;
21
+ return <fbt desc="Gift button's label">{'Gift'}</fbt>;
22
}
23
};
24
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/flag-enable-emit-hook-guards.expect.md
+5
-5
@@ -3,17 +3,17 @@
3
4
```javascript
5
// @enableEmitHookGuards
6
-import { createContext, useContext, useEffect, useState } from "react";
6
+import {createContext, useContext, useEffect, useState} from 'react';
7
import {
8
CONST_STRING0,
9
ObjectWithHooks,
10
getNumber,
11
identity,
12
print,
13
-} from "shared-runtime";
13
+} from 'shared-runtime';
14
15
-const MyContext = createContext("my context value");
16
-function Component({ value }) {
15
+const MyContext = createContext('my context value');
16
+function Component({value}) {
17
print(identity(CONST_STRING0));
18
const [state, setState] = useState(getNumber());
19
print(value, state);
@@ -28,7 +28,7 @@ function Component({ value }) {
28
29
export const FIXTURE_ENTRYPOINT = {
30
fn: Component,
31
- args: [{ value: 0 }],
31
+ args: [{value: 0}],
32
};
33
34
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/flag-enable-emit-hook-guards.ts
+5
-5
@@ -1,15 +1,15 @@
1
// @enableEmitHookGuards
2
-import { createContext, useContext, useEffect, useState } from "react";
2
+import {createContext, useContext, useEffect, useState} from 'react';
3
import {
4
CONST_STRING0,
5
ObjectWithHooks,
6
getNumber,
7
identity,
8
print,
9
-} from "shared-runtime";
9
+} from 'shared-runtime';
10
11
-const MyContext = createContext("my context value");
12
-function Component({ value }) {
11
+const MyContext = createContext('my context value');
12
+function Component({value}) {
13
print(identity(CONST_STRING0));
14
const [state, setState] = useState(getNumber());
15
print(value, state);
@@ -24,5 +24,5 @@ function Component({ value }) {
24
25
export const FIXTURE_ENTRYPOINT = {
26
fn: Component,
27
- args: [{ value: 0 }],
27
+ args: [{value: 0}],
28
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/flatten-scopes-with-methodcall-hook.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-const { ObjectWithHooks } = require("shared-runtime");
5
+const {ObjectWithHooks} = require('shared-runtime');
6
7
function Component(props) {
8
const x = [];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/flatten-scopes-with-methodcall-hook.js
+1
-1
@@ -1,4 +1,4 @@
1
-const { ObjectWithHooks } = require("shared-runtime");
1
+const {ObjectWithHooks} = require('shared-runtime');
2
3
function Component(props) {
4
const x = [];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-empty-update-with-continue.expect.md
+2
-2
@@ -14,8 +14,8 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: ["TodoAdd"],
18
- isComponent: "TodoAdd",
17
+ params: ['TodoAdd'],
18
+ isComponent: 'TodoAdd',
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-empty-update-with-continue.js
+2
-2
@@ -10,6 +10,6 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-empty-update.expect.md
+2
-2
@@ -15,8 +15,8 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-empty-update.js
+2
-2
@@ -11,6 +11,6 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-in-statement-body-always-returns.expect.md
+1
-1
@@ -11,7 +11,7 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ value: { a: "A!" } }],
14
+ params: [{value: {a: 'A!'}}],
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-in-statement-body-always-returns.js
+1
-1
@@ -7,5 +7,5 @@ function Component(props) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: [{ value: { a: "A!" } }],
10
+ params: [{value: {a: 'A!'}}],
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-in-statement-break.expect.md
+3
-3
@@ -4,9 +4,9 @@
4
```javascript
5
function Component(props) {
6
let x;
7
- const object = { ...props.value };
7
+ const object = {...props.value};
8
for (const y in object) {
9
- if (y === "break") {
9
+ if (y === 'break') {
10
break;
11
}
12
x = object[y];
@@ -17,7 +17,7 @@ function Component(props) {
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
// should return 'a'
20
- params: [{ a: "a", break: null, c: "C!" }],
20
+ params: [{a: 'a', break: null, c: 'C!'}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-in-statement-break.js
+3
-3
@@ -1,8 +1,8 @@
1
function Component(props) {
2
let x;
3
- const object = { ...props.value };
3
+ const object = {...props.value};
4
for (const y in object) {
5
- if (y === "break") {
5
+ if (y === 'break') {
6
break;
7
}
8
x = object[y];
@@ -13,5 +13,5 @@ function Component(props) {
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
// should return 'a'
16
- params: [{ a: "a", break: null, c: "C!" }],
16
+ params: [{a: 'a', break: null, c: 'C!'}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-in-statement-continue.expect.md
+11
-11
@@ -4,9 +4,9 @@
4
```javascript
5
function Component(props) {
6
let x;
7
- const object = { ...props.value };
7
+ const object = {...props.value};
8
for (const y in object) {
9
- if (y === "continue") {
9
+ if (y === 'continue') {
10
continue;
11
}
12
x = object[y];
@@ -16,16 +16,16 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ value: { a: "a", continue: "skip", b: "hello!" } }],
19
+ params: [{value: {a: 'a', continue: 'skip', b: 'hello!'}}],
20
sequentialRenders: [
21
- { value: { a: "a", continue: "skip", b: "hello!" } },
22
- { value: { a: "a", continue: "skip", b: "hello!" } },
23
- { value: { a: "skip!", continue: true } },
24
- { value: { a: "a", continue: "skip", b: "hello!" } },
25
- { value: { a: "skip!", continue: true } },
26
- { value: { a: "a", continue: "skip", b: "hello!" } },
27
- { value: { a: "skip!", continue: true } },
28
- { value: { a: "skip!", continue: true } },
21
+ {value: {a: 'a', continue: 'skip', b: 'hello!'}},
22
+ {value: {a: 'a', continue: 'skip', b: 'hello!'}},
23
+ {value: {a: 'skip!', continue: true}},
24
+ {value: {a: 'a', continue: 'skip', b: 'hello!'}},
25
+ {value: {a: 'skip!', continue: true}},
26
+ {value: {a: 'a', continue: 'skip', b: 'hello!'}},
27
+ {value: {a: 'skip!', continue: true}},
28
+ {value: {a: 'skip!', continue: true}},
29
],
30
};
31
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-in-statement-continue.js
+11
-11
@@ -1,8 +1,8 @@
1
function Component(props) {
2
let x;
3
- const object = { ...props.value };
3
+ const object = {...props.value};
4
for (const y in object) {
5
- if (y === "continue") {
5
+ if (y === 'continue') {
6
continue;
7
}
8
x = object[y];
@@ -12,15 +12,15 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ value: { a: "a", continue: "skip", b: "hello!" } }],
15
+ params: [{value: {a: 'a', continue: 'skip', b: 'hello!'}}],
16
sequentialRenders: [
17
- { value: { a: "a", continue: "skip", b: "hello!" } },
18
- { value: { a: "a", continue: "skip", b: "hello!" } },
19
- { value: { a: "skip!", continue: true } },
20
- { value: { a: "a", continue: "skip", b: "hello!" } },
21
- { value: { a: "skip!", continue: true } },
22
- { value: { a: "a", continue: "skip", b: "hello!" } },
23
- { value: { a: "skip!", continue: true } },
24
- { value: { a: "skip!", continue: true } },
17
+ {value: {a: 'a', continue: 'skip', b: 'hello!'}},
18
+ {value: {a: 'a', continue: 'skip', b: 'hello!'}},
19
+ {value: {a: 'skip!', continue: true}},
20
+ {value: {a: 'a', continue: 'skip', b: 'hello!'}},
21
+ {value: {a: 'skip!', continue: true}},
22
+ {value: {a: 'a', continue: 'skip', b: 'hello!'}},
23
+ {value: {a: 'skip!', continue: true}},
24
+ {value: {a: 'skip!', continue: true}},
25
],
26
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-in-statement-empty-body.expect.md
+1
-1
@@ -11,7 +11,7 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ value: { a: "a", b: "B", c: "C!" } }],
14
+ params: [{value: {a: 'a', b: 'B', c: 'C!'}}],
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-in-statement-empty-body.js
+1
-1
@@ -7,5 +7,5 @@ function Component(props) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: [{ value: { a: "a", b: "B", c: "C!" } }],
10
+ params: [{value: {a: 'a', b: 'B', c: 'C!'}}],
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-in-statement-type-inference.expect.md
+3
-3
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-const { identity, mutate } = require("shared-runtime");
5
+const {identity, mutate} = require('shared-runtime');
6
7
function Component(props) {
8
let x;
9
- const object = { ...props.value };
9
+ const object = {...props.value};
10
for (const y in object) {
11
x = y;
12
}
@@ -16,7 +16,7 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ value: { a: "a", b: "B", c: "C!" } }],
19
+ params: [{value: {a: 'a', b: 'B', c: 'C!'}}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-in-statement-type-inference.js
+3
-3
@@ -1,8 +1,8 @@
1
-const { identity, mutate } = require("shared-runtime");
1
+const {identity, mutate} = require('shared-runtime');
2
3
function Component(props) {
4
let x;
5
- const object = { ...props.value };
5
+ const object = {...props.value};
6
for (const y in object) {
7
x = y;
8
}
@@ -12,5 +12,5 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ value: { a: "a", b: "B", c: "C!" } }],
15
+ params: [{value: {a: 'a', b: 'B', c: 'C!'}}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-in-statement.expect.md
+3
-3
@@ -12,10 +12,10 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ hello: null, world: undefined, "!": true }],
15
+ params: [{hello: null, world: undefined, '!': true}],
16
sequentialRenders: [
17
- { a: null, b: null, c: null },
18
- { lauren: true, mofei: true, sathya: true, jason: true },
17
+ {a: null, b: null, c: null},
18
+ {lauren: true, mofei: true, sathya: true, jason: true},
19
],
20
};
21
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-in-statement.js
+3
-3
@@ -8,9 +8,9 @@ function Component(props) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: [{ hello: null, world: undefined, "!": true }],
11
+ params: [{hello: null, world: undefined, '!': true}],
12
sequentialRenders: [
13
- { a: null, b: null, c: null },
14
- { lauren: true, mofei: true, sathya: true, jason: true },
13
+ {a: null, b: null, c: null},
14
+ {lauren: true, mofei: true, sathya: true, jason: true},
15
],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-logical.expect.md
+2
-2
@@ -17,8 +17,8 @@ function foo(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: foo,
20
- params: ["TodoAdd"],
21
- isComponent: "TodoAdd",
20
+ params: ['TodoAdd'],
21
+ isComponent: 'TodoAdd',
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-logical.js
+2
-2
@@ -13,6 +13,6 @@ function foo(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: foo,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-loop-let-undefined-decl.expect.md
+2
-2
@@ -11,9 +11,9 @@ function useFoo() {
11
for (let i = 0; i <= 5; i++) {
12
let color;
13
if (isSelected) {
14
- color = isCurrent ? "#FFCC22" : "#FF5050";
14
+ color = isCurrent ? '#FFCC22' : '#FF5050';
15
} else {
16
- color = isCurrent ? "#CCFF03" : "#CCCCCC";
16
+ color = isCurrent ? '#CCFF03' : '#CCCCCC';
17
}
18
console.log(color);
19
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-loop-let-undefined-decl.js
+2
-2
@@ -7,9 +7,9 @@ function useFoo() {
7
for (let i = 0; i <= 5; i++) {
8
let color;
9
if (isSelected) {
10
- color = isCurrent ? "#FFCC22" : "#FF5050";
10
+ color = isCurrent ? '#FFCC22' : '#FF5050';
11
} else {
12
- color = isCurrent ? "#CCFF03" : "#CCCCCC";
12
+ color = isCurrent ? '#CCFF03' : '#CCCCCC';
13
}
14
console.log(color);
15
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-loop-with-value-block-initializer.expect.md
+12
-12
@@ -18,8 +18,8 @@ export const FIXTURE_ENTRYPOINT = {
18
{
19
start: null,
20
items: [
21
- { id: 0, value: "zero" },
22
- { id: 1, value: "one" },
21
+ {id: 0, value: 'zero'},
22
+ {id: 1, value: 'one'},
23
],
24
},
25
],
@@ -27,31 +27,31 @@ export const FIXTURE_ENTRYPOINT = {
27
{
28
start: 1,
29
items: [
30
- { id: 0, value: "zero" },
31
- { id: 1, value: "one" },
30
+ {id: 0, value: 'zero'},
31
+ {id: 1, value: 'one'},
32
],
33
},
34
{
35
start: 2,
36
items: [
37
- { id: 0, value: "zero" },
38
- { id: 1, value: "one" },
37
+ {id: 0, value: 'zero'},
38
+ {id: 1, value: 'one'},
39
],
40
},
41
{
42
start: 0,
43
items: [
44
- { id: 0, value: "zero" },
45
- { id: 1, value: "one" },
46
- { id: 2, value: "two" },
44
+ {id: 0, value: 'zero'},
45
+ {id: 1, value: 'one'},
46
+ {id: 2, value: 'two'},
47
],
48
},
49
{
50
start: 1,
51
items: [
52
- { id: 0, value: "zero" },
53
- { id: 1, value: "one" },
54
- { id: 2, value: "two" },
52
+ {id: 0, value: 'zero'},
53
+ {id: 1, value: 'one'},
54
+ {id: 2, value: 'two'},
55
],
56
},
57
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-loop-with-value-block-initializer.js
+12
-12
@@ -14,8 +14,8 @@ export const FIXTURE_ENTRYPOINT = {
14
{
15
start: null,
16
items: [
17
- { id: 0, value: "zero" },
18
- { id: 1, value: "one" },
17
+ {id: 0, value: 'zero'},
18
+ {id: 1, value: 'one'},
19
],
20
},
21
],
@@ -23,31 +23,31 @@ export const FIXTURE_ENTRYPOINT = {
23
{
24
start: 1,
25
items: [
26
- { id: 0, value: "zero" },
27
- { id: 1, value: "one" },
26
+ {id: 0, value: 'zero'},
27
+ {id: 1, value: 'one'},
28
],
29
},
30
{
31
start: 2,
32
items: [
33
- { id: 0, value: "zero" },
34
- { id: 1, value: "one" },
33
+ {id: 0, value: 'zero'},
34
+ {id: 1, value: 'one'},
35
],
36
},
37
{
38
start: 0,
39
items: [
40
- { id: 0, value: "zero" },
41
- { id: 1, value: "one" },
42
- { id: 2, value: "two" },
40
+ {id: 0, value: 'zero'},
41
+ {id: 1, value: 'one'},
42
+ {id: 2, value: 'two'},
43
],
44
},
45
{
46
start: 1,
47
items: [
48
- { id: 0, value: "zero" },
49
- { id: 1, value: "one" },
50
- { id: 2, value: "two" },
48
+ {id: 0, value: 'zero'},
49
+ {id: 1, value: 'one'},
50
+ {id: 2, value: 'two'},
51
],
52
},
53
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-multiple-variable-declarations-in-initializer.expect.md
+1
-1
@@ -14,7 +14,7 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ items: ["a", "b", 42] }],
17
+ params: [{items: ['a', 'b', 42]}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-multiple-variable-declarations-in-initializer.js
+1
-1
@@ -10,5 +10,5 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ items: ["a", "b", 42] }],
13
+ params: [{items: ['a', 'b', 42]}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-capture-item-of-local-collection-mutate-later-value-initially-null.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeObject_Primitives } from "shared-runtime";
5
+import {makeObject_Primitives} from 'shared-runtime';
6
7
function Component(props) {
8
let lastItem = null;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-capture-item-of-local-collection-mutate-later-value-initially-null.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { makeObject_Primitives } from "shared-runtime";
1
+import {makeObject_Primitives} from 'shared-runtime';
2
3
function Component(props) {
4
let lastItem = null;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-capture-item-of-local-collection-mutate-later.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeObject_Primitives } from "shared-runtime";
5
+import {makeObject_Primitives} from 'shared-runtime';
6
7
function Component(props) {
8
let lastItem = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-capture-item-of-local-collection-mutate-later.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { makeObject_Primitives } from "shared-runtime";
1
+import {makeObject_Primitives} from 'shared-runtime';
2
3
function Component(props) {
4
let lastItem = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-destructure.expect.md
+2
-2
@@ -4,8 +4,8 @@
4
```javascript
5
function Component() {
6
let x = [];
7
- let items = [{ v: 0 }, { v: 1 }, { v: 2 }];
8
- for (const { v } of items) {
7
+ let items = [{v: 0}, {v: 1}, {v: 2}];
8
+ for (const {v} of items) {
9
x.push(v * 2);
10
}
11
return x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-destructure.js
+2
-2
@@ -1,7 +1,7 @@
1
function Component() {
2
let x = [];
3
- let items = [{ v: 0 }, { v: 1 }, { v: 2 }];
4
- for (const { v } of items) {
3
+ let items = [{v: 0}, {v: 1}, {v: 2}];
4
+ for (const {v} of items) {
5
x.push(v * 2);
6
}
7
return x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-immutable-collection.expect.md
+5
-5
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function Router({ title, mapping }) {
5
+function Router({title, mapping}) {
6
const array = [];
7
for (let [, entry] of mapping) {
8
array.push([title, entry]);
@@ -11,8 +11,8 @@ function Router({ title, mapping }) {
11
}
12
13
const routes = new Map([
14
- ["about", "/about"],
15
- ["contact", "/contact"],
14
+ ['about', '/about'],
15
+ ['contact', '/contact'],
16
]);
17
18
export const FIXTURE_ENTRYPOINT = {
@@ -20,11 +20,11 @@ export const FIXTURE_ENTRYPOINT = {
20
params: [],
21
sequentialRenders: [
22
{
23
- title: "Foo",
23
+ title: 'Foo',
24
mapping: routes,
25
},
26
{
27
- title: "Bar",
27
+ title: 'Bar',
28
mapping: routes,
29
},
30
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-immutable-collection.js
+5
-5
@@ -1,4 +1,4 @@
1
-function Router({ title, mapping }) {
1
+function Router({title, mapping}) {
2
const array = [];
3
for (let [, entry] of mapping) {
4
array.push([title, entry]);
@@ -7,8 +7,8 @@ function Router({ title, mapping }) {
7
}
8
9
const routes = new Map([
10
- ["about", "/about"],
11
- ["contact", "/contact"],
10
+ ['about', '/about'],
11
+ ['contact', '/contact'],
12
]);
13
14
export const FIXTURE_ENTRYPOINT = {
@@ -16,11 +16,11 @@ export const FIXTURE_ENTRYPOINT = {
16
params: [],
17
sequentialRenders: [
18
{
19
- title: "Foo",
19
+ title: 'Foo',
20
mapping: routes,
21
},
22
{
23
- title: "Bar",
23
+ title: 'Bar',
24
mapping: routes,
25
},
26
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-iterator-of-immutable-collection.expect.md
+5
-5
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function Router({ title, mapping }) {
5
+function Router({title, mapping}) {
6
const array = [];
7
for (let entry of mapping.values()) {
8
array.push([title, entry]);
@@ -11,8 +11,8 @@ function Router({ title, mapping }) {
11
}
12
13
const routes = new Map([
14
- ["about", "/about"],
15
- ["contact", "/contact"],
14
+ ['about', '/about'],
15
+ ['contact', '/contact'],
16
]);
17
18
export const FIXTURE_ENTRYPOINT = {
@@ -20,11 +20,11 @@ export const FIXTURE_ENTRYPOINT = {
20
params: [],
21
sequentialRenders: [
22
{
23
- title: "Foo",
23
+ title: 'Foo',
24
mapping: routes,
25
},
26
{
27
- title: "Bar",
27
+ title: 'Bar',
28
mapping: routes,
29
},
30
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-iterator-of-immutable-collection.js
+5
-5
@@ -1,4 +1,4 @@
1
-function Router({ title, mapping }) {
1
+function Router({title, mapping}) {
2
const array = [];
3
for (let entry of mapping.values()) {
4
array.push([title, entry]);
@@ -7,8 +7,8 @@ function Router({ title, mapping }) {
7
}
8
9
const routes = new Map([
10
- ["about", "/about"],
11
- ["contact", "/contact"],
10
+ ['about', '/about'],
11
+ ['contact', '/contact'],
12
]);
13
14
export const FIXTURE_ENTRYPOINT = {
@@ -16,11 +16,11 @@ export const FIXTURE_ENTRYPOINT = {
16
params: [],
17
sequentialRenders: [
18
{
19
- title: "Foo",
19
+ title: 'Foo',
20
mapping: routes,
21
},
22
{
23
- title: "Bar",
23
+ title: 'Bar',
24
mapping: routes,
25
},
26
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-mutate-item-of-local-collection.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeObject_Primitives } from "shared-runtime";
5
+import {makeObject_Primitives} from 'shared-runtime';
6
7
function Component(props) {
8
const items = [makeObject_Primitives(), makeObject_Primitives()];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-mutate-item-of-local-collection.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { makeObject_Primitives } from "shared-runtime";
1
+import {makeObject_Primitives} from 'shared-runtime';
2
3
function Component(props) {
4
const items = [makeObject_Primitives(), makeObject_Primitives()];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-mutate.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeObject_Primitives, mutateAndReturn, toJSON } from "shared-runtime";
5
+import {makeObject_Primitives, mutateAndReturn, toJSON} from 'shared-runtime';
6
7
function Component(_props) {
8
const collection = [makeObject_Primitives()];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-mutate.tsx
+1
-1
@@ -1,4 +1,4 @@
1
-import { makeObject_Primitives, mutateAndReturn, toJSON } from "shared-runtime";
1
+import {makeObject_Primitives, mutateAndReturn, toJSON} from 'shared-runtime';
2
3
function Component(_props) {
4
const collection = [makeObject_Primitives()];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-nonmutating-loop-local-collection.expect.md
+7
-7
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { useMemo } from "react";
6
-import { ValidateMemoization } from "shared-runtime";
5
+import {useMemo} from 'react';
6
+import {ValidateMemoization} from 'shared-runtime';
7
8
-function Component({ a, b }) {
8
+function Component({a, b}) {
9
const x = useMemo(() => {
10
return [a];
11
}, [a]);
@@ -26,11 +26,11 @@ function Component({ a, b }) {
26
27
export const FIXTURE_ENTRYPOINT = {
28
fn: Component,
29
- params: [{ a: 0, b: 0 }],
29
+ params: [{a: 0, b: 0}],
30
sequentialRenders: [
31
- { a: 1, b: 0 },
32
- { a: 1, b: 1 },
33
- { a: 0, b: 1 },
31
+ {a: 1, b: 0},
32
+ {a: 1, b: 1},
33
+ {a: 0, b: 1},
34
],
35
};
36
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-of-nonmutating-loop-local-collection.js
+7
-7
@@ -1,7 +1,7 @@
1
-import { useMemo } from "react";
2
-import { ValidateMemoization } from "shared-runtime";
1
+import {useMemo} from 'react';
2
+import {ValidateMemoization} from 'shared-runtime';
3
4
-function Component({ a, b }) {
4
+function Component({a, b}) {
5
const x = useMemo(() => {
6
return [a];
7
}, [a]);
@@ -22,10 +22,10 @@ function Component({ a, b }) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
25
- params: [{ a: 0, b: 0 }],
25
+ params: [{a: 0, b: 0}],
26
sequentialRenders: [
27
- { a: 1, b: 0 },
28
- { a: 1, b: 1 },
29
- { a: 0, b: 1 },
27
+ {a: 1, b: 0},
28
+ {a: 1, b: 1},
29
+ {a: 0, b: 1},
30
],
31
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-return.expect.md
+2
-2
@@ -10,8 +10,8 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-return.js
+2
-2
@@ -6,6 +6,6 @@ function Component(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-with-assignment-as-update.expect.md
+1
-1
@@ -12,7 +12,7 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ init: 0 }],
15
+ params: [{init: 0}],
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/for-with-assignment-as-update.js
+1
-1
@@ -8,5 +8,5 @@ function Component(props) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: [{ init: 0 }],
11
+ params: [{init: 0}],
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-declaration-simple.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let t = { a };
6
+ let t = {a};
7
function x(p) {
8
p.foo();
9
}
@@ -13,8 +13,8 @@ function component(a) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: component,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-declaration-simple.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let t = { a };
2
+ let t = {a};
3
function x(p) {
4
p.foo();
5
}
@@ -9,6 +9,6 @@ function component(a) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: component,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-expr-directive.expect.md
+3
-3
@@ -3,11 +3,11 @@
3
4
```javascript
5
function Component() {
6
- "use strict";
6
+ 'use strict';
7
let [count, setCount] = React.useState(0);
8
function update() {
9
- "worklet";
10
- setCount((count) => count + 1);
9
+ 'worklet';
10
+ setCount(count => count + 1);
11
}
12
return <button onClick={update}>{count}</button>;
13
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-expr-directive.js
+3
-3
@@ -1,9 +1,9 @@
1
function Component() {
2
- "use strict";
2
+ 'use strict';
3
let [count, setCount] = React.useState(0);
4
function update() {
5
- "worklet";
6
- setCount((count) => count + 1);
5
+ 'worklet';
6
+ setCount(count => count + 1);
7
}
8
return <button onClick={update}>{count}</button>;
9
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-expression-captures-value-later-frozen-jsx.expect.md
+1
-1
@@ -6,7 +6,7 @@ function Component(props) {
6
let x = {};
7
// onChange should be inferred as immutable, because the value
8
// it captures (`x`) is frozen by the time the function is referenced
9
- const onChange = (e) => {
9
+ const onChange = e => {
10
maybeMutate(x, e.target.value);
11
};
12
if (props.cond) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-expression-captures-value-later-frozen-jsx.js
+1
-1
@@ -2,7 +2,7 @@ function Component(props) {
2
let x = {};
3
// onChange should be inferred as immutable, because the value
4
// it captures (`x`) is frozen by the time the function is referenced
5
- const onChange = (e) => {
5
+ const onChange = e => {
6
maybeMutate(x, e.target.value);
7
};
8
if (props.cond) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-expression-prototype-call-mutating.expect.md
+4
-8
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import { useMemo } from "react";
6
-import { ValidateMemoization } from "shared-runtime";
5
+import {useMemo} from 'react';
6
+import {ValidateMemoization} from 'shared-runtime';
7
8
function Component(props) {
9
const a = useMemo(() => {
@@ -19,12 +19,8 @@ function Component(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: [{ name: "Jason" }],
23
- sequentialRenders: [
24
- { name: "Lauren" },
25
- { name: "Lauren" },
26
- { name: "Jason" },
27
- ],
22
+ params: [{name: 'Jason'}],
23
+ sequentialRenders: [{name: 'Lauren'}, {name: 'Lauren'}, {name: 'Jason'}],
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-expression-prototype-call-mutating.js
+4
-8
@@ -1,5 +1,5 @@
1
-import { useMemo } from "react";
2
-import { ValidateMemoization } from "shared-runtime";
1
+import {useMemo} from 'react';
2
+import {ValidateMemoization} from 'shared-runtime';
3
4
function Component(props) {
5
const a = useMemo(() => {
@@ -15,10 +15,6 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ name: "Jason" }],
19
- sequentialRenders: [
20
- { name: "Lauren" },
21
- { name: "Lauren" },
22
- { name: "Jason" },
23
- ],
18
+ params: [{name: 'Jason'}],
19
+ sequentialRenders: [{name: 'Lauren'}, {name: 'Lauren'}, {name: 'Jason'}],
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-expression-prototype-call.expect.md
+1
-1
@@ -11,7 +11,7 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ name: "Jason" }],
14
+ params: [{name: 'Jason'}],
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-expression-prototype-call.js
+1
-1
@@ -7,5 +7,5 @@ function Component(props) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: [{ name: "Jason" }],
10
+ params: [{name: 'Jason'}],
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-param-assignment-pattern.expect.md
+3
-3
@@ -2,14 +2,14 @@
2
## Input
3
4
```javascript
5
-function Component(x = "default", y = [{}]) {
5
+function Component(x = 'default', y = [{}]) {
6
return [x, y];
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
14
15
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/function-param-assignment-pattern.js
+3
-3
@@ -1,9 +1,9 @@
1
-function Component(x = "default", y = [{}]) {
1
+function Component(x = 'default', y = [{}]) {
2
return [x, y];
3
}
4
5
export const FIXTURE_ENTRYPOINT = {
6
fn: Component,
7
- params: ["TodoAdd"],
8
- isComponent: "TodoAdd",
7
+ params: ['TodoAdd'],
8
+ isComponent: 'TodoAdd',
9
};
"b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/functionexpr\342\200\223conditional-access.expect.md"
renamed
+1
-1
@@ -13,7 +13,7 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ bar: null }],
16
+ params: [{bar: null}],
17
};
18
19
```
"b/compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/functionexpr\342\200\223conditional-access.js"
renamed
+1
-1
@@ -9,5 +9,5 @@ function Component(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: [{ bar: null }],
12
+ params: [{bar: null}],
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/gating-preserves-function-properties.expect.md
+2
-2
@@ -12,8 +12,8 @@ export function Component2() {
12
return <></>;
13
}
14
15
-Component.displayName = "Component ONE";
16
-Component2.displayName = "Component TWO";
15
+Component.displayName = 'Component ONE';
16
+Component2.displayName = 'Component TWO';
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/gating-preserves-function-properties.tsx
+2
-2
@@ -8,8 +8,8 @@ export function Component2() {
8
return <></>;
9
}
10
11
-Component.displayName = "Component ONE";
12
-Component2.displayName = "Component TWO";
11
+Component.displayName = 'Component ONE';
12
+Component2.displayName = 'Component TWO';
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/gating-test-export-default-function.expect.md
+2
-2
@@ -4,7 +4,7 @@
4
```javascript
5
// @gating @compilationMode(annotation)
6
export default function Bar(props) {
7
- "use forget";
7
+ 'use forget';
8
return <div>{props.bar}</div>;
9
}
10
@@ -13,7 +13,7 @@ function NoForget(props) {
13
}
14
15
function Foo(props) {
16
- "use forget";
16
+ 'use forget';
17
return <Foo>{props.bar}</Foo>;
18
}
19
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/gating-test-export-default-function.js
+2
-2
@@ -1,6 +1,6 @@
1
// @gating @compilationMode(annotation)
2
export default function Bar(props) {
3
- "use forget";
3
+ 'use forget';
4
return <div>{props.bar}</div>;
5
}
6
@@ -9,6 +9,6 @@ function NoForget(props) {
9
}
10
11
function Foo(props) {
12
- "use forget";
12
+ 'use forget';
13
return <Foo>{props.bar}</Foo>;
14
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/gating-test-export-function-and-default.expect.md
+2
-2
@@ -4,7 +4,7 @@
4
```javascript
5
// @gating @compilationMode(annotation)
6
export default function Bar(props) {
7
- "use forget";
7
+ 'use forget';
8
return <div>{props.bar}</div>;
9
}
10
@@ -13,7 +13,7 @@ function NoForget(props) {
13
}
14
15
export function Foo(props) {
16
- "use forget";
16
+ 'use forget';
17
return <Foo>{props.bar}</Foo>;
18
}
19
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/gating-test-export-function-and-default.js
+2
-2
@@ -1,6 +1,6 @@
1
// @gating @compilationMode(annotation)
2
export default function Bar(props) {
3
- "use forget";
3
+ 'use forget';
4
return <div>{props.bar}</div>;
5
}
6
@@ -9,6 +9,6 @@ function NoForget(props) {
9
}
10
11
export function Foo(props) {
12
- "use forget";
12
+ 'use forget';
13
return <Foo>{props.bar}</Foo>;
14
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/gating-test-export-function.expect.md
+2
-2
@@ -4,7 +4,7 @@
4
```javascript
5
// @gating @compilationMode(annotation)
6
export function Bar(props) {
7
- "use forget";
7
+ 'use forget';
8
return <div>{props.bar}</div>;
9
}
10
@@ -13,7 +13,7 @@ export function NoForget(props) {
13
}
14
15
export function Foo(props) {
16
- "use forget";
16
+ 'use forget';
17
return <Foo>{props.bar}</Foo>;
18
}
19
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/gating-test-export-function.js
+2
-2
@@ -1,6 +1,6 @@
1
// @gating @compilationMode(annotation)
2
export function Bar(props) {
3
- "use forget";
3
+ 'use forget';
4
return <div>{props.bar}</div>;
5
}
6
@@ -9,6 +9,6 @@ export function NoForget(props) {
9
}
10
11
export function Foo(props) {
12
- "use forget";
12
+ 'use forget';
13
return <Foo>{props.bar}</Foo>;
14
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/gating-test.expect.md
+2
-2
@@ -4,7 +4,7 @@
4
```javascript
5
// @gating @compilationMode(annotation)
6
function Bar(props) {
7
- "use forget";
7
+ 'use forget';
8
return <div>{props.bar}</div>;
9
}
10
@@ -13,7 +13,7 @@ function NoForget(props) {
13
}
14
15
function Foo(props) {
16
- "use forget";
16
+ 'use forget';
17
return <Foo>{props.bar}</Foo>;
18
}
19
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/gating-test.js
+2
-2
@@ -1,6 +1,6 @@
1
// @gating @compilationMode(annotation)
2
function Bar(props) {
3
- "use forget";
3
+ 'use forget';
4
return <div>{props.bar}</div>;
5
}
6
@@ -9,6 +9,6 @@ function NoForget(props) {
9
}
10
11
function Foo(props) {
12
- "use forget";
12
+ 'use forget';
13
return <Foo>{props.bar}</Foo>;
14
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/globals-Boolean.expect.md
+2
-2
@@ -10,8 +10,8 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/globals-Boolean.js
+2
-2
@@ -6,6 +6,6 @@ function Component(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/globals-Number.expect.md
+2
-2
@@ -10,8 +10,8 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/globals-Number.js
+2
-2
@@ -6,6 +6,6 @@ function Component(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/globals-String.expect.md
+2
-2
@@ -10,8 +10,8 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/globals-String.js
+2
-2
@@ -6,6 +6,6 @@ function Component(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/globals-dont-resolve-local-useState.expect.md
+4
-4
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import { useState as _useState, useCallback, useEffect } from "react";
6
-import { ValidateMemoization } from "shared-runtime";
5
+import {useState as _useState, useCallback, useEffect} from 'react';
6
+import {ValidateMemoization} from 'shared-runtime';
7
8
function useState(value) {
9
const [state, setState] = _useState(value);
@@ -11,9 +11,9 @@ function useState(value) {
11
}
12
13
function Component() {
14
- const [state, setState] = useState("hello");
14
+ const [state, setState] = useState('hello');
15
16
- return <div onClick={() => setState("goodbye")}>{state}</div>;
16
+ return <div onClick={() => setState('goodbye')}>{state}</div>;
17
}
18
19
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/globals-dont-resolve-local-useState.js
+4
-4
@@ -1,5 +1,5 @@
1
-import { useState as _useState, useCallback, useEffect } from "react";
2
-import { ValidateMemoization } from "shared-runtime";
1
+import {useState as _useState, useCallback, useEffect} from 'react';
2
+import {ValidateMemoization} from 'shared-runtime';
3
4
function useState(value) {
5
const [state, setState] = _useState(value);
@@ -7,9 +7,9 @@ function useState(value) {
7
}
8
9
function Component() {
10
- const [state, setState] = useState("hello");
10
+ const [state, setState] = useState('hello');
11
12
- return <div onClick={() => setState("goodbye")}>{state}</div>;
12
+ return <div onClick={() => setState('goodbye')}>{state}</div>;
13
}
14
15
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hoisted-declaration-with-scope.expect.md
+5
-5
@@ -2,23 +2,23 @@
2
## Input
3
4
```javascript
5
-import { StaticText1, Stringify, identity, useHook } from "shared-runtime";
5
+import {StaticText1, Stringify, identity, useHook} from 'shared-runtime';
6
7
/**
8
* `button` and `dispatcher` must end up in the same memo block. It would be
9
* invalid for `button` to take a dependency on `dispatcher` as dispatcher
10
* is created later.
11
*/
12
-function useFoo({ onClose }) {
12
+function useFoo({onClose}) {
13
const button = StaticText1 ?? (
14
<Stringify
15
primary={{
16
- label: identity("label"),
16
+ label: identity('label'),
17
onPress: onClose,
18
}}
19
secondary={{
20
onPress: () => {
21
- dispatcher.go("route2");
21
+ dispatcher.go('route2');
22
},
23
}}
24
/>
@@ -31,7 +31,7 @@ function useFoo({ onClose }) {
31
32
export const FIXTURE_ENTRYPOINT = {
33
fn: useFoo,
34
- params: [{ onClose: identity() }],
34
+ params: [{onClose: identity()}],
35
};
36
37
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hoisted-declaration-with-scope.tsx
+5
-5
@@ -1,20 +1,20 @@
1
-import { StaticText1, Stringify, identity, useHook } from "shared-runtime";
1
+import {StaticText1, Stringify, identity, useHook} from 'shared-runtime';
2
3
/**
4
* `button` and `dispatcher` must end up in the same memo block. It would be
5
* invalid for `button` to take a dependency on `dispatcher` as dispatcher
6
* is created later.
7
*/
8
-function useFoo({ onClose }) {
8
+function useFoo({onClose}) {
9
const button = StaticText1 ?? (
10
<Stringify
11
primary={{
12
- label: identity("label"),
12
+ label: identity('label'),
13
onPress: onClose,
14
}}
15
secondary={{
16
onPress: () => {
17
- dispatcher.go("route2");
17
+ dispatcher.go('route2');
18
},
19
}}
20
/>
@@ -27,5 +27,5 @@ function useFoo({ onClose }) {
27
28
export const FIXTURE_ENTRYPOINT = {
29
fn: useFoo,
30
- params: [{ onClose: identity() }],
30
+ params: [{onClose: identity()}],
31
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hoisting-computed-member-expression.expect.md
+4
-4
@@ -2,17 +2,17 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
function hoisting() {
8
function onClick() {
9
- return bar["baz"];
9
+ return bar['baz'];
10
}
11
function onClick2() {
12
return bar[baz];
13
}
14
- const baz = "baz";
15
- const bar = { baz: 1 };
14
+ const baz = 'baz';
15
+ const bar = {baz: 1};
16
17
return (
18
<Stringify onClick={onClick} onClick2={onClick2} shouldInvokeFns={true} />
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hoisting-computed-member-expression.js
+4
-4
@@ -1,14 +1,14 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
function hoisting() {
4
function onClick() {
5
- return bar["baz"];
5
+ return bar['baz'];
6
}
7
function onClick2() {
8
return bar[baz];
9
}
10
- const baz = "baz";
11
- const bar = { baz: 1 };
10
+ const baz = 'baz';
11
+ const bar = {baz: 1};
12
13
return (
14
<Stringify onClick={onClick} onClick2={onClick2} shouldInvokeFns={true} />
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hoisting-member-expression.expect.md
+2
-2
@@ -2,13 +2,13 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
function hoisting() {
8
function onClick(x) {
9
return x + bar.baz;
10
}
11
- const bar = { baz: 1 };
11
+ const bar = {baz: 1};
12
13
return <Stringify onClick={onClick} />;
14
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hoisting-member-expression.js
+2
-2
@@ -1,10 +1,10 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
function hoisting() {
4
function onClick(x) {
5
return x + bar.baz;
6
}
7
- const bar = { baz: 1 };
7
+ const bar = {baz: 1};
8
9
return <Stringify onClick={onClick} />;
10
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hoisting-nested-block-statements.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { print } from "shared-runtime";
5
+import {print} from 'shared-runtime';
6
7
function hoisting(cond) {
8
if (cond) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hoisting-nested-block-statements.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { print } from "shared-runtime";
1
+import {print} from 'shared-runtime';
2
3
function hoisting(cond) {
4
if (cond) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hoisting-recursive-call-within-lambda.expect.md
+2
-2
@@ -3,8 +3,8 @@
3
4
```javascript
5
function Foo({}) {
6
- const outer = (val) => {
7
- const fact = (x) => {
6
+ const outer = val => {
7
+ const fact = x => {
8
if (x <= 0) {
9
return 1;
10
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hoisting-recursive-call-within-lambda.js
+2
-2
@@ -1,6 +1,6 @@
1
function Foo({}) {
2
- const outer = (val) => {
3
- const fact = (x) => {
2
+ const outer = val => {
3
+ const fact = x => {
4
if (x <= 0) {
5
return 1;
6
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hoisting-recursive-call.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function Foo({ value }: { value: number }) {
5
+function Foo({value}: {value: number}) {
6
const factorial = (x: number) => {
7
if (x <= 1) {
8
return 1;
@@ -16,7 +16,7 @@ function Foo({ value }: { value: number }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Foo,
19
- params: [{ value: 3 }],
19
+ params: [{value: 3}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hoisting-recursive-call.ts
+2
-2
@@ -1,4 +1,4 @@
1
-function Foo({ value }: { value: number }) {
1
+function Foo({value}: {value: number}) {
2
const factorial = (x: number) => {
3
if (x <= 1) {
4
return 1;
@@ -12,5 +12,5 @@ function Foo({ value }: { value: number }) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Foo,
15
- params: [{ value: 3 }],
15
+ params: [{value: 3}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/holey-array-expr.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { CONST_STRING0 } from "shared-runtime";
5
+import {CONST_STRING0} from 'shared-runtime';
6
7
function t(props) {
8
let x = [, CONST_STRING0, props];
@@ -11,7 +11,7 @@ function t(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: t,
14
- params: [{ a: 1, b: 2 }],
14
+ params: [{a: 1, b: 2}],
15
isComponent: false,
16
};
17
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/holey-array-expr.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { CONST_STRING0 } from "shared-runtime";
1
+import {CONST_STRING0} from 'shared-runtime';
2
3
function t(props) {
4
let x = [, CONST_STRING0, props];
@@ -7,6 +7,6 @@ function t(props) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: t,
10
- params: [{ a: 1, b: 2 }],
10
+ params: [{a: 1, b: 2}],
11
isComponent: false,
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/holey-array-pattern-dce-2.expect.md
+2
-2
@@ -9,8 +9,8 @@ function t(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: t,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/holey-array-pattern-dce-2.js
+2
-2
@@ -5,6 +5,6 @@ function t(props) {
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: t,
8
- params: ["TodoAdd"],
9
- isComponent: "TodoAdd",
8
+ params: ['TodoAdd'],
9
+ isComponent: 'TodoAdd',
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/holey-array-pattern-dce.expect.md
+2
-2
@@ -9,8 +9,8 @@ function t(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: t,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/holey-array-pattern-dce.js
+2
-2
@@ -5,6 +5,6 @@ function t(props) {
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: t,
8
- params: ["TodoAdd"],
9
- isComponent: "TodoAdd",
8
+ params: ['TodoAdd'],
9
+ isComponent: 'TodoAdd',
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/holey-array.expect.md
+2
-2
@@ -10,8 +10,8 @@ function t(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: t,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/holey-array.js
+2
-2
@@ -6,6 +6,6 @@ function t(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: t,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hook-noAlias.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { useNoAlias } from "shared-runtime";
5
+import {useNoAlias} from 'shared-runtime';
6
7
function Component(props) {
8
- const item = { a: props.a };
8
+ const item = {a: props.a};
9
const x = useNoAlias(
10
item,
11
() => {
@@ -18,7 +18,7 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ a: { id: 42 } }],
21
+ params: [{a: {id: 42}}],
22
isComponent: true,
23
};
24
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hook-noAlias.js
+3
-3
@@ -1,7 +1,7 @@
1
-import { useNoAlias } from "shared-runtime";
1
+import {useNoAlias} from 'shared-runtime';
2
3
function Component(props) {
4
- const item = { a: props.a };
4
+ const item = {a: props.a};
5
const x = useNoAlias(
6
item,
7
() => {
@@ -14,6 +14,6 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ a: { id: 42 } }],
17
+ params: [{a: {id: 42}}],
18
isComponent: true,
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hooks-with-prefix.expect.md
+3
-3
@@ -4,8 +4,8 @@
4
```javascript
5
// @hookPattern:".*\b(use[^$]+)$"
6
7
-import * as React from "react";
8
-import { makeArray, useHook } from "shared-runtime";
7
+import * as React from 'react';
8
+import {makeArray, useHook} from 'shared-runtime';
9
10
const React$useState = React.useState;
11
const React$useMemo = React.useMemo;
@@ -20,7 +20,7 @@ function Component() {
20
}, [state]);
21
return (
22
<div>
23
- {doubledArray.join("")}
23
+ {doubledArray.join('')}
24
{json}
25
</div>
26
);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/hooks-with-prefix.js
+3
-3
@@ -1,7 +1,7 @@
1
// @hookPattern:".*\b(use[^$]+)$"
2
3
-import * as React from "react";
4
-import { makeArray, useHook } from "shared-runtime";
3
+import * as React from 'react';
4
+import {makeArray, useHook} from 'shared-runtime';
5
6
const React$useState = React.useState;
7
const React$useMemo = React.useMemo;
@@ -16,7 +16,7 @@ function Component() {
16
}, [state]);
17
return (
18
<div>
19
- {doubledArray.join("")}
19
+ {doubledArray.join('')}
20
{json}
21
</div>
22
);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ignore-use-no-forget.expect.md
+2
-2
@@ -4,14 +4,14 @@
4
```javascript
5
// @ignoreUseNoForget
6
function Component(prop) {
7
- "use no forget";
7
+ 'use no forget';
8
const result = prop.x.toFixed();
9
return <div>{result}</div>;
10
}
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ x: 1 }],
14
+ params: [{x: 1}],
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ignore-use-no-forget.js
+2
-2
@@ -1,11 +1,11 @@
1
// @ignoreUseNoForget
2
function Component(prop) {
3
- "use no forget";
3
+ 'use no forget';
4
const result = prop.x.toFixed();
5
return <div>{result}</div>;
6
}
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: [{ x: 1 }],
10
+ params: [{x: 1}],
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/iife-return-modified-later-phi.expect.md
+1
-1
@@ -16,7 +16,7 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ a: {} }],
19
+ params: [{a: {}}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/iife-return-modified-later-phi.js
+1
-1
@@ -12,5 +12,5 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ a: {} }],
15
+ params: [{a: {}}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/iife-return-modified-later.expect.md
+1
-1
@@ -12,7 +12,7 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ a: {} }],
15
+ params: [{a: {}}],
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/iife-return-modified-later.js
+1
-1
@@ -8,5 +8,5 @@ function Component(props) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: [{ a: {} }],
11
+ params: [{a: {}}],
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/inadvertent-mutability-readonly-lambda.expect.md
+1
-1
@@ -6,7 +6,7 @@ function Component(props) {
6
const [value, setValue] = useState(null);
7
// NOTE: this lambda does not capture any mutable values (only the state setter)
8
// and thus should be treated as readonly
9
- const onChange = (e) => setValue((value) => value + e.target.value);
9
+ const onChange = e => setValue(value => value + e.target.value);
10
11
useOtherHook();
12
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/inadvertent-mutability-readonly-lambda.js
+1
-1
@@ -2,7 +2,7 @@ function Component(props) {
2
const [value, setValue] = useState(null);
3
// NOTE: this lambda does not capture any mutable values (only the state setter)
4
// and thus should be treated as readonly
5
- const onChange = (e) => setValue((value) => value + e.target.value);
5
+ const onChange = e => setValue(value => value + e.target.value);
6
7
useOtherHook();
8
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/incompatible-destructuring-kinds.expect.md
+4
-4
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-import { useMemo } from "react";
6
-import { Stringify } from "shared-runtime";
5
+import {useMemo} from 'react';
6
+import {Stringify} from 'shared-runtime';
7
8
function Component({}) {
9
- let a = "a";
10
- let b = "";
9
+ let a = 'a';
10
+ let b = '';
11
[a, b] = [null, null];
12
// NOTE: reference `a` in a callback to force a context variable
13
return <Stringify a={a} b={b} onClick={() => a} />;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/incompatible-destructuring-kinds.js
+4
-4
@@ -1,9 +1,9 @@
1
-import { useMemo } from "react";
2
-import { Stringify } from "shared-runtime";
1
+import {useMemo} from 'react';
2
+import {Stringify} from 'shared-runtime';
3
4
function Component({}) {
5
- let a = "a";
6
- let b = "";
5
+ let a = 'a';
6
+ let b = '';
7
[a, b] = [null, null];
8
// NOTE: reference `a` in a callback to force a context variable
9
return <Stringify a={a} b={b} onClick={() => a} />;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/independently-memoize-object-property.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function foo(a, b, c) {
6
- const x = { a: a };
6
+ const x = {a: a};
7
// NOTE: this array should memoize independently from x, w only b,c as deps
8
x.y = [b, c];
9
@@ -12,8 +12,8 @@ function foo(a, b, c) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: foo,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/independently-memoize-object-property.js
+3
-3
@@ -1,5 +1,5 @@
1
function foo(a, b, c) {
2
- const x = { a: a };
2
+ const x = {a: a};
3
// NOTE: this array should memoize independently from x, w only b,c as deps
4
x.y = [b, c];
5
@@ -8,6 +8,6 @@ function foo(a, b, c) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: foo,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-compile-hooks-with-multiple-params.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @compilationMode(infer)
6
-import { useNoAlias } from "shared-runtime";
6
+import {useNoAlias} from 'shared-runtime';
7
8
// This should be compiled by Forget
9
function useFoo(value1, value2) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-compile-hooks-with-multiple-params.js
+1
-1
@@ -1,5 +1,5 @@
1
// @compilationMode(infer)
2
-import { useNoAlias } from "shared-runtime";
2
+import {useNoAlias} from 'shared-runtime';
3
4
// This should be compiled by Forget
5
function useFoo(value1, value2) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-function-React-memo.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @compilationMode(infer)
6
-React.memo((props) => {
6
+React.memo(props => {
7
return <div />;
8
});
9
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-function-React-memo.js
+1
-1
@@ -1,4 +1,4 @@
1
// @compilationMode(infer)
2
-React.memo((props) => {
2
+React.memo(props => {
3
return <div />;
4
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-function-assignment.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @compilationMode(infer)
6
-const Component = (props) => {
6
+const Component = props => {
7
return <div />;
8
};
9
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-function-assignment.js
+1
-1
@@ -1,4 +1,4 @@
1
// @compilationMode(infer)
2
-const Component = (props) => {
2
+const Component = props => {
3
return <div />;
4
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-function-expression-React-memo-gating.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @gating @compilationMode(infer)
6
-import React from "react";
6
+import React from 'react';
7
export default React.forwardRef(function notNamedLikeAComponent(props) {
8
return <div />;
9
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-function-expression-React-memo-gating.js
+1
-1
@@ -1,5 +1,5 @@
1
// @gating @compilationMode(infer)
2
-import React from "react";
2
+import React from 'react';
3
export default React.forwardRef(function notNamedLikeAComponent(props) {
4
return <div />;
5
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-function-forwardRef.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @compilationMode(infer)
6
-React.forwardRef((props) => {
6
+React.forwardRef(props => {
7
return <div />;
8
});
9
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-function-forwardRef.js
+1
-1
@@ -1,4 +1,4 @@
1
// @compilationMode(infer)
2
-React.forwardRef((props) => {
2
+React.forwardRef(props => {
3
return <div />;
4
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-global-object.expect.md
+3
-3
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity, sum } from "shared-runtime";
5
+import {identity, sum} from 'shared-runtime';
6
7
// Check that we correctly resolve type and effect lookups on the javascript
8
// global object.
@@ -15,12 +15,12 @@ function Component(props) {
15
// Even though we don't know the function signature of sum,
16
// we should be able to infer that it does not mutate its inputs.
17
sum(primitiveVal1, primitiveVal2, primitiveVal3);
18
- return { primitiveVal1, primitiveVal2, primitiveVal3 };
18
+ return {primitiveVal1, primitiveVal2, primitiveVal3};
19
}
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
- params: [{ a: 1, b: 2 }],
23
+ params: [{a: 1, b: 2}],
24
isComponent: false,
25
};
26
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-global-object.js
+3
-3
@@ -1,4 +1,4 @@
1
-import { identity, sum } from "shared-runtime";
1
+import {identity, sum} from 'shared-runtime';
2
3
// Check that we correctly resolve type and effect lookups on the javascript
4
// global object.
@@ -11,11 +11,11 @@ function Component(props) {
11
// Even though we don't know the function signature of sum,
12
// we should be able to infer that it does not mutate its inputs.
13
sum(primitiveVal1, primitiveVal2, primitiveVal3);
14
- return { primitiveVal1, primitiveVal2, primitiveVal3 };
14
+ return {primitiveVal1, primitiveVal2, primitiveVal3};
15
}
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ a: 1, b: 2 }],
19
+ params: [{a: 1, b: 2}],
20
isComponent: false,
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-no-component-annot.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @compilationMode(infer)
6
-import { useIdentity, identity } from "shared-runtime";
6
+import {useIdentity, identity} from 'shared-runtime';
7
8
function Component(fakeProps: number) {
9
const x = useIdentity(fakeProps);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-no-component-annot.ts
+1
-1
@@ -1,5 +1,5 @@
1
// @compilationMode(infer)
2
-import { useIdentity, identity } from "shared-runtime";
2
+import {useIdentity, identity} from 'shared-runtime';
3
4
function Component(fakeProps: number) {
5
const x = useIdentity(fakeProps);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-no-component-obj-return.expect.md
+1
-1
@@ -5,7 +5,7 @@
5
// @compilationMode(infer)
6
function Component(props) {
7
const ignore = <foo />;
8
- return { foo: f(props) };
8
+ return {foo: f(props)};
9
}
10
11
function f(props) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/infer-no-component-obj-return.js
+1
-1
@@ -1,7 +1,7 @@
1
// @compilationMode(infer)
2
function Component(props) {
3
const ignore = <foo />;
4
- return { foo: f(props) };
4
+ return {foo: f(props)};
5
}
6
7
function f(props) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/inverted-if-else.expect.md
+2
-2
@@ -16,8 +16,8 @@ function foo(a, b, c) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: foo,
19
- params: ["TodoAdd"],
20
- isComponent: "TodoAdd",
19
+ params: ['TodoAdd'],
20
+ isComponent: 'TodoAdd',
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/inverted-if-else.js
+2
-2
@@ -12,6 +12,6 @@ function foo(a, b, c) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: foo,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/inverted-if.expect.md
+2
-2
@@ -16,8 +16,8 @@ function foo(a, b, c, d) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: foo,
19
- params: ["TodoAdd"],
20
- isComponent: "TodoAdd",
19
+ params: ['TodoAdd'],
20
+ isComponent: 'TodoAdd',
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/inverted-if.js
+2
-2
@@ -12,6 +12,6 @@ function foo(a, b, c, d) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: foo,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/issue852.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function Component(c) {
6
- let x = { c };
6
+ let x = {c};
7
mutate(x);
8
let a = x;
9
let b = a;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/issue852.js
+1
-1
@@ -1,5 +1,5 @@
1
function Component(c) {
2
- let x = { c };
2
+ let x = {c};
3
mutate(x);
4
let a = x;
5
let b = a;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/issue933-disjoint-set-infinite-loop.expect.md
+2
-2
@@ -3,9 +3,9 @@
3
4
```javascript
5
function makeObj() {
6
- "use no forget";
6
+ 'use no forget';
7
const result = [];
8
- result.a = { b: 2 };
8
+ result.a = {b: 2};
9
10
return result;
11
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/issue933-disjoint-set-infinite-loop.js
+2
-2
@@ -1,7 +1,7 @@
1
function makeObj() {
2
- "use no forget";
2
+ 'use no forget';
3
const result = [];
4
- result.a = { b: 2 };
4
+ result.a = {b: 2};
5
6
return result;
7
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-attribute-default-to-true.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
function Component() {
8
// https://legacy.reactjs.org/docs/jsx-in-depth.html#props-default-to-true
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-attribute-default-to-true.tsx
+1
-1
@@ -1,4 +1,4 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
function Component() {
4
// https://legacy.reactjs.org/docs/jsx-in-depth.html#props-default-to-true
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-attribute-with-jsx-element-value.expect.md
+7
-8
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @flow
6
-function Component({ items }) {
6
+function Component({items}) {
7
// Per the spec, <Foo value=<>{...}</> /> is valid.
8
// But many tools don't allow fragments as jsx attribute values,
9
// so we ensure not to emit them wrapped in an expression container
@@ -11,30 +11,29 @@ function Component({ items }) {
11
<Foo
12
value={
13
<Bar>
14
- {items.map((item) => (
14
+ {items.map(item => (
15
<Item key={item.id} item={item} />
16
))}
17
</Bar>
18
- }
19
- ></Foo>
18
+ }></Foo>
19
) : null;
20
}
21
23
-function Foo({ value }) {
22
+function Foo({value}) {
23
return value;
24
}
25
27
-function Bar({ children }) {
26
+function Bar({children}) {
27
return <div>{children}</div>;
28
}
29
31
-function Item({ item }) {
30
+function Item({item}) {
31
return <div>{item.name}</div>;
32
}
33
34
export const FIXTURE_ENTRYPOINT = {
35
fn: Component,
37
- params: [{ items: [{ id: 1, name: "One!" }] }],
36
+ params: [{items: [{id: 1, name: 'One!'}]}],
37
};
38
39
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-attribute-with-jsx-element-value.js
+7
-8
@@ -1,5 +1,5 @@
1
// @flow
2
-function Component({ items }) {
2
+function Component({items}) {
3
// Per the spec, <Foo value=<>{...}</> /> is valid.
4
// But many tools don't allow fragments as jsx attribute values,
5
// so we ensure not to emit them wrapped in an expression container
@@ -7,28 +7,27 @@ function Component({ items }) {
7
<Foo
8
value={
9
<Bar>
10
- {items.map((item) => (
10
+ {items.map(item => (
11
<Item key={item.id} item={item} />
12
))}
13
</Bar>
14
- }
15
- ></Foo>
14
+ }></Foo>
15
) : null;
16
}
17
19
-function Foo({ value }) {
18
+function Foo({value}) {
19
return value;
20
}
21
23
-function Bar({ children }) {
22
+function Bar({children}) {
23
return <div>{children}</div>;
24
}
25
27
-function Item({ item }) {
26
+function Item({item}) {
27
return <div>{item.name}</div>;
28
}
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: Component,
33
- params: [{ items: [{ id: 1, name: "One!" }] }],
32
+ params: [{items: [{id: 1, name: 'One!'}]}],
33
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-empty-expression.expect.md
+1
-1
@@ -13,7 +13,7 @@ export function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ a: "hello" }],
16
+ params: [{a: 'hello'}],
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-empty-expression.js
+1
-1
@@ -9,5 +9,5 @@ export function Component(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: [{ a: "hello" }],
12
+ params: [{a: 'hello'}],
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-fragment.expect.md
+3
-3
@@ -5,7 +5,7 @@
5
function Foo(props) {
6
return (
7
<>
8
- Hello {props.greeting}{" "}
8
+ Hello {props.greeting}{' '}
9
<div>
10
<>Text</>
11
</div>
@@ -15,8 +15,8 @@ function Foo(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Foo,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-fragment.js
+3
-3
@@ -1,7 +1,7 @@
1
function Foo(props) {
2
return (
3
<>
4
- Hello {props.greeting}{" "}
4
+ Hello {props.greeting}{' '}
5
<div>
6
<>Text</>
7
</div>
@@ -11,6 +11,6 @@ function Foo(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Foo,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-freeze.expect.md
+4
-4
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-import { jsx as _jsx } from "react/jsx-runtime";
6
-import { shallowCopy } from "shared-runtime";
5
+import {jsx as _jsx} from 'react/jsx-runtime';
6
+import {shallowCopy} from 'shared-runtime';
7
8
function Component(props) {
9
- const childprops = { style: { width: props.width } };
10
- const element = _jsx("div", {
9
+ const childprops = {style: {width: props.width}};
10
+ const element = _jsx('div', {
11
childprops: childprops,
12
children: '"hello world"',
13
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-freeze.js
+4
-4
@@ -1,9 +1,9 @@
1
-import { jsx as _jsx } from "react/jsx-runtime";
2
-import { shallowCopy } from "shared-runtime";
1
+import {jsx as _jsx} from 'react/jsx-runtime';
2
+import {shallowCopy} from 'shared-runtime';
3
4
function Component(props) {
5
- const childprops = { style: { width: props.width } };
6
- const element = _jsx("div", {
5
+ const childprops = {style: {width: props.width}};
6
+ const element = _jsx('div', {
7
childprops: childprops,
8
children: '"hello world"',
9
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-local-memberexpr-tag-conditional.expect.md
+3
-3
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import * as SharedRuntime from "shared-runtime";
6
-function useFoo({ cond }) {
5
+import * as SharedRuntime from 'shared-runtime';
6
+function useFoo({cond}) {
7
const MyLocal = SharedRuntime;
8
if (cond) {
9
return <MyLocal.Text value={4} />;
@@ -14,7 +14,7 @@ function useFoo({ cond }) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: useFoo,
17
- params: [{ cond: true }],
17
+ params: [{cond: true}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-local-memberexpr-tag-conditional.js
+3
-3
@@ -1,5 +1,5 @@
1
-import * as SharedRuntime from "shared-runtime";
2
-function useFoo({ cond }) {
1
+import * as SharedRuntime from 'shared-runtime';
2
+function useFoo({cond}) {
3
const MyLocal = SharedRuntime;
4
if (cond) {
5
return <MyLocal.Text value={4} />;
@@ -10,5 +10,5 @@ function useFoo({ cond }) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: useFoo,
13
- params: [{ cond: true }],
13
+ params: [{cond: true}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-local-memberexpr-tag.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import * as SharedRuntime from "shared-runtime";
5
+import * as SharedRuntime from 'shared-runtime';
6
function useFoo() {
7
const MyLocal = SharedRuntime;
8
return <MyLocal.Text value={4} />;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-local-memberexpr-tag.js
+1
-1
@@ -1,4 +1,4 @@
1
-import * as SharedRuntime from "shared-runtime";
1
+import * as SharedRuntime from 'shared-runtime';
2
function useFoo() {
3
const MyLocal = SharedRuntime;
4
return <MyLocal.Text value={4} />;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-local-tag-in-lambda.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
function useFoo() {
7
const MyLocal = Stringify;
8
const callback = () => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-local-tag-in-lambda.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
function useFoo() {
3
const MyLocal = Stringify;
4
const callback = () => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-memberexpr-tag-in-lambda.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import * as SharedRuntime from "shared-runtime";
5
+import * as SharedRuntime from 'shared-runtime';
6
function useFoo() {
7
const MyLocal = SharedRuntime;
8
const callback = () => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-memberexpr-tag-in-lambda.js
+1
-1
@@ -1,4 +1,4 @@
1
-import * as SharedRuntime from "shared-runtime";
1
+import * as SharedRuntime from 'shared-runtime';
2
function useFoo() {
3
const MyLocal = SharedRuntime;
4
const callback = () => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-namespaced-name.expect.md
+2
-2
@@ -8,8 +8,8 @@ function Component(props) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
14
15
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-namespaced-name.js
+2
-2
@@ -4,6 +4,6 @@ function Component(props) {
4
5
export const FIXTURE_ENTRYPOINT = {
6
fn: Component,
7
- params: ["TodoAdd"],
8
- isComponent: "TodoAdd",
7
+ params: ['TodoAdd'],
8
+ isComponent: 'TodoAdd',
9
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-preserve-whitespace.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { StaticText1 } from "shared-runtime";
5
+import {StaticText1} from 'shared-runtime';
6
7
function Component() {
8
return (
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-preserve-whitespace.tsx
+1
-1
@@ -1,4 +1,4 @@
1
-import { StaticText1 } from "shared-runtime";
1
+import {StaticText1} from 'shared-runtime';
2
3
function Component() {
4
return (
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-reactive-local-variable-member-expr.expect.md
+3
-8
@@ -2,20 +2,16 @@
2
## Input
3
4
```javascript
5
-import * as sharedRuntime from "shared-runtime";
5
+import * as sharedRuntime from 'shared-runtime';
6
7
-function Component({
8
- something,
9
-}: {
10
- something: { StaticText1: React.ElementType };
11
-}) {
7
+function Component({something}: {something: {StaticText1: React.ElementType}}) {
8
const Foo = something.StaticText1;
9
return () => <Foo />;
10
}
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
18
- params: [{ something: sharedRuntime }],
14
+ params: [{something: sharedRuntime}],
15
};
16
17
```
@@ -29,7 +25,6 @@ import * as sharedRuntime from "shared-runtime";
25
function Component(t0) {
26
const $ = _c(2);
27
const { something } = t0;
32
-
28
const Foo = something.StaticText1;
29
let t1;
30
if ($[0] !== Foo) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-reactive-local-variable-member-expr.tsx
+3
-7
@@ -1,15 +1,11 @@
1
-import * as sharedRuntime from "shared-runtime";
1
+import * as sharedRuntime from 'shared-runtime';
2
3
-function Component({
4
- something,
5
-}: {
6
- something: { StaticText1: React.ElementType };
7
-}) {
3
+function Component({something}: {something: {StaticText1: React.ElementType}}) {
4
const Foo = something.StaticText1;
5
return () => <Foo />;
6
}
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
14
- params: [{ something: sharedRuntime }],
10
+ params: [{something: sharedRuntime}],
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-spread.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
function Component(props) {
6
return (
7
- <Component {...props} {...{ bar: props.cond ? props.foo : props.bar }} />
7
+ <Component {...props} {...{bar: props.cond ? props.foo : props.bar}} />
8
);
9
}
10
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-spread.js
+1
-1
@@ -1,5 +1,5 @@
1
function Component(props) {
2
return (
3
- <Component {...props} {...{ bar: props.cond ? props.foo : props.bar }} />
3
+ <Component {...props} {...{bar: props.cond ? props.foo : props.bar}} />
4
);
5
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-string-attribute-expression-container.expect.md
+7
-7
@@ -5,17 +5,17 @@
5
function Component() {
6
return (
7
<div>
8
- <Text value={"\n"} />
9
- <Text value={"A\tE"} />
10
- <Text value={"나은"} />
11
- <Text value={"Lauren"} />
12
- <Text value={"சத்யா"} />
13
- <Text value={"Sathya"} />
8
+ <Text value={'\n'} />
9
+ <Text value={'A\tE'} />
10
+ <Text value={'나은'} />
11
+ <Text value={'Lauren'} />
12
+ <Text value={'சத்யா'} />
13
+ <Text value={'Sathya'} />
14
</div>
15
);
16
}
17
18
-function Text({ value }) {
18
+function Text({value}) {
19
return <span>{value}</span>;
20
}
21
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-string-attribute-expression-container.js
+7
-7
@@ -1,17 +1,17 @@
1
function Component() {
2
return (
3
<div>
4
- <Text value={"\n"} />
5
- <Text value={"A\tE"} />
6
- <Text value={"나은"} />
7
- <Text value={"Lauren"} />
8
- <Text value={"சத்யா"} />
9
- <Text value={"Sathya"} />
4
+ <Text value={'\n'} />
5
+ <Text value={'A\tE'} />
6
+ <Text value={'나은'} />
7
+ <Text value={'Lauren'} />
8
+ <Text value={'சத்யா'} />
9
+ <Text value={'Sathya'} />
10
</div>
11
);
12
}
13
14
-function Text({ value }) {
14
+function Text({value}) {
15
return <span>{value}</span>;
16
}
17
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-string-attribute-non-ascii.expect.md
+1
-1
@@ -11,7 +11,7 @@ function Component() {
11
);
12
}
13
14
-function Post({ author, text }) {
14
+function Post({author, text}) {
15
return (
16
<div>
17
<h1>{author}</h1>
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-string-attribute-non-ascii.js
+1
-1
@@ -7,7 +7,7 @@ function Component() {
7
);
8
}
9
10
-function Post({ author, text }) {
10
+function Post({author, text}) {
11
return (
12
<div>
13
<h1>{author}</h1>
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-tag-evaluation-order-non-global.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { StaticText1, StaticText2 } from "shared-runtime";
5
+import {StaticText1, StaticText2} from 'shared-runtime';
6
7
function MaybeMutable() {
8
return {};
@@ -25,7 +25,7 @@ function Component(props) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Component,
28
- params: [{ component: StaticText1, alternateComponent: StaticText2 }],
28
+ params: [{component: StaticText1, alternateComponent: StaticText2}],
29
isComponent: true,
30
};
31
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-tag-evaluation-order-non-global.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { StaticText1, StaticText2 } from "shared-runtime";
1
+import {StaticText1, StaticText2} from 'shared-runtime';
2
3
function MaybeMutable() {
4
return {};
@@ -21,6 +21,6 @@ function Component(props) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
- params: [{ component: StaticText1, alternateComponent: StaticText2 }],
24
+ params: [{component: StaticText1, alternateComponent: StaticText2}],
25
isComponent: true,
26
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-tag-evaluation-order.expect.md
+3
-3
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { StaticText1, StaticText2 } from "shared-runtime";
5
+import {StaticText1, StaticText2} from 'shared-runtime';
6
7
-function Component(props: { value: string }) {
7
+function Component(props: {value: string}) {
8
let Tag = StaticText1;
9
10
// Currently, Forget preserves jsx whitespace in the source text.
@@ -16,7 +16,7 @@ function Component(props: { value: string }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ value: "string value 1" }],
19
+ params: [{value: 'string value 1'}],
20
isComponent: true,
21
};
22
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-tag-evaluation-order.tsx
+3
-3
@@ -1,6 +1,6 @@
1
-import { StaticText1, StaticText2 } from "shared-runtime";
1
+import {StaticText1, StaticText2} from 'shared-runtime';
2
3
-function Component(props: { value: string }) {
3
+function Component(props: {value: string}) {
4
let Tag = StaticText1;
5
6
// Currently, Forget preserves jsx whitespace in the source text.
@@ -12,6 +12,6 @@ function Component(props: { value: string }) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ value: "string value 1" }],
15
+ params: [{value: 'string value 1'}],
16
isComponent: true,
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-ternary-local-variable.expect.md
+3
-3
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { RenderPropAsChild, StaticText1, StaticText2 } from "shared-runtime";
5
+import {RenderPropAsChild, StaticText1, StaticText2} from 'shared-runtime';
6
7
-function Component(props: { showText1: boolean }) {
7
+function Component(props: {showText1: boolean}) {
8
const Foo = props.showText1 ? StaticText1 : StaticText2;
9
10
return <RenderPropAsChild items={[() => <Foo key="0" />]} />;
@@ -12,7 +12,7 @@ function Component(props: { showText1: boolean }) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ showText1: false }],
15
+ params: [{showText1: false}],
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/jsx-ternary-local-variable.tsx
+3
-3
@@ -1,6 +1,6 @@
1
-import { RenderPropAsChild, StaticText1, StaticText2 } from "shared-runtime";
1
+import {RenderPropAsChild, StaticText1, StaticText2} from 'shared-runtime';
2
3
-function Component(props: { showText1: boolean }) {
3
+function Component(props: {showText1: boolean}) {
4
const Foo = props.showText1 ? StaticText1 : StaticText2;
5
6
return <RenderPropAsChild items={[() => <Foo key="0" />]} />;
@@ -8,5 +8,5 @@ function Component(props: { showText1: boolean }) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: [{ showText1: false }],
11
+ params: [{showText1: false}],
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/labeled-break-within-label-switch.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { CONST_STRING0 } from "shared-runtime";
5
+import {CONST_STRING0} from 'shared-runtime';
6
7
function useHook(cond) {
8
const log = [];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/labeled-break-within-label-switch.ts
+1
-1
@@ -1,4 +1,4 @@
1
-import { CONST_STRING0 } from "shared-runtime";
1
+import {CONST_STRING0} from 'shared-runtime';
2
3
function useHook(cond) {
4
const log = [];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/lambda-array-access-member-expr-captured.expect.md
+2
-2
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { CONST_NUMBER0, invoke } from "shared-runtime";
5
+import {CONST_NUMBER0, invoke} from 'shared-runtime';
6
7
function Foo() {
8
- const x = [{ value: 0 }, { value: 1 }, { value: 2 }];
8
+ const x = [{value: 0}, {value: 1}, {value: 2}];
9
const param = CONST_NUMBER0;
10
const foo = () => {
11
return x[param].value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/lambda-array-access-member-expr-captured.ts
+2
-2
@@ -1,7 +1,7 @@
1
-import { CONST_NUMBER0, invoke } from "shared-runtime";
1
+import {CONST_NUMBER0, invoke} from 'shared-runtime';
2
3
function Foo() {
4
- const x = [{ value: 0 }, { value: 1 }, { value: 2 }];
4
+ const x = [{value: 0}, {value: 1}, {value: 2}];
5
const param = CONST_NUMBER0;
6
const foo = () => {
7
return x[param].value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/lambda-array-access-member-expr-param.expect.md
+2
-2
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { invoke } from "shared-runtime";
5
+import {invoke} from 'shared-runtime';
6
7
function Foo() {
8
- const x = [{ value: 0 }, { value: 1 }, { value: 2 }];
8
+ const x = [{value: 0}, {value: 1}, {value: 2}];
9
const foo = (param: number) => {
10
return x[param].value;
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/lambda-array-access-member-expr-param.ts
+2
-2
@@ -1,7 +1,7 @@
1
-import { invoke } from "shared-runtime";
1
+import {invoke} from 'shared-runtime';
2
3
function Foo() {
4
- const x = [{ value: 0 }, { value: 1 }, { value: 2 }];
4
+ const x = [{value: 0}, {value: 1}, {value: 2}];
5
const foo = (param: number) => {
6
return x[param].value;
7
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/lambda-capture-returned-alias.expect.md
+1
-1
@@ -13,7 +13,7 @@ function CaptureNotMutate(props) {
13
const element = bar(props.el);
14
15
const fn = function () {
16
- const arr = { element };
16
+ const arr = {element};
17
return arr[idx];
18
};
19
const aliasedElement = fn();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/lambda-capture-returned-alias.js
+1
-1
@@ -9,7 +9,7 @@ function CaptureNotMutate(props) {
9
const element = bar(props.el);
10
11
const fn = function () {
12
- const arr = { element };
12
+ const arr = {element};
13
return arr[idx];
14
};
15
const aliasedElement = fn();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/lambda-mutated-non-reactive-to-reactive.expect.md
+3
-3
@@ -5,15 +5,15 @@
5
function f(a) {
6
let x;
7
(() => {
8
- x = { a };
8
+ x = {a};
9
})();
10
return <div x={x} />;
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: f,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/lambda-mutated-non-reactive-to-reactive.js
+3
-3
@@ -1,13 +1,13 @@
1
function f(a) {
2
let x;
3
(() => {
4
- x = { a };
4
+ x = {a};
5
})();
6
return <div x={x} />;
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: f,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/lambda-mutated-ref-non-reactive.expect.md
+2
-2
@@ -13,8 +13,8 @@ function f(a) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: f,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/lambda-mutated-ref-non-reactive.js
+2
-2
@@ -9,6 +9,6 @@ function f(a) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: f,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/lambda-return-expression.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { invoke } from "shared-runtime";
5
+import {invoke} from 'shared-runtime';
6
7
function useFoo() {
8
const x = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/lambda-return-expression.ts
+1
-1
@@ -1,4 +1,4 @@
1
-import { invoke } from "shared-runtime";
1
+import {invoke} from 'shared-runtime';
2
3
function useFoo() {
4
const x = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/log-pruned-memoization.expect.md
+4
-4
@@ -3,13 +3,13 @@
3
4
```javascript
5
// @logger
6
-import { createContext, use, useState } from "react";
6
+import {createContext, use, useState} from 'react';
7
import {
8
Stringify,
9
identity,
10
makeObject_Primitives,
11
useHook,
12
-} from "shared-runtime";
12
+} from 'shared-runtime';
13
14
function Component() {
15
const w = use(Context);
@@ -129,8 +129,8 @@ export const FIXTURE_ENTRYPOINT = {
129
## Logs
130
131
```
132
-{"kind":"CompileSuccess","fnLoc":{"start":{"line":10,"column":0,"index":161},"end":{"line":33,"column":1,"index":905},"filename":"log-pruned-memoization.ts"},"fnName":"Component","memoSlots":6,"memoBlocks":2,"memoValues":2,"prunedMemoBlocks":2,"prunedMemoValues":3}
133
-{"kind":"CompileSuccess","fnLoc":{"start":{"line":37,"column":0,"index":941},"end":{"line":43,"column":1,"index":1039},"filename":"log-pruned-memoization.ts"},"fnName":"Wrapper","memoSlots":1,"memoBlocks":1,"memoValues":1,"prunedMemoBlocks":0,"prunedMemoValues":0}
132
+{"kind":"CompileSuccess","fnLoc":{"start":{"line":10,"column":0,"index":159},"end":{"line":33,"column":1,"index":903},"filename":"log-pruned-memoization.ts"},"fnName":"Component","memoSlots":6,"memoBlocks":2,"memoValues":2,"prunedMemoBlocks":2,"prunedMemoValues":3}
133
+{"kind":"CompileSuccess","fnLoc":{"start":{"line":37,"column":0,"index":939},"end":{"line":43,"column":1,"index":1037},"filename":"log-pruned-memoization.ts"},"fnName":"Wrapper","memoSlots":1,"memoBlocks":1,"memoValues":1,"prunedMemoBlocks":0,"prunedMemoValues":0}
134
```
135
136
### Eval output
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/log-pruned-memoization.js
+2
-2
@@ -1,11 +1,11 @@
1
// @logger
2
-import { createContext, use, useState } from "react";
2
+import {createContext, use, useState} from 'react';
3
import {
4
Stringify,
5
identity,
6
makeObject_Primitives,
7
useHook,
8
-} from "shared-runtime";
8
+} from 'shared-runtime';
9
10
function Component() {
11
const w = use(Context);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/logical-expression-object.expect.md
+3
-3
@@ -10,13 +10,13 @@ function component(props) {
10
// but what's weird is that the end of a's range doesn't quite extend to the object.
11
let a = props.a || (props.b && props.c && props.d);
12
let b = (props.a && props.b && props.c) || props.d;
13
- return { a, b };
13
+ return {a, b};
14
}
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: component,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/logical-expression-object.js
+3
-3
@@ -6,11 +6,11 @@ function component(props) {
6
// but what's weird is that the end of a's range doesn't quite extend to the object.
7
let a = props.a || (props.b && props.c && props.d);
8
let b = (props.a && props.b && props.c) || props.d;
9
- return { a, b };
9
+ return {a, b};
10
}
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: component,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/logical-expression.expect.md
+2
-2
@@ -10,8 +10,8 @@ function component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/logical-expression.js
+2
-2
@@ -6,6 +6,6 @@ function component(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: component,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/maybe-mutate-object-in-callback.expect.md
+3
-3
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-const { mutate } = require("shared-runtime");
5
+const {mutate} = require('shared-runtime');
6
7
function Component(props) {
8
const object = {};
@@ -14,13 +14,13 @@ function Component(props) {
14
return <Foo callback={onClick}>{props.children}</Foo>;
15
}
16
17
-function Foo({ children }) {
17
+function Foo({children}) {
18
return children;
19
}
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
- params: [{ children: <div>Hello</div> }],
23
+ params: [{children: <div>Hello</div>}],
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/maybe-mutate-object-in-callback.js
+3
-3
@@ -1,4 +1,4 @@
1
-const { mutate } = require("shared-runtime");
1
+const {mutate} = require('shared-runtime');
2
3
function Component(props) {
4
const object = {};
@@ -10,11 +10,11 @@ function Component(props) {
10
return <Foo callback={onClick}>{props.children}</Foo>;
11
}
12
13
-function Foo({ children }) {
13
+function Foo({children}) {
14
return children;
15
}
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ children: <div>Hello</div> }],
19
+ params: [{children: <div>Hello</div>}],
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mege-consecutive-scopes-dont-merge-with-different-deps.expect.md
+3
-3
@@ -2,17 +2,17 @@
2
## Input
3
4
```javascript
5
-const { getNumber, identity } = require("shared-runtime");
5
+const {getNumber, identity} = require('shared-runtime');
6
7
function Component(props) {
8
// Two scopes: one for `getNumber()`, one for the object literal.
9
// Neither has dependencies so they should merge
10
- return { a: getNumber(), b: identity(props.id), c: ["static"] };
10
+ return {a: getNumber(), b: identity(props.id), c: ['static']};
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ id: 42 }],
15
+ params: [{id: 42}],
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mege-consecutive-scopes-dont-merge-with-different-deps.js
+3
-3
@@ -1,12 +1,12 @@
1
-const { getNumber, identity } = require("shared-runtime");
1
+const {getNumber, identity} = require('shared-runtime');
2
3
function Component(props) {
4
// Two scopes: one for `getNumber()`, one for the object literal.
5
// Neither has dependencies so they should merge
6
- return { a: getNumber(), b: identity(props.id), c: ["static"] };
6
+ return {a: getNumber(), b: identity(props.id), c: ['static']};
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: [{ id: 42 }],
11
+ params: [{id: 42}],
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/memoization-comments.expect.md
+2
-2
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @enableMemoizationComments
6
-import { addOne, getNumber, identity } from "shared-runtime";
6
+import {addOne, getNumber, identity} from 'shared-runtime';
7
8
function Component(props) {
9
const x = identity(props.a);
@@ -14,7 +14,7 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ a: 1, b: 10 }],
17
+ params: [{a: 1, b: 10}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/memoization-comments.js
+2
-2
@@ -1,5 +1,5 @@
1
// @enableMemoizationComments
2
-import { addOne, getNumber, identity } from "shared-runtime";
2
+import {addOne, getNumber, identity} from 'shared-runtime';
3
4
function Component(props) {
5
const x = identity(props.a);
@@ -10,5 +10,5 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ a: 1, b: 10 }],
13
+ params: [{a: 1, b: 10}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-consecutive-nested-scopes.expect.md
+3
-3
@@ -2,21 +2,21 @@
2
## Input
3
4
```javascript
5
-const { getNumber } = require("shared-runtime");
5
+const {getNumber} = require('shared-runtime');
6
7
function Component(props) {
8
let x;
9
// Two scopes: one for `getNumber()`, one for the object literal.
10
// Neither has dependencies so they should merge
11
if (props.cond) {
12
- x = { session_id: getNumber() };
12
+ x = {session_id: getNumber()};
13
}
14
return x;
15
}
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ cond: true }],
19
+ params: [{cond: true}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-consecutive-nested-scopes.js
+3
-3
@@ -1,16 +1,16 @@
1
-const { getNumber } = require("shared-runtime");
1
+const {getNumber} = require('shared-runtime');
2
3
function Component(props) {
4
let x;
5
// Two scopes: one for `getNumber()`, one for the object literal.
6
// Neither has dependencies so they should merge
7
if (props.cond) {
8
- x = { session_id: getNumber() };
8
+ x = {session_id: getNumber()};
9
}
10
return x;
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ cond: true }],
15
+ params: [{cond: true}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-consecutive-scopes-deps-subset-of-decls.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useState } from "react";
5
+import {useState} from 'react';
6
7
function Component() {
8
const [count, setCount] = useState(0);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-consecutive-scopes-deps-subset-of-decls.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { useState } from "react";
1
+import {useState} from 'react';
2
3
function Component() {
4
const [count, setCount] = useState(0);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-consecutive-scopes-no-deps.expect.md
+2
-2
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-const { getNumber } = require("shared-runtime");
5
+const {getNumber} = require('shared-runtime');
6
7
function Component(props) {
8
// Two scopes: one for `getNumber()`, one for the object literal.
9
// Neither has dependencies so they should merge
10
- return { session_id: getNumber() };
10
+ return {session_id: getNumber()};
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-consecutive-scopes-no-deps.js
+2
-2
@@ -1,9 +1,9 @@
1
-const { getNumber } = require("shared-runtime");
1
+const {getNumber} = require('shared-runtime');
2
3
function Component(props) {
4
// Two scopes: one for `getNumber()`, one for the object literal.
5
// Neither has dependencies so they should merge
6
- return { session_id: getNumber() };
6
+ return {session_id: getNumber()};
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-consecutive-scopes-objects.expect.md
+7
-7
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import { useState } from "react";
6
-import { Stringify } from "shared-runtime";
5
+import {useState} from 'react';
6
+import {Stringify} from 'shared-runtime';
7
8
// This is a translation of the original merge-consecutive-scopes which uses plain objects
9
// to describe the UI instead of JSX. The JSXText elements in that fixture happen to
@@ -12,14 +12,14 @@ import { Stringify } from "shared-runtime";
12
function Component(props) {
13
let [state, setState] = useState(0);
14
return [
15
- { component: Stringify, props: { text: "Counter" } },
16
- { component: "span", props: { children: [state] } },
15
+ {component: Stringify, props: {text: 'Counter'}},
16
+ {component: 'span', props: {children: [state]}},
17
{
18
- component: "button",
18
+ component: 'button',
19
props: {
20
- "data-testid": "button",
20
+ 'data-testid': 'button',
21
onClick: () => setState(state + 1),
22
- children: ["increment"],
22
+ children: ['increment'],
23
},
24
},
25
];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-consecutive-scopes-objects.js
+7
-7
@@ -1,5 +1,5 @@
1
-import { useState } from "react";
2
-import { Stringify } from "shared-runtime";
1
+import {useState} from 'react';
2
+import {Stringify} from 'shared-runtime';
3
4
// This is a translation of the original merge-consecutive-scopes which uses plain objects
5
// to describe the UI instead of JSX. The JSXText elements in that fixture happen to
@@ -8,14 +8,14 @@ import { Stringify } from "shared-runtime";
8
function Component(props) {
9
let [state, setState] = useState(0);
10
return [
11
- { component: Stringify, props: { text: "Counter" } },
12
- { component: "span", props: { children: [state] } },
11
+ {component: Stringify, props: {text: 'Counter'}},
12
+ {component: 'span', props: {children: [state]}},
13
{
14
- component: "button",
14
+ component: 'button',
15
props: {
16
- "data-testid": "button",
16
+ 'data-testid': 'button',
17
onClick: () => setState(state + 1),
18
- children: ["increment"],
18
+ children: ['increment'],
19
},
20
},
21
];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-consecutive-scopes-reordering.expect.md
+3
-3
@@ -3,8 +3,8 @@
3
4
```javascript
5
// @enableInstructionReordering
6
-import { useState } from "react";
7
-import { Stringify } from "shared-runtime";
6
+import {useState} from 'react';
7
+import {Stringify} from 'shared-runtime';
8
9
function Component() {
10
let [state, setState] = useState(0);
@@ -21,7 +21,7 @@ function Component() {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
- params: [{ value: 42 }],
24
+ params: [{value: 42}],
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-consecutive-scopes-reordering.js
+3
-3
@@ -1,6 +1,6 @@
1
// @enableInstructionReordering
2
-import { useState } from "react";
3
-import { Stringify } from "shared-runtime";
2
+import {useState} from 'react';
3
+import {Stringify} from 'shared-runtime';
4
5
function Component() {
6
let [state, setState] = useState(0);
@@ -17,5 +17,5 @@ function Component() {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ value: 42 }],
20
+ params: [{value: 42}],
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-consecutive-scopes.expect.md
+3
-3
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import { useState } from "react";
6
-import { Stringify } from "shared-runtime";
5
+import {useState} from 'react';
6
+import {Stringify} from 'shared-runtime';
7
8
function Component() {
9
let [state, setState] = useState(0);
@@ -20,7 +20,7 @@ function Component() {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
- params: [{ value: 42 }],
23
+ params: [{value: 42}],
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-consecutive-scopes.js
+3
-3
@@ -1,5 +1,5 @@
1
-import { useState } from "react";
2
-import { Stringify } from "shared-runtime";
1
+import {useState} from 'react';
2
+import {Stringify} from 'shared-runtime';
3
4
function Component() {
5
let [state, setState] = useState(0);
@@ -16,5 +16,5 @@ function Component() {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ value: 42 }],
19
+ params: [{value: 42}],
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-nested-scopes-with-same-inputs.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { setProperty } from "shared-runtime";
5
+import {setProperty} from 'shared-runtime';
6
7
function Component(props) {
8
// start of scope for y, depend on props.a
@@ -22,7 +22,7 @@ function Component(props) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
25
- params: [{ a: 42 }],
25
+ params: [{a: 42}],
26
};
27
28
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-nested-scopes-with-same-inputs.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { setProperty } from "shared-runtime";
1
+import {setProperty} from 'shared-runtime';
2
3
function Component(props) {
4
// start of scope for y, depend on props.a
@@ -18,5 +18,5 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ a: 42 }],
21
+ params: [{a: 42}],
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-scopes-callback.expect.md
+2
-2
@@ -3,12 +3,12 @@
3
4
```javascript
5
// @enableInstructionReordering
6
-import { useState } from "react";
6
+import {useState} from 'react';
7
8
function Component() {
9
const [state, setState] = useState(0);
10
const onClick = () => {
11
- setState((s) => s + 1);
11
+ setState(s => s + 1);
12
};
13
return (
14
<>
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merge-scopes-callback.js
+2
-2
@@ -1,10 +1,10 @@
1
// @enableInstructionReordering
2
-import { useState } from "react";
2
+import {useState} from 'react';
3
4
function Component() {
5
const [state, setState] = useState(0);
6
const onClick = () => {
7
- setState((s) => s + 1);
7
+ setState(s => s + 1);
8
};
9
return (
10
<>
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merged-scopes-are-valid-effect-deps.expect.md
+2
-2
@@ -4,7 +4,7 @@
4
```javascript
5
// @validateMemoizedEffectDependencies
6
7
-import { useEffect } from "react";
7
+import {useEffect} from 'react';
8
9
function Component(props) {
10
const y = [[props.value]]; // merged w scope for inner array
@@ -18,7 +18,7 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ value: 42 }],
21
+ params: [{value: 42}],
22
isComponent: false,
23
};
24
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/merged-scopes-are-valid-effect-deps.js
+2
-2
@@ -1,6 +1,6 @@
1
// @validateMemoizedEffectDependencies
2
3
-import { useEffect } from "react";
3
+import {useEffect} from 'react';
4
5
function Component(props) {
6
const y = [[props.value]]; // merged w scope for inner array
@@ -14,6 +14,6 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ value: 42 }],
17
+ params: [{value: 42}],
18
isComponent: false,
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/meta-isms/repro-cx-assigned-to-temporary.expect.md
+5
-5
@@ -3,17 +3,17 @@
3
4
```javascript
5
// @compilationMode(infer) @enableAssumeHooksFollowRulesOfReact:false @customMacros(cx)
6
-import { identity } from "shared-runtime";
6
+import {identity} from 'shared-runtime';
7
8
-const DARK = "dark";
8
+const DARK = 'dark';
9
10
function Component() {
11
const theme = useTheme();
12
return (
13
<div
14
className={cx({
15
- "styles/light": true,
16
- "styles/dark": theme.getTheme() === DARK,
15
+ 'styles/light': true,
16
+ 'styles/dark': theme.getTheme() === DARK,
17
})}
18
/>
19
);
@@ -26,7 +26,7 @@ function cx(obj) {
26
classes.push(key);
27
}
28
}
29
- return classes.join(" ");
29
+ return classes.join(' ');
30
}
31
32
function useTheme() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/meta-isms/repro-cx-assigned-to-temporary.js
+5
-5
@@ -1,15 +1,15 @@
1
// @compilationMode(infer) @enableAssumeHooksFollowRulesOfReact:false @customMacros(cx)
2
-import { identity } from "shared-runtime";
2
+import {identity} from 'shared-runtime';
3
4
-const DARK = "dark";
4
+const DARK = 'dark';
5
6
function Component() {
7
const theme = useTheme();
8
return (
9
<div
10
className={cx({
11
- "styles/light": true,
12
- "styles/dark": theme.getTheme() === DARK,
11
+ 'styles/light': true,
12
+ 'styles/dark': theme.getTheme() === DARK,
13
})}
14
/>
15
);
@@ -22,7 +22,7 @@ function cx(obj) {
22
classes.push(key);
23
}
24
}
25
- return classes.join(" ");
25
+ return classes.join(' ');
26
}
27
28
function useTheme() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/meta-isms/repro-cx-namespace-assigned-to-temporary.expect.md
+5
-5
@@ -3,17 +3,17 @@
3
4
```javascript
5
// @compilationMode(infer) @enableAssumeHooksFollowRulesOfReact:false @customMacros(cx)
6
-import { identity } from "shared-runtime";
6
+import {identity} from 'shared-runtime';
7
8
-const DARK = "dark";
8
+const DARK = 'dark';
9
10
function Component() {
11
const theme = useTheme();
12
return (
13
<div
14
className={cx.foo({
15
- "styles/light": true,
16
- "styles/dark": identity([theme.getTheme()]),
15
+ 'styles/light': true,
16
+ 'styles/dark': identity([theme.getTheme()]),
17
})}
18
/>
19
);
@@ -26,7 +26,7 @@ function cx(obj) {
26
classes.push(key);
27
}
28
}
29
- return classes.join(" ");
29
+ return classes.join(' ');
30
}
31
32
function useTheme() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/meta-isms/repro-cx-namespace-assigned-to-temporary.js
+5
-5
@@ -1,15 +1,15 @@
1
// @compilationMode(infer) @enableAssumeHooksFollowRulesOfReact:false @customMacros(cx)
2
-import { identity } from "shared-runtime";
2
+import {identity} from 'shared-runtime';
3
4
-const DARK = "dark";
4
+const DARK = 'dark';
5
6
function Component() {
7
const theme = useTheme();
8
return (
9
<div
10
className={cx.foo({
11
- "styles/light": true,
12
- "styles/dark": identity([theme.getTheme()]),
11
+ 'styles/light': true,
12
+ 'styles/dark': identity([theme.getTheme()]),
13
})}
14
/>
15
);
@@ -22,7 +22,7 @@ function cx(obj) {
22
classes.push(key);
23
}
24
}
25
- return classes.join(" ");
25
+ return classes.join(' ');
26
}
27
28
function useTheme() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/meta-isms/repro-cx-namespace-nesting.expect.md
+4
-4
@@ -2,21 +2,21 @@
2
## Input
3
4
```javascript
5
-import { makeArray } from "shared-runtime";
5
+import {makeArray} from 'shared-runtime';
6
7
function Component() {
8
- const items = makeArray("foo", "bar", "", null, "baz", false, "merp");
8
+ const items = makeArray('foo', 'bar', '', null, 'baz', false, 'merp');
9
const classname = cx.namespace(...items.filter(isNonEmptyString));
10
return <div className={classname}>Ok</div>;
11
}
12
13
function isNonEmptyString(s) {
14
- return typeof s === "string" && s.trim().length !== 0;
14
+ return typeof s === 'string' && s.trim().length !== 0;
15
}
16
17
const cx = {
18
namespace(...items) {
19
- return items.join(" ");
19
+ return items.join(' ');
20
},
21
};
22
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/meta-isms/repro-cx-namespace-nesting.js
+4
-4
@@ -1,18 +1,18 @@
1
-import { makeArray } from "shared-runtime";
1
+import {makeArray} from 'shared-runtime';
2
3
function Component() {
4
- const items = makeArray("foo", "bar", "", null, "baz", false, "merp");
4
+ const items = makeArray('foo', 'bar', '', null, 'baz', false, 'merp');
5
const classname = cx.namespace(...items.filter(isNonEmptyString));
6
return <div className={classname}>Ok</div>;
7
}
8
9
function isNonEmptyString(s) {
10
- return typeof s === "string" && s.trim().length !== 0;
10
+ return typeof s === 'string' && s.trim().length !== 0;
11
}
12
13
const cx = {
14
namespace(...items) {
15
- return items.join(" ");
15
+ return items.join(' ');
16
},
17
};
18
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/method-call.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { addOne, shallowCopy } from "shared-runtime";
5
+import {addOne, shallowCopy} from 'shared-runtime';
6
7
function foo(a, b, c) {
8
// Construct and freeze x
@@ -16,7 +16,7 @@ function foo(a, b, c) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: foo,
19
- params: [{ foo: addOne }, 3],
19
+ params: [{foo: addOne}, 3],
20
isComponent: false,
21
};
22
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/method-call.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { addOne, shallowCopy } from "shared-runtime";
1
+import {addOne, shallowCopy} from 'shared-runtime';
2
3
function foo(a, b, c) {
4
// Construct and freeze x
@@ -12,6 +12,6 @@ function foo(a, b, c) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: foo,
15
- params: [{ foo: addOne }, 3],
15
+ params: [{foo: addOne}, 3],
16
isComponent: false,
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/module-scoped-bindings.expect.md
+2
-2
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import React from "react";
6
-import { useState } from "react";
5
+import React from 'react';
6
+import {useState} from 'react';
7
8
const CONST = true;
9
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/module-scoped-bindings.js
+2
-2
@@ -1,5 +1,5 @@
1
-import React from "react";
2
-import { useState } from "react";
1
+import React from 'react';
2
+import {useState} from 'react';
3
4
const CONST = true;
5
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/multi-arrow-expr-export-default-gating-test.expect.md
+1
-1
@@ -5,7 +5,7 @@
5
// @gating
6
const ErrorView = (error, _retry) => <MessageBox error={error}></MessageBox>;
7
8
-export default Renderer = (props) => (
8
+export default Renderer = props => (
9
<Foo>
10
<Bar></Bar>
11
<ErrorView></ErrorView>
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/multi-arrow-expr-export-default-gating-test.js
+1
-1
@@ -1,7 +1,7 @@
1
// @gating
2
const ErrorView = (error, _retry) => <MessageBox error={error}></MessageBox>;
3
4
-export default Renderer = (props) => (
4
+export default Renderer = props => (
5
<Foo>
6
<Bar></Bar>
7
<ErrorView></ErrorView>
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/multi-arrow-expr-export-gating-test.expect.md
+1
-1
@@ -5,7 +5,7 @@
5
// @gating
6
const ErrorView = (error, _retry) => <MessageBox error={error}></MessageBox>;
7
8
-export const Renderer = (props) => (
8
+export const Renderer = props => (
9
<Foo>
10
<Bar></Bar>
11
<ErrorView></ErrorView>
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/multi-arrow-expr-export-gating-test.js
+1
-1
@@ -1,7 +1,7 @@
1
// @gating
2
const ErrorView = (error, _retry) => <MessageBox error={error}></MessageBox>;
3
4
-export const Renderer = (props) => (
4
+export const Renderer = props => (
5
<Foo>
6
<Bar></Bar>
7
<ErrorView></ErrorView>
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/multi-arrow-expr-gating-test.expect.md
+1
-1
@@ -5,7 +5,7 @@
5
// @gating
6
const ErrorView = (error, _retry) => <MessageBox error={error}></MessageBox>;
7
8
-const Renderer = (props) => (
8
+const Renderer = props => (
9
<Foo>
10
<Bar></Bar>
11
<ErrorView></ErrorView>
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/multi-arrow-expr-gating-test.js
+1
-1
@@ -1,7 +1,7 @@
1
// @gating
2
const ErrorView = (error, _retry) => <MessageBox error={error}></MessageBox>;
3
4
-const Renderer = (props) => (
4
+const Renderer = props => (
5
<Foo>
6
<Bar></Bar>
7
<ErrorView></ErrorView>
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/multi-directive.expect.md
+2
-2
@@ -3,8 +3,8 @@
3
4
```javascript
5
function Component() {
6
- "use foo";
7
- "use bar";
6
+ 'use foo';
7
+ 'use bar';
8
return <div>"foo"</div>;
9
}
10
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/multi-directive.js
+2
-2
@@ -1,6 +1,6 @@
1
function Component() {
2
- "use foo";
3
- "use bar";
2
+ 'use foo';
3
+ 'use bar';
4
return <div>"foo"</div>;
5
}
6
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/multiple-calls-to-hoisted-callback-from-other-callback.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useState } from "react";
5
+import {useState} from 'react';
6
7
function Component(props) {
8
const [_state, setState] = useState();
@@ -17,7 +17,7 @@ function Component(props) {
17
</>
18
);
19
};
20
- const onClick = (value) => {
20
+ const onClick = value => {
21
setState(value);
22
};
23
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/multiple-calls-to-hoisted-callback-from-other-callback.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { useState } from "react";
1
+import {useState} from 'react';
2
3
function Component(props) {
4
const [_state, setState] = useState();
@@ -13,7 +13,7 @@ function Component(props) {
13
</>
14
);
15
};
16
- const onClick = (value) => {
16
+ const onClick = value => {
17
setState(value);
18
};
19
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutable-lifetime-loops.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function mutate(x, y) {
6
- "use no forget";
6
+ 'use no forget';
7
if (x != null) {
8
x.value = (x.value ?? 0) + 1;
9
}
@@ -12,7 +12,7 @@ function mutate(x, y) {
12
}
13
}
14
function cond(x) {
15
- "use no forget";
15
+ 'use no forget';
16
return x.value > 5;
17
}
18
@@ -46,7 +46,7 @@ function testFunction(props) {
46
}
47
48
mutate(d, null);
49
- return { a, b, c, d };
49
+ return {a, b, c, d};
50
}
51
52
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutable-lifetime-loops.js
+3
-3
@@ -1,5 +1,5 @@
1
function mutate(x, y) {
2
- "use no forget";
2
+ 'use no forget';
3
if (x != null) {
4
x.value = (x.value ?? 0) + 1;
5
}
@@ -8,7 +8,7 @@ function mutate(x, y) {
8
}
9
}
10
function cond(x) {
11
- "use no forget";
11
+ 'use no forget';
12
return x.value > 5;
13
}
14
@@ -42,7 +42,7 @@ function testFunction(props) {
42
}
43
44
mutate(d, null);
45
- return { a, b, c, d };
45
+ return {a, b, c, d};
46
}
47
48
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutable-lifetime-with-aliasing.expect.md
+2
-2
@@ -3,7 +3,7 @@
3
4
```javascript
5
function mutate(x, y) {
6
- "use no forget";
6
+ 'use no forget';
7
if (!Array.isArray(x.value)) {
8
x.value = [];
9
}
@@ -17,7 +17,7 @@ function Component(props) {
17
const a = {};
18
const b = [a]; // array elements alias
19
const c = {};
20
- const d = { c }; // object values alias
20
+ const d = {c}; // object values alias
21
22
// capture all the values into this object
23
const x = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutable-lifetime-with-aliasing.js
+2
-2
@@ -1,5 +1,5 @@
1
function mutate(x, y) {
2
- "use no forget";
2
+ 'use no forget';
3
if (!Array.isArray(x.value)) {
4
x.value = [];
5
}
@@ -13,7 +13,7 @@ function Component(props) {
13
const a = {};
14
const b = [a]; // array elements alias
15
const c = {};
16
- const d = { c }; // object values alias
16
+ const d = {c}; // object values alias
17
18
// capture all the values into this object
19
const x = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutate-outer-scope-within-value-block.expect.md
+4
-4
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { CONST_TRUE, identity, shallowCopy } from "shared-runtime";
5
+import {CONST_TRUE, identity, shallowCopy} from 'shared-runtime';
6
7
/**
8
* There are three values with their own scopes in this fixture.
@@ -25,16 +25,16 @@ import { CONST_TRUE, identity, shallowCopy } from "shared-runtime";
25
* Observe that instruction 5 mutates scope 0, which means that scopes 0 and 2
26
* should be merged.
27
*/
28
-function useFoo({ input }) {
28
+function useFoo({input}) {
29
const arr = shallowCopy(input);
30
31
const cond = identity(false);
32
- return cond ? { val: CONST_TRUE } : mutate(arr);
32
+ return cond ? {val: CONST_TRUE} : mutate(arr);
33
}
34
35
export const FIXTURE_ENTRYPOINT = {
36
fn: useFoo,
37
- params: [{ input: 3 }],
37
+ params: [{input: 3}],
38
};
39
40
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutate-outer-scope-within-value-block.ts
+4
-4
@@ -1,4 +1,4 @@
1
-import { CONST_TRUE, identity, shallowCopy } from "shared-runtime";
1
+import {CONST_TRUE, identity, shallowCopy} from 'shared-runtime';
2
3
/**
4
* There are three values with their own scopes in this fixture.
@@ -21,14 +21,14 @@ import { CONST_TRUE, identity, shallowCopy } from "shared-runtime";
21
* Observe that instruction 5 mutates scope 0, which means that scopes 0 and 2
22
* should be merged.
23
*/
24
-function useFoo({ input }) {
24
+function useFoo({input}) {
25
const arr = shallowCopy(input);
26
27
const cond = identity(false);
28
- return cond ? { val: CONST_TRUE } : mutate(arr);
28
+ return cond ? {val: CONST_TRUE} : mutate(arr);
29
}
30
31
export const FIXTURE_ENTRYPOINT = {
32
fn: useFoo,
33
- params: [{ input: 3 }],
33
+ params: [{input: 3}],
34
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutation-during-jsx-construction.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity, mutate, mutateAndReturnNewValue } from "shared-runtime";
5
+import {identity, mutate, mutateAndReturnNewValue} from 'shared-runtime';
6
7
function Component(props) {
8
const key = {};
@@ -16,7 +16,7 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ value: 42 }],
19
+ params: [{value: 42}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutation-during-jsx-construction.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { identity, mutate, mutateAndReturnNewValue } from "shared-runtime";
1
+import {identity, mutate, mutateAndReturnNewValue} from 'shared-runtime';
2
3
function Component(props) {
4
const key = {};
@@ -12,5 +12,5 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ value: 42 }],
15
+ params: [{value: 42}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutation-within-capture-and-mutablerange.expect.md
+4
-4
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { mutate } from "shared-runtime";
5
+import {mutate} from 'shared-runtime';
6
7
/**
8
* This test fixture is similar to mutation-within-jsx. The only difference
@@ -14,9 +14,9 @@ import { mutate } from "shared-runtime";
14
* memo blocks (which may lead to 'tearing', i.e. mutating one render's
15
* values in a subsequent render.
16
*/
17
-function useFoo({ a, b }) {
17
+function useFoo({a, b}) {
18
// x and y's scopes start here
19
- const x = { a };
19
+ const x = {a};
20
const y = [b];
21
mutate(x);
22
// z captures the result of `mutate(y)`, which may be aliased to `y`.
@@ -29,7 +29,7 @@ function useFoo({ a, b }) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: useFoo,
32
- params: [{ a: 2, b: 3 }],
32
+ params: [{a: 2, b: 3}],
33
};
34
35
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutation-within-capture-and-mutablerange.tsx
+4
-4
@@ -1,4 +1,4 @@
1
-import { mutate } from "shared-runtime";
1
+import {mutate} from 'shared-runtime';
2
3
/**
4
* This test fixture is similar to mutation-within-jsx. The only difference
@@ -10,9 +10,9 @@ import { mutate } from "shared-runtime";
10
* memo blocks (which may lead to 'tearing', i.e. mutating one render's
11
* values in a subsequent render.
12
*/
13
-function useFoo({ a, b }) {
13
+function useFoo({a, b}) {
14
// x and y's scopes start here
15
- const x = { a };
15
+ const x = {a};
16
const y = [b];
17
mutate(x);
18
// z captures the result of `mutate(y)`, which may be aliased to `y`.
@@ -25,5 +25,5 @@ function useFoo({ a, b }) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: useFoo,
28
- params: [{ a: 2, b: 3 }],
28
+ params: [{a: 2, b: 3}],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutation-within-jsx-and-break.expect.md
+5
-5
@@ -7,9 +7,9 @@ import {
7
makeObject_Primitives,
8
mutate,
9
mutateAndReturn,
10
-} from "shared-runtime";
10
+} from 'shared-runtime';
11
12
-function useFoo({ data }) {
12
+function useFoo({data}) {
13
let obj = null;
14
let myDiv = null;
15
label: {
@@ -28,10 +28,10 @@ function useFoo({ data }) {
28
29
export const FIXTURE_ENTRYPOINT = {
30
fn: useFoo,
31
- params: [{ data: { cond: true, cond1: true } }],
31
+ params: [{data: {cond: true, cond1: true}}],
32
sequentialRenders: [
33
- { data: { cond: true, cond1: true } },
34
- { data: { cond: true, cond1: true } },
33
+ {data: {cond: true, cond1: true}},
34
+ {data: {cond: true, cond1: true}},
35
],
36
};
37
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutation-within-jsx-and-break.tsx
+5
-5
@@ -3,9 +3,9 @@ import {
3
makeObject_Primitives,
4
mutate,
5
mutateAndReturn,
6
-} from "shared-runtime";
6
+} from 'shared-runtime';
7
8
-function useFoo({ data }) {
8
+function useFoo({data}) {
9
let obj = null;
10
let myDiv = null;
11
label: {
@@ -24,9 +24,9 @@ function useFoo({ data }) {
24
25
export const FIXTURE_ENTRYPOINT = {
26
fn: useFoo,
27
- params: [{ data: { cond: true, cond1: true } }],
27
+ params: [{data: {cond: true, cond1: true}}],
28
sequentialRenders: [
29
- { data: { cond: true, cond1: true } },
30
- { data: { cond: true, cond1: true } },
29
+ {data: {cond: true, cond1: true}},
30
+ {data: {cond: true, cond1: true}},
31
],
32
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutation-within-jsx.expect.md
+5
-5
@@ -6,7 +6,7 @@ import {
6
Stringify,
7
makeObject_Primitives,
8
mutateAndReturn,
9
-} from "shared-runtime";
9
+} from 'shared-runtime';
10
11
/**
12
* In this example, the `<Stringify ... />` JSX block mutates then captures obj.
@@ -34,7 +34,7 @@ import {
34
* a result, developers can never observe myDiv can aliasing a different value generation
35
* than `obj` (e.g. the invariant `myDiv.props.value === obj` always holds).
36
*/
37
-function useFoo({ data }) {
37
+function useFoo({data}) {
38
let obj = null;
39
let myDiv = null;
40
if (data.cond) {
@@ -48,10 +48,10 @@ function useFoo({ data }) {
48
49
export const FIXTURE_ENTRYPOINT = {
50
fn: useFoo,
51
- params: [{ data: { cond: true, cond1: true } }],
51
+ params: [{data: {cond: true, cond1: true}}],
52
sequentialRenders: [
53
- { data: { cond: true, cond1: true } },
54
- { data: { cond: true, cond1: true } },
53
+ {data: {cond: true, cond1: true}},
54
+ {data: {cond: true, cond1: true}},
55
],
56
};
57
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/mutation-within-jsx.tsx
+5
-5
@@ -2,7 +2,7 @@ import {
2
Stringify,
3
makeObject_Primitives,
4
mutateAndReturn,
5
-} from "shared-runtime";
5
+} from 'shared-runtime';
6
7
/**
8
* In this example, the `<Stringify ... />` JSX block mutates then captures obj.
@@ -30,7 +30,7 @@ import {
30
* a result, developers can never observe myDiv can aliasing a different value generation
31
* than `obj` (e.g. the invariant `myDiv.props.value === obj` always holds).
32
*/
33
-function useFoo({ data }) {
33
+function useFoo({data}) {
34
let obj = null;
35
let myDiv = null;
36
if (data.cond) {
@@ -44,9 +44,9 @@ function useFoo({ data }) {
44
45
export const FIXTURE_ENTRYPOINT = {
46
fn: useFoo,
47
- params: [{ data: { cond: true, cond1: true } }],
47
+ params: [{data: {cond: true, cond1: true}}],
48
sequentialRenders: [
49
- { data: { cond: true, cond1: true } },
50
- { data: { cond: true, cond1: true } },
49
+ {data: {cond: true, cond1: true}},
50
+ {data: {cond: true, cond1: true}},
51
],
52
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/nested-function-shadowed-identifiers.expect.md
+4
-4
@@ -5,9 +5,9 @@
5
function Component(props) {
6
const [x, setX] = useState(null);
7
8
- const onChange = (e) => {
8
+ const onChange = e => {
9
let x = null; // intentionally shadow the original x
10
- setX((currentX) => currentX + x); // intentionally refer to shadowed x
10
+ setX(currentX => currentX + x); // intentionally refer to shadowed x
11
};
12
13
return <input value={x} onChange={onChange} />;
@@ -15,8 +15,8 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/nested-function-shadowed-identifiers.js
+4
-4
@@ -1,9 +1,9 @@
1
function Component(props) {
2
const [x, setX] = useState(null);
3
4
- const onChange = (e) => {
4
+ const onChange = e => {
5
let x = null; // intentionally shadow the original x
6
- setX((currentX) => currentX + x); // intentionally refer to shadowed x
6
+ setX(currentX => currentX + x); // intentionally refer to shadowed x
7
};
8
9
return <input value={x} onChange={onChange} />;
@@ -11,6 +11,6 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/nested-scopes-begin-same-instr-valueblock.expect.md
+5
-10
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { identity, mutate } from "shared-runtime";
5
+import {identity, mutate} from 'shared-runtime';
6
7
-function Foo({ cond }) {
8
- const x = identity(identity(cond)) ? { a: 2 } : { b: 2 };
7
+function Foo({cond}) {
8
+ const x = identity(identity(cond)) ? {a: 2} : {b: 2};
9
10
mutate(x);
11
return x;
@@ -13,13 +13,8 @@ function Foo({ cond }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Foo,
16
- params: [{ cond: false }],
17
- sequentialRenders: [
18
- { cond: false },
19
- { cond: false },
20
- { cond: true },
21
- { cond: true },
22
- ],
16
+ params: [{cond: false}],
17
+ sequentialRenders: [{cond: false}, {cond: false}, {cond: true}, {cond: true}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/nested-scopes-begin-same-instr-valueblock.ts
+5
-10
@@ -1,7 +1,7 @@
1
-import { identity, mutate } from "shared-runtime";
1
+import {identity, mutate} from 'shared-runtime';
2
3
-function Foo({ cond }) {
4
- const x = identity(identity(cond)) ? { a: 2 } : { b: 2 };
3
+function Foo({cond}) {
4
+ const x = identity(identity(cond)) ? {a: 2} : {b: 2};
5
6
mutate(x);
7
return x;
@@ -9,11 +9,6 @@ function Foo({ cond }) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Foo,
12
- params: [{ cond: false }],
13
- sequentialRenders: [
14
- { cond: false },
15
- { cond: false },
16
- { cond: true },
17
- { cond: true },
18
- ],
12
+ params: [{cond: false}],
13
+ sequentialRenders: [{cond: false}, {cond: false}, {cond: true}, {cond: true}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/new-does-not-mutate-class.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
class Foo {}
8
-function Component({ val }) {
8
+function Component({val}) {
9
const MyClass = identity(Foo);
10
const x = [val];
11
const y = new MyClass();
@@ -15,7 +15,7 @@ function Component({ val }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ val: 0 }],
18
+ params: [{val: 0}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/new-does-not-mutate-class.ts
+3
-3
@@ -1,7 +1,7 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
class Foo {}
4
-function Component({ val }) {
4
+function Component({val}) {
5
const MyClass = identity(Foo);
6
const x = [val];
7
const y = new MyClass();
@@ -11,5 +11,5 @@ function Component({ val }) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ val: 0 }],
14
+ params: [{val: 0}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/noAlias-filter-on-array-prop.expect.md
+2
-12
@@ -3,7 +3,7 @@
3
4
```javascript
5
function Component(props) {
6
- const filtered = props.items.filter((item) => item != null);
6
+ const filtered = props.items.filter(item => item != null);
7
return filtered;
8
}
9
@@ -11,17 +11,7 @@ export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
params: [
13
{
14
- items: [
15
- { a: true },
16
- null,
17
- true,
18
- false,
19
- null,
20
- "string",
21
- 3.14,
22
- null,
23
- [null],
24
- ],
14
+ items: [{a: true}, null, true, false, null, 'string', 3.14, null, [null]],
15
},
16
],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/noAlias-filter-on-array-prop.js
+2
-12
@@ -1,5 +1,5 @@
1
function Component(props) {
2
- const filtered = props.items.filter((item) => item != null);
2
+ const filtered = props.items.filter(item => item != null);
3
return filtered;
4
}
5
@@ -7,17 +7,7 @@ export const FIXTURE_ENTRYPOINT = {
7
fn: Component,
8
params: [
9
{
10
- items: [
11
- { a: true },
12
- null,
13
- true,
14
- false,
15
- null,
16
- "string",
17
- 3.14,
18
- null,
19
- [null],
20
- ],
10
+ items: [{a: true}, null, true, false, null, 'string', 3.14, null, [null]],
11
},
12
],
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/non-null-assertion.expect.md
+1
-1
@@ -12,7 +12,7 @@ function Component(props: ComponentProps) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ name: "Alice" }],
15
+ params: [{name: 'Alice'}],
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/non-null-assertion.ts
+1
-1
@@ -8,5 +8,5 @@ function Component(props: ComponentProps) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: [{ name: "Alice" }],
11
+ params: [{name: 'Alice'}],
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/nonmutating-capture-in-unsplittable-memo-block.expect.md
+7
-7
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity, mutate } from "shared-runtime";
5
+import {identity, mutate} from 'shared-runtime';
6
7
/**
8
* Currently, InferReactiveScopeVariables do not ensure that maybe-aliased
@@ -22,25 +22,25 @@ import { identity, mutate } from "shared-runtime";
22
* that all aliases refer to the same value.
23
*
24
*/
25
-function useFoo({ a, b }) {
26
- const x = { a };
25
+function useFoo({a, b}) {
26
+ const x = {a};
27
const y = {};
28
mutate(x);
29
const z = [identity(y), b];
30
mutate(y);
31
32
if (z[0] !== y) {
33
- throw new Error("oh no!");
33
+ throw new Error('oh no!');
34
}
35
return z;
36
}
37
38
export const FIXTURE_ENTRYPOINT = {
39
fn: useFoo,
40
- params: [{ a: 2, b: 3 }],
40
+ params: [{a: 2, b: 3}],
41
sequentialRenders: [
42
- { a: 2, b: 3 },
43
- { a: 4, b: 3 },
42
+ {a: 2, b: 3},
43
+ {a: 4, b: 3},
44
],
45
};
46
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/nonmutating-capture-in-unsplittable-memo-block.ts
+7
-7
@@ -1,4 +1,4 @@
1
-import { identity, mutate } from "shared-runtime";
1
+import {identity, mutate} from 'shared-runtime';
2
3
/**
4
* Currently, InferReactiveScopeVariables do not ensure that maybe-aliased
@@ -18,24 +18,24 @@ import { identity, mutate } from "shared-runtime";
18
* that all aliases refer to the same value.
19
*
20
*/
21
-function useFoo({ a, b }) {
22
- const x = { a };
21
+function useFoo({a, b}) {
22
+ const x = {a};
23
const y = {};
24
mutate(x);
25
const z = [identity(y), b];
26
mutate(y);
27
28
if (z[0] !== y) {
29
- throw new Error("oh no!");
29
+ throw new Error('oh no!');
30
}
31
return z;
32
}
33
34
export const FIXTURE_ENTRYPOINT = {
35
fn: useFoo,
36
- params: [{ a: 2, b: 3 }],
36
+ params: [{a: 2, b: 3}],
37
sequentialRenders: [
38
- { a: 2, b: 3 },
39
- { a: 4, b: 3 },
38
+ {a: 2, b: 3},
39
+ {a: 4, b: 3},
40
],
41
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/nonoptional-load-from-optional-memberexpr.expect.md
+2
-2
@@ -13,8 +13,8 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/nonoptional-load-from-optional-memberexpr.js
+2
-2
@@ -9,6 +9,6 @@ function Component(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/nonreactive-noescaping-dependency-can-inline-into-consuming-scope.expect.md
+2
-3
@@ -10,9 +10,8 @@ function Component() {
10
// this value is a) in its own scope, b) non-reactive, and c) non-escaping
11
// its scope gets pruned bc it's non-escaping, but this doesn't mean we need to
12
// create a temporary for it
13
- flags.feature("feature-name") ? styles.featureNameStyle : null
14
- )}
15
- ></div>
13
+ flags.feature('feature-name') ? styles.featureNameStyle : null
14
+ )}></div>
15
);
16
}
17
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/nonreactive-noescaping-dependency-can-inline-into-consuming-scope.js
+2
-3
@@ -6,8 +6,7 @@ function Component() {
6
// this value is a) in its own scope, b) non-reactive, and c) non-escaping
7
// its scope gets pruned bc it's non-escaping, but this doesn't mean we need to
8
// create a temporary for it
9
- flags.feature("feature-name") ? styles.featureNameStyle : null
10
- )}
11
- ></div>
9
+ flags.feature('feature-name') ? styles.featureNameStyle : null
10
+ )}></div>
11
);
12
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/obj-literal-cached-in-if-else.expect.md
+2
-2
@@ -5,9 +5,9 @@
5
function foo(a, b, c, d) {
6
let x = {};
7
if (someVal) {
8
- x = { b };
8
+ x = {b};
9
} else {
10
- x = { c };
10
+ x = {c};
11
}
12
13
return x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/obj-literal-cached-in-if-else.js
+2
-2
@@ -1,9 +1,9 @@
1
function foo(a, b, c, d) {
2
let x = {};
3
if (someVal) {
4
- x = { b };
4
+ x = {b};
5
} else {
6
- x = { c };
6
+ x = {c};
7
}
8
9
return x;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/obj-literal-mutated-after-if-else.expect.md
+2
-2
@@ -5,9 +5,9 @@
5
function foo(a, b, c, d) {
6
let x = {};
7
if (someVal) {
8
- x = { b };
8
+ x = {b};
9
} else {
10
- x = { c };
10
+ x = {c};
11
}
12
13
x.f = 1;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/obj-literal-mutated-after-if-else.js
+2
-2
@@ -1,9 +1,9 @@
1
function foo(a, b, c, d) {
2
let x = {};
3
if (someVal) {
4
- x = { b };
4
+ x = {b};
5
} else {
6
- x = { c };
6
+ x = {c};
7
}
8
9
x.f = 1;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-computed-access-assignment.expect.md
+3
-3
@@ -3,15 +3,15 @@
3
4
```javascript
5
function foo(a, b, c) {
6
- const x = { ...a };
6
+ const x = {...a};
7
x[b] = c[b];
8
x[1 + 2] = c[b * 4];
9
}
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: foo,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-computed-access-assignment.js
+3
-3
@@ -1,11 +1,11 @@
1
function foo(a, b, c) {
2
- const x = { ...a };
2
+ const x = {...a};
3
x[b] = c[b];
4
x[1 + 2] = c[b * 4];
5
}
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: foo,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-expression-computed-key-constant-number.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
function Component(props) {
8
const key = 42;
@@ -14,7 +14,7 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ value: "hello!" }],
17
+ params: [{value: 'hello!'}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-expression-computed-key-constant-number.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
function Component(props) {
4
const key = 42;
@@ -10,5 +10,5 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ value: "hello!" }],
13
+ params: [{value: 'hello!'}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-expression-computed-key-constant-string.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
function Component(props) {
8
- const key = "KeyName";
8
+ const key = 'KeyName';
9
const context = {
10
[key]: identity([props.value]),
11
};
@@ -14,7 +14,7 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ value: 42 }],
17
+ params: [{value: 42}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-expression-computed-key-constant-string.js
+3
-3
@@ -1,7 +1,7 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
function Component(props) {
4
- const key = "KeyName";
4
+ const key = 'KeyName';
5
const context = {
6
[key]: identity([props.value]),
7
};
@@ -10,5 +10,5 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ value: 42 }],
13
+ params: [{value: 42}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-expression-computed-key-non-reactive.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
const SCALE = 2;
8
@@ -16,7 +16,7 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ key: "Sathya", value: "Compiler" }],
19
+ params: [{key: 'Sathya', value: 'Compiler'}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-expression-computed-key-non-reactive.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
const SCALE = 2;
4
@@ -12,5 +12,5 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ key: "Sathya", value: "Compiler" }],
15
+ params: [{key: 'Sathya', value: 'Compiler'}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-expression-computed-key-object-mutated-later.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity, mutate } from "shared-runtime";
5
+import {identity, mutate} from 'shared-runtime';
6
7
function Component(props) {
8
const key = {};
@@ -15,7 +15,7 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ value: 42 }],
18
+ params: [{value: 42}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-expression-computed-key-object-mutated-later.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { identity, mutate } from "shared-runtime";
1
+import {identity, mutate} from 'shared-runtime';
2
3
function Component(props) {
4
const key = {};
@@ -11,5 +11,5 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ value: 42 }],
14
+ params: [{value: 42}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-expression-computed-key.expect.md
+3
-3
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
const SCALE = 2;
8
9
function Component(props) {
10
- const { key } = props;
10
+ const {key} = props;
11
const context = {
12
[key]: identity([props.value, SCALE]),
13
};
@@ -16,7 +16,7 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ key: "Sathya", value: "Compiler" }],
19
+ params: [{key: 'Sathya', value: 'Compiler'}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-expression-computed-key.js
+3
-3
@@ -1,9 +1,9 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
const SCALE = 2;
4
5
function Component(props) {
6
- const { key } = props;
6
+ const {key} = props;
7
const context = {
8
[key]: identity([props.value, SCALE]),
9
};
@@ -12,5 +12,5 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ key: "Sathya", value: "Compiler" }],
15
+ params: [{key: 'Sathya', value: 'Compiler'}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-expression-string-literal-key.expect.md
+3
-3
@@ -3,14 +3,14 @@
3
4
```javascript
5
function Component(props) {
6
- const x = { ["foo"]: props.foo };
6
+ const x = {['foo']: props.foo};
7
return x;
8
}
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-expression-string-literal-key.js
+3
-3
@@ -1,10 +1,10 @@
1
function Component(props) {
2
- const x = { ["foo"]: props.foo };
2
+ const x = {['foo']: props.foo};
3
return x;
4
}
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: Component,
8
- params: ["TodoAdd"],
9
- isComponent: "TodoAdd",
8
+ params: ['TodoAdd'],
9
+ isComponent: 'TodoAdd',
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-literal-method-call-in-ternary-test.expect.md
+3
-3
@@ -7,9 +7,9 @@ import {
7
identity,
8
CONST_STRING0,
9
CONST_STRING1,
10
-} from "shared-runtime";
10
+} from 'shared-runtime';
11
12
-function useHook({ value }) {
12
+function useHook({value}) {
13
return {
14
getValue() {
15
return identity(value);
@@ -21,7 +21,7 @@ function useHook({ value }) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: createHookWrapper(useHook),
24
- params: [{ value: 0 }],
24
+ params: [{value: 0}],
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-literal-method-call-in-ternary-test.js
+3
-3
@@ -3,9 +3,9 @@ import {
3
identity,
4
CONST_STRING0,
5
CONST_STRING1,
6
-} from "shared-runtime";
6
+} from 'shared-runtime';
7
8
-function useHook({ value }) {
8
+function useHook({value}) {
9
return {
10
getValue() {
11
return identity(value);
@@ -17,5 +17,5 @@ function useHook({ value }) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: createHookWrapper(useHook),
20
- params: [{ value: 0 }],
20
+ params: [{value: 0}],
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-literal-method-derived-in-ternary-consequent.expect.md
+3
-3
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { identity, createHookWrapper } from "shared-runtime";
5
+import {identity, createHookWrapper} from 'shared-runtime';
6
7
-function useHook({ isCond, value }) {
7
+function useHook({isCond, value}) {
8
return isCond
9
? identity({
10
getValue() {
@@ -16,7 +16,7 @@ function useHook({ isCond, value }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: createHookWrapper(useHook),
19
- params: [{ isCond: true, value: 0 }],
19
+ params: [{isCond: true, value: 0}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-literal-method-derived-in-ternary-consequent.js
+3
-3
@@ -1,6 +1,6 @@
1
-import { identity, createHookWrapper } from "shared-runtime";
1
+import {identity, createHookWrapper} from 'shared-runtime';
2
3
-function useHook({ isCond, value }) {
3
+function useHook({isCond, value}) {
4
return isCond
5
? identity({
6
getValue() {
@@ -12,5 +12,5 @@ function useHook({ isCond, value }) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: createHookWrapper(useHook),
15
- params: [{ isCond: true, value: 0 }],
15
+ params: [{isCond: true, value: 0}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-literal-method-in-ternary-consequent.expect.md
+3
-3
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { createHookWrapper } from "shared-runtime";
5
+import {createHookWrapper} from 'shared-runtime';
6
7
-function useHook({ isCond, value }) {
7
+function useHook({isCond, value}) {
8
return isCond
9
? {
10
getValue() {
@@ -16,7 +16,7 @@ function useHook({ isCond, value }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: createHookWrapper(useHook),
19
- params: [{ isCond: true, value: 0 }],
19
+ params: [{isCond: true, value: 0}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-literal-method-in-ternary-consequent.js
+3
-3
@@ -1,6 +1,6 @@
1
-import { createHookWrapper } from "shared-runtime";
1
+import {createHookWrapper} from 'shared-runtime';
2
3
-function useHook({ isCond, value }) {
3
+function useHook({isCond, value}) {
4
return isCond
5
? {
6
getValue() {
@@ -12,5 +12,5 @@ function useHook({ isCond, value }) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: createHookWrapper(useHook),
15
- params: [{ isCond: true, value: 0 }],
15
+ params: [{isCond: true, value: 0}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-literal-method-in-ternary-test.expect.md
+3
-7
@@ -2,13 +2,9 @@
2
## Input
3
4
```javascript
5
-import {
6
- createHookWrapper,
7
- CONST_STRING0,
8
- CONST_STRING1,
9
-} from "shared-runtime";
5
+import {createHookWrapper, CONST_STRING0, CONST_STRING1} from 'shared-runtime';
6
11
-function useHook({ value }) {
7
+function useHook({value}) {
8
return {
9
getValue() {
10
return identity(value);
@@ -20,7 +16,7 @@ function useHook({ value }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: createHookWrapper(useHook),
23
- params: [{ value: 0 }],
19
+ params: [{value: 0}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-literal-method-in-ternary-test.js
+3
-7
@@ -1,10 +1,6 @@
1
-import {
2
- createHookWrapper,
3
- CONST_STRING0,
4
- CONST_STRING1,
5
-} from "shared-runtime";
1
+import {createHookWrapper, CONST_STRING0, CONST_STRING1} from 'shared-runtime';
2
7
-function useHook({ value }) {
3
+function useHook({value}) {
4
return {
5
getValue() {
6
return identity(value);
@@ -16,5 +12,5 @@ function useHook({ value }) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: createHookWrapper(useHook),
19
- params: [{ value: 0 }],
15
+ params: [{value: 0}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-literal-spread-element.expect.md
+3
-3
@@ -3,14 +3,14 @@
3
4
```javascript
5
function Component(props) {
6
- const x = { ...props.foo };
6
+ const x = {...props.foo};
7
return x;
8
}
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-literal-spread-element.js
+3
-3
@@ -1,10 +1,10 @@
1
function Component(props) {
2
- const x = { ...props.foo };
2
+ const x = {...props.foo};
3
return x;
4
}
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: Component,
8
- params: ["TodoAdd"],
9
- isComponent: "TodoAdd",
8
+ params: ['TodoAdd'],
9
+ isComponent: 'TodoAdd',
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-method-maybe-alias.expect.md
+3
-3
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { createHookWrapper, setProperty } from "shared-runtime";
5
+import {createHookWrapper, setProperty} from 'shared-runtime';
6
function useHook(props) {
7
const x = {
8
getX() {
@@ -11,7 +11,7 @@ function useHook(props) {
11
};
12
const y = {
13
getY() {
14
- return "y";
14
+ return 'y';
15
},
16
};
17
return setProperty(x, y);
@@ -19,7 +19,7 @@ function useHook(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: createHookWrapper(useHook),
22
- params: [{ value: 0 }],
22
+ params: [{value: 0}],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-method-maybe-alias.js
+3
-3
@@ -1,4 +1,4 @@
1
-import { createHookWrapper, setProperty } from "shared-runtime";
1
+import {createHookWrapper, setProperty} from 'shared-runtime';
2
function useHook(props) {
3
const x = {
4
getX() {
@@ -7,7 +7,7 @@ function useHook(props) {
7
};
8
const y = {
9
getY() {
10
- return "y";
10
+ return 'y';
11
},
12
};
13
return setProperty(x, y);
@@ -15,5 +15,5 @@ function useHook(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: createHookWrapper(useHook),
18
- params: [{ value: 0 }],
18
+ params: [{value: 0}],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-method-shorthand-3.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { createHookWrapper, mutate } from "shared-runtime";
5
+import {createHookWrapper, mutate} from 'shared-runtime';
6
7
function useHook(a) {
8
- const x = { a };
8
+ const x = {a};
9
let obj = {
10
method() {
11
mutate(x);
@@ -17,7 +17,7 @@ function useHook(a) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: createHookWrapper(useHook),
20
- params: [{ x: 1 }],
20
+ params: [{x: 1}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-method-shorthand-3.js
+3
-3
@@ -1,7 +1,7 @@
1
-import { createHookWrapper, mutate } from "shared-runtime";
1
+import {createHookWrapper, mutate} from 'shared-runtime';
2
3
function useHook(a) {
4
- const x = { a };
4
+ const x = {a};
5
let obj = {
6
method() {
7
mutate(x);
@@ -13,5 +13,5 @@ function useHook(a) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: createHookWrapper(useHook),
16
- params: [{ x: 1 }],
16
+ params: [{x: 1}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-method-shorthand-aliased-mutate-after.expect.md
+4
-4
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { createHookWrapper, mutate, mutateAndReturn } from "shared-runtime";
6
-function useHook({ value }) {
7
- const x = mutateAndReturn({ value });
5
+import {createHookWrapper, mutate, mutateAndReturn} from 'shared-runtime';
6
+function useHook({value}) {
7
+ const x = mutateAndReturn({value});
8
const obj = {
9
getValue() {
10
return value;
@@ -16,7 +16,7 @@ function useHook({ value }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: createHookWrapper(useHook),
19
- params: [{ value: 0 }],
19
+ params: [{value: 0}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-method-shorthand-aliased-mutate-after.js
+4
-4
@@ -1,6 +1,6 @@
1
-import { createHookWrapper, mutate, mutateAndReturn } from "shared-runtime";
2
-function useHook({ value }) {
3
- const x = mutateAndReturn({ value });
1
+import {createHookWrapper, mutate, mutateAndReturn} from 'shared-runtime';
2
+function useHook({value}) {
3
+ const x = mutateAndReturn({value});
4
const obj = {
5
getValue() {
6
return value;
@@ -12,5 +12,5 @@ function useHook({ value }) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: createHookWrapper(useHook),
15
- params: [{ value: 0 }],
15
+ params: [{value: 0}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-method-shorthand-derived-value.expect.md
+4
-4
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { createHookWrapper, mutateAndReturn } from "shared-runtime";
6
-function useHook({ value }) {
7
- const x = mutateAndReturn({ value });
5
+import {createHookWrapper, mutateAndReturn} from 'shared-runtime';
6
+function useHook({value}) {
7
+ const x = mutateAndReturn({value});
8
const obj = {
9
getValue() {
10
return x;
@@ -15,7 +15,7 @@ function useHook({ value }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: createHookWrapper(useHook),
18
- params: [{ value: 0 }],
18
+ params: [{value: 0}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-method-shorthand-derived-value.js
+4
-4
@@ -1,6 +1,6 @@
1
-import { createHookWrapper, mutateAndReturn } from "shared-runtime";
2
-function useHook({ value }) {
3
- const x = mutateAndReturn({ value });
1
+import {createHookWrapper, mutateAndReturn} from 'shared-runtime';
2
+function useHook({value}) {
3
+ const x = mutateAndReturn({value});
4
const obj = {
5
getValue() {
6
return x;
@@ -11,5 +11,5 @@ function useHook({ value }) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: createHookWrapper(useHook),
14
- params: [{ value: 0 }],
14
+ params: [{value: 0}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-method-shorthand-hook-dep.expect.md
+2
-2
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import { createHookWrapper } from "shared-runtime";
6
-import { useState } from "react";
5
+import {createHookWrapper} from 'shared-runtime';
6
+import {useState} from 'react';
7
function useFoo() {
8
const [state, _setState] = useState(false);
9
return {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-method-shorthand-hook-dep.js
+2
-2
@@ -1,5 +1,5 @@
1
-import { createHookWrapper } from "shared-runtime";
2
-import { useState } from "react";
1
+import {createHookWrapper} from 'shared-runtime';
2
+import {useState} from 'react';
3
function useFoo() {
4
const [state, _setState] = useState(false);
5
return {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-method-shorthand-mutated-after.expect.md
+4
-4
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { createHookWrapper, mutate, mutateAndReturn } from "shared-runtime";
6
-function useHook({ value }) {
7
- const x = mutateAndReturn({ value });
5
+import {createHookWrapper, mutate, mutateAndReturn} from 'shared-runtime';
6
+function useHook({value}) {
7
+ const x = mutateAndReturn({value});
8
const obj = {
9
getValue() {
10
return x;
@@ -16,7 +16,7 @@ function useHook({ value }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: createHookWrapper(useHook),
19
- params: [{ value: 0 }],
19
+ params: [{value: 0}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-method-shorthand-mutated-after.js
+4
-4
@@ -1,6 +1,6 @@
1
-import { createHookWrapper, mutate, mutateAndReturn } from "shared-runtime";
2
-function useHook({ value }) {
3
- const x = mutateAndReturn({ value });
1
+import {createHookWrapper, mutate, mutateAndReturn} from 'shared-runtime';
2
+function useHook({value}) {
3
+ const x = mutateAndReturn({value});
4
const obj = {
5
getValue() {
6
return x;
@@ -12,5 +12,5 @@ function useHook({ value }) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: createHookWrapper(useHook),
15
- params: [{ value: 0 }],
15
+ params: [{value: 0}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-method-shorthand.expect.md
+1
-1
@@ -13,7 +13,7 @@ function Component() {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ x: 1 }, { a: 2 }, { b: 2 }],
16
+ params: [{x: 1}, {a: 2}, {b: 2}],
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-method-shorthand.js
+1
-1
@@ -9,5 +9,5 @@ function Component() {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: [{ x: 1 }, { a: 2 }, { b: 2 }],
12
+ params: [{x: 1}, {a: 2}, {b: 2}],
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-mutated-in-consequent-alternate-both-return.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeObject_Primitives } from "shared-runtime";
5
+import {makeObject_Primitives} from 'shared-runtime';
6
7
function Component(props) {
8
const object = makeObject_Primitives();
@@ -17,7 +17,7 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ cond: false, value: [0, 1, 2] }],
20
+ params: [{cond: false, value: [0, 1, 2]}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-mutated-in-consequent-alternate-both-return.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { makeObject_Primitives } from "shared-runtime";
1
+import {makeObject_Primitives} from 'shared-runtime';
2
3
function Component(props) {
4
const object = makeObject_Primitives();
@@ -13,5 +13,5 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ cond: false, value: [0, 1, 2] }],
16
+ params: [{cond: false, value: [0, 1, 2]}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-pattern-params.expect.md
+6
-6
@@ -2,16 +2,16 @@
2
## Input
3
4
```javascript
5
-function component({ a, b }) {
6
- let y = { a };
7
- let z = { b };
8
- return { y, z };
5
+function component({a, b}) {
6
+ let y = {a};
7
+ let z = {b};
8
+ return {y, z};
9
}
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-pattern-params.js
+6
-6
@@ -1,11 +1,11 @@
1
-function component({ a, b }) {
2
- let y = { a };
3
- let z = { b };
4
- return { y, z };
1
+function component({a, b}) {
2
+ let y = {a};
3
+ let z = {b};
4
+ return {y, z};
5
}
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: component,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-properties.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
function foo(a, b, c) {
6
const x = a.x;
7
- const y = { ...b.c.d };
7
+ const y = {...b.c.d};
8
y.z = c.d.e;
9
foo(a.b.c);
10
[a.b.c];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-properties.js
+1
-1
@@ -1,6 +1,6 @@
1
function foo(a, b, c) {
2
const x = a.x;
3
- const y = { ...b.c.d };
3
+ const y = {...b.c.d};
4
y.z = c.d.e;
5
foo(a.b.c);
6
[a.b.c];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-shorthand-method-1.expect.md
+3
-3
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import { createHookWrapper } from "shared-runtime";
6
-function useHook({ a, b }) {
5
+import {createHookWrapper} from 'shared-runtime';
6
+function useHook({a, b}) {
7
return {
8
x: function () {
9
return [a];
@@ -16,7 +16,7 @@ function useHook({ a, b }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: createHookWrapper(useHook),
19
- params: [{ a: 1, b: 2 }],
19
+ params: [{a: 1, b: 2}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-shorthand-method-1.js
+3
-3
@@ -1,5 +1,5 @@
1
-import { createHookWrapper } from "shared-runtime";
2
-function useHook({ a, b }) {
1
+import {createHookWrapper} from 'shared-runtime';
2
+function useHook({a, b}) {
3
return {
4
x: function () {
5
return [a];
@@ -12,5 +12,5 @@ function useHook({ a, b }) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: createHookWrapper(useHook),
15
- params: [{ a: 1, b: 2 }],
15
+ params: [{a: 1, b: 2}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-shorthand-method-2.expect.md
+4
-4
@@ -2,21 +2,21 @@
2
## Input
3
4
```javascript
5
-import { createHookWrapper } from "shared-runtime";
5
+import {createHookWrapper} from 'shared-runtime';
6
7
-function useHook({ a, b, c }) {
7
+function useHook({a, b, c}) {
8
return {
9
x: [a],
10
y() {
11
return [b];
12
},
13
- z: { c },
13
+ z: {c},
14
};
15
}
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: createHookWrapper(useHook),
19
- params: [{ a: 1, b: 2, c: 2 }],
19
+ params: [{a: 1, b: 2, c: 2}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-shorthand-method-2.js
+4
-4
@@ -1,16 +1,16 @@
1
-import { createHookWrapper } from "shared-runtime";
1
+import {createHookWrapper} from 'shared-runtime';
2
3
-function useHook({ a, b, c }) {
3
+function useHook({a, b, c}) {
4
return {
5
x: [a],
6
y() {
7
return [b];
8
},
9
- z: { c },
9
+ z: {c},
10
};
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: createHookWrapper(useHook),
15
- params: [{ a: 1, b: 2, c: 2 }],
15
+ params: [{a: 1, b: 2, c: 2}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-shorthand-method-nested.expect.md
+4
-4
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { useState } from "react";
6
-import { createHookWrapper } from "shared-runtime";
5
+import {useState} from 'react';
6
+import {createHookWrapper} from 'shared-runtime';
7
8
-function useHook({ value }) {
8
+function useHook({value}) {
9
const [state] = useState(false);
10
11
return {
@@ -23,7 +23,7 @@ function useHook({ value }) {
23
24
export const FIXTURE_ENTRYPOINT = {
25
fn: createHookWrapper(useHook),
26
- params: [{ value: 0 }],
26
+ params: [{value: 0}],
27
};
28
29
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/object-shorthand-method-nested.js
+4
-4
@@ -1,7 +1,7 @@
1
-import { useState } from "react";
2
-import { createHookWrapper } from "shared-runtime";
1
+import {useState} from 'react';
2
+import {createHookWrapper} from 'shared-runtime';
3
4
-function useHook({ value }) {
4
+function useHook({value}) {
5
const [state] = useState(false);
6
7
return {
@@ -19,5 +19,5 @@ function useHook({ value }) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: createHookWrapper(useHook),
22
- params: [{ value: 0 }],
22
+ params: [{value: 0}],
23
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/option-enable-change-variable-codegen.expect.md
+1
-1
@@ -10,7 +10,7 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ a: 3.14, b: { c: true } }],
13
+ params: [{a: 3.14, b: {c: true}}],
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/option-enable-change-variable-codegen.js
+1
-1
@@ -6,5 +6,5 @@ function Component(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: [{ a: 3.14, b: { c: true } }],
9
+ params: [{a: 3.14, b: {c: true}}],
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/optional-call-logical.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
function Component(props) {
6
const item = useFragment(graphql`...`, props.item);
7
- return item.items?.map((item) => renderItem(item)) ?? [];
7
+ return item.items?.map(item => renderItem(item)) ?? [];
8
}
9
10
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/optional-call-logical.js
+1
-1
@@ -1,4 +1,4 @@
1
function Component(props) {
2
const item = useFragment(graphql`...`, props.item);
3
- return item.items?.map((item) => renderItem(item)) ?? [];
3
+ return item.items?.map(item => renderItem(item)) ?? [];
4
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/optional-member-expression-chain.expect.md
+3
-3
@@ -7,13 +7,13 @@
7
function Component(props) {
8
let x = props?.b.c;
9
let y = props?.b.c.d?.e.f.g?.h;
10
- return { x, y };
10
+ return {x, y};
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/optional-member-expression-chain.js
+3
-3
@@ -3,11 +3,11 @@
3
function Component(props) {
4
let x = props?.b.c;
5
let y = props?.b.c.d?.e.f.g?.h;
6
- return { x, y };
6
+ return {x, y};
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/allocating-logical-expression-instruction-scope.expect.md
+2
-2
@@ -9,11 +9,11 @@
9
* The only scoped value we currently infer in this program is the
10
* PropertyLoad `data?.toString`.
11
*/
12
-import { useFragment } from "shared-runtime";
12
+import {useFragment} from 'shared-runtime';
13
14
function Foo() {
15
const data = useFragment();
16
- return [data?.toString() || ""];
16
+ return [data?.toString() || ''];
17
}
18
19
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/allocating-logical-expression-instruction-scope.ts
+2
-2
@@ -5,11 +5,11 @@
5
* The only scoped value we currently infer in this program is the
6
* PropertyLoad `data?.toString`.
7
*/
8
-import { useFragment } from "shared-runtime";
8
+import {useFragment} from 'shared-runtime';
9
10
function Foo() {
11
const data = useFragment();
12
- return [data?.toString() || ""];
12
+ return [data?.toString() || ''];
13
}
14
15
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/bug-hoisted-declaration-with-scope.expect.md
+5
-5
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @enableReactiveScopesInHIR:false
6
-import { StaticText1, Stringify, identity, useHook } from "shared-runtime";
6
+import {StaticText1, Stringify, identity, useHook} from 'shared-runtime';
7
/**
8
* `button` and `dispatcher` must end up in the same memo block. It would be
9
* invalid for `button` to take a dependency on `dispatcher` as dispatcher
@@ -16,16 +16,16 @@ import { StaticText1, Stringify, identity, useHook } from "shared-runtime";
16
* Forget:
17
* (kind: exception) Cannot access 'dispatcher' before initialization
18
*/
19
-function useFoo({ onClose }) {
19
+function useFoo({onClose}) {
20
const button = StaticText1 ?? (
21
<Stringify
22
primary={{
23
- label: identity("label"),
23
+ label: identity('label'),
24
onPress: onClose,
25
}}
26
secondary={{
27
onPress: () => {
28
- dispatcher.go("route2");
28
+ dispatcher.go('route2');
29
},
30
}}
31
/>
@@ -38,7 +38,7 @@ function useFoo({ onClose }) {
38
39
export const FIXTURE_ENTRYPOINT = {
40
fn: useFoo,
41
- params: [{ onClose: identity() }],
41
+ params: [{onClose: identity()}],
42
};
43
44
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/bug-hoisted-declaration-with-scope.tsx
+5
-5
@@ -1,5 +1,5 @@
1
// @enableReactiveScopesInHIR:false
2
-import { StaticText1, Stringify, identity, useHook } from "shared-runtime";
2
+import {StaticText1, Stringify, identity, useHook} from 'shared-runtime';
3
/**
4
* `button` and `dispatcher` must end up in the same memo block. It would be
5
* invalid for `button` to take a dependency on `dispatcher` as dispatcher
@@ -12,16 +12,16 @@ import { StaticText1, Stringify, identity, useHook } from "shared-runtime";
12
* Forget:
13
* (kind: exception) Cannot access 'dispatcher' before initialization
14
*/
15
-function useFoo({ onClose }) {
15
+function useFoo({onClose}) {
16
const button = StaticText1 ?? (
17
<Stringify
18
primary={{
19
- label: identity("label"),
19
+ label: identity('label'),
20
onPress: onClose,
21
}}
22
secondary={{
23
onPress: () => {
24
- dispatcher.go("route2");
24
+ dispatcher.go('route2');
25
},
26
}}
27
/>
@@ -34,5 +34,5 @@ function useFoo({ onClose }) {
34
35
export const FIXTURE_ENTRYPOINT = {
36
fn: useFoo,
37
- params: [{ onClose: identity() }],
37
+ params: [{onClose: identity()}],
38
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/bug-nonmutating-capture-in-unsplittable-memo-block.expect.md
+7
-7
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @enableReactiveScopesInHIR:false
6
-import { identity, mutate } from "shared-runtime";
6
+import {identity, mutate} from 'shared-runtime';
7
8
/**
9
* The root cause of this bug is in `InferReactiveScopeVariables`. Currently,
@@ -33,25 +33,25 @@ import { identity, mutate } from "shared-runtime";
33
* [[ (exception in render) Error: oh no! ]]
34
*
35
*/
36
-function useFoo({ a, b }) {
37
- const x = { a };
36
+function useFoo({a, b}) {
37
+ const x = {a};
38
const y = {};
39
mutate(x);
40
const z = [identity(y), b];
41
mutate(y);
42
43
if (z[0] !== y) {
44
- throw new Error("oh no!");
44
+ throw new Error('oh no!');
45
}
46
return z;
47
}
48
49
export const FIXTURE_ENTRYPOINT = {
50
fn: useFoo,
51
- params: [{ a: 2, b: 3 }],
51
+ params: [{a: 2, b: 3}],
52
sequentialRenders: [
53
- { a: 2, b: 3 },
54
- { a: 4, b: 3 },
53
+ {a: 2, b: 3},
54
+ {a: 4, b: 3},
55
],
56
};
57
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/bug-nonmutating-capture-in-unsplittable-memo-block.ts
+7
-7
@@ -1,5 +1,5 @@
1
// @enableReactiveScopesInHIR:false
2
-import { identity, mutate } from "shared-runtime";
2
+import {identity, mutate} from 'shared-runtime';
3
4
/**
5
* The root cause of this bug is in `InferReactiveScopeVariables`. Currently,
@@ -29,24 +29,24 @@ import { identity, mutate } from "shared-runtime";
29
* [[ (exception in render) Error: oh no! ]]
30
*
31
*/
32
-function useFoo({ a, b }) {
33
- const x = { a };
32
+function useFoo({a, b}) {
33
+ const x = {a};
34
const y = {};
35
mutate(x);
36
const z = [identity(y), b];
37
mutate(y);
38
39
if (z[0] !== y) {
40
- throw new Error("oh no!");
40
+ throw new Error('oh no!');
41
}
42
return z;
43
}
44
45
export const FIXTURE_ENTRYPOINT = {
46
fn: useFoo,
47
- params: [{ a: 2, b: 3 }],
47
+ params: [{a: 2, b: 3}],
48
sequentialRenders: [
49
- { a: 2, b: 3 },
50
- { a: 4, b: 3 },
49
+ {a: 2, b: 3},
50
+ {a: 4, b: 3},
51
],
52
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/capture-ref-for-later-mutation.expect.md
+6
-6
@@ -3,21 +3,21 @@
3
4
```javascript
5
// @enableReactiveScopesInHIR:false
6
-import { useRef } from "react";
7
-import { addOne } from "shared-runtime";
6
+import {useRef} from 'react';
7
+import {addOne} from 'shared-runtime';
8
9
function useKeyCommand() {
10
const currentPosition = useRef(0);
11
- const handleKey = (direction) => () => {
11
+ const handleKey = direction => () => {
12
const position = currentPosition.current;
13
- const nextPosition = direction === "left" ? addOne(position) : position;
13
+ const nextPosition = direction === 'left' ? addOne(position) : position;
14
currentPosition.current = nextPosition;
15
};
16
const moveLeft = {
17
- handler: handleKey("left"),
17
+ handler: handleKey('left'),
18
};
19
const moveRight = {
20
- handler: handleKey("right"),
20
+ handler: handleKey('right'),
21
};
22
return [moveLeft, moveRight];
23
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/capture-ref-for-later-mutation.tsx
+6
-6
@@ -1,19 +1,19 @@
1
// @enableReactiveScopesInHIR:false
2
-import { useRef } from "react";
3
-import { addOne } from "shared-runtime";
2
+import {useRef} from 'react';
3
+import {addOne} from 'shared-runtime';
4
5
function useKeyCommand() {
6
const currentPosition = useRef(0);
7
- const handleKey = (direction) => () => {
7
+ const handleKey = direction => () => {
8
const position = currentPosition.current;
9
- const nextPosition = direction === "left" ? addOne(position) : position;
9
+ const nextPosition = direction === 'left' ? addOne(position) : position;
10
currentPosition.current = nextPosition;
11
};
12
const moveLeft = {
13
- handler: handleKey("left"),
13
+ handler: handleKey('left'),
14
};
15
const moveRight = {
16
- handler: handleKey("right"),
16
+ handler: handleKey('right'),
17
};
18
return [moveLeft, moveRight];
19
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/invalid-align-scopes-within-nested-valueblock-in-array.expect.md
+5
-5
@@ -4,7 +4,7 @@
4
```javascript
5
// @enableReactiveScopesInHIR:false
6
7
-import { Stringify, identity, makeArray, mutate } from "shared-runtime";
7
+import {Stringify, identity, makeArray, mutate} from 'shared-runtime';
8
9
/**
10
* Here, identity('foo') is an immutable allocating instruction.
@@ -16,12 +16,12 @@ import { Stringify, identity, makeArray, mutate } from "shared-runtime";
16
* (e.g. `cond1 ? <>: null`). The HIR version of alignScopesToBlocks
17
* handles this correctly.
18
*/
19
-function Foo({ cond1, cond2 }) {
20
- const arr = makeArray<any>({ a: 2 }, 2, []);
19
+function Foo({cond1, cond2}) {
20
+ const arr = makeArray<any>({a: 2}, 2, []);
21
22
return cond1 ? (
23
<>
24
- <div>{identity("foo")}</div>
24
+ <div>{identity('foo')}</div>
25
<Stringify value={cond2 ? arr.map(mutate) : null} />
26
</>
27
) : null;
@@ -29,7 +29,7 @@ function Foo({ cond1, cond2 }) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: Foo,
32
- params: [{ cond1: true, cond2: true }],
32
+ params: [{cond1: true, cond2: true}],
33
};
34
35
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/invalid-align-scopes-within-nested-valueblock-in-array.tsx
+5
-5
@@ -1,6 +1,6 @@
1
// @enableReactiveScopesInHIR:false
2
3
-import { Stringify, identity, makeArray, mutate } from "shared-runtime";
3
+import {Stringify, identity, makeArray, mutate} from 'shared-runtime';
4
5
/**
6
* Here, identity('foo') is an immutable allocating instruction.
@@ -12,12 +12,12 @@ import { Stringify, identity, makeArray, mutate } from "shared-runtime";
12
* (e.g. `cond1 ? <>: null`). The HIR version of alignScopesToBlocks
13
* handles this correctly.
14
*/
15
-function Foo({ cond1, cond2 }) {
16
- const arr = makeArray<any>({ a: 2 }, 2, []);
15
+function Foo({cond1, cond2}) {
16
+ const arr = makeArray<any>({a: 2}, 2, []);
17
18
return cond1 ? (
19
<>
20
- <div>{identity("foo")}</div>
20
+ <div>{identity('foo')}</div>
21
<Stringify value={cond2 ? arr.map(mutate) : null} />
22
</>
23
) : null;
@@ -25,5 +25,5 @@ function Foo({ cond1, cond2 }) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Foo,
28
- params: [{ cond1: true, cond2: true }],
28
+ params: [{cond1: true, cond2: true}],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/mutate-outer-scope-within-value-block.expect.md
+4
-4
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @enableReactiveScopesInHIR:false
6
-import { CONST_TRUE, identity, shallowCopy } from "shared-runtime";
6
+import {CONST_TRUE, identity, shallowCopy} from 'shared-runtime';
7
8
/**
9
* There are three values with their own scopes in this fixture.
@@ -26,16 +26,16 @@ import { CONST_TRUE, identity, shallowCopy } from "shared-runtime";
26
* Observe that instruction 5 mutates scope 0, which means that scopes 0 and 2
27
* should be merged.
28
*/
29
-function useFoo({ input }) {
29
+function useFoo({input}) {
30
const arr = shallowCopy(input);
31
32
const cond = identity(false);
33
- return cond ? { val: CONST_TRUE } : mutate(arr);
33
+ return cond ? {val: CONST_TRUE} : mutate(arr);
34
}
35
36
export const FIXTURE_ENTRYPOINT = {
37
fn: useFoo,
38
- params: [{ input: 3 }],
38
+ params: [{input: 3}],
39
};
40
41
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/mutate-outer-scope-within-value-block.ts
+4
-4
@@ -1,5 +1,5 @@
1
// @enableReactiveScopesInHIR:false
2
-import { CONST_TRUE, identity, shallowCopy } from "shared-runtime";
2
+import {CONST_TRUE, identity, shallowCopy} from 'shared-runtime';
3
4
/**
5
* There are three values with their own scopes in this fixture.
@@ -22,14 +22,14 @@ import { CONST_TRUE, identity, shallowCopy } from "shared-runtime";
22
* Observe that instruction 5 mutates scope 0, which means that scopes 0 and 2
23
* should be merged.
24
*/
25
-function useFoo({ input }) {
25
+function useFoo({input}) {
26
const arr = shallowCopy(input);
27
28
const cond = identity(false);
29
- return cond ? { val: CONST_TRUE } : mutate(arr);
29
+ return cond ? {val: CONST_TRUE} : mutate(arr);
30
}
31
32
export const FIXTURE_ENTRYPOINT = {
33
fn: useFoo,
34
- params: [{ input: 3 }],
34
+ params: [{input: 3}],
35
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/mutation-within-capture-and-mutablerange.expect.md
+4
-4
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @enableReactiveScopesInHIR:false
6
-import { mutate } from "shared-runtime";
6
+import {mutate} from 'shared-runtime';
7
8
/**
9
* This test fixture is similar to mutation-within-jsx. The only difference
@@ -15,9 +15,9 @@ import { mutate } from "shared-runtime";
15
* memo blocks (which may lead to 'tearing', i.e. mutating one render's
16
* values in a subsequent render.
17
*/
18
-function useFoo({ a, b }) {
18
+function useFoo({a, b}) {
19
// x and y's scopes start here
20
- const x = { a };
20
+ const x = {a};
21
const y = [b];
22
mutate(x);
23
// z captures the result of `mutate(y)`, which may be aliased to `y`.
@@ -30,7 +30,7 @@ function useFoo({ a, b }) {
30
31
export const FIXTURE_ENTRYPOINT = {
32
fn: useFoo,
33
- params: [{ a: 2, b: 3 }],
33
+ params: [{a: 2, b: 3}],
34
};
35
36
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/mutation-within-capture-and-mutablerange.tsx
+4
-4
@@ -1,5 +1,5 @@
1
// @enableReactiveScopesInHIR:false
2
-import { mutate } from "shared-runtime";
2
+import {mutate} from 'shared-runtime';
3
4
/**
5
* This test fixture is similar to mutation-within-jsx. The only difference
@@ -11,9 +11,9 @@ import { mutate } from "shared-runtime";
11
* memo blocks (which may lead to 'tearing', i.e. mutating one render's
12
* values in a subsequent render.
13
*/
14
-function useFoo({ a, b }) {
14
+function useFoo({a, b}) {
15
// x and y's scopes start here
16
- const x = { a };
16
+ const x = {a};
17
const y = [b];
18
mutate(x);
19
// z captures the result of `mutate(y)`, which may be aliased to `y`.
@@ -26,5 +26,5 @@ function useFoo({ a, b }) {
26
27
export const FIXTURE_ENTRYPOINT = {
28
fn: useFoo,
29
- params: [{ a: 2, b: 3 }],
29
+ params: [{a: 2, b: 3}],
30
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/mutation-within-jsx-and-break.expect.md
+5
-5
@@ -8,9 +8,9 @@ import {
8
makeObject_Primitives,
9
mutate,
10
mutateAndReturn,
11
-} from "shared-runtime";
11
+} from 'shared-runtime';
12
13
-function useFoo({ data }) {
13
+function useFoo({data}) {
14
let obj = null;
15
let myDiv = null;
16
label: {
@@ -29,10 +29,10 @@ function useFoo({ data }) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: useFoo,
32
- params: [{ data: { cond: true, cond1: true } }],
32
+ params: [{data: {cond: true, cond1: true}}],
33
sequentialRenders: [
34
- { data: { cond: true, cond1: true } },
35
- { data: { cond: true, cond1: true } },
34
+ {data: {cond: true, cond1: true}},
35
+ {data: {cond: true, cond1: true}},
36
],
37
};
38
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/mutation-within-jsx-and-break.tsx
+5
-5
@@ -4,9 +4,9 @@ import {
4
makeObject_Primitives,
5
mutate,
6
mutateAndReturn,
7
-} from "shared-runtime";
7
+} from 'shared-runtime';
8
9
-function useFoo({ data }) {
9
+function useFoo({data}) {
10
let obj = null;
11
let myDiv = null;
12
label: {
@@ -25,9 +25,9 @@ function useFoo({ data }) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: useFoo,
28
- params: [{ data: { cond: true, cond1: true } }],
28
+ params: [{data: {cond: true, cond1: true}}],
29
sequentialRenders: [
30
- { data: { cond: true, cond1: true } },
31
- { data: { cond: true, cond1: true } },
30
+ {data: {cond: true, cond1: true}},
31
+ {data: {cond: true, cond1: true}},
32
],
33
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/mutation-within-jsx.expect.md
+5
-5
@@ -7,7 +7,7 @@ import {
7
Stringify,
8
makeObject_Primitives,
9
mutateAndReturn,
10
-} from "shared-runtime";
10
+} from 'shared-runtime';
11
12
/**
13
* In this example, the `<Stringify ... />` JSX block mutates then captures obj.
@@ -35,7 +35,7 @@ import {
35
* a result, developers can never observe myDiv can aliasing a different value generation
36
* than `obj` (e.g. the invariant `myDiv.props.value === obj` always holds).
37
*/
38
-function useFoo({ data }) {
38
+function useFoo({data}) {
39
let obj = null;
40
let myDiv = null;
41
if (data.cond) {
@@ -49,10 +49,10 @@ function useFoo({ data }) {
49
50
export const FIXTURE_ENTRYPOINT = {
51
fn: useFoo,
52
- params: [{ data: { cond: true, cond1: true } }],
52
+ params: [{data: {cond: true, cond1: true}}],
53
sequentialRenders: [
54
- { data: { cond: true, cond1: true } },
55
- { data: { cond: true, cond1: true } },
54
+ {data: {cond: true, cond1: true}},
55
+ {data: {cond: true, cond1: true}},
56
],
57
};
58
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/mutation-within-jsx.tsx
+5
-5
@@ -3,7 +3,7 @@ import {
3
Stringify,
4
makeObject_Primitives,
5
mutateAndReturn,
6
-} from "shared-runtime";
6
+} from 'shared-runtime';
7
8
/**
9
* In this example, the `<Stringify ... />` JSX block mutates then captures obj.
@@ -31,7 +31,7 @@ import {
31
* a result, developers can never observe myDiv can aliasing a different value generation
32
* than `obj` (e.g. the invariant `myDiv.props.value === obj` always holds).
33
*/
34
-function useFoo({ data }) {
34
+function useFoo({data}) {
35
let obj = null;
36
let myDiv = null;
37
if (data.cond) {
@@ -45,9 +45,9 @@ function useFoo({ data }) {
45
46
export const FIXTURE_ENTRYPOINT = {
47
fn: useFoo,
48
- params: [{ data: { cond: true, cond1: true } }],
48
+ params: [{data: {cond: true, cond1: true}}],
49
sequentialRenders: [
50
- { data: { cond: true, cond1: true } },
51
- { data: { cond: true, cond1: true } },
50
+ {data: {cond: true, cond1: true}},
51
+ {data: {cond: true, cond1: true}},
52
],
53
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/repro-allocating-ternary-test-instruction-scope.expect.md
+3
-3
@@ -3,9 +3,9 @@
3
4
```javascript
5
// @enableReactiveScopesInHIR:false
6
-import { identity, makeObject_Primitives } from "shared-runtime";
6
+import {identity, makeObject_Primitives} from 'shared-runtime';
7
8
-function useTest({ cond }) {
8
+function useTest({cond}) {
9
const val = makeObject_Primitives();
10
11
useHook();
@@ -21,7 +21,7 @@ function useTest({ cond }) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: useTest,
24
- params: [{ cond: true }],
24
+ params: [{cond: true}],
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/original-reactive-scopes-fork/repro-allocating-ternary-test-instruction-scope.ts
+3
-3
@@ -1,7 +1,7 @@
1
// @enableReactiveScopesInHIR:false
2
-import { identity, makeObject_Primitives } from "shared-runtime";
2
+import {identity, makeObject_Primitives} from 'shared-runtime';
3
4
-function useTest({ cond }) {
4
+function useTest({cond}) {
5
const val = makeObject_Primitives();
6
7
useHook();
@@ -17,5 +17,5 @@ function useTest({ cond }) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: useTest,
20
- params: [{ cond: true }],
20
+ params: [{cond: true}],
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/outlined-destructured-params.expect.md
+3
-3
@@ -2,14 +2,14 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
function Component(props) {
8
// test outlined functions with destructured parameters - the
9
// temporary for the destructured param must be promoted
10
return (
11
<>
12
- {props.items.map(({ id, name }) => (
12
+ {props.items.map(({id, name}) => (
13
<Stringify key={id} name={name} />
14
))}
15
</>
@@ -18,7 +18,7 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ items: [{ id: 1, name: "one" }] }],
21
+ params: [{items: [{id: 1, name: 'one'}]}],
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/outlined-destructured-params.js
+3
-3
@@ -1,11 +1,11 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
function Component(props) {
4
// test outlined functions with destructured parameters - the
5
// temporary for the destructured param must be promoted
6
return (
7
<>
8
- {props.items.map(({ id, name }) => (
8
+ {props.items.map(({id, name}) => (
9
<Stringify key={id} name={name} />
10
))}
11
</>
@@ -14,5 +14,5 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ items: [{ id: 1, name: "one" }] }],
17
+ params: [{items: [{id: 1, name: 'one'}]}],
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/outlined-helper.expect.md
+3
-3
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
function Component(props) {
8
return (
9
<div>
10
- {props.items.map((item) => (
10
+ {props.items.map(item => (
11
<Stringify key={item.id} item={item.name} />
12
))}
13
</div>
@@ -16,7 +16,7 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ items: [{ id: 1, name: "one" }] }],
19
+ params: [{items: [{id: 1, name: 'one'}]}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/outlined-helper.js
+3
-3
@@ -1,9 +1,9 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
function Component(props) {
4
return (
5
<div>
6
- {props.items.map((item) => (
6
+ {props.items.map(item => (
7
<Stringify key={item.id} item={item.name} />
8
))}
9
</div>
@@ -12,5 +12,5 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ items: [{ id: 1, name: "one" }] }],
15
+ params: [{items: [{id: 1, name: 'one'}]}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/overlapping-scopes-interleaved-by-terminal.expect.md
+2
-2
@@ -15,8 +15,8 @@ function foo(a, b, c) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: foo,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/overlapping-scopes-interleaved-by-terminal.js
+2
-2
@@ -11,6 +11,6 @@ function foo(a, b, c) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/overlapping-scopes-interleaved.expect.md
+2
-2
@@ -11,8 +11,8 @@ function foo(a, b) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/overlapping-scopes-interleaved.js
+2
-2
@@ -7,6 +7,6 @@ function foo(a, b) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: foo,
10
- params: ["TodoAdd"],
11
- isComponent: "TodoAdd",
10
+ params: ['TodoAdd'],
11
+ isComponent: 'TodoAdd',
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/overlapping-scopes-shadowed.expect.md
+2
-2
@@ -11,8 +11,8 @@ function foo(a, b) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/overlapping-scopes-shadowed.js
+2
-2
@@ -7,6 +7,6 @@ function foo(a, b) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: foo,
10
- params: ["TodoAdd"],
11
- isComponent: "TodoAdd",
10
+ params: ['TodoAdd'],
11
+ isComponent: 'TodoAdd',
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/overlapping-scopes-shadowing-within-block.expect.md
+2
-2
@@ -17,8 +17,8 @@ function foo(a, b, c) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: foo,
20
- params: ["TodoAdd"],
21
- isComponent: "TodoAdd",
20
+ params: ['TodoAdd'],
21
+ isComponent: 'TodoAdd',
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/overlapping-scopes-shadowing-within-block.js
+2
-2
@@ -13,6 +13,6 @@ function foo(a, b, c) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: foo,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/overlapping-scopes-while.expect.md
+2
-2
@@ -13,8 +13,8 @@ function foo(a, b, c) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: foo,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/overlapping-scopes-while.js
+2
-2
@@ -9,6 +9,6 @@ function foo(a, b, c) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: foo,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/overlapping-scopes-within-block.expect.md
+2
-2
@@ -17,8 +17,8 @@ function foo(a, b, c) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: foo,
20
- params: ["TodoAdd"],
21
- isComponent: "TodoAdd",
20
+ params: ['TodoAdd'],
21
+ isComponent: 'TodoAdd',
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/overlapping-scopes-within-block.js
+2
-2
@@ -13,6 +13,6 @@ function foo(a, b, c) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: foo,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/partial-early-return-within-reactive-scope.expect.md
+1
-1
@@ -20,7 +20,7 @@ function Component(props) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
- params: [{ cond: true, a: 42 }],
23
+ params: [{cond: true, a: 42}],
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/partial-early-return-within-reactive-scope.js
+1
-1
@@ -16,5 +16,5 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ cond: true, a: 42 }],
19
+ params: [{cond: true, a: 42}],
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/phi-reference-effects.expect.md
+3
-3
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { arrayPush } from "shared-runtime";
5
+import {arrayPush} from 'shared-runtime';
6
7
function Foo(cond) {
8
let x = null;
@@ -18,8 +18,8 @@ function Foo(cond) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Foo,
21
- params: [{ cond: true }],
22
- sequentialRenders: [{ cond: true }, { cond: true }],
21
+ params: [{cond: true}],
22
+ sequentialRenders: [{cond: true}, {cond: true}],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/phi-reference-effects.ts
+3
-3
@@ -1,4 +1,4 @@
1
-import { arrayPush } from "shared-runtime";
1
+import {arrayPush} from 'shared-runtime';
2
3
function Foo(cond) {
4
let x = null;
@@ -14,6 +14,6 @@ function Foo(cond) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Foo,
17
- params: [{ cond: true }],
18
- sequentialRenders: [{ cond: true }, { cond: true }],
17
+ params: [{cond: true}],
18
+ sequentialRenders: [{cond: true}, {cond: true}],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/phi-type-inference-array-push.expect.md
+4
-4
@@ -21,11 +21,11 @@ function Component(props) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
- params: [{ cond: true, value: 42 }],
24
+ params: [{cond: true, value: 42}],
25
sequentialRenders: [
26
- { cond: true, value: 3.14 },
27
- { cond: false, value: 3.14 },
28
- { cond: true, value: 42 },
26
+ {cond: true, value: 3.14},
27
+ {cond: false, value: 3.14},
28
+ {cond: true, value: 42},
29
],
30
};
31
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/phi-type-inference-array-push.js
+4
-4
@@ -17,10 +17,10 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ cond: true, value: 42 }],
20
+ params: [{cond: true, value: 42}],
21
sequentialRenders: [
22
- { cond: true, value: 3.14 },
23
- { cond: false, value: 3.14 },
24
- { cond: true, value: 42 },
22
+ {cond: true, value: 3.14},
23
+ {cond: false, value: 3.14},
24
+ {cond: true, value: 42},
25
],
26
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/phi-type-inference-property-store.expect.md
+2
-2
@@ -9,7 +9,7 @@ function Component(props) {
9
if (props.cond) {
10
y = {};
11
} else {
12
- y = { a: props.a };
12
+ y = {a: props.a};
13
}
14
// This should be inferred as `<store> y` s.t. `x` can still
15
// be independently memoized. *But* this also must properly
@@ -22,7 +22,7 @@ function Component(props) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
25
- params: [{ cond: false, a: "a!" }],
25
+ params: [{cond: false, a: 'a!'}],
26
};
27
28
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/phi-type-inference-property-store.js
+2
-2
@@ -5,7 +5,7 @@ function Component(props) {
5
if (props.cond) {
6
y = {};
7
} else {
8
- y = { a: props.a };
8
+ y = {a: props.a};
9
}
10
// This should be inferred as `<store> y` s.t. `x` can still
11
// be independently memoized. *But* this also must properly
@@ -18,5 +18,5 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ cond: false, a: "a!" }],
21
+ params: [{cond: false, a: 'a!'}],
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-jsxtext-stringliteral-distinction.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function Foo() {
6
- return <div> {", "}</div>;
6
+ return <div> {', '}</div>;
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-jsxtext-stringliteral-distinction.js
+1
-1
@@ -1,5 +1,5 @@
1
function Foo() {
2
- return <div> {", "}</div>;
2
+ return <div> {', '}</div>;
3
}
4
5
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.false-positive-useMemo-infer-mutate-deps.expect.md
+2
-2
@@ -3,8 +3,8 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
7
-import { identity } from "shared-runtime";
6
+import {useMemo} from 'react';
7
+import {identity} from 'shared-runtime';
8
9
// This is a false positive as Forget's inferred memoization
10
// invalidates strictly less than source. We currently do not
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.false-positive-useMemo-infer-mutate-deps.ts
+2
-2
@@ -1,6 +1,6 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
3
-import { identity } from "shared-runtime";
2
+import {useMemo} from 'react';
3
+import {identity} from 'shared-runtime';
4
5
// This is a false positive as Forget's inferred memoization
6
// invalidates strictly less than source. We currently do not
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.invalid-useCallback-captures-reassigned-context.expect.md
+2
-2
@@ -4,8 +4,8 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useCallback } from "react";
8
-import { makeArray } from "shared-runtime";
7
+import {useCallback} from 'react';
8
+import {makeArray} from 'shared-runtime';
9
10
// This case is already unsound in source, so we can safely bailout
11
function Foo(props) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.invalid-useCallback-captures-reassigned-context.ts
+2
-2
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useCallback } from "react";
4
-import { makeArray } from "shared-runtime";
3
+import {useCallback} from 'react';
4
+import {makeArray} from 'shared-runtime';
5
6
// This case is already unsound in source, so we can safely bailout
7
function Foo(props) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.maybe-invalid-useCallback-read-maybeRef.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useCallback } from "react";
6
+import {useCallback} from 'react';
7
8
function useHook(maybeRef) {
9
return useCallback(() => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.maybe-invalid-useCallback-read-maybeRef.ts
+1
-1
@@ -1,5 +1,5 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useCallback } from "react";
2
+import {useCallback} from 'react';
3
4
function useHook(maybeRef) {
5
return useCallback(() => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.maybe-invalid-useMemo-read-maybeRef.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
6
+import {useMemo} from 'react';
7
8
function useHook(maybeRef, shouldRead) {
9
return useMemo(() => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.maybe-invalid-useMemo-read-maybeRef.ts
+1
-1
@@ -1,5 +1,5 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
2
+import {useMemo} from 'react';
3
4
function useHook(maybeRef, shouldRead) {
5
return useMemo(() => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.todo-useCallback-captures-invalidating-value.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useCallback } from "react";
7
+import {useCallback} from 'react';
8
9
// False positive:
10
// We currently bail out on this because we don't understand
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.todo-useCallback-captures-invalidating-value.ts
+1
-1
@@ -1,6 +1,6 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useCallback } from "react";
3
+import {useCallback} from 'react';
4
5
// False positive:
6
// We currently bail out on this because we don't understand
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useCallback-conditional-access-noAlloc.expect.md
+4
-4
@@ -3,9 +3,9 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useCallback } from "react";
6
+import {useCallback} from 'react';
7
8
-function Component({ propA, propB }) {
8
+function Component({propA, propB}) {
9
return useCallback(() => {
10
return {
11
value: propB?.x.y,
@@ -16,7 +16,7 @@ function Component({ propA, propB }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ propA: 2, propB: { x: { y: [] } } }],
19
+ params: [{propA: 2, propB: {x: {y: []}}}],
20
};
21
22
```
@@ -26,7 +26,7 @@ export const FIXTURE_ENTRYPOINT = {
26
27
```
28
3 |
29
- 4 | function Component({ propA, propB }) {
29
+ 4 | function Component({propA, propB}) {
30
> 5 | return useCallback(() => {
31
| ^^^^^^^
32
> 6 | return {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useCallback-conditional-access-noAlloc.ts
+3
-3
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useCallback } from "react";
2
+import {useCallback} from 'react';
3
4
-function Component({ propA, propB }) {
4
+function Component({propA, propB}) {
5
return useCallback(() => {
6
return {
7
value: propB?.x.y,
@@ -12,5 +12,5 @@ function Component({ propA, propB }) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ propA: 2, propB: { x: { y: [] } } }],
15
+ params: [{propA: 2, propB: {x: {y: []}}}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useCallback-infer-less-specific-conditional-access.expect.md
+4
-4
@@ -3,10 +3,10 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useCallback } from "react";
7
-import { mutate } from "shared-runtime";
6
+import {useCallback} from 'react';
7
+import {mutate} from 'shared-runtime';
8
9
-function Component({ propA, propB }) {
9
+function Component({propA, propB}) {
10
return useCallback(() => {
11
const x = {};
12
if (propA?.a) {
@@ -25,7 +25,7 @@ function Component({ propA, propB }) {
25
26
```
27
4 |
28
- 5 | function Component({ propA, propB }) {
28
+ 5 | function Component({propA, propB}) {
29
> 6 | return useCallback(() => {
30
| ^^^^^^^
31
> 7 | const x = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useCallback-infer-less-specific-conditional-access.ts
+3
-3
@@ -1,8 +1,8 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useCallback } from "react";
3
-import { mutate } from "shared-runtime";
2
+import {useCallback} from 'react';
3
+import {mutate} from 'shared-runtime';
4
5
-function Component({ propA, propB }) {
5
+function Component({propA, propB}) {
6
return useCallback(() => {
7
const x = {};
8
if (propA?.a) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useCallback-property-call-dep.expect.md
+3
-3
@@ -3,9 +3,9 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useCallback } from "react";
6
+import {useCallback} from 'react';
7
8
-function Component({ propA }) {
8
+function Component({propA}) {
9
return useCallback(() => {
10
return propA.x();
11
}, [propA.x]);
@@ -18,7 +18,7 @@ function Component({ propA }) {
18
19
```
20
3 |
21
- 4 | function Component({ propA }) {
21
+ 4 | function Component({propA}) {
22
> 5 | return useCallback(() => {
23
| ^^^^^^^
24
> 6 | return propA.x();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useCallback-property-call-dep.ts
+2
-2
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useCallback } from "react";
2
+import {useCallback} from 'react';
3
4
-function Component({ propA }) {
4
+function Component({propA}) {
5
return useCallback(() => {
6
return propA.x();
7
}, [propA.x]);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useMemo-dep-not-recognized.expect.md
+3
-3
@@ -4,8 +4,8 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useMemo } from "react";
8
-import { makeArray } from "shared-runtime";
7
+import {useMemo} from 'react';
8
+import {makeArray} from 'shared-runtime';
9
10
// We currently only recognize "hoistable" values (e.g. variable reads
11
// and property loads from named variables) in the source depslist.
@@ -19,7 +19,7 @@ function Foo(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Foo,
22
- params: [{ val: 1 }],
22
+ params: [{val: 1}],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useMemo-dep-not-recognized.ts
+3
-3
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useMemo } from "react";
4
-import { makeArray } from "shared-runtime";
3
+import {useMemo} from 'react';
4
+import {makeArray} from 'shared-runtime';
5
6
// We currently only recognize "hoistable" values (e.g. variable reads
7
// and property loads from named variables) in the source depslist.
@@ -15,5 +15,5 @@ function Foo(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Foo,
18
- params: [{ val: 1 }],
18
+ params: [{val: 1}],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useMemo-infer-less-specific-conditional-access.expect.md
+4
-4
@@ -3,10 +3,10 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
7
-import { mutate } from "shared-runtime";
6
+import {useMemo} from 'react';
7
+import {mutate} from 'shared-runtime';
8
9
-function Component({ propA, propB }) {
9
+function Component({propA, propB}) {
10
return useMemo(() => {
11
const x = {};
12
if (propA?.a) {
@@ -25,7 +25,7 @@ function Component({ propA, propB }) {
25
26
```
27
4 |
28
- 5 | function Component({ propA, propB }) {
28
+ 5 | function Component({propA, propB}) {
29
> 6 | return useMemo(() => {
30
| ^^^^^^^
31
> 7 | const x = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useMemo-infer-less-specific-conditional-access.ts
+3
-3
@@ -1,8 +1,8 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
3
-import { mutate } from "shared-runtime";
2
+import {useMemo} from 'react';
3
+import {mutate} from 'shared-runtime';
4
5
-function Component({ propA, propB }) {
5
+function Component({propA, propB}) {
6
return useMemo(() => {
7
const x = {};
8
if (propA?.a) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useMemo-infer-less-specific-conditional-value-block.expect.md
+4
-4
@@ -3,10 +3,10 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
7
-import { identity, mutate } from "shared-runtime";
6
+import {useMemo} from 'react';
7
+import {identity, mutate} from 'shared-runtime';
8
9
-function Component({ propA, propB }) {
9
+function Component({propA, propB}) {
10
return useMemo(() => {
11
const x = {};
12
if (identity(null) ?? propA.a) {
@@ -25,7 +25,7 @@ function Component({ propA, propB }) {
25
26
```
27
4 |
28
- 5 | function Component({ propA, propB }) {
28
+ 5 | function Component({propA, propB}) {
29
> 6 | return useMemo(() => {
30
| ^^^^^^^
31
> 7 | const x = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useMemo-infer-less-specific-conditional-value-block.ts
+3
-3
@@ -1,8 +1,8 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
3
-import { identity, mutate } from "shared-runtime";
2
+import {useMemo} from 'react';
3
+import {identity, mutate} from 'shared-runtime';
4
5
-function Component({ propA, propB }) {
5
+function Component({propA, propB}) {
6
return useMemo(() => {
7
const x = {};
8
if (identity(null) ?? propA.a) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useMemo-property-call-chained-object.expect.md
+3
-3
@@ -3,9 +3,9 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
6
+import {useMemo} from 'react';
7
8
-function Component({ propA }) {
8
+function Component({propA}) {
9
return useMemo(() => {
10
return {
11
value: propA.x().y,
@@ -20,7 +20,7 @@ function Component({ propA }) {
20
21
```
22
3 |
23
- 4 | function Component({ propA }) {
23
+ 4 | function Component({propA}) {
24
> 5 | return useMemo(() => {
25
| ^^^^^^^
26
> 6 | return {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useMemo-property-call-chained-object.ts
+2
-2
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
2
+import {useMemo} from 'react';
3
4
-function Component({ propA }) {
4
+function Component({propA}) {
5
return useMemo(() => {
6
return {
7
value: propA.x().y,
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useMemo-property-call-dep.expect.md
+3
-3
@@ -3,9 +3,9 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
6
+import {useMemo} from 'react';
7
8
-function Component({ propA }) {
8
+function Component({propA}) {
9
return useMemo(() => {
10
return propA.x();
11
}, [propA.x]);
@@ -18,7 +18,7 @@ function Component({ propA }) {
18
19
```
20
3 |
21
- 4 | function Component({ propA }) {
21
+ 4 | function Component({propA}) {
22
> 5 | return useMemo(() => {
23
| ^^^^^^^
24
> 6 | return propA.x();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useMemo-property-call-dep.ts
+2
-2
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
2
+import {useMemo} from 'react';
3
4
-function Component({ propA }) {
4
+function Component({propA}) {
5
return useMemo(() => {
6
return propA.x();
7
}, [propA.x]);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useMemo-unrelated-mutation-in-depslist.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useMemo } from "react";
7
+import {useMemo} from 'react';
8
9
// Here, Forget infers that the memo block dependency is input1
10
// 1. StartMemoize is emitted before the function expression
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/error.useMemo-unrelated-mutation-in-depslist.ts
+1
-1
@@ -1,6 +1,6 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useMemo } from "react";
3
+import {useMemo} from 'react';
4
5
// Here, Forget infers that the memo block dependency is input1
6
// 1. StartMemoize is emitted before the function expression
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/maybe-invalid-useMemo-no-memoblock-sideeffect.expect.md
+3
-3
@@ -4,12 +4,12 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useMemo } from "react";
7
+import {useMemo} from 'react';
8
9
// This is currently considered valid because we don't ensure that every
10
// instruction within manual memoization gets assigned to a reactive scope
11
// (i.e. inferred non-mutable or non-escaping values don't get memoized)
12
-function useFoo({ minWidth, styles, setStyles }) {
12
+function useFoo({minWidth, styles, setStyles}) {
13
useMemo(() => {
14
if (styles.width > minWidth) {
15
setStyles(styles);
@@ -19,7 +19,7 @@ function useFoo({ minWidth, styles, setStyles }) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: useFoo,
22
- params: [{ minWidth: 2, styles: { width: 1 }, setStyles: () => {} }],
22
+ params: [{minWidth: 2, styles: {width: 1}, setStyles: () => {}}],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/maybe-invalid-useMemo-no-memoblock-sideeffect.ts
+3
-3
@@ -1,11 +1,11 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useMemo } from "react";
3
+import {useMemo} from 'react';
4
5
// This is currently considered valid because we don't ensure that every
6
// instruction within manual memoization gets assigned to a reactive scope
7
// (i.e. inferred non-mutable or non-escaping values don't get memoized)
8
-function useFoo({ minWidth, styles, setStyles }) {
8
+function useFoo({minWidth, styles, setStyles}) {
9
useMemo(() => {
10
if (styles.width > minWidth) {
11
setStyles(styles);
@@ -15,5 +15,5 @@ function useFoo({ minWidth, styles, setStyles }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: useFoo,
18
- params: [{ minWidth: 2, styles: { width: 1 }, setStyles: () => {} }],
18
+ params: [{minWidth: 2, styles: {width: 1}, setStyles: () => {}}],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/todo-ensure-constant-prop-decls-get-removed.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useMemo } from "react";
7
+import {useMemo} from 'react';
8
9
// Todo: we currently only generate a `constVal` declaration when
10
// validatePreserveExistingMemoizationGuarantees is enabled, as the
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/todo-ensure-constant-prop-decls-get-removed.ts
+1
-1
@@ -1,6 +1,6 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useMemo } from "react";
3
+import {useMemo} from 'react';
4
5
// Todo: we currently only generate a `constVal` declaration when
6
// validatePreserveExistingMemoizationGuarantees is enabled, as the
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-alias-property-load-dep.expect.md
+4
-4
@@ -3,10 +3,10 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useCallback } from "react";
7
-import { sum } from "shared-runtime";
6
+import {useCallback} from 'react';
7
+import {sum} from 'shared-runtime';
8
9
-function Component({ propA, propB }) {
9
+function Component({propA, propB}) {
10
const x = propB.x.y;
11
return useCallback(() => {
12
return sum(propA.x, x);
@@ -15,7 +15,7 @@ function Component({ propA, propB }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ propA: { x: 2 }, propB: { x: { y: 3 } } }],
18
+ params: [{propA: {x: 2}, propB: {x: {y: 3}}}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-alias-property-load-dep.ts
+4
-4
@@ -1,8 +1,8 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useCallback } from "react";
3
-import { sum } from "shared-runtime";
2
+import {useCallback} from 'react';
3
+import {sum} from 'shared-runtime';
4
5
-function Component({ propA, propB }) {
5
+function Component({propA, propB}) {
6
const x = propB.x.y;
7
return useCallback(() => {
8
return sum(propA.x, x);
@@ -11,5 +11,5 @@ function Component({ propA, propB }) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ propA: { x: 2 }, propB: { x: { y: 3 } } }],
14
+ params: [{propA: {x: 2}, propB: {x: {y: 3}}}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-captures-reassigned-context-property.expect.md
+4
-4
@@ -3,13 +3,13 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useCallback } from "react";
7
-import { Stringify } from "shared-runtime";
6
+import {useCallback} from 'react';
7
+import {Stringify} from 'shared-runtime';
8
9
function Foo(props) {
10
let contextVar;
11
if (props.cond) {
12
- contextVar = { val: 2 };
12
+ contextVar = {val: 2};
13
} else {
14
contextVar = {};
15
}
@@ -21,7 +21,7 @@ function Foo(props) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: Foo,
24
- params: [{ cond: true }],
24
+ params: [{cond: true}],
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-captures-reassigned-context-property.tsx
+4
-4
@@ -1,11 +1,11 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useCallback } from "react";
3
-import { Stringify } from "shared-runtime";
2
+import {useCallback} from 'react';
3
+import {Stringify} from 'shared-runtime';
4
5
function Foo(props) {
6
let contextVar;
7
if (props.cond) {
8
- contextVar = { val: 2 };
8
+ contextVar = {val: 2};
9
} else {
10
contextVar = {};
11
}
@@ -17,5 +17,5 @@ function Foo(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Foo,
20
- params: [{ cond: true }],
20
+ params: [{cond: true}],
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-captures-reassigned-context.expect.md
+2
-2
@@ -4,8 +4,8 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useCallback } from "react";
8
-import { makeArray } from "shared-runtime";
7
+import {useCallback} from 'react';
8
+import {makeArray} from 'shared-runtime';
9
10
// This case is fine, as all reassignments happen before the useCallback
11
function Foo(props) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-captures-reassigned-context.ts
+2
-2
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useCallback } from "react";
4
-import { makeArray } from "shared-runtime";
3
+import {useCallback} from 'react';
4
+import {makeArray} from 'shared-runtime';
5
6
// This case is fine, as all reassignments happen before the useCallback
7
function Foo(props) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-conditional-access-own-scope.expect.md
+3
-3
@@ -3,9 +3,9 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useCallback } from "react";
6
+import {useCallback} from 'react';
7
8
-function Component({ propA, propB }) {
8
+function Component({propA, propB}) {
9
return useCallback(() => {
10
if (propA) {
11
return {
@@ -17,7 +17,7 @@ function Component({ propA, propB }) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ propA: 1, propB: { x: { y: [] } } }],
20
+ params: [{propA: 1, propB: {x: {y: []}}}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-conditional-access-own-scope.ts
+3
-3
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useCallback } from "react";
2
+import {useCallback} from 'react';
3
4
-function Component({ propA, propB }) {
4
+function Component({propA, propB}) {
5
return useCallback(() => {
6
if (propA) {
7
return {
@@ -13,5 +13,5 @@ function Component({ propA, propB }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ propA: 1, propB: { x: { y: [] } } }],
16
+ params: [{propA: 1, propB: {x: {y: []}}}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-in-other-reactive-block.expect.md
+3
-3
@@ -3,8 +3,8 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useCallback, useState } from "react";
7
-import { arrayPush } from "shared-runtime";
6
+import {useCallback, useState} from 'react';
7
+import {arrayPush} from 'shared-runtime';
8
9
// useCallback-produced values can exist in nested reactive blocks, as long
10
// as their reactive dependencies are a subset of depslist from source
@@ -22,7 +22,7 @@ function useFoo(minWidth, otherProp) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: useFoo,
25
- params: [2, "other"],
25
+ params: [2, 'other'],
26
};
27
28
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-in-other-reactive-block.ts
+3
-3
@@ -1,6 +1,6 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useCallback, useState } from "react";
3
-import { arrayPush } from "shared-runtime";
2
+import {useCallback, useState} from 'react';
3
+import {arrayPush} from 'shared-runtime';
4
5
// useCallback-produced values can exist in nested reactive blocks, as long
6
// as their reactive dependencies are a subset of depslist from source
@@ -18,5 +18,5 @@ function useFoo(minWidth, otherProp) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: useFoo,
21
- params: [2, "other"],
21
+ params: [2, 'other'],
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-infer-conditional-value-block.expect.md
+3
-3
@@ -3,8 +3,8 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useCallback } from "react";
7
-import { identity, mutate } from "shared-runtime";
6
+import {useCallback} from 'react';
7
+import {identity, mutate} from 'shared-runtime';
8
9
function useHook(propA, propB) {
10
return useCallback(() => {
@@ -20,7 +20,7 @@ function useHook(propA, propB) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: useHook,
23
- params: [{ a: 1 }, { x: { y: 3 } }],
23
+ params: [{a: 1}, {x: {y: 3}}],
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-infer-conditional-value-block.ts
+3
-3
@@ -1,6 +1,6 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useCallback } from "react";
3
-import { identity, mutate } from "shared-runtime";
2
+import {useCallback} from 'react';
3
+import {identity, mutate} from 'shared-runtime';
4
5
function useHook(propA, propB) {
6
return useCallback(() => {
@@ -16,5 +16,5 @@ function useHook(propA, propB) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: useHook,
19
- params: [{ a: 1 }, { x: { y: 3 } }],
19
+ params: [{a: 1}, {x: {y: 3}}],
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-infer-fewer-deps.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useCallback } from "react";
7
+import {useCallback} from 'react';
8
9
// It's correct to produce memo blocks with fewer deps than source
10
function useFoo(a, b) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-infer-fewer-deps.ts
+1
-1
@@ -1,6 +1,6 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useCallback } from "react";
3
+import {useCallback} from 'react';
4
5
// It's correct to produce memo blocks with fewer deps than source
6
function useFoo(a, b) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-infer-more-specific.expect.md
+2
-2
@@ -4,7 +4,7 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useCallback } from "react";
7
+import {useCallback} from 'react';
8
9
// More specific memoization always results in fewer memo block
10
// executions.
@@ -17,7 +17,7 @@ function useHook(x) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: useHook,
20
- params: [{ y: { z: 2 } }],
20
+ params: [{y: {z: 2}}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-infer-more-specific.ts
+2
-2
@@ -1,6 +1,6 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useCallback } from "react";
3
+import {useCallback} from 'react';
4
5
// More specific memoization always results in fewer memo block
6
// executions.
@@ -13,5 +13,5 @@ function useHook(x) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: useHook,
16
- params: [{ y: { z: 2 } }],
16
+ params: [{y: {z: 2}}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-infer-read-dep.expect.md
+2
-2
@@ -3,8 +3,8 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useCallback } from "react";
7
-import { sum } from "shared-runtime";
6
+import {useCallback} from 'react';
7
+import {sum} from 'shared-runtime';
8
9
function useFoo() {
10
const val = [1, 2, 3];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-infer-read-dep.ts
+2
-2
@@ -1,6 +1,6 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useCallback } from "react";
3
-import { sum } from "shared-runtime";
2
+import {useCallback} from 'react';
3
+import {sum} from 'shared-runtime';
4
5
function useFoo() {
6
const val = [1, 2, 3];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-infer-scope-global.expect.md
+2
-2
@@ -4,8 +4,8 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useCallback } from "react";
8
-import { CONST_STRING0 } from "shared-runtime";
7
+import {useCallback} from 'react';
8
+import {CONST_STRING0} from 'shared-runtime';
9
10
// It's correct to infer a useCallback block has no reactive dependencies
11
function useFoo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-infer-scope-global.ts
+2
-2
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useCallback } from "react";
4
-import { CONST_STRING0 } from "shared-runtime";
3
+import {useCallback} from 'react';
4
+import {CONST_STRING0} from 'shared-runtime';
5
6
// It's correct to infer a useCallback block has no reactive dependencies
7
function useFoo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-nonescaping-invoked-callback-escaping-return.expect.md
+3
-3
@@ -3,9 +3,9 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees @enableAssumeHooksFollowRulesOfReact @enableTransitivelyFreezeFunctionExpressions
6
-import { useCallback } from "react";
6
+import {useCallback} from 'react';
7
8
-function Component({ entity, children }) {
8
+function Component({entity, children}) {
9
const showMessage = useCallback(() => entity != null);
10
11
// We currently model functions as if they could escape intor their return value
@@ -25,7 +25,7 @@ export const FIXTURE_ENTRYPOINT = {
25
fn: Component,
26
params: [
27
{
28
- entity: { name: "Sathya" },
28
+ entity: {name: 'Sathya'},
29
children: [<div key="gsathya">Hi Sathya!</div>],
30
},
31
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-nonescaping-invoked-callback-escaping-return.js
+3
-3
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees @enableAssumeHooksFollowRulesOfReact @enableTransitivelyFreezeFunctionExpressions
2
-import { useCallback } from "react";
2
+import {useCallback} from 'react';
3
4
-function Component({ entity, children }) {
4
+function Component({entity, children}) {
5
const showMessage = useCallback(() => entity != null);
6
7
// We currently model functions as if they could escape intor their return value
@@ -21,7 +21,7 @@ export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
params: [
23
{
24
- entity: { name: "Sathya" },
24
+ entity: {name: 'Sathya'},
25
children: [<div key="gsathya">Hi Sathya!</div>],
26
},
27
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-nonescaping.expect.md
+3
-3
@@ -3,9 +3,9 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees @enableAssumeHooksFollowRulesOfReact @enableTransitivelyFreezeFunctionExpressions
6
-import { useCallback } from "react";
6
+import {useCallback} from 'react';
7
8
-function Component({ entity, children }) {
8
+function Component({entity, children}) {
9
// showMessage doesn't escape so we don't memoize it.
10
// However, validatePreserveExistingMemoizationGuarantees only sees that the scope
11
// doesn't exist, and thinks the memoization was missed instead of being intentionally dropped.
@@ -22,7 +22,7 @@ export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
params: [
24
{
25
- entity: { name: "Sathya" },
25
+ entity: {name: 'Sathya'},
26
children: [<div key="gsathya">Hi Sathya!</div>],
27
},
28
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-nonescaping.js
+3
-3
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees @enableAssumeHooksFollowRulesOfReact @enableTransitivelyFreezeFunctionExpressions
2
-import { useCallback } from "react";
2
+import {useCallback} from 'react';
3
4
-function Component({ entity, children }) {
4
+function Component({entity, children}) {
5
// showMessage doesn't escape so we don't memoize it.
6
// However, validatePreserveExistingMemoizationGuarantees only sees that the scope
7
// doesn't exist, and thinks the memoization was missed instead of being intentionally dropped.
@@ -18,7 +18,7 @@ export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
params: [
20
{
21
- entity: { name: "Sathya" },
21
+ entity: {name: 'Sathya'},
22
children: [<div key="gsathya">Hi Sathya!</div>],
23
},
24
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-reordering-deplist-controlflow.expect.md
+7
-7
@@ -2,16 +2,16 @@
2
## Input
3
4
```javascript
5
-import { useCallback } from "react";
6
-import { Stringify } from "shared-runtime";
5
+import {useCallback} from 'react';
6
+import {Stringify} from 'shared-runtime';
7
8
-function Foo({ arr1, arr2, foo }) {
8
+function Foo({arr1, arr2, foo}) {
9
const x = [arr1];
10
11
let y = [];
12
13
const getVal1 = useCallback(() => {
14
- return { x: 2 };
14
+ return {x: 2};
15
}, []);
16
17
const getVal2 = useCallback(() => {
@@ -23,10 +23,10 @@ function Foo({ arr1, arr2, foo }) {
23
24
export const FIXTURE_ENTRYPOINT = {
25
fn: Foo,
26
- params: [{ arr1: [1, 2], arr2: [3, 4], foo: true }],
26
+ params: [{arr1: [1, 2], arr2: [3, 4], foo: true}],
27
sequentialRenders: [
28
- { arr1: [1, 2], arr2: [3, 4], foo: true },
29
- { arr1: [1, 2], arr2: [3, 4], foo: false },
28
+ {arr1: [1, 2], arr2: [3, 4], foo: true},
29
+ {arr1: [1, 2], arr2: [3, 4], foo: false},
30
],
31
};
32
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-reordering-deplist-controlflow.tsx
+7
-7
@@ -1,13 +1,13 @@
1
-import { useCallback } from "react";
2
-import { Stringify } from "shared-runtime";
1
+import {useCallback} from 'react';
2
+import {Stringify} from 'shared-runtime';
3
4
-function Foo({ arr1, arr2, foo }) {
4
+function Foo({arr1, arr2, foo}) {
5
const x = [arr1];
6
7
let y = [];
8
9
const getVal1 = useCallback(() => {
10
- return { x: 2 };
10
+ return {x: 2};
11
}, []);
12
13
const getVal2 = useCallback(() => {
@@ -19,9 +19,9 @@ function Foo({ arr1, arr2, foo }) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Foo,
22
- params: [{ arr1: [1, 2], arr2: [3, 4], foo: true }],
22
+ params: [{arr1: [1, 2], arr2: [3, 4], foo: true}],
23
sequentialRenders: [
24
- { arr1: [1, 2], arr2: [3, 4], foo: true },
25
- { arr1: [1, 2], arr2: [3, 4], foo: false },
24
+ {arr1: [1, 2], arr2: [3, 4], foo: true},
25
+ {arr1: [1, 2], arr2: [3, 4], foo: false},
26
],
27
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-reordering-depslist-assignment.expect.md
+3
-3
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import { useCallback } from "react";
6
-import { Stringify } from "shared-runtime";
5
+import {useCallback} from 'react';
6
+import {Stringify} from 'shared-runtime';
7
8
// We currently produce invalid output (incorrect scoping for `y` declaration)
9
function useFoo(arr1, arr2) {
@@ -11,7 +11,7 @@ function useFoo(arr1, arr2) {
11
12
let y;
13
const getVal = useCallback(() => {
14
- return { y };
14
+ return {y};
15
}, [((y = x.concat(arr2)), y)]);
16
17
return <Stringify getVal={getVal} shouldInvokeFns={true} />;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-reordering-depslist-assignment.tsx
+3
-3
@@ -1,5 +1,5 @@
1
-import { useCallback } from "react";
2
-import { Stringify } from "shared-runtime";
1
+import {useCallback} from 'react';
2
+import {Stringify} from 'shared-runtime';
3
4
// We currently produce invalid output (incorrect scoping for `y` declaration)
5
function useFoo(arr1, arr2) {
@@ -7,7 +7,7 @@ function useFoo(arr1, arr2) {
7
8
let y;
9
const getVal = useCallback(() => {
10
- return { y };
10
+ return {y};
11
}, [((y = x.concat(arr2)), y)]);
12
13
return <Stringify getVal={getVal} shouldInvokeFns={true} />;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-with-no-depslist.expect.md
+3
-3
@@ -3,11 +3,11 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useCallback } from "react";
6
+import {useCallback} from 'react';
7
8
// Compiler can produce any memoization it finds valid if the
9
// source listed no memo deps
10
-function Component({ propA }) {
10
+function Component({propA}) {
11
// @ts-ignore
12
return useCallback(() => {
13
return [propA];
@@ -16,7 +16,7 @@ function Component({ propA }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ propA: 2 }],
19
+ params: [{propA: 2}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useCallback-with-no-depslist.ts
+3
-3
@@ -1,9 +1,9 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useCallback } from "react";
2
+import {useCallback} from 'react';
3
4
// Compiler can produce any memoization it finds valid if the
5
// source listed no memo deps
6
-function Component({ propA }) {
6
+function Component({propA}) {
7
// @ts-ignore
8
return useCallback(() => {
9
return [propA];
@@ -12,5 +12,5 @@ function Component({ propA }) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ propA: 2 }],
15
+ params: [{propA: 2}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-alias-property-load-dep.expect.md
+4
-4
@@ -3,10 +3,10 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
7
-import { sum } from "shared-runtime";
6
+import {useMemo} from 'react';
7
+import {sum} from 'shared-runtime';
8
9
-function Component({ propA, propB }) {
9
+function Component({propA, propB}) {
10
const x = propB.x.y;
11
return useMemo(() => {
12
return sum(propA.x, x);
@@ -15,7 +15,7 @@ function Component({ propA, propB }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ propA: { x: 2 }, propB: { x: { y: 3 } } }],
18
+ params: [{propA: {x: 2}, propB: {x: {y: 3}}}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-alias-property-load-dep.ts
+4
-4
@@ -1,8 +1,8 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
3
-import { sum } from "shared-runtime";
2
+import {useMemo} from 'react';
3
+import {sum} from 'shared-runtime';
4
5
-function Component({ propA, propB }) {
5
+function Component({propA, propB}) {
6
const x = propB.x.y;
7
return useMemo(() => {
8
return sum(propA.x, x);
@@ -11,5 +11,5 @@ function Component({ propA, propB }) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ propA: { x: 2 }, propB: { x: { y: 3 } } }],
14
+ params: [{propA: {x: 2}, propB: {x: {y: 3}}}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-conditional-access-alloc.expect.md
+4
-4
@@ -3,10 +3,10 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
7
-import { identity } from "shared-runtime";
6
+import {useMemo} from 'react';
7
+import {identity} from 'shared-runtime';
8
9
-function Component({ propA, propB }) {
9
+function Component({propA, propB}) {
10
return useMemo(() => {
11
return {
12
value: identity(propB?.x.y),
@@ -17,7 +17,7 @@ function Component({ propA, propB }) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ propA: 2, propB: { x: { y: [] } } }],
20
+ params: [{propA: 2, propB: {x: {y: []}}}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-conditional-access-alloc.ts
+4
-4
@@ -1,8 +1,8 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
3
-import { identity } from "shared-runtime";
2
+import {useMemo} from 'react';
3
+import {identity} from 'shared-runtime';
4
5
-function Component({ propA, propB }) {
5
+function Component({propA, propB}) {
6
return useMemo(() => {
7
return {
8
value: identity(propB?.x.y),
@@ -13,5 +13,5 @@ function Component({ propA, propB }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ propA: 2, propB: { x: { y: [] } } }],
16
+ params: [{propA: 2, propB: {x: {y: []}}}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-conditional-access-noAlloc.expect.md
+3
-3
@@ -3,9 +3,9 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
6
+import {useMemo} from 'react';
7
8
-function Component({ propA, propB }) {
8
+function Component({propA, propB}) {
9
return useMemo(() => {
10
return {
11
value: propB?.x.y,
@@ -16,7 +16,7 @@ function Component({ propA, propB }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ propA: 2, propB: { x: { y: [] } } }],
19
+ params: [{propA: 2, propB: {x: {y: []}}}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-conditional-access-noAlloc.ts
+3
-3
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
2
+import {useMemo} from 'react';
3
4
-function Component({ propA, propB }) {
4
+function Component({propA, propB}) {
5
return useMemo(() => {
6
return {
7
value: propB?.x.y,
@@ -12,5 +12,5 @@ function Component({ propA, propB }) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ propA: 2, propB: { x: { y: [] } } }],
15
+ params: [{propA: 2, propB: {x: {y: []}}}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-conditional-access-own-scope.expect.md
+3
-3
@@ -3,9 +3,9 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
6
+import {useMemo} from 'react';
7
8
-function Component({ propA, propB }) {
8
+function Component({propA, propB}) {
9
return useMemo(() => {
10
if (propA) {
11
return {
@@ -17,7 +17,7 @@ function Component({ propA, propB }) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ propA: 1, propB: { x: { y: [] } } }],
20
+ params: [{propA: 1, propB: {x: {y: []}}}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-conditional-access-own-scope.ts
+3
-3
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
2
+import {useMemo} from 'react';
3
4
-function Component({ propA, propB }) {
4
+function Component({propA, propB}) {
5
return useMemo(() => {
6
if (propA) {
7
return {
@@ -13,5 +13,5 @@ function Component({ propA, propB }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ propA: 1, propB: { x: { y: [] } } }],
16
+ params: [{propA: 1, propB: {x: {y: []}}}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-constant-prop.expect.md
+2
-2
@@ -3,8 +3,8 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
7
-import { identity } from "shared-runtime";
6
+import {useMemo} from 'react';
7
+import {identity} from 'shared-runtime';
8
9
function useFoo(cond) {
10
const sourceDep = 0;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-constant-prop.ts
+2
-2
@@ -1,6 +1,6 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
3
-import { identity } from "shared-runtime";
2
+import {useMemo} from 'react';
3
+import {identity} from 'shared-runtime';
4
5
function useFoo(cond) {
6
const sourceDep = 0;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-dropped-infer-always-invalidating.expect.md
+2
-2
@@ -4,8 +4,8 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useMemo } from "react";
8
-import { useHook } from "shared-runtime";
7
+import {useMemo} from 'react';
8
+import {useHook} from 'shared-runtime';
9
10
// useMemo values may not be memoized in Forget output if we
11
// infer that their deps always invalidate.
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-dropped-infer-always-invalidating.ts
+2
-2
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useMemo } from "react";
4
-import { useHook } from "shared-runtime";
3
+import {useMemo} from 'react';
4
+import {useHook} from 'shared-runtime';
5
6
// useMemo values may not be memoized in Forget output if we
7
// infer that their deps always invalidate.
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-in-other-reactive-block.expect.md
+3
-3
@@ -3,8 +3,8 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo, useState } from "react";
7
-import { arrayPush } from "shared-runtime";
6
+import {useMemo, useState} from 'react';
7
+import {arrayPush} from 'shared-runtime';
8
9
// useMemo-produced values can exist in nested reactive blocks, as long
10
// as their reactive dependencies are a subset of depslist from source
@@ -22,7 +22,7 @@ function useFoo(minWidth, otherProp) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: useFoo,
25
- params: [2, "other"],
25
+ params: [2, 'other'],
26
};
27
28
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-in-other-reactive-block.ts
+3
-3
@@ -1,6 +1,6 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo, useState } from "react";
3
-import { arrayPush } from "shared-runtime";
2
+import {useMemo, useState} from 'react';
3
+import {arrayPush} from 'shared-runtime';
4
5
// useMemo-produced values can exist in nested reactive blocks, as long
6
// as their reactive dependencies are a subset of depslist from source
@@ -18,5 +18,5 @@ function useFoo(minWidth, otherProp) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: useFoo,
21
- params: [2, "other"],
21
+ params: [2, 'other'],
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-infer-fewer-deps.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useMemo } from "react";
7
+import {useMemo} from 'react';
8
9
// It's correct to produce memo blocks with fewer deps than source
10
function useFoo(a, b) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-infer-fewer-deps.ts
+1
-1
@@ -1,6 +1,6 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useMemo } from "react";
3
+import {useMemo} from 'react';
4
5
// It's correct to produce memo blocks with fewer deps than source
6
function useFoo(a, b) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-infer-more-specific.expect.md
+2
-2
@@ -4,7 +4,7 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useMemo } from "react";
7
+import {useMemo} from 'react';
8
9
// More specific memoization always results in fewer memo block
10
// executions.
@@ -17,7 +17,7 @@ function useHook(x) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: useHook,
20
- params: [{ y: { z: 2 } }],
20
+ params: [{y: {z: 2}}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-infer-more-specific.ts
+2
-2
@@ -1,6 +1,6 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useMemo } from "react";
3
+import {useMemo} from 'react';
4
5
// More specific memoization always results in fewer memo block
6
// executions.
@@ -13,5 +13,5 @@ function useHook(x) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: useHook,
16
- params: [{ y: { z: 2 } }],
16
+ params: [{y: {z: 2}}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-infer-nonallocating.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useMemo } from "react";
7
+import {useMemo} from 'react';
8
9
// It's correct to infer a useMemo value is non-allocating
10
// and not provide it with a reactive scope
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-infer-nonallocating.ts
+1
-1
@@ -1,6 +1,6 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useMemo } from "react";
3
+import {useMemo} from 'react';
4
5
// It's correct to infer a useMemo value is non-allocating
6
// and not provide it with a reactive scope
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-infer-scope-global.expect.md
+2
-2
@@ -4,8 +4,8 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useMemo } from "react";
8
-import { CONST_STRING0 } from "shared-runtime";
7
+import {useMemo} from 'react';
8
+import {CONST_STRING0} from 'shared-runtime';
9
10
// It's correct to infer a useMemo block has no reactive dependencies
11
function useFoo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-infer-scope-global.ts
+2
-2
@@ -1,7 +1,7 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useMemo } from "react";
4
-import { CONST_STRING0 } from "shared-runtime";
3
+import {useMemo} from 'react';
4
+import {CONST_STRING0} from 'shared-runtime';
5
6
// It's correct to infer a useMemo block has no reactive dependencies
7
function useFoo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-inner-decl.expect.md
+4
-4
@@ -3,19 +3,19 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
7
-import { identity } from "shared-runtime";
6
+import {useMemo} from 'react';
7
+import {identity} from 'shared-runtime';
8
9
function useFoo(data) {
10
return useMemo(() => {
11
const temp = identity(data.a);
12
- return { temp };
12
+ return {temp};
13
}, [data.a]);
14
}
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: useFoo,
18
- params: [{ a: 2 }],
18
+ params: [{a: 2}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-inner-decl.ts
+4
-4
@@ -1,15 +1,15 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
3
-import { identity } from "shared-runtime";
2
+import {useMemo} from 'react';
3
+import {identity} from 'shared-runtime';
4
5
function useFoo(data) {
6
return useMemo(() => {
7
const temp = identity(data.a);
8
- return { temp };
8
+ return {temp};
9
}, [data.a]);
10
}
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: useFoo,
14
- params: [{ a: 2 }],
14
+ params: [{a: 2}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-invoke-prop.expect.md
+3
-3
@@ -4,9 +4,9 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { useMemo } from "react";
7
+import {useMemo} from 'react';
8
9
-function useFoo({ callback }) {
9
+function useFoo({callback}) {
10
return useMemo(() => new Array(callback()), [callback]);
11
}
12
@@ -15,7 +15,7 @@ export const FIXTURE_ENTRYPOINT = {
15
params: [
16
{
17
callback: () => {
18
- "use no forget";
18
+ 'use no forget';
19
return [1, 2, 3];
20
},
21
},
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-invoke-prop.ts
+3
-3
@@ -1,8 +1,8 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { useMemo } from "react";
3
+import {useMemo} from 'react';
4
5
-function useFoo({ callback }) {
5
+function useFoo({callback}) {
6
return useMemo(() => new Array(callback()), [callback]);
7
}
8
@@ -11,7 +11,7 @@ export const FIXTURE_ENTRYPOINT = {
11
params: [
12
{
13
callback: () => {
14
- "use no forget";
14
+ 'use no forget';
15
return [1, 2, 3];
16
},
17
},
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-reordering-depslist-assignment.expect.md
+2
-2
@@ -2,14 +2,14 @@
2
## Input
3
4
```javascript
5
-import { useMemo } from "react";
5
+import {useMemo} from 'react';
6
7
function useFoo(arr1, arr2) {
8
const x = [arr1];
9
10
let y;
11
return useMemo(() => {
12
- return { y };
12
+ return {y};
13
}, [((y = x.concat(arr2)), y)]);
14
}
15
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-reordering-depslist-assignment.ts
+2
-2
@@ -1,11 +1,11 @@
1
-import { useMemo } from "react";
1
+import {useMemo} from 'react';
2
3
function useFoo(arr1, arr2) {
4
const x = [arr1];
5
6
let y;
7
return useMemo(() => {
8
- return { y };
8
+ return {y};
9
}, [((y = x.concat(arr2)), y)]);
10
}
11
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-reordering-depslist-controlflow.expect.md
+7
-7
@@ -2,16 +2,16 @@
2
## Input
3
4
```javascript
5
-import { useMemo } from "react";
6
-import { Stringify } from "shared-runtime";
5
+import {useMemo} from 'react';
6
+import {Stringify} from 'shared-runtime';
7
8
-function Foo({ arr1, arr2, foo }) {
8
+function Foo({arr1, arr2, foo}) {
9
const x = [arr1];
10
11
let y = [];
12
13
const val1 = useMemo(() => {
14
- return { x: 2 };
14
+ return {x: 2};
15
}, []);
16
17
const val2 = useMemo(() => {
@@ -23,10 +23,10 @@ function Foo({ arr1, arr2, foo }) {
23
24
export const FIXTURE_ENTRYPOINT = {
25
fn: Foo,
26
- params: [{ arr1: [1, 2], arr2: [3, 4], foo: true }],
26
+ params: [{arr1: [1, 2], arr2: [3, 4], foo: true}],
27
sequentialRenders: [
28
- { arr1: [1, 2], arr2: [3, 4], foo: true },
29
- { arr1: [1, 2], arr2: [3, 4], foo: false },
28
+ {arr1: [1, 2], arr2: [3, 4], foo: true},
29
+ {arr1: [1, 2], arr2: [3, 4], foo: false},
30
],
31
};
32
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-reordering-depslist-controlflow.tsx
+7
-7
@@ -1,13 +1,13 @@
1
-import { useMemo } from "react";
2
-import { Stringify } from "shared-runtime";
1
+import {useMemo} from 'react';
2
+import {Stringify} from 'shared-runtime';
3
4
-function Foo({ arr1, arr2, foo }) {
4
+function Foo({arr1, arr2, foo}) {
5
const x = [arr1];
6
7
let y = [];
8
9
const val1 = useMemo(() => {
10
- return { x: 2 };
10
+ return {x: 2};
11
}, []);
12
13
const val2 = useMemo(() => {
@@ -19,9 +19,9 @@ function Foo({ arr1, arr2, foo }) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Foo,
22
- params: [{ arr1: [1, 2], arr2: [3, 4], foo: true }],
22
+ params: [{arr1: [1, 2], arr2: [3, 4], foo: true}],
23
sequentialRenders: [
24
- { arr1: [1, 2], arr2: [3, 4], foo: true },
25
- { arr1: [1, 2], arr2: [3, 4], foo: false },
24
+ {arr1: [1, 2], arr2: [3, 4], foo: true},
25
+ {arr1: [1, 2], arr2: [3, 4], foo: false},
26
],
27
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-with-no-depslist.expect.md
+3
-3
@@ -3,11 +3,11 @@
3
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
6
+import {useMemo} from 'react';
7
8
// Compiler can produce any memoization it finds valid if the
9
// source listed no memo deps
10
-function Component({ propA }) {
10
+function Component({propA}) {
11
// @ts-ignore
12
return useMemo(() => {
13
return [propA];
@@ -16,7 +16,7 @@ function Component({ propA }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ propA: 2 }],
19
+ params: [{propA: 2}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/preserve-memo-validation/useMemo-with-no-depslist.ts
+3
-3
@@ -1,9 +1,9 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
2
+import {useMemo} from 'react';
3
4
// Compiler can produce any memoization it finds valid if the
5
// source listed no memo deps
6
-function Component({ propA }) {
6
+function Component({propA}) {
7
// @ts-ignore
8
return useMemo(() => {
9
return [propA];
@@ -12,5 +12,5 @@ function Component({ propA }) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ propA: 2 }],
15
+ params: [{propA: 2}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/primitive-alias-mutate.expect.md
+3
-3
@@ -3,11 +3,11 @@
3
4
```javascript
5
function component(a) {
6
- let x = "foo";
6
+ let x = 'foo';
7
if (a) {
8
- x = "bar";
8
+ x = 'bar';
9
} else {
10
- x = "baz";
10
+ x = 'baz';
11
}
12
let y = x;
13
mutate(y);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/primitive-alias-mutate.js
+3
-3
@@ -1,9 +1,9 @@
1
function component(a) {
2
- let x = "foo";
2
+ let x = 'foo';
3
if (a) {
4
- x = "bar";
4
+ x = 'bar';
5
} else {
6
- x = "baz";
6
+ x = 'baz';
7
}
8
let y = x;
9
mutate(y);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/primitive-as-dep-nested-scope.expect.md
+6
-6
@@ -7,7 +7,7 @@
7
// separately from props.b)
8
// Correctness:
9
10
-import { identity, mutate, setProperty } from "shared-runtime";
10
+import {identity, mutate, setProperty} from 'shared-runtime';
11
12
// y depends on either props.b or props.b + 1
13
function PrimitiveAsDepNested(props) {
@@ -20,16 +20,16 @@ function PrimitiveAsDepNested(props) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: PrimitiveAsDepNested,
23
- params: [{ a: 1, b: 2 }],
23
+ params: [{a: 1, b: 2}],
24
sequentialRenders: [
25
// change b
26
- { a: 1, b: 3 },
26
+ {a: 1, b: 3},
27
// change b
28
- { a: 1, b: 4 },
28
+ {a: 1, b: 4},
29
// change a
30
- { a: 2, b: 4 },
30
+ {a: 2, b: 4},
31
// change a
32
- { a: 3, b: 4 },
32
+ {a: 3, b: 4},
33
],
34
};
35
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/primitive-as-dep-nested-scope.js
+6
-6
@@ -3,7 +3,7 @@
3
// separately from props.b)
4
// Correctness:
5
6
-import { identity, mutate, setProperty } from "shared-runtime";
6
+import {identity, mutate, setProperty} from 'shared-runtime';
7
8
// y depends on either props.b or props.b + 1
9
function PrimitiveAsDepNested(props) {
@@ -16,15 +16,15 @@ function PrimitiveAsDepNested(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: PrimitiveAsDepNested,
19
- params: [{ a: 1, b: 2 }],
19
+ params: [{a: 1, b: 2}],
20
sequentialRenders: [
21
// change b
22
- { a: 1, b: 3 },
22
+ {a: 1, b: 3},
23
// change b
24
- { a: 1, b: 4 },
24
+ {a: 1, b: 4},
25
// change a
26
- { a: 2, b: 4 },
26
+ {a: 2, b: 4},
27
// change a
28
- { a: 3, b: 4 },
28
+ {a: 3, b: 4},
29
],
30
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/primitive-reassigned-loop-force-scopes-enabled.expect.md
+6
-6
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @enableForest
6
-function Component({ base, start, increment, test }) {
6
+function Component({base, start, increment, test}) {
7
let value = base;
8
for (let i = start; i < test; i += increment) {
9
value += i;
@@ -13,12 +13,12 @@ function Component({ base, start, increment, test }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ base: 0, start: 0, test: 10, increment: 1 }],
16
+ params: [{base: 0, start: 0, test: 10, increment: 1}],
17
sequentialRenders: [
18
- { base: 0, start: 1, test: 10, increment: 1 },
19
- { base: 0, start: 0, test: 10, increment: 2 },
20
- { base: 2, start: 0, test: 10, increment: 2 },
21
- { base: 0, start: 0, test: 11, increment: 2 },
18
+ {base: 0, start: 1, test: 10, increment: 1},
19
+ {base: 0, start: 0, test: 10, increment: 2},
20
+ {base: 2, start: 0, test: 10, increment: 2},
21
+ {base: 0, start: 0, test: 11, increment: 2},
22
],
23
};
24
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/primitive-reassigned-loop-force-scopes-enabled.js
+6
-6
@@ -1,5 +1,5 @@
1
// @enableForest
2
-function Component({ base, start, increment, test }) {
2
+function Component({base, start, increment, test}) {
3
let value = base;
4
for (let i = start; i < test; i += increment) {
5
value += i;
@@ -9,11 +9,11 @@ function Component({ base, start, increment, test }) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: [{ base: 0, start: 0, test: 10, increment: 1 }],
12
+ params: [{base: 0, start: 0, test: 10, increment: 1}],
13
sequentialRenders: [
14
- { base: 0, start: 1, test: 10, increment: 1 },
15
- { base: 0, start: 0, test: 10, increment: 2 },
16
- { base: 2, start: 0, test: 10, increment: 2 },
17
- { base: 0, start: 0, test: 11, increment: 2 },
14
+ {base: 0, start: 1, test: 10, increment: 1},
15
+ {base: 0, start: 0, test: 10, increment: 2},
16
+ {base: 2, start: 0, test: 10, increment: 2},
17
+ {base: 0, start: 0, test: 11, increment: 2},
18
],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/prop-capturing-function-1.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a, b) {
6
- let z = { a, b };
6
+ let z = {a, b};
7
let x = function () {
8
console.log(z);
9
};
@@ -12,8 +12,8 @@ function component(a, b) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: component,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/prop-capturing-function-1.js
+3
-3
@@ -1,5 +1,5 @@
1
function component(a, b) {
2
- let z = { a, b };
2
+ let z = {a, b};
3
let x = function () {
4
console.log(z);
5
};
@@ -8,6 +8,6 @@ function component(a, b) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: component,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/property-call-evaluation-order.expect.md
+4
-4
@@ -5,14 +5,14 @@
5
// Should print A, arg, original
6
7
function Component() {
8
- const changeF = (o) => {
9
- o.f = () => console.log("new");
8
+ const changeF = o => {
9
+ o.f = () => console.log('new');
10
};
11
const x = {
12
- f: () => console.log("original"),
12
+ f: () => console.log('original'),
13
};
14
15
- (console.log("A"), x).f((changeF(x), console.log("arg"), 1));
15
+ (console.log('A'), x).f((changeF(x), console.log('arg'), 1));
16
return x;
17
}
18
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/property-call-evaluation-order.js
+4
-4
@@ -1,14 +1,14 @@
1
// Should print A, arg, original
2
3
function Component() {
4
- const changeF = (o) => {
5
- o.f = () => console.log("new");
4
+ const changeF = o => {
5
+ o.f = () => console.log('new');
6
};
7
const x = {
8
- f: () => console.log("original"),
8
+ f: () => console.log('original'),
9
};
10
11
- (console.log("A"), x).f((changeF(x), console.log("arg"), 1));
11
+ (console.log('A'), x).f((changeF(x), console.log('arg'), 1));
12
return x;
13
}
14
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/prune-scopes-whose-deps-invalidate-array.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useHook } from "shared-runtime";
5
+import {useHook} from 'shared-runtime';
6
7
function Component(props) {
8
const x = [];
@@ -16,7 +16,7 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ value: "sathya" }],
19
+ params: [{value: 'sathya'}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/prune-scopes-whose-deps-invalidate-array.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { useHook } from "shared-runtime";
1
+import {useHook} from 'shared-runtime';
2
3
function Component(props) {
4
const x = [];
@@ -12,5 +12,5 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ value: "sathya" }],
15
+ params: [{value: 'sathya'}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/prune-scopes-whose-deps-invalidate-jsx.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useHook } from "shared-runtime";
5
+import {useHook} from 'shared-runtime';
6
7
function Component(props) {
8
const o = {};
@@ -17,7 +17,7 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ value: "sathya" }],
20
+ params: [{value: 'sathya'}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/prune-scopes-whose-deps-invalidate-jsx.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { useHook } from "shared-runtime";
1
+import {useHook} from 'shared-runtime';
2
3
function Component(props) {
4
const o = {};
@@ -13,5 +13,5 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ value: "sathya" }],
16
+ params: [{value: 'sathya'}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/prune-scopes-whose-deps-invalidate-new.expect.md
+4
-4
@@ -2,23 +2,23 @@
2
## Input
3
4
```javascript
5
-import { useHook } from "shared-runtime";
5
+import {useHook} from 'shared-runtime';
6
7
function Component(props) {
8
const x = new Foo();
9
useHook(); // intersperse a hook call to prevent memoization of x
10
x.value = props.value;
11
12
- const y = { x };
12
+ const y = {x};
13
14
- return { y };
14
+ return {y};
15
}
16
17
class Foo {}
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ value: "sathya" }],
21
+ params: [{value: 'sathya'}],
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/prune-scopes-whose-deps-invalidate-new.js
+4
-4
@@ -1,18 +1,18 @@
1
-import { useHook } from "shared-runtime";
1
+import {useHook} from 'shared-runtime';
2
3
function Component(props) {
4
const x = new Foo();
5
useHook(); // intersperse a hook call to prevent memoization of x
6
x.value = props.value;
7
8
- const y = { x };
8
+ const y = {x};
9
10
- return { y };
10
+ return {y};
11
}
12
13
class Foo {}
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ value: "sathya" }],
17
+ params: [{value: 'sathya'}],
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/prune-scopes-whose-deps-invalidate-object.expect.md
+4
-4
@@ -2,21 +2,21 @@
2
## Input
3
4
```javascript
5
-import { useHook } from "shared-runtime";
5
+import {useHook} from 'shared-runtime';
6
7
function Component(props) {
8
const x = {};
9
useHook(); // intersperse a hook call to prevent memoization of x
10
x.value = props.value;
11
12
- const y = { x };
12
+ const y = {x};
13
14
- return { y };
14
+ return {y};
15
}
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ value: "sathya" }],
19
+ params: [{value: 'sathya'}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/prune-scopes-whose-deps-invalidate-object.js
+4
-4
@@ -1,16 +1,16 @@
1
-import { useHook } from "shared-runtime";
1
+import {useHook} from 'shared-runtime';
2
3
function Component(props) {
4
const x = {};
5
useHook(); // intersperse a hook call to prevent memoization of x
6
x.value = props.value;
7
8
- const y = { x };
8
+ const y = {x};
9
10
- return { y };
10
+ return {y};
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ value: "sathya" }],
15
+ params: [{value: 'sathya'}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/prune-scopes-whose-deps-may-invalidate-array.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useHook, identity } from "shared-runtime";
5
+import {useHook, identity} from 'shared-runtime';
6
7
function Component(props) {
8
let x = 42;
@@ -19,7 +19,7 @@ function Component(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: [{ value: "sathya" }],
22
+ params: [{value: 'sathya'}],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/prune-scopes-whose-deps-may-invalidate-array.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { useHook, identity } from "shared-runtime";
1
+import {useHook, identity} from 'shared-runtime';
2
3
function Component(props) {
4
let x = 42;
@@ -15,5 +15,5 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ value: "sathya" }],
18
+ params: [{value: 'sathya'}],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/react-namespace.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-const FooContext = React.createContext({ current: null });
5
+const FooContext = React.createContext({current: null});
6
7
function Component(props) {
8
const foo = React.useContext(FooContext);
@@ -17,7 +17,7 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ children: <div>Hello</div> }],
20
+ params: [{children: <div>Hello</div>}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/react-namespace.js
+2
-2
@@ -1,4 +1,4 @@
1
-const FooContext = React.createContext({ current: null });
1
+const FooContext = React.createContext({current: null});
2
3
function Component(props) {
4
const foo = React.useContext(FooContext);
@@ -13,5 +13,5 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ children: <div>Hello</div> }],
16
+ params: [{children: <div>Hello</div>}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-do-while-indirect.expect.md
+8
-8
@@ -18,14 +18,14 @@ export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
params: [],
20
sequentialRenders: [
21
- { limit: 10 },
22
- { limit: 10 },
23
- { limit: 1 },
24
- { limit: 1 },
25
- { limit: 10 },
26
- { limit: 1 },
27
- { limit: 10 },
28
- { limit: 1 },
21
+ {limit: 10},
22
+ {limit: 10},
23
+ {limit: 1},
24
+ {limit: 1},
25
+ {limit: 10},
26
+ {limit: 1},
27
+ {limit: 10},
28
+ {limit: 1},
29
],
30
};
31
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-do-while-indirect.js
+8
-8
@@ -14,13 +14,13 @@ export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
params: [],
16
sequentialRenders: [
17
- { limit: 10 },
18
- { limit: 10 },
19
- { limit: 1 },
20
- { limit: 1 },
21
- { limit: 10 },
22
- { limit: 1 },
23
- { limit: 10 },
24
- { limit: 1 },
17
+ {limit: 10},
18
+ {limit: 10},
19
+ {limit: 1},
20
+ {limit: 1},
21
+ {limit: 10},
22
+ {limit: 1},
23
+ {limit: 10},
24
+ {limit: 1},
25
],
26
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-do-while-test.expect.md
+8
-8
@@ -24,14 +24,14 @@ export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
25
params: [],
26
sequentialRenders: [
27
- { test: 12 },
28
- { test: 12 },
29
- { test: 1 },
30
- { test: 1 },
31
- { test: 12 },
32
- { test: 1 },
33
- { test: 12 },
34
- { test: 1 },
27
+ {test: 12},
28
+ {test: 12},
29
+ {test: 1},
30
+ {test: 1},
31
+ {test: 12},
32
+ {test: 1},
33
+ {test: 12},
34
+ {test: 1},
35
],
36
};
37
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-do-while-test.js
+8
-8
@@ -20,13 +20,13 @@ export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
params: [],
22
sequentialRenders: [
23
- { test: 12 },
24
- { test: 12 },
25
- { test: 1 },
26
- { test: 1 },
27
- { test: 12 },
28
- { test: 1 },
29
- { test: 12 },
30
- { test: 1 },
23
+ {test: 12},
24
+ {test: 12},
25
+ {test: 1},
26
+ {test: 1},
27
+ {test: 12},
28
+ {test: 1},
29
+ {test: 12},
30
+ {test: 1},
31
],
32
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-for-init.expect.md
+8
-8
@@ -23,14 +23,14 @@ export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
params: [],
25
sequentialRenders: [
26
- { init: 0 },
27
- { init: 0 },
28
- { init: 10 },
29
- { init: 10 },
30
- { init: 0 },
31
- { init: 10 },
32
- { init: 0 },
33
- { init: 10 },
26
+ {init: 0},
27
+ {init: 0},
28
+ {init: 10},
29
+ {init: 10},
30
+ {init: 0},
31
+ {init: 10},
32
+ {init: 0},
33
+ {init: 10},
34
],
35
};
36
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-for-init.js
+8
-8
@@ -19,13 +19,13 @@ export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
params: [],
21
sequentialRenders: [
22
- { init: 0 },
23
- { init: 0 },
24
- { init: 10 },
25
- { init: 10 },
26
- { init: 0 },
27
- { init: 10 },
28
- { init: 0 },
29
- { init: 10 },
22
+ {init: 0},
23
+ {init: 0},
24
+ {init: 10},
25
+ {init: 10},
26
+ {init: 0},
27
+ {init: 10},
28
+ {init: 0},
29
+ {init: 10},
30
],
31
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-for-test.expect.md
+8
-8
@@ -22,14 +22,14 @@ export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
params: [],
24
sequentialRenders: [
25
- { test: 12 },
26
- { test: 12 },
27
- { test: 1 },
28
- { test: 1 },
29
- { test: 12 },
30
- { test: 1 },
31
- { test: 12 },
32
- { test: 1 },
25
+ {test: 12},
26
+ {test: 12},
27
+ {test: 1},
28
+ {test: 1},
29
+ {test: 12},
30
+ {test: 1},
31
+ {test: 12},
32
+ {test: 1},
33
],
34
};
35
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-for-test.js
+8
-8
@@ -18,13 +18,13 @@ export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
params: [],
20
sequentialRenders: [
21
- { test: 12 },
22
- { test: 12 },
23
- { test: 1 },
24
- { test: 1 },
25
- { test: 12 },
26
- { test: 1 },
27
- { test: 12 },
28
- { test: 1 },
21
+ {test: 12},
22
+ {test: 12},
23
+ {test: 1},
24
+ {test: 1},
25
+ {test: 12},
26
+ {test: 1},
27
+ {test: 12},
28
+ {test: 1},
29
],
30
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-for-update.expect.md
+8
-8
@@ -22,14 +22,14 @@ export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
params: [],
24
sequentialRenders: [
25
- { update: 2 },
26
- { update: 2 },
27
- { update: 1 },
28
- { update: 1 },
29
- { update: 2 },
30
- { update: 1 },
31
- { update: 2 },
32
- { update: 1 },
25
+ {update: 2},
26
+ {update: 2},
27
+ {update: 1},
28
+ {update: 1},
29
+ {update: 2},
30
+ {update: 1},
31
+ {update: 2},
32
+ {update: 1},
33
],
34
};
35
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-for-update.js
+8
-8
@@ -18,13 +18,13 @@ export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
params: [],
20
sequentialRenders: [
21
- { update: 2 },
22
- { update: 2 },
23
- { update: 1 },
24
- { update: 1 },
25
- { update: 2 },
26
- { update: 1 },
27
- { update: 2 },
28
- { update: 1 },
21
+ {update: 2},
22
+ {update: 2},
23
+ {update: 1},
24
+ {update: 1},
25
+ {update: 2},
26
+ {update: 1},
27
+ {update: 2},
28
+ {update: 1},
29
],
30
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-forin-collection.expect.md
+8
-8
@@ -23,14 +23,14 @@ export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
params: [],
25
sequentialRenders: [
26
- { values: { "12": true } },
27
- { values: { "12": true } },
28
- { values: { "1": true } },
29
- { values: { "1": true } },
30
- { values: { "12": true } },
31
- { values: { "1": true } },
32
- { values: { "12": true } },
33
- { values: { "1": true } },
26
+ {values: {'12': true}},
27
+ {values: {'12': true}},
28
+ {values: {'1': true}},
29
+ {values: {'1': true}},
30
+ {values: {'12': true}},
31
+ {values: {'1': true}},
32
+ {values: {'12': true}},
33
+ {values: {'1': true}},
34
],
35
};
36
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-forin-collection.js
+8
-8
@@ -19,13 +19,13 @@ export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
params: [],
21
sequentialRenders: [
22
- { values: { "12": true } },
23
- { values: { "12": true } },
24
- { values: { "1": true } },
25
- { values: { "1": true } },
26
- { values: { "12": true } },
27
- { values: { "1": true } },
28
- { values: { "12": true } },
29
- { values: { "1": true } },
22
+ {values: {'12': true}},
23
+ {values: {'12': true}},
24
+ {values: {'1': true}},
25
+ {values: {'1': true}},
26
+ {values: {'12': true}},
27
+ {values: {'1': true}},
28
+ {values: {'12': true}},
29
+ {values: {'1': true}},
30
],
31
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-forof-collection.expect.md
+8
-8
@@ -22,14 +22,14 @@ export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
params: [],
24
sequentialRenders: [
25
- { values: [12] },
26
- { values: [12] },
27
- { values: [1] },
28
- { values: [1] },
29
- { values: [12] },
30
- { values: [1] },
31
- { values: [12] },
32
- { values: [1] },
25
+ {values: [12]},
26
+ {values: [12]},
27
+ {values: [1]},
28
+ {values: [1]},
29
+ {values: [12]},
30
+ {values: [1]},
31
+ {values: [12]},
32
+ {values: [1]},
33
],
34
};
35
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-forof-collection.js
+8
-8
@@ -18,13 +18,13 @@ export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
params: [],
20
sequentialRenders: [
21
- { values: [12] },
22
- { values: [12] },
23
- { values: [1] },
24
- { values: [1] },
25
- { values: [12] },
26
- { values: [1] },
27
- { values: [12] },
28
- { values: [1] },
21
+ {values: [12]},
22
+ {values: [12]},
23
+ {values: [1]},
24
+ {values: [1]},
25
+ {values: [12]},
26
+ {values: [1]},
27
+ {values: [12]},
28
+ {values: [1]},
29
],
30
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-do-while.expect.md
+1
-1
@@ -29,7 +29,7 @@ function Component(props) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: Component,
32
- params: [{ cond: true }],
32
+ params: [{cond: true}],
33
};
34
35
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-do-while.js
+1
-1
@@ -25,5 +25,5 @@ function Component(props) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Component,
28
- params: [{ cond: true }],
28
+ params: [{cond: true}],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-in.expect.md
+2
-2
@@ -10,7 +10,7 @@ function Component(props) {
10
const a = [];
11
const b = [];
12
b.push(props.cond);
13
- a.push({ a: false });
13
+ a.push({a: false});
14
15
// Downstream consumer of a, which initially seems non-reactive except
16
// that a becomes reactive, per above
@@ -29,7 +29,7 @@ function Component(props) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: Component,
32
- params: [{ cond: true }],
32
+ params: [{cond: true}],
33
};
34
35
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-in.js
+2
-2
@@ -6,7 +6,7 @@ function Component(props) {
6
const a = [];
7
const b = [];
8
b.push(props.cond);
9
- a.push({ a: false });
9
+ a.push({a: false});
10
11
// Downstream consumer of a, which initially seems non-reactive except
12
// that a becomes reactive, per above
@@ -25,5 +25,5 @@ function Component(props) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Component,
28
- params: [{ cond: true }],
28
+ params: [{cond: true}],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-init.expect.md
+1
-1
@@ -29,7 +29,7 @@ function Component(props) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: Component,
32
- params: [{ cond: true }],
32
+ params: [{cond: true}],
33
};
34
35
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-init.js
+1
-1
@@ -25,5 +25,5 @@ function Component(props) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Component,
28
- params: [{ cond: true }],
28
+ params: [{cond: true}],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-of.expect.md
+1
-1
@@ -29,7 +29,7 @@ function Component(props) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: Component,
32
- params: [{ cond: true }],
32
+ params: [{cond: true}],
33
};
34
35
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-of.js
+1
-1
@@ -25,5 +25,5 @@ function Component(props) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Component,
28
- params: [{ cond: true }],
28
+ params: [{cond: true}],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-test.expect.md
+1
-1
@@ -29,7 +29,7 @@ function Component(props) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: Component,
32
- params: [{ cond: true }],
32
+ params: [{cond: true}],
33
};
34
35
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-test.js
+1
-1
@@ -25,5 +25,5 @@ function Component(props) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Component,
28
- params: [{ cond: true }],
28
+ params: [{cond: true}],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-update.expect.md
+1
-1
@@ -29,7 +29,7 @@ function Component(props) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: Component,
32
- params: [{ cond: true }],
32
+ params: [{cond: true}],
33
};
34
35
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-for-update.js
+1
-1
@@ -25,5 +25,5 @@ function Component(props) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Component,
28
- params: [{ cond: true }],
28
+ params: [{cond: true}],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-if.expect.md
+1
-1
@@ -31,7 +31,7 @@ function Component(props) {
31
32
export const FIXTURE_ENTRYPOINT = {
33
fn: Component,
34
- params: [{ cond: true }],
34
+ params: [{cond: true}],
35
};
36
37
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-if.js
+1
-1
@@ -27,5 +27,5 @@ function Component(props) {
27
28
export const FIXTURE_ENTRYPOINT = {
29
fn: Component,
30
- params: [{ cond: true }],
30
+ params: [{cond: true}],
31
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-switch.expect.md
+1
-1
@@ -35,7 +35,7 @@ function Component(props) {
35
36
export const FIXTURE_ENTRYPOINT = {
37
fn: Component,
38
- params: [{ cond: true }],
38
+ params: [{cond: true}],
39
};
40
41
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-switch.js
+1
-1
@@ -31,5 +31,5 @@ function Component(props) {
31
32
export const FIXTURE_ENTRYPOINT = {
33
fn: Component,
34
- params: [{ cond: true }],
34
+ params: [{cond: true}],
35
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-while.expect.md
+1
-1
@@ -29,7 +29,7 @@ function Component(props) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: Component,
32
- params: [{ cond: true }],
32
+ params: [{cond: true}],
33
};
34
35
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-from-interleaved-reactivity-while.js
+1
-1
@@ -25,5 +25,5 @@ function Component(props) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Component,
28
- params: [{ cond: true }],
28
+ params: [{cond: true}],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-if.expect.md
+8
-8
@@ -19,14 +19,14 @@ export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
params: [],
21
sequentialRenders: [
22
- { cond: true },
23
- { cond: true },
24
- { cond: false },
25
- { cond: false },
26
- { cond: true },
27
- { cond: false },
28
- { cond: true },
29
- { cond: false },
22
+ {cond: true},
23
+ {cond: true},
24
+ {cond: false},
25
+ {cond: false},
26
+ {cond: true},
27
+ {cond: false},
28
+ {cond: true},
29
+ {cond: false},
30
],
31
};
32
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-if.js
+8
-8
@@ -15,13 +15,13 @@ export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
params: [],
17
sequentialRenders: [
18
- { cond: true },
19
- { cond: true },
20
- { cond: false },
21
- { cond: false },
22
- { cond: true },
23
- { cond: false },
24
- { cond: true },
25
- { cond: false },
18
+ {cond: true},
19
+ {cond: true},
20
+ {cond: false},
21
+ {cond: false},
22
+ {cond: true},
23
+ {cond: false},
24
+ {cond: true},
25
+ {cond: false},
26
],
27
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-on-context-variable.expect.md
+9
-9
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
function Component(props) {
8
let x;
@@ -29,14 +29,14 @@ export const FIXTURE_ENTRYPOINT = {
29
fn: Component,
30
params: [],
31
sequentialRenders: [
32
- { cond: true },
33
- { cond: true },
34
- { cond: false },
35
- { cond: false },
36
- { cond: true },
37
- { cond: false },
38
- { cond: true },
39
- { cond: false },
32
+ {cond: true},
33
+ {cond: true},
34
+ {cond: false},
35
+ {cond: false},
36
+ {cond: true},
37
+ {cond: false},
38
+ {cond: true},
39
+ {cond: false},
40
],
41
};
42
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-on-context-variable.js
+9
-9
@@ -1,4 +1,4 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
function Component(props) {
4
let x;
@@ -25,13 +25,13 @@ export const FIXTURE_ENTRYPOINT = {
25
fn: Component,
26
params: [],
27
sequentialRenders: [
28
- { cond: true },
29
- { cond: true },
30
- { cond: false },
31
- { cond: false },
32
- { cond: true },
33
- { cond: false },
34
- { cond: true },
35
- { cond: false },
28
+ {cond: true},
29
+ {cond: true},
30
+ {cond: false},
31
+ {cond: false},
32
+ {cond: true},
33
+ {cond: false},
34
+ {cond: true},
35
+ {cond: false},
36
],
37
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-phi-setState-type.expect.md
+15
-15
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import invariant from "invariant";
6
-import { useState } from "react";
5
+import invariant from 'invariant';
6
+import {useState} from 'react';
7
8
function Component(props) {
9
const [x, setX] = useState(false);
@@ -15,7 +15,7 @@ function Component(props) {
15
setState = setY;
16
}
17
const setState2 = setState;
18
- const stateObject = { setState: setState2 };
18
+ const stateObject = {setState: setState2};
19
return (
20
<Foo
21
cond={props.cond}
@@ -26,27 +26,27 @@ function Component(props) {
26
);
27
}
28
29
-function Foo({ cond, setX, setY, setState }) {
29
+function Foo({cond, setX, setY, setState}) {
30
if (cond) {
31
- invariant(setState === setX, "Expected the correct setState function");
31
+ invariant(setState === setX, 'Expected the correct setState function');
32
} else {
33
- invariant(setState === setY, "Expected the correct setState function");
33
+ invariant(setState === setY, 'Expected the correct setState function');
34
}
35
- return "ok";
35
+ return 'ok';
36
}
37
38
export const FIXTURE_ENTRYPOINT = {
39
fn: Component,
40
params: [],
41
sequentialRenders: [
42
- { cond: true },
43
- { cond: true },
44
- { cond: false },
45
- { cond: false },
46
- { cond: true },
47
- { cond: false },
48
- { cond: true },
49
- { cond: false },
42
+ {cond: true},
43
+ {cond: true},
44
+ {cond: false},
45
+ {cond: false},
46
+ {cond: true},
47
+ {cond: false},
48
+ {cond: true},
49
+ {cond: false},
50
],
51
};
52
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-phi-setState-type.js
+15
-15
@@ -1,5 +1,5 @@
1
-import invariant from "invariant";
2
-import { useState } from "react";
1
+import invariant from 'invariant';
2
+import {useState} from 'react';
3
4
function Component(props) {
5
const [x, setX] = useState(false);
@@ -11,7 +11,7 @@ function Component(props) {
11
setState = setY;
12
}
13
const setState2 = setState;
14
- const stateObject = { setState: setState2 };
14
+ const stateObject = {setState: setState2};
15
return (
16
<Foo
17
cond={props.cond}
@@ -22,26 +22,26 @@ function Component(props) {
22
);
23
}
24
25
-function Foo({ cond, setX, setY, setState }) {
25
+function Foo({cond, setX, setY, setState}) {
26
if (cond) {
27
- invariant(setState === setX, "Expected the correct setState function");
27
+ invariant(setState === setX, 'Expected the correct setState function');
28
} else {
29
- invariant(setState === setY, "Expected the correct setState function");
29
+ invariant(setState === setY, 'Expected the correct setState function');
30
}
31
- return "ok";
31
+ return 'ok';
32
}
33
34
export const FIXTURE_ENTRYPOINT = {
35
fn: Component,
36
params: [],
37
sequentialRenders: [
38
- { cond: true },
39
- { cond: true },
40
- { cond: false },
41
- { cond: false },
42
- { cond: true },
43
- { cond: false },
44
- { cond: true },
45
- { cond: false },
38
+ {cond: true},
39
+ {cond: true},
40
+ {cond: false},
41
+ {cond: false},
42
+ {cond: true},
43
+ {cond: false},
44
+ {cond: true},
45
+ {cond: false},
46
],
47
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-reactive-after-fixpoint.expect.md
+8
-8
@@ -33,14 +33,14 @@ export const FIXTURE_ENTRYPOINT = {
33
fn: Component,
34
params: [],
35
sequentialRenders: [
36
- { cond: true },
37
- { cond: true },
38
- { cond: false },
39
- { cond: false },
40
- { cond: true },
41
- { cond: false },
42
- { cond: true },
43
- { cond: false },
36
+ {cond: true},
37
+ {cond: true},
38
+ {cond: false},
39
+ {cond: false},
40
+ {cond: true},
41
+ {cond: false},
42
+ {cond: true},
43
+ {cond: false},
44
],
45
};
46
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-reactive-after-fixpoint.js
+8
-8
@@ -29,13 +29,13 @@ export const FIXTURE_ENTRYPOINT = {
29
fn: Component,
30
params: [],
31
sequentialRenders: [
32
- { cond: true },
33
- { cond: true },
34
- { cond: false },
35
- { cond: false },
36
- { cond: true },
37
- { cond: false },
38
- { cond: true },
39
- { cond: false },
32
+ {cond: true},
33
+ {cond: true},
34
+ {cond: false},
35
+ {cond: false},
36
+ {cond: true},
37
+ {cond: false},
38
+ {cond: true},
39
+ {cond: false},
40
],
41
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-switch-case-test.expect.md
+8
-8
@@ -27,14 +27,14 @@ export const FIXTURE_ENTRYPOINT = {
27
fn: Component,
28
params: [],
29
sequentialRenders: [
30
- { cond: true },
31
- { cond: true },
32
- { cond: false },
33
- { cond: false },
34
- { cond: true },
35
- { cond: false },
36
- { cond: true },
37
- { cond: false },
30
+ {cond: true},
31
+ {cond: true},
32
+ {cond: false},
33
+ {cond: false},
34
+ {cond: true},
35
+ {cond: false},
36
+ {cond: true},
37
+ {cond: false},
38
],
39
};
40
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-switch-case-test.js
+8
-8
@@ -23,13 +23,13 @@ export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
params: [],
25
sequentialRenders: [
26
- { cond: true },
27
- { cond: true },
28
- { cond: false },
29
- { cond: false },
30
- { cond: true },
31
- { cond: false },
32
- { cond: true },
33
- { cond: false },
26
+ {cond: true},
27
+ {cond: true},
28
+ {cond: false},
29
+ {cond: false},
30
+ {cond: true},
31
+ {cond: false},
32
+ {cond: true},
33
+ {cond: false},
34
],
35
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-switch-condition.expect.md
+9
-9
@@ -4,7 +4,7 @@
4
```javascript
5
const GLOBAL = 42;
6
7
-function Component({ value }) {
7
+function Component({value}) {
8
let x;
9
switch (GLOBAL) {
10
case value: {
@@ -25,14 +25,14 @@ export const FIXTURE_ENTRYPOINT = {
25
fn: Component,
26
params: [],
27
sequentialRenders: [
28
- { value: GLOBAL },
29
- { value: GLOBAL },
30
- { value: null },
31
- { value: null },
32
- { value: GLOBAL },
33
- { value: null },
34
- { value: GLOBAL },
35
- { value: null },
28
+ {value: GLOBAL},
29
+ {value: GLOBAL},
30
+ {value: null},
31
+ {value: null},
32
+ {value: GLOBAL},
33
+ {value: null},
34
+ {value: GLOBAL},
35
+ {value: null},
36
],
37
};
38
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-switch-condition.js
+9
-9
@@ -1,6 +1,6 @@
1
const GLOBAL = 42;
2
3
-function Component({ value }) {
3
+function Component({value}) {
4
let x;
5
switch (GLOBAL) {
6
case value: {
@@ -21,13 +21,13 @@ export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
params: [],
23
sequentialRenders: [
24
- { value: GLOBAL },
25
- { value: GLOBAL },
26
- { value: null },
27
- { value: null },
28
- { value: GLOBAL },
29
- { value: null },
30
- { value: GLOBAL },
31
- { value: null },
24
+ {value: GLOBAL},
25
+ {value: GLOBAL},
26
+ {value: null},
27
+ {value: null},
28
+ {value: GLOBAL},
29
+ {value: null},
30
+ {value: GLOBAL},
31
+ {value: null},
32
],
33
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-via-mutation-if.expect.md
+8
-8
@@ -22,14 +22,14 @@ export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
params: [],
24
sequentialRenders: [
25
- { cond: true },
26
- { cond: true },
27
- { cond: false },
28
- { cond: false },
29
- { cond: true },
30
- { cond: false },
31
- { cond: true },
32
- { cond: false },
25
+ {cond: true},
26
+ {cond: true},
27
+ {cond: false},
28
+ {cond: false},
29
+ {cond: true},
30
+ {cond: false},
31
+ {cond: true},
32
+ {cond: false},
33
],
34
};
35
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-via-mutation-if.js
+8
-8
@@ -18,13 +18,13 @@ export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
params: [],
20
sequentialRenders: [
21
- { cond: true },
22
- { cond: true },
23
- { cond: false },
24
- { cond: false },
25
- { cond: true },
26
- { cond: false },
27
- { cond: true },
28
- { cond: false },
21
+ {cond: true},
22
+ {cond: true},
23
+ {cond: false},
24
+ {cond: false},
25
+ {cond: true},
26
+ {cond: false},
27
+ {cond: true},
28
+ {cond: false},
29
],
30
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-via-mutation-switch.expect.md
+8
-8
@@ -25,14 +25,14 @@ export const FIXTURE_ENTRYPOINT = {
25
fn: Component,
26
params: [],
27
sequentialRenders: [
28
- { cond: true },
29
- { cond: true },
30
- { cond: false },
31
- { cond: false },
32
- { cond: true },
33
- { cond: false },
34
- { cond: true },
35
- { cond: false },
28
+ {cond: true},
29
+ {cond: true},
30
+ {cond: false},
31
+ {cond: false},
32
+ {cond: true},
33
+ {cond: false},
34
+ {cond: true},
35
+ {cond: false},
36
],
37
};
38
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-via-mutation-switch.js
+8
-8
@@ -21,13 +21,13 @@ export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
params: [],
23
sequentialRenders: [
24
- { cond: true },
25
- { cond: true },
26
- { cond: false },
27
- { cond: false },
28
- { cond: true },
29
- { cond: false },
30
- { cond: true },
31
- { cond: false },
24
+ {cond: true},
25
+ {cond: true},
26
+ {cond: false},
27
+ {cond: false},
28
+ {cond: true},
29
+ {cond: false},
30
+ {cond: true},
31
+ {cond: false},
32
],
33
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-while-test.expect.md
+8
-8
@@ -24,14 +24,14 @@ export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
25
params: [],
26
sequentialRenders: [
27
- { test: 12 },
28
- { test: 12 },
29
- { test: 1 },
30
- { test: 1 },
31
- { test: 12 },
32
- { test: 1 },
33
- { test: 12 },
34
- { test: 1 },
27
+ {test: 12},
28
+ {test: 12},
29
+ {test: 1},
30
+ {test: 1},
31
+ {test: 12},
32
+ {test: 1},
33
+ {test: 12},
34
+ {test: 1},
35
],
36
};
37
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-control-dependency-while-test.js
+8
-8
@@ -20,13 +20,13 @@ export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
params: [],
22
sequentialRenders: [
23
- { test: 12 },
24
- { test: 12 },
25
- { test: 1 },
26
- { test: 1 },
27
- { test: 12 },
28
- { test: 1 },
29
- { test: 12 },
30
- { test: 1 },
23
+ {test: 12},
24
+ {test: 12},
25
+ {test: 1},
26
+ {test: 1},
27
+ {test: 12},
28
+ {test: 1},
29
+ {test: 12},
30
+ {test: 1},
31
],
32
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-dependency-fixpoint.expect.md
+1
-1
@@ -20,7 +20,7 @@ function Component(props) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
- params: [{ value: 42 }],
23
+ params: [{value: 42}],
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-dependency-fixpoint.js
+1
-1
@@ -16,5 +16,5 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ value: 42 }],
19
+ params: [{value: 42}],
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-dependency-nonreactive-captured-with-reactive.expect.md
+1
-1
@@ -10,7 +10,7 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ y: 42 }],
13
+ params: [{y: 42}],
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-dependency-nonreactive-captured-with-reactive.js
+1
-1
@@ -6,5 +6,5 @@ function Component(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: [{ y: 42 }],
9
+ params: [{y: 42}],
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-dependency-object-captured-with-reactive-mutated.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-const { mutate } = require("shared-runtime");
5
+const {mutate} = require('shared-runtime');
6
7
function Component(props) {
8
const x = {};
@@ -15,7 +15,7 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ y: 42 }],
18
+ params: [{y: 42}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-dependency-object-captured-with-reactive-mutated.js
+2
-2
@@ -1,4 +1,4 @@
1
-const { mutate } = require("shared-runtime");
1
+const {mutate} = require('shared-runtime');
2
3
function Component(props) {
4
const x = {};
@@ -11,5 +11,5 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ y: 42 }],
14
+ params: [{y: 42}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-scopes-if.expect.md
+2
-2
@@ -16,8 +16,8 @@ function foo(a, b, c) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: foo,
19
- params: ["TodoAdd"],
20
- isComponent: "TodoAdd",
19
+ params: ['TodoAdd'],
20
+ isComponent: 'TodoAdd',
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-scopes-if.js
+2
-2
@@ -12,6 +12,6 @@ function foo(a, b, c) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: foo,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-scopes.expect.md
+2
-2
@@ -15,8 +15,8 @@ function f(a, b) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: f,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactive-scopes.js
+2
-2
@@ -11,6 +11,6 @@ function f(a, b) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: f,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-analysis-interleaved-reactivity.expect.md
+2
-2
@@ -24,8 +24,8 @@ function Component(props) {
24
25
export const FIXTURE_ENTRYPOINT = {
26
fn: Component,
27
- params: ["TodoAdd"],
28
- isComponent: "TodoAdd",
27
+ params: ['TodoAdd'],
28
+ isComponent: 'TodoAdd',
29
};
30
31
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-analysis-interleaved-reactivity.js
+2
-2
@@ -20,6 +20,6 @@ function Component(props) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
- params: ["TodoAdd"],
24
- isComponent: "TodoAdd",
23
+ params: ['TodoAdd'],
24
+ isComponent: 'TodoAdd',
25
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-analysis-reactive-via-mutation-of-computed-load.expect.md
+1
-1
@@ -8,7 +8,7 @@ function Component(props) {
8
9
const count = foo(items.length + 1);
10
11
- return { items, count };
11
+ return {items, count};
12
}
13
14
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-analysis-reactive-via-mutation-of-computed-load.js
+1
-1
@@ -4,5 +4,5 @@ function Component(props) {
4
5
const count = foo(items.length + 1);
6
7
- return { items, count };
7
+ return {items, count};
8
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-analysis-reactive-via-mutation-of-property-load.expect.md
+1
-1
@@ -8,7 +8,7 @@ function Component(props) {
8
9
const count = foo(items.length + 1);
10
11
- return { items, count };
11
+ return {items, count};
12
}
13
14
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-analysis-reactive-via-mutation-of-property-load.js
+1
-1
@@ -4,5 +4,5 @@ function Component(props) {
4
5
const count = foo(items.length + 1);
6
7
- return { items, count };
7
+ return {items, count};
8
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-via-aliased-mutation-array.expect.md
+8
-8
@@ -14,14 +14,14 @@ export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
params: [],
16
sequentialRenders: [
17
- { input: 42 },
18
- { input: 42 },
19
- { input: "sathya" },
20
- { input: "sathya" },
21
- { input: 42 },
22
- { input: "sathya" },
23
- { input: 42 },
24
- { input: "sathya" },
17
+ {input: 42},
18
+ {input: 42},
19
+ {input: 'sathya'},
20
+ {input: 'sathya'},
21
+ {input: 42},
22
+ {input: 'sathya'},
23
+ {input: 42},
24
+ {input: 'sathya'},
25
],
26
};
27
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-via-aliased-mutation-array.js
+8
-8
@@ -10,13 +10,13 @@ export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
params: [],
12
sequentialRenders: [
13
- { input: 42 },
14
- { input: 42 },
15
- { input: "sathya" },
16
- { input: "sathya" },
17
- { input: 42 },
18
- { input: "sathya" },
19
- { input: 42 },
20
- { input: "sathya" },
13
+ {input: 42},
14
+ {input: 42},
15
+ {input: 'sathya'},
16
+ {input: 'sathya'},
17
+ {input: 42},
18
+ {input: 'sathya'},
19
+ {input: 42},
20
+ {input: 'sathya'},
21
],
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-via-aliased-mutation-lambda.expect.md
+9
-9
@@ -4,7 +4,7 @@
4
```javascript
5
function Component(props) {
6
const x = [];
7
- const f = (arg) => {
7
+ const f = arg => {
8
const y = x;
9
y.push(arg);
10
};
@@ -17,14 +17,14 @@ export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
params: [],
19
sequentialRenders: [
20
- { input: 42 },
21
- { input: 42 },
22
- { input: "sathya" },
23
- { input: "sathya" },
24
- { input: 42 },
25
- { input: "sathya" },
26
- { input: 42 },
27
- { input: "sathya" },
20
+ {input: 42},
21
+ {input: 42},
22
+ {input: 'sathya'},
23
+ {input: 'sathya'},
24
+ {input: 42},
25
+ {input: 'sathya'},
26
+ {input: 42},
27
+ {input: 'sathya'},
28
],
29
};
30
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-via-aliased-mutation-lambda.js
+9
-9
@@ -1,6 +1,6 @@
1
function Component(props) {
2
const x = [];
3
- const f = (arg) => {
3
+ const f = arg => {
4
const y = x;
5
y.push(arg);
6
};
@@ -13,13 +13,13 @@ export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
params: [],
15
sequentialRenders: [
16
- { input: 42 },
17
- { input: 42 },
18
- { input: "sathya" },
19
- { input: "sathya" },
20
- { input: 42 },
21
- { input: "sathya" },
22
- { input: 42 },
23
- { input: "sathya" },
16
+ {input: 42},
17
+ {input: 42},
18
+ {input: 'sathya'},
19
+ {input: 'sathya'},
20
+ {input: 42},
21
+ {input: 'sathya'},
22
+ {input: 42},
23
+ {input: 'sathya'},
24
],
25
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-via-aliased-mutation-through-property-load.expect.md
+8
-8
@@ -20,14 +20,14 @@ export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
params: [],
22
sequentialRenders: [
23
- { input: true },
24
- { input: true },
25
- { input: false },
26
- { input: false },
27
- { input: true },
28
- { input: false },
29
- { input: true },
30
- { input: false },
23
+ {input: true},
24
+ {input: true},
25
+ {input: false},
26
+ {input: false},
27
+ {input: true},
28
+ {input: false},
29
+ {input: true},
30
+ {input: false},
31
],
32
};
33
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-via-aliased-mutation-through-property-load.js
+8
-8
@@ -16,13 +16,13 @@ export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
params: [],
18
sequentialRenders: [
19
- { input: true },
20
- { input: true },
21
- { input: false },
22
- { input: false },
23
- { input: true },
24
- { input: false },
25
- { input: true },
26
- { input: false },
19
+ {input: true},
20
+ {input: true},
21
+ {input: false},
22
+ {input: false},
23
+ {input: true},
24
+ {input: false},
25
+ {input: true},
26
+ {input: false},
27
],
28
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-via-readonly-alias-of-mutable-value.expect.md
+8
-8
@@ -29,14 +29,14 @@ export const FIXTURE_ENTRYPOINT = {
29
fn: Component,
30
params: [],
31
sequentialRenders: [
32
- { input: 42 },
33
- { input: 42 },
34
- { input: "sathya" },
35
- { input: "sathya" },
36
- { input: 42 },
37
- { input: "sathya" },
38
- { input: 42 },
39
- { input: "sathya" },
32
+ {input: 42},
33
+ {input: 42},
34
+ {input: 'sathya'},
35
+ {input: 'sathya'},
36
+ {input: 42},
37
+ {input: 'sathya'},
38
+ {input: 42},
39
+ {input: 'sathya'},
40
],
41
};
42
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reactivity-via-readonly-alias-of-mutable-value.js
+8
-8
@@ -25,13 +25,13 @@ export const FIXTURE_ENTRYPOINT = {
25
fn: Component,
26
params: [],
27
sequentialRenders: [
28
- { input: 42 },
29
- { input: 42 },
30
- { input: "sathya" },
31
- { input: "sathya" },
32
- { input: 42 },
33
- { input: "sathya" },
34
- { input: 42 },
35
- { input: "sathya" },
28
+ {input: 42},
29
+ {input: 42},
30
+ {input: 'sathya'},
31
+ {input: 'sathya'},
32
+ {input: 42},
33
+ {input: 'sathya'},
34
+ {input: 42},
35
+ {input: 'sathya'},
36
],
37
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/readonly-object-method-calls-mutable-lambda.expect.md
+1
-1
@@ -8,7 +8,7 @@ function Component(props) {
8
graphql`fragment Component_user on User { ... }`,
9
props.user
10
);
11
- const posts = user.timeline.posts.edges.nodes.map((node) => {
11
+ const posts = user.timeline.posts.edges.nodes.map(node => {
12
x.y = true;
13
return <Post post={node} />;
14
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/readonly-object-method-calls-mutable-lambda.js
+1
-1
@@ -4,7 +4,7 @@ function Component(props) {
4
graphql`fragment Component_user on User { ... }`,
5
props.user
6
);
7
- const posts = user.timeline.posts.edges.nodes.map((node) => {
7
+ const posts = user.timeline.posts.edges.nodes.map(node => {
8
x.y = true;
9
return <Post post={node} />;
10
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/readonly-object-method-calls.expect.md
+1
-1
@@ -7,7 +7,7 @@ function Component(props) {
7
graphql`fragment Component_user on User { ... }`,
8
props.user
9
);
10
- const posts = user.timeline.posts.edges.nodes.map((node) => (
10
+ const posts = user.timeline.posts.edges.nodes.map(node => (
11
<Post post={node} />
12
));
13
posts.push({});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/readonly-object-method-calls.js
+1
-1
@@ -3,7 +3,7 @@ function Component(props) {
3
graphql`fragment Component_user on User { ... }`,
4
props.user
5
);
6
- const posts = user.timeline.posts.edges.nodes.map((node) => (
6
+ const posts = user.timeline.posts.edges.nodes.map(node => (
7
<Post post={node} />
8
));
9
posts.push({});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reassign-in-while-loop-condition.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeArray } from "shared-runtime";
5
+import {makeArray} from 'shared-runtime';
6
7
// @flow
8
function Component() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reassign-in-while-loop-condition.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { makeArray } from "shared-runtime";
1
+import {makeArray} from 'shared-runtime';
2
3
// @flow
4
function Component() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reassignment-separate-scopes.expect.md
+2
-2
@@ -30,8 +30,8 @@ function foo(a, b, c) {
30
31
export const FIXTURE_ENTRYPOINT = {
32
fn: foo,
33
- params: ["TodoAdd"],
34
- isComponent: "TodoAdd",
33
+ params: ['TodoAdd'],
34
+ isComponent: 'TodoAdd',
35
};
36
37
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reassignment-separate-scopes.js
+2
-2
@@ -26,6 +26,6 @@ function foo(a, b, c) {
26
27
export const FIXTURE_ENTRYPOINT = {
28
fn: foo,
29
- params: ["TodoAdd"],
30
- isComponent: "TodoAdd",
29
+ params: ['TodoAdd'],
30
+ isComponent: 'TodoAdd',
31
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-cond-deps-break-in-scope.expect.md
+4
-4
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function useFoo({ obj, objIsNull }) {
5
+function useFoo({obj, objIsNull}) {
6
const x = [];
7
b0: {
8
if (objIsNull) {
@@ -17,10 +17,10 @@ function useFoo({ obj, objIsNull }) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: useFoo,
20
- params: [{ obj: null, objIsNull: true }],
20
+ params: [{obj: null, objIsNull: true}],
21
sequentialRenders: [
22
- { obj: null, objIsNull: true },
23
- { obj: { a: 2 }, objIsNull: false },
22
+ {obj: null, objIsNull: true},
23
+ {obj: {a: 2}, objIsNull: false},
24
],
25
};
26
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-cond-deps-break-in-scope.ts
+4
-4
@@ -1,4 +1,4 @@
1
-function useFoo({ obj, objIsNull }) {
1
+function useFoo({obj, objIsNull}) {
2
const x = [];
3
b0: {
4
if (objIsNull) {
@@ -13,9 +13,9 @@ function useFoo({ obj, objIsNull }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: useFoo,
16
- params: [{ obj: null, objIsNull: true }],
16
+ params: [{obj: null, objIsNull: true}],
17
sequentialRenders: [
18
- { obj: null, objIsNull: true },
19
- { obj: { a: 2 }, objIsNull: false },
18
+ {obj: null, objIsNull: true},
19
+ {obj: {a: 2}, objIsNull: false},
20
],
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-cond-deps-cfg-nested-testifelse.expect.md
+3
-9
@@ -2,15 +2,9 @@
2
## Input
3
4
```javascript
5
-import { setProperty } from "shared-runtime";
5
+import {setProperty} from 'shared-runtime';
6
7
-function useFoo({
8
- o,
9
- branchCheck,
10
-}: {
11
- o: { value: number };
12
- branchCheck: boolean;
13
-}) {
7
+function useFoo({o, branchCheck}: {o: {value: number}; branchCheck: boolean}) {
8
let x = {};
9
if (branchCheck) {
10
setProperty(x, o.value);
@@ -26,7 +20,7 @@ function useFoo({
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: useFoo,
29
- params: [{ o: { value: 2 }, branchCheck: false }],
23
+ params: [{o: {value: 2}, branchCheck: false}],
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-cond-deps-cfg-nested-testifelse.ts
+3
-9
@@ -1,12 +1,6 @@
1
-import { setProperty } from "shared-runtime";
1
+import {setProperty} from 'shared-runtime';
2
3
-function useFoo({
4
- o,
5
- branchCheck,
6
-}: {
7
- o: { value: number };
8
- branchCheck: boolean;
9
-}) {
3
+function useFoo({o, branchCheck}: {o: {value: number}; branchCheck: boolean}) {
4
let x = {};
5
if (branchCheck) {
6
setProperty(x, o.value);
@@ -22,5 +16,5 @@ function useFoo({
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: useFoo,
25
- params: [{ o: { value: 2 }, branchCheck: false }],
19
+ params: [{o: {value: 2}, branchCheck: false}],
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-cond-deps-return-in-scope.expect.md
+4
-4
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function useFoo({ obj, objIsNull }) {
5
+function useFoo({obj, objIsNull}) {
6
const x = [];
7
if (objIsNull) {
8
return;
@@ -15,10 +15,10 @@ function useFoo({ obj, objIsNull }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: useFoo,
18
- params: [{ obj: null, objIsNull: true }],
18
+ params: [{obj: null, objIsNull: true}],
19
sequentialRenders: [
20
- { obj: null, objIsNull: true },
21
- { obj: { a: 2 }, objIsNull: false },
20
+ {obj: null, objIsNull: true},
21
+ {obj: {a: 2}, objIsNull: false},
22
],
23
};
24
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-cond-deps-return-in-scope.ts
+4
-4
@@ -1,4 +1,4 @@
1
-function useFoo({ obj, objIsNull }) {
1
+function useFoo({obj, objIsNull}) {
2
const x = [];
3
if (objIsNull) {
4
return;
@@ -11,9 +11,9 @@ function useFoo({ obj, objIsNull }) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: useFoo,
14
- params: [{ obj: null, objIsNull: true }],
14
+ params: [{obj: null, objIsNull: true}],
15
sequentialRenders: [
16
- { obj: null, objIsNull: true },
17
- { obj: { a: 2 }, objIsNull: false },
16
+ {obj: null, objIsNull: true},
17
+ {obj: {a: 2}, objIsNull: false},
18
],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cfg-condexpr.expect.md
+2
-2
@@ -6,7 +6,7 @@
6
// scope that produces x, since it is accessed unconditionally in all cfg
7
// paths
8
9
-import { identity, addOne } from "shared-runtime";
9
+import {identity, addOne} from 'shared-runtime';
10
11
function useCondDepInConditionalExpr(props, cond) {
12
const x = identity(cond) ? addOne(props.a.b) : identity(props.a.b);
@@ -15,7 +15,7 @@ function useCondDepInConditionalExpr(props, cond) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: useCondDepInConditionalExpr,
18
- params: [{ a: { b: 2 } }, true],
18
+ params: [{a: {b: 2}}, true],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cfg-condexpr.js
+2
-2
@@ -2,7 +2,7 @@
2
// scope that produces x, since it is accessed unconditionally in all cfg
3
// paths
4
5
-import { identity, addOne } from "shared-runtime";
5
+import {identity, addOne} from 'shared-runtime';
6
7
function useCondDepInConditionalExpr(props, cond) {
8
const x = identity(cond) ? addOne(props.a.b) : identity(props.a.b);
@@ -11,5 +11,5 @@ function useCondDepInConditionalExpr(props, cond) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: useCondDepInConditionalExpr,
14
- params: [{ a: { b: 2 } }, true],
14
+ params: [{a: {b: 2}}, true],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cfg-ifelse.expect.md
+2
-2
@@ -6,7 +6,7 @@
6
// scope that produces x, since it is accessed unconditionally in all cfg
7
// paths
8
9
-import { identity } from "shared-runtime";
9
+import {identity} from 'shared-runtime';
10
11
function useCondDepInDirectIfElse(props, cond) {
12
const x = {};
@@ -20,7 +20,7 @@ function useCondDepInDirectIfElse(props, cond) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: useCondDepInDirectIfElse,
23
- params: [{ a: { b: 2 } }, true],
23
+ params: [{a: {b: 2}}, true],
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cfg-ifelse.js
+2
-2
@@ -2,7 +2,7 @@
2
// scope that produces x, since it is accessed unconditionally in all cfg
3
// paths
4
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
function useCondDepInDirectIfElse(props, cond) {
8
const x = {};
@@ -16,5 +16,5 @@ function useCondDepInDirectIfElse(props, cond) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: useCondDepInDirectIfElse,
19
- params: [{ a: { b: 2 } }, true],
19
+ params: [{a: {b: 2}}, true],
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cfg-nested-ifelse-missing.expect.md
+2
-2
@@ -5,7 +5,7 @@
5
// props.a.b should NOT be added as a unconditional dependency to the reactive
6
// scope that produces x if it is not accessed in every path
7
8
-import { identity, getNull } from "shared-runtime";
8
+import {identity, getNull} from 'shared-runtime';
9
10
function useCondDepInNestedIfElse(props, cond) {
11
const x = {};
@@ -21,7 +21,7 @@ function useCondDepInNestedIfElse(props, cond) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: useCondDepInNestedIfElse,
24
- params: [{ a: { b: 2 } }, true],
24
+ params: [{a: {b: 2}}, true],
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cfg-nested-ifelse-missing.js
+2
-2
@@ -1,7 +1,7 @@
1
// props.a.b should NOT be added as a unconditional dependency to the reactive
2
// scope that produces x if it is not accessed in every path
3
4
-import { identity, getNull } from "shared-runtime";
4
+import {identity, getNull} from 'shared-runtime';
5
6
function useCondDepInNestedIfElse(props, cond) {
7
const x = {};
@@ -17,5 +17,5 @@ function useCondDepInNestedIfElse(props, cond) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: useCondDepInNestedIfElse,
20
- params: [{ a: { b: 2 } }, true],
20
+ params: [{a: {b: 2}}, true],
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cfg-nested-ifelse.expect.md
+2
-2
@@ -6,7 +6,7 @@
6
// scope that produces x, since it is accessed unconditionally in all cfg
7
// paths
8
9
-import { getNull, identity } from "shared-runtime";
9
+import {getNull, identity} from 'shared-runtime';
10
11
function useCondDepInNestedIfElse(props, cond) {
12
const x = {};
@@ -26,7 +26,7 @@ function useCondDepInNestedIfElse(props, cond) {
26
27
export const FIXTURE_ENTRYPOINT = {
28
fn: useCondDepInNestedIfElse,
29
- params: [{ a: { b: 2 } }, true],
29
+ params: [{a: {b: 2}}, true],
30
};
31
32
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cfg-nested-ifelse.js
+2
-2
@@ -2,7 +2,7 @@
2
// scope that produces x, since it is accessed unconditionally in all cfg
3
// paths
4
5
-import { getNull, identity } from "shared-runtime";
5
+import {getNull, identity} from 'shared-runtime';
6
7
function useCondDepInNestedIfElse(props, cond) {
8
const x = {};
@@ -22,5 +22,5 @@ function useCondDepInNestedIfElse(props, cond) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: useCondDepInNestedIfElse,
25
- params: [{ a: { b: 2 } }, true],
25
+ params: [{a: {b: 2}}, true],
26
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cfg-switch-exhaustive.expect.md
+2
-2
@@ -6,7 +6,7 @@
6
// scope that produces x, since it is accessed unconditionally in all cfg
7
// paths
8
9
-import { identity } from "shared-runtime";
9
+import {identity} from 'shared-runtime';
10
11
function useCondDepInSwitch(props, other) {
12
const x = {};
@@ -25,7 +25,7 @@ function useCondDepInSwitch(props, other) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: useCondDepInSwitch,
28
- params: [{ a: { b: 2 } }, 2],
28
+ params: [{a: {b: 2}}, 2],
29
};
30
31
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cfg-switch-exhaustive.js
+2
-2
@@ -2,7 +2,7 @@
2
// scope that produces x, since it is accessed unconditionally in all cfg
3
// paths
4
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
function useCondDepInSwitch(props, other) {
8
const x = {};
@@ -21,5 +21,5 @@ function useCondDepInSwitch(props, other) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: useCondDepInSwitch,
24
- params: [{ a: { b: 2 } }, 2],
24
+ params: [{a: {b: 2}}, 2],
25
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cfg-switch-missing-case.expect.md
+2
-2
@@ -5,7 +5,7 @@
5
// props.a.b should NOT be added as a unconditional dependency to the reactive
6
// scope that produces x if it is not accessed in every path
7
8
-import { identity } from "shared-runtime";
8
+import {identity} from 'shared-runtime';
9
10
function useCondDepInSwitchMissingCase(props, other) {
11
const x = {};
@@ -25,7 +25,7 @@ function useCondDepInSwitchMissingCase(props, other) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: useCondDepInSwitchMissingCase,
28
- params: [{ a: { b: 2 } }, 2],
28
+ params: [{a: {b: 2}}, 2],
29
};
30
31
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cfg-switch-missing-case.js
+2
-2
@@ -1,7 +1,7 @@
1
// props.a.b should NOT be added as a unconditional dependency to the reactive
2
// scope that produces x if it is not accessed in every path
3
4
-import { identity } from "shared-runtime";
4
+import {identity} from 'shared-runtime';
5
6
function useCondDepInSwitchMissingCase(props, other) {
7
const x = {};
@@ -21,5 +21,5 @@ function useCondDepInSwitchMissingCase(props, other) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: useCondDepInSwitchMissingCase,
24
- params: [{ a: { b: 2 } }, 2],
24
+ params: [{a: {b: 2}}, 2],
25
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cfg-switch-missing-default.expect.md
+2
-2
@@ -5,7 +5,7 @@
5
// props.a.b should NOT be added as a unconditional dependency to the reactive
6
// scope that produces x if it is not accessed in the default case.
7
8
-import { identity } from "shared-runtime";
8
+import {identity} from 'shared-runtime';
9
10
function useCondDepInSwitchMissingDefault(props, other) {
11
const x = {};
@@ -22,7 +22,7 @@ function useCondDepInSwitchMissingDefault(props, other) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: useCondDepInSwitchMissingDefault,
25
- params: [{ a: { b: 2 } }, 3],
25
+ params: [{a: {b: 2}}, 3],
26
};
27
28
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cfg-switch-missing-default.js
+2
-2
@@ -1,7 +1,7 @@
1
// props.a.b should NOT be added as a unconditional dependency to the reactive
2
// scope that produces x if it is not accessed in the default case.
3
4
-import { identity } from "shared-runtime";
4
+import {identity} from 'shared-runtime';
5
6
function useCondDepInSwitchMissingDefault(props, other) {
7
const x = {};
@@ -18,5 +18,5 @@ function useCondDepInSwitchMissingDefault(props, other) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: useCondDepInSwitchMissingDefault,
21
- params: [{ a: { b: 2 } }, 3],
21
+ params: [{a: {b: 2}}, 3],
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cond-scope.expect.md
+1
-1
@@ -20,7 +20,7 @@
20
// return x;
21
// ```
22
23
-import { CONST_FALSE, identity } from "shared-runtime";
23
+import {CONST_FALSE, identity} from 'shared-runtime';
24
25
function useReactiveDepsInCondScope(props) {
26
let x = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/cond-scope.js
+1
-1
@@ -16,7 +16,7 @@
16
// return x;
17
// ```
18
19
-import { CONST_FALSE, identity } from "shared-runtime";
19
+import {CONST_FALSE, identity} from 'shared-runtime';
20
21
function useReactiveDepsInCondScope(props) {
22
let x = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/conditional-member-expr.expect.md
+1
-1
@@ -14,7 +14,7 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ a: null }],
17
+ params: [{a: null}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/conditional-member-expr.js
+1
-1
@@ -10,5 +10,5 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ a: null }],
13
+ params: [{a: null}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/join-uncond-scopes-cond-deps.expect.md
+2
-2
@@ -19,7 +19,7 @@
19
// mutate2(y, props.a.b);
20
// }
21
22
-import { CONST_TRUE, setProperty } from "shared-runtime";
22
+import {CONST_TRUE, setProperty} from 'shared-runtime';
23
24
function useJoinCondDepsInUncondScopes(props) {
25
let y = {};
@@ -33,7 +33,7 @@ function useJoinCondDepsInUncondScopes(props) {
33
34
export const FIXTURE_ENTRYPOINT = {
35
fn: useJoinCondDepsInUncondScopes,
36
- params: [{ a: { b: 3 } }],
36
+ params: [{a: {b: 3}}],
37
};
38
39
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/join-uncond-scopes-cond-deps.js
+2
-2
@@ -15,7 +15,7 @@
15
// mutate2(y, props.a.b);
16
// }
17
18
-import { CONST_TRUE, setProperty } from "shared-runtime";
18
+import {CONST_TRUE, setProperty} from 'shared-runtime';
19
20
function useJoinCondDepsInUncondScopes(props) {
21
let y = {};
@@ -29,5 +29,5 @@ function useJoinCondDepsInUncondScopes(props) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: useJoinCondDepsInUncondScopes,
32
- params: [{ a: { b: 3 } }],
32
+ params: [{a: {b: 3}}],
33
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-poisoned/break-in-scope.expect.md
+7
-7
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function useFoo({ obj, objIsNull }) {
5
+function useFoo({obj, objIsNull}) {
6
const x = [];
7
b0: {
8
if (objIsNull) {
@@ -15,14 +15,14 @@ function useFoo({ obj, objIsNull }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: useFoo,
18
- params: [{ obj: null, objIsNull: true }],
18
+ params: [{obj: null, objIsNull: true}],
19
sequentialRenders: [
20
- { obj: null, objIsNull: true },
21
- { obj: { a: 2 }, objIsNull: false },
20
+ {obj: null, objIsNull: true},
21
+ {obj: {a: 2}, objIsNull: false},
22
// check we preserve nullthrows
23
- { obj: { a: undefined }, objIsNull: false },
24
- { obj: undefined, objIsNull: false },
25
- { obj: { a: undefined }, objIsNull: false },
23
+ {obj: {a: undefined}, objIsNull: false},
24
+ {obj: undefined, objIsNull: false},
25
+ {obj: {a: undefined}, objIsNull: false},
26
],
27
};
28
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-poisoned/break-in-scope.ts
+7
-7
@@ -1,4 +1,4 @@
1
-function useFoo({ obj, objIsNull }) {
1
+function useFoo({obj, objIsNull}) {
2
const x = [];
3
b0: {
4
if (objIsNull) {
@@ -11,13 +11,13 @@ function useFoo({ obj, objIsNull }) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: useFoo,
14
- params: [{ obj: null, objIsNull: true }],
14
+ params: [{obj: null, objIsNull: true}],
15
sequentialRenders: [
16
- { obj: null, objIsNull: true },
17
- { obj: { a: 2 }, objIsNull: false },
16
+ {obj: null, objIsNull: true},
17
+ {obj: {a: 2}, objIsNull: false},
18
// check we preserve nullthrows
19
- { obj: { a: undefined }, objIsNull: false },
20
- { obj: undefined, objIsNull: false },
21
- { obj: { a: undefined }, objIsNull: false },
19
+ {obj: {a: undefined}, objIsNull: false},
20
+ {obj: undefined, objIsNull: false},
21
+ {obj: {a: undefined}, objIsNull: false},
22
],
23
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-poisoned/break-poisons-outer-scope.expect.md
+10
-10
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
-function useFoo({ input, cond }) {
7
+function useFoo({input, cond}) {
8
const x = [];
9
label: {
10
if (cond) {
@@ -17,16 +17,16 @@ function useFoo({ input, cond }) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: useFoo,
20
- params: [{ input: { a: { b: 2 } }, cond: false }],
20
+ params: [{input: {a: {b: 2}}, cond: false}],
21
sequentialRenders: [
22
- { input: { a: { b: 2 } }, cond: false },
22
+ {input: {a: {b: 2}}, cond: false},
23
// preserve nullthrows
24
- { input: null, cond: false },
25
- { input: null, cond: true },
26
- { input: {}, cond: false },
27
- { input: { a: { b: null } }, cond: false },
28
- { input: { a: null }, cond: false },
29
- { input: { a: { b: 3 } }, cond: false },
24
+ {input: null, cond: false},
25
+ {input: null, cond: true},
26
+ {input: {}, cond: false},
27
+ {input: {a: {b: null}}, cond: false},
28
+ {input: {a: null}, cond: false},
29
+ {input: {a: {b: 3}}, cond: false},
30
],
31
};
32
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-poisoned/break-poisons-outer-scope.ts
+10
-10
@@ -1,6 +1,6 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
-function useFoo({ input, cond }) {
3
+function useFoo({input, cond}) {
4
const x = [];
5
label: {
6
if (cond) {
@@ -13,15 +13,15 @@ function useFoo({ input, cond }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: useFoo,
16
- params: [{ input: { a: { b: 2 } }, cond: false }],
16
+ params: [{input: {a: {b: 2}}, cond: false}],
17
sequentialRenders: [
18
- { input: { a: { b: 2 } }, cond: false },
18
+ {input: {a: {b: 2}}, cond: false},
19
// preserve nullthrows
20
- { input: null, cond: false },
21
- { input: null, cond: true },
22
- { input: {}, cond: false },
23
- { input: { a: { b: null } }, cond: false },
24
- { input: { a: null }, cond: false },
25
- { input: { a: { b: 3 } }, cond: false },
20
+ {input: null, cond: false},
21
+ {input: null, cond: true},
22
+ {input: {}, cond: false},
23
+ {input: {a: {b: null}}, cond: false},
24
+ {input: {a: null}, cond: false},
25
+ {input: {a: {b: 3}}, cond: false},
26
],
27
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-poisoned/loop-break-in-scope.expect.md
+7
-7
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function useFoo({ obj, objIsNull }) {
5
+function useFoo({obj, objIsNull}) {
6
const x = [];
7
for (let i = 0; i < 5; i++) {
8
if (objIsNull) {
@@ -15,14 +15,14 @@ function useFoo({ obj, objIsNull }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: useFoo,
18
- params: [{ obj: null, objIsNull: true }],
18
+ params: [{obj: null, objIsNull: true}],
19
sequentialRenders: [
20
- { obj: null, objIsNull: true },
21
- { obj: { a: 2 }, objIsNull: false },
20
+ {obj: null, objIsNull: true},
21
+ {obj: {a: 2}, objIsNull: false},
22
// check we preserve nullthrows
23
- { obj: { a: undefined }, objIsNull: false },
24
- { obj: undefined, objIsNull: false },
25
- { obj: { a: undefined }, objIsNull: false },
23
+ {obj: {a: undefined}, objIsNull: false},
24
+ {obj: undefined, objIsNull: false},
25
+ {obj: {a: undefined}, objIsNull: false},
26
],
27
};
28
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-poisoned/loop-break-in-scope.ts
+7
-7
@@ -1,4 +1,4 @@
1
-function useFoo({ obj, objIsNull }) {
1
+function useFoo({obj, objIsNull}) {
2
const x = [];
3
for (let i = 0; i < 5; i++) {
4
if (objIsNull) {
@@ -11,13 +11,13 @@ function useFoo({ obj, objIsNull }) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: useFoo,
14
- params: [{ obj: null, objIsNull: true }],
14
+ params: [{obj: null, objIsNull: true}],
15
sequentialRenders: [
16
- { obj: null, objIsNull: true },
17
- { obj: { a: 2 }, objIsNull: false },
16
+ {obj: null, objIsNull: true},
17
+ {obj: {a: 2}, objIsNull: false},
18
// check we preserve nullthrows
19
- { obj: { a: undefined }, objIsNull: false },
20
- { obj: undefined, objIsNull: false },
21
- { obj: { a: undefined }, objIsNull: false },
19
+ {obj: {a: undefined}, objIsNull: false},
20
+ {obj: undefined, objIsNull: false},
21
+ {obj: {a: undefined}, objIsNull: false},
22
],
23
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-poisoned/reduce-if-nonexhaustive-poisoned-deps.expect.md
+9
-9
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
-function useFoo({ input, cond, hasAB }) {
7
+function useFoo({input, cond, hasAB}) {
8
const x = [];
9
if (cond) {
10
if (!hasAB) {
@@ -19,15 +19,15 @@ function useFoo({ input, cond, hasAB }) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: useFoo,
22
- params: [{ input: { b: 1 }, cond: true, hasAB: false }],
22
+ params: [{input: {b: 1}, cond: true, hasAB: false}],
23
sequentialRenders: [
24
- { input: { a: { b: 1 } }, cond: true, hasAB: true },
25
- { input: null, cond: true, hasAB: false },
24
+ {input: {a: {b: 1}}, cond: true, hasAB: true},
25
+ {input: null, cond: true, hasAB: false},
26
// preserve nullthrows
27
- { input: { a: { b: undefined } }, cond: true, hasAB: true },
28
- { input: { a: undefined }, cond: true, hasAB: true },
29
- { input: { a: { b: undefined } }, cond: true, hasAB: true },
30
- { input: undefined, cond: true, hasAB: true },
27
+ {input: {a: {b: undefined}}, cond: true, hasAB: true},
28
+ {input: {a: undefined}, cond: true, hasAB: true},
29
+ {input: {a: {b: undefined}}, cond: true, hasAB: true},
30
+ {input: undefined, cond: true, hasAB: true},
31
],
32
};
33
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-poisoned/reduce-if-nonexhaustive-poisoned-deps.ts
+9
-9
@@ -1,6 +1,6 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
-function useFoo({ input, cond, hasAB }) {
3
+function useFoo({input, cond, hasAB}) {
4
const x = [];
5
if (cond) {
6
if (!hasAB) {
@@ -15,14 +15,14 @@ function useFoo({ input, cond, hasAB }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: useFoo,
18
- params: [{ input: { b: 1 }, cond: true, hasAB: false }],
18
+ params: [{input: {b: 1}, cond: true, hasAB: false}],
19
sequentialRenders: [
20
- { input: { a: { b: 1 } }, cond: true, hasAB: true },
21
- { input: null, cond: true, hasAB: false },
20
+ {input: {a: {b: 1}}, cond: true, hasAB: true},
21
+ {input: null, cond: true, hasAB: false},
22
// preserve nullthrows
23
- { input: { a: { b: undefined } }, cond: true, hasAB: true },
24
- { input: { a: undefined }, cond: true, hasAB: true },
25
- { input: { a: { b: undefined } }, cond: true, hasAB: true },
26
- { input: undefined, cond: true, hasAB: true },
23
+ {input: {a: {b: undefined}}, cond: true, hasAB: true},
24
+ {input: {a: undefined}, cond: true, hasAB: true},
25
+ {input: {a: {b: undefined}}, cond: true, hasAB: true},
26
+ {input: undefined, cond: true, hasAB: true},
27
],
28
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-poisoned/reduce-if-nonexhaustive-poisoned-deps1.expect.md
+8
-8
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
-function useFoo({ input, cond, hasAB }) {
7
+function useFoo({input, cond, hasAB}) {
8
const x = [];
9
if (cond) {
10
if (!hasAB) {
@@ -21,14 +21,14 @@ function useFoo({ input, cond, hasAB }) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: useFoo,
24
- params: [{ input: { b: 1 }, cond: true, hasAB: false }],
24
+ params: [{input: {b: 1}, cond: true, hasAB: false}],
25
sequentialRenders: [
26
- { input: { a: { b: 1 } }, cond: true, hasAB: true },
27
- { input: null, cond: true, hasAB: false },
26
+ {input: {a: {b: 1}}, cond: true, hasAB: true},
27
+ {input: null, cond: true, hasAB: false},
28
// preserve nullthrows
29
- { input: { a: { b: undefined } }, cond: true, hasAB: true },
30
- { input: { a: null }, cond: true, hasAB: true },
31
- { input: { a: { b: undefined } }, cond: true, hasAB: true },
29
+ {input: {a: {b: undefined}}, cond: true, hasAB: true},
30
+ {input: {a: null}, cond: true, hasAB: true},
31
+ {input: {a: {b: undefined}}, cond: true, hasAB: true},
32
],
33
};
34
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-poisoned/reduce-if-nonexhaustive-poisoned-deps1.ts
+8
-8
@@ -1,6 +1,6 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
-function useFoo({ input, cond, hasAB }) {
3
+function useFoo({input, cond, hasAB}) {
4
const x = [];
5
if (cond) {
6
if (!hasAB) {
@@ -17,13 +17,13 @@ function useFoo({ input, cond, hasAB }) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: useFoo,
20
- params: [{ input: { b: 1 }, cond: true, hasAB: false }],
20
+ params: [{input: {b: 1}, cond: true, hasAB: false}],
21
sequentialRenders: [
22
- { input: { a: { b: 1 } }, cond: true, hasAB: true },
23
- { input: null, cond: true, hasAB: false },
22
+ {input: {a: {b: 1}}, cond: true, hasAB: true},
23
+ {input: null, cond: true, hasAB: false},
24
// preserve nullthrows
25
- { input: { a: { b: undefined } }, cond: true, hasAB: true },
26
- { input: { a: null }, cond: true, hasAB: true },
27
- { input: { a: { b: undefined } }, cond: true, hasAB: true },
25
+ {input: {a: {b: undefined}}, cond: true, hasAB: true},
26
+ {input: {a: null}, cond: true, hasAB: true},
27
+ {input: {a: {b: undefined}}, cond: true, hasAB: true},
28
],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-poisoned/return-in-scope.expect.md
+7
-7
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function useFoo({ obj, objIsNull }) {
5
+function useFoo({obj, objIsNull}) {
6
const x = [];
7
if (objIsNull) {
8
return;
@@ -13,14 +13,14 @@ function useFoo({ obj, objIsNull }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: useFoo,
16
- params: [{ obj: null, objIsNull: true }],
16
+ params: [{obj: null, objIsNull: true}],
17
sequentialRenders: [
18
- { obj: null, objIsNull: true },
19
- { obj: { a: 2 }, objIsNull: false },
18
+ {obj: null, objIsNull: true},
19
+ {obj: {a: 2}, objIsNull: false},
20
// check we preserve nullthrows
21
- { obj: { a: undefined }, objIsNull: false },
22
- { obj: undefined, objIsNull: false },
23
- { obj: { a: undefined }, objIsNull: false },
21
+ {obj: {a: undefined}, objIsNull: false},
22
+ {obj: undefined, objIsNull: false},
23
+ {obj: {a: undefined}, objIsNull: false},
24
],
25
};
26
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-poisoned/return-in-scope.ts
+7
-7
@@ -1,4 +1,4 @@
1
-function useFoo({ obj, objIsNull }) {
1
+function useFoo({obj, objIsNull}) {
2
const x = [];
3
if (objIsNull) {
4
return;
@@ -9,13 +9,13 @@ function useFoo({ obj, objIsNull }) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: useFoo,
12
- params: [{ obj: null, objIsNull: true }],
12
+ params: [{obj: null, objIsNull: true}],
13
sequentialRenders: [
14
- { obj: null, objIsNull: true },
15
- { obj: { a: 2 }, objIsNull: false },
14
+ {obj: null, objIsNull: true},
15
+ {obj: {a: 2}, objIsNull: false},
16
// check we preserve nullthrows
17
- { obj: { a: undefined }, objIsNull: false },
18
- { obj: undefined, objIsNull: false },
19
- { obj: { a: undefined }, objIsNull: false },
17
+ {obj: {a: undefined}, objIsNull: false},
18
+ {obj: undefined, objIsNull: false},
19
+ {obj: {a: undefined}, objIsNull: false},
20
],
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-poisoned/return-poisons-outer-scope.expect.md
+10
-10
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
-function useFoo({ input, cond }) {
7
+function useFoo({input, cond}) {
8
const x = [];
9
if (cond) {
10
return null;
@@ -15,16 +15,16 @@ function useFoo({ input, cond }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: useFoo,
18
- params: [{ input: { a: { b: 2 } }, cond: false }],
18
+ params: [{input: {a: {b: 2}}, cond: false}],
19
sequentialRenders: [
20
- { input: { a: { b: 2 } }, cond: false },
20
+ {input: {a: {b: 2}}, cond: false},
21
// preserve nullthrows
22
- { input: null, cond: false },
23
- { input: null, cond: true },
24
- { input: {}, cond: false },
25
- { input: { a: { b: null } }, cond: false },
26
- { input: { a: null }, cond: false },
27
- { input: { a: { b: 3 } }, cond: false },
22
+ {input: null, cond: false},
23
+ {input: null, cond: true},
24
+ {input: {}, cond: false},
25
+ {input: {a: {b: null}}, cond: false},
26
+ {input: {a: null}, cond: false},
27
+ {input: {a: {b: 3}}, cond: false},
28
],
29
};
30
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-poisoned/return-poisons-outer-scope.ts
+10
-10
@@ -1,6 +1,6 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
-function useFoo({ input, cond }) {
3
+function useFoo({input, cond}) {
4
const x = [];
5
if (cond) {
6
return null;
@@ -11,15 +11,15 @@ function useFoo({ input, cond }) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: useFoo,
14
- params: [{ input: { a: { b: 2 } }, cond: false }],
14
+ params: [{input: {a: {b: 2}}, cond: false}],
15
sequentialRenders: [
16
- { input: { a: { b: 2 } }, cond: false },
16
+ {input: {a: {b: 2}}, cond: false},
17
// preserve nullthrows
18
- { input: null, cond: false },
19
- { input: null, cond: true },
20
- { input: {}, cond: false },
21
- { input: { a: { b: null } }, cond: false },
22
- { input: { a: null }, cond: false },
23
- { input: { a: { b: 3 } }, cond: false },
18
+ {input: null, cond: false},
19
+ {input: null, cond: true},
20
+ {input: {}, cond: false},
21
+ {input: {a: {b: null}}, cond: false},
22
+ {input: {a: null}, cond: false},
23
+ {input: {a: {b: 3}}, cond: false},
24
],
25
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-unpoisoned/else-branch-scope-unpoisoned.expect.md
+10
-10
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
-function useFoo({ input, cond }) {
7
+function useFoo({input, cond}) {
8
const x = [];
9
label: {
10
if (cond) {
@@ -18,16 +18,16 @@ function useFoo({ input, cond }) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: useFoo,
21
- params: [{ input: { a: { b: 2 } }, cond: false }],
21
+ params: [{input: {a: {b: 2}}, cond: false}],
22
sequentialRenders: [
23
- { input: null, cond: true },
24
- { input: { a: { b: 2 } }, cond: false },
25
- { input: null, cond: true },
23
+ {input: null, cond: true},
24
+ {input: {a: {b: 2}}, cond: false},
25
+ {input: null, cond: true},
26
// preserve nullthrows
27
- { input: {}, cond: false },
28
- { input: { a: { b: null } }, cond: false },
29
- { input: { a: null }, cond: false },
30
- { input: { a: { b: 3 } }, cond: false },
27
+ {input: {}, cond: false},
28
+ {input: {a: {b: null}}, cond: false},
29
+ {input: {a: null}, cond: false},
30
+ {input: {a: {b: 3}}, cond: false},
31
],
32
};
33
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-unpoisoned/else-branch-scope-unpoisoned.ts
+10
-10
@@ -1,6 +1,6 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
-function useFoo({ input, cond }) {
3
+function useFoo({input, cond}) {
4
const x = [];
5
label: {
6
if (cond) {
@@ -14,15 +14,15 @@ function useFoo({ input, cond }) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: useFoo,
17
- params: [{ input: { a: { b: 2 } }, cond: false }],
17
+ params: [{input: {a: {b: 2}}, cond: false}],
18
sequentialRenders: [
19
- { input: null, cond: true },
20
- { input: { a: { b: 2 } }, cond: false },
21
- { input: null, cond: true },
19
+ {input: null, cond: true},
20
+ {input: {a: {b: 2}}, cond: false},
21
+ {input: null, cond: true},
22
// preserve nullthrows
23
- { input: {}, cond: false },
24
- { input: { a: { b: null } }, cond: false },
25
- { input: { a: null }, cond: false },
26
- { input: { a: { b: 3 } }, cond: false },
23
+ {input: {}, cond: false},
24
+ {input: {a: {b: null}}, cond: false},
25
+ {input: {a: null}, cond: false},
26
+ {input: {a: {b: 3}}, cond: false},
27
],
28
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-unpoisoned/jump-target-within-scope-label.expect.md
+9
-9
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function useFoo({ input, cond }) {
5
+function useFoo({input, cond}) {
6
const x = [];
7
label: {
8
if (cond) {
@@ -15,16 +15,16 @@ function useFoo({ input, cond }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: useFoo,
18
- params: [{ input: { a: { b: 2 } }, cond: false }],
18
+ params: [{input: {a: {b: 2}}, cond: false}],
19
sequentialRenders: [
20
- { input: { a: { b: 2 } }, cond: false },
20
+ {input: {a: {b: 2}}, cond: false},
21
// preserve nullthrows
22
- { input: null, cond: false },
23
- { input: null, cond: true },
24
- { input: {}, cond: false },
25
- { input: { a: { b: null } }, cond: false },
26
- { input: { a: null }, cond: false },
27
- { input: { a: { b: 3 } }, cond: false },
22
+ {input: null, cond: false},
23
+ {input: null, cond: true},
24
+ {input: {}, cond: false},
25
+ {input: {a: {b: null}}, cond: false},
26
+ {input: {a: null}, cond: false},
27
+ {input: {a: {b: 3}}, cond: false},
28
],
29
};
30
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-unpoisoned/jump-target-within-scope-label.ts
+9
-9
@@ -1,4 +1,4 @@
1
-function useFoo({ input, cond }) {
1
+function useFoo({input, cond}) {
2
const x = [];
3
label: {
4
if (cond) {
@@ -11,15 +11,15 @@ function useFoo({ input, cond }) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: useFoo,
14
- params: [{ input: { a: { b: 2 } }, cond: false }],
14
+ params: [{input: {a: {b: 2}}, cond: false}],
15
sequentialRenders: [
16
- { input: { a: { b: 2 } }, cond: false },
16
+ {input: {a: {b: 2}}, cond: false},
17
// preserve nullthrows
18
- { input: null, cond: false },
19
- { input: null, cond: true },
20
- { input: {}, cond: false },
21
- { input: { a: { b: null } }, cond: false },
22
- { input: { a: null }, cond: false },
23
- { input: { a: { b: 3 } }, cond: false },
18
+ {input: null, cond: false},
19
+ {input: null, cond: true},
20
+ {input: {}, cond: false},
21
+ {input: {a: {b: null}}, cond: false},
22
+ {input: {a: null}, cond: false},
23
+ {input: {a: {b: 3}}, cond: false},
24
],
25
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-unpoisoned/jump-target-within-scope-loop-break.expect.md
+8
-8
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function useFoo({ input, max }) {
5
+function useFoo({input, max}) {
6
const x = [];
7
let i = 0;
8
while (true) {
@@ -18,15 +18,15 @@ function useFoo({ input, max }) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: useFoo,
21
- params: [{ input: { a: { b: 2 } }, max: 8 }],
21
+ params: [{input: {a: {b: 2}}, max: 8}],
22
sequentialRenders: [
23
- { input: { a: { b: 2 } }, max: 8 },
23
+ {input: {a: {b: 2}}, max: 8},
24
// preserve nullthrows
25
- { input: null, max: 8 },
26
- { input: {}, max: 8 },
27
- { input: { a: { b: null } }, max: 8 },
28
- { input: { a: null }, max: 8 },
29
- { input: { a: { b: 3 } }, max: 8 },
25
+ {input: null, max: 8},
26
+ {input: {}, max: 8},
27
+ {input: {a: {b: null}}, max: 8},
28
+ {input: {a: null}, max: 8},
29
+ {input: {a: {b: 3}}, max: 8},
30
],
31
};
32
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-unpoisoned/jump-target-within-scope-loop-break.ts
+8
-8
@@ -1,4 +1,4 @@
1
-function useFoo({ input, max }) {
1
+function useFoo({input, max}) {
2
const x = [];
3
let i = 0;
4
while (true) {
@@ -14,14 +14,14 @@ function useFoo({ input, max }) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: useFoo,
17
- params: [{ input: { a: { b: 2 } }, max: 8 }],
17
+ params: [{input: {a: {b: 2}}, max: 8}],
18
sequentialRenders: [
19
- { input: { a: { b: 2 } }, max: 8 },
19
+ {input: {a: {b: 2}}, max: 8},
20
// preserve nullthrows
21
- { input: null, max: 8 },
22
- { input: {}, max: 8 },
23
- { input: { a: { b: null } }, max: 8 },
24
- { input: { a: null }, max: 8 },
25
- { input: { a: { b: 3 } }, max: 8 },
21
+ {input: null, max: 8},
22
+ {input: {}, max: 8},
23
+ {input: {a: {b: null}}, max: 8},
24
+ {input: {a: null}, max: 8},
25
+ {input: {a: {b: 3}}, max: 8},
26
],
27
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-unpoisoned/reduce-if-exhaustive-nonpoisoned-deps.expect.md
+3
-3
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
-function useFoo({ input, hasAB, returnNull }) {
7
+function useFoo({input, hasAB, returnNull}) {
8
const x = [];
9
if (!hasAB) {
10
x.push(identity(input.a));
@@ -19,7 +19,7 @@ function useFoo({ input, hasAB, returnNull }) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: useFoo,
22
- params: [{ input: { b: 1 }, hasAB: false, returnNull: false }],
22
+ params: [{input: {b: 1}, hasAB: false, returnNull: false}],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-unpoisoned/reduce-if-exhaustive-nonpoisoned-deps.ts
+3
-3
@@ -1,6 +1,6 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
-function useFoo({ input, hasAB, returnNull }) {
3
+function useFoo({input, hasAB, returnNull}) {
4
const x = [];
5
if (!hasAB) {
6
x.push(identity(input.a));
@@ -15,5 +15,5 @@ function useFoo({ input, hasAB, returnNull }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: useFoo,
18
- params: [{ input: { b: 1 }, hasAB: false, returnNull: false }],
18
+ params: [{input: {b: 1}, hasAB: false, returnNull: false}],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-unpoisoned/reduce-if-exhaustive-nonpoisoned-deps1.expect.md
+8
-8
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
-function useFoo({ input, cond2, cond1 }) {
7
+function useFoo({input, cond2, cond1}) {
8
const x = [];
9
if (cond1) {
10
if (!cond2) {
@@ -21,14 +21,14 @@ function useFoo({ input, cond2, cond1 }) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: useFoo,
24
- params: [{ input: { b: 1 }, cond1: true, cond2: false }],
24
+ params: [{input: {b: 1}, cond1: true, cond2: false}],
25
sequentialRenders: [
26
- { input: { a: { b: 1 } }, cond1: true, cond2: true },
27
- { input: null, cond1: true, cond2: false },
26
+ {input: {a: {b: 1}}, cond1: true, cond2: true},
27
+ {input: null, cond1: true, cond2: false},
28
// preserve nullthrows
29
- { input: { a: { b: undefined } }, cond1: true, cond2: true },
30
- { input: { a: null }, cond1: true, cond2: true },
31
- { input: { a: { b: undefined } }, cond1: true, cond2: true },
29
+ {input: {a: {b: undefined}}, cond1: true, cond2: true},
30
+ {input: {a: null}, cond1: true, cond2: true},
31
+ {input: {a: {b: undefined}}, cond1: true, cond2: true},
32
],
33
};
34
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-unpoisoned/reduce-if-exhaustive-nonpoisoned-deps1.ts
+8
-8
@@ -1,6 +1,6 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
-function useFoo({ input, cond2, cond1 }) {
3
+function useFoo({input, cond2, cond1}) {
4
const x = [];
5
if (cond1) {
6
if (!cond2) {
@@ -17,13 +17,13 @@ function useFoo({ input, cond2, cond1 }) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: useFoo,
20
- params: [{ input: { b: 1 }, cond1: true, cond2: false }],
20
+ params: [{input: {b: 1}, cond1: true, cond2: false}],
21
sequentialRenders: [
22
- { input: { a: { b: 1 } }, cond1: true, cond2: true },
23
- { input: null, cond1: true, cond2: false },
22
+ {input: {a: {b: 1}}, cond1: true, cond2: true},
23
+ {input: null, cond1: true, cond2: false},
24
// preserve nullthrows
25
- { input: { a: { b: undefined } }, cond1: true, cond2: true },
26
- { input: { a: null }, cond1: true, cond2: true },
27
- { input: { a: { b: undefined } }, cond1: true, cond2: true },
25
+ {input: {a: {b: undefined}}, cond1: true, cond2: true},
26
+ {input: {a: null}, cond1: true, cond2: true},
27
+ {input: {a: {b: undefined}}, cond1: true, cond2: true},
28
],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-unpoisoned/return-before-scope-starts.expect.md
+11
-11
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-import { arrayPush } from "shared-runtime";
5
+import {arrayPush} from 'shared-runtime';
6
7
-function useFoo({ input, cond }) {
7
+function useFoo({input, cond}) {
8
if (cond) {
9
- return { result: "early return" };
9
+ return {result: 'early return'};
10
}
11
12
// unconditional
@@ -17,16 +17,16 @@ function useFoo({ input, cond }) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: useFoo,
20
- params: [{ input: { a: { b: 2 } }, cond: false }],
20
+ params: [{input: {a: {b: 2}}, cond: false}],
21
sequentialRenders: [
22
- { input: null, cond: true },
23
- { input: { a: { b: 2 } }, cond: false },
24
- { input: null, cond: true },
22
+ {input: null, cond: true},
23
+ {input: {a: {b: 2}}, cond: false},
24
+ {input: null, cond: true},
25
// preserve nullthrows
26
- { input: {}, cond: false },
27
- { input: { a: { b: null } }, cond: false },
28
- { input: { a: null }, cond: false },
29
- { input: { a: { b: 3 } }, cond: false },
26
+ {input: {}, cond: false},
27
+ {input: {a: {b: null}}, cond: false},
28
+ {input: {a: null}, cond: false},
29
+ {input: {a: {b: 3}}, cond: false},
30
],
31
};
32
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-unpoisoned/return-before-scope-starts.ts
+11
-11
@@ -1,8 +1,8 @@
1
-import { arrayPush } from "shared-runtime";
1
+import {arrayPush} from 'shared-runtime';
2
3
-function useFoo({ input, cond }) {
3
+function useFoo({input, cond}) {
4
if (cond) {
5
- return { result: "early return" };
5
+ return {result: 'early return'};
6
}
7
8
// unconditional
@@ -13,15 +13,15 @@ function useFoo({ input, cond }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: useFoo,
16
- params: [{ input: { a: { b: 2 } }, cond: false }],
16
+ params: [{input: {a: {b: 2}}, cond: false}],
17
sequentialRenders: [
18
- { input: null, cond: true },
19
- { input: { a: { b: 2 } }, cond: false },
20
- { input: null, cond: true },
18
+ {input: null, cond: true},
19
+ {input: {a: {b: 2}}, cond: false},
20
+ {input: null, cond: true},
21
// preserve nullthrows
22
- { input: {}, cond: false },
23
- { input: { a: { b: null } }, cond: false },
24
- { input: { a: null }, cond: false },
25
- { input: { a: { b: 3 } }, cond: false },
22
+ {input: {}, cond: false},
23
+ {input: {a: {b: null}}, cond: false},
24
+ {input: {a: null}, cond: false},
25
+ {input: {a: {b: 3}}, cond: false},
26
],
27
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-unpoisoned/throw-before-scope-starts.expect.md
+11
-11
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-import { arrayPush } from "shared-runtime";
5
+import {arrayPush} from 'shared-runtime';
6
7
-function useFoo({ input, cond }) {
7
+function useFoo({input, cond}) {
8
if (cond) {
9
- throw new Error("throw with error!");
9
+ throw new Error('throw with error!');
10
}
11
12
// unconditional
@@ -17,16 +17,16 @@ function useFoo({ input, cond }) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: useFoo,
20
- params: [{ input: { a: { b: 2 } }, cond: false }],
20
+ params: [{input: {a: {b: 2}}, cond: false}],
21
sequentialRenders: [
22
- { input: null, cond: true },
23
- { input: { a: { b: 2 } }, cond: false },
24
- { input: null, cond: true },
22
+ {input: null, cond: true},
23
+ {input: {a: {b: 2}}, cond: false},
24
+ {input: null, cond: true},
25
// preserve nullthrows
26
- { input: {}, cond: false },
27
- { input: { a: { b: null } }, cond: false },
28
- { input: { a: null }, cond: false },
29
- { input: { a: { b: 3 } }, cond: false },
26
+ {input: {}, cond: false},
27
+ {input: {a: {b: null}}, cond: false},
28
+ {input: {a: null}, cond: false},
29
+ {input: {a: {b: 3}}, cond: false},
30
],
31
};
32
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/jump-unpoisoned/throw-before-scope-starts.ts
+11
-11
@@ -1,8 +1,8 @@
1
-import { arrayPush } from "shared-runtime";
1
+import {arrayPush} from 'shared-runtime';
2
3
-function useFoo({ input, cond }) {
3
+function useFoo({input, cond}) {
4
if (cond) {
5
- throw new Error("throw with error!");
5
+ throw new Error('throw with error!');
6
}
7
8
// unconditional
@@ -13,15 +13,15 @@ function useFoo({ input, cond }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: useFoo,
16
- params: [{ input: { a: { b: 2 } }, cond: false }],
16
+ params: [{input: {a: {b: 2}}, cond: false}],
17
sequentialRenders: [
18
- { input: null, cond: true },
19
- { input: { a: { b: 2 } }, cond: false },
20
- { input: null, cond: true },
18
+ {input: null, cond: true},
19
+ {input: {a: {b: 2}}, cond: false},
20
+ {input: null, cond: true},
21
// preserve nullthrows
22
- { input: {}, cond: false },
23
- { input: { a: { b: null } }, cond: false },
24
- { input: { a: null }, cond: false },
25
- { input: { a: { b: 3 } }, cond: false },
22
+ {input: {}, cond: false},
23
+ {input: {a: {b: null}}, cond: false},
24
+ {input: {a: null}, cond: false},
25
+ {input: {a: {b: 3}}, cond: false},
26
],
27
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/memberexpr-join-optional-chain.expect.md
+1
-1
@@ -22,7 +22,7 @@ function Component(props) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
25
- params: [{ a: { b: { c: 1 } } }],
25
+ params: [{a: {b: {c: 1}}}],
26
};
27
28
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/memberexpr-join-optional-chain.ts
+1
-1
@@ -18,5 +18,5 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ a: { b: { c: 1 } } }],
21
+ params: [{a: {b: {c: 1}}}],
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/memberexpr-join-optional-chain2.expect.md
+1
-1
@@ -11,7 +11,7 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ items: { edges: null, length: 0 } }],
14
+ params: [{items: {edges: null, length: 0}}],
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/memberexpr-join-optional-chain2.ts
+1
-1
@@ -7,5 +7,5 @@ function Component(props) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: [{ items: { edges: null, length: 0 } }],
10
+ params: [{items: {edges: null, length: 0}}],
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/no-uncond.expect.md
+9
-9
@@ -4,10 +4,10 @@
4
```javascript
5
// When an object's properties are only read conditionally, we should
6
7
-import { identity } from "shared-runtime";
7
+import {identity} from 'shared-runtime';
8
9
// track the base object as a dependency.
10
-function useOnlyConditionalDependencies({ props, cond }) {
10
+function useOnlyConditionalDependencies({props, cond}) {
11
const x = {};
12
if (identity(cond)) {
13
x.b = props.a.b;
@@ -18,15 +18,15 @@ function useOnlyConditionalDependencies({ props, cond }) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: useOnlyConditionalDependencies,
21
- params: [{ props: { a: { b: 2 } }, cond: true }],
21
+ params: [{props: {a: {b: 2}}, cond: true}],
22
sequentialRenders: [
23
- { props: { a: { b: 2 } }, cond: true },
24
- { props: null, cond: false },
23
+ {props: {a: {b: 2}}, cond: true},
24
+ {props: null, cond: false},
25
// check we preserve nullthrows
26
- { props: { a: { b: { c: undefined } } }, cond: true },
27
- { props: { a: { b: undefined } }, cond: true },
28
- { props: { a: { b: { c: undefined } } }, cond: true },
29
- { props: undefined, cond: true },
26
+ {props: {a: {b: {c: undefined}}}, cond: true},
27
+ {props: {a: {b: undefined}}, cond: true},
28
+ {props: {a: {b: {c: undefined}}}, cond: true},
29
+ {props: undefined, cond: true},
30
],
31
};
32
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/no-uncond.js
+9
-9
@@ -1,9 +1,9 @@
1
// When an object's properties are only read conditionally, we should
2
3
-import { identity } from "shared-runtime";
3
+import {identity} from 'shared-runtime';
4
5
// track the base object as a dependency.
6
-function useOnlyConditionalDependencies({ props, cond }) {
6
+function useOnlyConditionalDependencies({props, cond}) {
7
const x = {};
8
if (identity(cond)) {
9
x.b = props.a.b;
@@ -14,14 +14,14 @@ function useOnlyConditionalDependencies({ props, cond }) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: useOnlyConditionalDependencies,
17
- params: [{ props: { a: { b: 2 } }, cond: true }],
17
+ params: [{props: {a: {b: 2}}, cond: true}],
18
sequentialRenders: [
19
- { props: { a: { b: 2 } }, cond: true },
20
- { props: null, cond: false },
19
+ {props: {a: {b: 2}}, cond: true},
20
+ {props: null, cond: false},
21
// check we preserve nullthrows
22
- { props: { a: { b: { c: undefined } } }, cond: true },
23
- { props: { a: { b: undefined } }, cond: true },
24
- { props: { a: { b: { c: undefined } } }, cond: true },
25
- { props: undefined, cond: true },
22
+ {props: {a: {b: {c: undefined}}}, cond: true},
23
+ {props: {a: {b: undefined}}, cond: true},
24
+ {props: {a: {b: {c: undefined}}}, cond: true},
25
+ {props: undefined, cond: true},
26
],
27
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/promote-uncond.expect.md
+2
-2
@@ -5,7 +5,7 @@
5
// When a conditional dependency `props.a.b.c` has no unconditional dependency
6
// in its subpath or superpath, we should find the nearest unconditional access
7
8
-import { identity } from "shared-runtime";
8
+import {identity} from 'shared-runtime';
9
10
// and promote it to an unconditional dependency.
11
function usePromoteUnconditionalAccessToDependency(props, other) {
@@ -19,7 +19,7 @@ function usePromoteUnconditionalAccessToDependency(props, other) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: usePromoteUnconditionalAccessToDependency,
22
- params: [{ a: { a: { a: 3 } } }, false],
22
+ params: [{a: {a: {a: 3}}}, false],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/promote-uncond.js
+2
-2
@@ -1,7 +1,7 @@
1
// When a conditional dependency `props.a.b.c` has no unconditional dependency
2
// in its subpath or superpath, we should find the nearest unconditional access
3
4
-import { identity } from "shared-runtime";
4
+import {identity} from 'shared-runtime';
5
6
// and promote it to an unconditional dependency.
7
function usePromoteUnconditionalAccessToDependency(props, other) {
@@ -15,5 +15,5 @@ function usePromoteUnconditionalAccessToDependency(props, other) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: usePromoteUnconditionalAccessToDependency,
18
- params: [{ a: { a: { a: 3 } } }, false],
18
+ params: [{a: {a: {a: 3}}}, false],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/reduce-if-exhaustive-poisoned-deps.expect.md
+3
-3
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
-function useFoo({ input, inputHasAB, inputHasABC }) {
7
+function useFoo({input, inputHasAB, inputHasABC}) {
8
const x = [];
9
if (!inputHasABC) {
10
x.push(identity(input.a));
@@ -20,7 +20,7 @@ function useFoo({ input, inputHasAB, inputHasABC }) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: useFoo,
23
- params: [{ input: { b: 1 }, inputHasAB: false, inputHasABC: false }],
23
+ params: [{input: {b: 1}, inputHasAB: false, inputHasABC: false}],
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/reduce-if-exhaustive-poisoned-deps.ts
+3
-3
@@ -1,6 +1,6 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
-function useFoo({ input, inputHasAB, inputHasABC }) {
3
+function useFoo({input, inputHasAB, inputHasABC}) {
4
const x = [];
5
if (!inputHasABC) {
6
x.push(identity(input.a));
@@ -16,5 +16,5 @@ function useFoo({ input, inputHasAB, inputHasABC }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: useFoo,
19
- params: [{ input: { b: 1 }, inputHasAB: false, inputHasABC: false }],
19
+ params: [{input: {b: 1}, inputHasAB: false, inputHasABC: false}],
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/subpath-order1.expect.md
+2
-2
@@ -7,7 +7,7 @@
7
// semantics (with respect to nullthrows).
8
// deps: {`props.a`, `props.a.b`} can further reduce to just `props.a`
9
10
-import { identity } from "shared-runtime";
10
+import {identity} from 'shared-runtime';
11
12
// ordering of accesses should not matter
13
function useConditionalSubpath1(props, cond) {
@@ -21,7 +21,7 @@ function useConditionalSubpath1(props, cond) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: useConditionalSubpath1,
24
- params: [{ a: { b: 3 } }, false],
24
+ params: [{a: {b: 3}}, false],
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/subpath-order1.js
+2
-2
@@ -3,7 +3,7 @@
3
// semantics (with respect to nullthrows).
4
// deps: {`props.a`, `props.a.b`} can further reduce to just `props.a`
5
6
-import { identity } from "shared-runtime";
6
+import {identity} from 'shared-runtime';
7
8
// ordering of accesses should not matter
9
function useConditionalSubpath1(props, cond) {
@@ -17,5 +17,5 @@ function useConditionalSubpath1(props, cond) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: useConditionalSubpath1,
20
- params: [{ a: { b: 3 } }, false],
20
+ params: [{a: {b: 3}}, false],
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/subpath-order2.expect.md
+2
-2
@@ -7,7 +7,7 @@
7
// semantics (with respect to nullthrows).
8
// deps: {`props.a`, `props.a.b`} can further reduce to just `props.a`
9
10
-import { identity } from "shared-runtime";
10
+import {identity} from 'shared-runtime';
11
12
// ordering of accesses should not matter
13
function useConditionalSubpath2(props, other) {
@@ -21,7 +21,7 @@ function useConditionalSubpath2(props, other) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: useConditionalSubpath2,
24
- params: [{ a: { b: 3 } }, false],
24
+ params: [{a: {b: 3}}, false],
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/subpath-order2.js
+2
-2
@@ -3,7 +3,7 @@
3
// semantics (with respect to nullthrows).
4
// deps: {`props.a`, `props.a.b`} can further reduce to just `props.a`
5
6
-import { identity } from "shared-runtime";
6
+import {identity} from 'shared-runtime';
7
8
// ordering of accesses should not matter
9
function useConditionalSubpath2(props, other) {
@@ -17,5 +17,5 @@ function useConditionalSubpath2(props, other) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: useConditionalSubpath2,
20
- params: [{ a: { b: 3 } }, false],
20
+ params: [{a: {b: 3}}, false],
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/superpath-order1.expect.md
+9
-9
@@ -6,10 +6,10 @@
6
// dependency `props.a.b`, we can safely overestimate and only track `props.a`
7
// as a dependency
8
9
-import { identity } from "shared-runtime";
9
+import {identity} from 'shared-runtime';
10
11
// ordering of accesses should not matter
12
-function useConditionalSuperpath1({ props, cond }) {
12
+function useConditionalSuperpath1({props, cond}) {
13
const x = {};
14
x.a = props.a;
15
if (identity(cond)) {
@@ -20,15 +20,15 @@ function useConditionalSuperpath1({ props, cond }) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: useConditionalSuperpath1,
23
- params: [{ props: { a: null }, cond: false }],
23
+ params: [{props: {a: null}, cond: false}],
24
sequentialRenders: [
25
- { props: { a: null }, cond: false },
26
- { props: { a: {} }, cond: true },
27
- { props: { a: { b: 3 } }, cond: true },
28
- { props: {}, cond: false },
25
+ {props: {a: null}, cond: false},
26
+ {props: {a: {}}, cond: true},
27
+ {props: {a: {b: 3}}, cond: true},
28
+ {props: {}, cond: false},
29
// test that we preserve nullthrows
30
- { props: { a: { b: undefined } }, cond: true },
31
- { props: { a: undefined }, cond: true },
30
+ {props: {a: {b: undefined}}, cond: true},
31
+ {props: {a: undefined}, cond: true},
32
],
33
};
34
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/superpath-order1.js
+9
-9
@@ -2,10 +2,10 @@
2
// dependency `props.a.b`, we can safely overestimate and only track `props.a`
3
// as a dependency
4
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
// ordering of accesses should not matter
8
-function useConditionalSuperpath1({ props, cond }) {
8
+function useConditionalSuperpath1({props, cond}) {
9
const x = {};
10
x.a = props.a;
11
if (identity(cond)) {
@@ -16,14 +16,14 @@ function useConditionalSuperpath1({ props, cond }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: useConditionalSuperpath1,
19
- params: [{ props: { a: null }, cond: false }],
19
+ params: [{props: {a: null}, cond: false}],
20
sequentialRenders: [
21
- { props: { a: null }, cond: false },
22
- { props: { a: {} }, cond: true },
23
- { props: { a: { b: 3 } }, cond: true },
24
- { props: {}, cond: false },
21
+ {props: {a: null}, cond: false},
22
+ {props: {a: {}}, cond: true},
23
+ {props: {a: {b: 3}}, cond: true},
24
+ {props: {}, cond: false},
25
// test that we preserve nullthrows
26
- { props: { a: { b: undefined } }, cond: true },
27
- { props: { a: undefined }, cond: true },
26
+ {props: {a: {b: undefined}}, cond: true},
27
+ {props: {a: undefined}, cond: true},
28
],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/superpath-order2.expect.md
+9
-9
@@ -6,10 +6,10 @@
6
// dependency `props.a.b`, we can safely overestimate and only track `props.a`
7
// as a dependency
8
9
-import { identity } from "shared-runtime";
9
+import {identity} from 'shared-runtime';
10
11
// ordering of accesses should not matter
12
-function useConditionalSuperpath2({ props, cond }) {
12
+function useConditionalSuperpath2({props, cond}) {
13
const x = {};
14
if (identity(cond)) {
15
x.b = props.a.b;
@@ -20,15 +20,15 @@ function useConditionalSuperpath2({ props, cond }) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: useConditionalSuperpath2,
23
- params: [{ props: { a: null }, cond: false }],
23
+ params: [{props: {a: null}, cond: false}],
24
sequentialRenders: [
25
- { props: { a: null }, cond: false },
26
- { props: { a: {} }, cond: true },
27
- { props: { a: { b: 3 } }, cond: true },
28
- { props: {}, cond: false },
25
+ {props: {a: null}, cond: false},
26
+ {props: {a: {}}, cond: true},
27
+ {props: {a: {b: 3}}, cond: true},
28
+ {props: {}, cond: false},
29
// test that we preserve nullthrows
30
- { props: { a: { b: undefined } }, cond: true },
31
- { props: { a: undefined }, cond: true },
30
+ {props: {a: {b: undefined}}, cond: true},
31
+ {props: {a: undefined}, cond: true},
32
],
33
};
34
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/superpath-order2.js
+9
-9
@@ -2,10 +2,10 @@
2
// dependency `props.a.b`, we can safely overestimate and only track `props.a`
3
// as a dependency
4
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
// ordering of accesses should not matter
8
-function useConditionalSuperpath2({ props, cond }) {
8
+function useConditionalSuperpath2({props, cond}) {
9
const x = {};
10
if (identity(cond)) {
11
x.b = props.a.b;
@@ -16,14 +16,14 @@ function useConditionalSuperpath2({ props, cond }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: useConditionalSuperpath2,
19
- params: [{ props: { a: null }, cond: false }],
19
+ params: [{props: {a: null}, cond: false}],
20
sequentialRenders: [
21
- { props: { a: null }, cond: false },
22
- { props: { a: {} }, cond: true },
23
- { props: { a: { b: 3 } }, cond: true },
24
- { props: {}, cond: false },
21
+ {props: {a: null}, cond: false},
22
+ {props: {a: {}}, cond: true},
23
+ {props: {a: {b: 3}}, cond: true},
24
+ {props: {}, cond: false},
25
// test that we preserve nullthrows
26
- { props: { a: { b: undefined } }, cond: true },
27
- { props: { a: undefined }, cond: true },
26
+ {props: {a: {b: undefined}}, cond: true},
27
+ {props: {a: undefined}, cond: true},
28
],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/uncond-nonoverlap-descendant.expect.md
+1
-1
@@ -14,7 +14,7 @@ function TestNonOverlappingDescendantTracked(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: TestNonOverlappingDescendantTracked,
17
- params: [{ a: { x: {}, c: { x: { y: { z: 3 } } } } }],
17
+ params: [{a: {x: {}, c: {x: {y: {z: 3}}}}}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/uncond-nonoverlap-descendant.js
+1
-1
@@ -10,5 +10,5 @@ function TestNonOverlappingDescendantTracked(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: TestNonOverlappingDescendantTracked,
13
- params: [{ a: { x: {}, c: { x: { y: { z: 3 } } } } }],
13
+ params: [{a: {x: {}, c: {x: {y: {z: 3}}}}}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/uncond-nonoverlap-direct.expect.md
+1
-1
@@ -13,7 +13,7 @@ function TestNonOverlappingTracked(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: TestNonOverlappingTracked,
16
- params: [{ a: { b: 2, c: 3 } }],
16
+ params: [{a: {b: 2, c: 3}}],
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/uncond-nonoverlap-direct.js
+1
-1
@@ -9,5 +9,5 @@ function TestNonOverlappingTracked(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: TestNonOverlappingTracked,
12
- params: [{ a: { b: 2, c: 3 } }],
12
+ params: [{a: {b: 2, c: 3}}],
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/uncond-overlap-descendant.expect.md
+1
-1
@@ -14,7 +14,7 @@ function TestOverlappingDescendantTracked(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: TestOverlappingDescendantTracked,
17
- params: [{ a: { b: { c: { x: { y: 5 } } } } }],
17
+ params: [{a: {b: {c: {x: {y: 5}}}}}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/uncond-overlap-descendant.js
+1
-1
@@ -10,5 +10,5 @@ function TestOverlappingDescendantTracked(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: TestOverlappingDescendantTracked,
13
- params: [{ a: { b: { c: { x: { y: 5 } } } } }],
13
+ params: [{a: {b: {c: {x: {y: 5}}}}}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/uncond-overlap-direct.expect.md
+1
-1
@@ -14,7 +14,7 @@ function TestOverlappingTracked(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: TestOverlappingTracked,
17
- params: [{ a: { c: 2 } }],
17
+ params: [{a: {c: 2}}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/uncond-overlap-direct.js
+1
-1
@@ -10,5 +10,5 @@ function TestOverlappingTracked(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: TestOverlappingTracked,
13
- params: [{ a: { c: 2 } }],
13
+ params: [{a: {c: 2}}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/uncond-subpath-order1.expect.md
+1
-1
@@ -14,7 +14,7 @@ function TestDepsSubpathOrder1(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: TestDepsSubpathOrder1,
17
- params: [{ a: { b: { c: 2 } } }],
17
+ params: [{a: {b: {c: 2}}}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/uncond-subpath-order1.js
+1
-1
@@ -10,5 +10,5 @@ function TestDepsSubpathOrder1(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: TestDepsSubpathOrder1,
13
- params: [{ a: { b: { c: 2 } } }],
13
+ params: [{a: {b: {c: 2}}}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/uncond-subpath-order2.expect.md
+1
-1
@@ -14,7 +14,7 @@ function TestDepsSubpathOrder2(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: TestDepsSubpathOrder2,
17
- params: [{ a: { b: { c: 2 } } }],
17
+ params: [{a: {b: {c: 2}}}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/uncond-subpath-order2.js
+1
-1
@@ -10,5 +10,5 @@ function TestDepsSubpathOrder2(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: TestDepsSubpathOrder2,
13
- params: [{ a: { b: { c: 2 } } }],
13
+ params: [{a: {b: {c: 2}}}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/uncond-subpath-order3.expect.md
+1
-1
@@ -14,7 +14,7 @@ function TestDepsSubpathOrder3(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: TestDepsSubpathOrder3,
17
- params: [{ a: { b: { c: 2 } } }],
17
+ params: [{a: {b: {c: 2}}}],
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reduce-reactive-deps/uncond-subpath-order3.js
+1
-1
@@ -10,5 +10,5 @@ function TestDepsSubpathOrder3(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: TestDepsSubpathOrder3,
13
- params: [{ a: { b: { c: 2 } } }],
13
+ params: [{a: {b: {c: 2}}}],
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-current-aliased-not-added-to-dep-2.expect.md
+2
-2
@@ -3,10 +3,10 @@
3
4
```javascript
5
// @validateRefAccessDuringRender:false
6
-function Foo({ a }) {
6
+function Foo({a}) {
7
const ref = useRef();
8
const val = ref.current;
9
- const x = { a, val };
9
+ const x = {a, val};
10
11
return <VideoList videos={x} />;
12
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-current-aliased-not-added-to-dep-2.js
+2
-2
@@ -1,8 +1,8 @@
1
// @validateRefAccessDuringRender:false
2
-function Foo({ a }) {
2
+function Foo({a}) {
3
const ref = useRef();
4
const val = ref.current;
5
- const x = { a, val };
5
+ const x = {a, val};
6
7
return <VideoList videos={x} />;
8
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-current-field-write-not-added-to-dep.expect.md
+3
-3
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-import { useRef } from "react";
5
+import {useRef} from 'react';
6
7
function Component() {
8
- const ref = useRef({ text: { value: null } });
9
- const inputChanged = (e) => {
8
+ const ref = useRef({text: {value: null}});
9
+ const inputChanged = e => {
10
ref.current.text.value = e.target.value;
11
};
12
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-current-field-write-not-added-to-dep.js
+3
-3
@@ -1,8 +1,8 @@
1
-import { useRef } from "react";
1
+import {useRef} from 'react';
2
3
function Component() {
4
- const ref = useRef({ text: { value: null } });
5
- const inputChanged = (e) => {
4
+ const ref = useRef({text: {value: null}});
5
+ const inputChanged = e => {
6
ref.current.text.value = e.target.value;
7
};
8
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-current-not-added-to-dep-2.expect.md
+2
-2
@@ -3,9 +3,9 @@
3
4
```javascript
5
// @validateRefAccessDuringRender:false
6
-function Foo({ a }) {
6
+function Foo({a}) {
7
const ref = useRef();
8
- const x = { a, val: ref.current };
8
+ const x = {a, val: ref.current};
9
10
return <VideoList videos={x} />;
11
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-current-not-added-to-dep-2.js
+2
-2
@@ -1,7 +1,7 @@
1
// @validateRefAccessDuringRender:false
2
-function Foo({ a }) {
2
+function Foo({a}) {
3
const ref = useRef();
4
- const x = { a, val: ref.current };
4
+ const x = {a, val: ref.current};
5
6
return <VideoList videos={x} />;
7
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-in-effect.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
function Component(props) {
6
const ref = useRef(null);
7
- const onChange = (e) => {
7
+ const onChange = e => {
8
const newValue = e.target.value ?? ref.current;
9
ref.current = newValue;
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-in-effect.js
+1
-1
@@ -1,6 +1,6 @@
1
function Component(props) {
2
const ref = useRef(null);
3
- const onChange = (e) => {
3
+ const onChange = e => {
4
const newValue = e.target.value ?? ref.current;
5
ref.current = newValue;
6
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-like-name-in-effect.expect.md
+2
-2
@@ -3,10 +3,10 @@
3
4
```javascript
5
// @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
6
-import { useRef, useEffect } from "react";
6
+import {useRef, useEffect} from 'react';
7
8
function useCustomRef() {
9
- return useRef({ click: () => {} });
9
+ return useRef({click: () => {}});
10
}
11
12
function Foo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-like-name-in-effect.js
+2
-2
@@ -1,8 +1,8 @@
1
// @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
2
-import { useRef, useEffect } from "react";
2
+import {useRef, useEffect} from 'react';
3
4
function useCustomRef() {
5
- return useRef({ click: () => {} });
5
+ return useRef({click: () => {}});
6
}
7
8
function Foo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-like-name-in-useCallback-2.expect.md
+2
-2
@@ -3,10 +3,10 @@
3
4
```javascript
5
// @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
6
-import { useRef, useCallback } from "react";
6
+import {useRef, useCallback} from 'react';
7
8
function useCustomRef() {
9
- return useRef({ click: () => {} });
9
+ return useRef({click: () => {}});
10
}
11
12
function Foo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-like-name-in-useCallback-2.js
+2
-2
@@ -1,8 +1,8 @@
1
// @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
2
-import { useRef, useCallback } from "react";
2
+import {useRef, useCallback} from 'react';
3
4
function useCustomRef() {
5
- return useRef({ click: () => {} });
5
+ return useRef({click: () => {}});
6
}
7
8
function Foo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-like-name-in-useCallback.expect.md
+2
-2
@@ -3,10 +3,10 @@
3
4
```javascript
5
// @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
6
-import { useRef, useCallback } from "react";
6
+import {useRef, useCallback} from 'react';
7
8
function useCustomRef() {
9
- return useRef({ click: () => {} });
9
+ return useRef({click: () => {}});
10
}
11
12
function Foo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-like-name-in-useCallback.js
+2
-2
@@ -1,8 +1,8 @@
1
// @enableTreatRefLikeIdentifiersAsRefs @validatePreserveExistingMemoizationGuarantees
2
-import { useRef, useCallback } from "react";
2
+import {useRef, useCallback} from 'react';
3
4
function useCustomRef() {
5
- return useRef({ click: () => {} });
5
+ return useRef({click: () => {}});
6
}
7
8
function Foo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-parameter-mutate-in-effect.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useEffect } from "react";
5
+import {useEffect} from 'react';
6
7
function Foo(props, ref) {
8
useEffect(() => {
@@ -13,7 +13,7 @@ function Foo(props, ref) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Foo,
16
- params: [{ bar: "foo" }, { ref: { cuurrent: 1 } }],
16
+ params: [{bar: 'foo'}, {ref: {cuurrent: 1}}],
17
isComponent: true,
18
};
19
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ref-parameter-mutate-in-effect.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { useEffect } from "react";
1
+import {useEffect} from 'react';
2
3
function Foo(props, ref) {
4
useEffect(() => {
@@ -9,6 +9,6 @@ function Foo(props, ref) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Foo,
12
- params: [{ bar: "foo" }, { ref: { cuurrent: 1 } }],
12
+ params: [{bar: 'foo'}, {ref: {cuurrent: 1}}],
13
isComponent: true,
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rename-source-variables-nested-function.expect.md
+6
-6
@@ -3,12 +3,12 @@
3
4
```javascript
5
// @enableChangeVariableCodegen
6
-import { identity } from "shared-runtime";
6
+import {identity} from 'shared-runtime';
7
8
-const $ = "module_$";
9
-const t0 = "module_t0";
10
-const c_0 = "module_c_0";
11
-function useFoo(props: { value: number }): number {
8
+const $ = 'module_$';
9
+const t0 = 'module_t0';
10
+const c_0 = 'module_c_0';
11
+function useFoo(props: {value: number}): number {
12
const a = () => {
13
const b = () => {
14
const c = () => {
@@ -26,7 +26,7 @@ function useFoo(props: { value: number }): number {
26
27
export const FIXTURE_ENTRYPOINT = {
28
fn: useFoo,
29
- params: [{ value: 42 }],
29
+ params: [{value: 42}],
30
};
31
32
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rename-source-variables-nested-function.js
+6
-6
@@ -1,10 +1,10 @@
1
// @enableChangeVariableCodegen
2
-import { identity } from "shared-runtime";
2
+import {identity} from 'shared-runtime';
3
4
-const $ = "module_$";
5
-const t0 = "module_t0";
6
-const c_0 = "module_c_0";
7
-function useFoo(props: { value: number }): number {
4
+const $ = 'module_$';
5
+const t0 = 'module_t0';
6
+const c_0 = 'module_c_0';
7
+function useFoo(props: {value: number}): number {
8
const a = () => {
9
const b = () => {
10
const c = () => {
@@ -22,5 +22,5 @@ function useFoo(props: { value: number }): number {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: useFoo,
25
- params: [{ value: 42 }],
25
+ params: [{value: 42}],
26
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rename-source-variables-nested-object-method.expect.md
+6
-6
@@ -3,12 +3,12 @@
3
4
```javascript
5
// @enableChangeVariableCodegen
6
-import { identity } from "shared-runtime";
6
+import {identity} from 'shared-runtime';
7
8
-const $ = "module_$";
9
-const t0 = "module_t0";
10
-const c_0 = "module_c_0";
11
-function useFoo(props: { value: number }): number {
8
+const $ = 'module_$';
9
+const t0 = 'module_t0';
10
+const c_0 = 'module_c_0';
11
+function useFoo(props: {value: number}): number {
12
const a = {
13
foo() {
14
const b = {
@@ -27,7 +27,7 @@ function useFoo(props: { value: number }): number {
27
28
export const FIXTURE_ENTRYPOINT = {
29
fn: useFoo,
30
- params: [{ value: 42 }],
30
+ params: [{value: 42}],
31
};
32
33
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rename-source-variables-nested-object-method.js
+6
-6
@@ -1,10 +1,10 @@
1
// @enableChangeVariableCodegen
2
-import { identity } from "shared-runtime";
2
+import {identity} from 'shared-runtime';
3
4
-const $ = "module_$";
5
-const t0 = "module_t0";
6
-const c_0 = "module_c_0";
7
-function useFoo(props: { value: number }): number {
4
+const $ = 'module_$';
5
+const t0 = 'module_t0';
6
+const c_0 = 'module_c_0';
7
+function useFoo(props: {value: number}): number {
8
const a = {
9
foo() {
10
const b = {
@@ -23,5 +23,5 @@ function useFoo(props: { value: number }): number {
23
24
export const FIXTURE_ENTRYPOINT = {
25
fn: useFoo,
26
- params: [{ value: 42 }],
26
+ params: [{value: 42}],
27
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rename-source-variables.expect.md
+6
-6
@@ -3,12 +3,12 @@
3
4
```javascript
5
// @enableChangeVariableCodegen
6
-import { identity } from "shared-runtime";
6
+import {identity} from 'shared-runtime';
7
8
-const $ = "module_$";
9
-const t0 = "module_t0";
10
-const c_0 = "module_c_0";
11
-function useFoo(props: { value: number }): number {
8
+const $ = 'module_$';
9
+const t0 = 'module_t0';
10
+const c_0 = 'module_c_0';
11
+function useFoo(props: {value: number}): number {
12
const results = identity(props.value);
13
console.log($);
14
console.log(t0);
@@ -18,7 +18,7 @@ function useFoo(props: { value: number }): number {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: useFoo,
21
- params: [{ value: 0 }],
21
+ params: [{value: 0}],
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rename-source-variables.ts
+6
-6
@@ -1,10 +1,10 @@
1
// @enableChangeVariableCodegen
2
-import { identity } from "shared-runtime";
2
+import {identity} from 'shared-runtime';
3
4
-const $ = "module_$";
5
-const t0 = "module_t0";
6
-const c_0 = "module_c_0";
7
-function useFoo(props: { value: number }): number {
4
+const $ = 'module_$';
5
+const t0 = 'module_t0';
6
+const c_0 = 'module_c_0';
7
+function useFoo(props: {value: number}): number {
8
const results = identity(props.value);
9
console.log($);
10
console.log(t0);
@@ -14,5 +14,5 @@ function useFoo(props: { value: number }): number {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: useFoo,
17
- params: [{ value: 0 }],
17
+ params: [{value: 0}],
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reordering-across-blocks.expect.md
+4
-4
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
-function Component({ config }) {
7
+function Component({config}) {
8
/**
9
* The original memoization is optimal in the sense that it has
10
* one output (the object) and one dependency (`config`). Both
@@ -30,11 +30,11 @@ function Component({ config }) {
30
* `config`, so they can be merged.
31
*/
32
const object = useMemo(() => {
33
- const a = (event) => {
33
+ const a = event => {
34
config?.onA?.(event);
35
};
36
37
- const b = (event) => {
37
+ const b = event => {
38
config?.onB?.(event);
39
};
40
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reordering-across-blocks.js
+4
-4
@@ -1,6 +1,6 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
-function Component({ config }) {
3
+function Component({config}) {
4
/**
5
* The original memoization is optimal in the sense that it has
6
* one output (the object) and one dependency (`config`). Both
@@ -26,11 +26,11 @@ function Component({ config }) {
26
* `config`, so they can be merged.
27
*/
28
const object = useMemo(() => {
29
- const a = (event) => {
29
+ const a = event => {
30
config?.onA?.(event);
31
};
32
33
- const b = (event) => {
33
+ const b = event => {
34
config?.onB?.(event);
35
};
36
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-allocating-ternary-test-instruction-scope.expect.md
+3
-3
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { identity, makeObject_Primitives } from "shared-runtime";
5
+import {identity, makeObject_Primitives} from 'shared-runtime';
6
7
-function useTest({ cond }) {
7
+function useTest({cond}) {
8
const val = makeObject_Primitives();
9
10
useHook();
@@ -20,7 +20,7 @@ function useTest({ cond }) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: useTest,
23
- params: [{ cond: true }],
23
+ params: [{cond: true}],
24
};
25
26
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-allocating-ternary-test-instruction-scope.ts
+3
-3
@@ -1,6 +1,6 @@
1
-import { identity, makeObject_Primitives } from "shared-runtime";
1
+import {identity, makeObject_Primitives} from 'shared-runtime';
2
3
-function useTest({ cond }) {
3
+function useTest({cond}) {
4
const val = makeObject_Primitives();
5
6
useHook();
@@ -16,5 +16,5 @@ function useTest({ cond }) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: useTest,
19
- params: [{ cond: true }],
19
+ params: [{cond: true}],
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-dce-circular-reference.expect.md
+5
-5
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
-function Component({ data }) {
7
+function Component({data}) {
8
let x = 0;
9
for (const item of data) {
10
- const { current, other } = item;
10
+ const {current, other} = item;
11
x += current;
12
identity(other);
13
}
@@ -19,8 +19,8 @@ export const FIXTURE_ENTRYPOINT = {
19
params: [
20
{
21
data: [
22
- { current: 2, other: 3 },
23
- { current: 4, other: 5 },
22
+ {current: 2, other: 3},
23
+ {current: 4, other: 5},
24
],
25
},
26
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-dce-circular-reference.js
+5
-5
@@ -1,9 +1,9 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
-function Component({ data }) {
3
+function Component({data}) {
4
let x = 0;
5
for (const item of data) {
6
- const { current, other } = item;
6
+ const {current, other} = item;
7
x += current;
8
identity(other);
9
}
@@ -15,8 +15,8 @@ export const FIXTURE_ENTRYPOINT = {
15
params: [
16
{
17
data: [
18
- { current: 2, other: 3 },
19
- { current: 4, other: 5 },
18
+ {current: 2, other: 3},
19
+ {current: 4, other: 5},
20
],
21
},
22
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-dont-memoize-array-with-capturing-map-after-hook.expect.md
+5
-5
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-import { useEffect, useState } from "react";
6
-import { mutate } from "shared-runtime";
5
+import {useEffect, useState} from 'react';
6
+import {mutate} from 'shared-runtime';
7
8
function Component(props) {
9
- const x = [{ ...props.value }];
9
+ const x = [{...props.value}];
10
useEffect(() => {}, []);
11
const onClick = () => {
12
console.log(x.length);
@@ -14,7 +14,7 @@ function Component(props) {
14
let y;
15
return (
16
<div onClick={onClick}>
17
- {x.map((item) => {
17
+ {x.map(item => {
18
y = item;
19
return <span key={item.id}>{item.text}</span>;
20
})}
@@ -25,7 +25,7 @@ function Component(props) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Component,
28
- params: [{ value: { id: 0, text: "Hello!" } }],
28
+ params: [{value: {id: 0, text: 'Hello!'}}],
29
isComponent: true,
30
};
31
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-dont-memoize-array-with-capturing-map-after-hook.js
+5
-5
@@ -1,8 +1,8 @@
1
-import { useEffect, useState } from "react";
2
-import { mutate } from "shared-runtime";
1
+import {useEffect, useState} from 'react';
2
+import {mutate} from 'shared-runtime';
3
4
function Component(props) {
5
- const x = [{ ...props.value }];
5
+ const x = [{...props.value}];
6
useEffect(() => {}, []);
7
const onClick = () => {
8
console.log(x.length);
@@ -10,7 +10,7 @@ function Component(props) {
10
let y;
11
return (
12
<div onClick={onClick}>
13
- {x.map((item) => {
13
+ {x.map(item => {
14
y = item;
15
return <span key={item.id}>{item.text}</span>;
16
})}
@@ -21,6 +21,6 @@ function Component(props) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
- params: [{ value: { id: 0, text: "Hello!" } }],
24
+ params: [{value: {id: 0, text: 'Hello!'}}],
25
isComponent: true,
26
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-dont-memoize-array-with-mutable-map-after-hook.expect.md
+5
-5
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-import { useEffect, useState } from "react";
6
-import { mutate } from "shared-runtime";
5
+import {useEffect, useState} from 'react';
6
+import {mutate} from 'shared-runtime';
7
8
function Component(props) {
9
- const x = [{ ...props.value }];
9
+ const x = [{...props.value}];
10
useEffect(() => {}, []);
11
const onClick = () => {
12
console.log(x.length);
@@ -14,7 +14,7 @@ function Component(props) {
14
let y;
15
return (
16
<div onClick={onClick}>
17
- {x.map((item) => {
17
+ {x.map(item => {
18
item.flag = true;
19
return <span key={item.id}>{item.text}</span>;
20
})}
@@ -25,7 +25,7 @@ function Component(props) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Component,
28
- params: [{ value: { id: 0, text: "Hello", flag: false } }],
28
+ params: [{value: {id: 0, text: 'Hello', flag: false}}],
29
isComponent: true,
30
};
31
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-dont-memoize-array-with-mutable-map-after-hook.js
+5
-5
@@ -1,8 +1,8 @@
1
-import { useEffect, useState } from "react";
2
-import { mutate } from "shared-runtime";
1
+import {useEffect, useState} from 'react';
2
+import {mutate} from 'shared-runtime';
3
4
function Component(props) {
5
- const x = [{ ...props.value }];
5
+ const x = [{...props.value}];
6
useEffect(() => {}, []);
7
const onClick = () => {
8
console.log(x.length);
@@ -10,7 +10,7 @@ function Component(props) {
10
let y;
11
return (
12
<div onClick={onClick}>
13
- {x.map((item) => {
13
+ {x.map(item => {
14
item.flag = true;
15
return <span key={item.id}>{item.text}</span>;
16
})}
@@ -21,6 +21,6 @@ function Component(props) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
- params: [{ value: { id: 0, text: "Hello", flag: false } }],
24
+ params: [{value: {id: 0, text: 'Hello', flag: false}}],
25
isComponent: true,
26
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-duplicate-import-specifier.expect.md
+3
-3
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-import type { SetStateAction, Dispatch } from "react";
6
-import { useState } from "react";
5
+import type {SetStateAction, Dispatch} from 'react';
6
+import {useState} from 'react';
7
8
function Component(_props: {}) {
9
const [x, _setX]: [number, Dispatch<SetStateAction<number>>] = useState(0);
10
- return { x };
10
+ return {x};
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-duplicate-import-specifier.ts
+3
-3
@@ -1,9 +1,9 @@
1
-import type { SetStateAction, Dispatch } from "react";
2
-import { useState } from "react";
1
+import type {SetStateAction, Dispatch} from 'react';
2
+import {useState} from 'react';
3
4
function Component(_props: {}) {
5
const [x, _setX]: [number, Dispatch<SetStateAction<number>>] = useState(0);
6
- return { x };
6
+ return {x};
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-duplicate-instruction-from-merge-consecutive-scopes.expect.md
+2
-2
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
-function Component({ id }) {
7
+function Component({id}) {
8
const bar = (() => {})();
9
10
return (
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-duplicate-instruction-from-merge-consecutive-scopes.js
+2
-2
@@ -1,6 +1,6 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
-function Component({ id }) {
3
+function Component({id}) {
4
const bar = (() => {})();
5
6
return (
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-duplicate-type-import.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import type { ReactElement } from "react";
5
+import type {ReactElement} from 'react';
6
7
function Component(_props: {}): ReactElement {
8
return <div>hello world</div>;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-duplicate-type-import.tsx
+1
-1
@@ -1,4 +1,4 @@
1
-import type { ReactElement } from "react";
1
+import type {ReactElement} from 'react';
2
3
function Component(_props: {}): ReactElement {
4
return <div>hello world</div>;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-hoisting-variable-collision.expect.md
+2
-2
@@ -3,14 +3,14 @@
3
4
```javascript
5
function Component(props) {
6
- const items = props.items.map((x) => x);
6
+ const items = props.items.map(x => x);
7
const x = 42;
8
return [x, items];
9
}
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ items: [0, 42, null, undefined, { object: true }] }],
13
+ params: [{items: [0, 42, null, undefined, {object: true}]}],
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-hoisting-variable-collision.js
+2
-2
@@ -1,10 +1,10 @@
1
function Component(props) {
2
- const items = props.items.map((x) => x);
2
+ const items = props.items.map(x => x);
3
const x = 42;
4
return [x, items];
5
}
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: [{ items: [0, 42, null, undefined, { object: true }] }],
9
+ params: [{items: [0, 42, null, undefined, {object: true}]}],
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-hoisting.expect.md
+2
-2
@@ -4,7 +4,7 @@
4
```javascript
5
function Component(props) {
6
const wat = () => {
7
- const pathname = "wat";
7
+ const pathname = 'wat';
8
pathname;
9
};
10
@@ -16,7 +16,7 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ wat: "/dev/null", itemID: 42 }],
19
+ params: [{wat: '/dev/null', itemID: 42}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-hoisting.js
+2
-2
@@ -1,6 +1,6 @@
1
function Component(props) {
2
const wat = () => {
3
- const pathname = "wat";
3
+ const pathname = 'wat';
4
pathname;
5
};
6
@@ -12,5 +12,5 @@ function Component(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ wat: "/dev/null", itemID: 42 }],
15
+ params: [{wat: '/dev/null', itemID: 42}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-independently-memoized-property-load-for-method-call.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @flow @enableAssumeHooksFollowRulesOfReact
6
-function Component({ label, highlightedItem }) {
6
+function Component({label, highlightedItem}) {
7
const serverTime = useServerTime();
8
const highlight = new Highlight(highlightedItem);
9
@@ -23,7 +23,7 @@ function Component({ label, highlightedItem }) {
23
}
24
25
function useServerTime() {
26
- "use no forget";
26
+ 'use no forget';
27
28
return {
29
get() {
@@ -44,7 +44,7 @@ class Highlight {
44
45
export const FIXTURE_ENTRYPOINT = {
46
fn: Component,
47
- params: [{ label: "<unused>", highlightedItem: "Seconds passed: " }],
47
+ params: [{label: '<unused>', highlightedItem: 'Seconds passed: '}],
48
};
49
50
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-independently-memoized-property-load-for-method-call.js
+3
-3
@@ -1,5 +1,5 @@
1
// @flow @enableAssumeHooksFollowRulesOfReact
2
-function Component({ label, highlightedItem }) {
2
+function Component({label, highlightedItem}) {
3
const serverTime = useServerTime();
4
const highlight = new Highlight(highlightedItem);
5
@@ -19,7 +19,7 @@ function Component({ label, highlightedItem }) {
19
}
20
21
function useServerTime() {
22
- "use no forget";
22
+ 'use no forget';
23
24
return {
25
get() {
@@ -40,5 +40,5 @@ class Highlight {
40
41
export const FIXTURE_ENTRYPOINT = {
42
fn: Component,
43
- params: [{ label: "<unused>", highlightedItem: "Seconds passed: " }],
43
+ params: [{label: '<unused>', highlightedItem: 'Seconds passed: '}],
44
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-instruction-part-of-already-closed-scope.expect.md
+3
-3
@@ -3,9 +3,9 @@
3
4
```javascript
5
// @enableAssumeHooksFollowRulesOfReact
6
-import { Stringify, identity, useHook } from "shared-runtime";
6
+import {Stringify, identity, useHook} from 'shared-runtime';
7
8
-function Component({ index }) {
8
+function Component({index}) {
9
const data = useHook();
10
11
const a = identity(data, index);
@@ -23,7 +23,7 @@ function Component({ index }) {
23
24
export const FIXTURE_ENTRYPOINT = {
25
fn: Component,
26
- params: [{ index: 0 }],
26
+ params: [{index: 0}],
27
};
28
29
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-instruction-part-of-already-closed-scope.js
+3
-3
@@ -1,7 +1,7 @@
1
// @enableAssumeHooksFollowRulesOfReact
2
-import { Stringify, identity, useHook } from "shared-runtime";
2
+import {Stringify, identity, useHook} from 'shared-runtime';
3
4
-function Component({ index }) {
4
+function Component({index}) {
5
const data = useHook();
6
7
const a = identity(data, index);
@@ -19,5 +19,5 @@ function Component({ index }) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: [{ index: 0 }],
22
+ params: [{index: 0}],
23
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-invalid-pruned-scope-leaks-value-via-alias.expect.md
+6
-11
@@ -2,13 +2,8 @@
2
## Input
3
4
```javascript
5
-import invariant from "invariant";
6
-import {
7
- makeObject_Primitives,
8
- mutate,
9
- sum,
10
- useIdentity,
11
-} from "shared-runtime";
5
+import invariant from 'invariant';
6
+import {makeObject_Primitives, mutate, sum, useIdentity} from 'shared-runtime';
7
8
/**
9
* Here, `z`'s original memo block is removed due to the inner hook call.
@@ -21,7 +16,7 @@ import {
16
* The fix is to consider pruned memo block outputs as reactive, since they will
17
* recreate on every render. This means `thing` depends on both y and z.
18
*/
24
-function MyApp({ count }) {
19
+function MyApp({count}) {
20
const z = makeObject_Primitives();
21
const x = useIdentity(2);
22
const y = sum(x, count);
@@ -29,15 +24,15 @@ function MyApp({ count }) {
24
const z2 = z;
25
const thing = [y, z2];
26
if (thing[1] !== z) {
32
- invariant(false, "oh no!");
27
+ invariant(false, 'oh no!');
28
}
29
return thing;
30
}
31
32
export const FIXTURE_ENTRYPOINT = {
33
fn: MyApp,
39
- params: [{ count: 2 }],
40
- sequentialRenders: [{ count: 2 }, { count: 2 }, { count: 3 }],
34
+ params: [{count: 2}],
35
+ sequentialRenders: [{count: 2}, {count: 2}, {count: 3}],
36
};
37
38
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-invalid-pruned-scope-leaks-value-via-alias.ts
+6
-11
@@ -1,10 +1,5 @@
1
-import invariant from "invariant";
2
-import {
3
- makeObject_Primitives,
4
- mutate,
5
- sum,
6
- useIdentity,
7
-} from "shared-runtime";
1
+import invariant from 'invariant';
2
+import {makeObject_Primitives, mutate, sum, useIdentity} from 'shared-runtime';
3
4
/**
5
* Here, `z`'s original memo block is removed due to the inner hook call.
@@ -17,7 +12,7 @@ import {
12
* The fix is to consider pruned memo block outputs as reactive, since they will
13
* recreate on every render. This means `thing` depends on both y and z.
14
*/
20
-function MyApp({ count }) {
15
+function MyApp({count}) {
16
const z = makeObject_Primitives();
17
const x = useIdentity(2);
18
const y = sum(x, count);
@@ -25,13 +20,13 @@ function MyApp({ count }) {
20
const z2 = z;
21
const thing = [y, z2];
22
if (thing[1] !== z) {
28
- invariant(false, "oh no!");
23
+ invariant(false, 'oh no!');
24
}
25
return thing;
26
}
27
28
export const FIXTURE_ENTRYPOINT = {
29
fn: MyApp,
35
- params: [{ count: 2 }],
36
- sequentialRenders: [{ count: 2 }, { count: 2 }, { count: 3 }],
30
+ params: [{count: 2}],
31
+ sequentialRenders: [{count: 2}, {count: 2}, {count: 3}],
32
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-invalid-pruned-scope-leaks-value.expect.md
+6
-11
@@ -2,13 +2,8 @@
2
## Input
3
4
```javascript
5
-import invariant from "invariant";
6
-import {
7
- makeObject_Primitives,
8
- mutate,
9
- sum,
10
- useIdentity,
11
-} from "shared-runtime";
5
+import invariant from 'invariant';
6
+import {makeObject_Primitives, mutate, sum, useIdentity} from 'shared-runtime';
7
8
/**
9
* Here, `z`'s original memo block is removed due to the inner hook call.
@@ -21,22 +16,22 @@ import {
16
* The fix is to consider pruned memo block outputs as reactive, since they will
17
* recreate on every render. This means `thing` depends on both y and z.
18
*/
24
-function MyApp({ count }) {
19
+function MyApp({count}) {
20
const z = makeObject_Primitives();
21
const x = useIdentity(2);
22
const y = sum(x, count);
23
mutate(z);
24
const thing = [y, z];
25
if (thing[1] !== z) {
31
- invariant(false, "oh no!");
26
+ invariant(false, 'oh no!');
27
}
28
return thing;
29
}
30
31
export const FIXTURE_ENTRYPOINT = {
32
fn: MyApp,
38
- params: [{ count: 2 }],
39
- sequentialRenders: [{ count: 2 }, { count: 2 }, { count: 3 }],
33
+ params: [{count: 2}],
34
+ sequentialRenders: [{count: 2}, {count: 2}, {count: 3}],
35
};
36
37
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-invalid-pruned-scope-leaks-value.ts
+6
-11
@@ -1,10 +1,5 @@
1
-import invariant from "invariant";
2
-import {
3
- makeObject_Primitives,
4
- mutate,
5
- sum,
6
- useIdentity,
7
-} from "shared-runtime";
1
+import invariant from 'invariant';
2
+import {makeObject_Primitives, mutate, sum, useIdentity} from 'shared-runtime';
3
4
/**
5
* Here, `z`'s original memo block is removed due to the inner hook call.
@@ -17,20 +12,20 @@ import {
12
* The fix is to consider pruned memo block outputs as reactive, since they will
13
* recreate on every render. This means `thing` depends on both y and z.
14
*/
20
-function MyApp({ count }) {
15
+function MyApp({count}) {
16
const z = makeObject_Primitives();
17
const x = useIdentity(2);
18
const y = sum(x, count);
19
mutate(z);
20
const thing = [y, z];
21
if (thing[1] !== z) {
27
- invariant(false, "oh no!");
22
+ invariant(false, 'oh no!');
23
}
24
return thing;
25
}
26
27
export const FIXTURE_ENTRYPOINT = {
28
fn: MyApp,
34
- params: [{ count: 2 }],
35
- sequentialRenders: [{ count: 2 }, { count: 2 }, { count: 3 }],
29
+ params: [{count: 2}],
30
+ sequentialRenders: [{count: 2}, {count: 2}, {count: 3}],
31
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-invalid-reactivity-value-block.expect.md
+2
-2
@@ -7,7 +7,7 @@ import {
7
identity,
8
makeObject_Primitives,
9
useNoAlias,
10
-} from "shared-runtime";
10
+} from 'shared-runtime';
11
12
/**
13
* Here the scope for `obj` is pruned because it spans the `useNoAlias()` hook call.
@@ -29,7 +29,7 @@ function Foo() {
29
useNoAlias(result, obj);
30
31
if (shouldCaptureObj && result[0] !== obj) {
32
- throw new Error("Unexpected");
32
+ throw new Error('Unexpected');
33
}
34
return result;
35
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-invalid-reactivity-value-block.ts
+2
-2
@@ -3,7 +3,7 @@ import {
3
identity,
4
makeObject_Primitives,
5
useNoAlias,
6
-} from "shared-runtime";
6
+} from 'shared-runtime';
7
8
/**
9
* Here the scope for `obj` is pruned because it spans the `useNoAlias()` hook call.
@@ -25,7 +25,7 @@ function Foo() {
25
useNoAlias(result, obj);
26
27
if (shouldCaptureObj && result[0] !== obj) {
28
- throw new Error("Unexpected");
28
+ throw new Error('Unexpected');
29
}
30
return result;
31
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-invalid-scope-merging-value-blocks.expect.md
+1
-1
@@ -8,7 +8,7 @@ import {
8
makeObject_Primitives,
9
mutateAndReturn,
10
useHook,
11
-} from "shared-runtime";
11
+} from 'shared-runtime';
12
13
/**
14
* value and `mutateAndReturn(value)` should end up in the same reactive scope.
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-invalid-scope-merging-value-blocks.ts
+1
-1
@@ -4,7 +4,7 @@ import {
4
makeObject_Primitives,
5
mutateAndReturn,
6
useHook,
7
-} from "shared-runtime";
7
+} from 'shared-runtime';
8
9
/**
10
* value and `mutateAndReturn(value)` should end up in the same reactive scope.
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-memoize-array-with-immutable-map-after-hook.expect.md
+3
-3
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useEffect, useState } from "react";
5
+import {useEffect, useState} from 'react';
6
7
function Component(props) {
8
const x = [props.value];
@@ -12,7 +12,7 @@ function Component(props) {
12
};
13
return (
14
<div onClick={onClick}>
15
- {x.map((item) => {
15
+ {x.map(item => {
16
return <span key={item}>{item}</span>;
17
})}
18
</div>
@@ -21,7 +21,7 @@ function Component(props) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
- params: [{ value: 42 }],
24
+ params: [{value: 42}],
25
isComponent: true,
26
};
27
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-memoize-array-with-immutable-map-after-hook.js
+3
-3
@@ -1,4 +1,4 @@
1
-import { useEffect, useState } from "react";
1
+import {useEffect, useState} from 'react';
2
3
function Component(props) {
4
const x = [props.value];
@@ -8,7 +8,7 @@ function Component(props) {
8
};
9
return (
10
<div onClick={onClick}>
11
- {x.map((item) => {
11
+ {x.map(item => {
12
return <span key={item}>{item}</span>;
13
})}
14
</div>
@@ -17,6 +17,6 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ value: 42 }],
20
+ params: [{value: 42}],
21
isComponent: true,
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-missing-dependency-if-within-while.expect.md
+10
-10
@@ -4,7 +4,7 @@
4
```javascript
5
const someGlobal = true;
6
export default function Component(props) {
7
- const { b } = props;
7
+ const {b} = props;
8
const items = [];
9
let i = 0;
10
while (i < 10) {
@@ -18,16 +18,16 @@ export default function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ b: 42 }],
21
+ params: [{b: 42}],
22
sequentialRenders: [
23
- { b: 0 },
24
- { b: 0 },
25
- { b: 42 },
26
- { b: 42 },
27
- { b: 0 },
28
- { b: 42 },
29
- { b: 0 },
30
- { b: 42 },
23
+ {b: 0},
24
+ {b: 0},
25
+ {b: 42},
26
+ {b: 42},
27
+ {b: 0},
28
+ {b: 42},
29
+ {b: 0},
30
+ {b: 42},
31
],
32
};
33
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-missing-dependency-if-within-while.js
+10
-10
@@ -1,6 +1,6 @@
1
const someGlobal = true;
2
export default function Component(props) {
3
- const { b } = props;
3
+ const {b} = props;
4
const items = [];
5
let i = 0;
6
while (i < 10) {
@@ -14,15 +14,15 @@ export default function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ b: 42 }],
17
+ params: [{b: 42}],
18
sequentialRenders: [
19
- { b: 0 },
20
- { b: 0 },
21
- { b: 42 },
22
- { b: 42 },
23
- { b: 0 },
24
- { b: 42 },
25
- { b: 0 },
26
- { b: 42 },
19
+ {b: 0},
20
+ {b: 0},
21
+ {b: 42},
22
+ {b: 42},
23
+ {b: 0},
24
+ {b: 42},
25
+ {b: 0},
26
+ {b: 42},
27
],
28
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-mutable-range-extending-into-ternary.expect.md
+11
-11
@@ -2,16 +2,16 @@
2
## Input
3
4
```javascript
5
-import { useState } from "react";
5
+import {useState} from 'react';
6
7
function Component(props) {
8
const items = props.items ? props.items.slice() : [];
9
- const [state] = useState("");
9
+ const [state] = useState('');
10
return props.cond ? (
11
<div>{state}</div>
12
) : (
13
<div>
14
- {items.map((item) => (
14
+ {items.map(item => (
15
<div key={item.id}>{item.name}</div>
16
))}
17
</div>
@@ -20,28 +20,28 @@ function Component(props) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
- params: [{ cond: false, items: [{ id: 0, name: "Alice" }] }],
23
+ params: [{cond: false, items: [{id: 0, name: 'Alice'}]}],
24
sequentialRenders: [
25
- { cond: false, items: [{ id: 0, name: "Alice" }] },
25
+ {cond: false, items: [{id: 0, name: 'Alice'}]},
26
{
27
cond: false,
28
items: [
29
- { id: 0, name: "Alice" },
30
- { id: 1, name: "Bob" },
29
+ {id: 0, name: 'Alice'},
30
+ {id: 1, name: 'Bob'},
31
],
32
},
33
{
34
cond: true,
35
items: [
36
- { id: 0, name: "Alice" },
37
- { id: 1, name: "Bob" },
36
+ {id: 0, name: 'Alice'},
37
+ {id: 1, name: 'Bob'},
38
],
39
},
40
{
41
cond: false,
42
items: [
43
- { id: 1, name: "Bob" },
44
- { id: 2, name: "Claire" },
43
+ {id: 1, name: 'Bob'},
44
+ {id: 2, name: 'Claire'},
45
],
46
},
47
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-mutable-range-extending-into-ternary.js
+11
-11
@@ -1,13 +1,13 @@
1
-import { useState } from "react";
1
+import {useState} from 'react';
2
3
function Component(props) {
4
const items = props.items ? props.items.slice() : [];
5
- const [state] = useState("");
5
+ const [state] = useState('');
6
return props.cond ? (
7
<div>{state}</div>
8
) : (
9
<div>
10
- {items.map((item) => (
10
+ {items.map(item => (
11
<div key={item.id}>{item.name}</div>
12
))}
13
</div>
@@ -16,28 +16,28 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ cond: false, items: [{ id: 0, name: "Alice" }] }],
19
+ params: [{cond: false, items: [{id: 0, name: 'Alice'}]}],
20
sequentialRenders: [
21
- { cond: false, items: [{ id: 0, name: "Alice" }] },
21
+ {cond: false, items: [{id: 0, name: 'Alice'}]},
22
{
23
cond: false,
24
items: [
25
- { id: 0, name: "Alice" },
26
- { id: 1, name: "Bob" },
25
+ {id: 0, name: 'Alice'},
26
+ {id: 1, name: 'Bob'},
27
],
28
},
29
{
30
cond: true,
31
items: [
32
- { id: 0, name: "Alice" },
33
- { id: 1, name: "Bob" },
32
+ {id: 0, name: 'Alice'},
33
+ {id: 1, name: 'Bob'},
34
],
35
},
36
{
37
cond: false,
38
items: [
39
- { id: 1, name: "Bob" },
40
- { id: 2, name: "Claire" },
39
+ {id: 1, name: 'Bob'},
40
+ {id: 2, name: 'Claire'},
41
],
42
},
43
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-no-gating-import-without-compiled-functions.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @gating
6
-import { isForgetEnabled_Fixtures } from "ReactForgetFeatureFlag";
6
+import {isForgetEnabled_Fixtures} from 'ReactForgetFeatureFlag';
7
8
export default 42;
9
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-no-gating-import-without-compiled-functions.js
+1
-1
@@ -1,4 +1,4 @@
1
// @gating
2
-import { isForgetEnabled_Fixtures } from "ReactForgetFeatureFlag";
2
+import {isForgetEnabled_Fixtures} from 'ReactForgetFeatureFlag';
3
4
export default 42;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-no-value-for-temporary-reactive-scope-with-early-return.expect.md
+4
-4
@@ -3,8 +3,8 @@
3
4
```javascript
5
// @flow @enableAssumeHooksFollowRulesOfReact @enableTransitivelyFreezeFunctionExpressions
6
-import { identity, makeObject_Primitives } from "shared-runtime";
7
-import fbt from "fbt";
6
+import {identity, makeObject_Primitives} from 'shared-runtime';
7
+import fbt from 'fbt';
8
9
function Component(props) {
10
const object = makeObject_Primitives();
@@ -16,8 +16,8 @@ function Component(props) {
16
return (
17
<div className="foo">
18
{fbt(
19
- "Lorum ipsum" + fbt.param("thing", object.b) + " blah blah blah",
20
- "More text"
19
+ 'Lorum ipsum' + fbt.param('thing', object.b) + ' blah blah blah',
20
+ 'More text'
21
)}
22
</div>
23
);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-no-value-for-temporary-reactive-scope-with-early-return.js
+4
-4
@@ -1,6 +1,6 @@
1
// @flow @enableAssumeHooksFollowRulesOfReact @enableTransitivelyFreezeFunctionExpressions
2
-import { identity, makeObject_Primitives } from "shared-runtime";
3
-import fbt from "fbt";
2
+import {identity, makeObject_Primitives} from 'shared-runtime';
3
+import fbt from 'fbt';
4
5
function Component(props) {
6
const object = makeObject_Primitives();
@@ -12,8 +12,8 @@ function Component(props) {
12
return (
13
<div className="foo">
14
{fbt(
15
- "Lorum ipsum" + fbt.param("thing", object.b) + " blah blah blah",
16
- "More text"
15
+ 'Lorum ipsum' + fbt.param('thing', object.b) + ' blah blah blah',
16
+ 'More text'
17
)}
18
</div>
19
);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-non-identifier-object-keys.expect.md
+5
-5
@@ -4,11 +4,11 @@
4
```javascript
5
function Foo() {
6
return {
7
- "a.b": 1,
8
- "a\b": 2,
9
- "a/b": 3,
10
- "a+b": 4,
11
- "a b": 5,
7
+ 'a.b': 1,
8
+ 'a\b': 2,
9
+ 'a/b': 3,
10
+ 'a+b': 4,
11
+ 'a b': 5,
12
};
13
}
14
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-non-identifier-object-keys.ts
+5
-5
@@ -1,10 +1,10 @@
1
function Foo() {
2
return {
3
- "a.b": 1,
4
- "a\b": 2,
5
- "a/b": 3,
6
- "a+b": 4,
7
- "a b": 5,
3
+ 'a.b': 1,
4
+ 'a\b': 2,
5
+ 'a/b': 3,
6
+ 'a+b': 4,
7
+ 'a b': 5,
8
};
9
}
10
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-object-pattern.expect.md
+3
-3
@@ -3,14 +3,14 @@
3
4
```javascript
5
function component(t) {
6
- let { a } = t;
7
- let y = { a };
6
+ let {a} = t;
7
+ let y = {a};
8
return y;
9
}
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: component,
13
- params: [{ a: 42 }],
13
+ params: [{a: 42}],
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-object-pattern.js
+3
-3
@@ -1,10 +1,10 @@
1
function component(t) {
2
- let { a } = t;
3
- let y = { a };
2
+ let {a} = t;
3
+ let y = {a};
4
return y;
5
}
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: component,
9
- params: [{ a: 42 }],
9
+ params: [{a: 42}],
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-preds-undefined-try-catch-return-primitive.expect.md
+2
-2
@@ -4,14 +4,14 @@
4
```javascript
5
// @enableAssumeHooksFollowRulesOfReact @enableTransitivelyFreezeFunctionExpressions
6
7
-import { useMemo } from "react";
7
+import {useMemo} from 'react';
8
9
const checkforTouchEvents = true;
10
function useSupportsTouchEvent() {
11
return useMemo(() => {
12
if (checkforTouchEvents) {
13
try {
14
- document.createEvent("TouchEvent");
14
+ document.createEvent('TouchEvent');
15
return true;
16
} catch {
17
return false;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-preds-undefined-try-catch-return-primitive.js
+2
-2
@@ -1,13 +1,13 @@
1
// @enableAssumeHooksFollowRulesOfReact @enableTransitivelyFreezeFunctionExpressions
2
3
-import { useMemo } from "react";
3
+import {useMemo} from 'react';
4
5
const checkforTouchEvents = true;
6
function useSupportsTouchEvent() {
7
return useMemo(() => {
8
if (checkforTouchEvents) {
9
try {
10
- document.createEvent("TouchEvent");
10
+ document.createEvent('TouchEvent');
11
return true;
12
} catch {
13
return false;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-ref-mutable-range.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { Stringify, identity, mutate, CONST_TRUE } from "shared-runtime";
5
+import {Stringify, identity, mutate, CONST_TRUE} from 'shared-runtime';
6
7
function Foo(props, ref) {
8
const value = {};
@@ -19,7 +19,7 @@ function Foo(props, ref) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Foo,
22
- params: [{}, { current: "fake-ref-object" }],
22
+ params: [{}, {current: 'fake-ref-object'}],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-ref-mutable-range.tsx
+2
-2
@@ -1,4 +1,4 @@
1
-import { Stringify, identity, mutate, CONST_TRUE } from "shared-runtime";
1
+import {Stringify, identity, mutate, CONST_TRUE} from 'shared-runtime';
2
3
function Foo(props, ref) {
4
const value = {};
@@ -15,5 +15,5 @@ function Foo(props, ref) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Foo,
18
- params: [{}, { current: "fake-ref-object" }],
18
+ params: [{}, {current: 'fake-ref-object'}],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-renaming-conflicting-decls.expect.md
+4
-5
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import { Stringify, identity, makeArray, toJSON } from "shared-runtime";
6
-import { useMemo } from "react";
5
+import {Stringify, identity, makeArray, toJSON} from 'shared-runtime';
6
+import {useMemo} from 'react';
7
8
function Component(props) {
9
const propsString = useMemo(() => toJSON(props), [props]);
@@ -24,8 +24,7 @@ function Component(props) {
24
val2={[2]}
25
val3={[3]}
26
val4={[4]}
27
- val5={[5]}
28
- >
27
+ val5={[5]}>
28
{makeArray(x, 2)}
29
</Stringify>
30
);
@@ -33,7 +32,7 @@ function Component(props) {
32
33
export const FIXTURE_ENTRYPOINT = {
34
fn: Component,
36
- params: [{ val: 2 }],
35
+ params: [{val: 2}],
36
};
37
38
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-renaming-conflicting-decls.js
+4
-5
@@ -1,5 +1,5 @@
1
-import { Stringify, identity, makeArray, toJSON } from "shared-runtime";
2
-import { useMemo } from "react";
1
+import {Stringify, identity, makeArray, toJSON} from 'shared-runtime';
2
+import {useMemo} from 'react';
3
4
function Component(props) {
5
const propsString = useMemo(() => toJSON(props), [props]);
@@ -20,8 +20,7 @@ function Component(props) {
20
val2={[2]}
21
val3={[3]}
22
val4={[4]}
23
- val5={[5]}
24
- >
23
+ val5={[5]}>
24
{makeArray(x, 2)}
25
</Stringify>
26
);
@@ -29,5 +28,5 @@ function Component(props) {
28
29
export const FIXTURE_ENTRYPOINT = {
30
fn: Component,
32
- params: [{ val: 2 }],
31
+ params: [{val: 2}],
32
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-retain-source-when-bailout.expect.md
+2
-2
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @panicThreshold(none)
6
-import { useNoAlias } from "shared-runtime";
6
+import {useNoAlias} from 'shared-runtime';
7
8
const cond = true;
9
function useFoo(props) {
@@ -12,7 +12,7 @@ function useFoo(props) {
12
return useNoAlias({});
13
14
function bar() {
15
- console.log("bar called");
15
+ console.log('bar called');
16
return 5;
17
}
18
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-retain-source-when-bailout.js
+2
-2
@@ -1,5 +1,5 @@
1
// @panicThreshold(none)
2
-import { useNoAlias } from "shared-runtime";
2
+import {useNoAlias} from 'shared-runtime';
3
4
const cond = true;
5
function useFoo(props) {
@@ -8,7 +8,7 @@ function useFoo(props) {
8
return useNoAlias({});
9
10
function bar() {
11
- console.log("bar called");
11
+ console.log('bar called');
12
return 5;
13
}
14
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-scope-missing-mutable-range.expect.md
+1
-1
@@ -6,7 +6,7 @@ function HomeDiscoStoreItemTileRating(props) {
6
const item = useFragment();
7
let count = 0;
8
const aggregates = item?.aggregates || [];
9
- aggregates.forEach((aggregate) => {
9
+ aggregates.forEach(aggregate => {
10
count += aggregate.count || 0;
11
});
12
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-scope-missing-mutable-range.js
+1
-1
@@ -2,7 +2,7 @@ function HomeDiscoStoreItemTileRating(props) {
2
const item = useFragment();
3
let count = 0;
4
const aggregates = item?.aggregates || [];
5
- aggregates.forEach((aggregate) => {
5
+ aggregates.forEach(aggregate => {
6
count += aggregate.count || 0;
7
});
8
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-separate-scopes-for-divs.expect.md
+10
-10
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
const DISPLAY = true;
8
-function Component({ cond = false, id }) {
8
+function Component({cond = false, id}) {
9
return (
10
<>
11
<div className={identity(styles.a, id !== null ? styles.b : {})}></div>
@@ -19,19 +19,19 @@ function Component({ cond = false, id }) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: [{ cond: false, id: 42 }],
22
+ params: [{cond: false, id: 42}],
23
sequentialRenders: [
24
- { cond: false, id: 4 },
25
- { cond: true, id: 4 },
26
- { cond: true, id: 42 },
24
+ {cond: false, id: 4},
25
+ {cond: true, id: 4},
26
+ {cond: true, id: 42},
27
],
28
};
29
30
const styles = {
31
- a: "a",
32
- b: "b",
33
- c: "c",
34
- d: "d",
31
+ a: 'a',
32
+ b: 'b',
33
+ c: 'c',
34
+ d: 'd',
35
};
36
37
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-separate-scopes-for-divs.js
+10
-10
@@ -1,7 +1,7 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
const DISPLAY = true;
4
-function Component({ cond = false, id }) {
4
+function Component({cond = false, id}) {
5
return (
6
<>
7
<div className={identity(styles.a, id !== null ? styles.b : {})}></div>
@@ -15,17 +15,17 @@ function Component({ cond = false, id }) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ cond: false, id: 42 }],
18
+ params: [{cond: false, id: 42}],
19
sequentialRenders: [
20
- { cond: false, id: 4 },
21
- { cond: true, id: 4 },
22
- { cond: true, id: 42 },
20
+ {cond: false, id: 4},
21
+ {cond: true, id: 4},
22
+ {cond: true, id: 42},
23
],
24
};
25
26
const styles = {
27
- a: "a",
28
- b: "b",
29
- c: "c",
30
- d: "d",
27
+ a: 'a',
28
+ b: 'b',
29
+ c: 'c',
30
+ d: 'd',
31
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-slow-validate-preserve-memo.expect.md
+7
-7
@@ -4,24 +4,24 @@
4
```javascript
5
// @validatePreserveExistingMemoizationGuarantees
6
7
-import { Builder } from "shared-runtime";
8
-function useTest({ isNull, data }: { isNull: boolean; data: string }) {
9
- const result = Builder.makeBuilder(isNull, "hello world")
10
- ?.push("1", 2)
7
+import {Builder} from 'shared-runtime';
8
+function useTest({isNull, data}: {isNull: boolean; data: string}) {
9
+ const result = Builder.makeBuilder(isNull, 'hello world')
10
+ ?.push('1', 2)
11
?.push(3, {
12
a: 4,
13
b: 5,
14
c: data,
15
})
16
?.push(6, data)
17
- ?.push(7, "8")
18
- ?.push("8", Builder.makeBuilder(!isNull)?.push(9).vals)?.vals;
17
+ ?.push(7, '8')
18
+ ?.push('8', Builder.makeBuilder(!isNull)?.push(9).vals)?.vals;
19
return result;
20
}
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: useTest,
24
- params: [{ isNull: false, data: "param" }],
24
+ params: [{isNull: false, data: 'param'}],
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-slow-validate-preserve-memo.ts
+7
-7
@@ -1,21 +1,21 @@
1
// @validatePreserveExistingMemoizationGuarantees
2
3
-import { Builder } from "shared-runtime";
4
-function useTest({ isNull, data }: { isNull: boolean; data: string }) {
5
- const result = Builder.makeBuilder(isNull, "hello world")
6
- ?.push("1", 2)
3
+import {Builder} from 'shared-runtime';
4
+function useTest({isNull, data}: {isNull: boolean; data: string}) {
5
+ const result = Builder.makeBuilder(isNull, 'hello world')
6
+ ?.push('1', 2)
7
?.push(3, {
8
a: 4,
9
b: 5,
10
c: data,
11
})
12
?.push(6, data)
13
- ?.push(7, "8")
14
- ?.push("8", Builder.makeBuilder(!isNull)?.push(9).vals)?.vals;
13
+ ?.push(7, '8')
14
+ ?.push('8', Builder.makeBuilder(!isNull)?.push(9).vals)?.vals;
15
return result;
16
}
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: useTest,
20
- params: [{ isNull: false, data: "param" }],
20
+ params: [{isNull: false, data: 'param'}],
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-undefined-expression-of-jsxexpressioncontainer.expect.md
+6
-6
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { StaticText1, Stringify, Text } from "shared-runtime";
5
+import {StaticText1, Stringify, Text} from 'shared-runtime';
6
7
function Component(props) {
8
- const { buttons } = props;
8
+ const {buttons} = props;
9
const [primaryButton, ...nonPrimaryButtons] = buttons;
10
11
const renderedNonPrimaryButtons = nonPrimaryButtons.map((buttonProps, i) => (
@@ -22,8 +22,8 @@ function Component(props) {
22
}
23
24
const styles = {
25
- leftSecondaryButton: { left: true },
26
- rightSecondaryButton: { right: true },
25
+ leftSecondaryButton: {left: true},
26
+ rightSecondaryButton: {right: true},
27
};
28
29
export const FIXTURE_ENTRYPOINT = {
@@ -32,8 +32,8 @@ export const FIXTURE_ENTRYPOINT = {
32
{
33
buttons: [
34
{},
35
- { type: "submit", children: ["Submit!"] },
36
- { type: "button", children: ["Reset"] },
35
+ {type: 'submit', children: ['Submit!']},
36
+ {type: 'button', children: ['Reset']},
37
],
38
},
39
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-undefined-expression-of-jsxexpressioncontainer.js
+6
-6
@@ -1,7 +1,7 @@
1
-import { StaticText1, Stringify, Text } from "shared-runtime";
1
+import {StaticText1, Stringify, Text} from 'shared-runtime';
2
3
function Component(props) {
4
- const { buttons } = props;
4
+ const {buttons} = props;
5
const [primaryButton, ...nonPrimaryButtons] = buttons;
6
7
const renderedNonPrimaryButtons = nonPrimaryButtons.map((buttonProps, i) => (
@@ -18,8 +18,8 @@ function Component(props) {
18
}
19
20
const styles = {
21
- leftSecondaryButton: { left: true },
22
- rightSecondaryButton: { right: true },
21
+ leftSecondaryButton: {left: true},
22
+ rightSecondaryButton: {right: true},
23
};
24
25
export const FIXTURE_ENTRYPOINT = {
@@ -28,8 +28,8 @@ export const FIXTURE_ENTRYPOINT = {
28
{
29
buttons: [
30
{},
31
- { type: "submit", children: ["Submit!"] },
32
- { type: "button", children: ["Reset"] },
31
+ {type: 'submit', children: ['Submit!']},
32
+ {type: 'button', children: ['Reset']},
33
],
34
},
35
],
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-unmerged-fbt-call-merge-overlapping-reactive-scopes.expect.md
+7
-7
@@ -2,16 +2,16 @@
2
## Input
3
4
```javascript
5
-import fbt from "fbt";
6
-import { Stringify } from "shared-runtime";
5
+import fbt from 'fbt';
6
+import {Stringify} from 'shared-runtime';
7
8
function Component(props) {
9
const label = fbt(
10
- fbt.plural("bar", props.value.length, {
11
- many: "bars",
12
- showCount: "yes",
10
+ fbt.plural('bar', props.value.length, {
11
+ many: 'bars',
12
+ showCount: 'yes',
13
}),
14
- "The label text"
14
+ 'The label text'
15
);
16
return props.cond ? (
17
<Stringify
@@ -23,7 +23,7 @@ function Component(props) {
23
24
export const FIXTURE_ENTRYPOINT = {
25
fn: Component,
26
- params: [{ cond: true, value: [0, 1, 2] }],
26
+ params: [{cond: true, value: [0, 1, 2]}],
27
};
28
29
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-unmerged-fbt-call-merge-overlapping-reactive-scopes.js
+7
-7
@@ -1,13 +1,13 @@
1
-import fbt from "fbt";
2
-import { Stringify } from "shared-runtime";
1
+import fbt from 'fbt';
2
+import {Stringify} from 'shared-runtime';
3
4
function Component(props) {
5
const label = fbt(
6
- fbt.plural("bar", props.value.length, {
7
- many: "bars",
8
- showCount: "yes",
6
+ fbt.plural('bar', props.value.length, {
7
+ many: 'bars',
8
+ showCount: 'yes',
9
}),
10
- "The label text"
10
+ 'The label text'
11
);
12
return props.cond ? (
13
<Stringify
@@ -19,5 +19,5 @@ function Component(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: [{ cond: true, value: [0, 1, 2] }],
22
+ params: [{cond: true, value: [0, 1, 2]}],
23
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-unreachable-code-early-return-in-useMemo.expect.md
+13
-13
@@ -3,16 +3,16 @@
3
4
```javascript
5
// @enableAssumeHooksFollowRulesOfReact @enableTransitivelyFreezeFunctionExpressions
6
-import { useMemo, useState } from "react";
7
-import { ValidateMemoization, identity } from "shared-runtime";
6
+import {useMemo, useState} from 'react';
7
+import {ValidateMemoization, identity} from 'shared-runtime';
8
9
-function Component({ value }) {
9
+function Component({value}) {
10
const result = useMemo(() => {
11
if (value == null) {
12
return null;
13
}
14
try {
15
- return { value };
15
+ return {value};
16
} catch (e) {
17
return null;
18
}
@@ -22,16 +22,16 @@ function Component({ value }) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
25
- params: [{ value: null }],
25
+ params: [{value: null}],
26
sequentialRenders: [
27
- { value: null },
28
- { value: null },
29
- { value: 42 },
30
- { value: 42 },
31
- { value: null },
32
- { value: 42 },
33
- { value: null },
34
- { value: 42 },
27
+ {value: null},
28
+ {value: null},
29
+ {value: 42},
30
+ {value: 42},
31
+ {value: null},
32
+ {value: 42},
33
+ {value: null},
34
+ {value: 42},
35
],
36
};
37
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro-unreachable-code-early-return-in-useMemo.js
+13
-13
@@ -1,14 +1,14 @@
1
// @enableAssumeHooksFollowRulesOfReact @enableTransitivelyFreezeFunctionExpressions
2
-import { useMemo, useState } from "react";
3
-import { ValidateMemoization, identity } from "shared-runtime";
2
+import {useMemo, useState} from 'react';
3
+import {ValidateMemoization, identity} from 'shared-runtime';
4
5
-function Component({ value }) {
5
+function Component({value}) {
6
const result = useMemo(() => {
7
if (value == null) {
8
return null;
9
}
10
try {
11
- return { value };
11
+ return {value};
12
} catch (e) {
13
return null;
14
}
@@ -18,15 +18,15 @@ function Component({ value }) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ value: null }],
21
+ params: [{value: null}],
22
sequentialRenders: [
23
- { value: null },
24
- { value: null },
25
- { value: 42 },
26
- { value: 42 },
27
- { value: null },
28
- { value: 42 },
29
- { value: null },
30
- { value: 42 },
23
+ {value: null},
24
+ {value: null},
25
+ {value: 42},
26
+ {value: 42},
27
+ {value: null},
28
+ {value: 42},
29
+ {value: null},
30
+ {value: 42},
31
],
32
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro.expect.md
+2
-2
@@ -7,10 +7,10 @@ function Component(props) {
7
const thumbnails = [];
8
const baseVideos = getBaseVideos(item);
9
useMemo(() => {
10
- baseVideos.forEach((video) => {
10
+ baseVideos.forEach(video => {
11
const baseVideo = video.hasBaseVideo;
12
if (Boolean(baseVideo)) {
13
- thumbnails.push({ extraVideo: true });
13
+ thumbnails.push({extraVideo: true});
14
}
15
});
16
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/repro.js
+2
-2
@@ -3,10 +3,10 @@ function Component(props) {
3
const thumbnails = [];
4
const baseVideos = getBaseVideos(item);
5
useMemo(() => {
6
- baseVideos.forEach((video) => {
6
+ baseVideos.forEach(video => {
7
const baseVideo = video.hasBaseVideo;
8
if (Boolean(baseVideo)) {
9
- thumbnails.push({ extraVideo: true });
9
+ thumbnails.push({extraVideo: true});
10
}
11
});
12
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/resolve-react-hooks-based-on-import-name.expect.md
+2
-2
@@ -2,13 +2,13 @@
2
## Input
3
4
```javascript
5
-import { useState as useReactState } from "react";
5
+import {useState as useReactState} from 'react';
6
7
function Component() {
8
const [state, setState] = useReactState(0);
9
10
const onClick = () => {
11
- setState((s) => s + 1);
11
+ setState(s => s + 1);
12
};
13
14
return (
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/resolve-react-hooks-based-on-import-name.js
+2
-2
@@ -1,10 +1,10 @@
1
-import { useState as useReactState } from "react";
1
+import {useState as useReactState} from 'react';
2
3
function Component() {
4
const [state, setState] = useReactState(0);
5
6
const onClick = () => {
7
- setState((s) => s + 1);
7
+ setState(s => s + 1);
8
};
9
10
return (
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rest-param-with-array-pattern.expect.md
+1
-1
@@ -8,7 +8,7 @@ function Component(foo, ...[bar]) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: ["foo", ["bar", "baz"]],
11
+ params: ['foo', ['bar', 'baz']],
12
};
13
14
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rest-param-with-array-pattern.js
+1
-1
@@ -4,5 +4,5 @@ function Component(foo, ...[bar]) {
4
5
export const FIXTURE_ENTRYPOINT = {
6
fn: Component,
7
- params: ["foo", ["bar", "baz"]],
7
+ params: ['foo', ['bar', 'baz']],
8
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rest-param-with-identifier.expect.md
+1
-1
@@ -8,7 +8,7 @@ function Component(foo, ...bar) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: ["foo", "bar", "baz"],
11
+ params: ['foo', 'bar', 'baz'],
12
};
13
14
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rest-param-with-identifier.js
+1
-1
@@ -4,5 +4,5 @@ function Component(foo, ...bar) {
4
5
export const FIXTURE_ENTRYPOINT = {
6
fn: Component,
7
- params: ["foo", "bar", "baz"],
7
+ params: ['foo', 'bar', 'baz'],
8
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rest-param-with-object-spread-pattern.expect.md
+2
-2
@@ -2,13 +2,13 @@
2
## Input
3
4
```javascript
5
-function Component(foo, ...{ bar }) {
5
+function Component(foo, ...{bar}) {
6
return [foo, bar];
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: ["foo", { bar: "bar" }],
11
+ params: ['foo', {bar: 'bar'}],
12
};
13
14
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rest-param-with-object-spread-pattern.js
+2
-2
@@ -1,8 +1,8 @@
1
-function Component(foo, ...{ bar }) {
1
+function Component(foo, ...{bar}) {
2
return [foo, bar];
3
}
4
5
export const FIXTURE_ENTRYPOINT = {
6
fn: Component,
7
- params: ["foo", { bar: "bar" }],
7
+ params: ['foo', {bar: 'bar'}],
8
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/return-conditional.expect.md
+2
-2
@@ -12,8 +12,8 @@ function foo(a, b) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: foo,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/return-conditional.js
+2
-2
@@ -8,6 +8,6 @@ function foo(a, b) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: foo,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/return-undefined.expect.md
+2
-2
@@ -11,8 +11,8 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/return-undefined.js
+2
-2
@@ -7,6 +7,6 @@ function Component(props) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: ["TodoAdd"],
11
- isComponent: "TodoAdd",
10
+ params: ['TodoAdd'],
11
+ isComponent: 'TodoAdd',
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reverse-postorder.expect.md
+2
-2
@@ -32,8 +32,8 @@ function Component(props) {
32
33
export const FIXTURE_ENTRYPOINT = {
34
fn: Component,
35
- params: ["TodoAdd"],
36
- isComponent: "TodoAdd",
35
+ params: ['TodoAdd'],
36
+ isComponent: 'TodoAdd',
37
};
38
39
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/reverse-postorder.js
+2
-2
@@ -28,6 +28,6 @@ function Component(props) {
28
29
export const FIXTURE_ENTRYPOINT = {
30
fn: Component,
31
- params: ["TodoAdd"],
32
- isComponent: "TodoAdd",
31
+ params: ['TodoAdd'],
32
+ isComponent: 'TodoAdd',
33
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/allow-locals-named-like-hooks.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeObject_Primitives } from "shared-runtime";
5
+import {makeObject_Primitives} from 'shared-runtime';
6
7
function Component(props) {
8
let useFeature = makeObject_Primitives();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/allow-locals-named-like-hooks.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { makeObject_Primitives } from "shared-runtime";
1
+import {makeObject_Primitives} from 'shared-runtime';
2
3
function Component(props) {
4
let useFeature = makeObject_Primitives();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/allow-props-named-like-hooks.expect.md
+3
-3
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
-function Component({ useFeature }) {
7
+function Component({useFeature}) {
8
let x;
9
if (useFeature) {
10
x = [useFeature + useFeature].push(-useFeature);
@@ -22,7 +22,7 @@ function Component({ useFeature }) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
25
- params: [{ useFeature: { useProperty: true } }],
25
+ params: [{useFeature: {useProperty: true}}],
26
};
27
28
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/allow-props-named-like-hooks.js
+3
-3
@@ -1,6 +1,6 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
-function Component({ useFeature }) {
3
+function Component({useFeature}) {
4
let x;
5
if (useFeature) {
6
x = [useFeature + useFeature].push(-useFeature);
@@ -18,5 +18,5 @@ function Component({ useFeature }) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ useFeature: { useProperty: true } }],
21
+ params: [{useFeature: {useProperty: true}}],
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.bail.rules-of-hooks-8503ca76d6f8.expect.md
+2
-2
@@ -7,7 +7,7 @@
7
8
// Invalid because it's a common misunderstanding.
9
// We *could* make it valid but the runtime error could be confusing.
10
-const ComponentWithHookInsideCallback = React.memo((props) => {
10
+const ComponentWithHookInsideCallback = React.memo(props => {
11
useEffect(() => {
12
useHookInsideCallback();
13
});
@@ -20,7 +20,7 @@ const ComponentWithHookInsideCallback = React.memo((props) => {
20
## Error
21
22
```
23
- 6 | const ComponentWithHookInsideCallback = React.memo((props) => {
23
+ 6 | const ComponentWithHookInsideCallback = React.memo(props => {
24
7 | useEffect(() => {
25
> 8 | useHookInsideCallback();
26
| ^^^^^^^^^^^^^^^^^^^^^ InvalidReact: Hooks must be called at the top level in the body of a function component or custom hook, and may not be called within function expressions. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning). Cannot call Custom within a function component (8:8)
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.bail.rules-of-hooks-8503ca76d6f8.js
+1
-1
@@ -3,7 +3,7 @@
3
4
// Invalid because it's a common misunderstanding.
5
// We *could* make it valid but the runtime error could be confusing.
6
-const ComponentWithHookInsideCallback = React.memo((props) => {
6
+const ComponentWithHookInsideCallback = React.memo(props => {
7
useEffect(() => {
8
useHookInsideCallback();
9
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-conditionally-call-local-named-like-hook.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeObject_Primitives } from "shared-runtime";
5
+import {makeObject_Primitives} from 'shared-runtime';
6
7
function Component(props) {
8
const useFoo = makeObject_Primitives();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-conditionally-call-local-named-like-hook.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { makeObject_Primitives } from "shared-runtime";
1
+import {makeObject_Primitives} from 'shared-runtime';
2
3
function Component(props) {
4
const useFoo = makeObject_Primitives();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-conditionally-call-prop-named-like-hook.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function Component({ cond, useFoo }) {
5
+function Component({cond, useFoo}) {
6
if (cond) {
7
useFoo();
8
}
@@ -14,7 +14,7 @@ function Component({ cond, useFoo }) {
14
## Error
15
16
```
17
- 1 | function Component({ cond, useFoo }) {
17
+ 1 | function Component({cond, useFoo}) {
18
2 | if (cond) {
19
> 3 | useFoo();
20
| ^^^^^^ InvalidReact: Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning) (3:3)
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-conditionally-call-prop-named-like-hook.js
+1
-1
@@ -1,4 +1,4 @@
1
-function Component({ cond, useFoo }) {
1
+function Component({cond, useFoo}) {
2
if (cond) {
3
useFoo();
4
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-conditionally-methodcall-hooklike-property-of-local.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeObject_Primitives } from "shared-runtime";
5
+import {makeObject_Primitives} from 'shared-runtime';
6
7
function Component(props) {
8
const local = makeObject_Primitives();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-conditionally-methodcall-hooklike-property-of-local.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { makeObject_Primitives } from "shared-runtime";
1
+import {makeObject_Primitives} from 'shared-runtime';
2
3
function Component(props) {
4
const local = makeObject_Primitives();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-condtionally-call-hooklike-property-of-local.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeObject_Primitives } from "shared-runtime";
5
+import {makeObject_Primitives} from 'shared-runtime';
6
7
function Component(props) {
8
const local = makeObject_Primitives();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-condtionally-call-hooklike-property-of-local.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { makeObject_Primitives } from "shared-runtime";
1
+import {makeObject_Primitives} from 'shared-runtime';
2
3
function Component(props) {
4
const local = makeObject_Primitives();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-as-prop.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function Component({ useFoo }) {
5
+function Component({useFoo}) {
6
useFoo();
7
}
8
@@ -12,7 +12,7 @@ function Component({ useFoo }) {
12
## Error
13
14
```
15
- 1 | function Component({ useFoo }) {
15
+ 1 | function Component({useFoo}) {
16
> 2 | useFoo();
17
| ^^^^^^ InvalidReact: Hooks must be the same function on every render, but this value may change over time to a different function. See https://react.dev/reference/rules/react-calls-components-and-hooks#dont-dynamically-use-hooks (2:2)
18
3 | }
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-as-prop.js
+1
-1
@@ -1,3 +1,3 @@
1
-function Component({ useFoo }) {
1
+function Component({useFoo}) {
2
useFoo();
3
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-from-hook-return.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function useFoo({ data }) {
5
+function useFoo({data}) {
6
const useMedia = useVideoPlayer();
7
const foo = useMedia();
8
return foo;
@@ -14,7 +14,7 @@ function useFoo({ data }) {
14
## Error
15
16
```
17
- 1 | function useFoo({ data }) {
17
+ 1 | function useFoo({data}) {
18
2 | const useMedia = useVideoPlayer();
19
> 3 | const foo = useMedia();
20
| ^^^^^^^^ InvalidReact: Hooks must be the same function on every render, but this value may change over time to a different function. See https://react.dev/reference/rules/react-calls-components-and-hooks#dont-dynamically-use-hooks (3:3)
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-from-hook-return.js
+1
-1
@@ -1,4 +1,4 @@
1
-function useFoo({ data }) {
1
+function useFoo({data}) {
2
const useMedia = useVideoPlayer();
3
const foo = useMedia();
4
return foo;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-from-property-of-other-hook.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function useFoo({ data }) {
5
+function useFoo({data}) {
6
const player = useVideoPlayer();
7
const foo = player.useMedia();
8
return foo;
@@ -14,7 +14,7 @@ function useFoo({ data }) {
14
## Error
15
16
```
17
- 1 | function useFoo({ data }) {
17
+ 1 | function useFoo({data}) {
18
2 | const player = useVideoPlayer();
19
> 3 | const foo = player.useMedia();
20
| ^^^^^^^^^^^^^^^ InvalidReact: Hooks must be the same function on every render, but this value may change over time to a different function. See https://react.dev/reference/rules/react-calls-components-and-hooks#dont-dynamically-use-hooks (3:3)
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-from-property-of-other-hook.js
+1
-1
@@ -1,4 +1,4 @@
1
-function useFoo({ data }) {
1
+function useFoo({data}) {
2
const player = useVideoPlayer();
3
const foo = player.useMedia();
4
return foo;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-in-nested-function-expression-object-expression.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
// @compilationMode(infer)
6
function Component() {
7
- "use memo";
7
+ 'use memo';
8
const f = () => {
9
const x = {
10
outer() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-in-nested-function-expression-object-expression.js
+1
-1
@@ -1,6 +1,6 @@
1
// @compilationMode(infer)
2
function Component() {
3
- "use memo";
3
+ 'use memo';
4
const f = () => {
5
const x = {
6
outer() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-in-nested-object-method.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
// @compilationMode(infer)
6
function Component() {
7
- "use memo";
7
+ 'use memo';
8
const x = {
9
outer() {
10
const y = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-in-nested-object-method.js
+1
-1
@@ -1,6 +1,6 @@
1
// @compilationMode(infer)
2
function Component() {
3
- "use memo";
3
+ 'use memo';
4
const x = {
5
outer() {
6
const y = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-optional-methodcall.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function Component() {
6
- const { result } = Module.useConditionalHook?.() ?? {};
6
+ const {result} = Module.useConditionalHook?.() ?? {};
7
return result;
8
}
9
@@ -14,8 +14,8 @@ function Component() {
14
15
```
16
1 | function Component() {
17
-> 2 | const { result } = Module.useConditionalHook?.() ?? {};
18
- | ^^^^^^^^^^^^^^^^^^^^^^^^^ InvalidReact: Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning) (2:2)
17
+> 2 | const {result} = Module.useConditionalHook?.() ?? {};
18
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^ InvalidReact: Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning) (2:2)
19
3 | return result;
20
4 | }
21
5 |
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-optional-methodcall.js
+1
-1
@@ -1,4 +1,4 @@
1
function Component() {
2
- const { result } = Module.useConditionalHook?.() ?? {};
2
+ const {result} = Module.useConditionalHook?.() ?? {};
3
return result;
4
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-optional-property.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function Component() {
6
- const { result } = Module?.useConditionalHook() ?? {};
6
+ const {result} = Module?.useConditionalHook() ?? {};
7
return result;
8
}
9
@@ -14,8 +14,8 @@ function Component() {
14
15
```
16
1 | function Component() {
17
-> 2 | const { result } = Module?.useConditionalHook() ?? {};
18
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^ InvalidReact: Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning) (2:2)
17
+> 2 | const {result} = Module?.useConditionalHook() ?? {};
18
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^ InvalidReact: Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning) (2:2)
19
3 | return result;
20
4 | }
21
5 |
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-optional-property.js
+1
-1
@@ -1,4 +1,4 @@
1
function Component() {
2
- const { result } = Module?.useConditionalHook() ?? {};
2
+ const {result} = Module?.useConditionalHook() ?? {};
3
return result;
4
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-optionalcall.expect.md
+3
-3
@@ -3,7 +3,7 @@
3
4
```javascript
5
function Component() {
6
- const { result } = useConditionalHook?.() ?? {};
6
+ const {result} = useConditionalHook?.() ?? {};
7
return result;
8
}
9
@@ -14,8 +14,8 @@ function Component() {
14
15
```
16
1 | function Component() {
17
-> 2 | const { result } = useConditionalHook?.() ?? {};
18
- | ^^^^^^^^^^^^^^^^^^ InvalidReact: Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning) (2:2)
17
+> 2 | const {result} = useConditionalHook?.() ?? {};
18
+ | ^^^^^^^^^^^^^^^^^^ InvalidReact: Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning) (2:2)
19
3 | return result;
20
4 | }
21
5 |
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-hook-optionalcall.js
+1
-1
@@ -1,4 +1,4 @@
1
function Component() {
2
- const { result } = useConditionalHook?.() ?? {};
2
+ const {result} = useConditionalHook?.() ?? {};
3
return result;
4
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-rules-of-hooks-9718e30b856c.expect.md
+3
-3
@@ -9,9 +9,9 @@
9
function useHook() {
10
if (a) return;
11
if (b) {
12
- console.log("true");
12
+ console.log('true');
13
} else {
14
- console.log("false");
14
+ console.log('false');
15
}
16
useState();
17
}
@@ -22,7 +22,7 @@ function useHook() {
22
## Error
23
24
```
25
- 10 | console.log("false");
25
+ 10 | console.log('false');
26
11 | }
27
> 12 | useState();
28
| ^^^^^^^^ InvalidReact: Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning) (12:12)
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-rules-of-hooks-9718e30b856c.js
+2
-2
@@ -5,9 +5,9 @@
5
function useHook() {
6
if (a) return;
7
if (b) {
8
- console.log("true");
8
+ console.log('true');
9
} else {
10
- console.log("false");
10
+ console.log('false');
11
}
12
useState();
13
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-rules-of-hooks-f3d6c5e9c83d.expect.md
+2
-2
@@ -8,9 +8,9 @@
8
// This *must* be invalid.
9
function useHook() {
10
if (b) {
11
- console.log("true");
11
+ console.log('true');
12
} else {
13
- console.log("false");
13
+ console.log('false');
14
}
15
if (a) return;
16
useState();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-rules-of-hooks-f3d6c5e9c83d.js
+2
-2
@@ -4,9 +4,9 @@
4
// This *must* be invalid.
5
function useHook() {
6
if (b) {
7
- console.log("true");
7
+ console.log('true');
8
} else {
9
- console.log("false");
9
+ console.log('false');
10
}
11
if (a) return;
12
useState();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-rules-of-hooks-f69800950ff0.expect.md
+2
-2
@@ -6,7 +6,7 @@
6
7
// Invalid because it's dangerous and might not warn otherwise.
8
// This *must* be invalid.
9
-function useHook({ bar }) {
9
+function useHook({bar}) {
10
let foo1 = bar && useState();
11
let foo2 = bar || useState();
12
let foo3 = bar ?? useState();
@@ -19,7 +19,7 @@ function useHook({ bar }) {
19
20
```
21
4 | // This *must* be invalid.
22
- 5 | function useHook({ bar }) {
22
+ 5 | function useHook({bar}) {
23
> 6 | let foo1 = bar && useState();
24
| ^^^^^^^^ InvalidReact: Hooks must always be called in a consistent order, and may not be called conditionally. See the Rules of Hooks (https://react.dev/warnings/invalid-hook-call-warning) (6:6)
25
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/error.invalid-rules-of-hooks-f69800950ff0.js
+1
-1
@@ -2,7 +2,7 @@
2
3
// Invalid because it's dangerous and might not warn otherwise.
4
// This *must* be invalid.
5
-function useHook({ bar }) {
5
+function useHook({bar}) {
6
let foo1 = bar && useState();
7
let foo2 = bar || useState();
8
let foo3 = bar ?? useState();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/rules-of-hooks-0592bd574811.expect.md
+1
-1
@@ -8,7 +8,7 @@
8
// and doesn't kick in unless we're confident we're in
9
// a component or a hook.
10
function makeListener(instance) {
11
- each(pixelsWithInferredEvents, (pixel) => {
11
+ each(pixelsWithInferredEvents, pixel => {
12
if (useExtendedSelector(pixel.id) && extendedButton) {
13
foo();
14
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/rules-of-hooks-0592bd574811.js
+1
-1
@@ -4,7 +4,7 @@
4
// and doesn't kick in unless we're confident we're in
5
// a component or a hook.
6
function makeListener(instance) {
7
- each(pixelsWithInferredEvents, (pixel) => {
7
+ each(pixelsWithInferredEvents, pixel => {
8
if (useExtendedSelector(pixel.id) && extendedButton) {
9
foo();
10
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/rules-of-hooks-0e2214abc294.expect.md
+1
-1
@@ -5,7 +5,7 @@
5
// Valid because exceptions abort rendering
6
function RegressionTest() {
7
if (page == null) {
8
- throw new Error("oh no!");
8
+ throw new Error('oh no!');
9
}
10
useState();
11
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/rules-of-hooks-0e2214abc294.js
+1
-1
@@ -1,7 +1,7 @@
1
// Valid because exceptions abort rendering
2
function RegressionTest() {
3
if (page == null) {
4
- throw new Error("oh no!");
4
+ throw new Error('oh no!');
5
}
6
useState();
7
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/rules-of-hooks-69521d94fa03.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
// Valid because the neither the condition nor the loop affect the hook call.
6
function App(props) {
7
- const someObject = { propA: true };
7
+ const someObject = {propA: true};
8
for (const propName in someObject) {
9
if (propName === true) {
10
} else {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/rules-of-hooks-69521d94fa03.js
+1
-1
@@ -1,6 +1,6 @@
1
// Valid because the neither the condition nor the loop affect the hook call.
2
function App(props) {
3
- const someObject = { propA: true };
3
+ const someObject = {propA: true};
4
for (const propName in someObject) {
5
if (propName === true) {
6
} else {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/todo.bail.rules-of-hooks-28a78701970c.expect.md
+1
-1
@@ -7,7 +7,7 @@
7
8
// Valid because hooks can be used in anonymous function arguments to
9
// React.memo.
10
-const MemoizedFunction = React.memo((props) => {
10
+const MemoizedFunction = React.memo(props => {
11
useHook();
12
return <button {...props} />;
13
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/todo.bail.rules-of-hooks-28a78701970c.js
+1
-1
@@ -3,7 +3,7 @@
3
4
// Valid because hooks can be used in anonymous function arguments to
5
// React.memo.
6
-const MemoizedFunction = React.memo((props) => {
6
+const MemoizedFunction = React.memo(props => {
7
useHook();
8
return <button {...props} />;
9
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/todo.invalid.invalid-rules-of-hooks-28a7111f56a7.expect.md
+2
-2
@@ -13,9 +13,9 @@
13
// the runtime error by accident.
14
// So we prefer to disallow it despite the false positive.
15
16
-const { createHistory, useBasename } = require("history-2.1.2");
16
+const {createHistory, useBasename} = require('history-2.1.2');
17
const browserHistory = useBasename(createHistory)({
18
- basename: "/",
18
+ basename: '/',
19
});
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/rules-of-hooks/todo.invalid.invalid-rules-of-hooks-28a7111f56a7.js
+2
-2
@@ -9,7 +9,7 @@
9
// the runtime error by accident.
10
// So we prefer to disallow it despite the false positive.
11
12
-const { createHistory, useBasename } = require("history-2.1.2");
12
+const {createHistory, useBasename} = require('history-2.1.2');
13
const browserHistory = useBasename(createHistory)({
14
- basename: "/",
14
+ basename: '/',
15
});
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/same-variable-as-dep-and-redeclare-maybe-frozen.expect.md
+2
-2
@@ -40,8 +40,8 @@ function foo(props) {
40
41
export const FIXTURE_ENTRYPOINT = {
42
fn: foo,
43
- params: ["TodoAdd"],
44
- isComponent: "TodoAdd",
43
+ params: ['TodoAdd'],
44
+ isComponent: 'TodoAdd',
45
};
46
47
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/same-variable-as-dep-and-redeclare-maybe-frozen.js
+2
-2
@@ -36,6 +36,6 @@ function foo(props) {
36
37
export const FIXTURE_ENTRYPOINT = {
38
fn: foo,
39
- params: ["TodoAdd"],
40
- isComponent: "TodoAdd",
39
+ params: ['TodoAdd'],
40
+ isComponent: 'TodoAdd',
41
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/same-variable-as-dep-and-redeclare.expect.md
+2
-2
@@ -40,8 +40,8 @@ function foo(props) {
40
41
export const FIXTURE_ENTRYPOINT = {
42
fn: foo,
43
- params: ["TodoAdd"],
44
- isComponent: "TodoAdd",
43
+ params: ['TodoAdd'],
44
+ isComponent: 'TodoAdd',
45
};
46
47
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/same-variable-as-dep-and-redeclare.js
+2
-2
@@ -36,6 +36,6 @@ function foo(props) {
36
37
export const FIXTURE_ENTRYPOINT = {
38
fn: foo,
39
- params: ["TodoAdd"],
40
- isComponent: "TodoAdd",
39
+ params: ['TodoAdd'],
40
+ isComponent: 'TodoAdd',
41
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/sequential-destructuring-assignment-to-scope-declarations.expect.md
+6
-6
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
function Component(statusName) {
8
- const { status, text } = foo(statusName);
9
- const { bg, color } = getStyles(status);
8
+ const {status, text} = foo(statusName);
9
+ const {bg, color} = getStyles(status);
10
return (
11
<div className={identity(bg)}>
12
<span className={identity(color)}>{[text]}</span>
@@ -23,14 +23,14 @@ function foo(name) {
23
24
function getStyles(status) {
25
return {
26
- bg: "#eee8d5",
27
- color: "#657b83",
26
+ bg: '#eee8d5',
27
+ color: '#657b83',
28
};
29
}
30
31
export const FIXTURE_ENTRYPOINT = {
32
fn: Component,
33
- params: ["Mofei"],
33
+ params: ['Mofei'],
34
};
35
36
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/sequential-destructuring-assignment-to-scope-declarations.js
+6
-6
@@ -1,8 +1,8 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
function Component(statusName) {
4
- const { status, text } = foo(statusName);
5
- const { bg, color } = getStyles(status);
4
+ const {status, text} = foo(statusName);
5
+ const {bg, color} = getStyles(status);
6
return (
7
<div className={identity(bg)}>
8
<span className={identity(color)}>{[text]}</span>
@@ -19,12 +19,12 @@ function foo(name) {
19
20
function getStyles(status) {
21
return {
22
- bg: "#eee8d5",
23
- color: "#657b83",
22
+ bg: '#eee8d5',
23
+ color: '#657b83',
24
};
25
}
26
27
export const FIXTURE_ENTRYPOINT = {
28
fn: Component,
29
- params: ["Mofei"],
29
+ params: ['Mofei'],
30
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/sequential-destructuring-both-mixed-local-and-scope-declaration.expect.md
+6
-6
@@ -2,13 +2,13 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
function Component(statusName) {
8
// status is local, text is a scope declaration
9
- const { status, text } = foo(statusName);
9
+ const {status, text} = foo(statusName);
10
// color is local, font is a scope declaration
11
- const { color, font } = getStyles(status);
11
+ const {color, font} = getStyles(status);
12
// bg is a declaration
13
const bg = identity(color);
14
return (
@@ -26,14 +26,14 @@ function foo(name) {
26
27
function getStyles(status) {
28
return {
29
- font: "comic-sans",
30
- color: "#657b83",
29
+ font: 'comic-sans',
30
+ color: '#657b83',
31
};
32
}
33
34
export const FIXTURE_ENTRYPOINT = {
35
fn: Component,
36
- params: ["Sathya"],
36
+ params: ['Sathya'],
37
};
38
39
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/sequential-destructuring-both-mixed-local-and-scope-declaration.js
+6
-6
@@ -1,10 +1,10 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
function Component(statusName) {
4
// status is local, text is a scope declaration
5
- const { status, text } = foo(statusName);
5
+ const {status, text} = foo(statusName);
6
// color is local, font is a scope declaration
7
- const { color, font } = getStyles(status);
7
+ const {color, font} = getStyles(status);
8
// bg is a declaration
9
const bg = identity(color);
10
return (
@@ -22,12 +22,12 @@ function foo(name) {
22
23
function getStyles(status) {
24
return {
25
- font: "comic-sans",
26
- color: "#657b83",
25
+ font: 'comic-sans',
26
+ color: '#657b83',
27
};
28
}
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: Component,
32
- params: ["Sathya"],
32
+ params: ['Sathya'],
33
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/sequentially-constant-progagatable-if-test-conditions.expect.md
+4
-4
@@ -14,13 +14,13 @@ function Component() {
14
15
let c;
16
if (b) {
17
- c = "hello";
17
+ c = 'hello';
18
} else {
19
c = null;
20
}
21
22
let d;
23
- if (c === "hello") {
23
+ if (c === 'hello') {
24
d = 42.0;
25
} else {
26
d = 42.001;
@@ -28,9 +28,9 @@ function Component() {
28
29
let e;
30
if (d === 42.0) {
31
- e = "ok";
31
+ e = 'ok';
32
} else {
33
- e = "nope";
33
+ e = 'nope';
34
}
35
36
// should constant-propagate to "ok"
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/sequentially-constant-progagatable-if-test-conditions.js
+4
-4
@@ -10,13 +10,13 @@ function Component() {
10
11
let c;
12
if (b) {
13
- c = "hello";
13
+ c = 'hello';
14
} else {
15
c = null;
16
}
17
18
let d;
19
- if (c === "hello") {
19
+ if (c === 'hello') {
20
d = 42.0;
21
} else {
22
d = 42.001;
@@ -24,9 +24,9 @@ function Component() {
24
25
let e;
26
if (d === 42.0) {
27
- e = "ok";
27
+ e = 'ok';
28
} else {
29
- e = "nope";
29
+ e = 'nope';
30
}
31
32
// should constant-propagate to "ok"
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/should-bailout-without-compilation-annotation-mode.expect.md
+3
-3
@@ -3,11 +3,11 @@
3
4
```javascript
5
// @gating @panicThreshold(none) @compilationMode(annotation)
6
-let someGlobal = "joe";
6
+let someGlobal = 'joe';
7
8
function Component() {
9
- "use forget";
10
- someGlobal = "wat";
9
+ 'use forget';
10
+ someGlobal = 'wat';
11
return null;
12
}
13
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/should-bailout-without-compilation-annotation-mode.js
+3
-3
@@ -1,9 +1,9 @@
1
// @gating @panicThreshold(none) @compilationMode(annotation)
2
-let someGlobal = "joe";
2
+let someGlobal = 'joe';
3
4
function Component() {
5
- "use forget";
6
- someGlobal = "wat";
5
+ 'use forget';
6
+ someGlobal = 'wat';
7
return null;
8
}
9
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/should-bailout-without-compilation-infer-mode.expect.md
+2
-2
@@ -3,10 +3,10 @@
3
4
```javascript
5
// @gating @panicThreshold(none) @compilationMode(infer)
6
-let someGlobal = "joe";
6
+let someGlobal = 'joe';
7
8
function Component() {
9
- someGlobal = "wat";
9
+ someGlobal = 'wat';
10
return <div>{someGlobal}</div>;
11
}
12
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/should-bailout-without-compilation-infer-mode.js
+2
-2
@@ -1,8 +1,8 @@
1
// @gating @panicThreshold(none) @compilationMode(infer)
2
-let someGlobal = "joe";
2
+let someGlobal = 'joe';
3
4
function Component() {
5
- someGlobal = "wat";
5
+ someGlobal = 'wat';
6
return <div>{someGlobal}</div>;
7
}
8
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/simple-scope.expect.md
+2
-2
@@ -9,8 +9,8 @@ function foo(a) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: foo,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/simple-scope.js
+2
-2
@@ -5,6 +5,6 @@ function foo(a) {
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: foo,
8
- params: ["TodoAdd"],
9
- isComponent: "TodoAdd",
8
+ params: ['TodoAdd'],
9
+ isComponent: 'TodoAdd',
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/skip-useMemoCache.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { c as useMemoCache } from "react/compiler-runtime";
5
+import {c as useMemoCache} from 'react/compiler-runtime';
6
7
function Component(props) {
8
const $ = useMemoCache();
@@ -18,7 +18,7 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ value: 42 }],
21
+ params: [{value: 42}],
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/skip-useMemoCache.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { c as useMemoCache } from "react/compiler-runtime";
1
+import {c as useMemoCache} from 'react/compiler-runtime';
2
3
function Component(props) {
4
const $ = useMemoCache();
@@ -14,5 +14,5 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ value: 42 }],
17
+ params: [{value: 42}],
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-arrayexpression.expect.md
+2
-2
@@ -11,8 +11,8 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-arrayexpression.js
+2
-2
@@ -7,6 +7,6 @@ function Component(props) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: ["TodoAdd"],
11
- isComponent: "TodoAdd",
10
+ params: ['TodoAdd'],
11
+ isComponent: 'TodoAdd',
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-cascading-eliminated-phis.expect.md
+2
-2
@@ -20,8 +20,8 @@ function Component(props) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
- params: ["TodoAdd"],
24
- isComponent: "TodoAdd",
23
+ params: ['TodoAdd'],
24
+ isComponent: 'TodoAdd',
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-cascading-eliminated-phis.js
+2
-2
@@ -16,6 +16,6 @@ function Component(props) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: ["TodoAdd"],
20
- isComponent: "TodoAdd",
19
+ params: ['TodoAdd'],
20
+ isComponent: 'TodoAdd',
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-for-of.expect.md
+2
-2
@@ -15,8 +15,8 @@ function foo(cond) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: foo,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-for-of.js
+2
-2
@@ -11,6 +11,6 @@ function foo(cond) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-multiple-phis.expect.md
+2
-2
@@ -24,8 +24,8 @@ function foo(a, b, c, d) {
24
25
export const FIXTURE_ENTRYPOINT = {
26
fn: foo,
27
- params: ["TodoAdd"],
28
- isComponent: "TodoAdd",
27
+ params: ['TodoAdd'],
28
+ isComponent: 'TodoAdd',
29
};
30
31
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-multiple-phis.js
+2
-2
@@ -20,6 +20,6 @@ function foo(a, b, c, d) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: foo,
23
- params: ["TodoAdd"],
24
- isComponent: "TodoAdd",
23
+ params: ['TodoAdd'],
24
+ isComponent: 'TodoAdd',
25
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-nested-loops-no-reassign.expect.md
+2
-2
@@ -17,8 +17,8 @@ function foo(a, b, c) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: foo,
20
- params: ["TodoAdd"],
21
- isComponent: "TodoAdd",
20
+ params: ['TodoAdd'],
21
+ isComponent: 'TodoAdd',
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-nested-loops-no-reassign.js
+2
-2
@@ -13,6 +13,6 @@ function foo(a, b, c) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: foo,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-nested-partial-phi.expect.md
+2
-2
@@ -15,8 +15,8 @@ function foo(a, b, c) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: foo,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-nested-partial-phi.js
+2
-2
@@ -11,6 +11,6 @@ function foo(a, b, c) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-nested-partial-reassignment.expect.md
+2
-2
@@ -16,8 +16,8 @@ function foo(a, b, c, d, e) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: foo,
19
- params: ["TodoAdd"],
20
- isComponent: "TodoAdd",
19
+ params: ['TodoAdd'],
20
+ isComponent: 'TodoAdd',
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-nested-partial-reassignment.js
+2
-2
@@ -12,6 +12,6 @@ function foo(a, b, c, d, e) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: foo,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-non-empty-initializer.expect.md
+2
-2
@@ -14,8 +14,8 @@ function foo(a, b) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: foo,
17
- params: ["TodoAdd"],
18
- isComponent: "TodoAdd",
17
+ params: ['TodoAdd'],
18
+ isComponent: 'TodoAdd',
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-non-empty-initializer.js
+2
-2
@@ -10,6 +10,6 @@ function foo(a, b) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: foo,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-objectexpression-phi.expect.md
+1
-1
@@ -12,7 +12,7 @@ function foo() {
12
y = 3;
13
}
14
15
- let t = { x: x, y: y };
15
+ let t = {x: x, y: y};
16
return t;
17
}
18
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-objectexpression-phi.js
+1
-1
@@ -8,7 +8,7 @@ function foo() {
8
y = 3;
9
}
10
11
- let t = { x: x, y: y };
11
+ let t = {x: x, y: y};
12
return t;
13
}
14
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-objectexpression.expect.md
+3
-3
@@ -5,14 +5,14 @@
5
function Component(props) {
6
const a = 1;
7
const b = 2;
8
- const x = { a: a, b: b };
8
+ const x = {a: a, b: b};
9
return x;
10
}
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-objectexpression.js
+3
-3
@@ -1,12 +1,12 @@
1
function Component(props) {
2
const a = 1;
3
const b = 2;
4
- const x = { a: a, b: b };
4
+ const x = {a: a, b: b};
5
return x;
6
}
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: Component,
10
- params: ["TodoAdd"],
11
- isComponent: "TodoAdd",
10
+ params: ['TodoAdd'],
11
+ isComponent: 'TodoAdd',
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-property-alias-if.expect.md
+2
-2
@@ -16,8 +16,8 @@ function foo(a) {
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: foo,
19
- params: ["TodoAdd"],
20
- isComponent: "TodoAdd",
19
+ params: ['TodoAdd'],
20
+ isComponent: 'TodoAdd',
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-property-alias-if.js
+2
-2
@@ -12,6 +12,6 @@ function foo(a) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: foo,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-property-call.expect.md
+1
-1
@@ -4,7 +4,7 @@
4
```javascript
5
function foo() {
6
const x = [];
7
- const y = { x: x };
7
+ const y = {x: x};
8
y.x.push([]);
9
return y;
10
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-property-call.js
+1
-1
@@ -1,6 +1,6 @@
1
function foo() {
2
const x = [];
3
- const y = { x: x };
3
+ const y = {x: x};
4
y.x.push([]);
5
return y;
6
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-reassign.expect.md
+2
-2
@@ -12,8 +12,8 @@ function foo(a, b, c) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: foo,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-reassign.js
+2
-2
@@ -8,6 +8,6 @@ function foo(a, b, c) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: foo,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-ternary-destruction-with-mutation.expect.md
+1
-1
@@ -5,7 +5,7 @@
5
function foo(props) {
6
let x = [];
7
x.push(props.bar);
8
- props.cond ? (({ x } = { x: {} }), ([x] = [[]]), x.push(props.foo)) : null;
8
+ props.cond ? (({x} = {x: {}}), ([x] = [[]]), x.push(props.foo)) : null;
9
mut(x);
10
return x;
11
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-ternary-destruction-with-mutation.js
+1
-1
@@ -1,7 +1,7 @@
1
function foo(props) {
2
let x = [];
3
x.push(props.bar);
4
- props.cond ? (({ x } = { x: {} }), ([x] = [[]]), x.push(props.foo)) : null;
4
+ props.cond ? (({x} = {x: {}}), ([x] = [[]]), x.push(props.foo)) : null;
5
mut(x);
6
return x;
7
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-ternary-destruction.expect.md
+3
-3
@@ -5,14 +5,14 @@
5
function foo(props) {
6
let x = [];
7
x.push(props.bar);
8
- props.cond ? (({ x } = { x: {} }), ([x] = [[]]), x.push(props.foo)) : null;
8
+ props.cond ? (({x} = {x: {}}), ([x] = [[]]), x.push(props.foo)) : null;
9
return x;
10
}
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-ternary-destruction.js
+3
-3
@@ -1,12 +1,12 @@
1
function foo(props) {
2
let x = [];
3
x.push(props.bar);
4
- props.cond ? (({ x } = { x: {} }), ([x] = [[]]), x.push(props.foo)) : null;
4
+ props.cond ? (({x} = {x: {}}), ([x] = [[]]), x.push(props.foo)) : null;
5
return x;
6
}
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: foo,
10
- params: ["TodoAdd"],
11
- isComponent: "TodoAdd",
10
+ params: ['TodoAdd'],
11
+ isComponent: 'TodoAdd',
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-ternary.expect.md
+2
-2
@@ -11,8 +11,8 @@ function foo(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-ternary.js
+2
-2
@@ -7,6 +7,6 @@ function foo(props) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: foo,
10
- params: ["TodoAdd"],
11
- isComponent: "TodoAdd",
10
+ params: ['TodoAdd'],
11
+ isComponent: 'TodoAdd',
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-unconditional-ternary-with-mutation.expect.md
+5
-5
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { arrayPush } from "shared-runtime";
5
+import {arrayPush} from 'shared-runtime';
6
function foo(props) {
7
let x = [];
8
x.push(props.bar);
@@ -15,11 +15,11 @@ function foo(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: foo,
18
- params: [{ cond: false, foo: 2, bar: 55 }],
18
+ params: [{cond: false, foo: 2, bar: 55}],
19
sequentialRenders: [
20
- { cond: false, foo: 2, bar: 55 },
21
- { cond: false, foo: 3, bar: 55 },
22
- { cond: true, foo: 3, bar: 55 },
20
+ {cond: false, foo: 2, bar: 55},
21
+ {cond: false, foo: 3, bar: 55},
22
+ {cond: true, foo: 3, bar: 55},
23
],
24
};
25
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-unconditional-ternary-with-mutation.js
+5
-5
@@ -1,4 +1,4 @@
1
-import { arrayPush } from "shared-runtime";
1
+import {arrayPush} from 'shared-runtime';
2
function foo(props) {
3
let x = [];
4
x.push(props.bar);
@@ -11,10 +11,10 @@ function foo(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: [{ cond: false, foo: 2, bar: 55 }],
14
+ params: [{cond: false, foo: 2, bar: 55}],
15
sequentialRenders: [
16
- { cond: false, foo: 2, bar: 55 },
17
- { cond: false, foo: 3, bar: 55 },
18
- { cond: true, foo: 3, bar: 55 },
16
+ {cond: false, foo: 2, bar: 55},
17
+ {cond: false, foo: 3, bar: 55},
18
+ {cond: true, foo: 3, bar: 55},
19
],
20
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-unconditional-ternary.expect.md
+2
-2
@@ -13,8 +13,8 @@ function foo(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: foo,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-unconditional-ternary.js
+2
-2
@@ -9,6 +9,6 @@ function foo(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: foo,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-via-destructuring-with-mutation.expect.md
+3
-3
@@ -3,11 +3,11 @@
3
4
```javascript
5
function foo(props) {
6
- let { x } = { x: [] };
6
+ let {x} = {x: []};
7
x.push(props.bar);
8
if (props.cond) {
9
- ({ x } = { x: {} });
10
- ({ x } = { x: [] });
9
+ ({x} = {x: {}});
10
+ ({x} = {x: []});
11
x.push(props.foo);
12
}
13
mut(x);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-via-destructuring-with-mutation.js
+3
-3
@@ -1,9 +1,9 @@
1
function foo(props) {
2
- let { x } = { x: [] };
2
+ let {x} = {x: []};
3
x.push(props.bar);
4
if (props.cond) {
5
- ({ x } = { x: {} });
6
- ({ x } = { x: [] });
5
+ ({x} = {x: {}});
6
+ ({x} = {x: []});
7
x.push(props.foo);
8
}
9
mut(x);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-via-destructuring.expect.md
+5
-5
@@ -3,11 +3,11 @@
3
4
```javascript
5
function foo(props) {
6
- let { x } = { x: [] };
6
+ let {x} = {x: []};
7
x.push(props.bar);
8
if (props.cond) {
9
- ({ x } = { x: {} });
10
- ({ x } = { x: [] });
9
+ ({x} = {x: {}});
10
+ ({x} = {x: []});
11
x.push(props.foo);
12
}
13
return x;
@@ -15,8 +15,8 @@ function foo(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: foo,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-via-destructuring.js
+5
-5
@@ -1,9 +1,9 @@
1
function foo(props) {
2
- let { x } = { x: [] };
2
+ let {x} = {x: []};
3
x.push(props.bar);
4
if (props.cond) {
5
- ({ x } = { x: {} });
6
- ({ x } = { x: [] });
5
+ ({x} = {x: {}});
6
+ ({x} = {x: []});
7
x.push(props.foo);
8
}
9
return x;
@@ -11,6 +11,6 @@ function foo(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming.expect.md
+2
-2
@@ -15,8 +15,8 @@ function foo(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: foo,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming.js
+2
-2
@@ -11,6 +11,6 @@ function foo(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-shadowing.expect.md
+3
-3
@@ -5,12 +5,12 @@
5
function log() {}
6
7
function Foo(cond) {
8
- let str = "";
8
+ let str = '';
9
if (cond) {
10
- let str = "other test";
10
+ let str = 'other test';
11
log(str);
12
} else {
13
- str = "fallthrough test";
13
+ str = 'fallthrough test';
14
}
15
log(str);
16
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-shadowing.js
+3
-3
@@ -1,12 +1,12 @@
1
function log() {}
2
3
function Foo(cond) {
4
- let str = "";
4
+ let str = '';
5
if (cond) {
6
- let str = "other test";
6
+ let str = 'other test';
7
log(str);
8
} else {
9
- str = "fallthrough test";
9
+ str = 'fallthrough test';
10
}
11
log(str);
12
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-sibling-phis.expect.md
+2
-2
@@ -24,8 +24,8 @@ function foo(a, b, c, d) {
24
25
export const FIXTURE_ENTRYPOINT = {
26
fn: foo,
27
- params: ["TodoAdd"],
28
- isComponent: "TodoAdd",
27
+ params: ['TodoAdd'],
28
+ isComponent: 'TodoAdd',
29
};
30
31
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-sibling-phis.js
+2
-2
@@ -20,6 +20,6 @@ function foo(a, b, c, d) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: foo,
23
- params: ["TodoAdd"],
24
- isComponent: "TodoAdd",
23
+ params: ['TodoAdd'],
24
+ isComponent: 'TodoAdd',
25
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/switch-with-fallthrough.expect.md
+2
-2
@@ -32,8 +32,8 @@ function foo(x) {
32
33
export const FIXTURE_ENTRYPOINT = {
34
fn: foo,
35
- params: ["TodoAdd"],
36
- isComponent: "TodoAdd",
35
+ params: ['TodoAdd'],
36
+ isComponent: 'TodoAdd',
37
};
38
39
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/switch-with-fallthrough.js
+2
-2
@@ -28,6 +28,6 @@ function foo(x) {
28
29
export const FIXTURE_ENTRYPOINT = {
30
fn: foo,
31
- params: ["TodoAdd"],
32
- isComponent: "TodoAdd",
31
+ params: ['TodoAdd'],
32
+ isComponent: 'TodoAdd',
33
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/switch-with-only-default.expect.md
+3
-3
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { Stringify } from "shared-runtime";
5
+import {Stringify} from 'shared-runtime';
6
7
-function Component({ kind, ...props }) {
7
+function Component({kind, ...props}) {
8
switch (kind) {
9
default:
10
return <Stringify {...props} />;
@@ -13,7 +13,7 @@ function Component({ kind, ...props }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ kind: "foo", a: 1, b: true, c: "sathya" }],
16
+ params: [{kind: 'foo', a: 1, b: true, c: 'sathya'}],
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/switch-with-only-default.js
+3
-3
@@ -1,6 +1,6 @@
1
-import { Stringify } from "shared-runtime";
1
+import {Stringify} from 'shared-runtime';
2
3
-function Component({ kind, ...props }) {
3
+function Component({kind, ...props}) {
4
switch (kind) {
5
default:
6
return <Stringify {...props} />;
@@ -9,5 +9,5 @@ function Component({ kind, ...props }) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: [{ kind: "foo", a: 1, b: true, c: "sathya" }],
12
+ params: [{kind: 'foo', a: 1, b: true, c: 'sathya'}],
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ternary-assignment-expression.expect.md
+2
-2
@@ -10,8 +10,8 @@ function ternary(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: ternary,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ternary-assignment-expression.js
+2
-2
@@ -6,6 +6,6 @@ function ternary(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: ternary,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ternary-expression.expect.md
+2
-2
@@ -10,8 +10,8 @@ function ternary(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: ternary,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ternary-expression.js
+2
-2
@@ -6,6 +6,6 @@ function ternary(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: ternary,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/todo-function-expression-captures-value-later-frozen.expect.md
+1
-1
@@ -6,7 +6,7 @@ function Component(props) {
6
let x = {};
7
// onChange should be inferred as immutable, because the value
8
// it captures (`x`) is frozen by the time the function is referenced
9
- const onChange = (e) => {
9
+ const onChange = e => {
10
maybeMutate(x, e.target.value);
11
};
12
if (props.cond) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/todo-function-expression-captures-value-later-frozen.js
+1
-1
@@ -2,7 +2,7 @@ function Component(props) {
2
let x = {};
3
// onChange should be inferred as immutable, because the value
4
// it captures (`x`) is frozen by the time the function is referenced
5
- const onChange = (e) => {
5
+ const onChange = e => {
6
maybeMutate(x, e.target.value);
7
};
8
if (props.cond) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/todo.error.object-pattern-computed-key.expect.md
+5
-5
@@ -2,17 +2,17 @@
2
## Input
3
4
```javascript
5
-import { identity } from "shared-runtime";
5
+import {identity} from 'shared-runtime';
6
7
const SCALE = 2;
8
function Component(props) {
9
- const { [props.name]: value } = props;
9
+ const {[props.name]: value} = props;
10
return value;
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ name: "Sathya" }],
15
+ params: [{name: 'Sathya'}],
16
};
17
18
```
@@ -23,8 +23,8 @@ export const FIXTURE_ENTRYPOINT = {
23
```
24
3 | const SCALE = 2;
25
4 | function Component(props) {
26
-> 5 | const { [props.name]: value } = props;
27
- | ^^^^^^^^^^^^^^^^^^^ Todo: (BuildHIR::lowerAssignment) Handle computed properties in ObjectPattern (5:5)
26
+> 5 | const {[props.name]: value} = props;
27
+ | ^^^^^^^^^^^^^^^^^^^ Todo: (BuildHIR::lowerAssignment) Handle computed properties in ObjectPattern (5:5)
28
6 | return value;
29
7 | }
30
8 |
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/todo.error.object-pattern-computed-key.js
+3
-3
@@ -1,12 +1,12 @@
1
-import { identity } from "shared-runtime";
1
+import {identity} from 'shared-runtime';
2
3
const SCALE = 2;
4
function Component(props) {
5
- const { [props.name]: value } = props;
5
+ const {[props.name]: value} = props;
6
return value;
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: [{ name: "Sathya" }],
11
+ params: [{name: 'Sathya'}],
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/todo.invalid-nested-function-reassign-local-variable-in-effect.expect.md
+7
-7
@@ -2,26 +2,26 @@
2
## Input
3
4
```javascript
5
-import { useEffect } from "react";
5
+import {useEffect} from 'react';
6
function Component() {
7
let local;
8
const mk_reassignlocal = () => {
9
// Create the reassignment function inside another function, then return it
10
- const reassignLocal = (newValue) => {
10
+ const reassignLocal = newValue => {
11
local = newValue;
12
};
13
return reassignLocal;
14
};
15
const reassignLocal = mk_reassignlocal();
16
- const onMount = (newValue) => {
17
- reassignLocal("hello");
16
+ const onMount = newValue => {
17
+ reassignLocal('hello');
18
if (local === newValue) {
19
// Without React Compiler, `reassignLocal` is freshly created
20
// on each render, capturing a binding to the latest `local`,
21
// such that invoking reassignLocal will reassign the same
22
// binding that we are observing in the if condition, and
23
// we reach this branch
24
- console.log("`local` was updated!");
24
+ console.log('`local` was updated!');
25
} else {
26
// With React Compiler enabled, `reassignLocal` is only created
27
// once, capturing a binding to `local` in that render pass.
@@ -31,13 +31,13 @@ function Component() {
31
//
32
// To protect against this, we disallow reassigning locals from
33
// functions that escape
34
- throw new Error("`local` not updated!");
34
+ throw new Error('`local` not updated!');
35
}
36
};
37
useEffect(() => {
38
onMount();
39
}, [onMount]);
40
- return "ok";
40
+ return 'ok';
41
}
42
43
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/todo.invalid-nested-function-reassign-local-variable-in-effect.js
+7
-7
@@ -1,23 +1,23 @@
1
-import { useEffect } from "react";
1
+import {useEffect} from 'react';
2
function Component() {
3
let local;
4
const mk_reassignlocal = () => {
5
// Create the reassignment function inside another function, then return it
6
- const reassignLocal = (newValue) => {
6
+ const reassignLocal = newValue => {
7
local = newValue;
8
};
9
return reassignLocal;
10
};
11
const reassignLocal = mk_reassignlocal();
12
- const onMount = (newValue) => {
13
- reassignLocal("hello");
12
+ const onMount = newValue => {
13
+ reassignLocal('hello');
14
if (local === newValue) {
15
// Without React Compiler, `reassignLocal` is freshly created
16
// on each render, capturing a binding to the latest `local`,
17
// such that invoking reassignLocal will reassign the same
18
// binding that we are observing in the if condition, and
19
// we reach this branch
20
- console.log("`local` was updated!");
20
+ console.log('`local` was updated!');
21
} else {
22
// With React Compiler enabled, `reassignLocal` is only created
23
// once, capturing a binding to `local` in that render pass.
@@ -27,11 +27,11 @@ function Component() {
27
//
28
// To protect against this, we disallow reassigning locals from
29
// functions that escape
30
- throw new Error("`local` not updated!");
30
+ throw new Error('`local` not updated!');
31
}
32
};
33
useEffect(() => {
34
onMount();
35
}, [onMount]);
36
- return "ok";
36
+ return 'ok';
37
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/todo.unnecessary-lambda-memoization.expect.md
+1
-1
@@ -13,7 +13,7 @@ function Component(props) {
13
// that it is a plain, readonly javascript object, then we can infer that any `.map()`
14
// calls *must* be Array.prototype.map (or else they are a runtime error), since no
15
// other builtin has a .map() function.
16
- const items = data.items.map((item) => <Item item={item} />);
16
+ const items = data.items.map(item => <Item item={item} />);
17
return <div>{items}</div>;
18
}
19
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/todo.unnecessary-lambda-memoization.js
+1
-1
@@ -9,6 +9,6 @@ function Component(props) {
9
// that it is a plain, readonly javascript object, then we can infer that any `.map()`
10
// calls *must* be Array.prototype.map (or else they are a runtime error), since no
11
// other builtin has a .map() function.
12
- const items = data.items.map((item) => <Item item={item} />);
12
+ const items = data.items.map(item => <Item item={item} />);
13
return <div>{items}</div>;
14
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/transitive-freeze-array.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees
6
-const { mutate } = require("shared-runtime");
6
+const {mutate} = require('shared-runtime');
7
8
function Component(props) {
9
const x = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/transitive-freeze-array.js
+1
-1
@@ -1,5 +1,5 @@
1
// @enablePreserveExistingMemoizationGuarantees
2
-const { mutate } = require("shared-runtime");
2
+const {mutate} = require('shared-runtime');
3
4
function Component(props) {
5
const x = {};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/transitive-freeze-function-expressions.expect.md
+2
-2
@@ -4,7 +4,7 @@
4
```javascript
5
// @enableTransitivelyFreezeFunctionExpressions
6
function Component(props) {
7
- const { data, loadNext, isLoadingNext } =
7
+ const {data, loadNext, isLoadingNext} =
8
usePaginationFragment(props.key).items ?? [];
9
10
const loadMoreWithTiming = () => {
@@ -21,7 +21,7 @@ function Component(props) {
21
loadMoreWithTiming();
22
}, [isLoadingNext, loadMoreWithTiming]);
23
24
- const items = data.map((x) => x);
24
+ const items = data.map(x => x);
25
26
return items;
27
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/transitive-freeze-function-expressions.js
+2
-2
@@ -1,6 +1,6 @@
1
// @enableTransitivelyFreezeFunctionExpressions
2
function Component(props) {
3
- const { data, loadNext, isLoadingNext } =
3
+ const {data, loadNext, isLoadingNext} =
4
usePaginationFragment(props.key).items ?? [];
5
6
const loadMoreWithTiming = () => {
@@ -17,7 +17,7 @@ function Component(props) {
17
loadMoreWithTiming();
18
}, [isLoadingNext, loadMoreWithTiming]);
19
20
- const items = data.map((x) => x);
20
+ const items = data.map(x => x);
21
22
return items;
23
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/trivial.expect.md
+2
-2
@@ -8,8 +8,8 @@ function foo(x) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: foo,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
14
15
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/trivial.js
+2
-2
@@ -4,6 +4,6 @@ function foo(x) {
4
5
export const FIXTURE_ENTRYPOINT = {
6
fn: foo,
7
- params: ["TodoAdd"],
8
- isComponent: "TodoAdd",
7
+ params: ['TodoAdd'],
8
+ isComponent: 'TodoAdd',
9
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-alias-try-values.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-const { throwInput } = require("shared-runtime");
5
+const {throwInput} = require('shared-runtime');
6
7
function Component(props) {
8
let y;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-alias-try-values.js
+1
-1
@@ -1,4 +1,4 @@
1
-const { throwInput } = require("shared-runtime");
1
+const {throwInput} = require('shared-runtime');
2
3
function Component(props) {
4
let y;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-empty-try.expect.md
+1
-1
@@ -13,7 +13,7 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ default: 42 }],
16
+ params: [{default: 42}],
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-empty-try.js
+1
-1
@@ -9,5 +9,5 @@ function Component(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: [{ default: 42 }],
12
+ params: [{default: 42}],
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-in-nested-scope.expect.md
+10
-10
@@ -2,20 +2,20 @@
2
## Input
3
4
```javascript
5
-import { mutate, setProperty, throwErrorWithMessageIf } from "shared-runtime";
5
+import {mutate, setProperty, throwErrorWithMessageIf} from 'shared-runtime';
6
7
-function useFoo({ value, cond }) {
7
+function useFoo({value, cond}) {
8
let y = [value];
9
- let x = { cond };
9
+ let x = {cond};
10
11
try {
12
mutate(x);
13
- throwErrorWithMessageIf(x.cond, "error");
13
+ throwErrorWithMessageIf(x.cond, 'error');
14
} catch {
15
- setProperty(x, "henderson");
15
+ setProperty(x, 'henderson');
16
return x;
17
}
18
- setProperty(x, "nevada");
18
+ setProperty(x, 'nevada');
19
y.push(x);
20
21
return y;
@@ -23,11 +23,11 @@ function useFoo({ value, cond }) {
23
24
export const FIXTURE_ENTRYPOINT = {
25
fn: useFoo,
26
- params: [{ value: 4, cond: true }],
26
+ params: [{value: 4, cond: true}],
27
sequentialRenders: [
28
- { value: 4, cond: true },
29
- { value: 5, cond: true },
30
- { value: 5, cond: false },
28
+ {value: 4, cond: true},
29
+ {value: 5, cond: true},
30
+ {value: 5, cond: false},
31
],
32
};
33
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-in-nested-scope.ts
+10
-10
@@ -1,17 +1,17 @@
1
-import { mutate, setProperty, throwErrorWithMessageIf } from "shared-runtime";
1
+import {mutate, setProperty, throwErrorWithMessageIf} from 'shared-runtime';
2
3
-function useFoo({ value, cond }) {
3
+function useFoo({value, cond}) {
4
let y = [value];
5
- let x = { cond };
5
+ let x = {cond};
6
7
try {
8
mutate(x);
9
- throwErrorWithMessageIf(x.cond, "error");
9
+ throwErrorWithMessageIf(x.cond, 'error');
10
} catch {
11
- setProperty(x, "henderson");
11
+ setProperty(x, 'henderson');
12
return x;
13
}
14
- setProperty(x, "nevada");
14
+ setProperty(x, 'nevada');
15
y.push(x);
16
17
return y;
@@ -19,10 +19,10 @@ function useFoo({ value, cond }) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: useFoo,
22
- params: [{ value: 4, cond: true }],
22
+ params: [{value: 4, cond: true}],
23
sequentialRenders: [
24
- { value: 4, cond: true },
25
- { value: 5, cond: true },
26
- { value: 5, cond: false },
24
+ {value: 4, cond: true},
25
+ {value: 5, cond: true},
26
+ {value: 5, cond: false},
27
],
28
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-mutate-outer-value.expect.md
+4
-4
@@ -2,21 +2,21 @@
2
## Input
3
4
```javascript
5
-const { shallowCopy, throwErrorWithMessage } = require("shared-runtime");
5
+const {shallowCopy, throwErrorWithMessage} = require('shared-runtime');
6
7
function Component(props) {
8
const x = [];
9
try {
10
- x.push(throwErrorWithMessage("oops"));
10
+ x.push(throwErrorWithMessage('oops'));
11
} catch {
12
- x.push(shallowCopy({ a: props.a }));
12
+ x.push(shallowCopy({a: props.a}));
13
}
14
return x;
15
}
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: Component,
19
- params: [{ a: 1 }],
19
+ params: [{a: 1}],
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-mutate-outer-value.js
+4
-4
@@ -1,16 +1,16 @@
1
-const { shallowCopy, throwErrorWithMessage } = require("shared-runtime");
1
+const {shallowCopy, throwErrorWithMessage} = require('shared-runtime');
2
3
function Component(props) {
4
const x = [];
5
try {
6
- x.push(throwErrorWithMessage("oops"));
6
+ x.push(throwErrorWithMessage('oops'));
7
} catch {
8
- x.push(shallowCopy({ a: props.a }));
8
+ x.push(shallowCopy({a: props.a}));
9
}
10
return x;
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ a: 1 }],
15
+ params: [{a: 1}],
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-try-immediately-returns.expect.md
+1
-1
@@ -17,7 +17,7 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ default: 42 }],
20
+ params: [{default: 42}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-try-immediately-returns.js
+1
-1
@@ -13,5 +13,5 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ default: 42 }],
16
+ params: [{default: 42}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-try-immediately-throws-after-constant-propagation.expect.md
+1
-1
@@ -17,7 +17,7 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ default: 42 }],
20
+ params: [{default: 42}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-try-immediately-throws-after-constant-propagation.js
+1
-1
@@ -13,5 +13,5 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ default: 42 }],
16
+ params: [{default: 42}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-try-value-modified-in-catch-escaping.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-const { throwInput } = require("shared-runtime");
5
+const {throwInput} = require('shared-runtime');
6
7
function Component(props) {
8
let x;
@@ -19,7 +19,7 @@ function Component(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: [{ y: "foo", e: "bar" }],
22
+ params: [{y: 'foo', e: 'bar'}],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-try-value-modified-in-catch-escaping.js
+2
-2
@@ -1,4 +1,4 @@
1
-const { throwInput } = require("shared-runtime");
1
+const {throwInput} = require('shared-runtime');
2
3
function Component(props) {
4
let x;
@@ -15,5 +15,5 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ y: "foo", e: "bar" }],
18
+ params: [{y: 'foo', e: 'bar'}],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-try-value-modified-in-catch.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-const { throwInput } = require("shared-runtime");
5
+const {throwInput} = require('shared-runtime');
6
7
function Component(props) {
8
try {
@@ -18,7 +18,7 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ y: "foo", e: "bar" }],
21
+ params: [{y: 'foo', e: 'bar'}],
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-try-value-modified-in-catch.js
+2
-2
@@ -1,4 +1,4 @@
1
-const { throwInput } = require("shared-runtime");
1
+const {throwInput} = require('shared-runtime');
2
3
function Component(props) {
4
try {
@@ -14,5 +14,5 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ y: "foo", e: "bar" }],
17
+ params: [{y: 'foo', e: 'bar'}],
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-with-catch-param.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-const { throwInput } = require("shared-runtime");
5
+const {throwInput} = require('shared-runtime');
6
7
function Component(props) {
8
let x = [];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-with-catch-param.js
+1
-1
@@ -1,4 +1,4 @@
1
-const { throwInput } = require("shared-runtime");
1
+const {throwInput} = require('shared-runtime');
2
3
function Component(props) {
4
let x = [];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-with-return.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-const { shallowCopy, throwInput } = require("shared-runtime");
5
+const {shallowCopy, throwInput} = require('shared-runtime');
6
7
function Component(props) {
8
let x = [];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-with-return.js
+1
-1
@@ -1,4 +1,4 @@
1
-const { shallowCopy, throwInput } = require("shared-runtime");
1
+const {shallowCopy, throwInput} = require('shared-runtime');
2
3
function Component(props) {
4
let x = [];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-within-function-expression-returns-caught-value.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { throwInput } from "shared-runtime";
5
+import {throwInput} from 'shared-runtime';
6
7
function Component(props) {
8
const callback = () => {
@@ -17,7 +17,7 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ value: 42 }],
20
+ params: [{value: 42}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-within-function-expression-returns-caught-value.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { throwInput } from "shared-runtime";
1
+import {throwInput} from 'shared-runtime';
2
3
function Component(props) {
4
const callback = () => {
@@ -13,5 +13,5 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ value: 42 }],
16
+ params: [{value: 42}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-within-mutable-range.expect.md
+2
-2
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-const { throwErrorWithMessage, shallowCopy } = require("shared-runtime");
5
+const {throwErrorWithMessage, shallowCopy} = require('shared-runtime');
6
7
function Component(props) {
8
const x = [];
9
try {
10
- x.push(throwErrorWithMessage("oops"));
10
+ x.push(throwErrorWithMessage('oops'));
11
} catch {
12
x.push(shallowCopy({}));
13
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-within-mutable-range.js
+2
-2
@@ -1,9 +1,9 @@
1
-const { throwErrorWithMessage, shallowCopy } = require("shared-runtime");
1
+const {throwErrorWithMessage, shallowCopy} = require('shared-runtime');
2
3
function Component(props) {
4
const x = [];
5
try {
6
- x.push(throwErrorWithMessage("oops"));
6
+ x.push(throwErrorWithMessage('oops'));
7
} catch {
8
x.push(shallowCopy({}));
9
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-within-object-method-returns-caught-value.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { throwInput } from "shared-runtime";
5
+import {throwInput} from 'shared-runtime';
6
7
function Component(props) {
8
const object = {
@@ -19,7 +19,7 @@ function Component(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: [{ value: 42 }],
22
+ params: [{value: 42}],
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch-within-object-method-returns-caught-value.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { throwInput } from "shared-runtime";
1
+import {throwInput} from 'shared-runtime';
2
3
function Component(props) {
4
const object = {
@@ -15,5 +15,5 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ value: 42 }],
18
+ params: [{value: 42}],
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch.expect.md
+2
-2
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-const { throwErrorWithMessage } = require("shared-runtime");
5
+const {throwErrorWithMessage} = require('shared-runtime');
6
7
function Component(props) {
8
let x;
9
try {
10
- x = throwErrorWithMessage("oops");
10
+ x = throwErrorWithMessage('oops');
11
} catch {
12
x = null;
13
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/try-catch.js
+2
-2
@@ -1,9 +1,9 @@
1
-const { throwErrorWithMessage } = require("shared-runtime");
1
+const {throwErrorWithMessage} = require('shared-runtime');
2
3
function Component(props) {
4
let x;
5
try {
6
- x = throwErrorWithMessage("oops");
6
+ x = throwErrorWithMessage('oops');
7
} catch {
8
x = null;
9
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-alias-declaration.expect.md
+3
-3
@@ -3,14 +3,14 @@
3
4
```javascript
5
function Component(props) {
6
- type User = { name: string };
7
- const user: User = { name: props.name };
6
+ type User = {name: string};
7
+ const user: User = {name: props.name};
8
return user;
9
}
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ name: "Mofei" }],
13
+ params: [{name: 'Mofei'}],
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-alias-declaration.ts
+3
-3
@@ -1,10 +1,10 @@
1
function Component(props) {
2
- type User = { name: string };
3
- const user: User = { name: props.name };
2
+ type User = {name: string};
3
+ const user: User = {name: props.name};
4
return user;
5
}
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: [{ name: "Mofei" }],
9
+ params: [{name: 'Mofei'}],
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-alias-used-as-annotation.expect.md
+1
-1
@@ -9,7 +9,7 @@ function TypeAliasUsedAsParamAnnotation() {
9
const fun = (f: Foo) => {
10
console.log(f);
11
};
12
- fun("hello, world");
12
+ fun('hello, world');
13
}
14
15
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-alias-used-as-annotation.ts
+1
-1
@@ -5,7 +5,7 @@ function TypeAliasUsedAsParamAnnotation() {
5
const fun = (f: Foo) => {
6
console.log(f);
7
};
8
- fun("hello, world");
8
+ fun('hello, world');
9
}
10
11
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-alias-used-as-variable-annotation.expect.md
+2
-2
@@ -6,11 +6,11 @@
6
type Bar = string;
7
function TypeAliasUsedAsVariableAnnotation() {
8
type Foo = Bar;
9
- const fun = (f) => {
9
+ const fun = f => {
10
let g: Foo = f;
11
console.log(g);
12
};
13
- fun("hello, world");
13
+ fun('hello, world');
14
}
15
16
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-alias-used-as-variable-annotation.ts
+2
-2
@@ -2,11 +2,11 @@
2
type Bar = string;
3
function TypeAliasUsedAsVariableAnnotation() {
4
type Foo = Bar;
5
- const fun = (f) => {
5
+ const fun = f => {
6
let g: Foo = f;
7
console.log(g);
8
};
9
- fun("hello, world");
9
+ fun('hello, world');
10
}
11
12
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-annotations/todo_type-annotations-props.expect.md
+1
-1
@@ -7,7 +7,7 @@ function useArray(items: Array<number>) {
7
// With type information we know that the callback cannot escape
8
// and does not need to be memoized, only the result needs to be
9
// memoized:
10
- return items.filter((x) => x !== 0);
10
+ return items.filter(x => x !== 0);
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-annotations/todo_type-annotations-props.ts
+1
-1
@@ -3,7 +3,7 @@ function useArray(items: Array<number>) {
3
// With type information we know that the callback cannot escape
4
// and does not need to be memoized, only the result needs to be
5
// memoized:
6
- return items.filter((x) => x !== 0);
6
+ return items.filter(x => x !== 0);
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-annotations/type-annotation-as-array.expect.md
+2
-2
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @enableUseTypeAnnotations
6
-function Component(props: { id: number }) {
6
+function Component(props: {id: number}) {
7
const x = makeArray(props.id) as number[];
8
const y = x.at(0);
9
return y;
@@ -15,7 +15,7 @@ function makeArray<T>(x: T): Array<T> {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ id: 42 }],
18
+ params: [{id: 42}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-annotations/type-annotation-as-array.ts
+2
-2
@@ -1,5 +1,5 @@
1
// @enableUseTypeAnnotations
2
-function Component(props: { id: number }) {
2
+function Component(props: {id: number}) {
3
const x = makeArray(props.id) as number[];
4
const y = x.at(0);
5
return y;
@@ -11,5 +11,5 @@ function makeArray<T>(x: T): Array<T> {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ id: 42 }],
14
+ params: [{id: 42}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-annotations/type-annotation-as-number.expect.md
+3
-3
@@ -3,9 +3,9 @@
3
4
```javascript
5
// @enableUseTypeAnnotations
6
-import { identity } from "shared-runtime";
6
+import {identity} from 'shared-runtime';
7
8
-function Component(props: { id: number }) {
8
+function Component(props: {id: number}) {
9
const x = identity(props.id);
10
const y = x as number;
11
return y;
@@ -13,7 +13,7 @@ function Component(props: { id: number }) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ id: 42 }],
16
+ params: [{id: 42}],
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-annotations/type-annotation-as-number.ts
+3
-3
@@ -1,7 +1,7 @@
1
// @enableUseTypeAnnotations
2
-import { identity } from "shared-runtime";
2
+import {identity} from 'shared-runtime';
3
4
-function Component(props: { id: number }) {
4
+function Component(props: {id: number}) {
5
const x = identity(props.id);
6
const y = x as number;
7
return y;
@@ -9,5 +9,5 @@ function Component(props: { id: number }) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: [{ id: 42 }],
12
+ params: [{id: 42}],
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-annotations/type-annotation-var-array.expect.md
+2
-2
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @enableUseTypeAnnotations
6
-function Component(props: { id: number }) {
6
+function Component(props: {id: number}) {
7
const x: number[] = makeArray(props.id);
8
const y = x.at(0);
9
return y;
@@ -15,7 +15,7 @@ function makeArray<T>(x: T): Array<T> {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ id: 42 }],
18
+ params: [{id: 42}],
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-annotations/type-annotation-var-array.ts
+2
-2
@@ -1,5 +1,5 @@
1
// @enableUseTypeAnnotations
2
-function Component(props: { id: number }) {
2
+function Component(props: {id: number}) {
3
const x: number[] = makeArray(props.id);
4
const y = x.at(0);
5
return y;
@@ -11,5 +11,5 @@ function makeArray<T>(x: T): Array<T> {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ id: 42 }],
14
+ params: [{id: 42}],
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-args-test-binary-operator.expect.md
+2
-2
@@ -10,8 +10,8 @@ function component(a, b) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-args-test-binary-operator.js
+2
-2
@@ -6,6 +6,6 @@ function component(a, b) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: component,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-field-load.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component() {
6
- let x = { t: 1 };
6
+ let x = {t: 1};
7
let p = x.t;
8
return p;
9
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-field-load.js
+1
-1
@@ -1,5 +1,5 @@
1
function component() {
2
- let x = { t: 1 };
2
+ let x = {t: 1};
3
let p = x.t;
4
return p;
5
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-test-field-load-binary-op.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component() {
6
- let x = { u: makeSomePrimitive(), v: makeSomePrimitive() };
6
+ let x = {u: makeSomePrimitive(), v: makeSomePrimitive()};
7
let u = x.u;
8
let v = x.v;
9
if (u > v) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/type-test-field-load-binary-op.js
+1
-1
@@ -1,5 +1,5 @@
1
function component() {
2
- let x = { u: makeSomePrimitive(), v: makeSomePrimitive() };
2
+ let x = {u: makeSomePrimitive(), v: makeSomePrimitive()};
3
let u = x.u;
4
let v = x.v;
5
if (u > v) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unary-expr.expect.md
+4
-4
@@ -3,7 +3,7 @@
3
4
```javascript
5
function component(a) {
6
- let t = { t: a };
6
+ let t = {t: a};
7
let z = +t.t;
8
let q = -t.t;
9
let p = void t.t;
@@ -11,13 +11,13 @@ function component(a) {
11
let m = !t.t;
12
let e = ~t.t;
13
let f = typeof t.t;
14
- return { z, p, q, n, m, e, f };
14
+ return {z, p, q, n, m, e, f};
15
}
16
17
export const FIXTURE_ENTRYPOINT = {
18
fn: component,
19
- params: ["TodoAdd"],
20
- isComponent: "TodoAdd",
19
+ params: ['TodoAdd'],
20
+ isComponent: 'TodoAdd',
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unary-expr.js
+4
-4
@@ -1,5 +1,5 @@
1
function component(a) {
2
- let t = { t: a };
2
+ let t = {t: a};
3
let z = +t.t;
4
let q = -t.t;
5
let p = void t.t;
@@ -7,11 +7,11 @@ function component(a) {
7
let m = !t.t;
8
let e = ~t.t;
9
let f = typeof t.t;
10
- return { z, p, q, n, m, e, f };
10
+ return {z, p, q, n, m, e, f};
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: component,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unconditional-break-label.expect.md
+2
-2
@@ -13,8 +13,8 @@ function foo(a) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: foo,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unconditional-break-label.js
+2
-2
@@ -9,6 +9,6 @@ function foo(a) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: foo,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unlabeled-break-within-label-switch.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { CONST_STRING0 } from "shared-runtime";
5
+import {CONST_STRING0} from 'shared-runtime';
6
7
function useHook(cond) {
8
const log = [];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unlabeled-break-within-label-switch.ts
+1
-1
@@ -1,4 +1,4 @@
1
-import { CONST_STRING0 } from "shared-runtime";
1
+import {CONST_STRING0} from 'shared-runtime';
2
3
function useHook(cond) {
4
const log = [];
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unmemoized-nonreactive-dependency-is-pruned-as-dependency.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { mutate, useNoAlias } from "shared-runtime";
5
+import {mutate, useNoAlias} from 'shared-runtime';
6
7
function Component(props) {
8
// Here `x` cannot be memoized bc its mutable range spans a hook call:
@@ -17,7 +17,7 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ value: 42 }],
20
+ params: [{value: 42}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unmemoized-nonreactive-dependency-is-pruned-as-dependency.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { mutate, useNoAlias } from "shared-runtime";
1
+import {mutate, useNoAlias} from 'shared-runtime';
2
3
function Component(props) {
4
// Here `x` cannot be memoized bc its mutable range spans a hook call:
@@ -13,5 +13,5 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ value: 42 }],
16
+ params: [{value: 42}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unused-array-middle-element.expect.md
+2
-2
@@ -9,8 +9,8 @@ function foo(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: foo,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unused-array-middle-element.js
+2
-2
@@ -5,6 +5,6 @@ function foo(props) {
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: foo,
8
- params: ["TodoAdd"],
9
- isComponent: "TodoAdd",
8
+ params: ['TodoAdd'],
9
+ isComponent: 'TodoAdd',
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unused-array-rest-element.expect.md
+2
-2
@@ -9,8 +9,8 @@ function foo(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: foo,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unused-array-rest-element.js
+2
-2
@@ -5,6 +5,6 @@ function foo(props) {
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: foo,
8
- params: ["TodoAdd"],
9
- isComponent: "TodoAdd",
8
+ params: ['TodoAdd'],
9
+ isComponent: 'TodoAdd',
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unused-conditional.expect.md
+2
-2
@@ -10,8 +10,8 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unused-conditional.js
+2
-2
@@ -6,6 +6,6 @@ function Component(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unused-logical.expect.md
+2
-2
@@ -10,8 +10,8 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unused-logical.js
+2
-2
@@ -6,6 +6,6 @@ function Component(props) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unused-object-element-with-rest.expect.md
+3
-3
@@ -4,14 +4,14 @@
4
```javascript
5
function Foo(props) {
6
// can't remove `unused` since it affects which properties are copied into `rest`
7
- const { unused, ...rest } = props.a;
7
+ const {unused, ...rest} = props.a;
8
return rest;
9
}
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Foo,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
16
17
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unused-object-element-with-rest.js
+3
-3
@@ -1,11 +1,11 @@
1
function Foo(props) {
2
// can't remove `unused` since it affects which properties are copied into `rest`
3
- const { unused, ...rest } = props.a;
3
+ const {unused, ...rest} = props.a;
4
return rest;
5
}
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Foo,
9
- params: ["TodoAdd"],
10
- isComponent: "TodoAdd",
9
+ params: ['TodoAdd'],
10
+ isComponent: 'TodoAdd',
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unused-object-element.expect.md
+3
-3
@@ -3,14 +3,14 @@
3
4
```javascript
5
function Foo(props) {
6
- const { x, y, ...z } = props.a;
6
+ const {x, y, ...z} = props.a;
7
return x;
8
}
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Foo,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/unused-object-element.js
+3
-3
@@ -1,10 +1,10 @@
1
function Foo(props) {
2
- const { x, y, ...z } = props.a;
2
+ const {x, y, ...z} = props.a;
3
return x;
4
}
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: Foo,
8
- params: ["TodoAdd"],
9
- isComponent: "TodoAdd",
8
+ params: ['TodoAdd'],
9
+ isComponent: 'TodoAdd',
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/update-expression-constant-propagation.expect.md
+1
-1
@@ -8,7 +8,7 @@ function Component() {
8
const c = ++a;
9
const d = a--;
10
const e = --a;
11
- return { a, b, c, d, e };
11
+ return {a, b, c, d, e};
12
}
13
14
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/update-expression-constant-propagation.js
+1
-1
@@ -4,7 +4,7 @@ function Component() {
4
const c = ++a;
5
const d = a--;
6
const e = --a;
7
- return { a, b, c, d, e };
7
+ return {a, b, c, d, e};
8
}
9
10
export const FIXTURE_ENTRYPOINT = {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/update-expression-in-sequence.expect.md
+1
-1
@@ -15,7 +15,7 @@ function Component(props) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: Component,
18
- params: [{ x: 2, cond: true }],
18
+ params: [{x: 2, cond: true}],
19
isComponent: false,
20
};
21
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/update-expression-in-sequence.js
+1
-1
@@ -11,6 +11,6 @@ function Component(props) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: Component,
14
- params: [{ x: 2, cond: true }],
14
+ params: [{x: 2, cond: true}],
15
isComponent: false,
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/update-expression-on-function-parameter-1.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function Component({ a: a, b: [b], c: { c } }) {
5
+function Component({a: a, b: [b], c: {c}}) {
6
let d = a++;
7
let e = ++a;
8
let f = b--;
@@ -14,7 +14,7 @@ function Component({ a: a, b: [b], c: { c } }) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: [{ a: 2, b: [3], c: { c: 4 } }],
17
+ params: [{a: 2, b: [3], c: {c: 4}}],
18
isComponent: false,
19
};
20
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/update-expression-on-function-parameter-1.js
+2
-2
@@ -1,4 +1,4 @@
1
-function Component({ a: a, b: [b], c: { c } }) {
1
+function Component({a: a, b: [b], c: {c}}) {
2
let d = a++;
3
let e = ++a;
4
let f = b--;
@@ -10,6 +10,6 @@ function Component({ a: a, b: [b], c: { c } }) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ a: 2, b: [3], c: { c: 4 } }],
13
+ params: [{a: 2, b: [3], c: {c: 4}}],
14
isComponent: false,
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/update-expression-on-function-parameter-3.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-function Component({ c }) {
5
+function Component({c}) {
6
let h = c++;
7
let i = --c;
8
return [c, h, i];
@@ -10,7 +10,7 @@ function Component({ c }) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ c: 4 }],
13
+ params: [{c: 4}],
14
isComponent: false,
15
};
16
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/update-expression-on-function-parameter-3.js
+2
-2
@@ -1,4 +1,4 @@
1
-function Component({ c }) {
1
+function Component({c}) {
2
let h = c++;
3
let i = --c;
4
return [c, h, i];
@@ -6,6 +6,6 @@ function Component({ c }) {
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: [{ c: 4 }],
9
+ params: [{c: 4}],
10
isComponent: false,
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/update-expression.expect.md
+3
-3
@@ -2,16 +2,16 @@
2
## Input
3
4
```javascript
5
-function foo(props: { x: number }) {
5
+function foo(props: {x: number}) {
6
let x = props.x;
7
let y = x++;
8
let z = x--;
9
- return { x, y, z };
9
+ return {x, y, z};
10
}
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: [{ x: 1 }],
14
+ params: [{x: 1}],
15
isComponent: false,
16
};
17
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/update-expression.ts
+3
-3
@@ -1,12 +1,12 @@
1
-function foo(props: { x: number }) {
1
+function foo(props: {x: number}) {
2
let x = props.x;
3
let y = x++;
4
let z = x--;
5
- return { x, y, z };
5
+ return {x, y, z};
6
}
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: foo,
10
- params: [{ x: 1 }],
10
+ params: [{x: 1}],
11
isComponent: false,
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-memo-simple.expect.md
+2
-2
@@ -3,14 +3,14 @@
3
4
```javascript
5
function Component(props) {
6
- "use memo";
6
+ 'use memo';
7
let x = [props.foo];
8
return <div x={x}>"foo"</div>;
9
}
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ foo: 1 }],
13
+ params: [{foo: 1}],
14
isComponent: true,
15
};
16
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-memo-simple.js
+2
-2
@@ -1,11 +1,11 @@
1
function Component(props) {
2
- "use memo";
2
+ 'use memo';
3
let x = [props.foo];
4
return <div x={x}>"foo"</div>;
5
}
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: [{ foo: 1 }],
9
+ params: [{foo: 1}],
10
isComponent: true,
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-no-forget-module-level.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-"use no forget";
5
+'use no forget';
6
7
export default function foo(x, y) {
8
if (x) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-no-forget-module-level.js
+1
-1
@@ -1,4 +1,4 @@
1
-"use no forget";
1
+'use no forget';
2
3
export default function foo(x, y) {
4
if (x) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-no-forget-multiple-with-eslint-suppression.expect.md
+4
-4
@@ -2,16 +2,16 @@
2
## Input
3
4
```javascript
5
-import { useRef } from "react";
5
+import {useRef} from 'react';
6
7
-const useControllableState = (options) => {};
7
+const useControllableState = options => {};
8
function NoopComponent() {}
9
10
function Component() {
11
- "use no forget";
11
+ 'use no forget';
12
const ref = useRef(null);
13
// eslint-disable-next-line react-hooks/rules-of-hooks
14
- ref.current = "bad";
14
+ ref.current = 'bad';
15
return <button ref={ref} />;
16
}
17
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-no-forget-multiple-with-eslint-suppression.js
+4
-4
@@ -1,13 +1,13 @@
1
-import { useRef } from "react";
1
+import {useRef} from 'react';
2
3
-const useControllableState = (options) => {};
3
+const useControllableState = options => {};
4
function NoopComponent() {}
5
6
function Component() {
7
- "use no forget";
7
+ 'use no forget';
8
const ref = useRef(null);
9
// eslint-disable-next-line react-hooks/rules-of-hooks
10
- ref.current = "bad";
10
+ ref.current = 'bad';
11
return <button ref={ref} />;
12
}
13
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-no-forget-with-eslint-suppression.expect.md
+3
-3
@@ -2,13 +2,13 @@
2
## Input
3
4
```javascript
5
-import { useRef } from "react";
5
+import {useRef} from 'react';
6
7
function Component() {
8
- "use no forget";
8
+ 'use no forget';
9
const ref = useRef(null);
10
// eslint-disable-next-line react-hooks/rules-of-hooks
11
- ref.current = "bad";
11
+ ref.current = 'bad';
12
return <button ref={ref} />;
13
}
14
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-no-forget-with-eslint-suppression.js
+3
-3
@@ -1,10 +1,10 @@
1
-import { useRef } from "react";
1
+import {useRef} from 'react';
2
3
function Component() {
4
- "use no forget";
4
+ 'use no forget';
5
const ref = useRef(null);
6
// eslint-disable-next-line react-hooks/rules-of-hooks
7
- ref.current = "bad";
7
+ ref.current = 'bad';
8
return <button ref={ref} />;
9
}
10
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-no-memo-module-level.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-"use no memo";
5
+'use no memo';
6
7
export default function foo(x, y) {
8
if (x) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-no-memo-module-level.js
+1
-1
@@ -1,4 +1,4 @@
1
-"use no memo";
1
+'use no memo';
2
3
export default function foo(x, y) {
4
if (x) {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-no-memo-simple.expect.md
+2
-2
@@ -3,14 +3,14 @@
3
4
```javascript
5
function Component(props) {
6
- "use no memo";
6
+ 'use no memo';
7
let x = [props.foo];
8
return <div x={x}>"foo"</div>;
9
}
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: [{ foo: 1 }],
13
+ params: [{foo: 1}],
14
isComponent: true,
15
};
16
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-no-memo-simple.js
+2
-2
@@ -1,11 +1,11 @@
1
function Component(props) {
2
- "use no memo";
2
+ 'use no memo';
3
let x = [props.foo];
4
return <div x={x}>"foo"</div>;
5
}
6
7
export const FIXTURE_ENTRYPOINT = {
8
fn: Component,
9
- params: [{ foo: 1 }],
9
+ params: [{foo: 1}],
10
isComponent: true,
11
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-operator-call-expression.expect.md
+12
-12
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import { ValidateMemoization } from "shared-runtime";
6
-import { use, useMemo } from "react";
5
+import {ValidateMemoization} from 'shared-runtime';
6
+import {use, useMemo} from 'react';
7
8
const FooContext = React.createContext(null);
9
function Component(props) {
@@ -22,17 +22,17 @@ function Inner(props) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
25
- params: [{ value: 42 }],
25
+ params: [{value: 42}],
26
sequentialRenders: [
27
- { value: null },
28
- { value: 42 },
29
- { value: 42 },
30
- { value: null },
31
- { value: null },
32
- { value: 42 },
33
- { value: null },
34
- { value: 42 },
35
- { value: null },
27
+ {value: null},
28
+ {value: 42},
29
+ {value: 42},
30
+ {value: null},
31
+ {value: null},
32
+ {value: 42},
33
+ {value: null},
34
+ {value: 42},
35
+ {value: null},
36
],
37
};
38
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-operator-call-expression.js
+12
-12
@@ -1,5 +1,5 @@
1
-import { ValidateMemoization } from "shared-runtime";
2
-import { use, useMemo } from "react";
1
+import {ValidateMemoization} from 'shared-runtime';
2
+import {use, useMemo} from 'react';
3
4
const FooContext = React.createContext(null);
5
function Component(props) {
@@ -18,16 +18,16 @@ function Inner(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ value: 42 }],
21
+ params: [{value: 42}],
22
sequentialRenders: [
23
- { value: null },
24
- { value: 42 },
25
- { value: 42 },
26
- { value: null },
27
- { value: null },
28
- { value: 42 },
29
- { value: null },
30
- { value: 42 },
31
- { value: null },
23
+ {value: null},
24
+ {value: 42},
25
+ {value: 42},
26
+ {value: null},
27
+ {value: null},
28
+ {value: 42},
29
+ {value: null},
30
+ {value: 42},
31
+ {value: null},
32
],
33
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-operator-conditional.expect.md
+11
-11
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import { ValidateMemoization } from "shared-runtime";
6
-import { use, useMemo } from "react";
5
+import {ValidateMemoization} from 'shared-runtime';
6
+import {use, useMemo} from 'react';
7
8
const FooContext = React.createContext(null);
9
function Component(props) {
@@ -25,23 +25,23 @@ function Inner(props) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Component,
28
- params: [{ cond: true, value: 42 }],
28
+ params: [{cond: true, value: 42}],
29
sequentialRenders: [
30
// change cond true->false
31
- { cond: true, value: 42 },
32
- { cond: false, value: 42 },
31
+ {cond: true, value: 42},
32
+ {cond: false, value: 42},
33
34
// change value
35
- { cond: false, value: null },
36
- { cond: false, value: 42 },
35
+ {cond: false, value: null},
36
+ {cond: false, value: 42},
37
38
// change cond false->true
39
- { cond: true, value: 42 },
39
+ {cond: true, value: 42},
40
41
// change cond true->false, change unobserved value, change cond false->true
42
- { cond: false, value: 42 },
43
- { cond: false, value: null },
44
- { cond: true, value: 42 },
42
+ {cond: false, value: 42},
43
+ {cond: false, value: null},
44
+ {cond: true, value: 42},
45
],
46
};
47
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-operator-conditional.js
+11
-11
@@ -1,5 +1,5 @@
1
-import { ValidateMemoization } from "shared-runtime";
2
-import { use, useMemo } from "react";
1
+import {ValidateMemoization} from 'shared-runtime';
2
+import {use, useMemo} from 'react';
3
4
const FooContext = React.createContext(null);
5
function Component(props) {
@@ -21,22 +21,22 @@ function Inner(props) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
- params: [{ cond: true, value: 42 }],
24
+ params: [{cond: true, value: 42}],
25
sequentialRenders: [
26
// change cond true->false
27
- { cond: true, value: 42 },
28
- { cond: false, value: 42 },
27
+ {cond: true, value: 42},
28
+ {cond: false, value: 42},
29
30
// change value
31
- { cond: false, value: null },
32
- { cond: false, value: 42 },
31
+ {cond: false, value: null},
32
+ {cond: false, value: 42},
33
34
// change cond false->true
35
- { cond: true, value: 42 },
35
+ {cond: true, value: 42},
36
37
// change cond true->false, change unobserved value, change cond false->true
38
- { cond: false, value: 42 },
39
- { cond: false, value: null },
40
- { cond: true, value: 42 },
38
+ {cond: false, value: 42},
39
+ {cond: false, value: null},
40
+ {cond: true, value: 42},
41
],
42
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-operator-method-call.expect.md
+13
-13
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { ValidateMemoization } from "shared-runtime";
6
-import { useMemo } from "react";
7
-import * as React from "react";
5
+import {ValidateMemoization} from 'shared-runtime';
6
+import {useMemo} from 'react';
7
+import * as React from 'react';
8
9
const FooContext = React.createContext(null);
10
function Component(props) {
@@ -23,17 +23,17 @@ function Inner(props) {
23
24
export const FIXTURE_ENTRYPOINT = {
25
fn: Component,
26
- params: [{ value: 42 }],
26
+ params: [{value: 42}],
27
sequentialRenders: [
28
- { value: null },
29
- { value: 42 },
30
- { value: 42 },
31
- { value: null },
32
- { value: null },
33
- { value: 42 },
34
- { value: null },
35
- { value: 42 },
36
- { value: null },
28
+ {value: null},
29
+ {value: 42},
30
+ {value: 42},
31
+ {value: null},
32
+ {value: null},
33
+ {value: 42},
34
+ {value: null},
35
+ {value: 42},
36
+ {value: null},
37
],
38
};
39
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/use-operator-method-call.js
+13
-13
@@ -1,6 +1,6 @@
1
-import { ValidateMemoization } from "shared-runtime";
2
-import { useMemo } from "react";
3
-import * as React from "react";
1
+import {ValidateMemoization} from 'shared-runtime';
2
+import {useMemo} from 'react';
3
+import * as React from 'react';
4
5
const FooContext = React.createContext(null);
6
function Component(props) {
@@ -19,16 +19,16 @@ function Inner(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
22
- params: [{ value: 42 }],
22
+ params: [{value: 42}],
23
sequentialRenders: [
24
- { value: null },
25
- { value: 42 },
26
- { value: 42 },
27
- { value: null },
28
- { value: null },
29
- { value: 42 },
30
- { value: null },
31
- { value: 42 },
32
- { value: null },
24
+ {value: null},
25
+ {value: 42},
26
+ {value: 42},
27
+ {value: null},
28
+ {value: null},
29
+ {value: 42},
30
+ {value: null},
31
+ {value: 42},
32
+ {value: null},
33
],
34
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useActionState-dispatch-considered-as-non-reactive.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useActionState } from "react";
5
+import {useActionState} from 'react';
6
7
function Component() {
8
const [actionState, dispatchAction] = useActionState();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useActionState-dispatch-considered-as-non-reactive.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { useActionState } from "react";
1
+import {useActionState} from 'react';
2
3
function Component() {
4
const [actionState, dispatchAction] = useActionState();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-call-second-function-which-captures-maybe-mutable-value-dont-preserve-memoization.expect.md
+2
-2
@@ -3,13 +3,13 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees:false @enableTransitivelyFreezeFunctionExpressions:false
6
-import { useCallback } from "react";
6
+import {useCallback} from 'react';
7
import {
8
identity,
9
logValue,
10
makeObject_Primitives,
11
useHook,
12
-} from "shared-runtime";
12
+} from 'shared-runtime';
13
14
function Component(props) {
15
const object = makeObject_Primitives();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-call-second-function-which-captures-maybe-mutable-value-dont-preserve-memoization.js
+2
-2
@@ -1,11 +1,11 @@
1
// @enablePreserveExistingMemoizationGuarantees:false @enableTransitivelyFreezeFunctionExpressions:false
2
-import { useCallback } from "react";
2
+import {useCallback} from 'react';
3
import {
4
identity,
5
logValue,
6
makeObject_Primitives,
7
useHook,
8
-} from "shared-runtime";
8
+} from 'shared-runtime';
9
10
function Component(props) {
11
const object = makeObject_Primitives();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-call-second-function-which-captures-maybe-mutable-value-preserve-memoization.expect.md
+2
-2
@@ -3,13 +3,13 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees
6
-import { useCallback } from "react";
6
+import {useCallback} from 'react';
7
import {
8
identity,
9
logValue,
10
makeObject_Primitives,
11
useHook,
12
-} from "shared-runtime";
12
+} from 'shared-runtime';
13
14
function Component(props) {
15
const object = makeObject_Primitives();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-call-second-function-which-captures-maybe-mutable-value-preserve-memoization.js
+2
-2
@@ -1,11 +1,11 @@
1
// @enablePreserveExistingMemoizationGuarantees
2
-import { useCallback } from "react";
2
+import {useCallback} from 'react';
3
import {
4
identity,
5
logValue,
6
makeObject_Primitives,
7
useHook,
8
-} from "shared-runtime";
8
+} from 'shared-runtime';
9
10
function Component(props) {
11
const object = makeObject_Primitives();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-maybe-modify-free-variable-dont-preserve-memoization-guarantee.expect.md
+3
-8
@@ -3,13 +3,8 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees:false
6
-import { useCallback } from "react";
7
-import {
8
- identity,
9
- makeObject_Primitives,
10
- mutate,
11
- useHook,
12
-} from "shared-runtime";
6
+import {useCallback} from 'react';
7
+import {identity, makeObject_Primitives, mutate, useHook} from 'shared-runtime';
8
9
function Component(props) {
10
const free = makeObject_Primitives();
@@ -28,7 +23,7 @@ function Component(props) {
23
24
export const FIXTURE_ENTRYPOINT = {
25
fn: Component,
31
- params: [{ value: 42 }],
26
+ params: [{value: 42}],
27
};
28
29
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-maybe-modify-free-variable-dont-preserve-memoization-guarantee.js
+3
-8
@@ -1,11 +1,6 @@
1
// @enablePreserveExistingMemoizationGuarantees:false
2
-import { useCallback } from "react";
3
-import {
4
- identity,
5
- makeObject_Primitives,
6
- mutate,
7
- useHook,
8
-} from "shared-runtime";
2
+import {useCallback} from 'react';
3
+import {identity, makeObject_Primitives, mutate, useHook} from 'shared-runtime';
4
5
function Component(props) {
6
const free = makeObject_Primitives();
@@ -24,5 +19,5 @@ function Component(props) {
19
20
export const FIXTURE_ENTRYPOINT = {
21
fn: Component,
27
- params: [{ value: 42 }],
22
+ params: [{value: 42}],
23
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-maybe-modify-free-variable-preserve-memoization-guarantee.expect.md
+3
-8
@@ -3,13 +3,8 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees
6
-import { useCallback } from "react";
7
-import {
8
- identity,
9
- makeObject_Primitives,
10
- mutate,
11
- useHook,
12
-} from "shared-runtime";
6
+import {useCallback} from 'react';
7
+import {identity, makeObject_Primitives, mutate, useHook} from 'shared-runtime';
8
9
function Component(props) {
10
const free = makeObject_Primitives();
@@ -27,7 +22,7 @@ function Component(props) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
30
- params: [{ value: 42 }],
25
+ params: [{value: 42}],
26
};
27
28
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-maybe-modify-free-variable-preserve-memoization-guarantee.js
+3
-8
@@ -1,11 +1,6 @@
1
// @enablePreserveExistingMemoizationGuarantees
2
-import { useCallback } from "react";
3
-import {
4
- identity,
5
- makeObject_Primitives,
6
- mutate,
7
- useHook,
8
-} from "shared-runtime";
2
+import {useCallback} from 'react';
3
+import {identity, makeObject_Primitives, mutate, useHook} from 'shared-runtime';
4
5
function Component(props) {
6
const free = makeObject_Primitives();
@@ -23,5 +18,5 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
26
- params: [{ value: 42 }],
21
+ params: [{value: 42}],
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-multiple-callbacks-modifying-same-ref-preserve-memoization.expect.md
+3
-3
@@ -3,12 +3,12 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees
6
-import { useCallback, useRef } from "react";
6
+import {useCallback, useRef} from 'react';
7
8
function Component(props) {
9
- const ref = useRef({ inner: null });
9
+ const ref = useRef({inner: null});
10
11
- const onChange = useCallback((event) => {
11
+ const onChange = useCallback(event => {
12
// The ref should still be mutable here even though function deps are frozen in
13
// @enablePreserveExistingMemoizationGuarantees mode
14
ref.current.inner = event.target.value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-multiple-callbacks-modifying-same-ref-preserve-memoization.js
+3
-3
@@ -1,10 +1,10 @@
1
// @enablePreserveExistingMemoizationGuarantees
2
-import { useCallback, useRef } from "react";
2
+import {useCallback, useRef} from 'react';
3
4
function Component(props) {
5
- const ref = useRef({ inner: null });
5
+ const ref = useRef({inner: null});
6
7
- const onChange = useCallback((event) => {
7
+ const onChange = useCallback(event => {
8
// The ref should still be mutable here even though function deps are frozen in
9
// @enablePreserveExistingMemoizationGuarantees mode
10
ref.current.inner = event.target.value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-set-ref-nested-property-dont-preserve-memoization.expect.md
+3
-3
@@ -3,12 +3,12 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees:false
6
-import { useCallback, useRef } from "react";
6
+import {useCallback, useRef} from 'react';
7
8
function Component(props) {
9
- const ref = useRef({ inner: null });
9
+ const ref = useRef({inner: null});
10
11
- const onChange = useCallback((event) => {
11
+ const onChange = useCallback(event => {
12
// The ref should still be mutable here even though function deps are frozen in
13
// @enablePreserveExistingMemoizationGuarantees mode
14
ref.current.inner = event.target.value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-set-ref-nested-property-dont-preserve-memoization.js
+3
-3
@@ -1,10 +1,10 @@
1
// @enablePreserveExistingMemoizationGuarantees:false
2
-import { useCallback, useRef } from "react";
2
+import {useCallback, useRef} from 'react';
3
4
function Component(props) {
5
- const ref = useRef({ inner: null });
5
+ const ref = useRef({inner: null});
6
7
- const onChange = useCallback((event) => {
7
+ const onChange = useCallback(event => {
8
// The ref should still be mutable here even though function deps are frozen in
9
// @enablePreserveExistingMemoizationGuarantees mode
10
ref.current.inner = event.target.value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-set-ref-nested-property-preserve-memoization.expect.md
+3
-3
@@ -3,12 +3,12 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees
6
-import { useCallback, useRef } from "react";
6
+import {useCallback, useRef} from 'react';
7
8
function Component(props) {
9
- const ref = useRef({ inner: null });
9
+ const ref = useRef({inner: null});
10
11
- const onChange = useCallback((event) => {
11
+ const onChange = useCallback(event => {
12
// The ref should still be mutable here even though function deps are frozen in
13
// @enablePreserveExistingMemoizationGuarantees mode
14
ref.current.inner = event.target.value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-set-ref-nested-property-preserve-memoization.js
+3
-3
@@ -1,10 +1,10 @@
1
// @enablePreserveExistingMemoizationGuarantees
2
-import { useCallback, useRef } from "react";
2
+import {useCallback, useRef} from 'react';
3
4
function Component(props) {
5
- const ref = useRef({ inner: null });
5
+ const ref = useRef({inner: null});
6
7
- const onChange = useCallback((event) => {
7
+ const onChange = useCallback(event => {
8
// The ref should still be mutable here even though function deps are frozen in
9
// @enablePreserveExistingMemoizationGuarantees mode
10
ref.current.inner = event.target.value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-set-ref-nested-property.expect.md
+3
-3
@@ -2,14 +2,14 @@
2
## Input
3
4
```javascript
5
-import { useCallback, useRef } from "react";
5
+import {useCallback, useRef} from 'react';
6
7
// Identical to useCallback-set-ref-nested-property-preserve-memoization,
8
// but with a different set of compiler flags
9
function Component({}) {
10
- const ref = useRef({ inner: null });
10
+ const ref = useRef({inner: null});
11
12
- const onChange = useCallback((event) => {
12
+ const onChange = useCallback(event => {
13
// The ref should still be mutable here even though function deps are frozen in
14
// @enablePreserveExistingMemoizationGuarantees mode
15
ref.current.inner = event.target.value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-set-ref-nested-property.js
+3
-3
@@ -1,11 +1,11 @@
1
-import { useCallback, useRef } from "react";
1
+import {useCallback, useRef} from 'react';
2
3
// Identical to useCallback-set-ref-nested-property-preserve-memoization,
4
// but with a different set of compiler flags
5
function Component({}) {
6
- const ref = useRef({ inner: null });
6
+ const ref = useRef({inner: null});
7
8
- const onChange = useCallback((event) => {
8
+ const onChange = useCallback(event => {
9
// The ref should still be mutable here even though function deps are frozen in
10
// @enablePreserveExistingMemoizationGuarantees mode
11
ref.current.inner = event.target.value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-set-ref-value-dont-preserve-memoization.expect.md
+2
-2
@@ -3,12 +3,12 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees
6
-import { useCallback, useRef } from "react";
6
+import {useCallback, useRef} from 'react';
7
8
function Component(props) {
9
const ref = useRef(null);
10
11
- const onChange = useCallback((event) => {
11
+ const onChange = useCallback(event => {
12
// The ref should still be mutable here even though function deps are frozen in
13
// @enablePreserveExistingMemoizationGuarantees mode
14
ref.current = event.target.value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-set-ref-value-dont-preserve-memoization.js
+2
-2
@@ -1,10 +1,10 @@
1
// @enablePreserveExistingMemoizationGuarantees
2
-import { useCallback, useRef } from "react";
2
+import {useCallback, useRef} from 'react';
3
4
function Component(props) {
5
const ref = useRef(null);
6
7
- const onChange = useCallback((event) => {
7
+ const onChange = useCallback(event => {
8
// The ref should still be mutable here even though function deps are frozen in
9
// @enablePreserveExistingMemoizationGuarantees mode
10
ref.current = event.target.value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-set-ref-value-preserve-memoization.expect.md
+2
-2
@@ -3,12 +3,12 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees
6
-import { useCallback, useRef } from "react";
6
+import {useCallback, useRef} from 'react';
7
8
function Component(props) {
9
const ref = useRef(null);
10
11
- const onChange = useCallback((event) => {
11
+ const onChange = useCallback(event => {
12
// The ref should still be mutable here even though function deps are frozen in
13
// @enablePreserveExistingMemoizationGuarantees mode
14
ref.current = event.target.value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useCallback-set-ref-value-preserve-memoization.js
+2
-2
@@ -1,10 +1,10 @@
1
// @enablePreserveExistingMemoizationGuarantees
2
-import { useCallback, useRef } from "react";
2
+import {useCallback, useRef} from 'react';
3
4
function Component(props) {
5
const ref = useRef(null);
6
7
- const onChange = useCallback((event) => {
7
+ const onChange = useCallback(event => {
8
// The ref should still be mutable here even though function deps are frozen in
9
// @enablePreserveExistingMemoizationGuarantees mode
10
ref.current = event.target.value;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useContext-maybe-mutate-context-in-callback.expect.md
+5
-5
@@ -2,11 +2,11 @@
2
## Input
3
4
```javascript
5
-import * as React from "react";
6
-import { useContext } from "react";
7
-import { mutate } from "shared-runtime";
5
+import * as React from 'react';
6
+import {useContext} from 'react';
7
+import {mutate} from 'shared-runtime';
8
9
-const FooContext = React.createContext({ current: null });
9
+const FooContext = React.createContext({current: null});
10
11
function Component(props) {
12
const Foo = useContext(FooContext);
@@ -22,7 +22,7 @@ function Component(props) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: Component,
25
- params: [{ children: <div>Hello</div> }],
25
+ params: [{children: <div>Hello</div>}],
26
};
27
28
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useContext-maybe-mutate-context-in-callback.js
+5
-5
@@ -1,8 +1,8 @@
1
-import * as React from "react";
2
-import { useContext } from "react";
3
-import { mutate } from "shared-runtime";
1
+import * as React from 'react';
2
+import {useContext} from 'react';
3
+import {mutate} from 'shared-runtime';
4
5
-const FooContext = React.createContext({ current: null });
5
+const FooContext = React.createContext({current: null});
6
7
function Component(props) {
8
const Foo = useContext(FooContext);
@@ -18,5 +18,5 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: [{ children: <div>Hello</div> }],
21
+ params: [{children: <div>Hello</div>}],
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useContext-read-context-in-callback-if-condition.expect.md
+3
-3
@@ -2,10 +2,10 @@
2
## Input
3
4
```javascript
5
-import { createContext, useContext } from "react";
6
-import { Stringify } from "shared-runtime";
5
+import {createContext, useContext} from 'react';
6
+import {Stringify} from 'shared-runtime';
7
8
-const FooContext = createContext({ current: true });
8
+const FooContext = createContext({current: true});
9
10
function Component(props) {
11
const foo = useContext(FooContext);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useContext-read-context-in-callback-if-condition.js
+3
-3
@@ -1,7 +1,7 @@
1
-import { createContext, useContext } from "react";
2
-import { Stringify } from "shared-runtime";
1
+import {createContext, useContext} from 'react';
2
+import {Stringify} from 'shared-runtime';
3
4
-const FooContext = createContext({ current: true });
4
+const FooContext = createContext({current: true});
5
6
function Component(props) {
7
const foo = useContext(FooContext);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useContext-read-context-in-callback.expect.md
+3
-3
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { createContext, useContext } from "react";
5
+import {createContext, useContext} from 'react';
6
7
-const FooContext = createContext({ current: null });
7
+const FooContext = createContext({current: null});
8
9
function Component(props) {
10
const foo = useContext(FooContext);
@@ -17,7 +17,7 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ children: <div>Hello</div> }],
20
+ params: [{children: <div>Hello</div>}],
21
};
22
23
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useContext-read-context-in-callback.js
+3
-3
@@ -1,6 +1,6 @@
1
-import { createContext, useContext } from "react";
1
+import {createContext, useContext} from 'react';
2
3
-const FooContext = createContext({ current: null });
3
+const FooContext = createContext({current: null});
4
5
function Component(props) {
6
const foo = useContext(FooContext);
@@ -13,5 +13,5 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: [{ children: <div>Hello</div> }],
16
+ params: [{children: <div>Hello</div>}],
17
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-arg-memoized.expect.md
+1
-1
@@ -9,7 +9,7 @@ function Component(props) {
9
// onUpdate should be memoized even though it doesn't
10
// flow into the return value
11
const onUpdate = () => {
12
- dispatch({ kind: "update" });
12
+ dispatch({kind: 'update'});
13
};
14
15
useEffect(() => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-arg-memoized.js
+1
-1
@@ -5,7 +5,7 @@ function Component(props) {
5
// onUpdate should be memoized even though it doesn't
6
// flow into the return value
7
const onUpdate = () => {
8
- dispatch({ kind: "update" });
8
+ dispatch({kind: 'update'});
9
};
10
11
useEffect(() => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-external-mutate.expect.md
+2
-2
@@ -2,9 +2,9 @@
2
## Input
3
4
```javascript
5
-import { useEffect } from "react";
5
+import {useEffect} from 'react';
6
7
-let x = { a: 42 };
7
+let x = {a: 42};
8
9
function Component(props) {
10
useEffect(() => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-external-mutate.js
+2
-2
@@ -1,6 +1,6 @@
1
-import { useEffect } from "react";
1
+import {useEffect} from 'react';
2
3
-let x = { a: 42 };
3
+let x = {a: 42};
4
5
function Component(props) {
6
useEffect(() => {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-global-pruned.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useEffect } from "react";
5
+import {useEffect} from 'react';
6
7
function someGlobal() {}
8
function useFoo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-global-pruned.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { useEffect } from "react";
1
+import {useEffect} from 'react';
2
3
function someGlobal() {}
4
function useFoo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-namespace-pruned.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import * as React from "react";
5
+import * as React from 'react';
6
7
function someGlobal() {}
8
function useFoo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-namespace-pruned.js
+1
-1
@@ -1,4 +1,4 @@
1
-import * as React from "react";
1
+import * as React from 'react';
2
3
function someGlobal() {}
4
function useFoo() {
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-nested-lambdas.expect.md
+1
-1
@@ -14,7 +14,7 @@ function Component(props) {
14
}, [dispatch]);
15
16
useEffect(() => {
17
- const cleanup = GlobalEventEmitter.addListener("onInput", () => {
17
+ const cleanup = GlobalEventEmitter.addListener('onInput', () => {
18
if (item.value) {
19
exit();
20
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-nested-lambdas.js
+1
-1
@@ -10,7 +10,7 @@ function Component(props) {
10
}, [dispatch]);
11
12
useEffect(() => {
13
- const cleanup = GlobalEventEmitter.addListener("onInput", () => {
13
+ const cleanup = GlobalEventEmitter.addListener('onInput', () => {
14
if (item.value) {
15
exit();
16
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-snap-test.expect.md
+3
-3
@@ -2,12 +2,12 @@
2
## Input
3
4
```javascript
5
-import { useEffect, useState } from "react";
5
+import {useEffect, useState} from 'react';
6
7
function Component() {
8
- const [state, setState] = useState("hello");
8
+ const [state, setState] = useState('hello');
9
useEffect(() => {
10
- setState("goodbye");
10
+ setState('goodbye');
11
}, []);
12
13
return <div>{state}</div>;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useEffect-snap-test.js
+3
-3
@@ -1,9 +1,9 @@
1
-import { useEffect, useState } from "react";
1
+import {useEffect, useState} from 'react';
2
3
function Component() {
4
- const [state, setState] = useState("hello");
4
+ const [state, setState] = useState('hello');
5
useEffect(() => {
6
- setState("goodbye");
6
+ setState('goodbye');
7
}, []);
8
9
return <div>{state}</div>;
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-inlining-block-return.expect.md
+3
-3
@@ -5,7 +5,7 @@
5
function component(a, b) {
6
let x = useMemo(() => {
7
if (a) {
8
- return { b };
8
+ return {b};
9
}
10
}, [a, b]);
11
return x;
@@ -13,8 +13,8 @@ function component(a, b) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: component,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-inlining-block-return.js
+3
-3
@@ -1,7 +1,7 @@
1
function component(a, b) {
2
let x = useMemo(() => {
3
if (a) {
4
- return { b };
4
+ return {b};
5
}
6
}, [a, b]);
7
return x;
@@ -9,6 +9,6 @@ function component(a, b) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: component,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-inverted-if.expect.md
+2
-2
@@ -17,8 +17,8 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: ["TodoAdd"],
21
- isComponent: "TodoAdd",
20
+ params: ['TodoAdd'],
21
+ isComponent: 'TodoAdd',
22
};
23
24
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-inverted-if.js
+2
-2
@@ -13,6 +13,6 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-labeled-statement-unconditional-return.expect.md
+2
-2
@@ -13,8 +13,8 @@ function Component(props) {
13
14
export const FIXTURE_ENTRYPOINT = {
15
fn: Component,
16
- params: ["TodoAdd"],
17
- isComponent: "TodoAdd",
16
+ params: ['TodoAdd'],
17
+ isComponent: 'TodoAdd',
18
};
19
20
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-labeled-statement-unconditional-return.js
+2
-2
@@ -9,6 +9,6 @@ function Component(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-logical.expect.md
+2
-2
@@ -9,8 +9,8 @@ function Component(props) {
9
10
export const FIXTURE_ENTRYPOINT = {
11
fn: Component,
12
- params: ["TodoAdd"],
13
- isComponent: "TodoAdd",
12
+ params: ['TodoAdd'],
13
+ isComponent: 'TodoAdd',
14
};
15
16
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-logical.js
+2
-2
@@ -5,6 +5,6 @@ function Component(props) {
5
6
export const FIXTURE_ENTRYPOINT = {
7
fn: Component,
8
- params: ["TodoAdd"],
9
- isComponent: "TodoAdd",
8
+ params: ['TodoAdd'],
9
+ isComponent: 'TodoAdd',
10
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-mabye-modified-free-variable-dont-preserve-memoization-guarantees.expect.md
+3
-8
@@ -3,13 +3,8 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees:false
6
-import { useMemo } from "react";
7
-import {
8
- identity,
9
- makeObject_Primitives,
10
- mutate,
11
- useHook,
12
-} from "shared-runtime";
6
+import {useMemo} from 'react';
7
+import {identity, makeObject_Primitives, mutate, useHook} from 'shared-runtime';
8
9
function Component(props) {
10
// With the feature disabled these variables are inferred as being mutated inside the useMemo block
@@ -33,7 +28,7 @@ function Component(props) {
28
29
export const FIXTURE_ENTRYPOINT = {
30
fn: Component,
36
- params: [{ value: 42 }],
31
+ params: [{value: 42}],
32
};
33
34
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-mabye-modified-free-variable-dont-preserve-memoization-guarantees.js
+3
-8
@@ -1,11 +1,6 @@
1
// @enablePreserveExistingMemoizationGuarantees:false
2
-import { useMemo } from "react";
3
-import {
4
- identity,
5
- makeObject_Primitives,
6
- mutate,
7
- useHook,
8
-} from "shared-runtime";
2
+import {useMemo} from 'react';
3
+import {identity, makeObject_Primitives, mutate, useHook} from 'shared-runtime';
4
5
function Component(props) {
6
// With the feature disabled these variables are inferred as being mutated inside the useMemo block
@@ -29,5 +24,5 @@ function Component(props) {
24
25
export const FIXTURE_ENTRYPOINT = {
26
fn: Component,
32
- params: [{ value: 42 }],
27
+ params: [{value: 42}],
28
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-mabye-modified-free-variable-preserve-memoization-guarantees.expect.md
+3
-8
@@ -3,13 +3,8 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
7
-import {
8
- identity,
9
- makeObject_Primitives,
10
- mutate,
11
- useHook,
12
-} from "shared-runtime";
6
+import {useMemo} from 'react';
7
+import {identity, makeObject_Primitives, mutate, useHook} from 'shared-runtime';
8
9
function Component(props) {
10
// With the feature enabled these variables are inferred as frozen as of
@@ -38,7 +33,7 @@ function Component(props) {
33
34
export const FIXTURE_ENTRYPOINT = {
35
fn: Component,
41
- params: [{ value: 42 }],
36
+ params: [{value: 42}],
37
};
38
39
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-mabye-modified-free-variable-preserve-memoization-guarantees.js
+3
-8
@@ -1,11 +1,6 @@
1
// @enablePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
3
-import {
4
- identity,
5
- makeObject_Primitives,
6
- mutate,
7
- useHook,
8
-} from "shared-runtime";
2
+import {useMemo} from 'react';
3
+import {identity, makeObject_Primitives, mutate, useHook} from 'shared-runtime';
4
5
function Component(props) {
6
// With the feature enabled these variables are inferred as frozen as of
@@ -34,5 +29,5 @@ function Component(props) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: Component,
37
- params: [{ value: 42 }],
32
+ params: [{value: 42}],
33
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-maybe-modified-later-dont-preserve-memoization-guarantees.expect.md
+2
-2
@@ -3,8 +3,8 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees:false
6
-import { useMemo } from "react";
7
-import { identity, makeObject_Primitives, mutate } from "shared-runtime";
6
+import {useMemo} from 'react';
7
+import {identity, makeObject_Primitives, mutate} from 'shared-runtime';
8
9
function Component(props) {
10
const object = useMemo(() => makeObject_Primitives(), []);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-maybe-modified-later-dont-preserve-memoization-guarantees.js
+2
-2
@@ -1,6 +1,6 @@
1
// @enablePreserveExistingMemoizationGuarantees:false
2
-import { useMemo } from "react";
3
-import { identity, makeObject_Primitives, mutate } from "shared-runtime";
2
+import {useMemo} from 'react';
3
+import {identity, makeObject_Primitives, mutate} from 'shared-runtime';
4
5
function Component(props) {
6
const object = useMemo(() => makeObject_Primitives(), []);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-maybe-modified-later-preserve-memoization-guarantees.expect.md
+2
-2
@@ -3,8 +3,8 @@
3
4
```javascript
5
// @enablePreserveExistingMemoizationGuarantees
6
-import { useMemo } from "react";
7
-import { identity, makeObject_Primitives, mutate } from "shared-runtime";
6
+import {useMemo} from 'react';
7
+import {identity, makeObject_Primitives, mutate} from 'shared-runtime';
8
9
function Component(props) {
10
const object = useMemo(() => makeObject_Primitives(), []);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-maybe-modified-later-preserve-memoization-guarantees.js
+2
-2
@@ -1,6 +1,6 @@
1
// @enablePreserveExistingMemoizationGuarantees
2
-import { useMemo } from "react";
3
-import { identity, makeObject_Primitives, mutate } from "shared-runtime";
2
+import {useMemo} from 'react';
3
+import {identity, makeObject_Primitives, mutate} from 'shared-runtime';
4
5
function Component(props) {
6
const object = useMemo(() => makeObject_Primitives(), []);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-multiple-if-else.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useMemo } from "react";
5
+import {useMemo} from 'react';
6
7
function Component(props) {
8
const x = useMemo(() => {
@@ -21,7 +21,7 @@ function Component(props) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
- params: [{ a: 1, b: 2, cond2: false }],
24
+ params: [{a: 1, b: 2, cond2: false}],
25
};
26
27
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-multiple-if-else.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { useMemo } from "react";
1
+import {useMemo} from 'react';
2
3
function Component(props) {
4
const x = useMemo(() => {
@@ -17,5 +17,5 @@ function Component(props) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ a: 1, b: 2, cond2: false }],
20
+ params: [{a: 1, b: 2, cond2: false}],
21
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-named-function.expect.md
+2
-2
@@ -2,8 +2,8 @@
2
## Input
3
4
```javascript
5
-import { useMemo } from "react";
6
-import { makeArray } from "shared-runtime";
5
+import {useMemo} from 'react';
6
+import {makeArray} from 'shared-runtime';
7
8
function Component() {
9
const x = useMemo(makeArray, []);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-named-function.ts
+2
-2
@@ -1,5 +1,5 @@
1
-import { useMemo } from "react";
2
-import { makeArray } from "shared-runtime";
1
+import {useMemo} from 'react';
2
+import {makeArray} from 'shared-runtime';
3
4
function Component() {
5
const x = useMemo(makeArray, []);
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-nested-ifs.expect.md
+2
-2
@@ -14,8 +14,8 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: ["TodoAdd"],
18
- isComponent: "TodoAdd",
17
+ params: ['TodoAdd'],
18
+ isComponent: 'TodoAdd',
19
};
20
21
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-nested-ifs.js
+2
-2
@@ -10,6 +10,6 @@ function Component(props) {
10
11
export const FIXTURE_ENTRYPOINT = {
12
fn: Component,
13
- params: ["TodoAdd"],
14
- isComponent: "TodoAdd",
13
+ params: ['TodoAdd'],
14
+ isComponent: 'TodoAdd',
15
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-simple-preserved-nomemo.expect.md
+3
-3
@@ -3,16 +3,16 @@
3
4
```javascript
5
// @disableMemoizationForDebugging
6
-import { useMemo } from "react";
6
+import {useMemo} from 'react';
7
8
-function Component({ a }) {
8
+function Component({a}) {
9
let x = useMemo(() => [a], []);
10
return <div>{x}</div>;
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ a: 42 }],
15
+ params: [{a: 42}],
16
isComponent: true,
17
};
18
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-simple-preserved-nomemo.js
+3
-3
@@ -1,13 +1,13 @@
1
// @disableMemoizationForDebugging
2
-import { useMemo } from "react";
2
+import {useMemo} from 'react';
3
4
-function Component({ a }) {
4
+function Component({a}) {
5
let x = useMemo(() => [a], []);
6
return <div>{x}</div>;
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: [{ a: 42 }],
11
+ params: [{a: 42}],
12
isComponent: true,
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-simple-preserved.expect.md
+3
-3
@@ -3,16 +3,16 @@
3
4
```javascript
5
// @enablePreserveExistingManualUseMemo
6
-import { useMemo } from "react";
6
+import {useMemo} from 'react';
7
8
-function Component({ a }) {
8
+function Component({a}) {
9
let x = useMemo(() => [a], []);
10
return <div>{x}</div>;
11
}
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: Component,
15
- params: [{ a: 42 }],
15
+ params: [{a: 42}],
16
isComponent: true,
17
};
18
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-simple-preserved.js
+3
-3
@@ -1,13 +1,13 @@
1
// @enablePreserveExistingManualUseMemo
2
-import { useMemo } from "react";
2
+import {useMemo} from 'react';
3
4
-function Component({ a }) {
4
+function Component({a}) {
5
let x = useMemo(() => [a], []);
6
return <div>{x}</div>;
7
}
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: Component,
11
- params: [{ a: 42 }],
11
+ params: [{a: 42}],
12
isComponent: true,
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-switch-no-fallthrough.expect.md
+3
-3
@@ -5,7 +5,7 @@
5
function Component(props) {
6
const x = useMemo(() => {
7
switch (props.key) {
8
- case "key": {
8
+ case 'key': {
9
return props.value;
10
}
11
default: {
@@ -18,8 +18,8 @@ function Component(props) {
18
19
export const FIXTURE_ENTRYPOINT = {
20
fn: Component,
21
- params: ["TodoAdd"],
22
- isComponent: "TodoAdd",
21
+ params: ['TodoAdd'],
22
+ isComponent: 'TodoAdd',
23
};
24
25
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-switch-no-fallthrough.js
+3
-3
@@ -1,7 +1,7 @@
1
function Component(props) {
2
const x = useMemo(() => {
3
switch (props.key) {
4
- case "key": {
4
+ case 'key': {
5
return props.value;
6
}
7
default: {
@@ -14,6 +14,6 @@ function Component(props) {
14
15
export const FIXTURE_ENTRYPOINT = {
16
fn: Component,
17
- params: ["TodoAdd"],
18
- isComponent: "TodoAdd",
17
+ params: ['TodoAdd'],
18
+ isComponent: 'TodoAdd',
19
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-switch-return.expect.md
+6
-6
@@ -6,11 +6,11 @@ function Component(props) {
6
const x = useMemo(() => {
7
let y;
8
switch (props.switch) {
9
- case "foo": {
10
- return "foo";
9
+ case 'foo': {
10
+ return 'foo';
11
}
12
- case "bar": {
13
- y = "bar";
12
+ case 'bar': {
13
+ y = 'bar';
14
break;
15
}
16
default: {
@@ -24,8 +24,8 @@ function Component(props) {
24
25
export const FIXTURE_ENTRYPOINT = {
26
fn: Component,
27
- params: ["TodoAdd"],
28
- isComponent: "TodoAdd",
27
+ params: ['TodoAdd'],
28
+ isComponent: 'TodoAdd',
29
};
30
31
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useMemo-switch-return.js
+6
-6
@@ -2,11 +2,11 @@ function Component(props) {
2
const x = useMemo(() => {
3
let y;
4
switch (props.switch) {
5
- case "foo": {
6
- return "foo";
5
+ case 'foo': {
6
+ return 'foo';
7
}
8
- case "bar": {
9
- y = "bar";
8
+ case 'bar': {
9
+ y = 'bar';
10
break;
11
}
12
default: {
@@ -20,6 +20,6 @@ function Component(props) {
20
21
export const FIXTURE_ENTRYPOINT = {
22
fn: Component,
23
- params: ["TodoAdd"],
24
- isComponent: "TodoAdd",
23
+ params: ['TodoAdd'],
24
+ isComponent: 'TodoAdd',
25
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useReducer-returned-dispatcher-is-non-reactive.expect.md
+1
-1
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useReducer } from "react";
5
+import {useReducer} from 'react';
6
7
function f() {
8
const [state, dispatch] = useReducer();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useReducer-returned-dispatcher-is-non-reactive.js
+1
-1
@@ -1,4 +1,4 @@
1
-import { useReducer } from "react";
1
+import {useReducer} from 'react';
2
3
function f() {
4
const [state, dispatch] = useReducer();
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useState-and-other-hook-unpruned-dependency.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useState } from "react"; // @enableChangeDetectionForDebugging
5
+import {useState} from 'react'; // @enableChangeDetectionForDebugging
6
7
function useOther(x) {
8
return x;
@@ -21,7 +21,7 @@ function f(x) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
- params: [{ x: 42 }],
24
+ params: [{x: 42}],
25
isComponent: true,
26
};
27
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useState-and-other-hook-unpruned-dependency.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { useState } from "react"; // @enableChangeDetectionForDebugging
1
+import {useState} from 'react'; // @enableChangeDetectionForDebugging
2
3
function useOther(x) {
4
return x;
@@ -17,6 +17,6 @@ function f(x) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ x: 42 }],
20
+ params: [{x: 42}],
21
isComponent: true,
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useState-pruned-dependency-change-detect.expect.md
+1
-1
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @enableChangeDetectionForDebugging
6
-import { useState } from "react";
6
+import {useState} from 'react';
7
8
function Component(props) {
9
const [x, _] = useState(f(props.x));
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useState-pruned-dependency-change-detect.js
+1
-1
@@ -1,5 +1,5 @@
1
// @enableChangeDetectionForDebugging
2
-import { useState } from "react";
2
+import {useState} from 'react';
3
4
function Component(props) {
5
const [x, _] = useState(f(props.x));
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useState-unpruned-dependency.expect.md
+2
-2
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { useState } from "react"; // @enableChangeDetectionForDebugging
5
+import {useState} from 'react'; // @enableChangeDetectionForDebugging
6
7
function Component(props) {
8
const w = f(props.x);
@@ -21,7 +21,7 @@ function f(x) {
21
22
export const FIXTURE_ENTRYPOINT = {
23
fn: Component,
24
- params: [{ x: 42 }],
24
+ params: [{x: 42}],
25
isComponent: true,
26
};
27
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/useState-unpruned-dependency.js
+2
-2
@@ -1,4 +1,4 @@
1
-import { useState } from "react"; // @enableChangeDetectionForDebugging
1
+import {useState} from 'react'; // @enableChangeDetectionForDebugging
2
3
function Component(props) {
4
const w = f(props.x);
@@ -17,6 +17,6 @@ function f(x) {
17
18
export const FIXTURE_ENTRYPOINT = {
19
fn: Component,
20
- params: [{ x: 42 }],
20
+ params: [{x: 42}],
21
isComponent: true,
22
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/userspace-use-memo-cache.expect.md
+1
-2
@@ -13,8 +13,7 @@ function Component(props) {
13
<Button
14
onClick={() => {
15
setX(10 * y);
16
- }}
17
- ></Button>
16
+ }}></Button>
17
);
18
}
19
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/userspace-use-memo-cache.js
+1
-2
@@ -9,8 +9,7 @@ function Component(props) {
9
<Button
10
onClick={() => {
11
setX(10 * y);
12
- }}
13
- ></Button>
12
+ }}></Button>
13
);
14
}
15
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/validate-no-set-state-in-render-uncalled-function-with-mutable-range-is-valid.expect.md
+4
-4
@@ -11,19 +11,19 @@ function Component(props) {
11
// later. however, our validation uses direct aliasing to track function
12
// expressions which are invoked, and understands that this function isn't
13
// called during render:
14
- const onSubmit = (errorEvent) => {
14
+ const onSubmit = errorEvent => {
15
logEvent(errorEvent);
16
setCurrentStep(1);
17
};
18
19
switch (currentStep) {
20
case 0:
21
- return <OtherComponent data={{ foo: "bar" }} />;
21
+ return <OtherComponent data={{foo: 'bar'}} />;
22
case 1:
23
- return <OtherComponent data={{ foo: "joe" }} onSubmit={onSubmit} />;
23
+ return <OtherComponent data={{foo: 'joe'}} onSubmit={onSubmit} />;
24
default:
25
// 1. logEvent's mutable range is extended to this instruction
26
- logEvent("Invalid step");
26
+ logEvent('Invalid step');
27
return <OtherComponent data={null} />;
28
}
29
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/validate-no-set-state-in-render-uncalled-function-with-mutable-range-is-valid.js
+4
-4
@@ -7,19 +7,19 @@ function Component(props) {
7
// later. however, our validation uses direct aliasing to track function
8
// expressions which are invoked, and understands that this function isn't
9
// called during render:
10
- const onSubmit = (errorEvent) => {
10
+ const onSubmit = errorEvent => {
11
logEvent(errorEvent);
12
setCurrentStep(1);
13
};
14
15
switch (currentStep) {
16
case 0:
17
- return <OtherComponent data={{ foo: "bar" }} />;
17
+ return <OtherComponent data={{foo: 'bar'}} />;
18
case 1:
19
- return <OtherComponent data={{ foo: "joe" }} onSubmit={onSubmit} />;
19
+ return <OtherComponent data={{foo: 'joe'}} onSubmit={onSubmit} />;
20
default:
21
// 1. logEvent's mutable range is extended to this instruction
22
- logEvent("Invalid step");
22
+ logEvent('Invalid step');
23
return <OtherComponent data={null} />;
24
}
25
}
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/validate-no-set-state-in-render-unconditional-lambda-which-conditionally-sets-state-ok.expect.md
+2
-2
@@ -3,7 +3,7 @@
3
4
```javascript
5
// @validateNoSetStateInRender
6
-import { useState } from "react";
6
+import {useState} from 'react';
7
8
function Component(props) {
9
const [x, setX] = useState(0);
@@ -29,7 +29,7 @@ function Component(props) {
29
30
export const FIXTURE_ENTRYPOINT = {
31
fn: Component,
32
- params: [{ cond: false }],
32
+ params: [{cond: false}],
33
};
34
35
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/validate-no-set-state-in-render-unconditional-lambda-which-conditionally-sets-state-ok.js
+2
-2
@@ -1,5 +1,5 @@
1
// @validateNoSetStateInRender
2
-import { useState } from "react";
2
+import {useState} from 'react';
3
4
function Component(props) {
5
const [x, setX] = useState(0);
@@ -25,5 +25,5 @@ function Component(props) {
25
26
export const FIXTURE_ENTRYPOINT = {
27
fn: Component,
28
- params: [{ cond: false }],
28
+ params: [{cond: false}],
29
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/value-block-mutates-outer-value.expect.md
+4
-4
@@ -2,7 +2,7 @@
2
## Input
3
4
```javascript
5
-import { makeArray, useHook } from "shared-runtime";
5
+import {makeArray, useHook} from 'shared-runtime';
6
7
/**
8
* Here, the cond ? [...] : defaultList value block produces two
@@ -12,13 +12,13 @@ import { makeArray, useHook } from "shared-runtime";
12
* The same value block also mutates customList, so it must be
13
* merged with the scope producing customList
14
*/
15
-function Foo({ defaultList, cond }) {
15
+function Foo({defaultList, cond}) {
16
const comparator = (a, b) => a - b;
17
useHook();
18
const customList = makeArray(1, 5, 2);
19
useHook();
20
const result = cond
21
- ? [...customList.sort(comparator), { text: ["text"] }]
21
+ ? [...customList.sort(comparator), {text: ['text']}]
22
: defaultList;
23
24
return result;
@@ -26,7 +26,7 @@ function Foo({ defaultList, cond }) {
26
27
export const FIXTURE_ENTRYPOINT = {
28
fn: Foo,
29
- params: [{ defaultList: [2, 4], cond: true }],
29
+ params: [{defaultList: [2, 4], cond: true}],
30
};
31
32
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/value-block-mutates-outer-value.ts
+4
-4
@@ -1,4 +1,4 @@
1
-import { makeArray, useHook } from "shared-runtime";
1
+import {makeArray, useHook} from 'shared-runtime';
2
3
/**
4
* Here, the cond ? [...] : defaultList value block produces two
@@ -8,13 +8,13 @@ import { makeArray, useHook } from "shared-runtime";
8
* The same value block also mutates customList, so it must be
9
* merged with the scope producing customList
10
*/
11
-function Foo({ defaultList, cond }) {
11
+function Foo({defaultList, cond}) {
12
const comparator = (a, b) => a - b;
13
useHook();
14
const customList = makeArray(1, 5, 2);
15
useHook();
16
const result = cond
17
- ? [...customList.sort(comparator), { text: ["text"] }]
17
+ ? [...customList.sort(comparator), {text: ['text']}]
18
: defaultList;
19
20
return result;
@@ -22,5 +22,5 @@ function Foo({ defaultList, cond }) {
22
23
export const FIXTURE_ENTRYPOINT = {
24
fn: Foo,
25
- params: [{ defaultList: [2, 4], cond: true }],
25
+ params: [{defaultList: [2, 4], cond: true}],
26
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/while-break.expect.md
+2
-2
@@ -11,8 +11,8 @@ function foo(a, b) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
17
18
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/while-break.js
+2
-2
@@ -7,6 +7,6 @@ function foo(a, b) {
7
8
export const FIXTURE_ENTRYPOINT = {
9
fn: foo,
10
- params: ["TodoAdd"],
11
- isComponent: "TodoAdd",
10
+ params: ['TodoAdd'],
11
+ isComponent: 'TodoAdd',
12
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/while-conditional-continue.expect.md
+2
-2
@@ -15,8 +15,8 @@ function foo(a, b, c, d) {
15
16
export const FIXTURE_ENTRYPOINT = {
17
fn: foo,
18
- params: ["TodoAdd"],
19
- isComponent: "TodoAdd",
18
+ params: ['TodoAdd'],
19
+ isComponent: 'TodoAdd',
20
};
21
22
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/while-conditional-continue.js
+2
-2
@@ -11,6 +11,6 @@ function foo(a, b, c, d) {
11
12
export const FIXTURE_ENTRYPOINT = {
13
fn: foo,
14
- params: ["TodoAdd"],
15
- isComponent: "TodoAdd",
14
+ params: ['TodoAdd'],
15
+ isComponent: 'TodoAdd',
16
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/while-logical.expect.md
+2
-2
@@ -12,8 +12,8 @@ function foo(props) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: foo,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/while-logical.js
+2
-2
@@ -8,6 +8,6 @@ function foo(props) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: foo,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/while-property.expect.md
+2
-2
@@ -12,8 +12,8 @@ function foo(a, b) {
12
13
export const FIXTURE_ENTRYPOINT = {
14
fn: foo,
15
- params: ["TodoAdd"],
16
- isComponent: "TodoAdd",
15
+ params: ['TodoAdd'],
16
+ isComponent: 'TodoAdd',
17
};
18
19
```
compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/while-property.js
+2
-2
@@ -8,6 +8,6 @@ function foo(a, b) {
8
9
export const FIXTURE_ENTRYPOINT = {
10
fn: foo,
11
- params: ["TodoAdd"],
12
- isComponent: "TodoAdd",
11
+ params: ['TodoAdd'],
12
+ isComponent: 'TodoAdd',
13
};
compiler/packages/babel-plugin-react-compiler/src/__tests__/parseConfigPragma-test.ts
+4
-4
@@ -5,10 +5,10 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { parseConfigPragma, validateEnvironmentConfig } from "..";
8
+import {parseConfigPragma, validateEnvironmentConfig} from '..';
9
10
-describe("parseConfigPragma()", () => {
11
- it("parses flags in various forms", () => {
10
+describe('parseConfigPragma()', () => {
11
+ it('parses flags in various forms', () => {
12
const defaultConfig = validateEnvironmentConfig({});
13
14
// Validate defaults first to make sure that the parser is getting the value from the pragma,
@@ -18,7 +18,7 @@ describe("parseConfigPragma()", () => {
18
expect(defaultConfig.validateNoSetStateInRender).toBe(true);
19
20
const config = parseConfigPragma(
21
- "@enableUseTypeAnnotations @validateRefAccessDuringRender:true @validateNoSetStateInRender:false"
21
+ '@enableUseTypeAnnotations @validateRefAccessDuringRender:true @validateNoSetStateInRender:false',
22
);
23
expect(config).toEqual({
24
...defaultConfig,
compiler/packages/babel-plugin-react-compiler/src/__tests__/test-utils/validateNoUseBeforeDefine.ts
+12
-12
@@ -6,21 +6,21 @@
6
*/
7
8
// @ts-ignore-line
9
-import { Linter } from "../../../node_modules/eslint/lib/linter";
9
+import {Linter} from '../../../node_modules/eslint/lib/linter';
10
// @ts-ignore-line
11
-import * as HermesESLint from "hermes-eslint";
11
+import * as HermesESLint from 'hermes-eslint';
12
// @ts-ignore-line
13
-import { NoUseBeforeDefineRule } from "../..";
13
+import {NoUseBeforeDefineRule} from '../..';
14
15
const ESLINT_CONFIG: Linter.Config = {
16
- parser: "hermes-eslint",
16
+ parser: 'hermes-eslint',
17
parserOptions: {
18
- sourceType: "module",
18
+ sourceType: 'module',
19
},
20
rules: {
21
- "custom-no-use-before-define": [
22
- "error",
23
- { variables: false, functions: false },
21
+ 'custom-no-use-before-define': [
22
+ 'error',
23
+ {variables: false, functions: false},
24
],
25
},
26
};
@@ -32,10 +32,10 @@ const ESLINT_CONFIG: Linter.Config = {
32
* setting.
33
*/
34
export default function validateNoUseBeforeDefine(
35
- source: string
36
-): Array<{ line: number; column: number; message: string }> | null {
35
+ source: string,
36
+): Array<{line: number; column: number; message: string}> | null {
37
const linter = new Linter();
38
- linter.defineParser("hermes-eslint", HermesESLint);
39
- linter.defineRule("custom-no-use-before-define", NoUseBeforeDefineRule);
38
+ linter.defineParser('hermes-eslint', HermesESLint);
39
+ linter.defineRule('custom-no-use-before-define', NoUseBeforeDefineRule);
40
return linter.verify(source, ESLINT_CONFIG);
41
}
compiler/packages/babel-plugin-react-compiler/src/index.ts
+6
-6
@@ -5,14 +5,14 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-export { runBabelPluginReactCompiler } from "./Babel/RunReactCompilerBabelPlugin";
8
+export {runBabelPluginReactCompiler} from './Babel/RunReactCompilerBabelPlugin';
9
export {
10
CompilerError,
11
CompilerErrorDetail,
12
CompilerSuggestionOperation,
13
ErrorSeverity,
14
type CompilerErrorDetailOptions,
15
-} from "./CompilerError";
15
+} from './CompilerError';
16
export {
17
compileFn as compile,
18
compileProgram,
@@ -20,7 +20,7 @@ export {
20
run,
21
type CompilerPipelineValue,
22
type PluginOptions,
23
-} from "./Entrypoint";
23
+} from './Entrypoint';
24
export {
25
Effect,
26
ValueKind,
@@ -31,11 +31,11 @@ export {
31
type ExternalFunction,
32
type Hook,
33
type SourceLocation,
34
-} from "./HIR";
35
-export { printReactiveFunction } from "./ReactiveScopes";
34
+} from './HIR';
35
+export {printReactiveFunction} from './ReactiveScopes';
36
declare global {
37
let __DEV__: boolean | null | undefined;
38
}
39
40
-import BabelPluginReactCompiler from "./Babel/BabelPlugin";
40
+import BabelPluginReactCompiler from './Babel/BabelPlugin';
41
export default BabelPluginReactCompiler;
compiler/packages/eslint-plugin-react-compiler/__tests__/ReactCompilerRule-test.ts
+24
-24
@@ -5,18 +5,18 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { ErrorSeverity } from "babel-plugin-react-compiler/src";
9
-import { RuleTester as ESLintTester } from "eslint";
10
-import ReactCompilerRule from "../src/rules/ReactCompilerRule";
8
+import {ErrorSeverity} from 'babel-plugin-react-compiler/src';
9
+import {RuleTester as ESLintTester} from 'eslint';
10
+import ReactCompilerRule from '../src/rules/ReactCompilerRule';
11
12
/**
13
* A string template tag that removes padding from the left side of multi-line strings
14
* @param {Array} strings array of code strings (only one expected)
15
*/
16
function normalizeIndent(strings: TemplateStringsArray): string {
17
- const codeLines = strings[0].split("\n");
17
+ const codeLines = strings[0].split('\n');
18
const leftPadding = codeLines[1].match(/\s+/)![0];
19
- return codeLines.map((line) => line.slice(leftPadding.length)).join("\n");
19
+ return codeLines.map(line => line.slice(leftPadding.length)).join('\n');
20
}
21
22
type CompilerTestCases = {
@@ -27,7 +27,7 @@ type CompilerTestCases = {
27
const tests: CompilerTestCases = {
28
valid: [
29
{
30
- name: "Basic example",
30
+ name: 'Basic example',
31
code: normalizeIndent`
32
function foo(x, y) {
33
if (x) {
@@ -38,7 +38,7 @@ const tests: CompilerTestCases = {
38
`,
39
},
40
{
41
- name: "Violation with Flow suppression",
41
+ name: 'Violation with Flow suppression',
42
code: `
43
// Valid since error already suppressed with flow.
44
function useHookWithHook() {
@@ -50,7 +50,7 @@ const tests: CompilerTestCases = {
50
`,
51
},
52
{
53
- name: "Basic example with component syntax",
53
+ name: 'Basic example with component syntax',
54
code: normalizeIndent`
55
export default component HelloWorld(
56
text: string = 'Hello!',
@@ -61,7 +61,7 @@ const tests: CompilerTestCases = {
61
`,
62
},
63
{
64
- name: "Unsupported syntax",
64
+ name: 'Unsupported syntax',
65
code: normalizeIndent`
66
function foo(x) {
67
var y = 1;
@@ -71,7 +71,7 @@ const tests: CompilerTestCases = {
71
},
72
{
73
// OK because invariants are only meant for the compiler team's consumption
74
- name: "[Invariant] Defined after use",
74
+ name: '[Invariant] Defined after use',
75
code: normalizeIndent`
76
function Component(props) {
77
let y = function () {
@@ -95,7 +95,7 @@ const tests: CompilerTestCases = {
95
{
96
// TODO(gsn): Move this to invalid test suite, when we turn on
97
// validateRefAccessDuringRender validation
98
- name: "[InvalidInput] Ref access during render",
98
+ name: '[InvalidInput] Ref access during render',
99
code: normalizeIndent`
100
function Component(props) {
101
const ref = useRef(null);
@@ -107,8 +107,8 @@ const tests: CompilerTestCases = {
107
],
108
invalid: [
109
{
110
- name: "Reportable levels can be configured",
111
- options: [{ reportableLevels: new Set([ErrorSeverity.Todo]) }],
110
+ name: 'Reportable levels can be configured',
111
+ options: [{reportableLevels: new Set([ErrorSeverity.Todo])}],
112
code: normalizeIndent`
113
function Foo(x) {
114
var y = 1;
@@ -117,12 +117,12 @@ const tests: CompilerTestCases = {
117
errors: [
118
{
119
message:
120
- "(BuildHIR::lowerStatement) Handle var kinds in VariableDeclaration",
120
+ '(BuildHIR::lowerStatement) Handle var kinds in VariableDeclaration',
121
},
122
],
123
},
124
{
125
- name: "[InvalidReact] ESlint suppression",
125
+ name: '[InvalidReact] ESlint suppression',
126
// Indentation is intentionally weird so it doesn't add extra whitespace
127
code: normalizeIndent`
128
function Component(props) {
@@ -132,7 +132,7 @@ const tests: CompilerTestCases = {
132
errors: [
133
{
134
message:
135
- "React Compiler has skipped optimizing this component because one or more React ESLint rules were disabled. React Compiler only works when your components follow all the rules of React, disabling them may result in unexpected or incorrect behavior",
135
+ 'React Compiler has skipped optimizing this component because one or more React ESLint rules were disabled. React Compiler only works when your components follow all the rules of React, disabling them may result in unexpected or incorrect behavior',
136
suggestions: [
137
{
138
output: normalizeIndent`
@@ -150,7 +150,7 @@ const tests: CompilerTestCases = {
150
],
151
},
152
{
153
- name: "Multiple diagnostics are surfaced",
153
+ name: 'Multiple diagnostics are surfaced',
154
options: [
155
{
156
reportableLevels: new Set([
@@ -171,16 +171,16 @@ const tests: CompilerTestCases = {
171
errors: [
172
{
173
message:
174
- "(BuildHIR::lowerStatement) Handle var kinds in VariableDeclaration",
174
+ '(BuildHIR::lowerStatement) Handle var kinds in VariableDeclaration',
175
},
176
{
177
message:
178
- "Mutating component props or hook arguments is not allowed. Consider using a local variable instead",
178
+ 'Mutating component props or hook arguments is not allowed. Consider using a local variable instead',
179
},
180
],
181
},
182
{
183
- name: "Test experimental/unstable report all bailouts mode",
183
+ name: 'Test experimental/unstable report all bailouts mode',
184
options: [
185
{
186
reportableLevels: new Set([ErrorSeverity.InvalidReact]),
@@ -195,7 +195,7 @@ const tests: CompilerTestCases = {
195
errors: [
196
{
197
message:
198
- "[ReactCompilerBailout] (BuildHIR::lowerStatement) Handle var kinds in VariableDeclaration (@:3:2)",
198
+ '[ReactCompilerBailout] (BuildHIR::lowerStatement) Handle var kinds in VariableDeclaration (@:3:2)',
199
},
200
],
201
},
@@ -203,11 +203,11 @@ const tests: CompilerTestCases = {
203
};
204
205
const eslintTester = new ESLintTester({
206
- parser: require.resolve("hermes-eslint"),
206
+ parser: require.resolve('hermes-eslint'),
207
parserOptions: {
208
ecmaVersion: 2015,
209
- sourceType: "module",
209
+ sourceType: 'module',
210
enableExperimentalComponentSyntax: true,
211
},
212
});
213
-eslintTester.run("react-compiler", ReactCompilerRule, tests);
213
+eslintTester.run('react-compiler', ReactCompilerRule, tests);
compiler/packages/eslint-plugin-react-compiler/__tests__/ReactCompilerRuleTypescript-test.ts
+12
-12
@@ -5,17 +5,17 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { RuleTester } from "eslint";
9
-import ReactCompilerRule from "../src/rules/ReactCompilerRule";
8
+import {RuleTester} from 'eslint';
9
+import ReactCompilerRule from '../src/rules/ReactCompilerRule';
10
11
/**
12
* A string template tag that removes padding from the left side of multi-line strings
13
* @param {Array} strings array of code strings (only one expected)
14
*/
15
function normalizeIndent(strings: TemplateStringsArray): string {
16
- const codeLines = strings[0].split("\n");
16
+ const codeLines = strings[0].split('\n');
17
const leftPadding = codeLines[1].match(/\s+/)[0];
18
- return codeLines.map((line) => line.slice(leftPadding.length)).join("\n");
18
+ return codeLines.map(line => line.slice(leftPadding.length)).join('\n');
19
}
20
21
type CompilerTestCases = {
@@ -26,8 +26,8 @@ type CompilerTestCases = {
26
const tests: CompilerTestCases = {
27
valid: [
28
{
29
- name: "Basic example",
30
- filename: "test.tsx",
29
+ name: 'Basic example',
30
+ filename: 'test.tsx',
31
code: normalizeIndent`
32
function Button(props) {
33
return null;
@@ -35,8 +35,8 @@ const tests: CompilerTestCases = {
35
`,
36
},
37
{
38
- name: "Repro for hooks as normal values",
39
- filename: "test.tsx",
38
+ name: 'Repro for hooks as normal values',
39
+ filename: 'test.tsx',
40
code: normalizeIndent`
41
function Button(props) {
42
const scrollview = React.useRef<ScrollView>(null);
@@ -47,8 +47,8 @@ const tests: CompilerTestCases = {
47
],
48
invalid: [
49
{
50
- name: "Mutating useState value",
51
- filename: "test.tsx",
50
+ name: 'Mutating useState value',
51
+ filename: 'test.tsx',
52
code: `
53
import { useState } from 'react';
54
function Component(props) {
@@ -71,6 +71,6 @@ const tests: CompilerTestCases = {
71
};
72
73
const eslintTester = new RuleTester({
74
- parser: require.resolve("@typescript-eslint/parser"),
74
+ parser: require.resolve('@typescript-eslint/parser'),
75
});
76
-eslintTester.run("react-compiler", ReactCompilerRule, tests);
76
+eslintTester.run('react-compiler', ReactCompilerRule, tests);
compiler/packages/eslint-plugin-react-compiler/babel.config.js
+4
-4
@@ -6,10 +6,10 @@
6
*/
7
8
module.exports = {
9
- presets: ["@babel/preset-env", "@babel/preset-typescript"],
9
+ presets: ['@babel/preset-env', '@babel/preset-typescript'],
10
plugins: [
11
- ["@babel/plugin-transform-private-property-in-object", { loose: true }],
12
- ["@babel/plugin-transform-class-properties", { loose: true }],
13
- ["@babel/plugin-transform-private-methods", { loose: true }],
11
+ ['@babel/plugin-transform-private-property-in-object', {loose: true}],
12
+ ['@babel/plugin-transform-class-properties', {loose: true}],
13
+ ['@babel/plugin-transform-private-methods', {loose: true}],
14
],
15
};
compiler/packages/eslint-plugin-react-compiler/rollup.config.js
+19
-19
@@ -5,29 +5,29 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import typescript from "@rollup/plugin-typescript";
9
-import { nodeResolve } from "@rollup/plugin-node-resolve";
10
-import commonjs from "@rollup/plugin-commonjs";
11
-import json from "@rollup/plugin-json";
12
-import path from "path";
13
-import process from "process";
14
-import terser from "@rollup/plugin-terser";
15
-import prettier from "rollup-plugin-prettier";
16
-import banner2 from "rollup-plugin-banner2";
8
+import typescript from '@rollup/plugin-typescript';
9
+import {nodeResolve} from '@rollup/plugin-node-resolve';
10
+import commonjs from '@rollup/plugin-commonjs';
11
+import json from '@rollup/plugin-json';
12
+import path from 'path';
13
+import process from 'process';
14
+import terser from '@rollup/plugin-terser';
15
+import prettier from 'rollup-plugin-prettier';
16
+import banner2 from 'rollup-plugin-banner2';
17
18
const NO_INLINE = new Set([
19
- "@babel/core",
20
- "@babel/plugin-proposal-private-methods",
21
- "hermes-parser",
22
- "zod",
23
- "zod-validation-error",
19
+ '@babel/core',
20
+ '@babel/plugin-proposal-private-methods',
21
+ 'hermes-parser',
22
+ 'zod',
23
+ 'zod-validation-error',
24
]);
25
26
const DEV_ROLLUP_CONFIG = {
27
- input: "src/index.ts",
27
+ input: 'src/index.ts',
28
output: {
29
- file: "dist/index.js",
30
- format: "cjs",
29
+ file: 'dist/index.js',
30
+ format: 'cjs',
31
sourcemap: false,
32
},
33
treeshake: {
@@ -42,8 +42,8 @@ const DEV_ROLLUP_CONFIG = {
42
json(),
43
nodeResolve({
44
preferBuiltins: true,
45
- resolveOnly: (module) => NO_INLINE.has(module) === false,
46
- rootDir: path.join(process.cwd(), ".."),
45
+ resolveOnly: module => NO_INLINE.has(module) === false,
46
+ rootDir: path.join(process.cwd(), '..'),
47
}),
48
commonjs(),
49
terser({
compiler/packages/eslint-plugin-react-compiler/src/index.ts
+2
-2
@@ -5,10 +5,10 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import ReactCompilerRule from "./rules/ReactCompilerRule";
8
+import ReactCompilerRule from './rules/ReactCompilerRule';
9
10
module.exports = {
11
rules: {
12
- "react-compiler": ReactCompilerRule,
12
+ 'react-compiler': ReactCompilerRule,
13
},
14
};
compiler/packages/eslint-plugin-react-compiler/src/rules/ReactCompilerRule.ts
+42
-42
@@ -5,10 +5,10 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { transformFromAstSync } from "@babel/core";
8
+import {transformFromAstSync} from '@babel/core';
9
// @ts-expect-error: no types available
10
-import PluginProposalPrivateMethods from "@babel/plugin-proposal-private-methods";
11
-import type { SourceLocation as BabelSourceLocation } from "@babel/types";
10
+import PluginProposalPrivateMethods from '@babel/plugin-proposal-private-methods';
11
+import type {SourceLocation as BabelSourceLocation} from '@babel/types';
12
import BabelPluginReactCompiler, {
13
CompilerErrorDetailOptions,
14
CompilerSuggestionOperation,
@@ -16,12 +16,12 @@ import BabelPluginReactCompiler, {
16
parsePluginOptions,
17
validateEnvironmentConfig,
18
type PluginOptions,
19
-} from "babel-plugin-react-compiler/src";
20
-import { Logger } from "babel-plugin-react-compiler/src/Entrypoint";
21
-import type { Rule } from "eslint";
22
-import * as HermesParser from "hermes-parser";
19
+} from 'babel-plugin-react-compiler/src';
20
+import {Logger} from 'babel-plugin-react-compiler/src/Entrypoint';
21
+import type {Rule} from 'eslint';
22
+import * as HermesParser from 'hermes-parser';
23
24
-type CompilerErrorDetailWithLoc = Omit<CompilerErrorDetailOptions, "loc"> & {
24
+type CompilerErrorDetailWithLoc = Omit<CompilerErrorDetailOptions, 'loc'> & {
25
loc: BabelSourceLocation;
26
};
27
@@ -36,17 +36,17 @@ const DEFAULT_REPORTABLE_LEVELS = new Set([
36
let reportableLevels = DEFAULT_REPORTABLE_LEVELS;
37
38
function isReportableDiagnostic(
39
- detail: CompilerErrorDetailOptions
39
+ detail: CompilerErrorDetailOptions,
40
): detail is CompilerErrorDetailWithLoc {
41
return (
42
reportableLevels.has(detail.severity) &&
43
detail.loc != null &&
44
- typeof detail.loc !== "symbol"
44
+ typeof detail.loc !== 'symbol'
45
);
46
}
47
48
function makeSuggestions(
49
- detail: CompilerErrorDetailOptions
49
+ detail: CompilerErrorDetailOptions,
50
): Array<Rule.SuggestionReportDescriptor> {
51
let suggest: Array<Rule.SuggestionReportDescriptor> = [];
52
if (Array.isArray(detail.suggestions)) {
@@ -58,7 +58,7 @@ function makeSuggestions(
58
fix(fixer) {
59
return fixer.insertTextBeforeRange(
60
suggestion.range,
61
- suggestion.text
61
+ suggestion.text,
62
);
63
},
64
});
@@ -69,7 +69,7 @@ function makeSuggestions(
69
fix(fixer) {
70
return fixer.insertTextAfterRange(
71
suggestion.range,
72
- suggestion.text
72
+ suggestion.text,
73
);
74
},
75
});
@@ -91,7 +91,7 @@ function makeSuggestions(
91
});
92
break;
93
default:
94
- assertExhaustive(suggestion, "Unhandled suggestion operation");
94
+ assertExhaustive(suggestion, 'Unhandled suggestion operation');
95
}
96
}
97
}
@@ -100,21 +100,21 @@ function makeSuggestions(
100
101
const COMPILER_OPTIONS: Partial<PluginOptions> = {
102
noEmit: true,
103
- compilationMode: "infer",
104
- panicThreshold: "none",
103
+ compilationMode: 'infer',
104
+ panicThreshold: 'none',
105
};
106
107
const rule: Rule.RuleModule = {
108
meta: {
109
- type: "problem",
109
+ type: 'problem',
110
docs: {
111
- description: "Surfaces diagnostics from React Forget",
111
+ description: 'Surfaces diagnostics from React Forget',
112
recommended: true,
113
},
114
- fixable: "code",
114
+ fixable: 'code',
115
hasSuggestions: true,
116
// validation is done at runtime with zod
117
- schema: [{ type: "object", additionalProperties: true }],
117
+ schema: [{type: 'object', additionalProperties: true}],
118
},
119
create(context: Rule.RuleContext) {
120
// Compat with older versions of eslint
@@ -122,10 +122,10 @@ const rule: Rule.RuleModule = {
122
const filename = context.filename ?? context.getFilename();
123
const userOpts = context.options[0] ?? {};
124
if (
125
- userOpts["reportableLevels"] != null &&
126
- userOpts["reportableLevels"] instanceof Set
125
+ userOpts['reportableLevels'] != null &&
126
+ userOpts['reportableLevels'] instanceof Set
127
) {
128
- reportableLevels = userOpts["reportableLevels"];
128
+ reportableLevels = userOpts['reportableLevels'];
129
} else {
130
reportableLevels = DEFAULT_REPORTABLE_LEVELS;
131
}
@@ -138,11 +138,11 @@ const rule: Rule.RuleModule = {
138
*/
139
let __unstable_donotuse_reportAllBailouts: boolean = false;
140
if (
141
- userOpts["__unstable_donotuse_reportAllBailouts"] != null &&
142
- typeof userOpts["__unstable_donotuse_reportAllBailouts"] === "boolean"
141
+ userOpts['__unstable_donotuse_reportAllBailouts'] != null &&
142
+ typeof userOpts['__unstable_donotuse_reportAllBailouts'] === 'boolean'
143
) {
144
__unstable_donotuse_reportAllBailouts =
145
- userOpts["__unstable_donotuse_reportAllBailouts"];
145
+ userOpts['__unstable_donotuse_reportAllBailouts'];
146
}
147
148
const options: PluginOptions = {
@@ -153,14 +153,14 @@ const rule: Rule.RuleModule = {
153
options.logger = {
154
logEvent: (filename, event): void => {
155
userLogger?.logEvent(filename, event);
156
- if (event.kind === "CompileError") {
156
+ if (event.kind === 'CompileError') {
157
const detail = event.detail;
158
const suggest = makeSuggestions(detail);
159
if (__unstable_donotuse_reportAllBailouts && event.fnLoc != null) {
160
const locStr =
161
- detail.loc != null && typeof detail.loc !== "symbol"
161
+ detail.loc != null && typeof detail.loc !== 'symbol'
162
? ` (@:${detail.loc.start.line}:${detail.loc.start.column})`
163
- : "";
163
+ : '';
164
context.report({
165
message: `[ReactCompilerBailout] ${detail.reason}${locStr}`,
166
loc: event.fnLoc,
@@ -171,12 +171,12 @@ const rule: Rule.RuleModule = {
171
if (!isReportableDiagnostic(detail)) {
172
return;
173
}
174
- if (hasFlowSuppression(detail.loc, "react-rule-hook")) {
174
+ if (hasFlowSuppression(detail.loc, 'react-rule-hook')) {
175
// If Flow already caught this error, we don't need to report it again.
176
return;
177
}
178
const loc =
179
- detail.loc == null || typeof detail.loc == "symbol"
179
+ detail.loc == null || typeof detail.loc == 'symbol'
180
? event.fnLoc
181
: detail.loc;
182
if (loc != null) {
@@ -192,20 +192,20 @@ const rule: Rule.RuleModule = {
192
193
try {
194
options.environment = validateEnvironmentConfig(
195
- options.environment ?? {}
195
+ options.environment ?? {},
196
);
197
} catch (err) {
198
- options.logger?.logEvent("", err);
198
+ options.logger?.logEvent('', err);
199
}
200
201
function hasFlowSuppression(
202
nodeLoc: BabelSourceLocation,
203
- suppression: string
203
+ suppression: string,
204
): boolean {
205
const sourceCode = context.getSourceCode();
206
const comments = sourceCode.getAllComments();
207
const flowSuppressionRegex = new RegExp(
208
- "\\$FlowFixMe\\[" + suppression + "\\]"
208
+ '\\$FlowFixMe\\[' + suppression + '\\]',
209
);
210
for (const commentNode of comments) {
211
if (
@@ -219,13 +219,13 @@ const rule: Rule.RuleModule = {
219
}
220
221
let babelAST;
222
- if (filename.endsWith(".tsx") || filename.endsWith(".ts")) {
222
+ if (filename.endsWith('.tsx') || filename.endsWith('.ts')) {
223
try {
224
- const { parse: babelParse } = require("@babel/parser");
224
+ const {parse: babelParse} = require('@babel/parser');
225
babelAST = babelParse(sourceCode, {
226
filename,
227
- sourceType: "unambiguous",
228
- plugins: ["typescript", "jsx"],
227
+ sourceType: 'unambiguous',
228
+ plugins: ['typescript', 'jsx'],
229
});
230
} catch {
231
/* empty */
@@ -236,7 +236,7 @@ const rule: Rule.RuleModule = {
236
babel: true,
237
enableExperimentalComponentSyntax: true,
238
sourceFilename: filename,
239
- sourceType: "module",
239
+ sourceType: 'module',
240
});
241
} catch {
242
/* empty */
@@ -250,10 +250,10 @@ const rule: Rule.RuleModule = {
250
highlightCode: false,
251
retainLines: true,
252
plugins: [
253
- [PluginProposalPrivateMethods, { loose: true }],
253
+ [PluginProposalPrivateMethods, {loose: true}],
254
[BabelPluginReactCompiler, options],
255
],
256
- sourceType: "module",
256
+ sourceType: 'module',
257
configFile: false,
258
babelrc: false,
259
});
compiler/packages/make-read-only-util/jest.config.js
+2
-2
@@ -7,6 +7,6 @@
7
8
/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */
9
module.exports = {
10
- preset: "ts-jest",
11
- testEnvironment: "node",
10
+ preset: 'ts-jest',
11
+ testEnvironment: 'node',
12
};
compiler/packages/make-read-only-util/src/__tests__/makeReadOnly-test.ts
+68
-68
@@ -5,9 +5,9 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import buildMakeReadOnly from "../makeReadOnly";
8
+import buildMakeReadOnly from '../makeReadOnly';
9
10
-describe("makeReadOnly", () => {
10
+describe('makeReadOnly', () => {
11
let logger: jest.Func;
12
let makeReadOnly: <T>(value: T, source: string) => T;
13
@@ -16,110 +16,110 @@ describe("makeReadOnly", () => {
16
makeReadOnly = buildMakeReadOnly(logger, []);
17
});
18
19
- describe("Tracking mutations", () => {
20
- it("can be called with all primitives", () => {
19
+ describe('Tracking mutations', () => {
20
+ it('can be called with all primitives', () => {
21
const a = 5;
22
const b = true;
23
const c = null;
24
- expect(makeReadOnly(a, "test1")).toBe(a);
25
- expect(makeReadOnly(b, "test1")).toBe(b);
26
- expect(makeReadOnly(c, "test1")).toBe(c);
24
+ expect(makeReadOnly(a, 'test1')).toBe(a);
25
+ expect(makeReadOnly(b, 'test1')).toBe(b);
26
+ expect(makeReadOnly(c, 'test1')).toBe(c);
27
});
28
29
- it("retains referential equality", () => {
29
+ it('retains referential equality', () => {
30
const valA = {};
31
- const valB = { a: valA, _: valA };
32
- const o = { a: valA, b: valB, c: "c" };
33
- expect(makeReadOnly(o, "test2")).toBe(o);
34
- expect(makeReadOnly(o.a, "test2")).toBe(valA);
35
- expect(makeReadOnly(o.b, "test2")).toBe(valB);
36
- expect(makeReadOnly(o.b.a, "test2")).toBe(valA);
37
- expect(makeReadOnly(o.b._, "test2")).toBe(valA);
38
- expect(makeReadOnly(o.c, "test2")).toBe("c");
31
+ const valB = {a: valA, _: valA};
32
+ const o = {a: valA, b: valB, c: 'c'};
33
+ expect(makeReadOnly(o, 'test2')).toBe(o);
34
+ expect(makeReadOnly(o.a, 'test2')).toBe(valA);
35
+ expect(makeReadOnly(o.b, 'test2')).toBe(valB);
36
+ expect(makeReadOnly(o.b.a, 'test2')).toBe(valA);
37
+ expect(makeReadOnly(o.b._, 'test2')).toBe(valA);
38
+ expect(makeReadOnly(o.c, 'test2')).toBe('c');
39
});
40
41
- it("deals with cyclic references", () => {
41
+ it('deals with cyclic references', () => {
42
const o: any = {};
43
o.self_ref = o;
44
- expect(makeReadOnly(o, "test3")).toBe(o);
45
- expect(makeReadOnly(o.self_ref, "test3")).toBe(o);
44
+ expect(makeReadOnly(o, 'test3')).toBe(o);
45
+ expect(makeReadOnly(o.self_ref, 'test3')).toBe(o);
46
});
47
- it("logs direct interior mutability", () => {
48
- const o = { a: 0 };
49
- makeReadOnly(o, "test4");
47
+ it('logs direct interior mutability', () => {
48
+ const o = {a: 0};
49
+ makeReadOnly(o, 'test4');
50
o.a = 42;
51
- expect(logger).toBeCalledWith("FORGET_MUTATE_IMMUT", "test4", "a", 42);
51
+ expect(logger).toBeCalledWith('FORGET_MUTATE_IMMUT', 'test4', 'a', 42);
52
});
53
54
- it("tracks changes to known RO properties", () => {
55
- const o: any = { a: {} };
56
- makeReadOnly(o, "test5");
54
+ it('tracks changes to known RO properties', () => {
55
+ const o: any = {a: {}};
56
+ makeReadOnly(o, 'test5');
57
o.a = 42;
58
- expect(logger).toBeCalledWith("FORGET_MUTATE_IMMUT", "test5", "a", 42);
58
+ expect(logger).toBeCalledWith('FORGET_MUTATE_IMMUT', 'test5', 'a', 42);
59
expect(o.a).toBe(42);
60
- const newVal = { x: 0 };
60
+ const newVal = {x: 0};
61
o.a = newVal;
62
expect(logger).toBeCalledWith(
63
- "FORGET_MUTATE_IMMUT",
64
- "test5",
65
- "a",
66
- newVal
63
+ 'FORGET_MUTATE_IMMUT',
64
+ 'test5',
65
+ 'a',
66
+ newVal,
67
);
68
expect(o.a).toBe(newVal);
69
});
70
71
- it("logs aliased mutations", () => {
72
- const o: any = { a: { x: 4 } };
71
+ it('logs aliased mutations', () => {
72
+ const o: any = {a: {x: 4}};
73
74
const alias = o;
75
- makeReadOnly(o, "test6");
75
+ makeReadOnly(o, 'test6');
76
const newVal = {};
77
alias.a = newVal;
78
expect(logger).toBeCalledWith(
79
- "FORGET_MUTATE_IMMUT",
80
- "test6",
81
- "a",
82
- newVal
79
+ 'FORGET_MUTATE_IMMUT',
80
+ 'test6',
81
+ 'a',
82
+ newVal,
83
);
84
expect(o.a).toBe(newVal);
85
});
86
87
- it("logs transitive interior mutability", () => {
88
- const o: any = { a: { x: 0 } };
89
- makeReadOnly(o, "test7");
87
+ it('logs transitive interior mutability', () => {
88
+ const o: any = {a: {x: 0}};
89
+ makeReadOnly(o, 'test7');
90
o.a.x = 42;
91
- expect(logger).toBeCalledWith("FORGET_MUTATE_IMMUT", "test7", "x", 42);
91
+ expect(logger).toBeCalledWith('FORGET_MUTATE_IMMUT', 'test7', 'x', 42);
92
});
93
94
- describe("todo", () => {
95
- it("does not track newly added or deleted vals if makeReadOnly is only called once", () => {
94
+ describe('todo', () => {
95
+ it('does not track newly added or deleted vals if makeReadOnly is only called once', () => {
96
// this is a limitation of the current "proxy" approach,
97
// which overwrites object properties with getters and setters
98
- const x: any = { a: {} };
99
- makeReadOnly(x, "test8");
98
+ const x: any = {a: {}};
99
+ makeReadOnly(x, 'test8');
100
101
delete x.a;
102
x.b = 0;
103
expect(logger).toBeCalledTimes(0);
104
});
105
- it("does not log aliased indirect mutations", () => {
105
+ it('does not log aliased indirect mutations', () => {
106
// this could be easily implemented by making caching eager
107
- const innerObj = { x: 0 };
108
- const o = { a: innerObj };
109
- makeReadOnly(o, "test9");
107
+ const innerObj = {x: 0};
108
+ const o = {a: innerObj};
109
+ makeReadOnly(o, 'test9');
110
innerObj.x = 42;
111
expect(o.a.x).toBe(42);
112
113
- const o1 = { a: { x: 0 } };
113
+ const o1 = {a: {x: 0}};
114
const innerObj1 = o1.a;
115
- makeReadOnly(o1, "test9");
115
+ makeReadOnly(o1, 'test9');
116
innerObj1.x = 42;
117
118
expect(o1.a.x).toBe(42);
119
expect(logger).toBeCalledTimes(0);
120
});
121
122
- it("does not track objects with getter/setters", () => {
122
+ it('does not track objects with getter/setters', () => {
123
let backedX: string | null = null;
124
const o = {
125
set val(val: string | null) {
@@ -129,29 +129,29 @@ describe("makeReadOnly", () => {
129
return backedX;
130
},
131
};
132
- expect(makeReadOnly(o, "test10")).toBe(o);
133
- expect(makeReadOnly(o.val, "test10")).toBe(null);
132
+ expect(makeReadOnly(o, 'test10')).toBe(o);
133
+ expect(makeReadOnly(o.val, 'test10')).toBe(null);
134
135
- o.val = "40";
135
+ o.val = '40';
136
expect(logger).toBeCalledTimes(0);
137
});
138
});
139
});
140
141
- describe("Tracking adding or deleting properties", () => {
142
- it("tracks new properties added between calls to makeReadOnly", () => {
141
+ describe('Tracking adding or deleting properties', () => {
142
+ it('tracks new properties added between calls to makeReadOnly', () => {
143
const o: any = {};
144
- makeReadOnly(o, "test11");
145
- o.a = "new value";
146
- makeReadOnly(o, "test11");
147
- expect(logger).toBeCalledWith("FORGET_ADD_PROP_IMMUT", "test11", "a");
144
+ makeReadOnly(o, 'test11');
145
+ o.a = 'new value';
146
+ makeReadOnly(o, 'test11');
147
+ expect(logger).toBeCalledWith('FORGET_ADD_PROP_IMMUT', 'test11', 'a');
148
});
149
- it("tracks properties deleted between calls to makeReadOnly", () => {
150
- const o: any = { a: 0 };
151
- makeReadOnly(o, "test12");
149
+ it('tracks properties deleted between calls to makeReadOnly', () => {
150
+ const o: any = {a: 0};
151
+ makeReadOnly(o, 'test12');
152
delete o.a;
153
- makeReadOnly(o, "test12");
154
- expect(logger).toBeCalledWith("FORGET_DELETE_PROP_IMMUT", "test12", "a");
153
+ makeReadOnly(o, 'test12');
154
+ expect(logger).toBeCalledWith('FORGET_DELETE_PROP_IMMUT', 'test12', 'a');
155
});
156
157
// it("tracks properties deleted and re-added between calls to makeReadOnly", () => {
compiler/packages/make-read-only-util/src/makeReadOnly.ts
+24
-24
@@ -5,18 +5,18 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-"use strict";
8
+'use strict';
9
10
type ROViolationType =
11
- | "FORGET_MUTATE_IMMUT"
12
- | "FORGET_DELETE_PROP_IMMUT"
13
- | "FORGET_CHANGE_PROP_IMMUT"
14
- | "FORGET_ADD_PROP_IMMUT";
11
+ | 'FORGET_MUTATE_IMMUT'
12
+ | 'FORGET_DELETE_PROP_IMMUT'
13
+ | 'FORGET_CHANGE_PROP_IMMUT'
14
+ | 'FORGET_ADD_PROP_IMMUT';
15
type ROViolationLogger = (
16
violation: ROViolationType,
17
source: string,
18
key: string,
19
- value?: any
19
+ value?: any,
20
) => void;
21
22
/**
@@ -38,21 +38,21 @@ function isWriteable(desc: PropertyDescriptor) {
38
39
function getOrInsertDefault(
40
m: SavedROObjects,
41
- k: object
42
-): { existed: boolean; entry: SavedROObject } {
41
+ k: object,
42
+): {existed: boolean; entry: SavedROObject} {
43
const entry = m.get(k);
44
if (entry) {
45
- return { existed: true, entry };
45
+ return {existed: true, entry};
46
} else {
47
const newEntry: SavedROObject = new Map();
48
m.set(k, newEntry);
49
- return { existed: false, entry: newEntry };
49
+ return {existed: false, entry: newEntry};
50
}
51
}
52
53
function buildMakeReadOnly(
54
logger: ROViolationLogger,
55
- skippedClasses: string[]
55
+ skippedClasses: string[],
56
): <T>(val: T, source: string) => T {
57
// All saved proxys
58
const savedROObjects: SavedROObjects = new WeakMap();
@@ -63,15 +63,15 @@ function buildMakeReadOnly(
63
source: string,
64
key: string,
65
prop: PropertyDescriptor,
66
- savedEntries: Map<string, SavedEntry>
66
+ savedEntries: Map<string, SavedEntry>,
67
) {
68
- const proxy: PropertyDescriptor & { get(): unknown } = {
68
+ const proxy: PropertyDescriptor & {get(): unknown} = {
69
get() {
70
// read from backing cache entry
71
return makeReadOnly(savedEntries.get(key)!.savedVal, source);
72
},
73
set(newVal: unknown) {
74
- logger("FORGET_MUTATE_IMMUT", source, key, newVal);
74
+ logger('FORGET_MUTATE_IMMUT', source, key, newVal);
75
// update backing cache entry
76
savedEntries.get(key)!.savedVal = newVal;
77
},
@@ -83,13 +83,13 @@ function buildMakeReadOnly(
83
proxy.enumerable = prop.enumerable;
84
}
85
86
- savedEntries.set(key, { savedVal: (obj as any)[key], getter: proxy.get });
86
+ savedEntries.set(key, {savedVal: (obj as any)[key], getter: proxy.get});
87
Object.defineProperty(obj, key, proxy);
88
}
89
90
// Changes an object to be read-only, returns its input
91
function makeReadOnly<T>(o: T, source: string): T {
92
- if (typeof o !== "object" || o == null) {
92
+ if (typeof o !== 'object' || o == null) {
93
return o;
94
} else if (
95
o.constructor?.name != null &&
@@ -98,7 +98,7 @@ function buildMakeReadOnly(
98
return o;
99
}
100
101
- const { existed, entry: cache } = getOrInsertDefault(savedROObjects, o);
101
+ const {existed, entry: cache} = getOrInsertDefault(savedROObjects, o);
102
103
for (const [k, entry] of cache.entries()) {
104
const currentProp = Object.getOwnPropertyDescriptor(o, k);
@@ -116,21 +116,21 @@ function buildMakeReadOnly(
116
// and the current proxied value is stale)
117
cache.delete(k);
118
if (!currentProp) {
119
- logger("FORGET_DELETE_PROP_IMMUT", source, k);
119
+ logger('FORGET_DELETE_PROP_IMMUT', source, k);
120
} else if (currentProp) {
121
- logger("FORGET_CHANGE_PROP_IMMUT", source, k);
121
+ logger('FORGET_CHANGE_PROP_IMMUT', source, k);
122
addProperty(o, source, k, currentProp, cache);
123
}
124
}
125
}
126
for (const [k, prop] of Object.entries(
127
- Object.getOwnPropertyDescriptors(o)
127
+ Object.getOwnPropertyDescriptors(o),
128
)) {
129
if (!cache.has(k) && isWriteable(prop)) {
130
if (
131
- prop.hasOwnProperty("set") ||
132
- prop.hasOwnProperty("get") ||
133
- k === "current"
131
+ prop.hasOwnProperty('set') ||
132
+ prop.hasOwnProperty('get') ||
133
+ k === 'current'
134
) {
135
// - we currently don't handle accessor properties
136
// - we currently have no other way of checking whether an object
@@ -139,7 +139,7 @@ function buildMakeReadOnly(
139
}
140
141
if (existed) {
142
- logger("FORGET_ADD_PROP_IMMUT", source, k);
142
+ logger('FORGET_ADD_PROP_IMMUT', source, k);
143
}
144
addProperty(o, source, k, prop, cache);
145
}
compiler/packages/react-compiler-healthcheck/rollup.config.js
+24
-24
@@ -5,38 +5,38 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import typescript from "@rollup/plugin-typescript";
9
-import { nodeResolve } from "@rollup/plugin-node-resolve";
10
-import commonjs from "@rollup/plugin-commonjs";
11
-import json from "@rollup/plugin-json";
12
-import path from "path";
13
-import process from "process";
14
-import terser from "@rollup/plugin-terser";
15
-import prettier from "rollup-plugin-prettier";
16
-import banner2 from "rollup-plugin-banner2";
8
+import typescript from '@rollup/plugin-typescript';
9
+import {nodeResolve} from '@rollup/plugin-node-resolve';
10
+import commonjs from '@rollup/plugin-commonjs';
11
+import json from '@rollup/plugin-json';
12
+import path from 'path';
13
+import process from 'process';
14
+import terser from '@rollup/plugin-terser';
15
+import prettier from 'rollup-plugin-prettier';
16
+import banner2 from 'rollup-plugin-banner2';
17
18
const NO_INLINE = new Set([
19
- "@babel/core",
20
- "@babel/parser",
21
- "chalk",
22
- "fast-glob",
23
- "ora",
24
- "yargs",
25
- "zod",
26
- "zod-validation-error",
19
+ '@babel/core',
20
+ '@babel/parser',
21
+ 'chalk',
22
+ 'fast-glob',
23
+ 'ora',
24
+ 'yargs',
25
+ 'zod',
26
+ 'zod-validation-error',
27
]);
28
29
const DEV_ROLLUP_CONFIG = {
30
- input: "src/index.ts",
30
+ input: 'src/index.ts',
31
output: {
32
- file: "dist/index.js",
33
- format: "cjs",
32
+ file: 'dist/index.js',
33
+ format: 'cjs',
34
sourcemap: false,
35
- exports: "named",
35
+ exports: 'named',
36
},
37
plugins: [
38
typescript({
39
- tsconfig: "./tsconfig.json",
39
+ tsconfig: './tsconfig.json',
40
compilerOptions: {
41
noEmit: true,
42
},
@@ -44,8 +44,8 @@ const DEV_ROLLUP_CONFIG = {
44
json(),
45
nodeResolve({
46
preferBuiltins: true,
47
- resolveOnly: (module) => NO_INLINE.has(module) === false,
48
- rootDir: path.join(process.cwd(), ".."),
47
+ resolveOnly: module => NO_INLINE.has(module) === false,
48
+ rootDir: path.join(process.cwd(), '..'),
49
}),
50
commonjs(),
51
terser({
compiler/packages/react-compiler-healthcheck/src/checks/libraryCompat.ts
+2
-2
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import chalk from "chalk";
9
-import { config } from "../config";
8
+import chalk from 'chalk';
9
+import {config} from '../config';
10
11
const packageJsonRE = /package\.json$/;
12
const knownIncompatibleLibrariesUsage = new Set();
compiler/packages/react-compiler-healthcheck/src/checks/reactCompiler.ts
+24
-24
@@ -5,18 +5,18 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import type * as BabelCore from "@babel/core";
9
-import { transformFromAstSync } from "@babel/core";
10
-import * as BabelParser from "@babel/parser";
8
+import type * as BabelCore from '@babel/core';
9
+import {transformFromAstSync} from '@babel/core';
10
+import * as BabelParser from '@babel/parser';
11
import BabelPluginReactCompiler, {
12
ErrorSeverity,
13
type CompilerErrorDetailOptions,
14
type PluginOptions,
15
-} from "babel-plugin-react-compiler/src";
16
-import { LoggerEvent as RawLoggerEvent } from "babel-plugin-react-compiler/src/Entrypoint";
17
-import chalk from "chalk";
15
+} from 'babel-plugin-react-compiler/src';
16
+import {LoggerEvent as RawLoggerEvent} from 'babel-plugin-react-compiler/src/Entrypoint';
17
+import chalk from 'chalk';
18
19
-type LoggerEvent = RawLoggerEvent & { filename: string | null };
19
+type LoggerEvent = RawLoggerEvent & {filename: string | null};
20
21
const SucessfulCompilation: Array<LoggerEvent> = [];
22
const ActionableFailures: Array<LoggerEvent> = [];
@@ -24,13 +24,13 @@ const OtherFailures: Array<LoggerEvent> = [];
24
25
const logger = {
26
logEvent(filename: string | null, rawEvent: RawLoggerEvent) {
27
- const event = { ...rawEvent, filename };
27
+ const event = {...rawEvent, filename};
28
switch (event.kind) {
29
- case "CompileSuccess": {
29
+ case 'CompileSuccess': {
30
SucessfulCompilation.push(event);
31
return;
32
}
33
- case "CompileError": {
33
+ case 'CompileError': {
34
if (isActionableDiagnostic(event.detail)) {
35
ActionableFailures.push(event);
36
return;
@@ -38,8 +38,8 @@ const logger = {
38
OtherFailures.push(event);
39
return;
40
}
41
- case "CompileDiagnostic":
42
- case "PipelineError":
41
+ case 'CompileDiagnostic':
42
+ case 'PipelineError':
43
OtherFailures.push(event);
44
return;
45
}
@@ -48,8 +48,8 @@ const logger = {
48
49
const COMPILER_OPTIONS: Partial<PluginOptions> = {
50
noEmit: true,
51
- compilationMode: "infer",
52
- panicThreshold: "critical_errors",
51
+ compilationMode: 'infer',
52
+ panicThreshold: 'critical_errors',
53
logger,
54
};
55
@@ -71,26 +71,26 @@ function isActionableDiagnostic(detail: CompilerErrorDetailOptions) {
71
function runBabelPluginReactCompiler(
72
text: string,
73
file: string,
74
- language: "flow" | "typescript",
75
- options: Partial<PluginOptions> | null
74
+ language: 'flow' | 'typescript',
75
+ options: Partial<PluginOptions> | null,
76
): BabelCore.BabelFileResult {
77
const ast = BabelParser.parse(text, {
78
sourceFilename: file,
79
- plugins: [language, "jsx"],
80
- sourceType: "module",
79
+ plugins: [language, 'jsx'],
80
+ sourceType: 'module',
81
});
82
const result = transformFromAstSync(ast, text, {
83
filename: file,
84
highlightCode: false,
85
retainLines: true,
86
plugins: [[BabelPluginReactCompiler, options]],
87
- sourceType: "module",
87
+ sourceType: 'module',
88
configFile: false,
89
babelrc: false,
90
});
91
if (result?.code == null) {
92
throw new Error(
93
- `Expected BabelPluginReactForget to codegen successfully, got: ${result}`
93
+ `Expected BabelPluginReactForget to codegen successfully, got: ${result}`,
94
);
95
}
96
return result;
@@ -101,8 +101,8 @@ function compile(sourceCode: string, filename: string) {
101
runBabelPluginReactCompiler(
102
sourceCode,
103
filename,
104
- "typescript",
105
- COMPILER_OPTIONS
104
+ 'typescript',
105
+ COMPILER_OPTIONS,
106
);
107
} catch {}
108
}
@@ -146,8 +146,8 @@ export default {
146
countUniqueLocInEvents(ActionableFailures);
147
console.log(
148
chalk.green(
149
- `Successfully compiled ${SucessfulCompilation.length} out of ${totalComponents} components.`
150
- )
149
+ `Successfully compiled ${SucessfulCompilation.length} out of ${totalComponents} components.`,
150
+ ),
151
);
152
},
153
};
compiler/packages/react-compiler-healthcheck/src/checks/strictMode.ts
+3
-3
@@ -5,7 +5,7 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import chalk from "chalk";
8
+import chalk from 'chalk';
9
10
const JsFileExtensionRE = /(js|ts|jsx|tsx)$/;
11
const NextConfigFileRE = /^next\.config\.(js|mjs)$/;
@@ -28,9 +28,9 @@ export default {
28
29
report(): void {
30
if (StrictModeUsage) {
31
- console.log(chalk.green("StrictMode usage found."));
31
+ console.log(chalk.green('StrictMode usage found.'));
32
} else {
33
- console.log(chalk.red("StrictMode usage not found."));
33
+ console.log(chalk.red('StrictMode usage not found.'));
34
}
35
},
36
};
compiler/packages/react-compiler-healthcheck/src/config.ts
+1
-1
@@ -1,3 +1,3 @@
1
export const config = {
2
- knownIncompatibleLibraries: ["mobx", "@risingstack/react-easy-state"],
2
+ knownIncompatibleLibraries: ['mobx', '@risingstack/react-easy-state'],
3
};
compiler/packages/react-compiler-healthcheck/src/index.ts
+21
-21
@@ -5,42 +5,42 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { glob } from "fast-glob";
9
-import * as fs from "fs/promises";
10
-import ora from "ora";
11
-import yargs from "yargs/yargs";
12
-import libraryCompatCheck from "./checks/libraryCompat";
13
-import reactCompilerCheck from "./checks/reactCompiler";
14
-import strictModeCheck from "./checks/strictMode";
8
+import {glob} from 'fast-glob';
9
+import * as fs from 'fs/promises';
10
+import ora from 'ora';
11
+import yargs from 'yargs/yargs';
12
+import libraryCompatCheck from './checks/libraryCompat';
13
+import reactCompilerCheck from './checks/reactCompiler';
14
+import strictModeCheck from './checks/strictMode';
15
16
async function main() {
17
const argv = yargs(process.argv.slice(2))
18
- .scriptName("healthcheck")
19
- .usage("$ npx healthcheck <src>")
20
- .option("src", {
21
- description: "glob expression matching src files to compile",
22
- type: "string",
23
- default: "**/+(*.{js,mjs,jsx,ts,tsx}|package.json)",
18
+ .scriptName('healthcheck')
19
+ .usage('$ npx healthcheck <src>')
20
+ .option('src', {
21
+ description: 'glob expression matching src files to compile',
22
+ type: 'string',
23
+ default: '**/+(*.{js,mjs,jsx,ts,tsx}|package.json)',
24
})
25
.parseSync();
26
27
- const spinner = ora("Checking").start();
27
+ const spinner = ora('Checking').start();
28
let src = argv.src;
29
30
const globOptions = {
31
onlyFiles: true,
32
ignore: [
33
- "**/node_modules/**",
34
- "**/dist/**",
35
- "**/tests/**",
36
- "**/__tests__/**",
37
- "**/__mocks__/**",
38
- "**/__e2e__/**",
33
+ '**/node_modules/**',
34
+ '**/dist/**',
35
+ '**/tests/**',
36
+ '**/__tests__/**',
37
+ '**/__mocks__/**',
38
+ '**/__e2e__/**',
39
],
40
};
41
42
for (const path of await glob(src, globOptions)) {
43
- const source = await fs.readFile(path, "utf-8");
43
+ const source = await fs.readFile(path, 'utf-8');
44
spinner.text = `Checking ${path}`;
45
reactCompilerCheck.run(source, path);
46
strictModeCheck.run(source, path);
compiler/packages/react-compiler-runtime/rollup.config.js
+15
-15
@@ -5,27 +5,27 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import typescript from "@rollup/plugin-typescript";
9
-import { nodeResolve } from "@rollup/plugin-node-resolve";
10
-import commonjs from "@rollup/plugin-commonjs";
11
-import json from "@rollup/plugin-json";
12
-import path from "path";
13
-import process from "process";
14
-import terser from "@rollup/plugin-terser";
15
-import banner2 from "rollup-plugin-banner2";
8
+import typescript from '@rollup/plugin-typescript';
9
+import {nodeResolve} from '@rollup/plugin-node-resolve';
10
+import commonjs from '@rollup/plugin-commonjs';
11
+import json from '@rollup/plugin-json';
12
+import path from 'path';
13
+import process from 'process';
14
+import terser from '@rollup/plugin-terser';
15
+import banner2 from 'rollup-plugin-banner2';
16
17
-const NO_INLINE = new Set(["react"]);
17
+const NO_INLINE = new Set(['react']);
18
19
const PROD_ROLLUP_CONFIG = {
20
- input: "src/index.ts",
20
+ input: 'src/index.ts',
21
output: {
22
- file: "dist/index.js",
23
- format: "cjs",
22
+ file: 'dist/index.js',
23
+ format: 'cjs',
24
sourcemap: true,
25
},
26
plugins: [
27
typescript({
28
- tsconfig: "./tsconfig.json",
28
+ tsconfig: './tsconfig.json',
29
compilerOptions: {
30
noEmit: true,
31
},
@@ -33,8 +33,8 @@ const PROD_ROLLUP_CONFIG = {
33
json(),
34
nodeResolve({
35
preferBuiltins: true,
36
- resolveOnly: (module) => NO_INLINE.has(module) === false,
37
- rootDir: path.join(process.cwd(), ".."),
36
+ resolveOnly: module => NO_INLINE.has(module) === false,
37
+ rootDir: path.join(process.cwd(), '..'),
38
}),
39
commonjs(),
40
terser({
compiler/packages/react-compiler-runtime/src/index.ts
+68
-68
@@ -5,11 +5,11 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-"use no forget";
8
+'use no forget';
9
10
-import * as React from "react";
10
+import * as React from 'react';
11
12
-const { useRef, useEffect, isValidElement } = React;
12
+const {useRef, useEffect, isValidElement} = React;
13
const ReactSecretInternals =
14
//@ts-ignore
15
React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE ??
@@ -18,7 +18,7 @@ const ReactSecretInternals =
18
19
type MemoCache = Array<number | typeof $empty>;
20
21
-const $empty = Symbol.for("react.memo_cache_sentinel");
21
+const $empty = Symbol.for('react.memo_cache_sentinel');
22
/**
23
* DANGER: this hook is NEVER meant to be called directly!
24
**/
@@ -39,39 +39,39 @@ export function c(size: number) {
39
export function $read(memoCache: MemoCache, index: number) {
40
const value = memoCache[index];
41
if (value === $empty) {
42
- throw new Error("useMemoCache: read before write");
42
+ throw new Error('useMemoCache: read before write');
43
}
44
return value;
45
}
46
47
-const LazyGuardDispatcher: { [key: string]: (...args: Array<any>) => any } = {};
47
+const LazyGuardDispatcher: {[key: string]: (...args: Array<any>) => any} = {};
48
[
49
- "readContext",
50
- "useCallback",
51
- "useContext",
52
- "useEffect",
53
- "useImperativeHandle",
54
- "useInsertionEffect",
55
- "useLayoutEffect",
56
- "useMemo",
57
- "useReducer",
58
- "useRef",
59
- "useState",
60
- "useDebugValue",
61
- "useDeferredValue",
62
- "useTransition",
63
- "useMutableSource",
64
- "useSyncExternalStore",
65
- "useId",
66
- "unstable_isNewReconciler",
67
- "getCacheSignal",
68
- "getCacheForType",
69
- "useCacheRefresh",
70
-].forEach((name) => {
49
+ 'readContext',
50
+ 'useCallback',
51
+ 'useContext',
52
+ 'useEffect',
53
+ 'useImperativeHandle',
54
+ 'useInsertionEffect',
55
+ 'useLayoutEffect',
56
+ 'useMemo',
57
+ 'useReducer',
58
+ 'useRef',
59
+ 'useState',
60
+ 'useDebugValue',
61
+ 'useDeferredValue',
62
+ 'useTransition',
63
+ 'useMutableSource',
64
+ 'useSyncExternalStore',
65
+ 'useId',
66
+ 'unstable_isNewReconciler',
67
+ 'getCacheSignal',
68
+ 'getCacheForType',
69
+ 'useCacheRefresh',
70
+].forEach(name => {
71
LazyGuardDispatcher[name] = () => {
72
throw new Error(
73
`[React] Unexpected React hook call (${name}) from a React Forget compiled function. ` +
74
- "Check that all hooks are called directly and named according to convention ('use[A-Z]') "
74
+ "Check that all hooks are called directly and named according to convention ('use[A-Z]') ",
75
);
76
};
77
});
@@ -79,10 +79,10 @@ const LazyGuardDispatcher: { [key: string]: (...args: Array<any>) => any } = {};
79
let originalDispatcher: unknown = null;
80
81
// Allow guards are not emitted for useMemoCache
82
-LazyGuardDispatcher["useMemoCache"] = (count: number) => {
82
+LazyGuardDispatcher['useMemoCache'] = (count: number) => {
83
if (originalDispatcher == null) {
84
throw new Error(
85
- "React Forget internal invariant violation: unexpected null dispatcher"
85
+ 'React Forget internal invariant violation: unexpected null dispatcher',
86
);
87
} else {
88
return (originalDispatcher as any).useMemoCache(count);
@@ -153,7 +153,7 @@ export function $dispatcherGuard(kind: GuardKind) {
153
throw new Error(
154
`[React] Unexpected call to custom hook or component from a React Forget compiled function. ` +
155
"Check that (1) all hooks are called directly and named according to convention ('use[A-Z]') " +
156
- "and (2) components are returned as JSX instead of being directly invoked."
156
+ 'and (2) components are returned as JSX instead of being directly invoked.',
157
);
158
}
159
setCurrent(LazyGuardDispatcher);
@@ -163,7 +163,7 @@ export function $dispatcherGuard(kind: GuardKind) {
163
164
if (lastFrame == null) {
165
throw new Error(
166
- "React Forget internal error: unexpected null in guard stack"
166
+ 'React Forget internal error: unexpected null in guard stack',
167
);
168
}
169
if (guardFrames.length === 0) {
@@ -179,12 +179,12 @@ export function $dispatcherGuard(kind: GuardKind) {
179
const lastFrame = guardFrames.pop();
180
if (lastFrame == null) {
181
throw new Error(
182
- "React Forget internal error: unexpected null in guard stack"
182
+ 'React Forget internal error: unexpected null in guard stack',
183
);
184
}
185
setCurrent(lastFrame);
186
} else {
187
- throw new Error("Forget internal error: unreachable block" + kind);
187
+ throw new Error('Forget internal error: unreachable block' + kind);
188
}
189
}
190
@@ -195,7 +195,7 @@ export function $reset($: MemoCache) {
195
}
196
197
export function $makeReadOnly() {
198
- throw new Error("TODO: implement $makeReadOnly in react-compiler-runtime");
198
+ throw new Error('TODO: implement $makeReadOnly in react-compiler-runtime');
199
}
200
201
/**
@@ -203,17 +203,17 @@ export function $makeReadOnly() {
203
*/
204
export const renderCounterRegistry: Map<
205
string,
206
- Set<{ count: number }>
206
+ Set<{count: number}>
207
> = new Map();
208
export function clearRenderCounterRegistry() {
209
for (const counters of renderCounterRegistry.values()) {
210
- counters.forEach((counter) => {
210
+ counters.forEach(counter => {
211
counter.count = 0;
212
});
213
}
214
}
215
216
-function registerRenderCounter(name: string, val: { count: number }) {
216
+function registerRenderCounter(name: string, val: {count: number}) {
217
let counters = renderCounterRegistry.get(name);
218
if (counters == null) {
219
counters = new Set();
@@ -222,7 +222,7 @@ function registerRenderCounter(name: string, val: { count: number }) {
222
counters.add(val);
223
}
224
225
-function removeRenderCounter(name: string, val: { count: number }): void {
225
+function removeRenderCounter(name: string, val: {count: number}): void {
226
const counters = renderCounterRegistry.get(name);
227
if (counters == null) {
228
return;
@@ -231,7 +231,7 @@ function removeRenderCounter(name: string, val: { count: number }): void {
231
}
232
233
export function useRenderCounter(name: string): void {
234
- const val = useRef<{ count: number }>(null);
234
+ const val = useRef<{count: number}>(null);
235
236
if (val.current != null) {
237
val.current.count += 1;
@@ -239,7 +239,7 @@ export function useRenderCounter(name: string): void {
239
useEffect(() => {
240
// Not counting initial render shouldn't be a problem
241
if (val.current == null) {
242
- const counter = { count: 0 };
242
+ const counter = {count: 0};
243
registerRenderCounter(name, counter);
244
// @ts-ignore
245
val.current = counter;
@@ -260,7 +260,7 @@ export function $structuralCheck(
260
variableName: string,
261
fnName: string,
262
kind: string,
263
- loc: string
263
+ loc: string,
264
): void {
265
function error(l: string, r: string, path: string, depth: number) {
266
const str = `${fnName}:${loc} [${kind}] ${variableName}${path} changed from ${l} to ${r} at depth ${depth}`;
@@ -278,13 +278,13 @@ export function $structuralCheck(
278
return;
279
} else if (typeof oldValue !== typeof newValue) {
280
error(`type ${typeof oldValue}`, `type ${typeof newValue}`, path, depth);
281
- } else if (typeof oldValue === "object") {
281
+ } else if (typeof oldValue === 'object') {
282
const oldArray = Array.isArray(oldValue);
283
const newArray = Array.isArray(newValue);
284
if (oldValue === null && newValue !== null) {
285
- error("null", `type ${typeof newValue}`, path, depth);
285
+ error('null', `type ${typeof newValue}`, path, depth);
286
} else if (newValue === null) {
287
- error(`type ${typeof oldValue}`, "null", path, depth);
287
+ error(`type ${typeof oldValue}`, 'null', path, depth);
288
} else if (oldValue instanceof Map) {
289
if (!(newValue instanceof Map)) {
290
error(`Map instance`, `other value`, path, depth);
@@ -293,7 +293,7 @@ export function $structuralCheck(
293
`Map instance with size ${oldValue.size}`,
294
`Map instance with size ${newValue.size}`,
295
path,
296
- depth
296
+ depth,
297
);
298
} else {
299
for (const [k, v] of oldValue) {
@@ -302,7 +302,7 @@ export function $structuralCheck(
302
`Map instance with key ${k}`,
303
`Map instance without key ${k}`,
304
path,
305
- depth
305
+ depth,
306
);
307
} else {
308
recur(v, newValue.get(k), `${path}.get(${k})`, depth + 1);
@@ -310,7 +310,7 @@ export function $structuralCheck(
310
}
311
}
312
} else if (newValue instanceof Map) {
313
- error("other value", `Map instance`, path, depth);
313
+ error('other value', `Map instance`, path, depth);
314
} else if (oldValue instanceof Set) {
315
if (!(newValue instanceof Set)) {
316
error(`Set instance`, `other value`, path, depth);
@@ -319,7 +319,7 @@ export function $structuralCheck(
319
`Set instance with size ${oldValue.size}`,
320
`Set instance with size ${newValue.size}`,
321
path,
322
- depth
322
+ depth,
323
);
324
} else {
325
for (const v of newValue) {
@@ -328,27 +328,27 @@ export function $structuralCheck(
328
`Set instance without element ${v}`,
329
`Set instance with element ${v}`,
330
path,
331
- depth
331
+ depth,
332
);
333
}
334
}
335
}
336
} else if (newValue instanceof Set) {
337
- error("other value", `Set instance`, path, depth);
337
+ error('other value', `Set instance`, path, depth);
338
} else if (oldArray || newArray) {
339
if (oldArray !== newArray) {
340
error(
341
- `type ${oldArray ? "array" : "object"}`,
342
- `type ${newArray ? "array" : "object"}`,
341
+ `type ${oldArray ? 'array' : 'object'}`,
342
+ `type ${newArray ? 'array' : 'object'}`,
343
path,
344
- depth
344
+ depth,
345
);
346
} else if (oldValue.length !== newValue.length) {
347
error(
348
`array with length ${oldValue.length}`,
349
`array with length ${newValue.length}`,
350
path,
351
- depth
351
+ depth,
352
);
353
} else {
354
for (let ii = 0; ii < oldValue.length; ii++) {
@@ -358,24 +358,24 @@ export function $structuralCheck(
358
} else if (isValidElement(oldValue) || isValidElement(newValue)) {
359
if (isValidElement(oldValue) !== isValidElement(newValue)) {
360
error(
361
- `type ${isValidElement(oldValue) ? "React element" : "object"}`,
362
- `type ${isValidElement(newValue) ? "React element" : "object"}`,
361
+ `type ${isValidElement(oldValue) ? 'React element' : 'object'}`,
362
+ `type ${isValidElement(newValue) ? 'React element' : 'object'}`,
363
path,
364
- depth
364
+ depth,
365
);
366
} else if (oldValue.type !== newValue.type) {
367
error(
368
`React element of type ${oldValue.type}`,
369
`React element of type ${newValue.type}`,
370
path,
371
- depth
371
+ depth,
372
);
373
} else {
374
recur(
375
oldValue.props,
376
newValue.props,
377
`[props of ${path}]`,
378
- depth + 1
378
+ depth + 1,
379
);
380
}
381
} else {
@@ -385,7 +385,7 @@ export function $structuralCheck(
385
`object without key ${key}`,
386
`object with key ${key}`,
387
path,
388
- depth
388
+ depth,
389
);
390
}
391
}
@@ -395,28 +395,28 @@ export function $structuralCheck(
395
`object with key ${key}`,
396
`object without key ${key}`,
397
path,
398
- depth
398
+ depth,
399
);
400
} else {
401
recur(oldValue[key], newValue[key], `${path}.${key}`, depth + 1);
402
}
403
}
404
}
405
- } else if (typeof oldValue === "function") {
405
+ } else if (typeof oldValue === 'function') {
406
// Bail on functions for now
407
return;
408
} else if (isNaN(oldValue) || isNaN(newValue)) {
409
if (isNaN(oldValue) !== isNaN(newValue)) {
410
error(
411
- `${isNaN(oldValue) ? "NaN" : "non-NaN value"}`,
412
- `${isNaN(newValue) ? "NaN" : "non-NaN value"}`,
411
+ `${isNaN(oldValue) ? 'NaN' : 'non-NaN value'}`,
412
+ `${isNaN(newValue) ? 'NaN' : 'non-NaN value'}`,
413
path,
414
- depth
414
+ depth,
415
);
416
}
417
} else if (oldValue !== newValue) {
418
error(oldValue, newValue, path, depth);
419
}
420
}
421
- recur(oldValue, newValue, "", 0);
421
+ recur(oldValue, newValue, '', 0);
422
}
compiler/packages/snap/src/SproutTodoFilter.ts
+449
-449
@@ -9,499 +9,499 @@ const skipFilter = new Set([
9
/**
10
* Observable different in logging between Forget and non-Forget
11
*/
12
- "early-return-no-declarations-reassignments-dependencies",
12
+ 'early-return-no-declarations-reassignments-dependencies',
13
14
/**
15
* Category A:
16
* Tests with 0 parameters and 0 refs to external values
17
*/
18
// TODO: fix invalid .set call
19
- "assignment-variations-complex-lvalue-array",
19
+ 'assignment-variations-complex-lvalue-array',
20
// TODO: uses jsx (requires React)
21
- "sketchy-code-rules-of-hooks",
21
+ 'sketchy-code-rules-of-hooks',
22
// TODO: fix infinite loop
23
- "ssa-for-trivial-update",
23
+ 'ssa-for-trivial-update',
24
// TODO: fix infinite loop
25
- "ssa-while-no-reassign",
25
+ 'ssa-while-no-reassign',
26
27
/**
28
* Category B:
29
* Tests with at least one param and 0 refs to external values
30
*/
31
- "bug.useMemo-deps-array-not-cleared",
32
- "capture_mutate-across-fns",
33
- "capture-indirect-mutate-alias",
34
- "capturing-arrow-function-1",
35
- "capturing-func-mutate-3",
36
- "capturing-func-mutate-nested",
37
- "capturing-func-mutate",
38
- "capturing-function-1",
39
- "capturing-function-alias-computed-load",
40
- "capturing-function-decl",
41
- "capturing-function-skip-computed-path",
42
- "capturing-function-within-block",
43
- "capturing-member-expr",
44
- "capturing-nested-member-call",
45
- "capturing-nested-member-expr-in-nested-func",
46
- "capturing-nested-member-expr",
47
- "capturing-variable-in-nested-block",
48
- "capturing-variable-in-nested-function",
49
- "complex-while",
50
- "component",
51
- "cond-deps-conditional-member-expr",
52
- "conditional-break-labeled",
53
- "conditional-set-state-in-render",
54
- "constant-computed",
55
- "constant-propagation-phi",
56
- "debugger-memoized",
57
- "debugger",
58
- "declare-reassign-variable-in-closure",
59
- "delete-computed-property",
60
- "delete-property",
61
- "dependencies-outputs",
62
- "dependencies",
63
- "destructure-direct-reassignment",
64
- "destructuring-array-default",
65
- "destructuring-array-param-default",
66
- "destructuring-assignment-array-default",
67
- "destructuring-assignment",
68
- "destructuring-object-default",
69
- "destructuring-object-param-default",
70
- "destructuring",
71
- "disable-jsx-memoization",
72
- "do-while-break",
73
- "do-while-compound-test",
74
- "dominator",
75
- "early-return",
76
- "escape-analysis-destructured-rest-element",
77
- "escape-analysis-jsx-child",
78
- "escape-analysis-logical",
79
- "escape-analysis-non-escaping-interleaved-allocating-dependency",
80
- "escape-analysis-non-escaping-interleaved-allocating-nested-dependency",
81
- "escape-analysis-non-escaping-interleaved-primitive-dependency",
82
- "escape-analysis-not-conditional-test",
83
- "escape-analysis-not-if-test",
84
- "escape-analysis-not-switch-case",
85
- "escape-analysis-not-switch-test",
86
- "expression-with-assignment-dynamic",
87
- "extend-scopes-if",
88
- "fbt/fbt-params",
89
- "for-empty-update-with-continue",
90
- "for-empty-update",
91
- "for-logical",
92
- "for-return",
93
- "function-declaration-simple",
94
- "function-param-assignment-pattern",
95
- "globals-Boolean",
96
- "globals-Number",
97
- "globals-String",
98
- "holey-array-pattern-dce-2",
99
- "holey-array-pattern-dce",
100
- "holey-array",
101
- "independently-memoize-object-property",
102
- "inverted-if-else",
103
- "inverted-if",
104
- "jsx-empty-expression",
105
- "jsx-fragment",
106
- "jsx-namespaced-name",
107
- "lambda-mutated-non-reactive-to-reactive",
108
- "lambda-mutated-ref-non-reactive",
109
- "logical-expression-object",
110
- "logical-expression",
111
- "nested-function-shadowed-identifiers",
112
- "nonoptional-load-from-optional-memberexpr",
113
- "object-computed-access-assignment",
114
- "object-expression-string-literal-key",
115
- "object-literal-spread-element",
116
- "object-pattern-params",
117
- "optional-member-expression-chain",
118
- "overlapping-scopes-interleaved-by-terminal",
119
- "overlapping-scopes-interleaved",
120
- "overlapping-scopes-shadowed",
121
- "overlapping-scopes-shadowing-within-block",
122
- "overlapping-scopes-while",
123
- "overlapping-scopes-within-block",
124
- "prop-capturing-function-1",
125
- "reactive-scopes-if",
126
- "reactive-scopes",
127
- "reactivity-analysis-interleaved-reactivity",
128
- "reassign-object-in-context",
129
- "reassignment-separate-scopes",
130
- "return-conditional",
131
- "return-undefined",
132
- "reverse-postorder",
133
- "same-variable-as-dep-and-redeclare-maybe-frozen",
134
- "same-variable-as-dep-and-redeclare",
135
- "simple-scope",
136
- "ssa-arrayexpression",
137
- "ssa-cascading-eliminated-phis",
138
- "ssa-for-of",
139
- "ssa-multiple-phis",
140
- "ssa-nested-loops-no-reassign",
141
- "ssa-nested-partial-phi",
142
- "ssa-nested-partial-reassignment",
143
- "ssa-non-empty-initializer",
144
- "ssa-objectexpression",
145
- "ssa-property-alias-if",
146
- "ssa-reassign",
147
- "ssa-renaming-ternary-destruction",
148
- "ssa-renaming-ternary",
149
- "ssa-renaming-unconditional-ternary",
150
- "ssa-renaming-via-destructuring",
151
- "ssa-renaming",
152
- "ssa-sibling-phis",
153
- "switch-with-fallthrough",
154
- "ternary-assignment-expression",
155
- "ternary-expression",
156
- "trivial",
157
- "type-args-test-binary-operator",
158
- "type-cast-expression.flow",
159
- "unary-expr",
160
- "unconditional-break-label",
161
- "unused-array-middle-element",
162
- "unused-array-rest-element",
163
- "unused-conditional",
164
- "unused-logical",
165
- "unused-object-element-with-rest",
166
- "unused-object-element",
167
- "useMemo-inlining-block-return",
168
- "useMemo-inverted-if",
169
- "useMemo-labeled-statement-unconditional-return",
170
- "useMemo-logical",
171
- "useMemo-nested-ifs",
172
- "useMemo-switch-no-fallthrough",
173
- "useMemo-switch-return",
174
- "while-break",
175
- "while-conditional-continue",
176
- "while-logical",
177
- "while-property",
178
- "validate-no-set-state-in-render-uncalled-function-with-mutable-range-is-valid",
31
+ 'bug.useMemo-deps-array-not-cleared',
32
+ 'capture_mutate-across-fns',
33
+ 'capture-indirect-mutate-alias',
34
+ 'capturing-arrow-function-1',
35
+ 'capturing-func-mutate-3',
36
+ 'capturing-func-mutate-nested',
37
+ 'capturing-func-mutate',
38
+ 'capturing-function-1',
39
+ 'capturing-function-alias-computed-load',
40
+ 'capturing-function-decl',
41
+ 'capturing-function-skip-computed-path',
42
+ 'capturing-function-within-block',
43
+ 'capturing-member-expr',
44
+ 'capturing-nested-member-call',
45
+ 'capturing-nested-member-expr-in-nested-func',
46
+ 'capturing-nested-member-expr',
47
+ 'capturing-variable-in-nested-block',
48
+ 'capturing-variable-in-nested-function',
49
+ 'complex-while',
50
+ 'component',
51
+ 'cond-deps-conditional-member-expr',
52
+ 'conditional-break-labeled',
53
+ 'conditional-set-state-in-render',
54
+ 'constant-computed',
55
+ 'constant-propagation-phi',
56
+ 'debugger-memoized',
57
+ 'debugger',
58
+ 'declare-reassign-variable-in-closure',
59
+ 'delete-computed-property',
60
+ 'delete-property',
61
+ 'dependencies-outputs',
62
+ 'dependencies',
63
+ 'destructure-direct-reassignment',
64
+ 'destructuring-array-default',
65
+ 'destructuring-array-param-default',
66
+ 'destructuring-assignment-array-default',
67
+ 'destructuring-assignment',
68
+ 'destructuring-object-default',
69
+ 'destructuring-object-param-default',
70
+ 'destructuring',
71
+ 'disable-jsx-memoization',
72
+ 'do-while-break',
73
+ 'do-while-compound-test',
74
+ 'dominator',
75
+ 'early-return',
76
+ 'escape-analysis-destructured-rest-element',
77
+ 'escape-analysis-jsx-child',
78
+ 'escape-analysis-logical',
79
+ 'escape-analysis-non-escaping-interleaved-allocating-dependency',
80
+ 'escape-analysis-non-escaping-interleaved-allocating-nested-dependency',
81
+ 'escape-analysis-non-escaping-interleaved-primitive-dependency',
82
+ 'escape-analysis-not-conditional-test',
83
+ 'escape-analysis-not-if-test',
84
+ 'escape-analysis-not-switch-case',
85
+ 'escape-analysis-not-switch-test',
86
+ 'expression-with-assignment-dynamic',
87
+ 'extend-scopes-if',
88
+ 'fbt/fbt-params',
89
+ 'for-empty-update-with-continue',
90
+ 'for-empty-update',
91
+ 'for-logical',
92
+ 'for-return',
93
+ 'function-declaration-simple',
94
+ 'function-param-assignment-pattern',
95
+ 'globals-Boolean',
96
+ 'globals-Number',
97
+ 'globals-String',
98
+ 'holey-array-pattern-dce-2',
99
+ 'holey-array-pattern-dce',
100
+ 'holey-array',
101
+ 'independently-memoize-object-property',
102
+ 'inverted-if-else',
103
+ 'inverted-if',
104
+ 'jsx-empty-expression',
105
+ 'jsx-fragment',
106
+ 'jsx-namespaced-name',
107
+ 'lambda-mutated-non-reactive-to-reactive',
108
+ 'lambda-mutated-ref-non-reactive',
109
+ 'logical-expression-object',
110
+ 'logical-expression',
111
+ 'nested-function-shadowed-identifiers',
112
+ 'nonoptional-load-from-optional-memberexpr',
113
+ 'object-computed-access-assignment',
114
+ 'object-expression-string-literal-key',
115
+ 'object-literal-spread-element',
116
+ 'object-pattern-params',
117
+ 'optional-member-expression-chain',
118
+ 'overlapping-scopes-interleaved-by-terminal',
119
+ 'overlapping-scopes-interleaved',
120
+ 'overlapping-scopes-shadowed',
121
+ 'overlapping-scopes-shadowing-within-block',
122
+ 'overlapping-scopes-while',
123
+ 'overlapping-scopes-within-block',
124
+ 'prop-capturing-function-1',
125
+ 'reactive-scopes-if',
126
+ 'reactive-scopes',
127
+ 'reactivity-analysis-interleaved-reactivity',
128
+ 'reassign-object-in-context',
129
+ 'reassignment-separate-scopes',
130
+ 'return-conditional',
131
+ 'return-undefined',
132
+ 'reverse-postorder',
133
+ 'same-variable-as-dep-and-redeclare-maybe-frozen',
134
+ 'same-variable-as-dep-and-redeclare',
135
+ 'simple-scope',
136
+ 'ssa-arrayexpression',
137
+ 'ssa-cascading-eliminated-phis',
138
+ 'ssa-for-of',
139
+ 'ssa-multiple-phis',
140
+ 'ssa-nested-loops-no-reassign',
141
+ 'ssa-nested-partial-phi',
142
+ 'ssa-nested-partial-reassignment',
143
+ 'ssa-non-empty-initializer',
144
+ 'ssa-objectexpression',
145
+ 'ssa-property-alias-if',
146
+ 'ssa-reassign',
147
+ 'ssa-renaming-ternary-destruction',
148
+ 'ssa-renaming-ternary',
149
+ 'ssa-renaming-unconditional-ternary',
150
+ 'ssa-renaming-via-destructuring',
151
+ 'ssa-renaming',
152
+ 'ssa-sibling-phis',
153
+ 'switch-with-fallthrough',
154
+ 'ternary-assignment-expression',
155
+ 'ternary-expression',
156
+ 'trivial',
157
+ 'type-args-test-binary-operator',
158
+ 'type-cast-expression.flow',
159
+ 'unary-expr',
160
+ 'unconditional-break-label',
161
+ 'unused-array-middle-element',
162
+ 'unused-array-rest-element',
163
+ 'unused-conditional',
164
+ 'unused-logical',
165
+ 'unused-object-element-with-rest',
166
+ 'unused-object-element',
167
+ 'useMemo-inlining-block-return',
168
+ 'useMemo-inverted-if',
169
+ 'useMemo-labeled-statement-unconditional-return',
170
+ 'useMemo-logical',
171
+ 'useMemo-nested-ifs',
172
+ 'useMemo-switch-no-fallthrough',
173
+ 'useMemo-switch-return',
174
+ 'while-break',
175
+ 'while-conditional-continue',
176
+ 'while-logical',
177
+ 'while-property',
178
+ 'validate-no-set-state-in-render-uncalled-function-with-mutable-range-is-valid',
179
// Category B with multiple entrypoints,
180
- "conditional-break",
180
+ 'conditional-break',
181
182
/**
183
* Category C:
184
* Tests with at 0 params and at least one ref to external values
185
*/
186
- "alias-capture-in-method-receiver",
187
- "alias-nested-member-path-mutate",
188
- "concise-arrow-expr",
189
- "const-propagation-into-function-expression-global",
190
- "declare-reassign-variable-in-function-declaration",
191
- "lambda-mutate-shadowed-object",
192
- "fbt/lambda-with-fbt",
193
- "recursive-function-expr",
194
- "ref-current-aliased-no-added-to-dep",
195
- "ref-current-field-not-added-to-dep",
196
- "ref-current-not-added-to-dep",
197
- "ref-current-optional-field-no-added-to-dep",
198
- "ref-current-write-not-added-to-dep",
199
- "rewrite-phis-in-lambda-capture-context",
200
- "sketchy-code-exhaustive-deps",
201
- "ssa-property-alias-mutate",
202
- "ssa-property-mutate-2",
203
- "ssa-property-mutate-alias",
204
- "ssa-property-mutate",
205
- "ssa-reassign-in-rval",
206
- "store-via-call",
207
- "store-via-new",
208
- "tagged-template-literal",
209
- "transitive-alias-fields",
210
- "type-binary-operator",
211
- "type-test-field-load-binary-op",
212
- "type-test-polymorphic",
213
- "type-test-return-type-inference",
214
- "use-callback-simple",
186
+ 'alias-capture-in-method-receiver',
187
+ 'alias-nested-member-path-mutate',
188
+ 'concise-arrow-expr',
189
+ 'const-propagation-into-function-expression-global',
190
+ 'declare-reassign-variable-in-function-declaration',
191
+ 'lambda-mutate-shadowed-object',
192
+ 'fbt/lambda-with-fbt',
193
+ 'recursive-function-expr',
194
+ 'ref-current-aliased-no-added-to-dep',
195
+ 'ref-current-field-not-added-to-dep',
196
+ 'ref-current-not-added-to-dep',
197
+ 'ref-current-optional-field-no-added-to-dep',
198
+ 'ref-current-write-not-added-to-dep',
199
+ 'rewrite-phis-in-lambda-capture-context',
200
+ 'sketchy-code-exhaustive-deps',
201
+ 'ssa-property-alias-mutate',
202
+ 'ssa-property-mutate-2',
203
+ 'ssa-property-mutate-alias',
204
+ 'ssa-property-mutate',
205
+ 'ssa-reassign-in-rval',
206
+ 'store-via-call',
207
+ 'store-via-new',
208
+ 'tagged-template-literal',
209
+ 'transitive-alias-fields',
210
+ 'type-binary-operator',
211
+ 'type-test-field-load-binary-op',
212
+ 'type-test-polymorphic',
213
+ 'type-test-return-type-inference',
214
+ 'use-callback-simple',
215
// defines two functions
216
- "simple-alias",
216
+ 'simple-alias',
217
218
/**
219
* Category D:
220
* Tests with one or more params, with external references.
221
*/
222
- "alias-computed-load",
223
- "allocating-primitive-as-dep",
224
- "allow-passing-refs-as-props",
225
- "array-at-closure",
226
- "array-at-effect",
227
- "array-at-mutate-after-capture",
228
- "array-join",
229
- "array-push-effect",
230
- "arrow-function-expr-gating-test",
231
- "assignment-in-nested-if",
232
- "await-side-effecting-promise",
233
- "await",
234
- "builtin-jsx-tag-lowered-between-mutations",
235
- "call-args-assignment",
236
- "call-args-destructuring-assignment",
237
- "call-spread",
238
- "call-with-independently-memoizable-arg",
239
- "capture-param-mutate",
240
- "capturing-fun-alias-captured-mutate-2",
241
- "capturing-fun-alias-captured-mutate-arr-2",
242
- "capturing-func-alias-captured-mutate-arr",
243
- "capturing-func-alias-captured-mutate",
244
- "capturing-func-alias-computed-mutate",
245
- "capturing-func-alias-mutate",
246
- "capturing-func-alias-receiver-computed-mutate",
247
- "capturing-func-alias-receiver-mutate",
248
- "capturing-func-simple-alias",
249
- "capturing-function-capture-ref-before-rename",
250
- "capturing-function-conditional-capture-mutate",
251
- "capturing-function-member-expr-arguments",
252
- "capturing-function-member-expr-call",
253
- "capturing-function-renamed-ref",
254
- "capturing-function-runs-inference",
255
- "capturing-function-shadow-captured",
256
- "capturing-reference-changes-type",
257
- "codegen-emit-imports-same-source",
258
- "codegen-emit-make-read-only",
259
- "computed-call-spread",
260
- "computed-load-primitive-as-dependency",
261
- "computed-store-alias",
262
- "constant-propagation-into-function-expressions",
263
- "destructuring-mixed-scope-declarations-and-locals",
264
- "destructuring-property-inference",
265
- "do-while-conditional-break",
266
- "do-while-early-unconditional-break",
267
- "fbt/fbt-params-complex-param-value",
268
- "function-expression-captures-value-later-frozen-jsx",
269
- "function-expression-maybe-mutates-hook-return-value",
270
- "function-expression-with-store-to-parameter",
271
- "global-jsx-tag-lowered-between-mutations",
272
- "hook-inside-logical-expression",
273
- "immutable-hooks",
274
- "inadvertent-mutability-readonly-class",
275
- "inadvertent-mutability-readonly-lambda",
276
- "infer-computed-delete",
277
- "infer-property-delete",
278
- "inner-memo-value-not-promoted-to-outer-scope-dynamic",
279
- "inner-memo-value-not-promoted-to-outer-scope-static",
280
- "issue852",
281
- "jsx-member-expression-tag-grouping",
282
- "jsx-member-expression",
283
- "jsx-spread",
284
- "lambda-capture-returned-alias",
285
- "method-call-computed",
286
- "method-call-fn-call",
287
- "nested-optional-member-expr",
288
- "nested-scopes-hook-call",
289
- "new-spread",
290
- "obj-literal-cached-in-if-else",
291
- "obj-literal-mutated-after-if-else",
292
- "obj-mutated-after-if-else-with-alias",
293
- "obj-mutated-after-if-else",
294
- "obj-mutated-after-nested-if-else-with-alias",
295
- "object-properties",
296
- "optional-call-chained",
297
- "optional-call-logical",
298
- "optional-call-simple",
299
- "optional-call-with-independently-memoizable-arg",
300
- "optional-call-with-optional-property-load",
301
- "optional-call",
302
- "optional-computed-load-static",
303
- "optional-computed-member-expression",
304
- "optional-member-expression-call-as-property",
305
- "optional-member-expression-with-optional-member-expr-as-property",
306
- "optional-member-expression",
307
- "optional-method-call",
308
- "optional-receiver-method-call",
309
- "optional-receiver-optional-method",
310
- "primitive-alias-mutate",
311
- "primitive-as-dep",
312
- "property-assignment",
313
- "property-call-spread",
314
- "reactive-dependencies-non-optional-properties-inside-optional-chain",
315
- "reactivity-analysis-reactive-via-mutation-of-computed-load",
316
- "reactivity-analysis-reactive-via-mutation-of-property-load",
317
- "reassigned-phi-in-returned-function-expression",
318
- "reassignment-conditional",
319
- "reassignment",
320
- "ref-current-aliased-not-added-to-dep-2",
321
- "ref-current-not-added-to-dep-2",
322
- "ref-in-effect",
323
- "regexp-literal",
324
- "remove-memoization-kitchen-sink",
325
- "repro-reassign-to-variable-without-mutable-range",
326
- "repro-scope-missing-mutable-range",
327
- "repro",
328
- "simple",
329
- "ssa-leave-case",
330
- "ssa-property-alias-alias-mutate-if",
331
- "ssa-property-alias-mutate-if",
332
- "ssa-property-alias-mutate-inside-if",
333
- "ssa-renaming-ternary-destruction-with-mutation",
334
- "ssa-renaming-ternary-with-mutation",
335
- "ssa-renaming-unconditional-with-mutation",
336
- "ssa-renaming-via-destructuring-with-mutation",
337
- "ssa-renaming-with-mutation",
338
- "switch-global-propertyload-case-test",
339
- "switch-non-final-default",
340
- "switch",
341
- "tagged-template-in-hook",
342
- "temporary-accessed-outside-scope",
343
- "temporary-at-start-of-value-block",
344
- "temporary-property-load-accessed-outside-scope",
345
- "timers",
346
- "todo-function-expression-captures-value-later-frozen",
347
- "uninitialized-declaration-in-reactive-scope",
348
- "unknown-hooks-do-not-assert",
349
- "unused-logical-assigned-to-variable",
350
- "unused-optional-method-assigned-to-variable",
351
- "unused-ternary-assigned-to-variable",
352
- "useEffect-arg-memoized",
353
- "useEffect-nested-lambdas",
354
- "useMemo-if-else-multiple-return",
355
- "useMemo-independently-memoizeable",
356
- "useMemo-named-function",
357
- "useMemo-return-empty",
358
- "useMemo-simple",
359
- "use-no-forget-module-level",
360
- "use-no-memo-module-level",
222
+ 'alias-computed-load',
223
+ 'allocating-primitive-as-dep',
224
+ 'allow-passing-refs-as-props',
225
+ 'array-at-closure',
226
+ 'array-at-effect',
227
+ 'array-at-mutate-after-capture',
228
+ 'array-join',
229
+ 'array-push-effect',
230
+ 'arrow-function-expr-gating-test',
231
+ 'assignment-in-nested-if',
232
+ 'await-side-effecting-promise',
233
+ 'await',
234
+ 'builtin-jsx-tag-lowered-between-mutations',
235
+ 'call-args-assignment',
236
+ 'call-args-destructuring-assignment',
237
+ 'call-spread',
238
+ 'call-with-independently-memoizable-arg',
239
+ 'capture-param-mutate',
240
+ 'capturing-fun-alias-captured-mutate-2',
241
+ 'capturing-fun-alias-captured-mutate-arr-2',
242
+ 'capturing-func-alias-captured-mutate-arr',
243
+ 'capturing-func-alias-captured-mutate',
244
+ 'capturing-func-alias-computed-mutate',
245
+ 'capturing-func-alias-mutate',
246
+ 'capturing-func-alias-receiver-computed-mutate',
247
+ 'capturing-func-alias-receiver-mutate',
248
+ 'capturing-func-simple-alias',
249
+ 'capturing-function-capture-ref-before-rename',
250
+ 'capturing-function-conditional-capture-mutate',
251
+ 'capturing-function-member-expr-arguments',
252
+ 'capturing-function-member-expr-call',
253
+ 'capturing-function-renamed-ref',
254
+ 'capturing-function-runs-inference',
255
+ 'capturing-function-shadow-captured',
256
+ 'capturing-reference-changes-type',
257
+ 'codegen-emit-imports-same-source',
258
+ 'codegen-emit-make-read-only',
259
+ 'computed-call-spread',
260
+ 'computed-load-primitive-as-dependency',
261
+ 'computed-store-alias',
262
+ 'constant-propagation-into-function-expressions',
263
+ 'destructuring-mixed-scope-declarations-and-locals',
264
+ 'destructuring-property-inference',
265
+ 'do-while-conditional-break',
266
+ 'do-while-early-unconditional-break',
267
+ 'fbt/fbt-params-complex-param-value',
268
+ 'function-expression-captures-value-later-frozen-jsx',
269
+ 'function-expression-maybe-mutates-hook-return-value',
270
+ 'function-expression-with-store-to-parameter',
271
+ 'global-jsx-tag-lowered-between-mutations',
272
+ 'hook-inside-logical-expression',
273
+ 'immutable-hooks',
274
+ 'inadvertent-mutability-readonly-class',
275
+ 'inadvertent-mutability-readonly-lambda',
276
+ 'infer-computed-delete',
277
+ 'infer-property-delete',
278
+ 'inner-memo-value-not-promoted-to-outer-scope-dynamic',
279
+ 'inner-memo-value-not-promoted-to-outer-scope-static',
280
+ 'issue852',
281
+ 'jsx-member-expression-tag-grouping',
282
+ 'jsx-member-expression',
283
+ 'jsx-spread',
284
+ 'lambda-capture-returned-alias',
285
+ 'method-call-computed',
286
+ 'method-call-fn-call',
287
+ 'nested-optional-member-expr',
288
+ 'nested-scopes-hook-call',
289
+ 'new-spread',
290
+ 'obj-literal-cached-in-if-else',
291
+ 'obj-literal-mutated-after-if-else',
292
+ 'obj-mutated-after-if-else-with-alias',
293
+ 'obj-mutated-after-if-else',
294
+ 'obj-mutated-after-nested-if-else-with-alias',
295
+ 'object-properties',
296
+ 'optional-call-chained',
297
+ 'optional-call-logical',
298
+ 'optional-call-simple',
299
+ 'optional-call-with-independently-memoizable-arg',
300
+ 'optional-call-with-optional-property-load',
301
+ 'optional-call',
302
+ 'optional-computed-load-static',
303
+ 'optional-computed-member-expression',
304
+ 'optional-member-expression-call-as-property',
305
+ 'optional-member-expression-with-optional-member-expr-as-property',
306
+ 'optional-member-expression',
307
+ 'optional-method-call',
308
+ 'optional-receiver-method-call',
309
+ 'optional-receiver-optional-method',
310
+ 'primitive-alias-mutate',
311
+ 'primitive-as-dep',
312
+ 'property-assignment',
313
+ 'property-call-spread',
314
+ 'reactive-dependencies-non-optional-properties-inside-optional-chain',
315
+ 'reactivity-analysis-reactive-via-mutation-of-computed-load',
316
+ 'reactivity-analysis-reactive-via-mutation-of-property-load',
317
+ 'reassigned-phi-in-returned-function-expression',
318
+ 'reassignment-conditional',
319
+ 'reassignment',
320
+ 'ref-current-aliased-not-added-to-dep-2',
321
+ 'ref-current-not-added-to-dep-2',
322
+ 'ref-in-effect',
323
+ 'regexp-literal',
324
+ 'remove-memoization-kitchen-sink',
325
+ 'repro-reassign-to-variable-without-mutable-range',
326
+ 'repro-scope-missing-mutable-range',
327
+ 'repro',
328
+ 'simple',
329
+ 'ssa-leave-case',
330
+ 'ssa-property-alias-alias-mutate-if',
331
+ 'ssa-property-alias-mutate-if',
332
+ 'ssa-property-alias-mutate-inside-if',
333
+ 'ssa-renaming-ternary-destruction-with-mutation',
334
+ 'ssa-renaming-ternary-with-mutation',
335
+ 'ssa-renaming-unconditional-with-mutation',
336
+ 'ssa-renaming-via-destructuring-with-mutation',
337
+ 'ssa-renaming-with-mutation',
338
+ 'switch-global-propertyload-case-test',
339
+ 'switch-non-final-default',
340
+ 'switch',
341
+ 'tagged-template-in-hook',
342
+ 'temporary-accessed-outside-scope',
343
+ 'temporary-at-start-of-value-block',
344
+ 'temporary-property-load-accessed-outside-scope',
345
+ 'timers',
346
+ 'todo-function-expression-captures-value-later-frozen',
347
+ 'uninitialized-declaration-in-reactive-scope',
348
+ 'unknown-hooks-do-not-assert',
349
+ 'unused-logical-assigned-to-variable',
350
+ 'unused-optional-method-assigned-to-variable',
351
+ 'unused-ternary-assigned-to-variable',
352
+ 'useEffect-arg-memoized',
353
+ 'useEffect-nested-lambdas',
354
+ 'useMemo-if-else-multiple-return',
355
+ 'useMemo-independently-memoizeable',
356
+ 'useMemo-named-function',
357
+ 'useMemo-return-empty',
358
+ 'useMemo-simple',
359
+ 'use-no-forget-module-level',
360
+ 'use-no-memo-module-level',
361
// defines multiple functions
362
- "alias-while",
363
- "babel-existing-react-import",
364
- "babel-existing-react-kitchensink-import",
365
- "call",
366
- "codegen-instrument-forget-gating-test",
367
- "codegen-instrument-forget-test",
368
- "conditional-on-mutable",
369
- "constructor",
370
- "frozen-after-alias",
371
- "gating-test-export-default-function",
372
- "gating-test-export-function-and-default",
373
- "gating-test-export-function",
374
- "gating-test",
375
- "gating-with-hoisted-type-reference.flow",
376
- "hook-call",
377
- "hooks-freeze-arguments",
378
- "hooks-freeze-possibly-mutable-arguments",
379
- "independent-across-if",
380
- "independent",
381
- "interdependent-across-if",
382
- "interdependent",
383
- "multi-arrow-expr-export-gating-test",
384
- "multi-arrow-expr-gating-test",
385
- "mutable-liverange-loop",
386
- "sequence-expression",
387
- "ssa-call-jsx-2",
388
- "ssa-call-jsx",
389
- "ssa-newexpression",
390
- "ssa-shadowing",
391
- "template-literal",
392
- "multi-arrow-expr-export-default-gating-test",
362
+ 'alias-while',
363
+ 'babel-existing-react-import',
364
+ 'babel-existing-react-kitchensink-import',
365
+ 'call',
366
+ 'codegen-instrument-forget-gating-test',
367
+ 'codegen-instrument-forget-test',
368
+ 'conditional-on-mutable',
369
+ 'constructor',
370
+ 'frozen-after-alias',
371
+ 'gating-test-export-default-function',
372
+ 'gating-test-export-function-and-default',
373
+ 'gating-test-export-function',
374
+ 'gating-test',
375
+ 'gating-with-hoisted-type-reference.flow',
376
+ 'hook-call',
377
+ 'hooks-freeze-arguments',
378
+ 'hooks-freeze-possibly-mutable-arguments',
379
+ 'independent-across-if',
380
+ 'independent',
381
+ 'interdependent-across-if',
382
+ 'interdependent',
383
+ 'multi-arrow-expr-export-gating-test',
384
+ 'multi-arrow-expr-gating-test',
385
+ 'mutable-liverange-loop',
386
+ 'sequence-expression',
387
+ 'ssa-call-jsx-2',
388
+ 'ssa-call-jsx',
389
+ 'ssa-newexpression',
390
+ 'ssa-shadowing',
391
+ 'template-literal',
392
+ 'multi-arrow-expr-export-default-gating-test',
393
394
// TODO: we should be able to support these
395
- "component-declaration-basic.flow",
396
- "hook-declaration-basic.flow",
397
- "nested-function-with-param-as-captured-dep",
398
- "deeply-nested-function-expressions-with-params",
399
- "readonly-object-method-calls",
400
- "readonly-object-method-calls-mutable-lambda",
395
+ 'component-declaration-basic.flow',
396
+ 'hook-declaration-basic.flow',
397
+ 'nested-function-with-param-as-captured-dep',
398
+ 'deeply-nested-function-expressions-with-params',
399
+ 'readonly-object-method-calls',
400
+ 'readonly-object-method-calls-mutable-lambda',
401
402
// TODO: we probably want to always skip these
403
- "rules-of-hooks/rules-of-hooks-0592bd574811",
404
- "rules-of-hooks/rules-of-hooks-0e2214abc294",
405
- "rules-of-hooks/rules-of-hooks-1ff6c3fbbc94",
406
- "rules-of-hooks/rules-of-hooks-23dc7fffde57",
407
- "rules-of-hooks/rules-of-hooks-2bec02ac982b",
408
- "rules-of-hooks/rules-of-hooks-2e405c78cb80",
409
- "rules-of-hooks/rules-of-hooks-33a6e23edac1",
410
- "rules-of-hooks/rules-of-hooks-347b0dae66f1",
411
- "rules-of-hooks/rules-of-hooks-485bf041f55f",
412
- "rules-of-hooks/rules-of-hooks-4f6c78a14bf7",
413
- "rules-of-hooks/rules-of-hooks-7e52f5eec669",
414
- "rules-of-hooks/rules-of-hooks-844a496db20b",
415
- "rules-of-hooks/rules-of-hooks-8f1c2c3f71c9",
416
- "rules-of-hooks/rules-of-hooks-9a47e97b5d13",
417
- "rules-of-hooks/rules-of-hooks-9d7879272ff6",
418
- "rules-of-hooks/rules-of-hooks-c1e8c7f4c191",
419
- "rules-of-hooks/rules-of-hooks-c5d1f3143c4c",
420
- "rules-of-hooks/rules-of-hooks-cfdfe5572fc7",
421
- "rules-of-hooks/rules-of-hooks-df4d750736f3",
422
- "rules-of-hooks/rules-of-hooks-dfde14171fcd",
423
- "rules-of-hooks/rules-of-hooks-e5dd6caf4084",
424
- "rules-of-hooks/rules-of-hooks-e66a744cffbe",
425
- "rules-of-hooks/rules-of-hooks-eacfcaa6ef89",
426
- "rules-of-hooks/rules-of-hooks-fe6042f7628b",
427
- "infer-function-assignment",
428
- "infer-functions-component-with-jsx",
429
- "infer-function-forwardRef",
430
- "infer-function-React-memo",
431
- "infer-functions-component-with-hook-call",
432
- "infer-functions-component-with-jsx",
433
- "infer-functions-hook-with-hook-call",
434
- "infer-functions-hook-with-jsx",
435
- "infer-function-expression-component",
436
- "infer-function-expression-React-memo-gating",
437
- "infer-skip-components-without-hooks-or-jsx",
438
- "class-component-with-render-helper",
439
- "fbt/fbtparam-with-jsx-element-content",
440
- "fbt/fbtparam-text-must-use-expression-container",
441
- "fbt/fbtparam-with-jsx-fragment-value",
442
- "fbt/fbt-preserve-jsxtext",
443
- "todo.useContext-mutate-context-in-callback",
444
- "loop-unused-let",
445
- "reanimated-no-memo-arg",
403
+ 'rules-of-hooks/rules-of-hooks-0592bd574811',
404
+ 'rules-of-hooks/rules-of-hooks-0e2214abc294',
405
+ 'rules-of-hooks/rules-of-hooks-1ff6c3fbbc94',
406
+ 'rules-of-hooks/rules-of-hooks-23dc7fffde57',
407
+ 'rules-of-hooks/rules-of-hooks-2bec02ac982b',
408
+ 'rules-of-hooks/rules-of-hooks-2e405c78cb80',
409
+ 'rules-of-hooks/rules-of-hooks-33a6e23edac1',
410
+ 'rules-of-hooks/rules-of-hooks-347b0dae66f1',
411
+ 'rules-of-hooks/rules-of-hooks-485bf041f55f',
412
+ 'rules-of-hooks/rules-of-hooks-4f6c78a14bf7',
413
+ 'rules-of-hooks/rules-of-hooks-7e52f5eec669',
414
+ 'rules-of-hooks/rules-of-hooks-844a496db20b',
415
+ 'rules-of-hooks/rules-of-hooks-8f1c2c3f71c9',
416
+ 'rules-of-hooks/rules-of-hooks-9a47e97b5d13',
417
+ 'rules-of-hooks/rules-of-hooks-9d7879272ff6',
418
+ 'rules-of-hooks/rules-of-hooks-c1e8c7f4c191',
419
+ 'rules-of-hooks/rules-of-hooks-c5d1f3143c4c',
420
+ 'rules-of-hooks/rules-of-hooks-cfdfe5572fc7',
421
+ 'rules-of-hooks/rules-of-hooks-df4d750736f3',
422
+ 'rules-of-hooks/rules-of-hooks-dfde14171fcd',
423
+ 'rules-of-hooks/rules-of-hooks-e5dd6caf4084',
424
+ 'rules-of-hooks/rules-of-hooks-e66a744cffbe',
425
+ 'rules-of-hooks/rules-of-hooks-eacfcaa6ef89',
426
+ 'rules-of-hooks/rules-of-hooks-fe6042f7628b',
427
+ 'infer-function-assignment',
428
+ 'infer-functions-component-with-jsx',
429
+ 'infer-function-forwardRef',
430
+ 'infer-function-React-memo',
431
+ 'infer-functions-component-with-hook-call',
432
+ 'infer-functions-component-with-jsx',
433
+ 'infer-functions-hook-with-hook-call',
434
+ 'infer-functions-hook-with-jsx',
435
+ 'infer-function-expression-component',
436
+ 'infer-function-expression-React-memo-gating',
437
+ 'infer-skip-components-without-hooks-or-jsx',
438
+ 'class-component-with-render-helper',
439
+ 'fbt/fbtparam-with-jsx-element-content',
440
+ 'fbt/fbtparam-text-must-use-expression-container',
441
+ 'fbt/fbtparam-with-jsx-fragment-value',
442
+ 'fbt/fbt-preserve-jsxtext',
443
+ 'todo.useContext-mutate-context-in-callback',
444
+ 'loop-unused-let',
445
+ 'reanimated-no-memo-arg',
446
447
- "userspace-use-memo-cache",
448
- "transitive-freeze-function-expressions",
447
+ 'userspace-use-memo-cache',
448
+ 'transitive-freeze-function-expressions',
449
450
// nothing to compile/run
451
- "repro-no-gating-import-without-compiled-functions",
451
+ 'repro-no-gating-import-without-compiled-functions',
452
453
// TODOs
454
- "rules-of-hooks/todo.bail.rules-of-hooks-279ac76f53af",
455
- "rules-of-hooks/todo.bail.rules-of-hooks-28a78701970c",
456
- "rules-of-hooks/todo.bail.rules-of-hooks-3d692676194b",
457
- "rules-of-hooks/todo.bail.rules-of-hooks-6949b255e7eb",
458
- "rules-of-hooks/todo.bail.rules-of-hooks-8503ca76d6f8",
459
- "rules-of-hooks/todo.bail.rules-of-hooks-e0a5db3ae21e",
460
- "rules-of-hooks/todo.bail.rules-of-hooks-e9f9bac89f8f",
461
- "rules-of-hooks/todo.bail.rules-of-hooks-fadd52c1e460",
462
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-0a1dbff27ba0",
463
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-0de1224ce64b",
464
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-191029ac48c8",
465
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-206e2811c87c",
466
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-28a7111f56a7",
467
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-2c51251df67a",
468
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-449a37146a83",
469
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-5a7ac9a6e8fa",
470
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-76a74b4666e9",
471
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-8303403b8e4c",
472
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-99b5c750d1d1",
473
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-9c79feec4b9b",
474
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-a63fd4f9dcc0",
475
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-acb56658fe7e",
476
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-c59788ef5676",
477
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-d842d36db450",
478
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-d952b82c2597",
479
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-ddeca9708b63",
480
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-e675f0a672d8",
481
- "rules-of-hooks/todo.invalid.invalid-rules-of-hooks-e69ffce323c3",
482
- "todo.unnecessary-lambda-memoization",
483
- "rules-of-hooks/rules-of-hooks-93dc5d5e538a",
484
- "rules-of-hooks/rules-of-hooks-69521d94fa03",
454
+ 'rules-of-hooks/todo.bail.rules-of-hooks-279ac76f53af',
455
+ 'rules-of-hooks/todo.bail.rules-of-hooks-28a78701970c',
456
+ 'rules-of-hooks/todo.bail.rules-of-hooks-3d692676194b',
457
+ 'rules-of-hooks/todo.bail.rules-of-hooks-6949b255e7eb',
458
+ 'rules-of-hooks/todo.bail.rules-of-hooks-8503ca76d6f8',
459
+ 'rules-of-hooks/todo.bail.rules-of-hooks-e0a5db3ae21e',
460
+ 'rules-of-hooks/todo.bail.rules-of-hooks-e9f9bac89f8f',
461
+ 'rules-of-hooks/todo.bail.rules-of-hooks-fadd52c1e460',
462
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-0a1dbff27ba0',
463
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-0de1224ce64b',
464
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-191029ac48c8',
465
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-206e2811c87c',
466
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-28a7111f56a7',
467
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-2c51251df67a',
468
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-449a37146a83',
469
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-5a7ac9a6e8fa',
470
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-76a74b4666e9',
471
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-8303403b8e4c',
472
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-99b5c750d1d1',
473
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-9c79feec4b9b',
474
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-a63fd4f9dcc0',
475
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-acb56658fe7e',
476
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-c59788ef5676',
477
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-d842d36db450',
478
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-d952b82c2597',
479
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-ddeca9708b63',
480
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-e675f0a672d8',
481
+ 'rules-of-hooks/todo.invalid.invalid-rules-of-hooks-e69ffce323c3',
482
+ 'todo.unnecessary-lambda-memoization',
483
+ 'rules-of-hooks/rules-of-hooks-93dc5d5e538a',
484
+ 'rules-of-hooks/rules-of-hooks-69521d94fa03',
485
486
// bugs
487
- "bug-invalid-hoisting-functionexpr",
488
- "original-reactive-scopes-fork/bug-nonmutating-capture-in-unsplittable-memo-block",
489
- "original-reactive-scopes-fork/bug-hoisted-declaration-with-scope",
490
- "bug-codegen-inline-iife",
487
+ 'bug-invalid-hoisting-functionexpr',
488
+ 'original-reactive-scopes-fork/bug-nonmutating-capture-in-unsplittable-memo-block',
489
+ 'original-reactive-scopes-fork/bug-hoisted-declaration-with-scope',
490
+ 'bug-codegen-inline-iife',
491
492
// 'react-compiler-runtime' not yet supported
493
- "flag-enable-emit-hook-guards",
493
+ 'flag-enable-emit-hook-guards',
494
495
- "fast-refresh-refresh-on-const-changes-dev",
496
- "useState-pruned-dependency-change-detect",
497
- "useState-unpruned-dependency",
498
- "useState-and-other-hook-unpruned-dependency",
499
- "change-detect-reassign",
495
+ 'fast-refresh-refresh-on-const-changes-dev',
496
+ 'useState-pruned-dependency-change-detect',
497
+ 'useState-unpruned-dependency',
498
+ 'useState-and-other-hook-unpruned-dependency',
499
+ 'change-detect-reassign',
500
501
// needs to be executed as a module
502
- "meta-property",
502
+ 'meta-property',
503
504
- "todo.invalid-nested-function-reassign-local-variable-in-effect",
504
+ 'todo.invalid-nested-function-reassign-local-variable-in-effect',
505
]);
506
507
export default skipFilter;
compiler/packages/snap/src/compiler.ts
+119
-121
@@ -5,129 +5,129 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import type * as BabelCore from "@babel/core";
9
-import { transformFromAstSync } from "@babel/core";
8
+import type * as BabelCore from '@babel/core';
9
+import {transformFromAstSync} from '@babel/core';
10
11
-import * as BabelParser from "@babel/parser";
12
-import { NodePath } from "@babel/traverse";
13
-import * as t from "@babel/types";
14
-import assert from "assert";
11
+import * as BabelParser from '@babel/parser';
12
+import {NodePath} from '@babel/traverse';
13
+import * as t from '@babel/types';
14
+import assert from 'assert';
15
import type {
16
CompilationMode,
17
Logger,
18
LoggerEvent,
19
PanicThresholdOptions,
20
PluginOptions,
21
-} from "babel-plugin-react-compiler/src/Entrypoint";
22
-import type { Effect, ValueKind } from "babel-plugin-react-compiler/src/HIR";
23
-import type { parseConfigPragma as ParseConfigPragma } from "babel-plugin-react-compiler/src/HIR/Environment";
24
-import * as HermesParser from "hermes-parser";
25
-import invariant from "invariant";
26
-import path from "path";
27
-import prettier from "prettier";
28
-import SproutTodoFilter from "./SproutTodoFilter";
29
-import { isExpectError } from "./fixture-utils";
30
-export function parseLanguage(source: string): "flow" | "typescript" {
31
- return source.indexOf("@flow") !== -1 ? "flow" : "typescript";
21
+} from 'babel-plugin-react-compiler/src/Entrypoint';
22
+import type {Effect, ValueKind} from 'babel-plugin-react-compiler/src/HIR';
23
+import type {parseConfigPragma as ParseConfigPragma} from 'babel-plugin-react-compiler/src/HIR/Environment';
24
+import * as HermesParser from 'hermes-parser';
25
+import invariant from 'invariant';
26
+import path from 'path';
27
+import prettier from 'prettier';
28
+import SproutTodoFilter from './SproutTodoFilter';
29
+import {isExpectError} from './fixture-utils';
30
+export function parseLanguage(source: string): 'flow' | 'typescript' {
31
+ return source.indexOf('@flow') !== -1 ? 'flow' : 'typescript';
32
}
33
34
function makePluginOptions(
35
firstLine: string,
36
- parseConfigPragmaFn: typeof ParseConfigPragma
37
-): [PluginOptions, Array<{ filename: string | null; event: LoggerEvent }>] {
36
+ parseConfigPragmaFn: typeof ParseConfigPragma,
37
+): [PluginOptions, Array<{filename: string | null; event: LoggerEvent}>] {
38
let gating = null;
39
let enableEmitInstrumentForget = null;
40
let enableEmitFreeze = null;
41
let enableEmitHookGuards = null;
42
- let compilationMode: CompilationMode = "all";
42
+ let compilationMode: CompilationMode = 'all';
43
let runtimeModule = null;
44
- let panicThreshold: PanicThresholdOptions = "all_errors";
44
+ let panicThreshold: PanicThresholdOptions = 'all_errors';
45
let hookPattern: string | null = null;
46
// TODO(@mofeiZ) rewrite snap fixtures to @validatePreserveExistingMemo:false
47
let validatePreserveExistingMemoizationGuarantees = false;
48
let enableChangeDetectionForDebugging = null;
49
let customMacros = null;
50
51
- if (firstLine.indexOf("@compilationMode(annotation)") !== -1) {
51
+ if (firstLine.indexOf('@compilationMode(annotation)') !== -1) {
52
assert(
53
- compilationMode === "all",
54
- "Cannot set @compilationMode(..) more than once"
53
+ compilationMode === 'all',
54
+ 'Cannot set @compilationMode(..) more than once',
55
);
56
- compilationMode = "annotation";
56
+ compilationMode = 'annotation';
57
}
58
- if (firstLine.indexOf("@compilationMode(infer)") !== -1) {
58
+ if (firstLine.indexOf('@compilationMode(infer)') !== -1) {
59
assert(
60
- compilationMode === "all",
61
- "Cannot set @compilationMode(..) more than once"
60
+ compilationMode === 'all',
61
+ 'Cannot set @compilationMode(..) more than once',
62
);
63
- compilationMode = "infer";
63
+ compilationMode = 'infer';
64
}
65
66
- if (firstLine.includes("@gating")) {
66
+ if (firstLine.includes('@gating')) {
67
gating = {
68
- source: "ReactForgetFeatureFlag",
69
- importSpecifierName: "isForgetEnabled_Fixtures",
68
+ source: 'ReactForgetFeatureFlag',
69
+ importSpecifierName: 'isForgetEnabled_Fixtures',
70
};
71
}
72
- if (firstLine.includes("@instrumentForget")) {
72
+ if (firstLine.includes('@instrumentForget')) {
73
enableEmitInstrumentForget = {
74
fn: {
75
- source: "react-compiler-runtime",
76
- importSpecifierName: "useRenderCounter",
75
+ source: 'react-compiler-runtime',
76
+ importSpecifierName: 'useRenderCounter',
77
},
78
gating: {
79
- source: "react-compiler-runtime",
80
- importSpecifierName: "shouldInstrument",
79
+ source: 'react-compiler-runtime',
80
+ importSpecifierName: 'shouldInstrument',
81
},
82
- globalGating: "__DEV__",
82
+ globalGating: '__DEV__',
83
};
84
}
85
- if (firstLine.includes("@enableEmitFreeze")) {
85
+ if (firstLine.includes('@enableEmitFreeze')) {
86
enableEmitFreeze = {
87
- source: "react-compiler-runtime",
88
- importSpecifierName: "makeReadOnly",
87
+ source: 'react-compiler-runtime',
88
+ importSpecifierName: 'makeReadOnly',
89
};
90
}
91
- if (firstLine.includes("@enableEmitHookGuards")) {
91
+ if (firstLine.includes('@enableEmitHookGuards')) {
92
enableEmitHookGuards = {
93
- source: "react-compiler-runtime",
94
- importSpecifierName: "$dispatcherGuard",
93
+ source: 'react-compiler-runtime',
94
+ importSpecifierName: '$dispatcherGuard',
95
};
96
}
97
const runtimeModuleMatch = /@runtimeModule="([^"]+)"/.exec(firstLine);
98
if (runtimeModuleMatch) {
99
runtimeModule = runtimeModuleMatch[1];
100
}
101
- if (firstLine.includes("@panicThreshold(none)")) {
102
- panicThreshold = "none";
101
+ if (firstLine.includes('@panicThreshold(none)')) {
102
+ panicThreshold = 'none';
103
}
104
105
let eslintSuppressionRules: Array<string> | null = null;
106
const eslintSuppressionMatch = /@eslintSuppressionRules\(([^)]+)\)/.exec(
107
- firstLine
107
+ firstLine,
108
);
109
if (eslintSuppressionMatch != null) {
110
- eslintSuppressionRules = eslintSuppressionMatch[1].split("|");
110
+ eslintSuppressionRules = eslintSuppressionMatch[1].split('|');
111
}
112
113
let flowSuppressions: boolean = false;
114
- if (firstLine.includes("@enableFlowSuppressions")) {
114
+ if (firstLine.includes('@enableFlowSuppressions')) {
115
flowSuppressions = true;
116
}
117
118
let ignoreUseNoForget: boolean = false;
119
- if (firstLine.includes("@ignoreUseNoForget")) {
119
+ if (firstLine.includes('@ignoreUseNoForget')) {
120
ignoreUseNoForget = true;
121
}
122
123
- if (firstLine.includes("@validatePreserveExistingMemoizationGuarantees")) {
123
+ if (firstLine.includes('@validatePreserveExistingMemoizationGuarantees')) {
124
validatePreserveExistingMemoizationGuarantees = true;
125
}
126
127
- if (firstLine.includes("@enableChangeDetectionForDebugging")) {
127
+ if (firstLine.includes('@enableChangeDetectionForDebugging')) {
128
enableChangeDetectionForDebugging = {
129
- source: "react-compiler-runtime",
130
- importSpecifierName: "$structuralCheck",
129
+ source: 'react-compiler-runtime',
130
+ importSpecifierName: '$structuralCheck',
131
};
132
}
133
const hookPatternMatch = /@hookPattern:"([^"]+)"/.exec(firstLine);
@@ -137,9 +137,9 @@ function makePluginOptions(
137
hookPatternMatch[1].trim().length > 0
138
) {
139
hookPattern = hookPatternMatch[1].trim();
140
- } else if (firstLine.includes("@hookPattern")) {
140
+ } else if (firstLine.includes('@hookPattern')) {
141
throw new Error(
142
- 'Invalid @hookPattern:"..." pragma, must contain the prefix between balanced double quotes eg @hookPattern:"pattern"'
142
+ 'Invalid @hookPattern:"..." pragma, must contain the prefix between balanced double quotes eg @hookPattern:"pattern"',
143
);
144
}
145
@@ -150,17 +150,17 @@ function makePluginOptions(
150
customMacrosMatch[1].trim().length > 0
151
) {
152
customMacros = customMacrosMatch[1]
153
- .split(" ")
154
- .map((s) => s.trim())
155
- .filter((s) => s.length > 0);
153
+ .split(' ')
154
+ .map(s => s.trim())
155
+ .filter(s => s.length > 0);
156
}
157
158
- let logs: Array<{ filename: string | null; event: LoggerEvent }> = [];
158
+ let logs: Array<{filename: string | null; event: LoggerEvent}> = [];
159
let logger: Logger | null = null;
160
- if (firstLine.includes("@logger")) {
160
+ if (firstLine.includes('@logger')) {
161
logger = {
162
logEvent(filename: string | null, event: LoggerEvent): void {
163
- logs.push({ filename, event });
163
+ logs.push({filename, event});
164
},
165
};
166
}
@@ -171,28 +171,28 @@ function makePluginOptions(
171
...config,
172
customHooks: new Map([
173
[
174
- "useFreeze",
174
+ 'useFreeze',
175
{
176
- valueKind: "frozen" as ValueKind,
177
- effectKind: "freeze" as Effect,
176
+ valueKind: 'frozen' as ValueKind,
177
+ effectKind: 'freeze' as Effect,
178
transitiveMixedData: false,
179
noAlias: false,
180
},
181
],
182
[
183
- "useFragment",
183
+ 'useFragment',
184
{
185
- valueKind: "frozen" as ValueKind,
186
- effectKind: "freeze" as Effect,
185
+ valueKind: 'frozen' as ValueKind,
186
+ effectKind: 'freeze' as Effect,
187
transitiveMixedData: true,
188
noAlias: true,
189
},
190
],
191
[
192
- "useNoAlias",
192
+ 'useNoAlias',
193
{
194
- valueKind: "mutable" as ValueKind,
195
- effectKind: "read" as Effect,
194
+ valueKind: 'mutable' as ValueKind,
195
+ effectKind: 'read' as Effect,
196
transitiveMixedData: false,
197
noAlias: true,
198
},
@@ -225,38 +225,38 @@ function makePluginOptions(
225
export function parseInput(
226
input: string,
227
filename: string,
228
- language: "flow" | "typescript"
228
+ language: 'flow' | 'typescript',
229
): BabelCore.types.File {
230
// Extract the first line to quickly check for custom test directives
231
- if (language === "flow") {
231
+ if (language === 'flow') {
232
return HermesParser.parse(input, {
233
babel: true,
234
- flow: "all",
234
+ flow: 'all',
235
sourceFilename: filename,
236
- sourceType: "module",
236
+ sourceType: 'module',
237
enableExperimentalComponentSyntax: true,
238
});
239
} else {
240
return BabelParser.parse(input, {
241
sourceFilename: filename,
242
- plugins: ["typescript", "jsx"],
243
- sourceType: "module",
242
+ plugins: ['typescript', 'jsx'],
243
+ sourceType: 'module',
244
});
245
}
246
}
247
248
function getEvaluatorPresets(
249
- language: "typescript" | "flow"
249
+ language: 'typescript' | 'flow',
250
): Array<BabelCore.PluginItem> {
251
const presets: Array<BabelCore.PluginItem> = [
252
{
253
- plugins: ["babel-plugin-fbt", "babel-plugin-fbt-runtime"],
253
+ plugins: ['babel-plugin-fbt', 'babel-plugin-fbt-runtime'],
254
},
255
];
256
presets.push(
257
- language === "typescript"
257
+ language === 'typescript'
258
? [
259
- "@babel/preset-typescript",
259
+ '@babel/preset-typescript',
260
{
261
/**
262
* onlyRemoveTypeImports needs to be set as fbt imports
@@ -268,16 +268,16 @@ function getEvaluatorPresets(
268
onlyRemoveTypeImports: true,
269
},
270
]
271
- : "@babel/preset-flow"
271
+ : '@babel/preset-flow',
272
);
273
274
presets.push({
275
- plugins: ["@babel/plugin-syntax-jsx"],
275
+ plugins: ['@babel/plugin-syntax-jsx'],
276
});
277
presets.push(
278
- ["@babel/preset-react", { throwIfNamespace: false }],
278
+ ['@babel/preset-react', {throwIfNamespace: false}],
279
{
280
- plugins: ["@babel/plugin-transform-modules-commonjs"],
280
+ plugins: ['@babel/plugin-transform-modules-commonjs'],
281
},
282
{
283
plugins: [
@@ -285,16 +285,16 @@ function getEvaluatorPresets(
285
return {
286
visitor: {
287
CallExpression(path: NodePath<t.CallExpression>) {
288
- const { callee } = path.node;
289
- if (callee.type === "Identifier" && callee.name === "require") {
288
+ const {callee} = path.node;
289
+ if (callee.type === 'Identifier' && callee.name === 'require') {
290
const arg = path.node.arguments[0];
291
- if (arg.type === "StringLiteral") {
291
+ if (arg.type === 'StringLiteral') {
292
// rewrite to use relative import as eval happens in
293
// sprout/evaluator.ts
294
- if (arg.value === "shared-runtime") {
295
- arg.value = "./shared-runtime";
296
- } else if (arg.value === "ReactForgetFeatureFlag") {
297
- arg.value = "./ReactForgetFeatureFlag";
294
+ if (arg.value === 'shared-runtime') {
295
+ arg.value = './shared-runtime';
296
+ } else if (arg.value === 'ReactForgetFeatureFlag') {
297
+ arg.value = './ReactForgetFeatureFlag';
298
}
299
}
300
}
@@ -303,21 +303,21 @@ function getEvaluatorPresets(
303
};
304
},
305
],
306
- }
306
+ },
307
);
308
return presets;
309
}
310
async function format(
311
inputCode: string,
312
- language: "typescript" | "flow"
312
+ language: 'typescript' | 'flow',
313
): Promise<string> {
314
return await prettier.format(inputCode, {
315
semi: true,
316
- parser: language === "typescript" ? "babel-ts" : "flow",
316
+ parser: language === 'typescript' ? 'babel-ts' : 'flow',
317
});
318
}
319
-const TypescriptEvaluatorPresets = getEvaluatorPresets("typescript");
320
-const FlowEvaluatorPresets = getEvaluatorPresets("flow");
319
+const TypescriptEvaluatorPresets = getEvaluatorPresets('typescript');
320
+const FlowEvaluatorPresets = getEvaluatorPresets('flow');
321
322
export type TransformResult = {
323
forgetOutput: string;
@@ -333,25 +333,23 @@ export async function transformFixtureInput(
333
fixturePath: string,
334
parseConfigPragmaFn: typeof ParseConfigPragma,
335
plugin: BabelCore.PluginObj,
336
- includeEvaluator: boolean
337
-): Promise<
338
- { kind: "ok"; value: TransformResult } | { kind: "err"; msg: string }
339
-> {
336
+ includeEvaluator: boolean,
337
+): Promise<{kind: 'ok'; value: TransformResult} | {kind: 'err'; msg: string}> {
338
// Extract the first line to quickly check for custom test directives
341
- const firstLine = input.substring(0, input.indexOf("\n"));
339
+ const firstLine = input.substring(0, input.indexOf('\n'));
340
341
const language = parseLanguage(firstLine);
342
// Preserve file extension as it determines typescript's babel transform
343
// mode (e.g. stripping types, parsing rules for brackets)
344
const filename =
347
- path.basename(fixturePath) + (language === "typescript" ? ".ts" : "");
345
+ path.basename(fixturePath) + (language === 'typescript' ? '.ts' : '');
346
const inputAst = parseInput(input, filename, language);
347
// Give babel transforms an absolute path as relative paths get prefixed
348
// with `cwd`, which is different across machines
351
- const virtualFilepath = "/" + filename;
349
+ const virtualFilepath = '/' + filename;
350
351
const presets =
354
- language === "typescript"
352
+ language === 'typescript'
353
? TypescriptEvaluatorPresets
354
: FlowEvaluatorPresets;
355
@@ -365,10 +363,10 @@ export async function transformFixtureInput(
363
retainLines: true,
364
plugins: [
365
[plugin, options],
368
- "babel-plugin-fbt",
369
- "babel-plugin-fbt-runtime",
366
+ 'babel-plugin-fbt',
367
+ 'babel-plugin-fbt-runtime',
368
],
371
- sourceType: "module",
369
+ sourceType: 'module',
370
ast: includeEvaluator,
371
cloneInputAst: includeEvaluator,
372
configFile: false,
@@ -376,7 +374,7 @@ export async function transformFixtureInput(
374
});
375
invariant(
376
forgetResult?.code != null,
379
- "Expected BabelPluginReactForget to codegen successfully."
377
+ 'Expected BabelPluginReactForget to codegen successfully.',
378
);
379
const forgetCode = forgetResult.code;
380
let evaluatorCode = null;
@@ -390,7 +388,7 @@ export async function transformFixtureInput(
388
try {
389
invariant(
390
forgetResult?.ast != null,
393
- "Expected BabelPluginReactForget ast."
391
+ 'Expected BabelPluginReactForget ast.',
392
);
393
const result = transformFromAstSync(forgetResult.ast, forgetCode, {
394
presets,
@@ -400,16 +398,16 @@ export async function transformFixtureInput(
398
});
399
if (result?.code == null) {
400
return {
403
- kind: "err",
404
- msg: "Unexpected error in forget transform pipeline - no code emitted",
401
+ kind: 'err',
402
+ msg: 'Unexpected error in forget transform pipeline - no code emitted',
403
};
404
} else {
405
forgetEval = result.code;
406
}
407
} catch (e) {
408
return {
411
- kind: "err",
412
- msg: "Unexpected error in Forget transform pipeline: " + e.message,
409
+ kind: 'err',
410
+ msg: 'Unexpected error in Forget transform pipeline: ' + e.message,
411
};
412
}
413
@@ -427,16 +425,16 @@ export async function transformFixtureInput(
425
426
if (result?.code == null) {
427
return {
430
- kind: "err",
431
- msg: "Unexpected error in non-forget transform pipeline - no code emitted",
428
+ kind: 'err',
429
+ msg: 'Unexpected error in non-forget transform pipeline - no code emitted',
430
};
431
} else {
432
originalEval = result.code;
433
}
434
} catch (e) {
435
return {
438
- kind: "err",
439
- msg: "Unexpected error in non-forget transform pipeline: " + e.message,
436
+ kind: 'err',
437
+ msg: 'Unexpected error in non-forget transform pipeline: ' + e.message,
438
};
439
}
440
evaluatorCode = {
@@ -448,13 +446,13 @@ export async function transformFixtureInput(
446
let formattedLogs = null;
447
if (logs.length !== 0) {
448
formattedLogs = logs
451
- .map(({ event }) => {
449
+ .map(({event}) => {
450
return JSON.stringify(event);
451
})
454
- .join("\n");
452
+ .join('\n');
453
}
454
return {
457
- kind: "ok",
455
+ kind: 'ok',
456
value: {
457
forgetOutput,
458
logs: formattedLogs,
compiler/packages/snap/src/constants.ts
+17
-17
@@ -5,37 +5,37 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import path from "path";
8
+import path from 'path';
9
10
// We assume this is run from `babel-plugin-react-compiler`
11
export const PROJECT_ROOT = path.normalize(
12
- path.join(process.cwd(), "..", "..")
12
+ path.join(process.cwd(), '..', '..'),
13
);
14
export const COMPILER_PATH = path.join(
15
process.cwd(),
16
- "dist",
17
- "Babel",
18
- "BabelPlugin.js"
16
+ 'dist',
17
+ 'Babel',
18
+ 'BabelPlugin.js',
19
);
20
export const LOGGER_PATH = path.join(
21
process.cwd(),
22
- "dist",
23
- "Utils",
24
- "logger.js"
22
+ 'dist',
23
+ 'Utils',
24
+ 'logger.js',
25
);
26
export const PARSE_CONFIG_PRAGMA_PATH = path.join(
27
process.cwd(),
28
- "dist",
29
- "HIR",
30
- "Environment.js"
28
+ 'dist',
29
+ 'HIR',
30
+ 'Environment.js',
31
);
32
export const FIXTURES_PATH = path.join(
33
process.cwd(),
34
- "src",
35
- "__tests__",
36
- "fixtures",
37
- "compiler"
34
+ 'src',
35
+ '__tests__',
36
+ 'fixtures',
37
+ 'compiler',
38
);
39
-export const SNAPSHOT_EXTENSION = ".expect.md";
40
-export const FILTER_FILENAME = "testfilter.txt";
39
+export const SNAPSHOT_EXTENSION = '.expect.md';
40
+export const FILTER_FILENAME = 'testfilter.txt';
41
export const FILTER_PATH = path.join(process.cwd(), FILTER_FILENAME);
compiler/packages/snap/src/fixture-utils.ts
+38
-38
@@ -5,20 +5,20 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import fs from "fs/promises";
9
-import * as glob from "glob";
10
-import path from "path";
11
-import { FILTER_PATH, FIXTURES_PATH, SNAPSHOT_EXTENSION } from "./constants";
8
+import fs from 'fs/promises';
9
+import * as glob from 'glob';
10
+import path from 'path';
11
+import {FILTER_PATH, FIXTURES_PATH, SNAPSHOT_EXTENSION} from './constants';
12
13
const INPUT_EXTENSIONS = [
14
- ".js",
15
- ".cjs",
16
- ".mjs",
17
- ".ts",
18
- ".cts",
19
- ".mts",
20
- ".jsx",
21
- ".tsx",
14
+ '.js',
15
+ '.cjs',
16
+ '.mjs',
17
+ '.ts',
18
+ '.cts',
19
+ '.mts',
20
+ '.jsx',
21
+ '.tsx',
22
];
23
24
export type TestFilter = {
@@ -49,18 +49,18 @@ export async function readTestFilter(): Promise<TestFilter | null> {
49
throw new Error(`testfilter file not found at \`${FILTER_PATH}\``);
50
}
51
52
- const input = await fs.readFile(FILTER_PATH, "utf8");
53
- const lines = input.trim().split("\n");
52
+ const input = await fs.readFile(FILTER_PATH, 'utf8');
53
+ const lines = input.trim().split('\n');
54
55
let debug: boolean = false;
56
const line0 = lines[0];
57
if (line0 != null) {
58
// Try to parse pragmas
59
let consumedLine0 = false;
60
- if (line0.indexOf("@only") !== -1) {
60
+ if (line0.indexOf('@only') !== -1) {
61
consumedLine0 = true;
62
}
63
- if (line0.indexOf("@debug") !== -1) {
63
+ if (line0.indexOf('@debug') !== -1) {
64
debug = true;
65
consumedLine0 = true;
66
}
@@ -71,7 +71,7 @@ export async function readTestFilter(): Promise<TestFilter | null> {
71
}
72
return {
73
debug,
74
- paths: lines.filter((line) => !line.trimStart().startsWith("//")),
74
+ paths: lines.filter(line => !line.trimStart().startsWith('//')),
75
};
76
}
77
@@ -79,8 +79,8 @@ export function getBasename(fixture: TestFixture): string {
79
return stripExtension(path.basename(fixture.inputPath), INPUT_EXTENSIONS);
80
}
81
export function isExpectError(fixture: TestFixture | string): boolean {
82
- const basename = typeof fixture === "string" ? fixture : getBasename(fixture);
83
- return basename.startsWith("error.") || basename.startsWith("todo.error");
82
+ const basename = typeof fixture === 'string' ? fixture : getBasename(fixture);
83
+ return basename.startsWith('error.') || basename.startsWith('todo.error');
84
}
85
86
export type TestFixture =
@@ -101,31 +101,31 @@ export type TestFixture =
101
102
async function readInputFixtures(
103
rootDir: string,
104
- filter: TestFilter | null
105
-): Promise<Map<string, { value: string; filepath: string }>> {
104
+ filter: TestFilter | null,
105
+): Promise<Map<string, {value: string; filepath: string}>> {
106
let inputFiles: Array<string>;
107
if (filter == null) {
108
- inputFiles = glob.sync(`**/*{${INPUT_EXTENSIONS.join(",")}}`, {
108
+ inputFiles = glob.sync(`**/*{${INPUT_EXTENSIONS.join(',')}}`, {
109
cwd: rootDir,
110
});
111
} else {
112
inputFiles = (
113
await Promise.all(
114
- filter.paths.map((pattern) =>
115
- glob.glob(`${pattern}{${INPUT_EXTENSIONS.join(",")}}`, {
114
+ filter.paths.map(pattern =>
115
+ glob.glob(`${pattern}{${INPUT_EXTENSIONS.join(',')}}`, {
116
cwd: rootDir,
117
- })
118
- )
117
+ }),
118
+ ),
119
)
120
).flat();
121
}
122
- const inputs: Array<Promise<[string, { value: string; filepath: string }]>> =
122
+ const inputs: Array<Promise<[string, {value: string; filepath: string}]>> =
123
[];
124
for (const filePath of inputFiles) {
125
// Do not include extensions in unique identifier for fixture
126
const partialPath = stripExtension(filePath, INPUT_EXTENSIONS);
127
inputs.push(
128
- fs.readFile(path.join(rootDir, filePath), "utf8").then((input) => {
128
+ fs.readFile(path.join(rootDir, filePath), 'utf8').then(input => {
129
return [
130
partialPath,
131
{
@@ -133,14 +133,14 @@ async function readInputFixtures(
133
filepath: filePath,
134
},
135
];
136
- })
136
+ }),
137
);
138
}
139
return new Map(await Promise.all(inputs));
140
}
141
async function readOutputFixtures(
142
rootDir: string,
143
- filter: TestFilter | null
143
+ filter: TestFilter | null,
144
): Promise<Map<string, string>> {
145
let outputFiles: Array<string>;
146
if (filter == null) {
@@ -150,11 +150,11 @@ async function readOutputFixtures(
150
} else {
151
outputFiles = (
152
await Promise.all(
153
- filter.paths.map((pattern) =>
153
+ filter.paths.map(pattern =>
154
glob.glob(`${pattern}${SNAPSHOT_EXTENSION}`, {
155
cwd: rootDir,
156
- })
157
- )
156
+ }),
157
+ ),
158
)
159
).flat();
160
}
@@ -165,8 +165,8 @@ async function readOutputFixtures(
165
166
const outputPath = path.join(rootDir, filePath);
167
const output: Promise<[string, string]> = fs
168
- .readFile(outputPath, "utf8")
169
- .then((output) => {
168
+ .readFile(outputPath, 'utf8')
169
+ .then(output => {
170
return [partialPath, output];
171
});
172
outputs.push(output);
@@ -175,13 +175,13 @@ async function readOutputFixtures(
175
}
176
177
export async function getFixtures(
178
- filter: TestFilter | null
178
+ filter: TestFilter | null,
179
): Promise<Map<string, TestFixture>> {
180
const inputs = await readInputFixtures(FIXTURES_PATH, filter);
181
const outputs = await readOutputFixtures(FIXTURES_PATH, filter);
182
183
const fixtures: Map<string, TestFixture> = new Map();
184
- for (const [partialPath, { value, filepath }] of inputs) {
184
+ for (const [partialPath, {value, filepath}] of inputs) {
185
const output = outputs.get(partialPath) ?? null;
186
fixtures.set(partialPath, {
187
fixturePath: partialPath,
@@ -197,7 +197,7 @@ export async function getFixtures(
197
fixtures.set(partialPath, {
198
fixturePath: partialPath,
199
input: null,
200
- inputPath: "none",
200
+ inputPath: 'none',
201
snapshot: output,
202
snapshotPath:
203
path.join(FIXTURES_PATH, partialPath) + SNAPSHOT_EXTENSION,
compiler/packages/snap/src/main.ts
+14
-14
@@ -5,11 +5,11 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { fork } from "child_process";
9
-import invariant from "invariant";
10
-import process from "process";
11
-import * as readline from "readline";
12
-import { hideBin } from "yargs/helpers";
8
+import {fork} from 'child_process';
9
+import invariant from 'invariant';
10
+import process from 'process';
11
+import * as readline from 'readline';
12
+import {hideBin} from 'yargs/helpers';
13
14
readline.emitKeypressEvents(process.stdin);
15
@@ -17,36 +17,36 @@ if (process.stdin.isTTY) {
17
process.stdin.setRawMode(true);
18
}
19
20
-process.stdin.on("keypress", function (_, key) {
21
- if (key && key.name === "c" && key.ctrl) {
20
+process.stdin.on('keypress', function (_, key) {
21
+ if (key && key.name === 'c' && key.ctrl) {
22
// handle sigint
23
if (childProc) {
24
- console.log("Interrupted!!");
25
- childProc.kill("SIGINT");
24
+ console.log('Interrupted!!');
25
+ childProc.kill('SIGINT');
26
childProc.unref();
27
process.exit(-1);
28
}
29
}
30
});
31
32
-const childProc = fork(require.resolve("./runner.js"), hideBin(process.argv), {
32
+const childProc = fork(require.resolve('./runner.js'), hideBin(process.argv), {
33
// for some reason, keypress events aren't sent to handlers in both processes
34
// when we `inherit` stdin.
35
// pipe stdout and stderr so we can silence child process after parent exits
36
- stdio: ["pipe", "pipe", "pipe", "ipc"],
36
+ stdio: ['pipe', 'pipe', 'pipe', 'ipc'],
37
// forward existing env variables, like `NODE_OPTIONS` which VSCode uses to attach
38
// its debugger
39
- env: { ...process.env, FORCE_COLOR: "true" },
39
+ env: {...process.env, FORCE_COLOR: 'true'},
40
});
41
42
invariant(
43
childProc.stdin && childProc.stdout && childProc.stderr,
44
- "Expected forked process to have piped stdio"
44
+ 'Expected forked process to have piped stdio',
45
);
46
process.stdin.pipe(childProc.stdin);
47
childProc.stdout.pipe(process.stdout);
48
childProc.stderr.pipe(process.stderr);
49
50
-childProc.on("exit", (code) => {
50
+childProc.on('exit', code => {
51
process.exit(code ?? -1);
52
});
compiler/packages/snap/src/reporter.ts
+35
-35
@@ -5,41 +5,41 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import chalk from "chalk";
9
-import fs from "fs";
10
-import invariant from "invariant";
11
-import { diff } from "jest-diff";
12
-import path from "path";
8
+import chalk from 'chalk';
9
+import fs from 'fs';
10
+import invariant from 'invariant';
11
+import {diff} from 'jest-diff';
12
+import path from 'path';
13
14
function wrapWithTripleBackticks(s: string, ext: string | null = null): string {
15
- return `\`\`\`${ext ?? ""}
15
+ return `\`\`\`${ext ?? ''}
16
${s}
17
\`\`\``;
18
}
19
-const SPROUT_SEPARATOR = "\n### Eval output\n";
19
+const SPROUT_SEPARATOR = '\n### Eval output\n';
20
21
export function writeOutputToString(
22
input: string,
23
compilerOutput: string | null,
24
evaluatorOutput: string | null,
25
logs: string | null,
26
- errorMessage: string | null
26
+ errorMessage: string | null,
27
) {
28
// leading newline intentional
29
let result = `
30
## Input
31
32
-${wrapWithTripleBackticks(input, "javascript")}
32
+${wrapWithTripleBackticks(input, 'javascript')}
33
`; // trailing newline + space internional
34
35
if (compilerOutput != null) {
36
result += `
37
## Code
38
39
-${wrapWithTripleBackticks(compilerOutput, "javascript")}
39
+${wrapWithTripleBackticks(compilerOutput, 'javascript')}
40
`;
41
} else {
42
- result += "\n";
42
+ result += '\n';
43
}
44
45
if (logs != null) {
@@ -54,7 +54,7 @@ ${wrapWithTripleBackticks(logs, null)}
54
result += `
55
## Error
56
57
-${wrapWithTripleBackticks(errorMessage.replace(/^\/.*?:\s/, ""))}
57
+${wrapWithTripleBackticks(errorMessage.replace(/^\/.*?:\s/, ''))}
58
\n`;
59
}
60
result += ` `;
@@ -83,36 +83,36 @@ export async function update(results: TestResults): Promise<void> {
83
for (const [basename, result] of results) {
84
if (result.unexpectedError != null) {
85
console.log(
86
- chalk.red.inverse.bold(" FAILED ") + " " + chalk.dim(basename)
86
+ chalk.red.inverse.bold(' FAILED ') + ' ' + chalk.dim(basename),
87
);
88
failed.push([basename, result.unexpectedError]);
89
} else if (result.actual == null) {
90
// Input was deleted but the expect file still existed, remove it
91
console.log(
92
- chalk.red.inverse.bold(" REMOVE ") + " " + chalk.dim(basename)
92
+ chalk.red.inverse.bold(' REMOVE ') + ' ' + chalk.dim(basename),
93
);
94
try {
95
fs.unlinkSync(result.outputPath);
96
- console.log(" remove " + result.outputPath);
96
+ console.log(' remove ' + result.outputPath);
97
deleted++;
98
} catch (e) {
99
console.error(
100
- "[Snap tester error]: failed to remove " + result.outputPath
100
+ '[Snap tester error]: failed to remove ' + result.outputPath,
101
);
102
failed.push([basename, result.unexpectedError]);
103
}
104
} else if (result.actual !== result.expected) {
105
// Expected output has changed
106
console.log(
107
- chalk.blue.inverse.bold(" UPDATE ") + " " + chalk.dim(basename)
107
+ chalk.blue.inverse.bold(' UPDATE ') + ' ' + chalk.dim(basename),
108
);
109
try {
110
- fs.writeFileSync(result.outputPath, result.actual, "utf8");
110
+ fs.writeFileSync(result.outputPath, result.actual, 'utf8');
111
} catch (e) {
112
- if (e?.code === "ENOENT") {
112
+ if (e?.code === 'ENOENT') {
113
// May have failed to create nested dir, so make a directory and retry
114
- fs.mkdirSync(path.dirname(result.outputPath), { recursive: true });
115
- fs.writeFileSync(result.outputPath, result.actual, "utf8");
114
+ fs.mkdirSync(path.dirname(result.outputPath), {recursive: true});
115
+ fs.writeFileSync(result.outputPath, result.actual, 'utf8');
116
}
117
}
118
if (result.expected == null) {
@@ -123,15 +123,15 @@ export async function update(results: TestResults): Promise<void> {
123
} else {
124
// Expected output is current
125
console.log(
126
- chalk.green.inverse.bold(" OKAY ") + " " + chalk.dim(basename)
126
+ chalk.green.inverse.bold(' OKAY ') + ' ' + chalk.dim(basename),
127
);
128
}
129
}
130
console.log(
131
- `${deleted} Deleted, ${created} Created, ${updated} Updated, ${failed.length} Failed`
131
+ `${deleted} Deleted, ${created} Created, ${updated} Updated, ${failed.length} Failed`,
132
);
133
for (const [basename, errorMsg] of failed) {
134
- console.log(`${chalk.red.bold("Fail:")} ${basename}\n${errorMsg}`);
134
+ console.log(`${chalk.red.bold('Fail:')} ${basename}\n${errorMsg}`);
135
}
136
}
137
@@ -144,37 +144,37 @@ export function report(results: TestResults): boolean {
144
for (const [basename, result] of results) {
145
if (result.actual === result.expected && result.unexpectedError == null) {
146
console.log(
147
- chalk.green.inverse.bold(" PASS ") + " " + chalk.dim(basename)
147
+ chalk.green.inverse.bold(' PASS ') + ' ' + chalk.dim(basename),
148
);
149
} else {
150
- console.log(chalk.red.inverse.bold(" FAIL ") + " " + chalk.dim(basename));
150
+ console.log(chalk.red.inverse.bold(' FAIL ') + ' ' + chalk.dim(basename));
151
failures.push([basename, result]);
152
}
153
}
154
155
if (failures.length !== 0) {
156
- console.log("\n" + chalk.red.bold("Failures:") + "\n");
156
+ console.log('\n' + chalk.red.bold('Failures:') + '\n');
157
158
for (const [basename, result] of failures) {
159
- console.log(chalk.red.bold("FAIL:") + " " + basename);
159
+ console.log(chalk.red.bold('FAIL:') + ' ' + basename);
160
if (result.unexpectedError != null) {
161
console.log(
162
- ` >> Unexpected error during test: \n${result.unexpectedError}`
162
+ ` >> Unexpected error during test: \n${result.unexpectedError}`,
163
);
164
} else {
165
if (result.expected == null) {
166
- invariant(result.actual != null, "[Tester] Internal failure.");
166
+ invariant(result.actual != null, '[Tester] Internal failure.');
167
console.log(
168
- chalk.red("[ expected fixture output is absent ]") + "\n"
168
+ chalk.red('[ expected fixture output is absent ]') + '\n',
169
);
170
} else if (result.actual == null) {
171
- invariant(result.expected != null, "[Tester] Internal failure.");
171
+ invariant(result.expected != null, '[Tester] Internal failure.');
172
console.log(
173
chalk.red(`[ fixture input for ${result.outputPath} is absent ]`) +
174
- "\n"
174
+ '\n',
175
);
176
} else {
177
- console.log(diff(result.expected, result.actual) + "\n");
177
+ console.log(diff(result.expected, result.actual) + '\n');
178
}
179
}
180
}
@@ -183,7 +183,7 @@ export function report(results: TestResults): boolean {
183
console.log(
184
`${results.size} Tests, ${results.size - failures.length} Passed, ${
185
failures.length
186
- } Failed`
186
+ } Failed`,
187
);
188
return failures.length === 0;
189
}
compiler/packages/snap/src/runner-watch.ts
+36
-36
@@ -5,20 +5,20 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import watcher from "@parcel/watcher";
9
-import path from "path";
10
-import ts from "typescript";
11
-import { FILTER_FILENAME, FIXTURES_PATH } from "./constants";
12
-import { TestFilter, readTestFilter } from "./fixture-utils";
8
+import watcher from '@parcel/watcher';
9
+import path from 'path';
10
+import ts from 'typescript';
11
+import {FILTER_FILENAME, FIXTURES_PATH} from './constants';
12
+import {TestFilter, readTestFilter} from './fixture-utils';
13
14
export function watchSrc(
15
onStart: () => void,
16
- onComplete: (isSuccess: boolean) => void
16
+ onComplete: (isSuccess: boolean) => void,
17
): ts.WatchOfConfigFile<ts.SemanticDiagnosticsBuilderProgram> {
18
const configPath = ts.findConfigFile(
19
- /*searchPath*/ "./",
19
+ /*searchPath*/ './',
20
ts.sys.fileExists,
21
- "tsconfig.json"
21
+ 'tsconfig.json',
22
);
23
if (!configPath) {
24
throw new Error("Could not find a valid 'tsconfig.json'.");
@@ -27,13 +27,13 @@ export function watchSrc(
27
const host = ts.createWatchCompilerHost(
28
configPath,
29
ts.convertCompilerOptionsFromJson(
30
- { module: "commonjs", outDir: "dist", sourceMap: true },
31
- "."
30
+ {module: 'commonjs', outDir: 'dist', sourceMap: true},
31
+ '.',
32
).options,
33
ts.sys,
34
createProgram,
35
() => {}, // we manually report errors in afterProgramCreate
36
- () => {} // we manually report watch status
36
+ () => {}, // we manually report watch status
37
);
38
39
const origCreateProgram = host.createProgram;
@@ -42,18 +42,18 @@ export function watchSrc(
42
return origCreateProgram(rootNames, options, host, oldProgram);
43
};
44
const origPostProgramCreate = host.afterProgramCreate;
45
- host.afterProgramCreate = (program) => {
45
+ host.afterProgramCreate = program => {
46
origPostProgramCreate!(program);
47
48
// syntactic diagnostics refer to javascript syntax
49
const errors = program
50
.getSyntacticDiagnostics()
51
- .filter((diag) => diag.category === ts.DiagnosticCategory.Error);
51
+ .filter(diag => diag.category === ts.DiagnosticCategory.Error);
52
// semantic diagnostics refer to typescript semantics
53
errors.push(
54
...program
55
.getSemanticDiagnostics()
56
- .filter((diag) => diag.category === ts.DiagnosticCategory.Error)
56
+ .filter(diag => diag.category === ts.DiagnosticCategory.Error),
57
);
58
59
if (errors.length > 0) {
@@ -61,27 +61,27 @@ export function watchSrc(
61
let fileLoc: string;
62
if (diagnostic.file) {
63
// https://github.com/microsoft/TypeScript/blob/ddd5084659c423f4003d2176e12d879b6a5bcf30/src/compiler/program.ts#L663-L674
64
- const { line, character } = ts.getLineAndCharacterOfPosition(
64
+ const {line, character} = ts.getLineAndCharacterOfPosition(
65
diagnostic.file,
66
- diagnostic.start!
66
+ diagnostic.start!,
67
);
68
const fileName = path.relative(
69
ts.sys.getCurrentDirectory(),
70
- diagnostic.file.fileName
70
+ diagnostic.file.fileName,
71
);
72
fileLoc = `${fileName}:${line + 1}:${character + 1} - `;
73
} else {
74
- fileLoc = "";
74
+ fileLoc = '';
75
}
76
console.error(
77
`${fileLoc}error TS${diagnostic.code}:`,
78
- ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")
78
+ ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'),
79
);
80
}
81
console.error(
82
`Compilation failed (${errors.length} ${
83
- errors.length > 1 ? "errors" : "error"
84
- }).\n`
83
+ errors.length > 1 ? 'errors' : 'error'
84
+ }).\n`,
85
);
86
}
87
@@ -98,8 +98,8 @@ export function watchSrc(
98
* Watch mode helpers
99
*/
100
export enum RunnerAction {
101
- Test = "Test",
102
- Update = "Update",
101
+ Test = 'Test',
102
+ Update = 'Update',
103
}
104
105
type RunnerMode = {
@@ -121,7 +121,7 @@ export type RunnerState = {
121
122
function subscribeFixtures(
123
state: RunnerState,
124
- onChange: (state: RunnerState) => void
124
+ onChange: (state: RunnerState) => void,
125
) {
126
// Watch the fixtures directory for changes
127
watcher.subscribe(FIXTURES_PATH, async (err, _events) => {
@@ -144,14 +144,14 @@ function subscribeFixtures(
144
145
function subscribeFilterFile(
146
state: RunnerState,
147
- onChange: (state: RunnerState) => void
147
+ onChange: (state: RunnerState) => void,
148
) {
149
watcher.subscribe(process.cwd(), async (err, events) => {
150
if (err) {
151
console.error(err);
152
process.exit(1);
153
} else if (
154
- events.findIndex((event) => event.path.includes(FILTER_FILENAME)) !== -1
154
+ events.findIndex(event => event.path.includes(FILTER_FILENAME)) !== -1
155
) {
156
if (state.mode.filter) {
157
state.filter = await readTestFilter();
@@ -164,15 +164,15 @@ function subscribeFilterFile(
164
165
function subscribeTsc(
166
state: RunnerState,
167
- onChange: (state: RunnerState) => void
167
+ onChange: (state: RunnerState) => void,
168
) {
169
// Run TS in incremental watch mode
170
watchSrc(
171
function onStart() {
172
// Notify the user when compilation starts but don't clear the screen yet
173
- console.log("\nCompiling...");
173
+ console.log('\nCompiling...');
174
},
175
- (isSuccess) => {
175
+ isSuccess => {
176
// Bump the compiler version after a build finishes
177
// and re-run tests
178
if (isSuccess) {
@@ -181,21 +181,21 @@ function subscribeTsc(
181
state.isCompilerBuildValid = isSuccess;
182
state.mode.action = RunnerAction.Test;
183
onChange(state);
184
- }
184
+ },
185
);
186
}
187
188
function subscribeKeyEvents(
189
state: RunnerState,
190
- onChange: (state: RunnerState) => void
190
+ onChange: (state: RunnerState) => void,
191
) {
192
- process.stdin.on("keypress", async (str, key) => {
193
- if (key.name === "u") {
192
+ process.stdin.on('keypress', async (str, key) => {
193
+ if (key.name === 'u') {
194
// u => update fixtures
195
state.mode.action = RunnerAction.Update;
196
- } else if (key.name === "q") {
196
+ } else if (key.name === 'q') {
197
process.exit(0);
198
- } else if (key.name === "f") {
198
+ } else if (key.name === 'f') {
199
state.mode.filter = !state.mode.filter;
200
state.filter = state.mode.filter ? await readTestFilter() : null;
201
state.mode.action = RunnerAction.Test;
@@ -209,7 +209,7 @@ function subscribeKeyEvents(
209
210
export async function makeWatchRunner(
211
onChange: (state: RunnerState) => void,
212
- filterMode: boolean
212
+ filterMode: boolean,
213
): Promise<void> {
214
const state = {
215
compilerVersion: 0,
compiler/packages/snap/src/runner-worker.ts
+26
-26
@@ -5,25 +5,25 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { codeFrameColumns } from "@babel/code-frame";
9
-import type { PluginObj } from "@babel/core";
10
-import type { parseConfigPragma as ParseConfigPragma } from "babel-plugin-react-compiler/src/HIR/Environment";
11
-import { TransformResult, transformFixtureInput } from "./compiler";
8
+import {codeFrameColumns} from '@babel/code-frame';
9
+import type {PluginObj} from '@babel/core';
10
+import type {parseConfigPragma as ParseConfigPragma} from 'babel-plugin-react-compiler/src/HIR/Environment';
11
+import {TransformResult, transformFixtureInput} from './compiler';
12
import {
13
COMPILER_PATH,
14
LOGGER_PATH,
15
PARSE_CONFIG_PRAGMA_PATH,
16
-} from "./constants";
17
-import { TestFixture, getBasename, isExpectError } from "./fixture-utils";
18
-import { TestResult, writeOutputToString } from "./reporter";
19
-import { runSprout } from "./sprout";
16
+} from './constants';
17
+import {TestFixture, getBasename, isExpectError} from './fixture-utils';
18
+import {TestResult, writeOutputToString} from './reporter';
19
+import {runSprout} from './sprout';
20
21
const originalConsoleError = console.error;
22
23
// Try to avoid clearing the entire require cache, which (as of this PR)
24
// contains ~1250 files. This assumes that no dependencies have global caches
25
// that may need to be invalidated across Forget reloads.
26
-const invalidationSubpath = "packages/babel-plugin-react-compiler/dist";
26
+const invalidationSubpath = 'packages/babel-plugin-react-compiler/dist';
27
let version: number | null = null;
28
export function clearRequireCache() {
29
Object.keys(require.cache).forEach(function (path) {
@@ -38,7 +38,7 @@ async function compile(
38
fixturePath: string,
39
compilerVersion: number,
40
shouldLog: boolean,
41
- includeEvaluator: boolean
41
+ includeEvaluator: boolean,
42
): Promise<{
43
error: string | null;
44
compileResult: TransformResult | null;
@@ -57,11 +57,11 @@ async function compile(
57
try {
58
// NOTE: we intentionally require lazily here so that we can clear the require cache
59
// and load fresh versions of the compiler when `compilerVersion` changes.
60
- const { default: BabelPluginReactCompiler } = require(COMPILER_PATH) as {
60
+ const {default: BabelPluginReactCompiler} = require(COMPILER_PATH) as {
61
default: PluginObj;
62
};
63
- const { toggleLogging } = require(LOGGER_PATH);
64
- const { parseConfigPragma } = require(PARSE_CONFIG_PRAGMA_PATH) as {
63
+ const {toggleLogging} = require(LOGGER_PATH);
64
+ const {parseConfigPragma} = require(PARSE_CONFIG_PRAGMA_PATH) as {
65
parseConfigPragma: typeof ParseConfigPragma;
66
};
67
@@ -73,10 +73,10 @@ async function compile(
73
fixturePath,
74
parseConfigPragma,
75
BabelPluginReactCompiler,
76
- includeEvaluator
76
+ includeEvaluator,
77
);
78
79
- if (result.kind === "err") {
79
+ if (result.kind === 'err') {
80
error = result.msg;
81
} else {
82
compileResult = result.value;
@@ -85,7 +85,7 @@ async function compile(
85
if (shouldLog) {
86
console.error(e.stack);
87
}
88
- error = e.message.replace(/\u001b[^m]*m/g, "");
88
+ error = e.message.replace(/\u001b[^m]*m/g, '');
89
const loc = e.details?.[0]?.loc;
90
if (loc != null) {
91
try {
@@ -103,7 +103,7 @@ async function compile(
103
},
104
{
105
message: e.message,
106
- }
106
+ },
107
);
108
} catch {
109
// In case the location data isn't valid, skip printing a code frame.
@@ -131,9 +131,9 @@ export async function transformFixture(
131
fixture: TestFixture,
132
compilerVersion: number,
133
shouldLog: boolean,
134
- includeEvaluator: boolean
134
+ includeEvaluator: boolean,
135
): Promise<TestResult> {
136
- const { input, snapshot: expected, snapshotPath: outputPath } = fixture;
136
+ const {input, snapshot: expected, snapshotPath: outputPath} = fixture;
137
const basename = getBasename(fixture);
138
const expectError = isExpectError(fixture);
139
@@ -147,12 +147,12 @@ export async function transformFixture(
147
unexpectedError: null,
148
};
149
}
150
- const { compileResult, error } = await compile(
150
+ const {compileResult, error} = await compile(
151
input,
152
fixture.fixturePath,
153
compilerVersion,
154
shouldLog,
155
- includeEvaluator
155
+ includeEvaluator,
156
);
157
158
let unexpectedError: string | null = null;
@@ -173,16 +173,16 @@ export async function transformFixture(
173
if (compileResult?.evaluatorCode != null) {
174
const sproutResult = runSprout(
175
compileResult.evaluatorCode.original,
176
- compileResult.evaluatorCode.forget
176
+ compileResult.evaluatorCode.forget,
177
);
178
- if (sproutResult.kind === "invalid") {
179
- unexpectedError ??= "";
178
+ if (sproutResult.kind === 'invalid') {
179
+ unexpectedError ??= '';
180
unexpectedError += `\n\n${sproutResult.value}`;
181
} else {
182
sproutOutput = sproutResult.value;
183
}
184
} else if (!includeEvaluator && expected != null) {
185
- sproutOutput = expected.split("\n### Eval output\n")[1];
185
+ sproutOutput = expected.split('\n### Eval output\n')[1];
186
}
187
188
const actualOutput = writeOutputToString(
@@ -190,7 +190,7 @@ export async function transformFixture(
190
snapOutput,
191
sproutOutput,
192
compileResult?.logs ?? null,
193
- error
193
+ error,
194
);
195
196
return {
compiler/packages/snap/src/runner.ts
+56
-56
@@ -5,25 +5,25 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { Worker } from "jest-worker";
9
-import { cpus } from "os";
10
-import process from "process";
11
-import * as readline from "readline";
12
-import ts from "typescript";
13
-import yargs from "yargs";
14
-import { hideBin } from "yargs/helpers";
15
-import { FILTER_PATH } from "./constants";
16
-import { TestFilter, getFixtures, readTestFilter } from "./fixture-utils";
17
-import { TestResult, TestResults, report, update } from "./reporter";
8
+import {Worker} from 'jest-worker';
9
+import {cpus} from 'os';
10
+import process from 'process';
11
+import * as readline from 'readline';
12
+import ts from 'typescript';
13
+import yargs from 'yargs';
14
+import {hideBin} from 'yargs/helpers';
15
+import {FILTER_PATH} from './constants';
16
+import {TestFilter, getFixtures, readTestFilter} from './fixture-utils';
17
+import {TestResult, TestResults, report, update} from './reporter';
18
import {
19
RunnerAction,
20
RunnerState,
21
makeWatchRunner,
22
watchSrc,
23
-} from "./runner-watch";
24
-import * as runnerWorker from "./runner-worker";
23
+} from './runner-watch';
24
+import * as runnerWorker from './runner-worker';
25
26
-const WORKER_PATH = require.resolve("./runner-worker.js");
26
+const WORKER_PATH = require.resolve('./runner-worker.js');
27
const NUM_WORKERS = cpus().length - 1;
28
29
readline.emitKeypressEvents(process.stdin);
@@ -37,31 +37,31 @@ type RunnerOptions = {
37
};
38
39
const opts: RunnerOptions = yargs
40
- .boolean("sync")
40
+ .boolean('sync')
41
.describe(
42
- "sync",
43
- "Run compiler in main thread (instead of using worker threads or subprocesses). Defaults to false."
42
+ 'sync',
43
+ 'Run compiler in main thread (instead of using worker threads or subprocesses). Defaults to false.',
44
)
45
- .default("sync", false)
46
- .boolean("worker-threads")
45
+ .default('sync', false)
46
+ .boolean('worker-threads')
47
.describe(
48
- "worker-threads",
49
- "Run compiler in worker threads (instead of subprocesses). Defaults to true."
48
+ 'worker-threads',
49
+ 'Run compiler in worker threads (instead of subprocesses). Defaults to true.',
50
)
51
- .default("worker-threads", true)
52
- .boolean("watch")
53
- .describe("watch", "Run compiler in watch mode, re-running after changes")
54
- .default("watch", false)
55
- .boolean("update")
56
- .describe("update", "Update fixtures")
57
- .default("update", false)
58
- .boolean("filter")
51
+ .default('worker-threads', true)
52
+ .boolean('watch')
53
+ .describe('watch', 'Run compiler in watch mode, re-running after changes')
54
+ .default('watch', false)
55
+ .boolean('update')
56
+ .describe('update', 'Update fixtures')
57
+ .default('update', false)
58
+ .boolean('filter')
59
.describe(
60
- "filter",
61
- "Only run fixtures which match the contents of testfilter.txt"
60
+ 'filter',
61
+ 'Only run fixtures which match the contents of testfilter.txt',
62
)
63
- .default("filter", false)
64
- .help("help")
63
+ .default('filter', false)
64
+ .help('help')
65
.strict()
66
.parseSync(hideBin(process.argv));
67
@@ -71,7 +71,7 @@ const opts: RunnerOptions = yargs
71
async function runFixtures(
72
worker: Worker & typeof runnerWorker,
73
filter: TestFilter | null,
74
- compilerVersion: number
74
+ compilerVersion: number,
75
): Promise<TestResults> {
76
// We could in theory be fancy about tracking the contents of the fixtures
77
// directory via our file subscription, but it's simpler to just re-read
@@ -90,9 +90,9 @@ async function runFixtures(
90
fixture,
91
compilerVersion,
92
(filter?.debug ?? false) && isOnlyFixture,
93
- true
93
+ true,
94
)
95
- .then((result) => [fixtureName, result])
95
+ .then(result => [fixtureName, result]),
96
);
97
}
98
@@ -104,7 +104,7 @@ async function runFixtures(
104
fixture,
105
compilerVersion,
106
(filter?.debug ?? false) && isOnlyFixture,
107
- true
107
+ true,
108
);
109
entries.push([fixtureName, output]);
110
}
@@ -116,22 +116,22 @@ async function runFixtures(
116
// Callback to re-run tests after some change
117
async function onChange(
118
worker: Worker & typeof runnerWorker,
119
- state: RunnerState
119
+ state: RunnerState,
120
) {
121
- const { compilerVersion, isCompilerBuildValid, mode, filter } = state;
121
+ const {compilerVersion, isCompilerBuildValid, mode, filter} = state;
122
if (isCompilerBuildValid) {
123
const start = performance.now();
124
125
// console.clear() only works when stdout is connected to a TTY device.
126
// we're currently piping stdout (see main.ts), so let's do a 'hack'
127
- console.log("\u001Bc");
127
+ console.log('\u001Bc');
128
129
// we don't clear console after this point, since
130
// it may contain debug console logging
131
const results = await runFixtures(
132
worker,
133
mode.filter ? filter : null,
134
- compilerVersion
134
+ compilerVersion,
135
);
136
const end = performance.now();
137
if (mode.action === RunnerAction.Update) {
@@ -143,19 +143,19 @@ async function onChange(
143
console.log(`Completed in ${Math.floor(end - start)} ms`);
144
} else {
145
console.error(
146
- `${mode}: Found errors in Forget source code, skipping test fixtures.`
146
+ `${mode}: Found errors in Forget source code, skipping test fixtures.`,
147
);
148
}
149
console.log(
150
- "\n" +
150
+ '\n' +
151
(mode.filter
152
? `Current mode = FILTER, filter test fixtures by "${FILTER_PATH}".`
153
- : "Current mode = NORMAL, run all test fixtures.") +
154
- "\nWaiting for input or file changes...\n" +
155
- "u - update all fixtures\n" +
156
- `f - toggle (turn ${mode.filter ? "off" : "on"}) filter mode\n` +
157
- "q - quit\n" +
158
- "[any] - rerun tests\n"
153
+ : 'Current mode = NORMAL, run all test fixtures.') +
154
+ '\nWaiting for input or file changes...\n' +
155
+ 'u - update all fixtures\n' +
156
+ `f - toggle (turn ${mode.filter ? 'off' : 'on'}) filter mode\n` +
157
+ 'q - quit\n' +
158
+ '[any] - rerun tests\n',
159
);
160
}
161
@@ -171,7 +171,7 @@ export async function main(opts: RunnerOptions): Promise<void> {
171
worker.getStdout().pipe(process.stdout);
172
173
if (opts.watch) {
174
- makeWatchRunner((state) => onChange(worker, state), opts.filter);
174
+ makeWatchRunner(state => onChange(worker, state), opts.filter);
175
if (opts.filter) {
176
/**
177
* Warm up wormers when in watch mode. Loading the Forget babel plugin
@@ -183,9 +183,9 @@ export async function main(opts: RunnerOptions): Promise<void> {
183
for (let i = 0; i < NUM_WORKERS - 1; i++) {
184
worker.transformFixture(
185
{
186
- fixturePath: "tmp",
187
- snapshotPath: "./tmp.expect.md",
188
- inputPath: "./tmp.js",
186
+ fixturePath: 'tmp',
187
+ snapshotPath: './tmp.expect.md',
188
+ inputPath: './tmp.js',
189
input: `
190
function Foo(props) {
191
return identity(props);
@@ -195,7 +195,7 @@ export async function main(opts: RunnerOptions): Promise<void> {
195
},
196
0,
197
false,
198
- false
198
+ false,
199
);
200
}
201
}
@@ -218,15 +218,15 @@ export async function main(opts: RunnerOptions): Promise<void> {
218
}
219
} else {
220
console.error(
221
- "Found errors in Forget source code, skipping test fixtures."
221
+ 'Found errors in Forget source code, skipping test fixtures.',
222
);
223
}
224
tsWatch.close();
225
await worker.end();
226
process.exit(isSuccess ? 0 : 1);
227
- }
227
+ },
228
);
229
}
230
}
231
232
-main(opts).catch((error) => console.error(error));
232
+main(opts).catch(error => console.error(error));
compiler/packages/snap/src/sprout/evaluator.ts
+50
-50
@@ -5,15 +5,15 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { render } from "@testing-library/react";
9
-import { JSDOM } from "jsdom";
10
-import React, { MutableRefObject } from "react";
8
+import {render} from '@testing-library/react';
9
+import {JSDOM} from 'jsdom';
10
+import React, {MutableRefObject} from 'react';
11
// @ts-ignore
12
-import { c as useMemoCache } from "react/compiler-runtime";
13
-import util from "util";
14
-import { z } from "zod";
15
-import { fromZodError } from "zod-validation-error";
16
-import { initFbt, toJSON } from "./shared-runtime";
12
+import {c as useMemoCache} from 'react/compiler-runtime';
13
+import util from 'util';
14
+import {z} from 'zod';
15
+import {fromZodError} from 'zod-validation-error';
16
+import {initFbt, toJSON} from './shared-runtime';
17
18
// @ts-ignore
19
React.c = useMemoCache;
@@ -25,7 +25,7 @@ React.c = useMemoCache;
25
* in the jsdom test environment (which provides more isolation), but that
26
* may be slower.
27
*/
28
-const { window: testWindow } = new JSDOM(undefined);
28
+const {window: testWindow} = new JSDOM(undefined);
29
(globalThis as any).document = testWindow.document;
30
(globalThis as any).window = testWindow.window;
31
(globalThis as any).React = React;
@@ -33,10 +33,10 @@ const { window: testWindow } = new JSDOM(undefined);
33
initFbt();
34
35
(globalThis as any).placeholderFn = function (..._args: Array<any>) {
36
- throw new Error("Fixture not implemented!");
36
+ throw new Error('Fixture not implemented!');
37
};
38
export type EvaluatorResult = {
39
- kind: "ok" | "exception" | "UnexpectedError";
39
+ kind: 'ok' | 'exception' | 'UnexpectedError';
40
value: string;
41
logs: Array<string>;
42
};
@@ -66,29 +66,29 @@ const ExportSchema = z.object({
66
* A simpler alternative may be to re-mount test components manually.
67
*/
68
class WrapperTestComponentWithErrorBoundary extends React.Component<
69
- { fn: any; params: Array<any> },
70
- { hasError: boolean; error: any }
69
+ {fn: any; params: Array<any>},
70
+ {hasError: boolean; error: any}
71
> {
72
propsErrorMap: MutableRefObject<Map<any, any>>;
73
constructor(props: any) {
74
super(props);
75
- this.state = { hasError: false, error: null };
75
+ this.state = {hasError: false, error: null};
76
this.propsErrorMap = React.createRef() as MutableRefObject<Map<any, any>>;
77
this.propsErrorMap.current = new Map();
78
}
79
static getDerivedStateFromError(error: any) {
80
- return { hasError: true, error: error };
80
+ return {hasError: true, error: error};
81
}
82
override componentDidUpdate() {
83
if (this.state.hasError) {
84
- this.setState({ hasError: false, error: null });
84
+ this.setState({hasError: false, error: null});
85
}
86
}
87
override render() {
88
if (this.state.hasError) {
89
this.propsErrorMap.current!.set(
90
this.props,
91
- `[[ (exception in render) ${this.state.error?.toString()} ]]`
91
+ `[[ (exception in render) ${this.state.error?.toString()} ]]`,
92
);
93
}
94
const cachedError = this.propsErrorMap.current!.get(this.props);
@@ -99,12 +99,12 @@ class WrapperTestComponentWithErrorBoundary extends React.Component<
99
}
100
}
101
102
-function WrapperTestComponent(props: { fn: any; params: Array<any> }) {
102
+function WrapperTestComponent(props: {fn: any; params: Array<any>}) {
103
const result = props.fn(...props.params);
104
// Hacky solution to determine whether the fixture returned jsx (which
105
// needs to passed through to React's runtime as-is) or a non-jsx value
106
// (which should be converted to a string).
107
- if (typeof result === "object" && result != null && "$$typeof" in result) {
107
+ if (typeof result === 'object' && result != null && '$$typeof' in result) {
108
return result;
109
} else {
110
return toJSON(result);
@@ -113,20 +113,20 @@ function WrapperTestComponent(props: { fn: any; params: Array<any> }) {
113
114
function renderComponentSequentiallyForEachProps(
115
fn: any,
116
- sequentialRenders: Array<any>
116
+ sequentialRenders: Array<any>,
117
): string {
118
if (sequentialRenders.length === 0) {
119
throw new Error(
120
- "Expected at least one set of props when using `sequentialRenders`"
120
+ 'Expected at least one set of props when using `sequentialRenders`',
121
);
122
}
123
const initialProps = sequentialRenders[0]!;
124
const results = [];
125
- const { rerender, container } = render(
125
+ const {rerender, container} = render(
126
React.createElement(WrapperTestComponentWithErrorBoundary, {
127
fn,
128
params: [initialProps],
129
- })
129
+ }),
130
);
131
results.push(container.innerHTML);
132
@@ -135,25 +135,25 @@ function renderComponentSequentiallyForEachProps(
135
React.createElement(WrapperTestComponentWithErrorBoundary, {
136
fn,
137
params: [sequentialRenders[i]],
138
- })
138
+ }),
139
);
140
results.push(container.innerHTML);
141
}
142
- return results.join("\n");
142
+ return results.join('\n');
143
}
144
145
-type FixtureEvaluatorResult = Omit<EvaluatorResult, "logs">;
145
+type FixtureEvaluatorResult = Omit<EvaluatorResult, 'logs'>;
146
(globalThis as any).evaluateFixtureExport = function (
147
- exports: unknown
147
+ exports: unknown,
148
): FixtureEvaluatorResult {
149
const parsedExportResult = ExportSchema.safeParse(exports);
150
if (!parsedExportResult.success) {
151
const exportDetail =
152
- typeof exports === "object" && exports != null
152
+ typeof exports === 'object' && exports != null
153
? `object ${util.inspect(exports)}`
154
: `${exports}`;
155
return {
156
- kind: "UnexpectedError",
156
+ kind: 'UnexpectedError',
157
value: `${fromZodError(parsedExportResult.error)}\nFound ` + exportDetail,
158
};
159
}
@@ -161,49 +161,49 @@ type FixtureEvaluatorResult = Omit<EvaluatorResult, "logs">;
161
if (entrypoint.sequentialRenders !== null) {
162
const result = renderComponentSequentiallyForEachProps(
163
entrypoint.fn,
164
- entrypoint.sequentialRenders
164
+ entrypoint.sequentialRenders,
165
);
166
167
return {
168
- kind: "ok",
169
- value: result ?? "null",
168
+ kind: 'ok',
169
+ value: result ?? 'null',
170
};
171
- } else if (typeof entrypoint.fn === "object") {
171
+ } else if (typeof entrypoint.fn === 'object') {
172
// Try to run fixture as a react component. This is necessary because not
173
// all components are functions (some are ForwardRef or Memo objects).
174
const result = render(
175
- React.createElement(entrypoint.fn as any, entrypoint.params[0])
175
+ React.createElement(entrypoint.fn as any, entrypoint.params[0]),
176
).container.innerHTML;
177
178
return {
179
- kind: "ok",
180
- value: result ?? "null",
179
+ kind: 'ok',
180
+ value: result ?? 'null',
181
};
182
} else {
183
const result = render(React.createElement(WrapperTestComponent, entrypoint))
184
.container.innerHTML;
185
186
return {
187
- kind: "ok",
188
- value: result ?? "null",
187
+ kind: 'ok',
188
+ value: result ?? 'null',
189
};
190
}
191
};
192
193
export function doEval(source: string): EvaluatorResult {
194
- "use strict";
194
+ 'use strict';
195
196
const originalConsole = globalThis.console;
197
const logs: Array<string> = [];
198
const mockedLog = (...args: Array<any>) => {
199
logs.push(
200
- `${args.map((arg) => {
200
+ `${args.map(arg => {
201
if (arg instanceof Error) {
202
return arg.toString();
203
} else {
204
return util.inspect(arg);
205
}
206
- })}`
206
+ })}`,
207
);
208
};
209
@@ -213,22 +213,22 @@ export function doEval(source: string): EvaluatorResult {
213
warn: mockedLog,
214
error: (...args: Array<any>) => {
215
if (
216
- typeof args[0] === "string" &&
217
- args[0].includes("ReactDOMTestUtils.act` is deprecated")
216
+ typeof args[0] === 'string' &&
217
+ args[0].includes('ReactDOMTestUtils.act` is deprecated')
218
) {
219
// remove this once @testing-library/react is upgraded to React 19.
220
return;
221
}
222
223
- const stack = new Error().stack?.split("\n", 5) ?? [];
223
+ const stack = new Error().stack?.split('\n', 5) ?? [];
224
for (const stackFrame of stack) {
225
// React warns on exceptions thrown during render, we avoid printing
226
// here to reduce noise in test fixture outputs.
227
if (
228
- (stackFrame.includes("at logCaughtError") &&
229
- stackFrame.includes("react-dom-client.development.js")) ||
230
- (stackFrame.includes("at defaultOnRecoverableError") &&
231
- stackFrame.includes("react-dom-client.development.js"))
228
+ (stackFrame.includes('at logCaughtError') &&
229
+ stackFrame.includes('react-dom-client.development.js')) ||
230
+ (stackFrame.includes('at defaultOnRecoverableError') &&
231
+ stackFrame.includes('react-dom-client.development.js'))
232
) {
233
return;
234
}
@@ -284,9 +284,9 @@ export function doEval(source: string): EvaluatorResult {
284
} catch (e) {
285
// syntax errors will cause the eval to throw and bubble up here
286
return {
287
- kind: "UnexpectedError",
287
+ kind: 'UnexpectedError',
288
value:
289
- "Unexpected error during eval, possible syntax error?\n" + e.message,
289
+ 'Unexpected error during eval, possible syntax error?\n' + e.message,
290
logs,
291
};
292
} finally {
compiler/packages/snap/src/sprout/index.ts
+16
-16
@@ -5,21 +5,21 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { EvaluatorResult, doEval } from "./evaluator";
8
+import {EvaluatorResult, doEval} from './evaluator';
9
10
export type SproutResult =
11
- | { kind: "success"; value: string }
12
- | { kind: "invalid"; value: string };
11
+ | {kind: 'success'; value: string}
12
+ | {kind: 'invalid'; value: string};
13
14
function stringify(result: EvaluatorResult): string {
15
return `(kind: ${result.kind}) ${result.value}${
16
- result.logs.length > 0 ? `\nlogs: [${result.logs.toString()}]` : ""
16
+ result.logs.length > 0 ? `\nlogs: [${result.logs.toString()}]` : ''
17
}`;
18
}
19
function makeError(description: string, value: string): SproutResult {
20
return {
21
- kind: "invalid",
22
- value: description + "\n" + value,
21
+ kind: 'invalid',
22
+ value: description + '\n' + value,
23
};
24
}
25
function logsEqual(a: Array<string>, b: Array<string>) {
@@ -30,19 +30,19 @@ function logsEqual(a: Array<string>, b: Array<string>) {
30
}
31
export function runSprout(
32
originalCode: string,
33
- forgetCode: string
33
+ forgetCode: string,
34
): SproutResult {
35
const forgetResult = doEval(forgetCode);
36
- if (forgetResult.kind === "UnexpectedError") {
37
- return makeError("Unexpected error in Forget runner", forgetResult.value);
36
+ if (forgetResult.kind === 'UnexpectedError') {
37
+ return makeError('Unexpected error in Forget runner', forgetResult.value);
38
}
39
- if (originalCode.indexOf("@disableNonForgetInSprout") === -1) {
39
+ if (originalCode.indexOf('@disableNonForgetInSprout') === -1) {
40
const nonForgetResult = doEval(originalCode);
41
42
- if (nonForgetResult.kind === "UnexpectedError") {
42
+ if (nonForgetResult.kind === 'UnexpectedError') {
43
return makeError(
44
- "Unexpected error in non-forget runner",
45
- nonForgetResult.value
44
+ 'Unexpected error in non-forget runner',
45
+ nonForgetResult.value,
46
);
47
} else if (
48
forgetResult.kind !== nonForgetResult.kind ||
@@ -50,17 +50,17 @@ export function runSprout(
50
!logsEqual(forgetResult.logs, nonForgetResult.logs)
51
) {
52
return makeError(
53
- "Found differences in evaluator results",
53
+ 'Found differences in evaluator results',
54
`Non-forget (expected):
55
${stringify(nonForgetResult)}
56
Forget:
57
${stringify(forgetResult)}
58
-`
58
+`,
59
);
60
}
61
}
62
return {
63
- kind: "success",
63
+ kind: 'success',
64
value: stringify(forgetResult),
65
};
66
}
compiler/packages/snap/src/sprout/shared-runtime.ts
+32
-32
@@ -5,8 +5,8 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-import { IntlVariations, IntlViewerContext, init } from "fbt";
9
-import React, { FunctionComponent } from "react";
8
+import {IntlVariations, IntlViewerContext, init} from 'fbt';
9
+import React, {FunctionComponent} from 'react';
10
11
/**
12
* This file is meant for use by `runner-evaluator` and fixture tests.
@@ -23,11 +23,11 @@ import React, { FunctionComponent } from "react";
23
* ```
24
*/
25
26
-export type StringKeyedObject = { [key: string]: unknown };
26
+export type StringKeyedObject = {[key: string]: unknown};
27
28
-export const CONST_STRING0 = "global string 0";
29
-export const CONST_STRING1 = "global string 1";
30
-export const CONST_STRING2 = "global string 2";
28
+export const CONST_STRING0 = 'global string 0';
29
+export const CONST_STRING1 = 'global string 1';
30
+export const CONST_STRING2 = 'global string 2';
31
32
export const CONST_NUMBER0 = 0;
33
export const CONST_NUMBER1 = 1;
@@ -39,7 +39,7 @@ export const CONST_FALSE = false;
39
export function initFbt(): void {
40
const viewerContext: IntlViewerContext = {
41
GENDER: IntlVariations.GENDER_UNKNOWN,
42
- locale: "en_US",
42
+ locale: 'en_US',
43
};
44
45
init({
@@ -52,16 +52,16 @@ export function initFbt(): void {
52
53
export function mutate(arg: any): void {
54
// don't mutate primitive
55
- if (arg == null || typeof arg !== "object") {
55
+ if (arg == null || typeof arg !== 'object') {
56
return;
57
}
58
59
let count: number = 0;
60
let key;
61
while (true) {
62
- key = "wat" + count;
62
+ key = 'wat' + count;
63
if (!Object.hasOwn(arg, key)) {
64
- arg[key] = "joe";
64
+ arg[key] = 'joe';
65
return;
66
}
67
count++;
@@ -75,19 +75,19 @@ export function mutateAndReturn<T>(arg: T): T {
75
76
export function mutateAndReturnNewValue<T>(arg: T): string {
77
mutate(arg);
78
- return "hello!";
78
+ return 'hello!';
79
}
80
81
export function setProperty(arg: any, property: any): void {
82
// don't mutate primitive
83
- if (arg == null || typeof arg !== "object") {
83
+ if (arg == null || typeof arg !== 'object') {
84
return arg;
85
}
86
87
let count: number = 0;
88
let key;
89
while (true) {
90
- key = "wat" + count;
90
+ key = 'wat' + count;
91
if (!Object.hasOwn(arg, key)) {
92
arg[key] = property;
93
return arg;
@@ -128,7 +128,7 @@ export function shallowCopy(obj: object): object {
128
}
129
130
export function makeObject_Primitives(): StringKeyedObject {
131
- return { a: 0, b: "value1", c: true };
131
+ return {a: 0, b: 'value1', c: true};
132
}
133
134
export function makeArray<T>(...values: Array<T>): Array<T> {
@@ -208,37 +208,37 @@ export function Text(props: {
208
value: string;
209
children?: Array<React.ReactNode>;
210
}): React.ReactElement {
211
- return React.createElement("div", null, props.value, props.children);
211
+ return React.createElement('div', null, props.value, props.children);
212
}
213
214
export function StaticText1(props: {
215
children?: Array<React.ReactNode>;
216
}): React.ReactElement {
217
- return React.createElement("div", null, "StaticText1", props.children);
217
+ return React.createElement('div', null, 'StaticText1', props.children);
218
}
219
220
export function StaticText2(props: {
221
children?: Array<React.ReactNode>;
222
}): React.ReactElement {
223
- return React.createElement("div", null, "StaticText2", props.children);
223
+ return React.createElement('div', null, 'StaticText2', props.children);
224
}
225
226
export function RenderPropAsChild(props: {
227
items: Array<() => React.ReactNode>;
228
}): React.ReactElement {
229
return React.createElement(
230
- "div",
230
+ 'div',
231
null,
232
- "HigherOrderComponent",
233
- props.items.map((item) => item())
232
+ 'HigherOrderComponent',
233
+ props.items.map(item => item()),
234
);
235
}
236
237
export function Stringify(props: any): React.ReactElement {
238
return React.createElement(
239
- "div",
239
+ 'div',
240
null,
241
- toJSON(props, props?.shouldInvokeFns)
241
+ toJSON(props, props?.shouldInvokeFns),
242
);
243
}
244
@@ -249,7 +249,7 @@ export function ValidateMemoization({
249
inputs: Array<any>;
250
output: any;
251
}): React.ReactElement {
252
- "use no forget";
252
+ 'use no forget';
253
const [previousInputs, setPreviousInputs] = React.useState(inputs);
254
const [previousOutput, setPreviousOutput] = React.useState(output);
255
if (
@@ -261,13 +261,13 @@ export function ValidateMemoization({
261
setPreviousOutput(output);
262
} else if (output !== previousOutput) {
263
// Else output should be stable
264
- throw new Error("Output identity changed but inputs did not");
264
+ throw new Error('Output identity changed but inputs did not');
265
}
266
- return React.createElement(Stringify, { inputs, output });
266
+ return React.createElement(Stringify, {inputs, output});
267
}
268
269
export function createHookWrapper<TProps, TRet>(
270
- useMaybeHook: (props: TProps) => TRet
270
+ useMaybeHook: (props: TProps) => TRet,
271
): FunctionComponent<TProps> {
272
return function Component(props: TProps): React.ReactElement {
273
const result = useMaybeHook(props);
@@ -283,27 +283,27 @@ export function toJSON(value: any, invokeFns: boolean = false): string {
283
const seen = new Map();
284
285
return JSON.stringify(value, (_key: string, val: any) => {
286
- if (typeof val === "function") {
286
+ if (typeof val === 'function') {
287
if (val.length === 0 && invokeFns) {
288
return {
289
- kind: "Function",
289
+ kind: 'Function',
290
result: val(),
291
};
292
} else {
293
return `[[ function params=${val.length} ]]`;
294
}
295
- } else if (typeof val === "object") {
295
+ } else if (typeof val === 'object') {
296
let id = seen.get(val);
297
if (id != null) {
298
return `[[ cyclic ref *${id} ]]`;
299
} else if (val instanceof Map) {
300
return {
301
- kind: "Map",
301
+ kind: 'Map',
302
value: Array.from(val.entries()),
303
};
304
} else if (val instanceof Set) {
305
return {
306
- kind: "Set",
306
+ kind: 'Set',
307
value: Array.from(val.values()),
308
};
309
}
@@ -344,6 +344,6 @@ export const ObjectWithHooks = {
344
export function useFragment(..._args: Array<any>): object {
345
return {
346
a: [1, 2, 3],
347
- b: { c: { d: 4 } },
347
+ b: {c: {d: 4}},
348
};
349
}
compiler/scripts/copyright.js
+14
-14
@@ -5,10 +5,10 @@
5
* LICENSE file in the root directory of this source tree.
6
*/
7
8
-"use strict";
8
+'use strict';
9
10
-const fs = require("fs");
11
-const glob = require("glob");
10
+const fs = require('fs');
11
+const glob = require('glob');
12
13
const META_COPYRIGHT_COMMENT_BLOCK =
14
`/**
@@ -16,20 +16,20 @@ const META_COPYRIGHT_COMMENT_BLOCK =
16
*
17
* This source code is licensed under the MIT license found in the
18
* LICENSE file in the root directory of this source tree.
19
- */`.trim() + "\n\n";
19
+ */`.trim() + '\n\n';
20
21
-const files = glob.sync("**/*.{js,ts,tsx,jsx,rs}", {
21
+const files = glob.sync('**/*.{js,ts,tsx,jsx,rs}', {
22
ignore: [
23
- "**/dist/**",
24
- "**/node_modules/**",
25
- "**/tests/fixtures/**",
26
- "**/__tests__/fixtures/**",
23
+ '**/dist/**',
24
+ '**/node_modules/**',
25
+ '**/tests/fixtures/**',
26
+ '**/__tests__/fixtures/**',
27
],
28
});
29
30
const updatedFiles = new Map();
31
let hasErrors = false;
32
-files.forEach((file) => {
32
+files.forEach(file => {
33
try {
34
const result = processFile(file);
35
if (result != null) {
@@ -41,17 +41,17 @@ files.forEach((file) => {
41
}
42
});
43
if (hasErrors) {
44
- console.error("Update failed");
44
+ console.error('Update failed');
45
process.exit(1);
46
} else {
47
for (const [file, source] of updatedFiles) {
48
- fs.writeFileSync(file, source, "utf8");
48
+ fs.writeFileSync(file, source, 'utf8');
49
}
50
- console.log("Update complete");
50
+ console.log('Update complete');
51
}
52
53
function processFile(file) {
54
- let source = fs.readFileSync(file, "utf8");
54
+ let source = fs.readFileSync(file, 'utf8');
55
56
if (source.indexOf(META_COPYRIGHT_COMMENT_BLOCK) === 0) {
57
return null;
compiler/scripts/release/prompt-for-otp.js
+3
-3
@@ -1,15 +1,15 @@
1
#!/usr/bin/env node
2
3
-const prompt = require("prompt-promise");
3
+const prompt = require('prompt-promise');
4
5
const run = async () => {
6
while (true) {
7
- const otp = await prompt("NPM 2-factor auth code: ");
7
+ const otp = await prompt('NPM 2-factor auth code: ');
8
prompt.done();
9
if (otp) {
10
return otp;
11
} else {
12
- console.error("\nTwo-factor auth is required to publish.");
12
+ console.error('\nTwo-factor auth is required to publish.');
13
// (Ask again.)
14
}
15
}
compiler/scripts/release/publish-manual.js
+45
-45
@@ -1,21 +1,21 @@
1
-const cp = require("child_process");
2
-const ora = require("ora");
3
-const path = require("path");
4
-const yargs = require("yargs");
5
-const util = require("util");
6
-const { hashElement } = require("folder-hash");
7
-const promptForOTP = require("./prompt-for-otp");
1
+const cp = require('child_process');
2
+const ora = require('ora');
3
+const path = require('path');
4
+const yargs = require('yargs');
5
+const util = require('util');
6
+const {hashElement} = require('folder-hash');
7
+const promptForOTP = require('./prompt-for-otp');
8
9
const PUBLISHABLE_PACKAGES = [
10
- "babel-plugin-react-compiler",
11
- "eslint-plugin-react-compiler",
12
- "react-compiler-healthcheck",
10
+ 'babel-plugin-react-compiler',
11
+ 'eslint-plugin-react-compiler',
12
+ 'react-compiler-healthcheck',
13
];
14
const TIME_TO_RECONSIDER = 3_000;
15
16
function _spawn(command, args, options, cb) {
17
const child = cp.spawn(command, args, options);
18
- child.on("close", (exitCode) => {
18
+ child.on('close', exitCode => {
19
cb(null, exitCode);
20
});
21
return child;
@@ -34,7 +34,7 @@ function execHelper(command, options, streamStdout = false) {
34
}
35
36
function sleep(ms) {
37
- return new Promise((resolve) => setTimeout(resolve, ms));
37
+ return new Promise(resolve => setTimeout(resolve, ms));
38
}
39
40
async function getDateStringForCommit(commit) {
@@ -70,35 +70,35 @@ async function getDateStringForCommit(commit) {
70
*/
71
async function main() {
72
const argv = yargs(process.argv.slice(2))
73
- .option("packages", {
74
- description: "which packages to publish, defaults to all",
73
+ .option('packages', {
74
+ description: 'which packages to publish, defaults to all',
75
choices: PUBLISHABLE_PACKAGES,
76
default: PUBLISHABLE_PACKAGES,
77
})
78
- .option("for-real", {
79
- alias: "frfr",
78
+ .option('for-real', {
79
+ alias: 'frfr',
80
description:
81
- "whether to publish to npm (npm publish) or dryrun (npm publish --dry-run)",
82
- type: "boolean",
81
+ 'whether to publish to npm (npm publish) or dryrun (npm publish --dry-run)',
82
+ type: 'boolean',
83
default: false,
84
})
85
- .option("debug", {
85
+ .option('debug', {
86
description:
87
- "If enabled, will always run npm commands in dry run mode irregardless of the for-real flag",
88
- type: "boolean",
87
+ 'If enabled, will always run npm commands in dry run mode irregardless of the for-real flag',
88
+ type: 'boolean',
89
default: false,
90
})
91
- .help("help")
91
+ .help('help')
92
.parseSync();
93
94
- const { packages, forReal, debug } = argv;
94
+ const {packages, forReal, debug} = argv;
95
96
if (debug === false) {
97
- const currBranchName = await execHelper("git rev-parse --abbrev-ref HEAD");
98
- const isPristine = (await execHelper("git status --porcelain")) === "";
99
- if (currBranchName !== "main" || isPristine === false) {
97
+ const currBranchName = await execHelper('git rev-parse --abbrev-ref HEAD');
98
+ const isPristine = (await execHelper('git status --porcelain')) === '';
99
+ if (currBranchName !== 'main' || isPristine === false) {
100
throw new Error(
101
- "This script must be run from the `main` branch with no uncommitted changes"
101
+ 'This script must be run from the `main` branch with no uncommitted changes'
102
);
103
}
104
}
@@ -109,11 +109,11 @@ async function main() {
109
}
110
const spinner = ora(
111
`Preparing to publish ${
112
- forReal === true ? "(for real)" : "(dry run)"
112
+ forReal === true ? '(for real)' : '(dry run)'
113
} [debug=${debug}]`
114
).info();
115
116
- spinner.info("Building packages");
116
+ spinner.info('Building packages');
117
for (const pkgName of pkgNames) {
118
const command = `yarn workspace ${pkgName} run build`;
119
spinner.start(`Running: ${command}\n`);
@@ -128,14 +128,14 @@ async function main() {
128
spinner.stop();
129
130
if (forReal === false) {
131
- spinner.info("Dry run: Report tarball contents");
131
+ spinner.info('Dry run: Report tarball contents');
132
for (const pkgName of pkgNames) {
133
console.log(`\n========== ${pkgName} ==========\n`);
134
spinner.start(`Running npm pack --dry-run\n`);
135
try {
136
- await spawnHelper("npm", ["pack", "--dry-run"], {
136
+ await spawnHelper('npm', ['pack', '--dry-run'], {
137
cwd: path.resolve(__dirname, `../../packages/${pkgName}`),
138
- stdio: "inherit",
138
+ stdio: 'inherit',
139
});
140
} catch (e) {
141
spinner.fail(e.toString());
@@ -144,26 +144,26 @@ async function main() {
144
spinner.stop(`Successfully packed ${pkgName} (dry run)`);
145
}
146
spinner.succeed(
147
- "Please confirm contents of packages before publishing. You can run this command again with --for-real to publish to npm"
147
+ 'Please confirm contents of packages before publishing. You can run this command again with --for-real to publish to npm'
148
);
149
}
150
151
if (forReal === true) {
152
const otp = await promptForOTP();
153
const commit = await execHelper(
154
- "git show -s --no-show-signature --format=%h",
154
+ 'git show -s --no-show-signature --format=%h',
155
{
156
- cwd: path.resolve(__dirname, ".."),
156
+ cwd: path.resolve(__dirname, '..'),
157
}
158
);
159
const dateString = await getDateStringForCommit(commit);
160
161
for (const pkgName of pkgNames) {
162
const pkgDir = path.resolve(__dirname, `../../packages/${pkgName}`);
163
- const { hash } = await hashElement(pkgDir, {
164
- encoding: "hex",
165
- folders: { exclude: ["node_modules"] },
166
- files: { exclude: [".DS_Store"] },
163
+ const {hash} = await hashElement(pkgDir, {
164
+ encoding: 'hex',
165
+ folders: {exclude: ['node_modules']},
166
+ files: {exclude: ['.DS_Store']},
167
});
168
const truncatedHash = hash.slice(0, 7);
169
const newVersion = `0.0.0-experimental-${truncatedHash}-${dateString}`;
@@ -205,17 +205,17 @@ async function main() {
205
console.log(`\n========== ${pkgName} ==========\n`);
206
spinner.start(`Publishing ${pkgName} to npm\n`);
207
208
- const opts = debug === true ? ["publish", "--dry-run"] : ["publish"];
208
+ const opts = debug === true ? ['publish', '--dry-run'] : ['publish'];
209
try {
210
await spawnHelper(
211
- "npm",
212
- [...opts, "--registry=https://registry.npmjs.org", `--otp=${otp}`],
211
+ 'npm',
212
+ [...opts, '--registry=https://registry.npmjs.org', `--otp=${otp}`],
213
{
214
cwd: pkgDir,
215
- stdio: "inherit",
215
+ stdio: 'inherit',
216
}
217
);
218
- console.log("\n");
218
+ console.log('\n');
219
} catch (e) {
220
spinner.fail(e.toString());
221
throw e;
@@ -223,7 +223,7 @@ async function main() {
223
spinner.succeed(`Successfully published ${pkgName} to npm`);
224
}
225
226
- console.log("\n\n✅ All done, please push version bump commits to GitHub");
226
+ console.log('\n\n✅ All done, please push version bump commits to GitHub');
227
}
228
}
229
compiler/scripts/update-commit-message.js
+25
-27
@@ -13,48 +13,48 @@
13
* - $ GITHUB_AUTH_TOKEN="..." git filter-branch -f --msg-filter "node update-commit-message.js" 2364096862b72cf4d801ef2008c54252335a2df9..HEAD
14
*/
15
16
-const { Octokit, App } = require("octokit");
17
-const fs = require("fs");
16
+const {Octokit, App} = require('octokit');
17
+const fs = require('fs');
18
19
-const OWNER = "facebook";
20
-const REPO = "react-forget";
21
-const octokit = new Octokit({ auth: process.env.GITHUB_AUTH_TOKEN });
19
+const OWNER = 'facebook';
20
+const REPO = 'react-forget';
21
+const octokit = new Octokit({auth: process.env.GITHUB_AUTH_TOKEN});
22
23
-const fetchPullRequest = async (pullNumber) => {
23
+const fetchPullRequest = async pullNumber => {
24
const response = await octokit.request(
25
- "GET /repos/{owner}/{repo}/pulls/{pull_number}",
25
+ 'GET /repos/{owner}/{repo}/pulls/{pull_number}',
26
{
27
owner: OWNER,
28
repo: REPO,
29
pull_number: pullNumber,
30
headers: {
31
- "X-GitHub-Api-Version": "2022-11-28",
31
+ 'X-GitHub-Api-Version': '2022-11-28',
32
},
33
}
34
);
35
- return { body: response.data.body, title: response.data.title };
35
+ return {body: response.data.body, title: response.data.title};
36
};
37
38
function formatCommitMessage(str) {
39
- let formattedStr = "";
40
- let line = "";
39
+ let formattedStr = '';
40
+ let line = '';
41
42
- const trim = str.replace(/(\r\n|\n|\r)/gm, " ").trim();
42
+ const trim = str.replace(/(\r\n|\n|\r)/gm, ' ').trim();
43
if (!trim) {
44
- return "";
44
+ return '';
45
}
46
47
// Split the string into words
48
- const words = trim.split(" ");
48
+ const words = trim.split(' ');
49
// Iterate over each word
50
for (let i = 0; i < words.length; i++) {
51
// If adding the next word doesn't exceed the line length limit, add it to the line
52
if ((line + words[i]).length <= 80) {
53
- line += words[i] + " ";
53
+ line += words[i] + ' ';
54
} else {
55
// Otherwise, add the line to the formatted string and start a new line
56
- formattedStr += line + "\n";
57
- line = words[i] + " ";
56
+ formattedStr += line + '\n';
57
+ line = words[i] + ' ';
58
}
59
}
60
// Add the last line to the formatted string
@@ -63,9 +63,9 @@ function formatCommitMessage(str) {
63
}
64
65
function filterMsg(response) {
66
- const { body, title } = response;
66
+ const {body, title} = response;
67
68
- const msgs = body.split("\n\n").flatMap((x) => x.split("\r\n"));
68
+ const msgs = body.split('\n\n').flatMap(x => x.split('\r\n'));
69
70
const newMessage = [];
71
@@ -74,17 +74,17 @@ function filterMsg(response) {
74
75
for (const msg of msgs) {
76
// remove "Stack from [ghstack] blurb"
77
- if (msg.startsWith("Stack from ")) {
77
+ if (msg.startsWith('Stack from ')) {
78
continue;
79
}
80
81
// remove "* #1234"
82
- if (msg.startsWith("* #")) {
82
+ if (msg.startsWith('* #')) {
83
continue;
84
}
85
86
// remove "* __->__ #1234"
87
- if (msg.startsWith("* __")) {
87
+ if (msg.startsWith('* __')) {
88
continue;
89
}
90
@@ -95,7 +95,7 @@ function filterMsg(response) {
95
newMessage.push(formattedStr);
96
}
97
98
- const updatedMsg = newMessage.join("\n\n");
98
+ const updatedMsg = newMessage.join('\n\n');
99
return updatedMsg;
100
}
101
@@ -109,9 +109,7 @@ function parsePullRequestNumber(text) {
109
if (ghstackMatch) {
110
return ghstackMatch[1];
111
}
112
- const firstLine = text
113
- .split("\n")
114
- .filter((text) => text.trim().length > 0)[0];
112
+ const firstLine = text.split('\n').filter(text => text.trim().length > 0)[0];
113
if (firstLine == null) {
114
return null;
115
}
@@ -124,7 +122,7 @@ function parsePullRequestNumber(text) {
122
}
123
124
async function main() {
127
- const data = fs.readFileSync(0, "utf-8");
125
+ const data = fs.readFileSync(0, 'utf-8');
126
const pr = parsePullRequestNumber(data);
127
128
if (pr) {
scripts/shared/pathsByLanguageVersion.js
-6
@@ -6,8 +6,6 @@
6
*/
7
'use strict';
8
9
-const compilerPaths = ['compiler/**'];
10
-
9
// Files that are transformed and can use ES6/Flow/JSX.
10
const esNextPaths = [
11
// Internal forwarding modules
@@ -27,11 +25,7 @@ const esNextPaths = [
25
// Files that we distribute on npm that should be ES5-only.
26
const es5Paths = ['packages/*/npm/**/*.js'];
27
30
-const typescriptPaths = ['packages/**/*.d.ts'];
31
-
28
module.exports = {
33
- compilerPaths,
29
esNextPaths,
30
es5Paths,
36
- typescriptPaths,
31
};