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 //------------------------------------------------------------------------------
35 description
: "disallow unused variables",
36 category
: "Variables",
38 url
: "https://eslint.org/docs/rules/no-unused-vars"
45 enum: ["all", "local"]
51 enum: ["all", "local"]
57 enum: ["all", "after-used", "none"]
68 caughtErrorsIgnorePattern
: {
72 additionalProperties
: false
79 unusedVar
: "'{{varName}}' is {{action}} but never used{{additional}}."
84 const sourceCode
= context
.getSourceCode();
86 const REST_PROPERTY_TYPE
= /^(?:RestElement|(?:Experimental)?RestProperty)$/u;
91 ignoreRestSiblings
: false,
95 const firstOption
= context
.options
[0];
98 if (typeof firstOption
=== "string") {
99 config
.vars
= firstOption
;
101 config
.vars
= firstOption
.vars
|| config
.vars
;
102 config
.args
= firstOption
.args
|| config
.args
;
103 config
.ignoreRestSiblings
= firstOption
.ignoreRestSiblings
|| config
.ignoreRestSiblings
;
104 config
.caughtErrors
= firstOption
.caughtErrors
|| config
.caughtErrors
;
106 if (firstOption
.varsIgnorePattern
) {
107 config
.varsIgnorePattern
= new RegExp(firstOption
.varsIgnorePattern
, "u");
110 if (firstOption
.argsIgnorePattern
) {
111 config
.argsIgnorePattern
= new RegExp(firstOption
.argsIgnorePattern
, "u");
114 if (firstOption
.caughtErrorsIgnorePattern
) {
115 config
.caughtErrorsIgnorePattern
= new RegExp(firstOption
.caughtErrorsIgnorePattern
, "u");
121 * Generates the message data about the variable being defined and unused,
122 * including the ignore pattern if configured.
123 * @param {Variable} unusedVar eslint-scope variable object.
124 * @returns {UnusedVarMessageData} The message data to be used with this unused variable.
126 function getDefinedMessageData(unusedVar
) {
127 const defType
= unusedVar
.defs
&& unusedVar
.defs
[0] && unusedVar
.defs
[0].type
;
131 if (defType
=== "CatchClause" && config
.caughtErrorsIgnorePattern
) {
133 pattern
= config
.caughtErrorsIgnorePattern
.toString();
134 } else if (defType
=== "Parameter" && config
.argsIgnorePattern
) {
136 pattern
= config
.argsIgnorePattern
.toString();
137 } else if (defType
!== "Parameter" && config
.varsIgnorePattern
) {
139 pattern
= config
.varsIgnorePattern
.toString();
142 const additional
= type
? `. Allowed unused ${type} must match ${pattern}` : "";
145 varName
: unusedVar
.name
,
152 * Generate the warning message about the variable being
153 * assigned and unused, including the ignore pattern if configured.
154 * @param {Variable} unusedVar eslint-scope variable object.
155 * @returns {UnusedVarMessageData} The message data to be used with this unused variable.
157 function getAssignedMessageData(unusedVar
) {
158 const additional
= config
.varsIgnorePattern
? `. Allowed unused vars must match ${config.varsIgnorePattern.toString()}` : "";
161 varName
: unusedVar
.name
,
162 action
: "assigned a value",
167 //--------------------------------------------------------------------------
169 //--------------------------------------------------------------------------
171 const STATEMENT_TYPE
= /(?:Statement|Declaration)$/u;
174 * Determines if a given variable is being exported from a module.
175 * @param {Variable} variable eslint-scope variable object.
176 * @returns {boolean} True if the variable is exported, false if not.
179 function isExported(variable
) {
181 const definition
= variable
.defs
[0];
185 let node
= definition
.node
;
187 if (node
.type
=== "VariableDeclarator") {
189 } else if (definition
.type
=== "Parameter") {
193 return node
.parent
.type
.indexOf("Export") === 0;
200 * Checks whether a node is a sibling of the rest property or not.
201 * @param {ASTNode} node a node to check
202 * @returns {boolean} True if the node is a sibling of the rest property, otherwise false.
204 function hasRestSibling(node
) {
205 return node
.type
=== "Property" &&
206 node
.parent
.type
=== "ObjectPattern" &&
207 REST_PROPERTY_TYPE
.test(node
.parent
.properties
[node
.parent
.properties
.length
- 1].type
);
211 * Determines if a variable has a sibling rest property
212 * @param {Variable} variable eslint-scope variable object.
213 * @returns {boolean} True if the variable is exported, false if not.
216 function hasRestSpreadSibling(variable
) {
217 if (config
.ignoreRestSiblings
) {
218 const hasRestSiblingDefinition
= variable
.defs
.some(def
=> hasRestSibling(def
.name
.parent
));
219 const hasRestSiblingReference
= variable
.references
.some(ref
=> hasRestSibling(ref
.identifier
.parent
));
221 return hasRestSiblingDefinition
|| hasRestSiblingReference
;
228 * Determines if a reference is a read operation.
229 * @param {Reference} ref An eslint-scope Reference
230 * @returns {boolean} whether the given reference represents a read operation
233 function isReadRef(ref
) {
238 * Determine if an identifier is referencing an enclosing function name.
239 * @param {Reference} ref The reference to check.
240 * @param {ASTNode[]} nodes The candidate function nodes.
241 * @returns {boolean} True if it's a self-reference, false if not.
244 function isSelfReference(ref
, nodes
) {
245 let scope
= ref
.from;
248 if (nodes
.indexOf(scope
.block
) >= 0) {
259 * Gets a list of function definitions for a specified variable.
260 * @param {Variable} variable eslint-scope variable object.
261 * @returns {ASTNode[]} Function nodes.
264 function getFunctionDefinitions(variable
) {
265 const functionDefinitions
= [];
267 variable
.defs
.forEach(def
=> {
268 const { type
, node
} = def
;
270 // FunctionDeclarations
271 if (type
=== "FunctionName") {
272 functionDefinitions
.push(node
);
275 // FunctionExpressions
276 if (type
=== "Variable" && node
.init
&&
277 (node
.init
.type
=== "FunctionExpression" || node
.init
.type
=== "ArrowFunctionExpression")) {
278 functionDefinitions
.push(node
.init
);
281 return functionDefinitions
;
285 * Checks the position of given nodes.
286 * @param {ASTNode} inner A node which is expected as inside.
287 * @param {ASTNode} outer A node which is expected as outside.
288 * @returns {boolean} `true` if the `inner` node exists in the `outer` node.
291 function isInside(inner
, outer
) {
293 inner
.range
[0] >= outer
.range
[0] &&
294 inner
.range
[1] <= outer
.range
[1]
299 * If a given reference is left-hand side of an assignment, this gets
300 * the right-hand side node of the assignment.
302 * In the following cases, this returns null.
304 * - The reference is not the LHS of an assignment expression.
305 * - The reference is inside of a loop.
306 * - The reference is inside of a function scope which is different from
308 * @param {eslint-scope.Reference} ref A reference to check.
309 * @param {ASTNode} prevRhsNode The previous RHS node.
310 * @returns {ASTNode|null} The RHS node or null.
313 function getRhsNode(ref
, prevRhsNode
) {
314 const id
= ref
.identifier
;
315 const parent
= id
.parent
;
316 const grandparent
= parent
.parent
;
317 const refScope
= ref
.from.variableScope
;
318 const varScope
= ref
.resolved
.scope
.variableScope
;
319 const canBeUsedLater
= refScope
!== varScope
|| astUtils
.isInLoop(id
);
322 * Inherits the previous node if this reference is in the node.
323 * This is for `a = a + a`-like code.
325 if (prevRhsNode
&& isInside(id
, prevRhsNode
)) {
329 if (parent
.type
=== "AssignmentExpression" &&
330 grandparent
.type
=== "ExpressionStatement" &&
331 id
=== parent
.left
&&
340 * Checks whether a given function node is stored to somewhere or not.
341 * If the function node is stored, the function can be used later.
342 * @param {ASTNode} funcNode A function node to check.
343 * @param {ASTNode} rhsNode The RHS node of the previous assignment.
344 * @returns {boolean} `true` if under the following conditions:
345 * - the funcNode is assigned to a variable.
346 * - the funcNode is bound as an argument of a function call.
347 * - the function is bound to a property and the object satisfies above conditions.
350 function isStorableFunction(funcNode
, rhsNode
) {
352 let parent
= funcNode
.parent
;
354 while (parent
&& isInside(parent
, rhsNode
)) {
355 switch (parent
.type
) {
356 case "SequenceExpression":
357 if (parent
.expressions
[parent
.expressions
.length
- 1] !== node
) {
362 case "CallExpression":
363 case "NewExpression":
364 return parent
.callee
!== node
;
366 case "AssignmentExpression":
367 case "TaggedTemplateExpression":
368 case "YieldExpression":
372 if (STATEMENT_TYPE
.test(parent
.type
)) {
375 * If it encountered statements, this is a complex pattern.
376 * Since analyzing complex patterns is hard, this returns `true` to avoid false positive.
383 parent
= parent
.parent
;
390 * Checks whether a given Identifier node exists inside of a function node which can be used later.
392 * "can be used later" means:
393 * - the function is assigned to a variable.
394 * - the function is bound to a property and the object can be used later.
395 * - the function is bound as an argument of a function call.
397 * If a reference exists in a function which can be used later, the reference is read when the function is called.
398 * @param {ASTNode} id An Identifier node to check.
399 * @param {ASTNode} rhsNode The RHS node of the previous assignment.
400 * @returns {boolean} `true` if the `id` node exists inside of a function node which can be used later.
403 function isInsideOfStorableFunction(id
, rhsNode
) {
404 const funcNode
= astUtils
.getUpperFunction(id
);
408 isInside(funcNode
, rhsNode
) &&
409 isStorableFunction(funcNode
, rhsNode
)
414 * Checks whether a given node is unused expression or not.
415 * @param {ASTNode} node The node itself
416 * @returns {boolean} The node is an unused expression.
419 function isUnusedExpression(node
) {
420 const parent
= node
.parent
;
422 if (parent
.type
=== "ExpressionStatement") {
426 if (parent
.type
=== "SequenceExpression") {
427 const isLastExpression
= parent
.expressions
[parent
.expressions
.length
- 1] === node
;
429 if (!isLastExpression
) {
432 return isUnusedExpression(parent
);
439 * Checks whether a given reference is a read to update itself or not.
440 * @param {eslint-scope.Reference} ref A reference to check.
441 * @param {ASTNode} rhsNode The RHS node of the previous assignment.
442 * @returns {boolean} The reference is a read to update itself.
445 function isReadForItself(ref
, rhsNode
) {
446 const id
= ref
.identifier
;
447 const parent
= id
.parent
;
449 return ref
.isRead() && (
451 // self update. e.g. `a += 1`, `a++`
454 parent
.type
=== "AssignmentExpression" &&
455 parent
.left
=== id
&&
456 isUnusedExpression(parent
)
459 parent
.type
=== "UpdateExpression" &&
460 isUnusedExpression(parent
)
464 // in RHS of an assignment for itself. e.g. `a = a + 1`
467 isInside(id
, rhsNode
) &&
468 !isInsideOfStorableFunction(id
, rhsNode
)
474 * Determine if an identifier is used either in for-in loops.
475 * @param {Reference} ref The reference to check.
476 * @returns {boolean} whether reference is used in the for-in loops
479 function isForInRef(ref
) {
480 let target
= ref
.identifier
.parent
;
483 // "for (var ...) { return; }"
484 if (target
.type
=== "VariableDeclarator") {
485 target
= target
.parent
.parent
;
488 if (target
.type
!== "ForInStatement") {
492 // "for (...) { return; }"
493 if (target
.body
.type
=== "BlockStatement") {
494 target
= target
.body
.body
[0];
496 // "for (...) return;"
498 target
= target
.body
;
501 // For empty loop body
506 return target
.type
=== "ReturnStatement";
510 * Determines if the variable is used.
511 * @param {Variable} variable The variable to check.
512 * @returns {boolean} True if the variable is used
515 function isUsedVariable(variable
) {
516 const functionNodes
= getFunctionDefinitions(variable
),
517 isFunctionDefinition
= functionNodes
.length
> 0;
520 return variable
.references
.some(ref
=> {
521 if (isForInRef(ref
)) {
525 const forItself
= isReadForItself(ref
, rhsNode
);
527 rhsNode
= getRhsNode(ref
, rhsNode
);
532 !(isFunctionDefinition
&& isSelfReference(ref
, functionNodes
))
538 * Checks whether the given variable is after the last used parameter.
539 * @param {eslint-scope.Variable} variable The variable to check.
540 * @returns {boolean} `true` if the variable is defined after the last
543 function isAfterLastUsedArg(variable
) {
544 const def
= variable
.defs
[0];
545 const params
= context
.getDeclaredVariables(def
.node
);
546 const posteriorParams
= params
.slice(params
.indexOf(variable
) + 1);
548 // If any used parameters occur after this parameter, do not report.
549 return !posteriorParams
.some(v
=> v
.references
.length
> 0 || v
.eslintUsed
);
553 * Gets an array of variables without read references.
554 * @param {Scope} scope an eslint-scope Scope object.
555 * @param {Variable[]} unusedVars an array that saving result.
556 * @returns {Variable[]} unused variables of the scope and descendant scopes.
559 function collectUnusedVariables(scope
, unusedVars
) {
560 const variables
= scope
.variables
;
561 const childScopes
= scope
.childScopes
;
564 if (scope
.type
!== "global" || config
.vars
=== "all") {
565 for (i
= 0, l
= variables
.length
; i
< l
; ++i
) {
566 const variable
= variables
[i
];
568 // skip a variable of class itself name in the class scope
569 if (scope
.type
=== "class" && scope
.block
.id
=== variable
.identifiers
[0]) {
573 // skip function expression names and variables marked with markVariableAsUsed()
574 if (scope
.functionExpressionScope
|| variable
.eslintUsed
) {
578 // skip implicit "arguments" variable
579 if (scope
.type
=== "function" && variable
.name
=== "arguments" && variable
.identifiers
.length
=== 0) {
583 // explicit global variables don't have definitions.
584 const def
= variable
.defs
[0];
587 const type
= def
.type
;
589 // skip catch variables
590 if (type
=== "CatchClause") {
591 if (config
.caughtErrors
=== "none") {
595 // skip ignored parameters
596 if (config
.caughtErrorsIgnorePattern
&& config
.caughtErrorsIgnorePattern
.test(def
.name
.name
)) {
601 if (type
=== "Parameter") {
603 // skip any setter argument
604 if ((def
.node
.parent
.type
=== "Property" || def
.node
.parent
.type
=== "MethodDefinition") && def
.node
.parent
.kind
=== "set") {
608 // if "args" option is "none", skip any parameter
609 if (config
.args
=== "none") {
613 // skip ignored parameters
614 if (config
.argsIgnorePattern
&& config
.argsIgnorePattern
.test(def
.name
.name
)) {
618 // if "args" option is "after-used", skip used variables
619 if (config
.args
=== "after-used" && astUtils
.isFunction(def
.name
.parent
) && !isAfterLastUsedArg(variable
)) {
624 // skip ignored variables
625 if (config
.varsIgnorePattern
&& config
.varsIgnorePattern
.test(def
.name
.name
)) {
631 if (!isUsedVariable(variable
) && !isExported(variable
) && !hasRestSpreadSibling(variable
)) {
632 unusedVars
.push(variable
);
637 for (i
= 0, l
= childScopes
.length
; i
< l
; ++i
) {
638 collectUnusedVariables(childScopes
[i
], unusedVars
);
644 //--------------------------------------------------------------------------
646 //--------------------------------------------------------------------------
649 "Program:exit"(programNode
) {
650 const unusedVars
= collectUnusedVariables(context
.getScope(), []);
652 for (let i
= 0, l
= unusedVars
.length
; i
< l
; ++i
) {
653 const unusedVar
= unusedVars
[i
];
655 // Report the first declaration.
656 if (unusedVar
.defs
.length
> 0) {
658 // report last write reference, https://github.com/eslint/eslint/issues/14324
659 const writeReferences
= unusedVar
.references
.filter(ref
=> ref
.isWrite() && ref
.from.variableScope
=== unusedVar
.scope
.variableScope
);
661 let referenceToReport
;
663 if (writeReferences
.length
> 0) {
664 referenceToReport
= writeReferences
[writeReferences
.length
- 1];
668 node
: referenceToReport
? referenceToReport
.identifier
: unusedVar
.identifiers
[0],
669 messageId
: "unusedVar",
670 data
: unusedVar
.references
.some(ref
=> ref
.isWrite())
671 ? getAssignedMessageData(unusedVar
)
672 : getDefinedMessageData(unusedVar
)
675 // If there are no regular declaration, report the first `/*globals*/` comment directive.
676 } else if (unusedVar
.eslintExplicitGlobalComments
) {
677 const directiveComment
= unusedVar
.eslintExplicitGlobalComments
[0];
681 loc
: astUtils
.getNameLocationInGlobalDirectiveComment(sourceCode
, directiveComment
, unusedVar
.name
),
682 messageId
: "unusedVar",
683 data
: getDefinedMessageData(unusedVar
)