-
Notifications
You must be signed in to change notification settings - Fork 48.1k
/
Copy pathExhaustiveDeps.js
591 lines (549 loc) · 18 KB
/
ExhaustiveDeps.js
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
/**
* Copyright (c) Facebook, Inc. and its 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 */
'use strict';
// const [state, setState] = useState() / React.useState()
// ^^^ true for this reference
// const [state, dispatch] = useReducer() / React.useReducer()
// ^^^ true for this reference
// const ref = useRef()
// ^^ true for this reference
// False for everything else.
function isDefinitelyStaticDependency(reference) {
// This function is written defensively because I'm not sure about corner cases.
// TODO: we can strengthen this if we're sure about the types.
const resolved = reference.resolved;
if (resolved == null || !Array.isArray(resolved.defs)) {
return false;
}
const def = resolved.defs[0];
if (def == null || def.node.init == null) {
return false;
}
// Look for `let stuff = SomeHook();`
const init = def.node.init;
if (init.callee == null) {
return false;
}
let callee = init.callee;
// Step into `= React.something` initializer.
if (
callee.type === 'MemberExpression' &&
callee.object.name === 'React' &&
callee.property != null &&
!callee.computed
) {
callee = callee.property;
}
if (callee.type !== 'Identifier') {
return;
}
const id = def.node.id;
if (callee.name === 'useRef' && id.type === 'Identifier') {
// useRef() return value is static.
return true;
} else if (callee.name === 'useState' || callee.name === 'useReducer') {
// Only consider second value in initializing tuple static.
if (
id.type === 'ArrayPattern' &&
id.elements.length === 2 &&
Array.isArray(reference.resolved.identifiers) &&
// Is second tuple value the same reference we're checking?
id.elements[1] === reference.resolved.identifiers[0]
) {
return true;
}
}
// By default assume it's dynamic.
return false;
}
export default {
meta: {
fixable: 'code',
schema: [
{
type: 'object',
additionalProperties: false,
properties: {
additionalHooks: {
type: 'string',
},
},
},
],
},
create(context) {
// Parse the `additionalHooks` regex.
const additionalHooks =
context.options &&
context.options[0] &&
context.options[0].additionalHooks
? new RegExp(context.options[0].additionalHooks)
: undefined;
const options = {additionalHooks};
return {
FunctionExpression: visitFunctionExpression,
ArrowFunctionExpression: visitFunctionExpression,
};
/**
* Visitor for both function expressions and arrow function expressions.
*/
function visitFunctionExpression(node) {
// We only want to lint nodes which are reactive hook callbacks.
if (
(node.type !== 'FunctionExpression' &&
node.type !== 'ArrowFunctionExpression') ||
node.parent.type !== 'CallExpression'
) {
return;
}
const callbackIndex = getReactiveHookCallbackIndex(
node.parent.callee,
options,
);
if (node.parent.arguments[callbackIndex] !== node) {
return;
}
// Get the reactive hook node.
const reactiveHook = node.parent.callee;
// Get the declared dependencies for this reactive hook. If there is no
// second argument then the reactive callback will re-run on every render.
// So no need to check for dependency inclusion.
const depsIndex = callbackIndex + 1;
const declaredDependenciesNode = node.parent.arguments[depsIndex];
if (!declaredDependenciesNode) {
return;
}
// Get the current scope.
const scope = context.getScope();
// Find all our "pure scopes". On every re-render of a component these
// pure scopes may have changes to the variables declared within. So all
// variables used in our reactive hook callback but declared in a pure
// scope need to be listed as dependencies of our reactive hook callback.
//
// According to the rules of React you can't read a mutable value in pure
// scope. We can't enforce this in a lint so we trust that all variables
// declared outside of pure scope are indeed frozen.
const pureScopes = new Set();
{
let currentScope = scope.upper;
while (currentScope) {
pureScopes.add(currentScope);
if (currentScope.type === 'function') {
break;
}
currentScope = currentScope.upper;
}
// If there is no parent function scope then there are no pure scopes.
// The ones we've collected so far are incorrect. So don't continue with
// the lint.
if (!currentScope) {
return;
}
}
// Get dependencies from all our resolved references in pure scopes.
// Key is dependency string, value is whether it's static.
const dependencies = new Map();
gatherDependenciesRecursively(scope);
function gatherDependenciesRecursively(currentScope) {
for (const reference of currentScope.references) {
// If this reference is not resolved or it is not declared in a pure
// scope then we don't care about this reference.
if (!reference.resolved) {
continue;
}
if (!pureScopes.has(reference.resolved.scope)) {
continue;
}
// Narrow the scope of a dependency if it is, say, a member expression.
// Then normalize the narrowed dependency.
const referenceNode = fastFindReferenceWithParent(
node,
reference.identifier,
);
const dependencyNode = getDependency(referenceNode);
const dependency = toPropertyAccessString(dependencyNode);
// Add the dependency to a map so we can make sure it is referenced
// again in our dependencies array. Remember whether it's static.
if (!dependencies.has(dependency)) {
const isStatic = isDefinitelyStaticDependency(reference);
dependencies.set(dependency, {
isStatic,
reference,
});
}
}
for (const childScope of currentScope.childScopes) {
gatherDependenciesRecursively(childScope);
}
}
const declaredDependencies = [];
if (declaredDependenciesNode.type !== 'ArrayExpression') {
// If the declared dependencies are not an array expression then we
// can't verify that the user provided the correct dependencies. Tell
// the user this in an error.
context.report({
node: declaredDependenciesNode,
message:
`React Hook ${context.getSource(reactiveHook)} has a second ` +
"argument which is not an array literal. This means we can't " +
"statically verify whether you've passed the correct dependencies.",
});
} else {
declaredDependenciesNode.elements.forEach(declaredDependencyNode => {
// Skip elided elements.
if (declaredDependencyNode === null) {
return;
}
// If we see a spread element then add a special warning.
if (declaredDependencyNode.type === 'SpreadElement') {
context.report({
node: declaredDependencyNode,
message:
`React Hook ${context.getSource(reactiveHook)} has a spread ` +
"element in its dependency array. This means we can't " +
"statically verify whether you've passed the " +
'correct dependencies.',
});
return;
}
// Try to normalize the declared dependency. If we can't then an error
// will be thrown. We will catch that error and report an error.
let declaredDependency;
try {
declaredDependency = toPropertyAccessString(declaredDependencyNode);
} catch (error) {
if (/Unsupported node type/.test(error.message)) {
context.report({
node: declaredDependencyNode,
message:
`React Hook ${context.getSource(reactiveHook)} has a ` +
`complex expression in the dependency array. ` +
'Extract it to a separate variable so it can be statically checked.',
});
return;
} else {
throw error;
}
}
// Add the dependency to our declared dependency map.
declaredDependencies.push({
key: declaredDependency,
node: declaredDependencyNode,
});
});
}
// TODO: we can do a pass at this code and pick more appropriate
// data structures to avoid nested loops if we can.
let suggestedDependencies = [];
let duplicateDependencies = new Set();
let unnecessaryDependencies = new Set();
let missingDependencies = new Set();
let actualDependencies = Array.from(dependencies.keys());
let foundStaleAssignments = false;
function satisfies(actualDep, dep) {
return actualDep === dep || actualDep.startsWith(dep + '.');
}
// First, ensure what user specified makes sense.
declaredDependencies.forEach(({key}) => {
if (actualDependencies.some(actualDep => satisfies(actualDep, key))) {
// Legit dependency.
if (suggestedDependencies.indexOf(key) === -1) {
suggestedDependencies.push(key);
} else {
// Duplicate. Do nothing.
duplicateDependencies.add(key);
}
} else {
// Unnecessary dependency. Do nothing.
unnecessaryDependencies.add(key);
}
});
// Then fill in the missing ones.
dependencies.forEach(({isStatic, reference}, key) => {
if (reference.writeExpr) {
foundStaleAssignments = true;
context.report({
node: reference.writeExpr,
message:
`Assignments to the '${key}' variable from inside a React ${context.getSource(
reactiveHook,
)} Hook ` +
`will not persist between re-renders. ` +
`If it's only needed by this Hook, move the variable inside it. ` +
`Alternatively, declare a ref with the useRef Hook, ` +
`and keep the mutable value in its 'current' property.`,
});
}
if (
!suggestedDependencies.some(suggestedDep =>
satisfies(key, suggestedDep),
)
) {
if (!isStatic) {
// Legit missing.
suggestedDependencies.push(key);
missingDependencies.add(key);
}
} else {
// Already did that. Do nothing.
}
});
function areDeclaredDepsAlphabetized() {
if (declaredDependencies.length === 0) {
return true;
}
const declaredDepKeys = declaredDependencies.map(dep => dep.key);
const sortedDeclaredDepKeys = declaredDepKeys.slice().sort();
return declaredDepKeys.join(',') === sortedDeclaredDepKeys.join(',');
}
if (areDeclaredDepsAlphabetized()) {
// Alphabetize the autofix, but only if deps were already alphabetized.
suggestedDependencies.sort();
}
const problemCount =
duplicateDependencies.size +
missingDependencies.size +
unnecessaryDependencies.size;
if (problemCount === 0) {
return;
}
if (foundStaleAssignments) {
// The intent isn't clear so we'll wait until you fix those first.
return;
}
function getWarningMessage(deps, singlePrefix, label, fixVerb) {
if (deps.size === 0) {
return null;
}
return (
(deps.size > 1 ? '' : singlePrefix + ' ') +
label +
' ' +
(deps.size > 1 ? 'dependencies' : 'dependency') +
': ' +
joinEnglish(
Array.from(deps)
.sort()
.map(name => "'" + name + "'"),
) +
`. Either ${fixVerb} ${
deps.size > 1 ? 'them' : 'it'
} or remove the dependency array.`
);
}
let extraWarning = '';
if (unnecessaryDependencies.size > 0) {
let badRef = null;
Array.from(unnecessaryDependencies.keys()).forEach(key => {
if (badRef !== null) {
return;
}
if (key.endsWith('.current')) {
badRef = key;
}
});
if (badRef !== null) {
extraWarning =
` Mutable values like '${badRef}' aren't valid dependencies ` +
"because their mutation doesn't re-render the component.";
}
}
context.report({
node: declaredDependenciesNode,
message:
`React Hook ${context.getSource(reactiveHook)} has ` +
// To avoid a long message, show the next actionable item.
(getWarningMessage(missingDependencies, 'a', 'missing', 'include') ||
getWarningMessage(
unnecessaryDependencies,
'an',
'unnecessary',
'exclude',
) ||
getWarningMessage(
duplicateDependencies,
'a',
'duplicate',
'omit',
)) +
extraWarning,
fix(fixer) {
// TODO: consider preserving the comments or formatting?
return fixer.replaceText(
declaredDependenciesNode,
`[${suggestedDependencies.join(', ')}]`,
);
},
});
}
},
};
/**
* Assuming () means the passed/returned node:
* (props) => (props)
* props.(foo) => (props.foo)
* props.foo.(bar) => (props.foo).bar
*/
function getDependency(node) {
if (
node.parent.type === 'MemberExpression' &&
node.parent.object === node &&
node.parent.property.name !== 'current' &&
!node.parent.computed &&
!(
node.parent.parent != null &&
node.parent.parent.type === 'CallExpression' &&
node.parent.parent.callee === node.parent
)
) {
return node.parent;
} else {
return node;
}
}
/**
* Assuming () means the passed node.
* (foo) -> 'foo'
* foo.(bar) -> 'foo.bar'
* foo.bar.(baz) -> 'foo.bar.baz'
* Otherwise throw.
*/
function toPropertyAccessString(node) {
if (node.type === 'Identifier') {
return node.name;
} else if (node.type === 'MemberExpression' && !node.computed) {
const object = toPropertyAccessString(node.object);
const property = toPropertyAccessString(node.property);
return `${object}.${property}`;
} else {
throw new Error(`Unsupported node type: ${node.type}`);
}
}
// What's the index of callback that needs to be analyzed for a given Hook?
// -1 if it's not a Hook we care about (e.g. useState).
// 0 for useEffect/useMemo/useCallback(fn).
// 1 for useImperativeHandle(ref, fn).
// For additionally configured Hooks, assume that they're like useEffect (0).
function getReactiveHookCallbackIndex(node, options) {
let isOnReactObject = false;
if (
node.type === 'MemberExpression' &&
node.object.type === 'Identifier' &&
node.object.name === 'React' &&
node.property.type === 'Identifier' &&
!node.computed
) {
node = node.property;
isOnReactObject = true;
}
if (node.type !== 'Identifier') {
return;
}
switch (node.name) {
case 'useEffect':
case 'useLayoutEffect':
case 'useCallback':
case 'useMemo':
// useEffect(fn)
return 0;
case 'useImperativeHandle':
// useImperativeHandle(ref, fn)
return 1;
default:
if (!isOnReactObject && options && options.additionalHooks) {
// Allow the user to provide a regular expression which enables the lint to
// target custom reactive hooks.
let name;
try {
name = toPropertyAccessString(node);
} catch (error) {
if (/Unsupported node type/.test(error.message)) {
return 0;
} else {
throw error;
}
}
return options.additionalHooks.test(name) ? 0 : -1;
} else {
return -1;
}
}
}
/**
* ESLint won't assign node.parent to references from context.getScope()
*
* So instead we search for the node from an ancestor assigning node.parent
* as we go. This mutates the AST.
*
* This traversal is:
* - optimized by only searching nodes with a range surrounding our target node
* - agnostic to AST node types, it looks for `{ type: string, ... }`
*/
function fastFindReferenceWithParent(start, target) {
let queue = [start];
let item = null;
while (queue.length) {
item = queue.shift();
if (isSameIdentifier(item, target)) {
return item;
}
if (!isAncestorNodeOf(item, target)) {
continue;
}
for (let [key, value] of Object.entries(item)) {
if (key === 'parent') {
continue;
}
if (isNodeLike(value)) {
value.parent = item;
queue.push(value);
} else if (Array.isArray(value)) {
value.forEach(val => {
if (isNodeLike(val)) {
val.parent = item;
queue.push(val);
}
});
}
}
}
return null;
}
function joinEnglish(arr) {
let s = '';
for (let i = 0; i < arr.length; i++) {
s += arr[i];
if (i === 0 && arr.length === 2) {
s += ' and ';
} else if (i === arr.length - 2 && arr.length > 2) {
s += ', and ';
} else if (i < arr.length - 1) {
s += ', ';
}
}
return s;
}
function isNodeLike(val) {
return (
typeof val === 'object' &&
val !== null &&
!Array.isArray(val) &&
typeof val.type === 'string'
);
}
function isSameIdentifier(a, b) {
return (
a.type === 'Identifier' &&
a.name === b.name &&
a.range[0] === b.range[0] &&
a.range[1] === b.range[1]
);
}
function isAncestorNodeOf(a, b) {
return a.range[0] <= b.range[0] && a.range[1] >= b.range[1];
}