2 * @fileoverview Rule to flag declared but unused variables
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
12 const astUtils
= require("./utils/ast-utils");
14 //------------------------------------------------------------------------------
16 //------------------------------------------------------------------------------
19 * Bag of data used for formatting the `unusedVar` lint message.
20 * @typedef {Object} UnusedVarMessageData
21 * @property {string} varName The name of the unused var.
22 * @property {'defined'|'assigned a value'} action Description of the vars state.
23 * @property {string} additional Any additional info to be appended at the end.
26 //------------------------------------------------------------------------------
28 //------------------------------------------------------------------------------
30 /** @type {import('../shared/types').Rule} */
36 description
: "Disallow unused variables",
38 url
: "https://eslint.org/docs/latest/rules/no-unused-vars"
45 enum: ["all", "local"]
51 enum: ["all", "local"]
57 enum: ["all", "after-used", "none"]
68 caughtErrorsIgnorePattern
: {
71 destructuredArrayIgnorePattern
: {
75 additionalProperties
: false
82 unusedVar
: "'{{varName}}' is {{action}} but never used{{additional}}."
87 const sourceCode
= context
.sourceCode
;
89 const REST_PROPERTY_TYPE
= /^(?:RestElement|(?:Experimental)?RestProperty)$/u;
94 ignoreRestSiblings
: false,
98 const firstOption
= context
.options
[0];
101 if (typeof firstOption
=== "string") {
102 config
.vars
= firstOption
;
104 config
.vars
= firstOption
.vars
|| config
.vars
;
105 config
.args
= firstOption
.args
|| config
.args
;
106 config
.ignoreRestSiblings
= firstOption
.ignoreRestSiblings
|| config
.ignoreRestSiblings
;
107 config
.caughtErrors
= firstOption
.caughtErrors
|| config
.caughtErrors
;
109 if (firstOption
.varsIgnorePattern
) {
110 config
.varsIgnorePattern
= new RegExp(firstOption
.varsIgnorePattern
, "u");
113 if (firstOption
.argsIgnorePattern
) {
114 config
.argsIgnorePattern
= new RegExp(firstOption
.argsIgnorePattern
, "u");
117 if (firstOption
.caughtErrorsIgnorePattern
) {
118 config
.caughtErrorsIgnorePattern
= new RegExp(firstOption
.caughtErrorsIgnorePattern
, "u");
121 if (firstOption
.destructuredArrayIgnorePattern
) {
122 config
.destructuredArrayIgnorePattern
= new RegExp(firstOption
.destructuredArrayIgnorePattern
, "u");
128 * Generates the message data about the variable being defined and unused,
129 * including the ignore pattern if configured.
130 * @param {Variable} unusedVar eslint-scope variable object.
131 * @returns {UnusedVarMessageData} The message data to be used with this unused variable.
133 function getDefinedMessageData(unusedVar
) {
134 const defType
= unusedVar
.defs
&& unusedVar
.defs
[0] && unusedVar
.defs
[0].type
;
138 if (defType
=== "CatchClause" && config
.caughtErrorsIgnorePattern
) {
140 pattern
= config
.caughtErrorsIgnorePattern
.toString();
141 } else if (defType
=== "Parameter" && config
.argsIgnorePattern
) {
143 pattern
= config
.argsIgnorePattern
.toString();
144 } else if (defType
!== "Parameter" && config
.varsIgnorePattern
) {
146 pattern
= config
.varsIgnorePattern
.toString();
149 const additional
= type
? `. Allowed unused ${type} must match ${pattern}` : "";
152 varName
: unusedVar
.name
,
159 * Generate the warning message about the variable being
160 * assigned and unused, including the ignore pattern if configured.
161 * @param {Variable} unusedVar eslint-scope variable object.
162 * @returns {UnusedVarMessageData} The message data to be used with this unused variable.
164 function getAssignedMessageData(unusedVar
) {
165 const def
= unusedVar
.defs
[0];
168 if (config
.destructuredArrayIgnorePattern
&& def
&& def
.name
.parent
.type
=== "ArrayPattern") {
169 additional
= `. Allowed unused elements of array destructuring patterns must match ${config.destructuredArrayIgnorePattern.toString()}`;
170 } else if (config
.varsIgnorePattern
) {
171 additional
= `. Allowed unused vars must match ${config.varsIgnorePattern.toString()}`;
175 varName
: unusedVar
.name
,
176 action
: "assigned a value",
181 //--------------------------------------------------------------------------
183 //--------------------------------------------------------------------------
185 const STATEMENT_TYPE
= /(?:Statement|Declaration)$/u;
188 * Determines if a given variable is being exported from a module.
189 * @param {Variable} variable eslint-scope variable object.
190 * @returns {boolean} True if the variable is exported, false if not.
193 function isExported(variable
) {
195 const definition
= variable
.defs
[0];
199 let node
= definition
.node
;
201 if (node
.type
=== "VariableDeclarator") {
203 } else if (definition
.type
=== "Parameter") {
207 return node
.parent
.type
.indexOf("Export") === 0;
214 * Checks whether a node is a sibling of the rest property or not.
215 * @param {ASTNode} node a node to check
216 * @returns {boolean} True if the node is a sibling of the rest property, otherwise false.
218 function hasRestSibling(node
) {
219 return node
.type
=== "Property" &&
220 node
.parent
.type
=== "ObjectPattern" &&
221 REST_PROPERTY_TYPE
.test(node
.parent
.properties
[node
.parent
.properties
.length
- 1].type
);
225 * Determines if a variable has a sibling rest property
226 * @param {Variable} variable eslint-scope variable object.
227 * @returns {boolean} True if the variable is exported, false if not.
230 function hasRestSpreadSibling(variable
) {
231 if (config
.ignoreRestSiblings
) {
232 const hasRestSiblingDefinition
= variable
.defs
.some(def
=> hasRestSibling(def
.name
.parent
));
233 const hasRestSiblingReference
= variable
.references
.some(ref
=> hasRestSibling(ref
.identifier
.parent
));
235 return hasRestSiblingDefinition
|| hasRestSiblingReference
;
242 * Determines if a reference is a read operation.
243 * @param {Reference} ref An eslint-scope Reference
244 * @returns {boolean} whether the given reference represents a read operation
247 function isReadRef(ref
) {
252 * Determine if an identifier is referencing an enclosing function name.
253 * @param {Reference} ref The reference to check.
254 * @param {ASTNode[]} nodes The candidate function nodes.
255 * @returns {boolean} True if it's a self-reference, false if not.
258 function isSelfReference(ref
, nodes
) {
259 let scope
= ref
.from;
262 if (nodes
.includes(scope
.block
)) {
273 * Gets a list of function definitions for a specified variable.
274 * @param {Variable} variable eslint-scope variable object.
275 * @returns {ASTNode[]} Function nodes.
278 function getFunctionDefinitions(variable
) {
279 const functionDefinitions
= [];
281 variable
.defs
.forEach(def
=> {
282 const { type
, node
} = def
;
284 // FunctionDeclarations
285 if (type
=== "FunctionName") {
286 functionDefinitions
.push(node
);
289 // FunctionExpressions
290 if (type
=== "Variable" && node
.init
&&
291 (node
.init
.type
=== "FunctionExpression" || node
.init
.type
=== "ArrowFunctionExpression")) {
292 functionDefinitions
.push(node
.init
);
295 return functionDefinitions
;
299 * Checks the position of given nodes.
300 * @param {ASTNode} inner A node which is expected as inside.
301 * @param {ASTNode} outer A node which is expected as outside.
302 * @returns {boolean} `true` if the `inner` node exists in the `outer` node.
305 function isInside(inner
, outer
) {
307 inner
.range
[0] >= outer
.range
[0] &&
308 inner
.range
[1] <= outer
.range
[1]
313 * Checks whether a given node is unused expression or not.
314 * @param {ASTNode} node The node itself
315 * @returns {boolean} The node is an unused expression.
318 function isUnusedExpression(node
) {
319 const parent
= node
.parent
;
321 if (parent
.type
=== "ExpressionStatement") {
325 if (parent
.type
=== "SequenceExpression") {
326 const isLastExpression
= parent
.expressions
[parent
.expressions
.length
- 1] === node
;
328 if (!isLastExpression
) {
331 return isUnusedExpression(parent
);
338 * If a given reference is left-hand side of an assignment, this gets
339 * the right-hand side node of the assignment.
341 * In the following cases, this returns null.
343 * - The reference is not the LHS of an assignment expression.
344 * - The reference is inside of a loop.
345 * - The reference is inside of a function scope which is different from
347 * @param {eslint-scope.Reference} ref A reference to check.
348 * @param {ASTNode} prevRhsNode The previous RHS node.
349 * @returns {ASTNode|null} The RHS node or null.
352 function getRhsNode(ref
, prevRhsNode
) {
353 const id
= ref
.identifier
;
354 const parent
= id
.parent
;
355 const refScope
= ref
.from.variableScope
;
356 const varScope
= ref
.resolved
.scope
.variableScope
;
357 const canBeUsedLater
= refScope
!== varScope
|| astUtils
.isInLoop(id
);
360 * Inherits the previous node if this reference is in the node.
361 * This is for `a = a + a`-like code.
363 if (prevRhsNode
&& isInside(id
, prevRhsNode
)) {
367 if (parent
.type
=== "AssignmentExpression" &&
368 isUnusedExpression(parent
) &&
369 id
=== parent
.left
&&
378 * Checks whether a given function node is stored to somewhere or not.
379 * If the function node is stored, the function can be used later.
380 * @param {ASTNode} funcNode A function node to check.
381 * @param {ASTNode} rhsNode The RHS node of the previous assignment.
382 * @returns {boolean} `true` if under the following conditions:
383 * - the funcNode is assigned to a variable.
384 * - the funcNode is bound as an argument of a function call.
385 * - the function is bound to a property and the object satisfies above conditions.
388 function isStorableFunction(funcNode
, rhsNode
) {
390 let parent
= funcNode
.parent
;
392 while (parent
&& isInside(parent
, rhsNode
)) {
393 switch (parent
.type
) {
394 case "SequenceExpression":
395 if (parent
.expressions
[parent
.expressions
.length
- 1] !== node
) {
400 case "CallExpression":
401 case "NewExpression":
402 return parent
.callee
!== node
;
404 case "AssignmentExpression":
405 case "TaggedTemplateExpression":
406 case "YieldExpression":
410 if (STATEMENT_TYPE
.test(parent
.type
)) {
413 * If it encountered statements, this is a complex pattern.
414 * Since analyzing complex patterns is hard, this returns `true` to avoid false positive.
421 parent
= parent
.parent
;
428 * Checks whether a given Identifier node exists inside of a function node which can be used later.
430 * "can be used later" means:
431 * - the function is assigned to a variable.
432 * - the function is bound to a property and the object can be used later.
433 * - the function is bound as an argument of a function call.
435 * If a reference exists in a function which can be used later, the reference is read when the function is called.
436 * @param {ASTNode} id An Identifier node to check.
437 * @param {ASTNode} rhsNode The RHS node of the previous assignment.
438 * @returns {boolean} `true` if the `id` node exists inside of a function node which can be used later.
441 function isInsideOfStorableFunction(id
, rhsNode
) {
442 const funcNode
= astUtils
.getUpperFunction(id
);
446 isInside(funcNode
, rhsNode
) &&
447 isStorableFunction(funcNode
, rhsNode
)
452 * Checks whether a given reference is a read to update itself or not.
453 * @param {eslint-scope.Reference} ref A reference to check.
454 * @param {ASTNode} rhsNode The RHS node of the previous assignment.
455 * @returns {boolean} The reference is a read to update itself.
458 function isReadForItself(ref
, rhsNode
) {
459 const id
= ref
.identifier
;
460 const parent
= id
.parent
;
462 return ref
.isRead() && (
464 // self update. e.g. `a += 1`, `a++`
467 parent
.type
=== "AssignmentExpression" &&
468 parent
.left
=== id
&&
469 isUnusedExpression(parent
)
472 parent
.type
=== "UpdateExpression" &&
473 isUnusedExpression(parent
)
477 // in RHS of an assignment for itself. e.g. `a = a + 1`
480 isInside(id
, rhsNode
) &&
481 !isInsideOfStorableFunction(id
, rhsNode
)
487 * Determine if an identifier is used either in for-in or for-of loops.
488 * @param {Reference} ref The reference to check.
489 * @returns {boolean} whether reference is used in the for-in loops
492 function isForInOfRef(ref
) {
493 let target
= ref
.identifier
.parent
;
496 // "for (var ...) { return; }"
497 if (target
.type
=== "VariableDeclarator") {
498 target
= target
.parent
.parent
;
501 if (target
.type
!== "ForInStatement" && target
.type
!== "ForOfStatement") {
505 // "for (...) { return; }"
506 if (target
.body
.type
=== "BlockStatement") {
507 target
= target
.body
.body
[0];
509 // "for (...) return;"
511 target
= target
.body
;
514 // For empty loop body
519 return target
.type
=== "ReturnStatement";
523 * Determines if the variable is used.
524 * @param {Variable} variable The variable to check.
525 * @returns {boolean} True if the variable is used
528 function isUsedVariable(variable
) {
529 const functionNodes
= getFunctionDefinitions(variable
),
530 isFunctionDefinition
= functionNodes
.length
> 0;
533 return variable
.references
.some(ref
=> {
534 if (isForInOfRef(ref
)) {
538 const forItself
= isReadForItself(ref
, rhsNode
);
540 rhsNode
= getRhsNode(ref
, rhsNode
);
545 !(isFunctionDefinition
&& isSelfReference(ref
, functionNodes
))
551 * Checks whether the given variable is after the last used parameter.
552 * @param {eslint-scope.Variable} variable The variable to check.
553 * @returns {boolean} `true` if the variable is defined after the last
556 function isAfterLastUsedArg(variable
) {
557 const def
= variable
.defs
[0];
558 const params
= sourceCode
.getDeclaredVariables(def
.node
);
559 const posteriorParams
= params
.slice(params
.indexOf(variable
) + 1);
561 // If any used parameters occur after this parameter, do not report.
562 return !posteriorParams
.some(v
=> v
.references
.length
> 0 || v
.eslintUsed
);
566 * Gets an array of variables without read references.
567 * @param {Scope} scope an eslint-scope Scope object.
568 * @param {Variable[]} unusedVars an array that saving result.
569 * @returns {Variable[]} unused variables of the scope and descendant scopes.
572 function collectUnusedVariables(scope
, unusedVars
) {
573 const variables
= scope
.variables
;
574 const childScopes
= scope
.childScopes
;
577 if (scope
.type
!== "global" || config
.vars
=== "all") {
578 for (i
= 0, l
= variables
.length
; i
< l
; ++i
) {
579 const variable
= variables
[i
];
581 // skip a variable of class itself name in the class scope
582 if (scope
.type
=== "class" && scope
.block
.id
=== variable
.identifiers
[0]) {
586 // skip function expression names and variables marked with markVariableAsUsed()
587 if (scope
.functionExpressionScope
|| variable
.eslintUsed
) {
591 // skip implicit "arguments" variable
592 if (scope
.type
=== "function" && variable
.name
=== "arguments" && variable
.identifiers
.length
=== 0) {
596 // explicit global variables don't have definitions.
597 const def
= variable
.defs
[0];
600 const type
= def
.type
;
601 const refUsedInArrayPatterns
= variable
.references
.some(ref
=> ref
.identifier
.parent
.type
=== "ArrayPattern");
603 // skip elements of array destructuring patterns
606 def
.name
.parent
.type
=== "ArrayPattern" ||
607 refUsedInArrayPatterns
609 config
.destructuredArrayIgnorePattern
&&
610 config
.destructuredArrayIgnorePattern
.test(def
.name
.name
)
615 // skip catch variables
616 if (type
=== "CatchClause") {
617 if (config
.caughtErrors
=== "none") {
621 // skip ignored parameters
622 if (config
.caughtErrorsIgnorePattern
&& config
.caughtErrorsIgnorePattern
.test(def
.name
.name
)) {
627 if (type
=== "Parameter") {
629 // skip any setter argument
630 if ((def
.node
.parent
.type
=== "Property" || def
.node
.parent
.type
=== "MethodDefinition") && def
.node
.parent
.kind
=== "set") {
634 // if "args" option is "none", skip any parameter
635 if (config
.args
=== "none") {
639 // skip ignored parameters
640 if (config
.argsIgnorePattern
&& config
.argsIgnorePattern
.test(def
.name
.name
)) {
644 // if "args" option is "after-used", skip used variables
645 if (config
.args
=== "after-used" && astUtils
.isFunction(def
.name
.parent
) && !isAfterLastUsedArg(variable
)) {
650 // skip ignored variables
651 if (config
.varsIgnorePattern
&& config
.varsIgnorePattern
.test(def
.name
.name
)) {
657 if (!isUsedVariable(variable
) && !isExported(variable
) && !hasRestSpreadSibling(variable
)) {
658 unusedVars
.push(variable
);
663 for (i
= 0, l
= childScopes
.length
; i
< l
; ++i
) {
664 collectUnusedVariables(childScopes
[i
], unusedVars
);
670 //--------------------------------------------------------------------------
672 //--------------------------------------------------------------------------
675 "Program:exit"(programNode
) {
676 const unusedVars
= collectUnusedVariables(sourceCode
.getScope(programNode
), []);
678 for (let i
= 0, l
= unusedVars
.length
; i
< l
; ++i
) {
679 const unusedVar
= unusedVars
[i
];
681 // Report the first declaration.
682 if (unusedVar
.defs
.length
> 0) {
684 // report last write reference, https://github.com/eslint/eslint/issues/14324
685 const writeReferences
= unusedVar
.references
.filter(ref
=> ref
.isWrite() && ref
.from.variableScope
=== unusedVar
.scope
.variableScope
);
687 let referenceToReport
;
689 if (writeReferences
.length
> 0) {
690 referenceToReport
= writeReferences
[writeReferences
.length
- 1];
694 node
: referenceToReport
? referenceToReport
.identifier
: unusedVar
.identifiers
[0],
695 messageId
: "unusedVar",
696 data
: unusedVar
.references
.some(ref
=> ref
.isWrite())
697 ? getAssignedMessageData(unusedVar
)
698 : getDefinedMessageData(unusedVar
)
701 // If there are no regular declaration, report the first `/*globals*/` comment directive.
702 } else if (unusedVar
.eslintExplicitGlobalComments
) {
703 const directiveComment
= unusedVar
.eslintExplicitGlobalComments
[0];
707 loc
: astUtils
.getNameLocationInGlobalDirectiveComment(sourceCode
, directiveComment
, unusedVar
.name
),
708 messageId
: "unusedVar",
709 data
: getDefinedMessageData(unusedVar
)