no-unused-vars.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  1. /**
  2. * @fileoverview Rule to flag declared but unused variables
  3. * @author Ilya Volodin
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Typedefs
  12. //------------------------------------------------------------------------------
  13. /**
  14. * Bag of data used for formatting the `unusedVar` lint message.
  15. * @typedef {Object} UnusedVarMessageData
  16. * @property {string} varName The name of the unused var.
  17. * @property {'defined'|'assigned a value'} action Description of the vars state.
  18. * @property {string} additional Any additional info to be appended at the end.
  19. */
  20. //------------------------------------------------------------------------------
  21. // Rule Definition
  22. //------------------------------------------------------------------------------
  23. module.exports = {
  24. meta: {
  25. type: "problem",
  26. docs: {
  27. description: "disallow unused variables",
  28. category: "Variables",
  29. recommended: true,
  30. url: "https://eslint.org/docs/rules/no-unused-vars"
  31. },
  32. schema: [
  33. {
  34. oneOf: [
  35. {
  36. enum: ["all", "local"]
  37. },
  38. {
  39. type: "object",
  40. properties: {
  41. vars: {
  42. enum: ["all", "local"]
  43. },
  44. varsIgnorePattern: {
  45. type: "string"
  46. },
  47. args: {
  48. enum: ["all", "after-used", "none"]
  49. },
  50. ignoreRestSiblings: {
  51. type: "boolean"
  52. },
  53. argsIgnorePattern: {
  54. type: "string"
  55. },
  56. caughtErrors: {
  57. enum: ["all", "none"]
  58. },
  59. caughtErrorsIgnorePattern: {
  60. type: "string"
  61. }
  62. },
  63. additionalProperties: false
  64. }
  65. ]
  66. }
  67. ],
  68. messages: {
  69. unusedVar: "'{{varName}}' is {{action}} but never used{{additional}}."
  70. }
  71. },
  72. create(context) {
  73. const sourceCode = context.getSourceCode();
  74. const REST_PROPERTY_TYPE = /^(?:RestElement|(?:Experimental)?RestProperty)$/u;
  75. const config = {
  76. vars: "all",
  77. args: "after-used",
  78. ignoreRestSiblings: false,
  79. caughtErrors: "none"
  80. };
  81. const firstOption = context.options[0];
  82. if (firstOption) {
  83. if (typeof firstOption === "string") {
  84. config.vars = firstOption;
  85. } else {
  86. config.vars = firstOption.vars || config.vars;
  87. config.args = firstOption.args || config.args;
  88. config.ignoreRestSiblings = firstOption.ignoreRestSiblings || config.ignoreRestSiblings;
  89. config.caughtErrors = firstOption.caughtErrors || config.caughtErrors;
  90. if (firstOption.varsIgnorePattern) {
  91. config.varsIgnorePattern = new RegExp(firstOption.varsIgnorePattern, "u");
  92. }
  93. if (firstOption.argsIgnorePattern) {
  94. config.argsIgnorePattern = new RegExp(firstOption.argsIgnorePattern, "u");
  95. }
  96. if (firstOption.caughtErrorsIgnorePattern) {
  97. config.caughtErrorsIgnorePattern = new RegExp(firstOption.caughtErrorsIgnorePattern, "u");
  98. }
  99. }
  100. }
  101. /**
  102. * Generates the message data about the variable being defined and unused,
  103. * including the ignore pattern if configured.
  104. * @param {Variable} unusedVar eslint-scope variable object.
  105. * @returns {UnusedVarMessageData} The message data to be used with this unused variable.
  106. */
  107. function getDefinedMessageData(unusedVar) {
  108. const defType = unusedVar.defs && unusedVar.defs[0] && unusedVar.defs[0].type;
  109. let type;
  110. let pattern;
  111. if (defType === "CatchClause" && config.caughtErrorsIgnorePattern) {
  112. type = "args";
  113. pattern = config.caughtErrorsIgnorePattern.toString();
  114. } else if (defType === "Parameter" && config.argsIgnorePattern) {
  115. type = "args";
  116. pattern = config.argsIgnorePattern.toString();
  117. } else if (defType !== "Parameter" && config.varsIgnorePattern) {
  118. type = "vars";
  119. pattern = config.varsIgnorePattern.toString();
  120. }
  121. const additional = type ? `. Allowed unused ${type} must match ${pattern}` : "";
  122. return {
  123. varName: unusedVar.name,
  124. action: "defined",
  125. additional
  126. };
  127. }
  128. /**
  129. * Generate the warning message about the variable being
  130. * assigned and unused, including the ignore pattern if configured.
  131. * @param {Variable} unusedVar eslint-scope variable object.
  132. * @returns {UnusedVarMessageData} The message data to be used with this unused variable.
  133. */
  134. function getAssignedMessageData(unusedVar) {
  135. const additional = config.varsIgnorePattern ? `. Allowed unused vars must match ${config.varsIgnorePattern.toString()}` : "";
  136. return {
  137. varName: unusedVar.name,
  138. action: "assigned a value",
  139. additional
  140. };
  141. }
  142. //--------------------------------------------------------------------------
  143. // Helpers
  144. //--------------------------------------------------------------------------
  145. const STATEMENT_TYPE = /(?:Statement|Declaration)$/u;
  146. /**
  147. * Determines if a given variable is being exported from a module.
  148. * @param {Variable} variable eslint-scope variable object.
  149. * @returns {boolean} True if the variable is exported, false if not.
  150. * @private
  151. */
  152. function isExported(variable) {
  153. const definition = variable.defs[0];
  154. if (definition) {
  155. let node = definition.node;
  156. if (node.type === "VariableDeclarator") {
  157. node = node.parent;
  158. } else if (definition.type === "Parameter") {
  159. return false;
  160. }
  161. return node.parent.type.indexOf("Export") === 0;
  162. }
  163. return false;
  164. }
  165. /**
  166. * Checks whether a node is a sibling of the rest property or not.
  167. * @param {ASTNode} node a node to check
  168. * @returns {boolean} True if the node is a sibling of the rest property, otherwise false.
  169. */
  170. function hasRestSibling(node) {
  171. return node.type === "Property" &&
  172. node.parent.type === "ObjectPattern" &&
  173. REST_PROPERTY_TYPE.test(node.parent.properties[node.parent.properties.length - 1].type);
  174. }
  175. /**
  176. * Determines if a variable has a sibling rest property
  177. * @param {Variable} variable eslint-scope variable object.
  178. * @returns {boolean} True if the variable is exported, false if not.
  179. * @private
  180. */
  181. function hasRestSpreadSibling(variable) {
  182. if (config.ignoreRestSiblings) {
  183. const hasRestSiblingDefinition = variable.defs.some(def => hasRestSibling(def.name.parent));
  184. const hasRestSiblingReference = variable.references.some(ref => hasRestSibling(ref.identifier.parent));
  185. return hasRestSiblingDefinition || hasRestSiblingReference;
  186. }
  187. return false;
  188. }
  189. /**
  190. * Determines if a reference is a read operation.
  191. * @param {Reference} ref An eslint-scope Reference
  192. * @returns {boolean} whether the given reference represents a read operation
  193. * @private
  194. */
  195. function isReadRef(ref) {
  196. return ref.isRead();
  197. }
  198. /**
  199. * Determine if an identifier is referencing an enclosing function name.
  200. * @param {Reference} ref The reference to check.
  201. * @param {ASTNode[]} nodes The candidate function nodes.
  202. * @returns {boolean} True if it's a self-reference, false if not.
  203. * @private
  204. */
  205. function isSelfReference(ref, nodes) {
  206. let scope = ref.from;
  207. while (scope) {
  208. if (nodes.indexOf(scope.block) >= 0) {
  209. return true;
  210. }
  211. scope = scope.upper;
  212. }
  213. return false;
  214. }
  215. /**
  216. * Gets a list of function definitions for a specified variable.
  217. * @param {Variable} variable eslint-scope variable object.
  218. * @returns {ASTNode[]} Function nodes.
  219. * @private
  220. */
  221. function getFunctionDefinitions(variable) {
  222. const functionDefinitions = [];
  223. variable.defs.forEach(def => {
  224. const { type, node } = def;
  225. // FunctionDeclarations
  226. if (type === "FunctionName") {
  227. functionDefinitions.push(node);
  228. }
  229. // FunctionExpressions
  230. if (type === "Variable" && node.init &&
  231. (node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) {
  232. functionDefinitions.push(node.init);
  233. }
  234. });
  235. return functionDefinitions;
  236. }
  237. /**
  238. * Checks the position of given nodes.
  239. * @param {ASTNode} inner A node which is expected as inside.
  240. * @param {ASTNode} outer A node which is expected as outside.
  241. * @returns {boolean} `true` if the `inner` node exists in the `outer` node.
  242. * @private
  243. */
  244. function isInside(inner, outer) {
  245. return (
  246. inner.range[0] >= outer.range[0] &&
  247. inner.range[1] <= outer.range[1]
  248. );
  249. }
  250. /**
  251. * If a given reference is left-hand side of an assignment, this gets
  252. * the right-hand side node of the assignment.
  253. *
  254. * In the following cases, this returns null.
  255. *
  256. * - The reference is not the LHS of an assignment expression.
  257. * - The reference is inside of a loop.
  258. * - The reference is inside of a function scope which is different from
  259. * the declaration.
  260. * @param {eslint-scope.Reference} ref A reference to check.
  261. * @param {ASTNode} prevRhsNode The previous RHS node.
  262. * @returns {ASTNode|null} The RHS node or null.
  263. * @private
  264. */
  265. function getRhsNode(ref, prevRhsNode) {
  266. const id = ref.identifier;
  267. const parent = id.parent;
  268. const grandparent = parent.parent;
  269. const refScope = ref.from.variableScope;
  270. const varScope = ref.resolved.scope.variableScope;
  271. const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id);
  272. /*
  273. * Inherits the previous node if this reference is in the node.
  274. * This is for `a = a + a`-like code.
  275. */
  276. if (prevRhsNode && isInside(id, prevRhsNode)) {
  277. return prevRhsNode;
  278. }
  279. if (parent.type === "AssignmentExpression" &&
  280. grandparent.type === "ExpressionStatement" &&
  281. id === parent.left &&
  282. !canBeUsedLater
  283. ) {
  284. return parent.right;
  285. }
  286. return null;
  287. }
  288. /**
  289. * Checks whether a given function node is stored to somewhere or not.
  290. * If the function node is stored, the function can be used later.
  291. * @param {ASTNode} funcNode A function node to check.
  292. * @param {ASTNode} rhsNode The RHS node of the previous assignment.
  293. * @returns {boolean} `true` if under the following conditions:
  294. * - the funcNode is assigned to a variable.
  295. * - the funcNode is bound as an argument of a function call.
  296. * - the function is bound to a property and the object satisfies above conditions.
  297. * @private
  298. */
  299. function isStorableFunction(funcNode, rhsNode) {
  300. let node = funcNode;
  301. let parent = funcNode.parent;
  302. while (parent && isInside(parent, rhsNode)) {
  303. switch (parent.type) {
  304. case "SequenceExpression":
  305. if (parent.expressions[parent.expressions.length - 1] !== node) {
  306. return false;
  307. }
  308. break;
  309. case "CallExpression":
  310. case "NewExpression":
  311. return parent.callee !== node;
  312. case "AssignmentExpression":
  313. case "TaggedTemplateExpression":
  314. case "YieldExpression":
  315. return true;
  316. default:
  317. if (STATEMENT_TYPE.test(parent.type)) {
  318. /*
  319. * If it encountered statements, this is a complex pattern.
  320. * Since analyzing complex patterns is hard, this returns `true` to avoid false positive.
  321. */
  322. return true;
  323. }
  324. }
  325. node = parent;
  326. parent = parent.parent;
  327. }
  328. return false;
  329. }
  330. /**
  331. * Checks whether a given Identifier node exists inside of a function node which can be used later.
  332. *
  333. * "can be used later" means:
  334. * - the function is assigned to a variable.
  335. * - the function is bound to a property and the object can be used later.
  336. * - the function is bound as an argument of a function call.
  337. *
  338. * If a reference exists in a function which can be used later, the reference is read when the function is called.
  339. * @param {ASTNode} id An Identifier node to check.
  340. * @param {ASTNode} rhsNode The RHS node of the previous assignment.
  341. * @returns {boolean} `true` if the `id` node exists inside of a function node which can be used later.
  342. * @private
  343. */
  344. function isInsideOfStorableFunction(id, rhsNode) {
  345. const funcNode = astUtils.getUpperFunction(id);
  346. return (
  347. funcNode &&
  348. isInside(funcNode, rhsNode) &&
  349. isStorableFunction(funcNode, rhsNode)
  350. );
  351. }
  352. /**
  353. * Checks whether a given node is unused expression or not.
  354. * @param {ASTNode} node The node itself
  355. * @returns {boolean} The node is an unused expression.
  356. * @private
  357. */
  358. function isUnusedExpression(node) {
  359. const parent = node.parent;
  360. if (parent.type === "ExpressionStatement") {
  361. return true;
  362. }
  363. if (parent.type === "SequenceExpression") {
  364. const isLastExpression = parent.expressions[parent.expressions.length - 1] === node;
  365. if (!isLastExpression) {
  366. return true;
  367. }
  368. return isUnusedExpression(parent);
  369. }
  370. return false;
  371. }
  372. /**
  373. * Checks whether a given reference is a read to update itself or not.
  374. * @param {eslint-scope.Reference} ref A reference to check.
  375. * @param {ASTNode} rhsNode The RHS node of the previous assignment.
  376. * @returns {boolean} The reference is a read to update itself.
  377. * @private
  378. */
  379. function isReadForItself(ref, rhsNode) {
  380. const id = ref.identifier;
  381. const parent = id.parent;
  382. return ref.isRead() && (
  383. // self update. e.g. `a += 1`, `a++`
  384. (
  385. (
  386. parent.type === "AssignmentExpression" &&
  387. parent.left === id &&
  388. isUnusedExpression(parent)
  389. ) ||
  390. (
  391. parent.type === "UpdateExpression" &&
  392. isUnusedExpression(parent)
  393. )
  394. ) ||
  395. // in RHS of an assignment for itself. e.g. `a = a + 1`
  396. (
  397. rhsNode &&
  398. isInside(id, rhsNode) &&
  399. !isInsideOfStorableFunction(id, rhsNode)
  400. )
  401. );
  402. }
  403. /**
  404. * Determine if an identifier is used either in for-in loops.
  405. * @param {Reference} ref The reference to check.
  406. * @returns {boolean} whether reference is used in the for-in loops
  407. * @private
  408. */
  409. function isForInRef(ref) {
  410. let target = ref.identifier.parent;
  411. // "for (var ...) { return; }"
  412. if (target.type === "VariableDeclarator") {
  413. target = target.parent.parent;
  414. }
  415. if (target.type !== "ForInStatement") {
  416. return false;
  417. }
  418. // "for (...) { return; }"
  419. if (target.body.type === "BlockStatement") {
  420. target = target.body.body[0];
  421. // "for (...) return;"
  422. } else {
  423. target = target.body;
  424. }
  425. // For empty loop body
  426. if (!target) {
  427. return false;
  428. }
  429. return target.type === "ReturnStatement";
  430. }
  431. /**
  432. * Determines if the variable is used.
  433. * @param {Variable} variable The variable to check.
  434. * @returns {boolean} True if the variable is used
  435. * @private
  436. */
  437. function isUsedVariable(variable) {
  438. const functionNodes = getFunctionDefinitions(variable),
  439. isFunctionDefinition = functionNodes.length > 0;
  440. let rhsNode = null;
  441. return variable.references.some(ref => {
  442. if (isForInRef(ref)) {
  443. return true;
  444. }
  445. const forItself = isReadForItself(ref, rhsNode);
  446. rhsNode = getRhsNode(ref, rhsNode);
  447. return (
  448. isReadRef(ref) &&
  449. !forItself &&
  450. !(isFunctionDefinition && isSelfReference(ref, functionNodes))
  451. );
  452. });
  453. }
  454. /**
  455. * Checks whether the given variable is after the last used parameter.
  456. * @param {eslint-scope.Variable} variable The variable to check.
  457. * @returns {boolean} `true` if the variable is defined after the last
  458. * used parameter.
  459. */
  460. function isAfterLastUsedArg(variable) {
  461. const def = variable.defs[0];
  462. const params = context.getDeclaredVariables(def.node);
  463. const posteriorParams = params.slice(params.indexOf(variable) + 1);
  464. // If any used parameters occur after this parameter, do not report.
  465. return !posteriorParams.some(v => v.references.length > 0 || v.eslintUsed);
  466. }
  467. /**
  468. * Gets an array of variables without read references.
  469. * @param {Scope} scope an eslint-scope Scope object.
  470. * @param {Variable[]} unusedVars an array that saving result.
  471. * @returns {Variable[]} unused variables of the scope and descendant scopes.
  472. * @private
  473. */
  474. function collectUnusedVariables(scope, unusedVars) {
  475. const variables = scope.variables;
  476. const childScopes = scope.childScopes;
  477. let i, l;
  478. if (scope.type !== "global" || config.vars === "all") {
  479. for (i = 0, l = variables.length; i < l; ++i) {
  480. const variable = variables[i];
  481. // skip a variable of class itself name in the class scope
  482. if (scope.type === "class" && scope.block.id === variable.identifiers[0]) {
  483. continue;
  484. }
  485. // skip function expression names and variables marked with markVariableAsUsed()
  486. if (scope.functionExpressionScope || variable.eslintUsed) {
  487. continue;
  488. }
  489. // skip implicit "arguments" variable
  490. if (scope.type === "function" && variable.name === "arguments" && variable.identifiers.length === 0) {
  491. continue;
  492. }
  493. // explicit global variables don't have definitions.
  494. const def = variable.defs[0];
  495. if (def) {
  496. const type = def.type;
  497. // skip catch variables
  498. if (type === "CatchClause") {
  499. if (config.caughtErrors === "none") {
  500. continue;
  501. }
  502. // skip ignored parameters
  503. if (config.caughtErrorsIgnorePattern && config.caughtErrorsIgnorePattern.test(def.name.name)) {
  504. continue;
  505. }
  506. }
  507. if (type === "Parameter") {
  508. // skip any setter argument
  509. if ((def.node.parent.type === "Property" || def.node.parent.type === "MethodDefinition") && def.node.parent.kind === "set") {
  510. continue;
  511. }
  512. // if "args" option is "none", skip any parameter
  513. if (config.args === "none") {
  514. continue;
  515. }
  516. // skip ignored parameters
  517. if (config.argsIgnorePattern && config.argsIgnorePattern.test(def.name.name)) {
  518. continue;
  519. }
  520. // if "args" option is "after-used", skip used variables
  521. if (config.args === "after-used" && astUtils.isFunction(def.name.parent) && !isAfterLastUsedArg(variable)) {
  522. continue;
  523. }
  524. } else {
  525. // skip ignored variables
  526. if (config.varsIgnorePattern && config.varsIgnorePattern.test(def.name.name)) {
  527. continue;
  528. }
  529. }
  530. }
  531. if (!isUsedVariable(variable) && !isExported(variable) && !hasRestSpreadSibling(variable)) {
  532. unusedVars.push(variable);
  533. }
  534. }
  535. }
  536. for (i = 0, l = childScopes.length; i < l; ++i) {
  537. collectUnusedVariables(childScopes[i], unusedVars);
  538. }
  539. return unusedVars;
  540. }
  541. //--------------------------------------------------------------------------
  542. // Public
  543. //--------------------------------------------------------------------------
  544. return {
  545. "Program:exit"(programNode) {
  546. const unusedVars = collectUnusedVariables(context.getScope(), []);
  547. for (let i = 0, l = unusedVars.length; i < l; ++i) {
  548. const unusedVar = unusedVars[i];
  549. // Report the first declaration.
  550. if (unusedVar.defs.length > 0) {
  551. // report last write reference, https://github.com/eslint/eslint/issues/14324
  552. const writeReferences = unusedVar.references.filter(ref => ref.isWrite() && ref.from.variableScope === unusedVar.scope.variableScope);
  553. let referenceToReport;
  554. if (writeReferences.length > 0) {
  555. referenceToReport = writeReferences[writeReferences.length - 1];
  556. }
  557. context.report({
  558. node: referenceToReport ? referenceToReport.identifier : unusedVar.identifiers[0],
  559. messageId: "unusedVar",
  560. data: unusedVar.references.some(ref => ref.isWrite())
  561. ? getAssignedMessageData(unusedVar)
  562. : getDefinedMessageData(unusedVar)
  563. });
  564. // If there are no regular declaration, report the first `/*globals*/` comment directive.
  565. } else if (unusedVar.eslintExplicitGlobalComments) {
  566. const directiveComment = unusedVar.eslintExplicitGlobalComments[0];
  567. context.report({
  568. node: programNode,
  569. loc: astUtils.getNameLocationInGlobalDirectiveComment(sourceCode, directiveComment, unusedVar.name),
  570. messageId: "unusedVar",
  571. data: getDefinedMessageData(unusedVar)
  572. });
  573. }
  574. }
  575. }
  576. };
  577. }
  578. };