-
Notifications
You must be signed in to change notification settings - Fork 48.3k
/
Copy pathReactCompilerRule.ts
351 lines (335 loc) · 10.6 KB
/
ReactCompilerRule.ts
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
349
350
351
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {transformFromAstSync} from '@babel/core';
// @ts-expect-error: no types available
import PluginProposalPrivateMethods from '@babel/plugin-proposal-private-methods';
import type {SourceLocation as BabelSourceLocation} from '@babel/types';
import BabelPluginReactCompiler, {
CompilerErrorDetailOptions,
CompilerSuggestionOperation,
ErrorSeverity,
parsePluginOptions,
validateEnvironmentConfig,
OPT_OUT_DIRECTIVES,
type PluginOptions,
} from 'babel-plugin-react-compiler/src';
import {Logger} from 'babel-plugin-react-compiler/src/Entrypoint';
import type {Rule} from 'eslint';
import {Statement} from 'estree';
import * as HermesParser from 'hermes-parser';
type CompilerErrorDetailWithLoc = Omit<CompilerErrorDetailOptions, 'loc'> & {
loc: BabelSourceLocation;
};
function assertExhaustive(_: never, errorMsg: string): never {
throw new Error(errorMsg);
}
const DEFAULT_REPORTABLE_LEVELS = new Set([
ErrorSeverity.InvalidReact,
ErrorSeverity.InvalidJS,
]);
let reportableLevels = DEFAULT_REPORTABLE_LEVELS;
function isReportableDiagnostic(
detail: CompilerErrorDetailOptions,
): detail is CompilerErrorDetailWithLoc {
return (
reportableLevels.has(detail.severity) &&
detail.loc != null &&
typeof detail.loc !== 'symbol'
);
}
function makeSuggestions(
detail: CompilerErrorDetailOptions,
): Array<Rule.SuggestionReportDescriptor> {
let suggest: Array<Rule.SuggestionReportDescriptor> = [];
if (Array.isArray(detail.suggestions)) {
for (const suggestion of detail.suggestions) {
switch (suggestion.op) {
case CompilerSuggestionOperation.InsertBefore:
suggest.push({
desc: suggestion.description,
fix(fixer) {
return fixer.insertTextBeforeRange(
suggestion.range,
suggestion.text,
);
},
});
break;
case CompilerSuggestionOperation.InsertAfter:
suggest.push({
desc: suggestion.description,
fix(fixer) {
return fixer.insertTextAfterRange(
suggestion.range,
suggestion.text,
);
},
});
break;
case CompilerSuggestionOperation.Replace:
suggest.push({
desc: suggestion.description,
fix(fixer) {
return fixer.replaceTextRange(suggestion.range, suggestion.text);
},
});
break;
case CompilerSuggestionOperation.Remove:
suggest.push({
desc: suggestion.description,
fix(fixer) {
return fixer.removeRange(suggestion.range);
},
});
break;
default:
assertExhaustive(suggestion, 'Unhandled suggestion operation');
}
}
}
return suggest;
}
const COMPILER_OPTIONS: Partial<PluginOptions> = {
noEmit: true,
panicThreshold: 'none',
// Don't emit errors on Flow suppressions--Flow already gave a signal
flowSuppressions: false,
environment: validateEnvironmentConfig({
validateRefAccessDuringRender: false,
}),
};
const rule: Rule.RuleModule = {
meta: {
type: 'problem',
docs: {
description: 'Surfaces diagnostics from React Forget',
recommended: true,
},
fixable: 'code',
hasSuggestions: true,
// validation is done at runtime with zod
schema: [{type: 'object', additionalProperties: true}],
},
create(context: Rule.RuleContext) {
// Compat with older versions of eslint
const sourceCode = context.sourceCode ?? context.getSourceCode();
const filename = context.filename ?? context.getFilename();
const userOpts = context.options[0] ?? {};
if (
userOpts['reportableLevels'] != null &&
userOpts['reportableLevels'] instanceof Set
) {
reportableLevels = userOpts['reportableLevels'];
} else {
reportableLevels = DEFAULT_REPORTABLE_LEVELS;
}
/**
* Experimental setting to report all compilation bailouts on the compilation
* unit (e.g. function or hook) instead of the offensive line.
* Intended to be used when a codebase is 100% reliant on the compiler for
* memoization (i.e. deleted all manual memo) and needs compilation success
* signals for perf debugging.
*/
let __unstable_donotuse_reportAllBailouts: boolean = false;
if (
userOpts['__unstable_donotuse_reportAllBailouts'] != null &&
typeof userOpts['__unstable_donotuse_reportAllBailouts'] === 'boolean'
) {
__unstable_donotuse_reportAllBailouts =
userOpts['__unstable_donotuse_reportAllBailouts'];
}
let shouldReportUnusedOptOutDirective = true;
const options: PluginOptions = parsePluginOptions({
...COMPILER_OPTIONS,
...userOpts,
environment: {
...COMPILER_OPTIONS.environment,
...userOpts.environment,
},
});
const userLogger: Logger | null = options.logger;
options.logger = {
logEvent: (filename, event): void => {
userLogger?.logEvent(filename, event);
if (event.kind === 'CompileError') {
shouldReportUnusedOptOutDirective = false;
const detail = event.detail;
const suggest = makeSuggestions(detail);
if (__unstable_donotuse_reportAllBailouts && event.fnLoc != null) {
const locStr =
detail.loc != null && typeof detail.loc !== 'symbol'
? ` (@:${detail.loc.start.line}:${detail.loc.start.column})`
: '';
/**
* Report bailouts with a smaller span (just the first line).
* Compiler bailout lints only serve to flag that a react function
* has not been optimized by the compiler for codebases which depend
* on compiler memo heavily for perf. These lints are also often not
* actionable.
*/
let endLoc;
if (event.fnLoc.end.line === event.fnLoc.start.line) {
endLoc = event.fnLoc.end;
} else {
endLoc = {
line: event.fnLoc.start.line,
// Babel loc line numbers are 1-indexed
column: sourceCode.text.split(
/\r?\n|\r|\n/g,
event.fnLoc.start.line,
)[event.fnLoc.start.line - 1].length,
};
}
const firstLineLoc = {
start: event.fnLoc.start,
end: endLoc,
};
context.report({
message: `[ReactCompilerBailout] ${detail.reason}${locStr}`,
loc: firstLineLoc,
suggest,
});
}
if (!isReportableDiagnostic(detail)) {
return;
}
if (
hasFlowSuppression(detail.loc, 'react-rule-hook') ||
hasFlowSuppression(detail.loc, 'react-rule-unsafe-ref')
) {
// If Flow already caught this error, we don't need to report it again.
return;
}
const loc =
detail.loc == null || typeof detail.loc == 'symbol'
? event.fnLoc
: detail.loc;
if (loc != null) {
context.report({
message: detail.reason,
loc,
suggest,
});
}
}
},
};
try {
options.environment = validateEnvironmentConfig(
options.environment ?? {},
);
} catch (err) {
options.logger?.logEvent('', err);
}
function hasFlowSuppression(
nodeLoc: BabelSourceLocation,
suppression: string,
): boolean {
const comments = sourceCode.getAllComments();
const flowSuppressionRegex = new RegExp(
'\\$FlowFixMe\\[' + suppression + '\\]',
);
for (const commentNode of comments) {
if (
flowSuppressionRegex.test(commentNode.value) &&
commentNode.loc!.end.line === nodeLoc.start.line - 1
) {
return true;
}
}
return false;
}
let babelAST;
if (filename.endsWith('.tsx') || filename.endsWith('.ts')) {
try {
const {parse: babelParse} = require('@babel/parser');
babelAST = babelParse(sourceCode.text, {
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) {
try {
transformFromAstSync(babelAST, sourceCode.text, {
filename,
highlightCode: false,
retainLines: true,
plugins: [
[PluginProposalPrivateMethods, {loose: true}],
[BabelPluginReactCompiler, options],
],
sourceType: 'module',
configFile: false,
babelrc: false,
});
} catch (err) {
/* errors handled by injected logger */
}
}
function reportUnusedOptOutDirective(stmt: Statement) {
if (
stmt.type === 'ExpressionStatement' &&
stmt.expression.type === 'Literal' &&
typeof stmt.expression.value === 'string' &&
OPT_OUT_DIRECTIVES.has(stmt.expression.value) &&
stmt.loc != null
) {
context.report({
message: `Unused '${stmt.expression.value}' directive`,
loc: stmt.loc,
suggest: [
{
desc: 'Remove the directive',
fix(fixer) {
return fixer.remove(stmt);
},
},
],
});
}
}
if (shouldReportUnusedOptOutDirective) {
return {
FunctionDeclaration(fnDecl) {
for (const stmt of fnDecl.body.body) {
reportUnusedOptOutDirective(stmt);
}
},
ArrowFunctionExpression(fnExpr) {
if (fnExpr.body.type === 'BlockStatement') {
for (const stmt of fnExpr.body.body) {
reportUnusedOptOutDirective(stmt);
}
}
},
FunctionExpression(fnExpr) {
for (const stmt of fnExpr.body.body) {
reportUnusedOptOutDirective(stmt);
}
},
};
} else {
return {};
}
},
};
export default rule;