forked from sindresorhus/eslint-plugin-unicorn
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
no-array-for-each.js
485 lines (412 loc) · 13.8 KB
/
no-array-for-each.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
'use strict';
const {
isParenthesized,
isCommaToken,
isSemicolonToken,
isClosingParenToken,
findVariable,
hasSideEffect,
} = require('eslint-utils');
const {methodCallSelector, referenceIdentifierSelector} = require('./selectors/index.js');
const {extendFixRange} = require('./fix/index.js');
const needsSemicolon = require('./utils/needs-semicolon.js');
const shouldAddParenthesesToExpressionStatementExpression = require('./utils/should-add-parentheses-to-expression-statement-expression.js');
const shouldAddParenthesesToMemberExpressionObject = require('./utils/should-add-parentheses-to-member-expression-object.js');
const {getParentheses, getParenthesizedRange} = require('./utils/parentheses.js');
const isFunctionSelfUsedInside = require('./utils/is-function-self-used-inside.js');
const {isNodeMatches} = require('./utils/is-node-matches.js');
const assertToken = require('./utils/assert-token.js');
const {fixSpaceAroundKeyword, removeParentheses} = require('./fix/index.js');
const {isArrowFunctionBody} = require('./ast/index.js');
const MESSAGE_ID_ERROR = 'no-array-for-each/error';
const MESSAGE_ID_SUGGESTION = 'no-array-for-each/suggestion';
const messages = {
[MESSAGE_ID_ERROR]: 'Use `for…of` instead of `.forEach(…)`.',
[MESSAGE_ID_SUGGESTION]: 'Switch to `for…of`.',
};
const forEachMethodCallSelector = methodCallSelector({
method: 'forEach',
includeOptionalCall: true,
includeOptionalMember: true,
});
const continueAbleNodeTypes = new Set([
'WhileStatement',
'DoWhileStatement',
'ForStatement',
'ForOfStatement',
'ForInStatement',
]);
const stripChainExpression = node =>
(node.parent.type === 'ChainExpression' && node.parent.expression === node)
? node.parent
: node;
function isReturnStatementInContinueAbleNodes(returnStatement, callbackFunction) {
for (let node = returnStatement; node && node !== callbackFunction; node = node.parent) {
if (continueAbleNodeTypes.has(node.type)) {
return true;
}
}
return false;
}
function shouldSwitchReturnStatementToBlockStatement(returnStatement) {
const {parent} = returnStatement;
switch (parent.type) {
case 'IfStatement':
return parent.consequent === returnStatement || parent.alternate === returnStatement;
// These parent's body need switch to `BlockStatement` too, but since they are "continueAble", won't fix
// case 'ForStatement':
// case 'ForInStatement':
// case 'ForOfStatement':
// case 'WhileStatement':
// case 'DoWhileStatement':
case 'WithStatement':
return parent.body === returnStatement;
default:
return false;
}
}
function getFixFunction(callExpression, functionInfo, context) {
const sourceCode = context.getSourceCode();
const [callback] = callExpression.arguments;
const parameters = callback.params;
const iterableObject = callExpression.callee.object;
const {returnStatements} = functionInfo.get(callback);
const isOptionalObject = callExpression.callee.optional;
const ancestor = stripChainExpression(callExpression).parent;
const objectText = sourceCode.getText(iterableObject);
const getForOfLoopHeadText = () => {
const [elementText, indexText] = parameters.map(parameter => sourceCode.getText(parameter));
const shouldUseEntries = parameters.length === 2;
let text = 'for (';
text += isFunctionParameterVariableReassigned(callback, context) ? 'let' : 'const';
text += ' ';
text += shouldUseEntries ? `[${indexText}, ${elementText}]` : elementText;
text += ' of ';
const shouldAddParenthesesToObject
= isParenthesized(iterableObject, sourceCode)
|| (
// `1?.forEach()` -> `(1).entries()`
isOptionalObject
&& shouldUseEntries
&& shouldAddParenthesesToMemberExpressionObject(iterableObject, sourceCode)
);
text += shouldAddParenthesesToObject ? `(${objectText})` : objectText;
if (shouldUseEntries) {
text += '.entries()';
}
text += ') ';
return text;
};
const getForOfLoopHeadRange = () => {
const [start] = callExpression.range;
const [end] = getParenthesizedRange(callback.body, sourceCode);
return [start, end];
};
function * replaceReturnStatement(returnStatement, fixer) {
const returnToken = sourceCode.getFirstToken(returnStatement);
assertToken(returnToken, {
expected: 'return',
ruleId: 'no-array-for-each',
});
if (!returnStatement.argument) {
yield fixer.replaceText(returnToken, 'continue');
return;
}
// Remove `return`
yield fixer.remove(returnToken);
const previousToken = sourceCode.getTokenBefore(returnToken);
const nextToken = sourceCode.getTokenAfter(returnToken);
let textBefore = '';
let textAfter = '';
const shouldAddParentheses
= !isParenthesized(returnStatement.argument, sourceCode)
&& shouldAddParenthesesToExpressionStatementExpression(returnStatement.argument);
if (shouldAddParentheses) {
textBefore = `(${textBefore}`;
textAfter = `${textAfter})`;
}
const insertBraces = shouldSwitchReturnStatementToBlockStatement(returnStatement);
if (insertBraces) {
textBefore = `{ ${textBefore}`;
} else if (needsSemicolon(previousToken, sourceCode, shouldAddParentheses ? '(' : nextToken.value)) {
textBefore = `;${textBefore}`;
}
if (textBefore) {
yield fixer.insertTextBefore(nextToken, textBefore);
}
if (textAfter) {
yield fixer.insertTextAfter(returnStatement.argument, textAfter);
}
const returnStatementHasSemicolon = isSemicolonToken(sourceCode.getLastToken(returnStatement));
if (!returnStatementHasSemicolon) {
yield fixer.insertTextAfter(returnStatement, ';');
}
yield fixer.insertTextAfter(returnStatement, ' continue;');
if (insertBraces) {
yield fixer.insertTextAfter(returnStatement, ' }');
}
}
const shouldRemoveExpressionStatementLastToken = token => {
if (!isSemicolonToken(token)) {
return false;
}
if (callback.body.type !== 'BlockStatement') {
return false;
}
return true;
};
function * removeCallbackParentheses(fixer) {
// Opening parenthesis tokens already included in `getForOfLoopHeadRange`
const closingParenthesisTokens = getParentheses(callback, sourceCode)
.filter(token => isClosingParenToken(token));
for (const closingParenthesisToken of closingParenthesisTokens) {
yield fixer.remove(closingParenthesisToken);
}
}
return function * (fixer) {
// `(( foo.forEach(bar => bar) ))`
yield * removeParentheses(callExpression, fixer, sourceCode);
// Replace these with `for (const … of …) `
// foo.forEach(bar => bar)
// ^^^^^^^^^^^^^^^^^^^^^^
// foo.forEach(bar => (bar))
// ^^^^^^^^^^^^^^^^^^^^^^
// foo.forEach(bar => {})
// ^^^^^^^^^^^^^^^^^^^^^^
// foo.forEach(function(bar) {})
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
yield fixer.replaceTextRange(getForOfLoopHeadRange(), getForOfLoopHeadText());
// Parenthesized callback function
// foo.forEach( ((bar => {})) )
// ^^
yield * removeCallbackParentheses(fixer);
const [
penultimateToken,
lastToken,
] = sourceCode.getLastTokens(callExpression, 2);
// The possible trailing comma token of `Array#forEach()` CallExpression
// foo.forEach(bar => {},)
// ^
if (isCommaToken(penultimateToken)) {
yield fixer.remove(penultimateToken);
}
// The closing parenthesis token of `Array#forEach()` CallExpression
// foo.forEach(bar => {})
// ^
yield fixer.remove(lastToken);
for (const returnStatement of returnStatements) {
yield * replaceReturnStatement(returnStatement, fixer);
}
if (ancestor.type === 'ExpressionStatement') {
const expressionStatementLastToken = sourceCode.getLastToken(ancestor);
// Remove semicolon if it's not needed anymore
// foo.forEach(bar => {});
// ^
if (shouldRemoveExpressionStatementLastToken(expressionStatementLastToken)) {
yield fixer.remove(expressionStatementLastToken, fixer);
}
} else if (ancestor.type === 'ArrowFunctionExpression') {
yield fixer.insertTextBefore(callExpression, '{ ');
yield fixer.insertTextAfter(callExpression, ' }');
}
yield * fixSpaceAroundKeyword(fixer, callExpression.parent, sourceCode);
if (isOptionalObject) {
yield fixer.insertTextBefore(callExpression, `if (${objectText}) `);
}
// Prevent possible variable conflicts
yield * extendFixRange(fixer, callExpression.parent.range);
};
}
const isChildScope = (child, parent) => {
for (let scope = child; scope; scope = scope.upper) {
if (scope === parent) {
return true;
}
}
return false;
};
function isFunctionParametersSafeToFix(callbackFunction, {context, scope, callExpression, allIdentifiers}) {
const variables = context.getDeclaredVariables(callbackFunction);
for (const variable of variables) {
if (variable.defs.length !== 1) {
return false;
}
const [definition] = variable.defs;
if (definition.type !== 'Parameter') {
continue;
}
const variableName = definition.name.name;
const [callExpressionStart, callExpressionEnd] = callExpression.range;
for (const identifier of allIdentifiers) {
const {name, range: [start, end]} = identifier;
if (
name !== variableName
|| start < callExpressionStart
|| end > callExpressionEnd
) {
continue;
}
const variable = findVariable(scope, identifier);
if (!variable || variable.scope === scope || isChildScope(scope, variable.scope)) {
return false;
}
}
}
return true;
}
// TODO[@fisker]: Improve `./utils/is-left-hand-side.js` with similar logic
function isAssignmentLeftHandSide(node) {
const {parent} = node;
switch (parent.type) {
case 'AssignmentExpression':
case 'ForInStatement':
case 'ForOfStatement':
return parent.left === node;
case 'UpdateExpression':
return parent.argument === node;
case 'Property':
return parent.value === node && isAssignmentLeftHandSide(parent);
case 'AssignmentPattern':
return parent.left === node && isAssignmentLeftHandSide(parent);
case 'ArrayPattern':
return parent.elements.includes(node) && isAssignmentLeftHandSide(parent);
case 'ObjectPattern':
return parent.properties.includes(node) && isAssignmentLeftHandSide(parent);
default:
return false;
}
}
function isFunctionParameterVariableReassigned(callbackFunction, context) {
return context.getDeclaredVariables(callbackFunction)
.filter(variable => variable.defs[0].type === 'Parameter')
.some(variable =>
variable.references.some(reference => isAssignmentLeftHandSide(reference.identifier)),
);
}
function isFixable(callExpression, {scope, functionInfo, allIdentifiers, context}) {
// Check `CallExpression`
if (callExpression.optional || callExpression.arguments.length !== 1) {
return false;
}
// Check ancestors, we only fix `ExpressionStatement`
const callOrChainExpression = stripChainExpression(callExpression);
if (
callOrChainExpression.parent.type !== 'ExpressionStatement'
&& !isArrowFunctionBody(callOrChainExpression)
) {
return false;
}
// Check `CallExpression.arguments[0]`;
const [callback] = callExpression.arguments;
if (
// Leave non-function type to `no-array-callback-reference` rule
(callback.type !== 'FunctionExpression' && callback.type !== 'ArrowFunctionExpression')
|| callback.async
|| callback.generator
) {
return false;
}
// Check `callback.params`
const parameters = callback.params;
if (
!(parameters.length === 1 || parameters.length === 2)
// `array.forEach((element = defaultValue) => {})`
|| (parameters.length === 1 && parameters[0].type === 'AssignmentPattern')
|| parameters.some(({type, typeAnnotation}) => type === 'RestElement' || typeAnnotation)
|| !isFunctionParametersSafeToFix(callback, {scope, callExpression, allIdentifiers, context})
) {
return false;
}
// Check `ReturnStatement`s in `callback`
const {returnStatements, scope: callbackScope} = functionInfo.get(callback);
if (returnStatements.some(returnStatement => isReturnStatementInContinueAbleNodes(returnStatement, callback))) {
return false;
}
if (isFunctionSelfUsedInside(callback, callbackScope)) {
return false;
}
return true;
}
const ignoredObjects = [
'React.Children',
'Children',
'R',
// https://www.npmjs.com/package/p-iteration
'pIteration',
];
/** @param {import('eslint').Rule.RuleContext} context */
const create = context => {
const functionStack = [];
const callExpressions = [];
const allIdentifiers = [];
const functionInfo = new Map();
const sourceCode = context.getSourceCode();
return {
':function'(node) {
functionStack.push(node);
functionInfo.set(node, {
returnStatements: [],
scope: context.getScope(),
});
},
':function:exit'() {
functionStack.pop();
},
[referenceIdentifierSelector()](node) {
allIdentifiers.push(node);
},
':function ReturnStatement'(node) {
const currentFunction = functionStack[functionStack.length - 1];
const {returnStatements} = functionInfo.get(currentFunction);
returnStatements.push(node);
},
[forEachMethodCallSelector](node) {
if (isNodeMatches(node.callee.object, ignoredObjects)) {
return;
}
callExpressions.push({
node,
scope: context.getScope(),
});
},
* 'Program:exit'() {
for (const {node, scope} of callExpressions) {
const iterable = node.callee;
const problem = {
node: iterable.property,
messageId: MESSAGE_ID_ERROR,
};
if (!isFixable(node, {scope, allIdentifiers, functionInfo, context})) {
yield problem;
continue;
}
const shouldUseSuggestion = iterable.optional && hasSideEffect(iterable, sourceCode);
const fix = getFixFunction(node, functionInfo, context);
if (shouldUseSuggestion) {
problem.suggest = [
{
messageId: MESSAGE_ID_SUGGESTION,
fix,
},
];
} else {
problem.fix = fix;
}
yield problem;
}
},
};
};
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
create,
meta: {
type: 'suggestion',
docs: {
description: 'Prefer `for…of` over the `forEach` method.',
},
fixable: 'code',
hasSuggestions: true,
messages,
},
};