no-unused-vars.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. * Determines if a variable has a sibling rest property
  167. * @param {Variable} variable eslint-scope variable object.
  168. * @returns {boolean} True if the variable is exported, false if not.
  169. * @private
  170. */
  171. function hasRestSpreadSibling(variable) {
  172. if (config.ignoreRestSiblings) {
  173. return variable.defs.some(def => {
  174. const propertyNode = def.name.parent;
  175. const patternNode = propertyNode.parent;
  176. return (
  177. propertyNode.type === "Property" &&
  178. patternNode.type === "ObjectPattern" &&
  179. REST_PROPERTY_TYPE.test(patternNode.properties[patternNode.properties.length - 1].type)
  180. );
  181. });
  182. }
  183. return false;
  184. }
  185. /**
  186. * Determines if a reference is a read operation.
  187. * @param {Reference} ref An eslint-scope Reference
  188. * @returns {boolean} whether the given reference represents a read operation
  189. * @private
  190. */
  191. function isReadRef(ref) {
  192. return ref.isRead();
  193. }
  194. /**
  195. * Determine if an identifier is referencing an enclosing function name.
  196. * @param {Reference} ref The reference to check.
  197. * @param {ASTNode[]} nodes The candidate function nodes.
  198. * @returns {boolean} True if it's a self-reference, false if not.
  199. * @private
  200. */
  201. function isSelfReference(ref, nodes) {
  202. let scope = ref.from;
  203. while (scope) {
  204. if (nodes.indexOf(scope.block) >= 0) {
  205. return true;
  206. }
  207. scope = scope.upper;
  208. }
  209. return false;
  210. }
  211. /**
  212. * Gets a list of function definitions for a specified variable.
  213. * @param {Variable} variable eslint-scope variable object.
  214. * @returns {ASTNode[]} Function nodes.
  215. * @private
  216. */
  217. function getFunctionDefinitions(variable) {
  218. const functionDefinitions = [];
  219. variable.defs.forEach(def => {
  220. const { type, node } = def;
  221. // FunctionDeclarations
  222. if (type === "FunctionName") {
  223. functionDefinitions.push(node);
  224. }
  225. // FunctionExpressions
  226. if (type === "Variable" && node.init &&
  227. (node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) {
  228. functionDefinitions.push(node.init);
  229. }
  230. });
  231. return functionDefinitions;
  232. }
  233. /**
  234. * Checks the position of given nodes.
  235. * @param {ASTNode} inner A node which is expected as inside.
  236. * @param {ASTNode} outer A node which is expected as outside.
  237. * @returns {boolean} `true` if the `inner` node exists in the `outer` node.
  238. * @private
  239. */
  240. function isInside(inner, outer) {
  241. return (
  242. inner.range[0] >= outer.range[0] &&
  243. inner.range[1] <= outer.range[1]
  244. );
  245. }
  246. /**
  247. * If a given reference is left-hand side of an assignment, this gets
  248. * the right-hand side node of the assignment.
  249. *
  250. * In the following cases, this returns null.
  251. *
  252. * - The reference is not the LHS of an assignment expression.
  253. * - The reference is inside of a loop.
  254. * - The reference is inside of a function scope which is different from
  255. * the declaration.
  256. * @param {eslint-scope.Reference} ref A reference to check.
  257. * @param {ASTNode} prevRhsNode The previous RHS node.
  258. * @returns {ASTNode|null} The RHS node or null.
  259. * @private
  260. */
  261. function getRhsNode(ref, prevRhsNode) {
  262. const id = ref.identifier;
  263. const parent = id.parent;
  264. const grandparent = parent.parent;
  265. const refScope = ref.from.variableScope;
  266. const varScope = ref.resolved.scope.variableScope;
  267. const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id);
  268. /*
  269. * Inherits the previous node if this reference is in the node.
  270. * This is for `a = a + a`-like code.
  271. */
  272. if (prevRhsNode && isInside(id, prevRhsNode)) {
  273. return prevRhsNode;
  274. }
  275. if (parent.type === "AssignmentExpression" &&
  276. grandparent.type === "ExpressionStatement" &&
  277. id === parent.left &&
  278. !canBeUsedLater
  279. ) {
  280. return parent.right;
  281. }
  282. return null;
  283. }
  284. /**
  285. * Checks whether a given function node is stored to somewhere or not.
  286. * If the function node is stored, the function can be used later.
  287. * @param {ASTNode} funcNode A function node to check.
  288. * @param {ASTNode} rhsNode The RHS node of the previous assignment.
  289. * @returns {boolean} `true` if under the following conditions:
  290. * - the funcNode is assigned to a variable.
  291. * - the funcNode is bound as an argument of a function call.
  292. * - the function is bound to a property and the object satisfies above conditions.
  293. * @private
  294. */
  295. function isStorableFunction(funcNode, rhsNode) {
  296. let node = funcNode;
  297. let parent = funcNode.parent;
  298. while (parent && isInside(parent, rhsNode)) {
  299. switch (parent.type) {
  300. case "SequenceExpression":
  301. if (parent.expressions[parent.expressions.length - 1] !== node) {
  302. return false;
  303. }
  304. break;
  305. case "CallExpression":
  306. case "NewExpression":
  307. return parent.callee !== node;
  308. case "AssignmentExpression":
  309. case "TaggedTemplateExpression":
  310. case "YieldExpression":
  311. return true;
  312. default:
  313. if (STATEMENT_TYPE.test(parent.type)) {
  314. /*
  315. * If it encountered statements, this is a complex pattern.
  316. * Since analyzing complex patterns is hard, this returns `true` to avoid false positive.
  317. */
  318. return true;
  319. }
  320. }
  321. node = parent;
  322. parent = parent.parent;
  323. }
  324. return false;
  325. }
  326. /**
  327. * Checks whether a given Identifier node exists inside of a function node which can be used later.
  328. *
  329. * "can be used later" means:
  330. * - the function is assigned to a variable.
  331. * - the function is bound to a property and the object can be used later.
  332. * - the function is bound as an argument of a function call.
  333. *
  334. * If a reference exists in a function which can be used later, the reference is read when the function is called.
  335. * @param {ASTNode} id An Identifier node to check.
  336. * @param {ASTNode} rhsNode The RHS node of the previous assignment.
  337. * @returns {boolean} `true` if the `id` node exists inside of a function node which can be used later.
  338. * @private
  339. */
  340. function isInsideOfStorableFunction(id, rhsNode) {
  341. const funcNode = astUtils.getUpperFunction(id);
  342. return (
  343. funcNode &&
  344. isInside(funcNode, rhsNode) &&
  345. isStorableFunction(funcNode, rhsNode)
  346. );
  347. }
  348. /**
  349. * Checks whether a given reference is a read to update itself or not.
  350. * @param {eslint-scope.Reference} ref A reference to check.
  351. * @param {ASTNode} rhsNode The RHS node of the previous assignment.
  352. * @returns {boolean} The reference is a read to update itself.
  353. * @private
  354. */
  355. function isReadForItself(ref, rhsNode) {
  356. const id = ref.identifier;
  357. const parent = id.parent;
  358. const grandparent = parent.parent;
  359. return ref.isRead() && (
  360. // self update. e.g. `a += 1`, `a++`
  361. (// in RHS of an assignment for itself. e.g. `a = a + 1`
  362. ((
  363. parent.type === "AssignmentExpression" &&
  364. grandparent.type === "ExpressionStatement" &&
  365. parent.left === id
  366. ) ||
  367. (
  368. parent.type === "UpdateExpression" &&
  369. grandparent.type === "ExpressionStatement"
  370. ) || rhsNode &&
  371. isInside(id, rhsNode) &&
  372. !isInsideOfStorableFunction(id, rhsNode)))
  373. );
  374. }
  375. /**
  376. * Determine if an identifier is used either in for-in loops.
  377. * @param {Reference} ref The reference to check.
  378. * @returns {boolean} whether reference is used in the for-in loops
  379. * @private
  380. */
  381. function isForInRef(ref) {
  382. let target = ref.identifier.parent;
  383. // "for (var ...) { return; }"
  384. if (target.type === "VariableDeclarator") {
  385. target = target.parent.parent;
  386. }
  387. if (target.type !== "ForInStatement") {
  388. return false;
  389. }
  390. // "for (...) { return; }"
  391. if (target.body.type === "BlockStatement") {
  392. target = target.body.body[0];
  393. // "for (...) return;"
  394. } else {
  395. target = target.body;
  396. }
  397. // For empty loop body
  398. if (!target) {
  399. return false;
  400. }
  401. return target.type === "ReturnStatement";
  402. }
  403. /**
  404. * Determines if the variable is used.
  405. * @param {Variable} variable The variable to check.
  406. * @returns {boolean} True if the variable is used
  407. * @private
  408. */
  409. function isUsedVariable(variable) {
  410. const functionNodes = getFunctionDefinitions(variable),
  411. isFunctionDefinition = functionNodes.length > 0;
  412. let rhsNode = null;
  413. return variable.references.some(ref => {
  414. if (isForInRef(ref)) {
  415. return true;
  416. }
  417. const forItself = isReadForItself(ref, rhsNode);
  418. rhsNode = getRhsNode(ref, rhsNode);
  419. return (
  420. isReadRef(ref) &&
  421. !forItself &&
  422. !(isFunctionDefinition && isSelfReference(ref, functionNodes))
  423. );
  424. });
  425. }
  426. /**
  427. * Checks whether the given variable is after the last used parameter.
  428. * @param {eslint-scope.Variable} variable The variable to check.
  429. * @returns {boolean} `true` if the variable is defined after the last
  430. * used parameter.
  431. */
  432. function isAfterLastUsedArg(variable) {
  433. const def = variable.defs[0];
  434. const params = context.getDeclaredVariables(def.node);
  435. const posteriorParams = params.slice(params.indexOf(variable) + 1);
  436. // If any used parameters occur after this parameter, do not report.
  437. return !posteriorParams.some(v => v.references.length > 0 || v.eslintUsed);
  438. }
  439. /**
  440. * Gets an array of variables without read references.
  441. * @param {Scope} scope an eslint-scope Scope object.
  442. * @param {Variable[]} unusedVars an array that saving result.
  443. * @returns {Variable[]} unused variables of the scope and descendant scopes.
  444. * @private
  445. */
  446. function collectUnusedVariables(scope, unusedVars) {
  447. const variables = scope.variables;
  448. const childScopes = scope.childScopes;
  449. let i, l;
  450. if (scope.type !== "global" || config.vars === "all") {
  451. for (i = 0, l = variables.length; i < l; ++i) {
  452. const variable = variables[i];
  453. // skip a variable of class itself name in the class scope
  454. if (scope.type === "class" && scope.block.id === variable.identifiers[0]) {
  455. continue;
  456. }
  457. // skip function expression names and variables marked with markVariableAsUsed()
  458. if (scope.functionExpressionScope || variable.eslintUsed) {
  459. continue;
  460. }
  461. // skip implicit "arguments" variable
  462. if (scope.type === "function" && variable.name === "arguments" && variable.identifiers.length === 0) {
  463. continue;
  464. }
  465. // explicit global variables don't have definitions.
  466. const def = variable.defs[0];
  467. if (def) {
  468. const type = def.type;
  469. // skip catch variables
  470. if (type === "CatchClause") {
  471. if (config.caughtErrors === "none") {
  472. continue;
  473. }
  474. // skip ignored parameters
  475. if (config.caughtErrorsIgnorePattern && config.caughtErrorsIgnorePattern.test(def.name.name)) {
  476. continue;
  477. }
  478. }
  479. if (type === "Parameter") {
  480. // skip any setter argument
  481. if ((def.node.parent.type === "Property" || def.node.parent.type === "MethodDefinition") && def.node.parent.kind === "set") {
  482. continue;
  483. }
  484. // if "args" option is "none", skip any parameter
  485. if (config.args === "none") {
  486. continue;
  487. }
  488. // skip ignored parameters
  489. if (config.argsIgnorePattern && config.argsIgnorePattern.test(def.name.name)) {
  490. continue;
  491. }
  492. // if "args" option is "after-used", skip used variables
  493. if (config.args === "after-used" && astUtils.isFunction(def.name.parent) && !isAfterLastUsedArg(variable)) {
  494. continue;
  495. }
  496. } else {
  497. // skip ignored variables
  498. if (config.varsIgnorePattern && config.varsIgnorePattern.test(def.name.name)) {
  499. continue;
  500. }
  501. }
  502. }
  503. if (!isUsedVariable(variable) && !isExported(variable) && !hasRestSpreadSibling(variable)) {
  504. unusedVars.push(variable);
  505. }
  506. }
  507. }
  508. for (i = 0, l = childScopes.length; i < l; ++i) {
  509. collectUnusedVariables(childScopes[i], unusedVars);
  510. }
  511. return unusedVars;
  512. }
  513. //--------------------------------------------------------------------------
  514. // Public
  515. //--------------------------------------------------------------------------
  516. return {
  517. "Program:exit"(programNode) {
  518. const unusedVars = collectUnusedVariables(context.getScope(), []);
  519. for (let i = 0, l = unusedVars.length; i < l; ++i) {
  520. const unusedVar = unusedVars[i];
  521. // Report the first declaration.
  522. if (unusedVar.defs.length > 0) {
  523. context.report({
  524. node: unusedVar.references.length ? unusedVar.references[
  525. unusedVar.references.length - 1
  526. ].identifier : unusedVar.identifiers[0],
  527. messageId: "unusedVar",
  528. data: unusedVar.references.some(ref => ref.isWrite())
  529. ? getAssignedMessageData(unusedVar)
  530. : getDefinedMessageData(unusedVar)
  531. });
  532. // If there are no regular declaration, report the first `/*globals*/` comment directive.
  533. } else if (unusedVar.eslintExplicitGlobalComments) {
  534. const directiveComment = unusedVar.eslintExplicitGlobalComments[0];
  535. context.report({
  536. node: programNode,
  537. loc: astUtils.getNameLocationInGlobalDirectiveComment(sourceCode, directiveComment, unusedVar.name),
  538. messageId: "unusedVar",
  539. data: getDefinedMessageData(unusedVar)
  540. });
  541. }
  542. }
  543. }
  544. };
  545. }
  546. };