123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691 |
- "use strict";
- const astUtils = require("./utils/ast-utils");
- module.exports = {
- meta: {
- type: "problem",
- docs: {
- description: "disallow unused variables",
- category: "Variables",
- recommended: true,
- url: "https://eslint.org/docs/rules/no-unused-vars"
- },
- schema: [
- {
- oneOf: [
- {
- enum: ["all", "local"]
- },
- {
- type: "object",
- properties: {
- vars: {
- enum: ["all", "local"]
- },
- varsIgnorePattern: {
- type: "string"
- },
- args: {
- enum: ["all", "after-used", "none"]
- },
- ignoreRestSiblings: {
- type: "boolean"
- },
- argsIgnorePattern: {
- type: "string"
- },
- caughtErrors: {
- enum: ["all", "none"]
- },
- caughtErrorsIgnorePattern: {
- type: "string"
- }
- },
- additionalProperties: false
- }
- ]
- }
- ],
- messages: {
- unusedVar: "'{{varName}}' is {{action}} but never used{{additional}}."
- }
- },
- create(context) {
- const sourceCode = context.getSourceCode();
- const REST_PROPERTY_TYPE = /^(?:RestElement|(?:Experimental)?RestProperty)$/u;
- const config = {
- vars: "all",
- args: "after-used",
- ignoreRestSiblings: false,
- caughtErrors: "none"
- };
- const firstOption = context.options[0];
- if (firstOption) {
- if (typeof firstOption === "string") {
- config.vars = firstOption;
- } else {
- config.vars = firstOption.vars || config.vars;
- config.args = firstOption.args || config.args;
- config.ignoreRestSiblings = firstOption.ignoreRestSiblings || config.ignoreRestSiblings;
- config.caughtErrors = firstOption.caughtErrors || config.caughtErrors;
- if (firstOption.varsIgnorePattern) {
- config.varsIgnorePattern = new RegExp(firstOption.varsIgnorePattern, "u");
- }
- if (firstOption.argsIgnorePattern) {
- config.argsIgnorePattern = new RegExp(firstOption.argsIgnorePattern, "u");
- }
- if (firstOption.caughtErrorsIgnorePattern) {
- config.caughtErrorsIgnorePattern = new RegExp(firstOption.caughtErrorsIgnorePattern, "u");
- }
- }
- }
-
- function getDefinedMessageData(unusedVar) {
- const defType = unusedVar.defs && unusedVar.defs[0] && unusedVar.defs[0].type;
- let type;
- let pattern;
- if (defType === "CatchClause" && config.caughtErrorsIgnorePattern) {
- type = "args";
- pattern = config.caughtErrorsIgnorePattern.toString();
- } else if (defType === "Parameter" && config.argsIgnorePattern) {
- type = "args";
- pattern = config.argsIgnorePattern.toString();
- } else if (defType !== "Parameter" && config.varsIgnorePattern) {
- type = "vars";
- pattern = config.varsIgnorePattern.toString();
- }
- const additional = type ? `. Allowed unused ${type} must match ${pattern}` : "";
- return {
- varName: unusedVar.name,
- action: "defined",
- additional
- };
- }
-
- function getAssignedMessageData(unusedVar) {
- const additional = config.varsIgnorePattern ? `. Allowed unused vars must match ${config.varsIgnorePattern.toString()}` : "";
- return {
- varName: unusedVar.name,
- action: "assigned a value",
- additional
- };
- }
-
-
-
- const STATEMENT_TYPE = /(?:Statement|Declaration)$/u;
-
- function isExported(variable) {
- const definition = variable.defs[0];
- if (definition) {
- let node = definition.node;
- if (node.type === "VariableDeclarator") {
- node = node.parent;
- } else if (definition.type === "Parameter") {
- return false;
- }
- return node.parent.type.indexOf("Export") === 0;
- }
- return false;
- }
-
- function hasRestSibling(node) {
- return node.type === "Property" &&
- node.parent.type === "ObjectPattern" &&
- REST_PROPERTY_TYPE.test(node.parent.properties[node.parent.properties.length - 1].type);
- }
-
- function hasRestSpreadSibling(variable) {
- if (config.ignoreRestSiblings) {
- const hasRestSiblingDefinition = variable.defs.some(def => hasRestSibling(def.name.parent));
- const hasRestSiblingReference = variable.references.some(ref => hasRestSibling(ref.identifier.parent));
- return hasRestSiblingDefinition || hasRestSiblingReference;
- }
- return false;
- }
-
- function isReadRef(ref) {
- return ref.isRead();
- }
-
- function isSelfReference(ref, nodes) {
- let scope = ref.from;
- while (scope) {
- if (nodes.indexOf(scope.block) >= 0) {
- return true;
- }
- scope = scope.upper;
- }
- return false;
- }
-
- function getFunctionDefinitions(variable) {
- const functionDefinitions = [];
- variable.defs.forEach(def => {
- const { type, node } = def;
-
- if (type === "FunctionName") {
- functionDefinitions.push(node);
- }
-
- if (type === "Variable" && node.init &&
- (node.init.type === "FunctionExpression" || node.init.type === "ArrowFunctionExpression")) {
- functionDefinitions.push(node.init);
- }
- });
- return functionDefinitions;
- }
-
- function isInside(inner, outer) {
- return (
- inner.range[0] >= outer.range[0] &&
- inner.range[1] <= outer.range[1]
- );
- }
-
- function getRhsNode(ref, prevRhsNode) {
- const id = ref.identifier;
- const parent = id.parent;
- const grandparent = parent.parent;
- const refScope = ref.from.variableScope;
- const varScope = ref.resolved.scope.variableScope;
- const canBeUsedLater = refScope !== varScope || astUtils.isInLoop(id);
-
- if (prevRhsNode && isInside(id, prevRhsNode)) {
- return prevRhsNode;
- }
- if (parent.type === "AssignmentExpression" &&
- grandparent.type === "ExpressionStatement" &&
- id === parent.left &&
- !canBeUsedLater
- ) {
- return parent.right;
- }
- return null;
- }
-
- function isStorableFunction(funcNode, rhsNode) {
- let node = funcNode;
- let parent = funcNode.parent;
- while (parent && isInside(parent, rhsNode)) {
- switch (parent.type) {
- case "SequenceExpression":
- if (parent.expressions[parent.expressions.length - 1] !== node) {
- return false;
- }
- break;
- case "CallExpression":
- case "NewExpression":
- return parent.callee !== node;
- case "AssignmentExpression":
- case "TaggedTemplateExpression":
- case "YieldExpression":
- return true;
- default:
- if (STATEMENT_TYPE.test(parent.type)) {
-
- return true;
- }
- }
- node = parent;
- parent = parent.parent;
- }
- return false;
- }
-
- function isInsideOfStorableFunction(id, rhsNode) {
- const funcNode = astUtils.getUpperFunction(id);
- return (
- funcNode &&
- isInside(funcNode, rhsNode) &&
- isStorableFunction(funcNode, rhsNode)
- );
- }
-
- function isUnusedExpression(node) {
- const parent = node.parent;
- if (parent.type === "ExpressionStatement") {
- return true;
- }
- if (parent.type === "SequenceExpression") {
- const isLastExpression = parent.expressions[parent.expressions.length - 1] === node;
- if (!isLastExpression) {
- return true;
- }
- return isUnusedExpression(parent);
- }
- return false;
- }
-
- function isReadForItself(ref, rhsNode) {
- const id = ref.identifier;
- const parent = id.parent;
- return ref.isRead() && (
-
- (
- (
- parent.type === "AssignmentExpression" &&
- parent.left === id &&
- isUnusedExpression(parent)
- ) ||
- (
- parent.type === "UpdateExpression" &&
- isUnusedExpression(parent)
- )
- ) ||
-
- (
- rhsNode &&
- isInside(id, rhsNode) &&
- !isInsideOfStorableFunction(id, rhsNode)
- )
- );
- }
-
- function isForInRef(ref) {
- let target = ref.identifier.parent;
-
- if (target.type === "VariableDeclarator") {
- target = target.parent.parent;
- }
- if (target.type !== "ForInStatement") {
- return false;
- }
-
- if (target.body.type === "BlockStatement") {
- target = target.body.body[0];
-
- } else {
- target = target.body;
- }
-
- if (!target) {
- return false;
- }
- return target.type === "ReturnStatement";
- }
-
- function isUsedVariable(variable) {
- const functionNodes = getFunctionDefinitions(variable),
- isFunctionDefinition = functionNodes.length > 0;
- let rhsNode = null;
- return variable.references.some(ref => {
- if (isForInRef(ref)) {
- return true;
- }
- const forItself = isReadForItself(ref, rhsNode);
- rhsNode = getRhsNode(ref, rhsNode);
- return (
- isReadRef(ref) &&
- !forItself &&
- !(isFunctionDefinition && isSelfReference(ref, functionNodes))
- );
- });
- }
-
- function isAfterLastUsedArg(variable) {
- const def = variable.defs[0];
- const params = context.getDeclaredVariables(def.node);
- const posteriorParams = params.slice(params.indexOf(variable) + 1);
-
- return !posteriorParams.some(v => v.references.length > 0 || v.eslintUsed);
- }
-
- function collectUnusedVariables(scope, unusedVars) {
- const variables = scope.variables;
- const childScopes = scope.childScopes;
- let i, l;
- if (scope.type !== "global" || config.vars === "all") {
- for (i = 0, l = variables.length; i < l; ++i) {
- const variable = variables[i];
-
- if (scope.type === "class" && scope.block.id === variable.identifiers[0]) {
- continue;
- }
-
- if (scope.functionExpressionScope || variable.eslintUsed) {
- continue;
- }
-
- if (scope.type === "function" && variable.name === "arguments" && variable.identifiers.length === 0) {
- continue;
- }
-
- const def = variable.defs[0];
- if (def) {
- const type = def.type;
-
- if (type === "CatchClause") {
- if (config.caughtErrors === "none") {
- continue;
- }
-
- if (config.caughtErrorsIgnorePattern && config.caughtErrorsIgnorePattern.test(def.name.name)) {
- continue;
- }
- }
- if (type === "Parameter") {
-
- if ((def.node.parent.type === "Property" || def.node.parent.type === "MethodDefinition") && def.node.parent.kind === "set") {
- continue;
- }
-
- if (config.args === "none") {
- continue;
- }
-
- if (config.argsIgnorePattern && config.argsIgnorePattern.test(def.name.name)) {
- continue;
- }
-
- if (config.args === "after-used" && astUtils.isFunction(def.name.parent) && !isAfterLastUsedArg(variable)) {
- continue;
- }
- } else {
-
- if (config.varsIgnorePattern && config.varsIgnorePattern.test(def.name.name)) {
- continue;
- }
- }
- }
- if (!isUsedVariable(variable) && !isExported(variable) && !hasRestSpreadSibling(variable)) {
- unusedVars.push(variable);
- }
- }
- }
- for (i = 0, l = childScopes.length; i < l; ++i) {
- collectUnusedVariables(childScopes[i], unusedVars);
- }
- return unusedVars;
- }
-
-
-
- return {
- "Program:exit"(programNode) {
- const unusedVars = collectUnusedVariables(context.getScope(), []);
- for (let i = 0, l = unusedVars.length; i < l; ++i) {
- const unusedVar = unusedVars[i];
-
- if (unusedVar.defs.length > 0) {
-
- const writeReferences = unusedVar.references.filter(ref => ref.isWrite() && ref.from.variableScope === unusedVar.scope.variableScope);
- let referenceToReport;
- if (writeReferences.length > 0) {
- referenceToReport = writeReferences[writeReferences.length - 1];
- }
- context.report({
- node: referenceToReport ? referenceToReport.identifier : unusedVar.identifiers[0],
- messageId: "unusedVar",
- data: unusedVar.references.some(ref => ref.isWrite())
- ? getAssignedMessageData(unusedVar)
- : getDefinedMessageData(unusedVar)
- });
-
- } else if (unusedVar.eslintExplicitGlobalComments) {
- const directiveComment = unusedVar.eslintExplicitGlobalComments[0];
- context.report({
- node: programNode,
- loc: astUtils.getNameLocationInGlobalDirectiveComment(sourceCode, directiveComment, unusedVar.name),
- messageId: "unusedVar",
- data: getDefinedMessageData(unusedVar)
- });
- }
- }
- }
- };
- }
- };
|