123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379 |
- "use strict";
- const astUtils = require("./utils/ast-utils");
- function isFunctionName(variable) {
- return variable && variable.defs[0].type === "FunctionName";
- }
- function checkMetaProperty(node, metaName, propertyName) {
- return node.meta.name === metaName && node.property.name === propertyName;
- }
- function getVariableOfArguments(scope) {
- const variables = scope.variables;
- for (let i = 0; i < variables.length; ++i) {
- const variable = variables[i];
- if (variable.name === "arguments") {
-
- return (variable.identifiers.length === 0) ? variable : null;
- }
- }
-
- return null;
- }
- function getCallbackInfo(node) {
- const retv = { isCallback: false, isLexicalThis: false };
- let currentNode = node;
- let parent = node.parent;
- let bound = false;
- while (currentNode) {
- switch (parent.type) {
-
- case "LogicalExpression":
- case "ChainExpression":
- case "ConditionalExpression":
- break;
-
- 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;
- retv.isLexicalThis = (
- maybeCallee.parent.arguments.length === 1 &&
- maybeCallee.parent.arguments[0].type === "ThisExpression"
- );
- }
- parent = maybeCallee.parent;
- } else {
- return retv;
- }
- } else {
- return retv;
- }
- break;
-
- case "CallExpression":
- case "NewExpression":
- if (parent.callee !== currentNode) {
- retv.isCallback = true;
- }
- return retv;
- default:
- return retv;
- }
- currentNode = parent;
- parent = parent.parent;
- }
-
- throw new Error("unreachable");
- }
- function hasDuplicateParams(paramsList) {
- return paramsList.every(param => param.type === "Identifier") && paramsList.length !== new Set(paramsList.map(param => param.name)).size;
- }
- module.exports = {
- meta: {
- type: "suggestion",
- docs: {
- description: "require using arrow functions for callbacks",
- category: "ECMAScript 6",
- 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;
- const allowNamedFunctions = options.allowNamedFunctions;
- const sourceCode = context.getSourceCode();
-
- let stack = [];
-
- function enterScope() {
- stack.push({ this: false, super: false, meta: false });
- }
-
- function exitScope() {
- return stack.pop();
- }
- return {
-
- Program() {
- stack = [];
- },
-
- 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;
- }
- },
-
- FunctionDeclaration: enterScope,
- "FunctionDeclaration:exit": exitScope,
-
- FunctionExpression: enterScope,
- "FunctionExpression:exit"(node) {
- const scopeInfo = exitScope();
-
- if (allowNamedFunctions && node.id && node.id.name) {
- return;
- }
-
- if (node.generator) {
- return;
- }
-
- const nameVar = context.getDeclaredVariables(node)[0];
- if (isFunctionName(nameVar) && nameVar.references.length > 0) {
- return;
- }
-
- const variable = getVariableOfArguments(context.getScope());
- if (variable && variable.references.length > 0) {
- return;
- }
-
- 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)) {
-
- return;
- }
-
- if (callbackInfo.isLexicalThis) {
- const memberNode = node.parent;
-
- if (memberNode.type !== "MemberExpression") {
- return;
- }
- const callNode = memberNode.parent;
- const firstTokenToRemove = sourceCode.getTokenAfter(memberNode.object, astUtils.isNotClosingParenToken);
- const lastTokenToRemove = sourceCode.getLastToken(callNode);
-
- if (astUtils.isParenthesised(sourceCode, memberNode)) {
- return;
- }
-
- if (sourceCode.commentsExistBetween(firstTokenToRemove, lastTokenToRemove)) {
- return;
- }
- yield fixer.removeRange([firstTokenToRemove.range[0], lastTokenToRemove.range[1]]);
- }
-
- const functionToken = sourceCode.getFirstToken(node, node.async ? 1 : 0);
- const leftParenToken = sourceCode.getTokenAfter(functionToken, astUtils.isOpeningParenToken);
- if (sourceCode.commentsExistBetween(functionToken, leftParenToken)) {
-
- yield fixer.remove(functionToken);
- if (node.id) {
- yield fixer.remove(node.id);
- }
- } else {
-
- yield fixer.removeRange([functionToken.range[0], leftParenToken.range[0]]);
- }
- yield fixer.insertTextBefore(node.body, "=> ");
-
- let replacedNode = callbackInfo.isLexicalThis ? node.parent.parent : node;
- if (replacedNode.type === "ChainExpression") {
- replacedNode = replacedNode.parent;
- }
-
- 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, ")");
- }
- }
- });
- }
- }
- };
- }
- };
|