prefer-arrow-callback.js
14.2 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
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
/**
* @fileoverview A rule to suggest using arrow functions as callbacks.
* @author Toru Nagashima
*/
"use strict";
const astUtils = require("./utils/ast-utils");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Checks whether or not a given variable is a function name.
* @param {eslint-scope.Variable} variable A variable to check.
* @returns {boolean} `true` if the variable is a function name.
*/
function isFunctionName(variable) {
return variable && variable.defs[0].type === "FunctionName";
}
/**
* Checks whether or not a given MetaProperty node equals to a given value.
* @param {ASTNode} node A MetaProperty node to check.
* @param {string} metaName The name of `MetaProperty.meta`.
* @param {string} propertyName The name of `MetaProperty.property`.
* @returns {boolean} `true` if the node is the specific value.
*/
function checkMetaProperty(node, metaName, propertyName) {
return node.meta.name === metaName && node.property.name === propertyName;
}
/**
* Gets the variable object of `arguments` which is defined implicitly.
* @param {eslint-scope.Scope} scope A scope to get.
* @returns {eslint-scope.Variable} The found variable object.
*/
function getVariableOfArguments(scope) {
const variables = scope.variables;
for (let i = 0; i < variables.length; ++i) {
const variable = variables[i];
if (variable.name === "arguments") {
/*
* If there was a parameter which is named "arguments", the
* implicit "arguments" is not defined.
* So does fast return with null.
*/
return (variable.identifiers.length === 0) ? variable : null;
}
}
/* c8 ignore next */
return null;
}
/**
* Checks whether or not a given node is a callback.
* @param {ASTNode} node A node to check.
* @throws {Error} (Unreachable.)
* @returns {Object}
* {boolean} retv.isCallback - `true` if the node is a callback.
* {boolean} retv.isLexicalThis - `true` if the node is with `.bind(this)`.
*/
function getCallbackInfo(node) {
const retv = { isCallback: false, isLexicalThis: false };
let currentNode = node;
let parent = node.parent;
let bound = false;
while (currentNode) {
switch (parent.type) {
// Checks parents recursively.
case "LogicalExpression":
case "ChainExpression":
case "ConditionalExpression":
break;
// Checks whether the parent node is `.bind(this)` call.
case "MemberExpression":
if (
parent.object === currentNode &&
!parent.property.computed &&
parent.property.type === "Identifier" &&
parent.property.name === "bind"
) {
const maybeCallee = parent.parent.type === "ChainExpression"
? parent.parent
: parent;
if (astUtils.isCallee(maybeCallee)) {
if (!bound) {
bound = true; // Use only the first `.bind()` to make `isLexicalThis` value.
retv.isLexicalThis = (
maybeCallee.parent.arguments.length === 1 &&
maybeCallee.parent.arguments[0].type === "ThisExpression"
);
}
parent = maybeCallee.parent;
} else {
return retv;
}
} else {
return retv;
}
break;
// Checks whether the node is a callback.
case "CallExpression":
case "NewExpression":
if (parent.callee !== currentNode) {
retv.isCallback = true;
}
return retv;
default:
return retv;
}
currentNode = parent;
parent = parent.parent;
}
/* c8 ignore next */
throw new Error("unreachable");
}
/**
* Checks whether a simple list of parameters contains any duplicates. This does not handle complex
* parameter lists (e.g. with destructuring), since complex parameter lists are a SyntaxError with duplicate
* parameter names anyway. Instead, it always returns `false` for complex parameter lists.
* @param {ASTNode[]} paramsList The list of parameters for a function
* @returns {boolean} `true` if the list of parameters contains any duplicates
*/
function hasDuplicateParams(paramsList) {
return paramsList.every(param => param.type === "Identifier") && paramsList.length !== new Set(paramsList.map(param => param.name)).size;
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
/** @type {import('../shared/types').Rule} */
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "Require using arrow functions for callbacks",
recommended: false,
url: "https://eslint.org/docs/rules/prefer-arrow-callback"
},
schema: [
{
type: "object",
properties: {
allowNamedFunctions: {
type: "boolean",
default: false
},
allowUnboundThis: {
type: "boolean",
default: true
}
},
additionalProperties: false
}
],
fixable: "code",
messages: {
preferArrowCallback: "Unexpected function expression."
}
},
create(context) {
const options = context.options[0] || {};
const allowUnboundThis = options.allowUnboundThis !== false; // default to true
const allowNamedFunctions = options.allowNamedFunctions;
const sourceCode = context.getSourceCode();
/*
* {Array<{this: boolean, super: boolean, meta: boolean}>}
* - this - A flag which shows there are one or more ThisExpression.
* - super - A flag which shows there are one or more Super.
* - meta - A flag which shows there are one or more MethProperty.
*/
let stack = [];
/**
* Pushes new function scope with all `false` flags.
* @returns {void}
*/
function enterScope() {
stack.push({ this: false, super: false, meta: false });
}
/**
* Pops a function scope from the stack.
* @returns {{this: boolean, super: boolean, meta: boolean}} The information of the last scope.
*/
function exitScope() {
return stack.pop();
}
return {
// Reset internal state.
Program() {
stack = [];
},
// If there are below, it cannot replace with arrow functions merely.
ThisExpression() {
const info = stack[stack.length - 1];
if (info) {
info.this = true;
}
},
Super() {
const info = stack[stack.length - 1];
if (info) {
info.super = true;
}
},
MetaProperty(node) {
const info = stack[stack.length - 1];
if (info && checkMetaProperty(node, "new", "target")) {
info.meta = true;
}
},
// To skip nested scopes.
FunctionDeclaration: enterScope,
"FunctionDeclaration:exit": exitScope,
// Main.
FunctionExpression: enterScope,
"FunctionExpression:exit"(node) {
const scopeInfo = exitScope();
// Skip named function expressions
if (allowNamedFunctions && node.id && node.id.name) {
return;
}
// Skip generators.
if (node.generator) {
return;
}
// Skip recursive functions.
const nameVar = context.getDeclaredVariables(node)[0];
if (isFunctionName(nameVar) && nameVar.references.length > 0) {
return;
}
// Skip if it's using arguments.
const variable = getVariableOfArguments(context.getScope());
if (variable && variable.references.length > 0) {
return;
}
// Reports if it's a callback which can replace with arrows.
const callbackInfo = getCallbackInfo(node);
if (callbackInfo.isCallback &&
(!allowUnboundThis || !scopeInfo.this || callbackInfo.isLexicalThis) &&
!scopeInfo.super &&
!scopeInfo.meta
) {
context.report({
node,
messageId: "preferArrowCallback",
*fix(fixer) {
if ((!callbackInfo.isLexicalThis && scopeInfo.this) || hasDuplicateParams(node.params)) {
/*
* If the callback function does not have .bind(this) and contains a reference to `this`, there
* is no way to determine what `this` should be, so don't perform any fixes.
* If the callback function has duplicates in its list of parameters (possible in sloppy mode),
* don't replace it with an arrow function, because this is a SyntaxError with arrow functions.
*/
return;
}
// Remove `.bind(this)` if exists.
if (callbackInfo.isLexicalThis) {
const memberNode = node.parent;
/*
* If `.bind(this)` exists but the parent is not `.bind(this)`, don't remove it automatically.
* E.g. `(foo || function(){}).bind(this)`
*/
if (memberNode.type !== "MemberExpression") {
return;
}
const callNode = memberNode.parent;
const firstTokenToRemove = sourceCode.getTokenAfter(memberNode.object, astUtils.isNotClosingParenToken);
const lastTokenToRemove = sourceCode.getLastToken(callNode);
/*
* If the member expression is parenthesized, don't remove the right paren.
* E.g. `(function(){}.bind)(this)`
* ^^^^^^^^^^^^
*/
if (astUtils.isParenthesised(sourceCode, memberNode)) {
return;
}
// If comments exist in the `.bind(this)`, don't remove those.
if (sourceCode.commentsExistBetween(firstTokenToRemove, lastTokenToRemove)) {
return;
}
yield fixer.removeRange([firstTokenToRemove.range[0], lastTokenToRemove.range[1]]);
}
// Convert the function expression to an arrow function.
const functionToken = sourceCode.getFirstToken(node, node.async ? 1 : 0);
const leftParenToken = sourceCode.getTokenAfter(functionToken, astUtils.isOpeningParenToken);
if (sourceCode.commentsExistBetween(functionToken, leftParenToken)) {
// Remove only extra tokens to keep comments.
yield fixer.remove(functionToken);
if (node.id) {
yield fixer.remove(node.id);
}
} else {
// Remove extra tokens and spaces.
yield fixer.removeRange([functionToken.range[0], leftParenToken.range[0]]);
}
yield fixer.insertTextBefore(node.body, "=> ");
// Get the node that will become the new arrow function.
let replacedNode = callbackInfo.isLexicalThis ? node.parent.parent : node;
if (replacedNode.type === "ChainExpression") {
replacedNode = replacedNode.parent;
}
/*
* If the replaced node is part of a BinaryExpression, LogicalExpression, or MemberExpression, then
* the arrow function needs to be parenthesized, because `foo || () => {}` is invalid syntax even
* though `foo || function() {}` is valid.
*/
if (
replacedNode.parent.type !== "CallExpression" &&
replacedNode.parent.type !== "ConditionalExpression" &&
!astUtils.isParenthesised(sourceCode, replacedNode) &&
!astUtils.isParenthesised(sourceCode, node)
) {
yield fixer.insertTextBefore(replacedNode, "(");
yield fixer.insertTextAfter(replacedNode, ")");
}
}
});
}
}
};
}
};