UNPKG

11.3 kBJavaScriptView Raw
1/**
2 * @fileoverview A rule to suggest using arrow functions as callbacks.
3 * @author Toru Nagashima
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Helpers
10//------------------------------------------------------------------------------
11
12/**
13 * Checks whether or not a given variable is a function name.
14 * @param {eslint-scope.Variable} variable - A variable to check.
15 * @returns {boolean} `true` if the variable is a function name.
16 */
17function isFunctionName(variable) {
18 return variable && variable.defs[0].type === "FunctionName";
19}
20
21/**
22 * Checks whether or not a given MetaProperty node equals to a given value.
23 * @param {ASTNode} node - A MetaProperty node to check.
24 * @param {string} metaName - The name of `MetaProperty.meta`.
25 * @param {string} propertyName - The name of `MetaProperty.property`.
26 * @returns {boolean} `true` if the node is the specific value.
27 */
28function checkMetaProperty(node, metaName, propertyName) {
29 return node.meta.name === metaName && node.property.name === propertyName;
30}
31
32/**
33 * Gets the variable object of `arguments` which is defined implicitly.
34 * @param {eslint-scope.Scope} scope - A scope to get.
35 * @returns {eslint-scope.Variable} The found variable object.
36 */
37function getVariableOfArguments(scope) {
38 const variables = scope.variables;
39
40 for (let i = 0; i < variables.length; ++i) {
41 const variable = variables[i];
42
43 if (variable.name === "arguments") {
44
45 /*
46 * If there was a parameter which is named "arguments", the
47 * implicit "arguments" is not defined.
48 * So does fast return with null.
49 */
50 return (variable.identifiers.length === 0) ? variable : null;
51 }
52 }
53
54 /* istanbul ignore next */
55 return null;
56}
57
58/**
59 * Checkes whether or not a given node is a callback.
60 * @param {ASTNode} node - A node to check.
61 * @returns {Object}
62 * {boolean} retv.isCallback - `true` if the node is a callback.
63 * {boolean} retv.isLexicalThis - `true` if the node is with `.bind(this)`.
64 */
65function getCallbackInfo(node) {
66 const retv = { isCallback: false, isLexicalThis: false };
67 let currentNode = node;
68 let parent = node.parent;
69
70 while (currentNode) {
71 switch (parent.type) {
72
73 // Checks parents recursively.
74
75 case "LogicalExpression":
76 case "ConditionalExpression":
77 break;
78
79 // Checks whether the parent node is `.bind(this)` call.
80 case "MemberExpression":
81 if (parent.object === currentNode &&
82 !parent.property.computed &&
83 parent.property.type === "Identifier" &&
84 parent.property.name === "bind" &&
85 parent.parent.type === "CallExpression" &&
86 parent.parent.callee === parent
87 ) {
88 retv.isLexicalThis = (
89 parent.parent.arguments.length === 1 &&
90 parent.parent.arguments[0].type === "ThisExpression"
91 );
92 parent = parent.parent;
93 } else {
94 return retv;
95 }
96 break;
97
98 // Checks whether the node is a callback.
99 case "CallExpression":
100 case "NewExpression":
101 if (parent.callee !== currentNode) {
102 retv.isCallback = true;
103 }
104 return retv;
105
106 default:
107 return retv;
108 }
109
110 currentNode = parent;
111 parent = parent.parent;
112 }
113
114 /* istanbul ignore next */
115 throw new Error("unreachable");
116}
117
118/**
119 * Checks whether a simple list of parameters contains any duplicates. This does not handle complex
120 * parameter lists (e.g. with destructuring), since complex parameter lists are a SyntaxError with duplicate
121 * parameter names anyway. Instead, it always returns `false` for complex parameter lists.
122 * @param {ASTNode[]} paramsList The list of parameters for a function
123 * @returns {boolean} `true` if the list of parameters contains any duplicates
124 */
125function hasDuplicateParams(paramsList) {
126 return paramsList.every(param => param.type === "Identifier") && paramsList.length !== new Set(paramsList.map(param => param.name)).size;
127}
128
129//------------------------------------------------------------------------------
130// Rule Definition
131//------------------------------------------------------------------------------
132
133module.exports = {
134 meta: {
135 docs: {
136 description: "require using arrow functions for callbacks",
137 category: "ECMAScript 6",
138 recommended: false,
139 url: "https://eslint.org/docs/rules/prefer-arrow-callback"
140 },
141
142 schema: [
143 {
144 type: "object",
145 properties: {
146 allowNamedFunctions: {
147 type: "boolean"
148 },
149 allowUnboundThis: {
150 type: "boolean"
151 }
152 },
153 additionalProperties: false
154 }
155 ],
156
157 fixable: "code"
158 },
159
160 create(context) {
161 const options = context.options[0] || {};
162
163 const allowUnboundThis = options.allowUnboundThis !== false; // default to true
164 const allowNamedFunctions = options.allowNamedFunctions;
165 const sourceCode = context.getSourceCode();
166
167 /*
168 * {Array<{this: boolean, super: boolean, meta: boolean}>}
169 * - this - A flag which shows there are one or more ThisExpression.
170 * - super - A flag which shows there are one or more Super.
171 * - meta - A flag which shows there are one or more MethProperty.
172 */
173 let stack = [];
174
175 /**
176 * Pushes new function scope with all `false` flags.
177 * @returns {void}
178 */
179 function enterScope() {
180 stack.push({ this: false, super: false, meta: false });
181 }
182
183 /**
184 * Pops a function scope from the stack.
185 * @returns {{this: boolean, super: boolean, meta: boolean}} The information of the last scope.
186 */
187 function exitScope() {
188 return stack.pop();
189 }
190
191 return {
192
193 // Reset internal state.
194 Program() {
195 stack = [];
196 },
197
198 // If there are below, it cannot replace with arrow functions merely.
199 ThisExpression() {
200 const info = stack[stack.length - 1];
201
202 if (info) {
203 info.this = true;
204 }
205 },
206
207 Super() {
208 const info = stack[stack.length - 1];
209
210 if (info) {
211 info.super = true;
212 }
213 },
214
215 MetaProperty(node) {
216 const info = stack[stack.length - 1];
217
218 if (info && checkMetaProperty(node, "new", "target")) {
219 info.meta = true;
220 }
221 },
222
223 // To skip nested scopes.
224 FunctionDeclaration: enterScope,
225 "FunctionDeclaration:exit": exitScope,
226
227 // Main.
228 FunctionExpression: enterScope,
229 "FunctionExpression:exit"(node) {
230 const scopeInfo = exitScope();
231
232 // Skip named function expressions
233 if (allowNamedFunctions && node.id && node.id.name) {
234 return;
235 }
236
237 // Skip generators.
238 if (node.generator) {
239 return;
240 }
241
242 // Skip recursive functions.
243 const nameVar = context.getDeclaredVariables(node)[0];
244
245 if (isFunctionName(nameVar) && nameVar.references.length > 0) {
246 return;
247 }
248
249 // Skip if it's using arguments.
250 const variable = getVariableOfArguments(context.getScope());
251
252 if (variable && variable.references.length > 0) {
253 return;
254 }
255
256 // Reports if it's a callback which can replace with arrows.
257 const callbackInfo = getCallbackInfo(node);
258
259 if (callbackInfo.isCallback &&
260 (!allowUnboundThis || !scopeInfo.this || callbackInfo.isLexicalThis) &&
261 !scopeInfo.super &&
262 !scopeInfo.meta
263 ) {
264 context.report({
265 node,
266 message: "Unexpected function expression.",
267 fix(fixer) {
268 if ((!callbackInfo.isLexicalThis && scopeInfo.this) || hasDuplicateParams(node.params)) {
269
270 /*
271 * If the callback function does not have .bind(this) and contains a reference to `this`, there
272 * is no way to determine what `this` should be, so don't perform any fixes.
273 * If the callback function has duplicates in its list of parameters (possible in sloppy mode),
274 * don't replace it with an arrow function, because this is a SyntaxError with arrow functions.
275 */
276 return null;
277 }
278
279 const paramsLeftParen = node.params.length ? sourceCode.getTokenBefore(node.params[0]) : sourceCode.getTokenBefore(node.body, 1);
280 const paramsRightParen = sourceCode.getTokenBefore(node.body);
281 const asyncKeyword = node.async ? "async " : "";
282 const paramsFullText = sourceCode.text.slice(paramsLeftParen.range[0], paramsRightParen.range[1]);
283 const arrowFunctionText = `${asyncKeyword}${paramsFullText} => ${sourceCode.getText(node.body)}`;
284
285 /*
286 * If the callback function has `.bind(this)`, replace it with an arrow function and remove the binding.
287 * Otherwise, just replace the arrow function itself.
288 */
289 const replacedNode = callbackInfo.isLexicalThis ? node.parent.parent : node;
290
291 /*
292 * If the replaced node is part of a BinaryExpression, LogicalExpression, or MemberExpression, then
293 * the arrow function needs to be parenthesized, because `foo || () => {}` is invalid syntax even
294 * though `foo || function() {}` is valid.
295 */
296 const needsParens = replacedNode.parent.type !== "CallExpression" && replacedNode.parent.type !== "ConditionalExpression";
297 const replacementText = needsParens ? `(${arrowFunctionText})` : arrowFunctionText;
298
299 return fixer.replaceText(replacedNode, replacementText);
300 }
301 });
302 }
303 }
304 };
305 }
306};