-
Notifications
You must be signed in to change notification settings - Fork 51k
Expand file tree
/
Copy pathRunReactCompiler.ts
More file actions
348 lines (317 loc) · 9.87 KB
/
RunReactCompiler.ts
File metadata and controls
348 lines (317 loc) · 9.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* eslint-disable no-for-of-loops/no-for-of-loops */
import {transformFromAstSync} from '@babel/core';
import {parse as babelParse} from '@babel/parser';
import {File} from '@babel/types';
import BabelPluginReactCompiler, {
parsePluginOptions,
validateEnvironmentConfig,
type PluginOptions,
Logger,
LoggerEvent,
} from 'babel-plugin-react-compiler';
import type {SourceCode} from 'eslint';
import type * as ESTree from 'estree';
import * as HermesParser from 'hermes-parser';
import {isDeepStrictEqual} from 'util';
import type {ParseResult} from '@babel/parser';
// Pattern for component names: starts with uppercase letter
const COMPONENT_NAME_PATTERN = /^[A-Z]/;
// Pattern for hook names: starts with 'use' followed by uppercase letter or digit
const HOOK_NAME_PATTERN = /^use[A-Z0-9]/;
/**
* Quick heuristic using ESLint's already-parsed AST to detect if the file
* may contain React components or hooks based on function naming patterns.
* Only checks top-level declarations since components/hooks are declared at module scope.
* Returns true if compilation should proceed, false to skip.
*/
function mayContainReactCode(sourceCode: SourceCode): boolean {
const ast = sourceCode.ast;
// Only check top-level statements - components/hooks are declared at module scope
for (const node of ast.body) {
if (checkTopLevelNode(node)) {
return true;
}
}
return false;
}
function checkTopLevelNode(node: ESTree.Node): boolean {
// Handle Flow component/hook declarations (hermes-eslint produces these node types)
// @ts-expect-error not part of ESTree spec
if (node.type === 'ComponentDeclaration' || node.type === 'HookDeclaration') {
return true;
}
// Handle: export function MyComponent() {} or export const useHook = () => {}
if (node.type === 'ExportNamedDeclaration') {
const decl = (node as ESTree.ExportNamedDeclaration).declaration;
if (decl != null) {
return checkTopLevelNode(decl);
}
return false;
}
// Handle: export default function MyComponent() {} or export default () => {}
if (node.type === 'ExportDefaultDeclaration') {
const decl = (node as ESTree.ExportDefaultDeclaration).declaration;
// Anonymous default function export - compile conservatively
if (
decl.type === 'FunctionExpression' ||
decl.type === 'ArrowFunctionExpression' ||
(decl.type === 'FunctionDeclaration' &&
(decl as ESTree.FunctionDeclaration).id == null)
) {
return true;
}
return checkTopLevelNode(decl as ESTree.Node);
}
// Handle: function MyComponent() {}
// Also handles Flow component/hook syntax transformed to FunctionDeclaration with flags
if (node.type === 'FunctionDeclaration') {
// Check for Hermes-added flags indicating Flow component/hook syntax
if (
'__componentDeclaration' in node ||
'__hookDeclaration' in node
) {
return true;
}
const id = (node as ESTree.FunctionDeclaration).id;
if (id != null) {
const name = id.name;
if (COMPONENT_NAME_PATTERN.test(name) || HOOK_NAME_PATTERN.test(name)) {
return true;
}
}
}
// Handle: const MyComponent = () => {} or const useHook = function() {}
// Also handles: const MyComponent = wrap(() => {})
if (node.type === 'VariableDeclaration') {
for (const decl of (node as ESTree.VariableDeclaration).declarations) {
if (decl.id.type === 'Identifier') {
const init = decl.init;
if (
init != null &&
(init.type === 'ArrowFunctionExpression' ||
init.type === 'FunctionExpression' ||
init.type === 'CallExpression')
) {
const name = decl.id.name;
if (COMPONENT_NAME_PATTERN.test(name) || HOOK_NAME_PATTERN.test(name)) {
return true;
}
}
}
}
}
return false;
}
const COMPILER_OPTIONS: PluginOptions = {
outputMode: 'lint',
panicThreshold: 'none',
// Don't emit errors on Flow suppressions--Flow already gave a signal
flowSuppressions: false,
environment: {
validateRefAccessDuringRender: true,
validateNoSetStateInRender: true,
validateNoSetStateInEffects: true,
validateNoJSXInTryStatements: true,
validateNoImpureFunctionsInRender: true,
validateStaticComponents: true,
validateNoFreezingKnownMutableFunctions: true,
validateNoVoidUseMemo: true,
// TODO: remove, this should be in the type system
validateNoCapitalizedCalls: [],
validateHooksUsage: true,
validateNoDerivedComputationsInEffects: true,
// Temporarily enabled for internal testing
enableUseKeyedState: true,
enableVerboseNoSetStateInEffect: true,
validateExhaustiveEffectDependencies: 'extra-only',
},
};
export type RunCacheEntry = {
sourceCode: string;
filename: string;
userOpts: PluginOptions;
flowSuppressions: Array<{line: number; code: string}>;
events: Array<LoggerEvent>;
};
type RunParams = {
sourceCode: SourceCode;
filename: string;
userOpts: PluginOptions;
};
const FLOW_SUPPRESSION_REGEX = /\$FlowFixMe\[([^\]]*)\]/g;
function getFlowSuppressions(
sourceCode: SourceCode,
): Array<{line: number; code: string}> {
const comments = sourceCode.getAllComments();
const results: Array<{line: number; code: string}> = [];
for (const commentNode of comments) {
const matches = commentNode.value.matchAll(FLOW_SUPPRESSION_REGEX);
for (const match of matches) {
if (match.index != null && commentNode.loc != null) {
const code = match[1];
results.push({
line: commentNode.loc!.end.line,
code,
});
}
}
}
return results;
}
function runReactCompilerImpl({
sourceCode,
filename,
userOpts,
}: RunParams): RunCacheEntry {
// Compat with older versions of eslint
const options = parsePluginOptions({
...COMPILER_OPTIONS,
...userOpts,
environment: {
...COMPILER_OPTIONS.environment,
...userOpts.environment,
},
});
const results: RunCacheEntry = {
sourceCode: sourceCode.text,
filename,
userOpts,
flowSuppressions: [],
events: [],
};
const userLogger: Logger | null = options.logger;
options.logger = {
logEvent: (eventFilename, event): void => {
userLogger?.logEvent(eventFilename, event);
results.events.push(event);
},
};
try {
options.environment = validateEnvironmentConfig(options.environment ?? {});
} catch (err: unknown) {
options.logger?.logEvent(filename, err as LoggerEvent);
}
let babelAST: ParseResult<File> | null = null;
if (filename.endsWith('.tsx') || filename.endsWith('.ts')) {
try {
babelAST = babelParse(sourceCode.text, {
sourceFilename: filename,
sourceType: 'unambiguous',
plugins: ['typescript', 'jsx'],
});
} catch {
/* empty */
}
} else {
try {
babelAST = HermesParser.parse(sourceCode.text, {
babel: true,
enableExperimentalComponentSyntax: true,
sourceFilename: filename,
sourceType: 'module',
});
} catch {
/* empty */
}
}
if (babelAST != null) {
results.flowSuppressions = getFlowSuppressions(sourceCode);
try {
transformFromAstSync(babelAST, sourceCode.text, {
filename,
highlightCode: false,
retainLines: true,
plugins: [[BabelPluginReactCompiler, options]],
sourceType: 'module',
configFile: false,
babelrc: false,
});
} catch (err) {
/* errors handled by injected logger */
}
}
return results;
}
const SENTINEL = Symbol();
// Array backed LRU cache -- should be small < 10 elements
class LRUCache<K, T> {
// newest at headIdx, then headIdx + 1, ..., tailIdx
#values: Array<[K, T | Error] | [typeof SENTINEL, void]>;
#headIdx: number = 0;
constructor(size: number) {
this.#values = new Array(size).fill(SENTINEL);
}
// gets a value and sets it as "recently used"
get(key: K): T | null {
const idx = this.#values.findIndex(entry => entry[0] === key);
// If found, move to front
if (idx === this.#headIdx) {
return this.#values[this.#headIdx][1] as T;
} else if (idx < 0) {
return null;
}
const entry: [K, T] = this.#values[idx] as [K, T];
const len = this.#values.length;
for (let i = 0; i < Math.min(idx, len - 1); i++) {
this.#values[(this.#headIdx + i + 1) % len] =
this.#values[(this.#headIdx + i) % len];
}
this.#values[this.#headIdx] = entry;
return entry[1];
}
push(key: K, value: T): void {
this.#headIdx =
(this.#headIdx - 1 + this.#values.length) % this.#values.length;
this.#values[this.#headIdx] = [key, value];
}
}
const cache = new LRUCache<string, RunCacheEntry>(10);
export default function runReactCompiler({
sourceCode,
filename,
userOpts,
}: RunParams): RunCacheEntry {
const entry = cache.get(filename);
if (
entry != null &&
entry.sourceCode === sourceCode.text &&
isDeepStrictEqual(entry.userOpts, userOpts)
) {
return entry;
}
// Quick heuristic: skip files that don't appear to contain React code.
// We still cache the empty result so subsequent rules don't re-run the check.
if (!mayContainReactCode(sourceCode)) {
const emptyResult: RunCacheEntry = {
sourceCode: sourceCode.text,
filename,
userOpts,
flowSuppressions: [],
events: [],
};
if (entry != null) {
Object.assign(entry, emptyResult);
} else {
cache.push(filename, emptyResult);
}
return {...emptyResult};
}
const runEntry = runReactCompilerImpl({
sourceCode,
filename,
userOpts,
});
// If we have a cache entry, we can update it
if (entry != null) {
Object.assign(entry, runEntry);
} else {
cache.push(filename, runEntry);
}
return {...runEntry};
}