2 * @fileoverview A rule to suggest using arrow functions as callbacks.
3 * @author Toru Nagashima
8 const astUtils = require("./utils/ast-utils");
10 //------------------------------------------------------------------------------
12 //------------------------------------------------------------------------------
15 * Checks whether or not a given variable is a function name.
16 * @param {eslint-scope.Variable} variable A variable to check.
17 * @returns {boolean} `true` if the variable is a function name.
19 function isFunctionName(variable) {
20 return variable && variable.defs[0].type === "FunctionName";
24 * Checks whether or not a given MetaProperty node equals to a given value.
25 * @param {ASTNode} node A MetaProperty node to check.
26 * @param {string} metaName The name of `MetaProperty.meta`.
27 * @param {string} propertyName The name of `MetaProperty.property`.
28 * @returns {boolean} `true` if the node is the specific value.
30 function checkMetaProperty(node, metaName, propertyName) {
31 return node.meta.name === metaName && node.property.name === propertyName;
35 * Gets the variable object of `arguments` which is defined implicitly.
36 * @param {eslint-scope.Scope} scope A scope to get.
37 * @returns {eslint-scope.Variable} The found variable object.
39 function getVariableOfArguments(scope) {
40 const variables = scope.variables;
42 for (let i = 0; i < variables.length; ++i) {
43 const variable = variables[i];
45 if (variable.name === "arguments") {
48 * If there was a parameter which is named "arguments", the
49 * implicit "arguments" is not defined.
50 * So does fast return with null.
52 return (variable.identifiers.length === 0) ? variable : null;
56 /* istanbul ignore next */
61 * Checks whether or not a given node is a callback.
62 * @param {ASTNode} node A node to check.
64 * {boolean} retv.isCallback - `true` if the node is a callback.
65 * {boolean} retv.isLexicalThis - `true` if the node is with `.bind(this)`.
67 function getCallbackInfo(node) {
68 const retv = { isCallback: false, isLexicalThis: false };
69 let currentNode = node;
70 let parent = node.parent;
74 switch (parent.type) {
76 // Checks parents recursively.
78 case "LogicalExpression":
79 case "ChainExpression":
80 case "ConditionalExpression":
83 // Checks whether the parent node is `.bind(this)` call.
84 case "MemberExpression":
86 parent.object === currentNode &&
87 !parent.property.computed &&
88 parent.property.type === "Identifier" &&
89 parent.property.name === "bind"
91 const maybeCallee = parent.parent.type === "ChainExpression"
95 if (astUtils.isCallee(maybeCallee)) {
97 bound = true; // Use only the first `.bind()` to make `isLexicalThis` value.
98 retv.isLexicalThis = (
99 maybeCallee.parent.arguments.length === 1 &&
100 maybeCallee.parent.arguments[0].type === "ThisExpression"
103 parent = maybeCallee.parent;
112 // Checks whether the node is a callback.
113 case "CallExpression":
114 case "NewExpression":
115 if (parent.callee !== currentNode) {
116 retv.isCallback = true;
124 currentNode = parent;
125 parent = parent.parent;
128 /* istanbul ignore next */
129 throw new Error("unreachable");
133 * Checks whether a simple list of parameters contains any duplicates. This does not handle complex
134 * parameter lists (e.g. with destructuring), since complex parameter lists are a SyntaxError with duplicate
135 * parameter names anyway. Instead, it always returns `false` for complex parameter lists.
136 * @param {ASTNode[]} paramsList The list of parameters for a function
137 * @returns {boolean} `true` if the list of parameters contains any duplicates
139 function hasDuplicateParams(paramsList) {
140 return paramsList.every(param => param.type === "Identifier") && paramsList.length !== new Set(paramsList.map(param => param.name)).size;
143 //------------------------------------------------------------------------------
145 //------------------------------------------------------------------------------
152 description: "require using arrow functions for callbacks",
153 category: "ECMAScript 6",
155 url: "https://eslint.org/docs/rules/prefer-arrow-callback"
162 allowNamedFunctions: {
171 additionalProperties: false
178 preferArrowCallback: "Unexpected function expression."
183 const options = context.options[0] || {};
185 const allowUnboundThis = options.allowUnboundThis !== false; // default to true
186 const allowNamedFunctions = options.allowNamedFunctions;
187 const sourceCode = context.getSourceCode();
190 * {Array<{this: boolean, super: boolean, meta: boolean}>}
191 * - this - A flag which shows there are one or more ThisExpression.
192 * - super - A flag which shows there are one or more Super.
193 * - meta - A flag which shows there are one or more MethProperty.
198 * Pushes new function scope with all `false` flags.
201 function enterScope() {
202 stack.push({ this: false, super: false, meta: false });
206 * Pops a function scope from the stack.
207 * @returns {{this: boolean, super: boolean, meta: boolean}} The information of the last scope.
209 function exitScope() {
215 // Reset internal state.
220 // If there are below, it cannot replace with arrow functions merely.
222 const info = stack[stack.length - 1];
230 const info = stack[stack.length - 1];
238 const info = stack[stack.length - 1];
240 if (info && checkMetaProperty(node, "new", "target")) {
245 // To skip nested scopes.
246 FunctionDeclaration: enterScope,
247 "FunctionDeclaration:exit": exitScope,
250 FunctionExpression: enterScope,
251 "FunctionExpression:exit"(node) {
252 const scopeInfo = exitScope();
254 // Skip named function expressions
255 if (allowNamedFunctions && node.id && node.id.name) {
260 if (node.generator) {
264 // Skip recursive functions.
265 const nameVar = context.getDeclaredVariables(node)[0];
267 if (isFunctionName(nameVar) && nameVar.references.length > 0) {
271 // Skip if it's using arguments.
272 const variable = getVariableOfArguments(context.getScope());
274 if (variable && variable.references.length > 0) {
278 // Reports if it's a callback which can replace with arrows.
279 const callbackInfo = getCallbackInfo(node);
281 if (callbackInfo.isCallback &&
282 (!allowUnboundThis || !scopeInfo.this || callbackInfo.isLexicalThis) &&
288 messageId: "preferArrowCallback",
290 if ((!callbackInfo.isLexicalThis && scopeInfo.this) || hasDuplicateParams(node.params)) {
293 * If the callback function does not have .bind(this) and contains a reference to `this`, there
294 * is no way to determine what `this` should be, so don't perform any fixes.
295 * If the callback function has duplicates in its list of parameters (possible in sloppy mode),
296 * don't replace it with an arrow function, because this is a SyntaxError with arrow functions.
301 // Remove `.bind(this)` if exists.
302 if (callbackInfo.isLexicalThis) {
303 const memberNode = node.parent;
306 * If `.bind(this)` exists but the parent is not `.bind(this)`, don't remove it automatically.
307 * E.g. `(foo || function(){}).bind(this)`
309 if (memberNode.type !== "MemberExpression") {
313 const callNode = memberNode.parent;
314 const firstTokenToRemove = sourceCode.getTokenAfter(memberNode.object, astUtils.isNotClosingParenToken);
315 const lastTokenToRemove = sourceCode.getLastToken(callNode);
318 * If the member expression is parenthesized, don't remove the right paren.
319 * E.g. `(function(){}.bind)(this)`
322 if (astUtils.isParenthesised(sourceCode, memberNode)) {
326 // If comments exist in the `.bind(this)`, don't remove those.
327 if (sourceCode.commentsExistBetween(firstTokenToRemove, lastTokenToRemove)) {
331 yield fixer.removeRange([firstTokenToRemove.range[0], lastTokenToRemove.range[1]]);
334 // Convert the function expression to an arrow function.
335 const functionToken = sourceCode.getFirstToken(node, node.async ? 1 : 0);
336 const leftParenToken = sourceCode.getTokenAfter(functionToken, astUtils.isOpeningParenToken);
338 if (sourceCode.commentsExistBetween(functionToken, leftParenToken)) {
340 // Remove only extra tokens to keep comments.
341 yield fixer.remove(functionToken);
343 yield fixer.remove(node.id);
347 // Remove extra tokens and spaces.
348 yield fixer.removeRange([functionToken.range[0], leftParenToken.range[0]]);
350 yield fixer.insertTextBefore(node.body, "=> ");
352 // Get the node that will become the new arrow function.
353 let replacedNode = callbackInfo.isLexicalThis ? node.parent.parent : node;
355 if (replacedNode.type === "ChainExpression") {
356 replacedNode = replacedNode.parent;
360 * If the replaced node is part of a BinaryExpression, LogicalExpression, or MemberExpression, then
361 * the arrow function needs to be parenthesized, because `foo || () => {}` is invalid syntax even
362 * though `foo || function() {}` is valid.
365 replacedNode.parent.type !== "CallExpression" &&
366 replacedNode.parent.type !== "ConditionalExpression" &&
367 !astUtils.isParenthesised(sourceCode, replacedNode) &&
368 !astUtils.isParenthesised(sourceCode, node)
370 yield fixer.insertTextBefore(replacedNode, "(");
371 yield fixer.insertTextAfter(replacedNode, ")");