no-unused-vars.js 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492
  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. * A simple name for the types of variables that this rule supports
  15. * @typedef {'array-destructure'|'catch-clause'|'parameter'|'variable'} VariableType
  16. */
  17. /**
  18. * Bag of data used for formatting the `unusedVar` lint message.
  19. * @typedef {Object} UnusedVarMessageData
  20. * @property {string} varName The name of the unused var.
  21. * @property {'defined'|'assigned a value'} action Description of the vars state.
  22. * @property {string} additional Any additional info to be appended at the end.
  23. */
  24. /**
  25. * Bag of data used for formatting the `usedIgnoredVar` lint message.
  26. * @typedef {Object} UsedIgnoredVarMessageData
  27. * @property {string} varName The name of the unused var.
  28. * @property {string} additional Any additional info to be appended at the end.
  29. */
  30. //------------------------------------------------------------------------------
  31. // Rule Definition
  32. //------------------------------------------------------------------------------
  33. /** @type {import('../shared/types').Rule} */
  34. module.exports = {
  35. meta: {
  36. type: "problem",
  37. docs: {
  38. description: "Disallow unused variables",
  39. recommended: true,
  40. url: "https://eslint.org/docs/latest/rules/no-unused-vars"
  41. },
  42. hasSuggestions: true,
  43. schema: [
  44. {
  45. oneOf: [
  46. {
  47. enum: ["all", "local"]
  48. },
  49. {
  50. type: "object",
  51. properties: {
  52. vars: {
  53. enum: ["all", "local"]
  54. },
  55. varsIgnorePattern: {
  56. type: "string"
  57. },
  58. args: {
  59. enum: ["all", "after-used", "none"]
  60. },
  61. ignoreRestSiblings: {
  62. type: "boolean"
  63. },
  64. argsIgnorePattern: {
  65. type: "string"
  66. },
  67. caughtErrors: {
  68. enum: ["all", "none"]
  69. },
  70. caughtErrorsIgnorePattern: {
  71. type: "string"
  72. },
  73. destructuredArrayIgnorePattern: {
  74. type: "string"
  75. },
  76. ignoreClassWithStaticInitBlock: {
  77. type: "boolean"
  78. },
  79. reportUsedIgnorePattern: {
  80. type: "boolean"
  81. }
  82. },
  83. additionalProperties: false
  84. }
  85. ]
  86. }
  87. ],
  88. messages: {
  89. unusedVar: "'{{varName}}' is {{action}} but never used{{additional}}.",
  90. usedIgnoredVar: "'{{varName}}' is marked as ignored but is used{{additional}}.",
  91. removeVar: "Remove unused variable '{{varName}}'."
  92. }
  93. },
  94. create(context) {
  95. const sourceCode = context.sourceCode;
  96. const REST_PROPERTY_TYPE = /^(?:RestElement|(?:Experimental)?RestProperty)$/u;
  97. const config = {
  98. vars: "all",
  99. args: "after-used",
  100. ignoreRestSiblings: false,
  101. caughtErrors: "all",
  102. ignoreClassWithStaticInitBlock: false,
  103. reportUsedIgnorePattern: false
  104. };
  105. const firstOption = context.options[0];
  106. if (firstOption) {
  107. if (typeof firstOption === "string") {
  108. config.vars = firstOption;
  109. } else {
  110. config.vars = firstOption.vars || config.vars;
  111. config.args = firstOption.args || config.args;
  112. config.ignoreRestSiblings = firstOption.ignoreRestSiblings || config.ignoreRestSiblings;
  113. config.caughtErrors = firstOption.caughtErrors || config.caughtErrors;
  114. config.ignoreClassWithStaticInitBlock = firstOption.ignoreClassWithStaticInitBlock || config.ignoreClassWithStaticInitBlock;
  115. config.reportUsedIgnorePattern = firstOption.reportUsedIgnorePattern || config.reportUsedIgnorePattern;
  116. if (firstOption.varsIgnorePattern) {
  117. config.varsIgnorePattern = new RegExp(firstOption.varsIgnorePattern, "u");
  118. }
  119. if (firstOption.argsIgnorePattern) {
  120. config.argsIgnorePattern = new RegExp(firstOption.argsIgnorePattern, "u");
  121. }
  122. if (firstOption.caughtErrorsIgnorePattern) {
  123. config.caughtErrorsIgnorePattern = new RegExp(firstOption.caughtErrorsIgnorePattern, "u");
  124. }
  125. if (firstOption.destructuredArrayIgnorePattern) {
  126. config.destructuredArrayIgnorePattern = new RegExp(firstOption.destructuredArrayIgnorePattern, "u");
  127. }
  128. }
  129. }
  130. /**
  131. * Determines what variable type a def is.
  132. * @param {Object} def the declaration to check
  133. * @returns {VariableType} a simple name for the types of variables that this rule supports
  134. */
  135. function defToVariableType(def) {
  136. /*
  137. * This `destructuredArrayIgnorePattern` error report works differently from the catch
  138. * clause and parameter error reports. _Both_ the `varsIgnorePattern` and the
  139. * `destructuredArrayIgnorePattern` will be checked for array destructuring. However,
  140. * for the purposes of the report, the currently defined behavior is to only inform the
  141. * user of the `destructuredArrayIgnorePattern` if it's present (regardless of the fact
  142. * that the `varsIgnorePattern` would also apply). If it's not present, the user will be
  143. * informed of the `varsIgnorePattern`, assuming that's present.
  144. */
  145. if (config.destructuredArrayIgnorePattern && def.name.parent.type === "ArrayPattern") {
  146. return "array-destructure";
  147. }
  148. switch (def.type) {
  149. case "CatchClause":
  150. return "catch-clause";
  151. case "Parameter":
  152. return "parameter";
  153. default:
  154. return "variable";
  155. }
  156. }
  157. /**
  158. * Gets a given variable's description and configured ignore pattern
  159. * based on the provided variableType
  160. * @param {VariableType} variableType a simple name for the types of variables that this rule supports
  161. * @throws {Error} (Unreachable)
  162. * @returns {[string | undefined, string | undefined]} the given variable's description and
  163. * ignore pattern
  164. */
  165. function getVariableDescription(variableType) {
  166. let pattern;
  167. let variableDescription;
  168. switch (variableType) {
  169. case "array-destructure":
  170. pattern = config.destructuredArrayIgnorePattern;
  171. variableDescription = "elements of array destructuring";
  172. break;
  173. case "catch-clause":
  174. pattern = config.caughtErrorsIgnorePattern;
  175. variableDescription = "caught errors";
  176. break;
  177. case "parameter":
  178. pattern = config.argsIgnorePattern;
  179. variableDescription = "args";
  180. break;
  181. case "variable":
  182. pattern = config.varsIgnorePattern;
  183. variableDescription = "vars";
  184. break;
  185. default:
  186. throw new Error(`Unexpected variable type: ${variableType}`);
  187. }
  188. if (pattern) {
  189. pattern = pattern.toString();
  190. }
  191. return [variableDescription, pattern];
  192. }
  193. /**
  194. * Generates the message data about the variable being defined and unused,
  195. * including the ignore pattern if configured.
  196. * @param {Variable} unusedVar eslint-scope variable object.
  197. * @returns {UnusedVarMessageData} The message data to be used with this unused variable.
  198. */
  199. function getDefinedMessageData(unusedVar) {
  200. const def = unusedVar.defs && unusedVar.defs[0];
  201. let additionalMessageData = "";
  202. if (def) {
  203. const [variableDescription, pattern] = getVariableDescription(defToVariableType(def));
  204. if (pattern && variableDescription) {
  205. additionalMessageData = `. Allowed unused ${variableDescription} must match ${pattern}`;
  206. }
  207. }
  208. return {
  209. varName: unusedVar.name,
  210. action: "defined",
  211. additional: additionalMessageData
  212. };
  213. }
  214. /**
  215. * Generate the warning message about the variable being
  216. * assigned and unused, including the ignore pattern if configured.
  217. * @param {Variable} unusedVar eslint-scope variable object.
  218. * @returns {UnusedVarMessageData} The message data to be used with this unused variable.
  219. */
  220. function getAssignedMessageData(unusedVar) {
  221. const def = unusedVar.defs && unusedVar.defs[0];
  222. let additionalMessageData = "";
  223. if (def) {
  224. const [variableDescription, pattern] = getVariableDescription(defToVariableType(def));
  225. if (pattern && variableDescription) {
  226. additionalMessageData = `. Allowed unused ${variableDescription} must match ${pattern}`;
  227. }
  228. }
  229. return {
  230. varName: unusedVar.name,
  231. action: "assigned a value",
  232. additional: additionalMessageData
  233. };
  234. }
  235. /**
  236. * Generate the warning message about a variable being used even though
  237. * it is marked as being ignored.
  238. * @param {Variable} variable eslint-scope variable object
  239. * @param {VariableType} variableType a simple name for the types of variables that this rule supports
  240. * @returns {UsedIgnoredVarMessageData} The message data to be used with
  241. * this used ignored variable.
  242. */
  243. function getUsedIgnoredMessageData(variable, variableType) {
  244. const [variableDescription, pattern] = getVariableDescription(variableType);
  245. let additionalMessageData = "";
  246. if (pattern && variableDescription) {
  247. additionalMessageData = `. Used ${variableDescription} must not match ${pattern}`;
  248. }
  249. return {
  250. varName: variable.name,
  251. additional: additionalMessageData
  252. };
  253. }
  254. //--------------------------------------------------------------------------
  255. // Helpers
  256. //--------------------------------------------------------------------------
  257. const STATEMENT_TYPE = /(?:Statement|Declaration)$/u;
  258. /**
  259. * Determines if a given variable is being exported from a module.
  260. * @param {Variable} variable eslint-scope variable object.
  261. * @returns {boolean} True if the variable is exported, false if not.
  262. * @private
  263. */
  264. function isExported(variable) {
  265. const definition = variable.defs[0];
  266. if (definition) {
  267. let node = definition.node;
  268. if (node.type === "VariableDeclarator") {
  269. node = node.parent;
  270. } else if (definition.type === "Parameter") {
  271. return false;
  272. }
  273. return node.parent.type.indexOf("Export") === 0;
  274. }
  275. return false;
  276. }
  277. /**
  278. * Checks whether a node is a sibling of the rest property or not.
  279. * @param {ASTNode} node a node to check
  280. * @returns {boolean} True if the node is a sibling of the rest property, otherwise false.
  281. */
  282. function hasRestSibling(node) {
  283. return node.type === "Property" &&
  284. node.parent.type === "ObjectPattern" &&
  285. REST_PROPERTY_TYPE.test(node.parent.properties.at(-1).type);
  286. }
  287. /**
  288. * Determines if a variable has a sibling rest property
  289. * @param {Variable} variable eslint-scope variable object.
  290. * @returns {boolean} True if the variable has a sibling rest property, false if not.
  291. * @private
  292. */
  293. function hasRestSpreadSibling(variable) {
  294. if (config.ignoreRestSiblings) {
  295. const hasRestSiblingDefinition = variable.defs.some(def => hasRestSibling(def.name.parent));
  296. const hasRestSiblingReference = variable.references.some(ref => hasRestSibling(ref.identifier.parent));
  297. return hasRestSiblingDefinition || hasRestSiblingReference;
  298. }
  299. return false;
  300. }
  301. /**
  302. * Determines if a reference is a read operation.
  303. * @param {Reference} ref An eslint-scope Reference
  304. * @returns {boolean} whether the given reference represents a read operation
  305. * @private
  306. */
  307. function isReadRef(ref) {
  308. return ref.isRead();
  309. }
  310. /**
  311. * Determine if an identifier is referencing an enclosing function name.
  312. * @param {Reference} ref The reference to check.
  313. * @param {ASTNode[]} nodes The candidate function nodes.
  314. * @returns {boolean} True if it's a self-reference, false if not.
  315. * @private
  316. */
  317. function isSelfReference(ref, nodes) {
  318. let scope = ref.from;
  319. while (scope) {
  320. if (nodes.includes(scope.block)) {
  321. return true;
  322. }
  323. scope = scope.upper;
  324. }
  325. return false;
  326. }
  327. /**
  328. * Gets a list of function definitions for a specified variable.
  329. * @param {Variable} variable eslint-scope variable object.
  330. * @returns {ASTNode[]} Function nodes.
  331. * @private
  332. */
  333. function getFunctionDefinitions(variable) {
  334. const functionDefinitions = [];
  335. variable.defs.forEach(def => {
  336. const { type, node } = def;
  337. // FunctionDeclarations
  338. if (type === "FunctionName") {
  339. functionDefinitions.push(node);
  340. }
  341. // FunctionExpressions
  342. if (type === "Variable" && node.init &&
  343. (node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) {
  344. functionDefinitions.push(node.init);
  345. }
  346. });
  347. return functionDefinitions;
  348. }
  349. /**
  350. * Checks the position of given nodes.
  351. * @param {ASTNode} inner A node which is expected as inside.
  352. * @param {ASTNode} outer A node which is expected as outside.
  353. * @returns {boolean} `true` if the `inner` node exists in the `outer` node.
  354. * @private
  355. */
  356. function isInside(inner, outer) {
  357. return (
  358. inner.range[0] >= outer.range[0] &&
  359. inner.range[1] <= outer.range[1]
  360. );
  361. }
  362. /**
  363. * Checks whether a given node is unused expression or not.
  364. * @param {ASTNode} node The node itself
  365. * @returns {boolean} The node is an unused expression.
  366. * @private
  367. */
  368. function isUnusedExpression(node) {
  369. const parent = node.parent;
  370. if (parent.type === "ExpressionStatement") {
  371. return true;
  372. }
  373. if (parent.type === "SequenceExpression") {
  374. const isLastExpression = parent.expressions.at(-1) === node;
  375. if (!isLastExpression) {
  376. return true;
  377. }
  378. return isUnusedExpression(parent);
  379. }
  380. return false;
  381. }
  382. /**
  383. * If a given reference is left-hand side of an assignment, this gets
  384. * the right-hand side node of the assignment.
  385. *
  386. * In the following cases, this returns null.
  387. *
  388. * - The reference is not the LHS of an assignment expression.
  389. * - The reference is inside of a loop.
  390. * - The reference is inside of a function scope which is different from
  391. * the declaration.
  392. * @param {eslint-scope.Reference} ref A reference to check.
  393. * @param {ASTNode} prevRhsNode The previous RHS node.
  394. * @returns {ASTNode|null} The RHS node or null.
  395. * @private
  396. */
  397. function getRhsNode(ref, prevRhsNode) {
  398. const id = ref.identifier;
  399. const parent = id.parent;
  400. const refScope = ref.from.variableScope;
  401. const varScope = ref.resolved.scope.variableScope;
  402. const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id);
  403. /*
  404. * Inherits the previous node if this reference is in the node.
  405. * This is for `a = a + a`-like code.
  406. */
  407. if (prevRhsNode && isInside(id, prevRhsNode)) {
  408. return prevRhsNode;
  409. }
  410. if (parent.type === "AssignmentExpression" &&
  411. isUnusedExpression(parent) &&
  412. id === parent.left &&
  413. !canBeUsedLater
  414. ) {
  415. return parent.right;
  416. }
  417. return null;
  418. }
  419. /**
  420. * Checks whether a given function node is stored to somewhere or not.
  421. * If the function node is stored, the function can be used later.
  422. * @param {ASTNode} funcNode A function node to check.
  423. * @param {ASTNode} rhsNode The RHS node of the previous assignment.
  424. * @returns {boolean} `true` if under the following conditions:
  425. * - the funcNode is assigned to a variable.
  426. * - the funcNode is bound as an argument of a function call.
  427. * - the function is bound to a property and the object satisfies above conditions.
  428. * @private
  429. */
  430. function isStorableFunction(funcNode, rhsNode) {
  431. let node = funcNode;
  432. let parent = funcNode.parent;
  433. while (parent && isInside(parent, rhsNode)) {
  434. switch (parent.type) {
  435. case "SequenceExpression":
  436. if (parent.expressions.at(-1) !== node) {
  437. return false;
  438. }
  439. break;
  440. case "CallExpression":
  441. case "NewExpression":
  442. return parent.callee !== node;
  443. case "AssignmentExpression":
  444. case "TaggedTemplateExpression":
  445. case "YieldExpression":
  446. return true;
  447. default:
  448. if (STATEMENT_TYPE.test(parent.type)) {
  449. /*
  450. * If it encountered statements, this is a complex pattern.
  451. * Since analyzing complex patterns is hard, this returns `true` to avoid false positive.
  452. */
  453. return true;
  454. }
  455. }
  456. node = parent;
  457. parent = parent.parent;
  458. }
  459. return false;
  460. }
  461. /**
  462. * Checks whether a given Identifier node exists inside of a function node which can be used later.
  463. *
  464. * "can be used later" means:
  465. * - the function is assigned to a variable.
  466. * - the function is bound to a property and the object can be used later.
  467. * - the function is bound as an argument of a function call.
  468. *
  469. * If a reference exists in a function which can be used later, the reference is read when the function is called.
  470. * @param {ASTNode} id An Identifier node to check.
  471. * @param {ASTNode} rhsNode The RHS node of the previous assignment.
  472. * @returns {boolean} `true` if the `id` node exists inside of a function node which can be used later.
  473. * @private
  474. */
  475. function isInsideOfStorableFunction(id, rhsNode) {
  476. const funcNode = astUtils.getUpperFunction(id);
  477. return (
  478. funcNode &&
  479. isInside(funcNode, rhsNode) &&
  480. isStorableFunction(funcNode, rhsNode)
  481. );
  482. }
  483. /**
  484. * Checks whether a given reference is a read to update itself or not.
  485. * @param {eslint-scope.Reference} ref A reference to check.
  486. * @param {ASTNode} rhsNode The RHS node of the previous assignment.
  487. * @returns {boolean} The reference is a read to update itself.
  488. * @private
  489. */
  490. function isReadForItself(ref, rhsNode) {
  491. const id = ref.identifier;
  492. const parent = id.parent;
  493. return ref.isRead() && (
  494. // self update. e.g. `a += 1`, `a++`
  495. (
  496. (
  497. parent.type === "AssignmentExpression" &&
  498. parent.left === id &&
  499. isUnusedExpression(parent) &&
  500. !astUtils.isLogicalAssignmentOperator(parent.operator)
  501. ) ||
  502. (
  503. parent.type === "UpdateExpression" &&
  504. isUnusedExpression(parent)
  505. )
  506. ) ||
  507. // in RHS of an assignment for itself. e.g. `a = a + 1`
  508. (
  509. rhsNode &&
  510. isInside(id, rhsNode) &&
  511. !isInsideOfStorableFunction(id, rhsNode)
  512. )
  513. );
  514. }
  515. /**
  516. * Determine if an identifier is used either in for-in or for-of loops.
  517. * @param {Reference} ref The reference to check.
  518. * @returns {boolean} whether reference is used in the for-in loops
  519. * @private
  520. */
  521. function isForInOfRef(ref) {
  522. let target = ref.identifier.parent;
  523. // "for (var ...) { return; }"
  524. if (target.type === "VariableDeclarator") {
  525. target = target.parent.parent;
  526. }
  527. if (target.type !== "ForInStatement" && target.type !== "ForOfStatement") {
  528. return false;
  529. }
  530. // "for (...) { return; }"
  531. if (target.body.type === "BlockStatement") {
  532. target = target.body.body[0];
  533. // "for (...) return;"
  534. } else {
  535. target = target.body;
  536. }
  537. // For empty loop body
  538. if (!target) {
  539. return false;
  540. }
  541. return target.type === "ReturnStatement";
  542. }
  543. /**
  544. * Determines if the variable is used.
  545. * @param {Variable} variable The variable to check.
  546. * @returns {boolean} True if the variable is used
  547. * @private
  548. */
  549. function isUsedVariable(variable) {
  550. if (variable.eslintUsed) {
  551. return true;
  552. }
  553. const functionNodes = getFunctionDefinitions(variable);
  554. const isFunctionDefinition = functionNodes.length > 0;
  555. let rhsNode = null;
  556. return variable.references.some(ref => {
  557. if (isForInOfRef(ref)) {
  558. return true;
  559. }
  560. const forItself = isReadForItself(ref, rhsNode);
  561. rhsNode = getRhsNode(ref, rhsNode);
  562. return (
  563. isReadRef(ref) &&
  564. !forItself &&
  565. !(isFunctionDefinition && isSelfReference(ref, functionNodes))
  566. );
  567. });
  568. }
  569. /**
  570. * Checks whether the given variable is after the last used parameter.
  571. * @param {eslint-scope.Variable} variable The variable to check.
  572. * @returns {boolean} `true` if the variable is defined after the last
  573. * used parameter.
  574. */
  575. function isAfterLastUsedArg(variable) {
  576. const def = variable.defs[0];
  577. const params = sourceCode.getDeclaredVariables(def.node);
  578. const posteriorParams = params.slice(params.indexOf(variable) + 1);
  579. // If any used parameters occur after this parameter, do not report.
  580. return !posteriorParams.some(v => v.references.length > 0 || v.eslintUsed);
  581. }
  582. /**
  583. * Gets an array of variables without read references.
  584. * @param {Scope} scope an eslint-scope Scope object.
  585. * @param {Variable[]} unusedVars an array that saving result.
  586. * @returns {Variable[]} unused variables of the scope and descendant scopes.
  587. * @private
  588. */
  589. function collectUnusedVariables(scope, unusedVars) {
  590. const variables = scope.variables;
  591. const childScopes = scope.childScopes;
  592. let i, l;
  593. if (scope.type !== "global" || config.vars === "all") {
  594. for (i = 0, l = variables.length; i < l; ++i) {
  595. const variable = variables[i];
  596. // skip a variable of class itself name in the class scope
  597. if (scope.type === "class" && scope.block.id === variable.identifiers[0]) {
  598. continue;
  599. }
  600. // skip function expression names
  601. if (scope.functionExpressionScope) {
  602. continue;
  603. }
  604. // skip variables marked with markVariableAsUsed()
  605. if (!config.reportUsedIgnorePattern && variable.eslintUsed) {
  606. continue;
  607. }
  608. // skip implicit "arguments" variable
  609. if (scope.type === "function" && variable.name === "arguments" && variable.identifiers.length === 0) {
  610. continue;
  611. }
  612. // explicit global variables don't have definitions.
  613. const def = variable.defs[0];
  614. if (def) {
  615. const type = def.type;
  616. const refUsedInArrayPatterns = variable.references.some(ref => ref.identifier.parent.type === "ArrayPattern");
  617. // skip elements of array destructuring patterns
  618. if (
  619. (
  620. def.name.parent.type === "ArrayPattern" ||
  621. refUsedInArrayPatterns
  622. ) &&
  623. config.destructuredArrayIgnorePattern &&
  624. config.destructuredArrayIgnorePattern.test(def.name.name)
  625. ) {
  626. if (config.reportUsedIgnorePattern && isUsedVariable(variable)) {
  627. context.report({
  628. node: def.name,
  629. messageId: "usedIgnoredVar",
  630. data: getUsedIgnoredMessageData(variable, "array-destructure")
  631. });
  632. }
  633. continue;
  634. }
  635. if (type === "ClassName") {
  636. const hasStaticBlock = def.node.body.body.some(node => node.type === "StaticBlock");
  637. if (config.ignoreClassWithStaticInitBlock && hasStaticBlock) {
  638. continue;
  639. }
  640. }
  641. // skip catch variables
  642. if (type === "CatchClause") {
  643. if (config.caughtErrors === "none") {
  644. continue;
  645. }
  646. // skip ignored parameters
  647. if (config.caughtErrorsIgnorePattern && config.caughtErrorsIgnorePattern.test(def.name.name)) {
  648. if (config.reportUsedIgnorePattern && isUsedVariable(variable)) {
  649. context.report({
  650. node: def.name,
  651. messageId: "usedIgnoredVar",
  652. data: getUsedIgnoredMessageData(variable, "catch-clause")
  653. });
  654. }
  655. continue;
  656. }
  657. } else if (type === "Parameter") {
  658. // skip any setter argument
  659. if ((def.node.parent.type === "Property" || def.node.parent.type === "MethodDefinition") && def.node.parent.kind === "set") {
  660. continue;
  661. }
  662. // if "args" option is "none", skip any parameter
  663. if (config.args === "none") {
  664. continue;
  665. }
  666. // skip ignored parameters
  667. if (config.argsIgnorePattern && config.argsIgnorePattern.test(def.name.name)) {
  668. if (config.reportUsedIgnorePattern && isUsedVariable(variable)) {
  669. context.report({
  670. node: def.name,
  671. messageId: "usedIgnoredVar",
  672. data: getUsedIgnoredMessageData(variable, "parameter")
  673. });
  674. }
  675. continue;
  676. }
  677. // if "args" option is "after-used", skip used variables
  678. if (config.args === "after-used" && astUtils.isFunction(def.name.parent) && !isAfterLastUsedArg(variable)) {
  679. continue;
  680. }
  681. } else {
  682. // skip ignored variables
  683. if (config.varsIgnorePattern && config.varsIgnorePattern.test(def.name.name)) {
  684. if (config.reportUsedIgnorePattern && isUsedVariable(variable)) {
  685. context.report({
  686. node: def.name,
  687. messageId: "usedIgnoredVar",
  688. data: getUsedIgnoredMessageData(variable, "variable")
  689. });
  690. }
  691. continue;
  692. }
  693. }
  694. }
  695. if (!isUsedVariable(variable) && !isExported(variable) && !hasRestSpreadSibling(variable)) {
  696. unusedVars.push(variable);
  697. }
  698. }
  699. }
  700. for (i = 0, l = childScopes.length; i < l; ++i) {
  701. collectUnusedVariables(childScopes[i], unusedVars);
  702. }
  703. return unusedVars;
  704. }
  705. /**
  706. * fixes unused variables
  707. * @param {Object} fixer fixer object
  708. * @param {Object} unusedVar unused variable to fix
  709. * @returns {Object} fixer object
  710. */
  711. function handleFixes(fixer, unusedVar) {
  712. const id = unusedVar.identifiers[0];
  713. const parent = id.parent;
  714. const parentType = parent.type;
  715. const tokenBefore = sourceCode.getTokenBefore(id);
  716. const tokenAfter = sourceCode.getTokenAfter(id);
  717. const isFunction = astUtils.isFunction;
  718. const isLoop = astUtils.isLoop;
  719. const allWriteReferences = unusedVar.references.filter(ref => ref.isWrite());
  720. /**
  721. * get range from token before of a given node
  722. * @param {ASTNode} node node of identifier
  723. * @param {number} skips number of token to skip
  724. * @returns {number} start range of token before the identifier
  725. */
  726. function getPreviousTokenStart(node, skips) {
  727. return sourceCode.getTokenBefore(node, skips).range[0];
  728. }
  729. /**
  730. * get range to token after of a given node
  731. * @param {ASTNode} node node of identifier
  732. * @param {number} skips number of token to skip
  733. * @returns {number} end range of token after the identifier
  734. */
  735. function getNextTokenEnd(node, skips) {
  736. return sourceCode.getTokenAfter(node, skips).range[1];
  737. }
  738. /**
  739. * get the value of token before of a given node
  740. * @param {ASTNode} node node of identifier
  741. * @returns {string} value of token before the identifier
  742. */
  743. function getTokenBeforeValue(node) {
  744. return sourceCode.getTokenBefore(node).value;
  745. }
  746. /**
  747. * get the value of token after of a given node
  748. * @param {ASTNode} node node of identifier
  749. * @returns {string} value of token after the identifier
  750. */
  751. function getTokenAfterValue(node) {
  752. return sourceCode.getTokenAfter(node).value;
  753. }
  754. /**
  755. * Check if an array has a single element with null as other element.
  756. * @param {ASTNode} node ArrayPattern node
  757. * @returns {boolean} true if array has single element with other null elements
  758. */
  759. function hasSingleElement(node) {
  760. return node.elements.filter(e => e !== null).length === 1;
  761. }
  762. /**
  763. * check whether import specifier has an import of particular type
  764. * @param {ASTNode} node ImportDeclaration node
  765. * @param {string} type type of import to check
  766. * @returns {boolean} true if import specifier has import of specified type
  767. */
  768. function hasImportOfCertainType(node, type) {
  769. return node.specifiers.some(e => e.type === type);
  770. }
  771. /**
  772. * Check whether declaration is safe to remove or not
  773. * @param {ASTNode} nextToken next token of unused variable
  774. * @param {ASTNode} prevToken previous token of unused variable
  775. * @returns {boolean} true if declaration is not safe to remove
  776. */
  777. function isDeclarationNotSafeToRemove(nextToken, prevToken) {
  778. return (
  779. (nextToken.type === "String") ||
  780. (
  781. prevToken &&
  782. !astUtils.isSemicolonToken(prevToken) &&
  783. !astUtils.isOpeningBraceToken(prevToken)
  784. )
  785. );
  786. }
  787. /**
  788. * give fixes for unused variables in function parameters
  789. * @param {ASTNode} node node to check
  790. * @returns {Object} fixer object
  791. */
  792. function fixFunctionParameters(node) {
  793. const parentNode = node.parent;
  794. if (isFunction(parentNode)) {
  795. // remove unused function parameter if there is only a single parameter
  796. if (parentNode.params.length === 1) {
  797. return fixer.removeRange(node.range);
  798. }
  799. // remove first unused function parameter when there are multiple parameters
  800. if (getTokenBeforeValue(node) === "(" && getTokenAfterValue(node) === ",") {
  801. return fixer.removeRange([node.range[0], getNextTokenEnd(node)]);
  802. }
  803. // remove unused function parameters except first one when there are multiple parameters
  804. return fixer.removeRange([getPreviousTokenStart(node), node.range[1]]);
  805. }
  806. return null;
  807. }
  808. /**
  809. * fix unused variable declarations and function parameters
  810. * @param {ASTNode} node parent node to identifier
  811. * @returns {Object} fixer object
  812. */
  813. function fixVariables(node) {
  814. const parentNode = node.parent;
  815. // remove unused declared variables such as var a = b; or var a = b, c;
  816. if (parentNode.type === "VariableDeclarator") {
  817. // skip variable in for (const [ foo ] of bar);
  818. if (isLoop(parentNode.parent.parent)) {
  819. return null;
  820. }
  821. /*
  822. * remove unused declared variable with single declaration such as 'var a = b;'
  823. * remove complete declaration when there is an unused variable in 'const { a } = foo;', same for arrays.
  824. */
  825. if (parentNode.parent.declarations.length === 1) {
  826. // if next token is a string it could become a directive if node is removed -> no suggestion.
  827. const nextToken = sourceCode.getTokenAfter(parentNode.parent);
  828. // if previous token exists and is not ";" or "{" not sure about ASI rules -> no suggestion.
  829. const prevToken = sourceCode.getTokenBefore(parentNode.parent);
  830. if (nextToken && isDeclarationNotSafeToRemove(nextToken, prevToken)) {
  831. return null;
  832. }
  833. return fixer.removeRange(parentNode.parent.range);
  834. }
  835. /*
  836. * remove unused declared variable with multiple declaration except first one such as 'var a = b, c = d;'
  837. * fix 'let bar = "hello", { a } = foo;' to 'let bar = "hello";' if 'a' is unused, same for arrays.
  838. */
  839. if (getTokenBeforeValue(parentNode) === ",") {
  840. return fixer.removeRange([getPreviousTokenStart(parentNode), parentNode.range[1]]);
  841. }
  842. /*
  843. * remove first unused declared variable when there are multiple declarations
  844. * fix 'let { a } = foo, bar = "hello";' to 'let bar = "hello";' if 'a' is unused, same for arrays.
  845. */
  846. return fixer.removeRange([parentNode.range[0], getNextTokenEnd(parentNode)]);
  847. }
  848. // fixes [{a: {k}}], [{a: [k]}]
  849. if (getTokenBeforeValue(node) === ":") {
  850. if (parentNode.parent.type === "ObjectPattern") {
  851. // eslint-disable-next-line no-use-before-define -- due to interdependency of functions
  852. return fixObjectWithValueSeparator(node);
  853. }
  854. }
  855. // fix unused function parameters
  856. return fixFunctionParameters(node);
  857. }
  858. /**
  859. * fix nested object like { a: { b } }
  860. * @param {ASTNode} node parent node to check
  861. * @returns {Object} fixer object
  862. */
  863. function fixNestedObjectVariable(node) {
  864. const parentNode = node.parent;
  865. // fix for { a: { b: { c: { d } } } }
  866. if (
  867. parentNode.parent.parent.parent.type === "ObjectPattern" &&
  868. parentNode.parent.properties.length === 1
  869. ) {
  870. return fixNestedObjectVariable(parentNode.parent);
  871. }
  872. // fix for { a: { b } }
  873. if (parentNode.parent.type === "ObjectPattern") {
  874. // fix for unused variables in dectructured object with single property in variable decalartion and function parameter
  875. if (parentNode.parent.properties.length === 1) {
  876. return fixVariables(parentNode.parent);
  877. }
  878. // fix for first unused property when there are multiple properties such as '{ a: { b }, c }'
  879. if (getTokenBeforeValue(parentNode) === "{") {
  880. return fixer.removeRange(
  881. [parentNode.range[0], getNextTokenEnd(parentNode)]
  882. );
  883. }
  884. // fix for unused property except first one when there are multiple properties such as '{ k, a: { b } }'
  885. return fixer.removeRange([getPreviousTokenStart(parentNode), parentNode.range[1]]);
  886. }
  887. return null;
  888. }
  889. /**
  890. * fix unused variables in array and nested array
  891. * @param {ASTNode} node parent node to check
  892. * @returns {Object} fixer object
  893. */
  894. function fixNestedArrayVariable(node) {
  895. const parentNode = node.parent;
  896. // fix for nested arrays [[ a ]]
  897. if (parentNode.parent.type === "ArrayPattern" && hasSingleElement(parentNode)) {
  898. return fixNestedArrayVariable(parentNode);
  899. }
  900. if (hasSingleElement(parentNode)) {
  901. // fixes { a: [{ b }] } or { a: [[ b ]] }
  902. if (getTokenBeforeValue(parentNode) === ":") {
  903. return fixVariables(parentNode);
  904. }
  905. // fixes [a, ...[[ b ]]] or [a, ...[{ b }]]
  906. if (parentNode.parent.type === "RestElement") {
  907. // eslint-disable-next-line no-use-before-define -- due to interdependency of functions
  908. return fixRestInPattern(parentNode.parent);
  909. }
  910. // fix unused variables in destructured array in variable declaration or function parameter
  911. return fixVariables(parentNode);
  912. }
  913. // remove last unused array element
  914. if (
  915. getTokenBeforeValue(node) === "," &&
  916. getTokenAfterValue(node) === "]"
  917. ) {
  918. return fixer.removeRange([getPreviousTokenStart(node), node.range[1]]);
  919. }
  920. // remove unused array element
  921. return fixer.removeRange(node.range);
  922. }
  923. /**
  924. * fix cases like {a: {k}} or {a: [k]}
  925. * @param {ASTNode} node parent node to check
  926. * @returns {Object} fixer object
  927. */
  928. function fixObjectWithValueSeparator(node) {
  929. const parentNode = node.parent.parent;
  930. // fix cases like [{a : { b }}] or [{a : [ b ]}]
  931. if (
  932. parentNode.parent.type === "ArrayPattern" &&
  933. parentNode.properties.length === 1
  934. ) {
  935. return fixNestedArrayVariable(parentNode);
  936. }
  937. // fix cases like {a: {k}} or {a: [k]}
  938. return fixNestedObjectVariable(node);
  939. }
  940. /**
  941. * fix ...[[a]] or ...[{a}] like patterns
  942. * @param {ASTNode} node parent node to check
  943. * @returns {Object} fixer object
  944. */
  945. function fixRestInPattern(node) {
  946. const parentNode = node.parent;
  947. // fix ...[[a]] or ...[{a}] in function parameters
  948. if (isFunction(parentNode)) {
  949. if (parentNode.params.length === 1) {
  950. return fixer.removeRange(node.range);
  951. }
  952. return fixer.removeRange([getPreviousTokenStart(node), node.range[1]]);
  953. }
  954. // fix rest in nested array pattern like [[a, ...[b]]]
  955. if (parentNode.type === "ArrayPattern") {
  956. // fix [[...[b]]]
  957. if (hasSingleElement(parentNode)) {
  958. if (parentNode.parent.type === "ArrayPattern") {
  959. return fixNestedArrayVariable(parentNode);
  960. }
  961. // fix 'const [...[b]] = foo; and function foo([...[b]]) {}
  962. return fixVariables(parentNode);
  963. }
  964. // fix [[a, ...[b]]]
  965. return fixer.removeRange([getPreviousTokenStart(node), node.range[1]]);
  966. }
  967. return null;
  968. }
  969. // skip fix when variable has references that would be left behind
  970. if (allWriteReferences.some(ref => ref.identifier.range[0] !== id.range[0])) {
  971. return null;
  972. }
  973. // remove declared variables such as var a; or var a, b;
  974. if (parentType === "VariableDeclarator") {
  975. if (parent.parent.declarations.length === 1) {
  976. // prevent fix of variable in forOf and forIn loops.
  977. if (isLoop(parent.parent.parent) && parent.parent.parent.body !== parent.parent) {
  978. return null;
  979. }
  980. // removes only variable not semicolon in 'if (foo()) var bar;' or in 'loops' or in 'with' statement.
  981. if (
  982. parent.parent.parent.type === "IfStatement" ||
  983. isLoop(parent.parent.parent) ||
  984. (parent.parent.parent.type === "WithStatement" && parent.parent.parent.body === parent.parent)
  985. ) {
  986. return fixer.replaceText(parent.parent, ";");
  987. }
  988. // if next token is a string it could become a directive if node is removed -> no suggestion.
  989. const nextToken = sourceCode.getTokenAfter(parent.parent);
  990. // if previous token exists and is not ";" or "{" not sure about ASI rules -> no suggestion.
  991. const prevToken = sourceCode.getTokenBefore(parent.parent);
  992. if (nextToken && isDeclarationNotSafeToRemove(nextToken, prevToken)) {
  993. return null;
  994. }
  995. // remove unused declared variable with single declaration like 'var a = b;'
  996. return fixer.removeRange(parent.parent.range);
  997. }
  998. // remove unused declared variable with multiple declaration except first one like 'var a = b, c = d;'
  999. if (tokenBefore.value === ",") {
  1000. return fixer.removeRange([tokenBefore.range[0], parent.range[1]]);
  1001. }
  1002. // remove first unused declared variable when there are multiple declarations
  1003. return fixer.removeRange([parent.range[0], getNextTokenEnd(parent)]);
  1004. }
  1005. // remove variables in object patterns
  1006. if (parent.parent.type === "ObjectPattern") {
  1007. if (parent.parent.properties.length === 1) {
  1008. // fix [a, ...{b}]
  1009. if (parent.parent.parent.type === "RestElement") {
  1010. return fixRestInPattern(parent.parent.parent);
  1011. }
  1012. // fix [{ a }]
  1013. if (parent.parent.parent.type === "ArrayPattern") {
  1014. return fixNestedArrayVariable(parent.parent);
  1015. }
  1016. /*
  1017. * var {a} = foo;
  1018. * function a({a}) {}
  1019. * fix const { a: { b } } = foo;
  1020. */
  1021. return fixVariables(parent.parent);
  1022. }
  1023. // fix const { a:b } = foo;
  1024. if (tokenBefore.value === ":") {
  1025. // remove first unused variable in const { a:b } = foo;
  1026. if (getTokenBeforeValue(parent) === "{" && getTokenAfterValue(parent) === ",") {
  1027. return fixer.removeRange([parent.range[0], getNextTokenEnd(parent)]);
  1028. }
  1029. // remove unused variables in const { a: b, c: d } = foo; except first one
  1030. return fixer.removeRange([getPreviousTokenStart(parent), id.range[1]]);
  1031. }
  1032. }
  1033. // remove unused variables inside an array
  1034. if (parentType === "ArrayPattern") {
  1035. if (hasSingleElement(parent)) {
  1036. // fix [a, ...[b]]
  1037. if (parent.parent.type === "RestElement") {
  1038. return fixRestInPattern(parent.parent);
  1039. }
  1040. // fix [ [a] ]
  1041. if (parent.parent.type === "ArrayPattern") {
  1042. return fixNestedArrayVariable(parent);
  1043. }
  1044. /*
  1045. * fix var [a] = foo;
  1046. * fix function foo([a]) {}
  1047. * fix const { a: [b] } = foo;
  1048. */
  1049. return fixVariables(parent);
  1050. }
  1051. // if "a" is unused in [a, b ,c] fixes to [, b, c]
  1052. if (tokenBefore.value === "," && tokenAfter.value === ",") {
  1053. return fixer.removeRange(id.range);
  1054. }
  1055. }
  1056. // remove unused rest elements
  1057. if (parentType === "RestElement") {
  1058. // fix [a, ...rest]
  1059. if (parent.parent.type === "ArrayPattern") {
  1060. if (hasSingleElement(parent.parent)) {
  1061. // fix [[...rest]] when there is only rest element
  1062. if (
  1063. parent.parent.parent.type === "ArrayPattern"
  1064. ) {
  1065. return fixNestedArrayVariable(parent.parent);
  1066. }
  1067. // fix 'const [...rest] = foo;' and 'function foo([...rest]) {}'
  1068. return fixVariables(parent.parent);
  1069. }
  1070. // fix [a, ...rest]
  1071. return fixer.removeRange([getPreviousTokenStart(id, 1), id.range[1]]);
  1072. }
  1073. // fix { a, ...rest}
  1074. if (parent.parent.type === "ObjectPattern") {
  1075. // fix 'const {...rest} = foo;' and 'function foo({...rest}) {}'
  1076. if (parent.parent.properties.length === 1) {
  1077. return fixVariables(parent.parent);
  1078. }
  1079. // fix { a, ...rest} when there are multiple properties
  1080. return fixer.removeRange([getPreviousTokenStart(id, 1), id.range[1]]);
  1081. }
  1082. // fix function foo(...rest) {}
  1083. if (isFunction(parent.parent)) {
  1084. // remove unused rest in function parameter if there is only single parameter
  1085. if (parent.parent.params.length === 1) {
  1086. return fixer.removeRange(parent.range);
  1087. }
  1088. // remove unused rest in function parameter if there multiple parameter
  1089. return fixer.removeRange([getPreviousTokenStart(parent), parent.range[1]]);
  1090. }
  1091. }
  1092. if (parentType === "AssignmentPattern") {
  1093. // fix [a = aDefault]
  1094. if (parent.parent.type === "ArrayPattern") {
  1095. return fixNestedArrayVariable(parent);
  1096. }
  1097. // fix {a = aDefault}
  1098. if (parent.parent.parent.type === "ObjectPattern") {
  1099. if (parent.parent.parent.properties.length === 1) {
  1100. // fixes [{a = aDefault}]
  1101. if (parent.parent.parent.parent.type === "ArrayPattern") {
  1102. return fixNestedArrayVariable(parent.parent.parent);
  1103. }
  1104. // fix 'const {a = aDefault} = foo;' and 'function foo({a = aDefault}) {}'
  1105. return fixVariables(parent.parent.parent);
  1106. }
  1107. // fix unused 'a' in {a = aDefault} if it is the first property
  1108. if (
  1109. getTokenBeforeValue(parent.parent) === "{" &&
  1110. getTokenAfterValue(parent.parent) === ","
  1111. ) {
  1112. return fixer.removeRange([parent.parent.range[0], getNextTokenEnd(parent.parent)]);
  1113. }
  1114. // fix unused 'b' in {a, b = aDefault} if it is not the first property
  1115. return fixer.removeRange([getPreviousTokenStart(parent.parent), parent.parent.range[1]]);
  1116. }
  1117. // fix unused assignment patterns in function parameters
  1118. if (isFunction(parent.parent)) {
  1119. return fixFunctionParameters(parent);
  1120. }
  1121. }
  1122. // remove unused functions
  1123. if (parentType === "FunctionDeclaration" && parent.id === id) {
  1124. return fixer.removeRange(parent.range);
  1125. }
  1126. // remove unused default import
  1127. if (parentType === "ImportDefaultSpecifier") {
  1128. // remove unused default import when there are not other imports
  1129. if (
  1130. !hasImportOfCertainType(parent.parent, "ImportSpecifier") &&
  1131. !hasImportOfCertainType(parent.parent, "ImportNamespaceSpecifier")
  1132. ) {
  1133. return fixer.removeRange([parent.range[0], parent.parent.source.range[0]]);
  1134. }
  1135. // remove unused default import when there are other imports also
  1136. return fixer.removeRange([id.range[0], tokenAfter.range[1]]);
  1137. }
  1138. if (parentType === "ImportSpecifier") {
  1139. // remove unused imports when there is a single import
  1140. if (parent.parent.specifiers.filter(e => e.type === "ImportSpecifier").length === 1) {
  1141. // remove unused import when there is no default import
  1142. if (!hasImportOfCertainType(parent.parent, "ImportDefaultSpecifier")) {
  1143. return fixer.removeRange(parent.parent.range);
  1144. }
  1145. // fixes "import foo from 'module';" to "import 'module';"
  1146. return fixer.removeRange([getPreviousTokenStart(parent, 1), tokenAfter.range[1]]);
  1147. }
  1148. if (getTokenBeforeValue(parent) === "{") {
  1149. return fixer.removeRange([parent.range[0], getNextTokenEnd(parent)]);
  1150. }
  1151. return fixer.removeRange([getPreviousTokenStart(parent), parent.range[1]]);
  1152. }
  1153. if (parentType === "ImportNamespaceSpecifier") {
  1154. if (hasImportOfCertainType(parent.parent, "ImportDefaultSpecifier")) {
  1155. return fixer.removeRange([getPreviousTokenStart(parent), parent.range[1]]);
  1156. }
  1157. // fixes "import * as foo from 'module';" to "import 'module';"
  1158. return fixer.removeRange([parent.range[0], parent.parent.source.range[0]]);
  1159. }
  1160. // skip error in catch(error) variable
  1161. if (parentType === "CatchClause") {
  1162. return null;
  1163. }
  1164. // remove unused declared classes
  1165. if (parentType === "ClassDeclaration") {
  1166. return fixer.removeRange(parent.range);
  1167. }
  1168. // remove unused varible that is in a sequence [a,b] fixes to [a]
  1169. if (tokenBefore?.value === ",") {
  1170. return fixer.removeRange([tokenBefore.range[0], id.range[1]]);
  1171. }
  1172. // remove unused varible that is in a sequence inside function arguments and object pattern
  1173. if (tokenAfter.value === ",") {
  1174. // fix function foo(a, b) {}
  1175. if (tokenBefore.value === "(") {
  1176. return fixer.removeRange([id.range[0], tokenAfter.range[1]]);
  1177. }
  1178. // fix const {a, b} = foo;
  1179. if (tokenBefore.value === "{") {
  1180. return fixer.removeRange([id.range[0], tokenAfter.range[1]]);
  1181. }
  1182. }
  1183. if (parentType === "ArrowFunctionExpression" && parent.params.length === 1 && tokenAfter?.value !== ")") {
  1184. return fixer.replaceText(id, "()");
  1185. }
  1186. return fixer.removeRange(id.range);
  1187. }
  1188. //--------------------------------------------------------------------------
  1189. // Public
  1190. //--------------------------------------------------------------------------
  1191. return {
  1192. "Program:exit"(programNode) {
  1193. const unusedVars = collectUnusedVariables(sourceCode.getScope(programNode), []);
  1194. for (let i = 0, l = unusedVars.length; i < l; ++i) {
  1195. const unusedVar = unusedVars[i];
  1196. // Report the first declaration.
  1197. if (unusedVar.defs.length > 0) {
  1198. // report last write reference, https://github.com/eslint/eslint/issues/14324
  1199. const writeReferences = unusedVar.references.filter(ref => ref.isWrite() && ref.from.variableScope === unusedVar.scope.variableScope);
  1200. let referenceToReport;
  1201. if (writeReferences.length > 0) {
  1202. referenceToReport = writeReferences.at(-1);
  1203. }
  1204. context.report({
  1205. node: referenceToReport ? referenceToReport.identifier : unusedVar.identifiers[0],
  1206. messageId: "unusedVar",
  1207. data: unusedVar.references.some(ref => ref.isWrite())
  1208. ? getAssignedMessageData(unusedVar)
  1209. : getDefinedMessageData(unusedVar),
  1210. suggest: [
  1211. {
  1212. messageId: "removeVar",
  1213. data: {
  1214. varName: unusedVar.name
  1215. },
  1216. fix(fixer) {
  1217. return handleFixes(fixer, unusedVar);
  1218. }
  1219. }
  1220. ]
  1221. });
  1222. // If there are no regular declaration, report the first `/*globals*/` comment directive.
  1223. } else if (unusedVar.eslintExplicitGlobalComments) {
  1224. const directiveComment = unusedVar.eslintExplicitGlobalComments[0];
  1225. context.report({
  1226. node: programNode,
  1227. loc: astUtils.getNameLocationInGlobalDirectiveComment(sourceCode, directiveComment, unusedVar.name),
  1228. messageId: "unusedVar",
  1229. data: getDefinedMessageData(unusedVar)
  1230. });
  1231. }
  1232. }
  1233. }
  1234. };
  1235. }
  1236. };