github-pages-deploy-action/node_modules/eslint/lib/rules/no-unused-labels.js

111 lines
3.2 KiB
JavaScript
Raw Permalink Normal View History

2020-03-07 11:45:40 +08:00
/**
* @fileoverview Rule to disallow unused labels.
* @author Toru Nagashima
*/
"use strict";
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "disallow unused labels",
category: "Best Practices",
recommended: true,
url: "https://eslint.org/docs/rules/no-unused-labels"
},
schema: [],
fixable: "code",
messages: {
unused: "'{{name}}:' is defined but never used."
}
},
create(context) {
const sourceCode = context.getSourceCode();
let scopeInfo = null;
/**
* Adds a scope info to the stack.
2020-03-31 20:40:00 +08:00
* @param {ASTNode} node A node to add. This is a LabeledStatement.
2020-03-07 11:45:40 +08:00
* @returns {void}
*/
function enterLabeledScope(node) {
scopeInfo = {
label: node.label.name,
used: false,
upper: scopeInfo
};
}
/**
* Removes the top of the stack.
* At the same time, this reports the label if it's never used.
2020-03-31 20:40:00 +08:00
* @param {ASTNode} node A node to report. This is a LabeledStatement.
2020-03-07 11:45:40 +08:00
* @returns {void}
*/
function exitLabeledScope(node) {
if (!scopeInfo.used) {
context.report({
node: node.label,
messageId: "unused",
data: node.label,
fix(fixer) {
/*
* Only perform a fix if there are no comments between the label and the body. This will be the case
* when there is exactly one token/comment (the ":") between the label and the body.
*/
if (sourceCode.getTokenAfter(node.label, { includeComments: true }) ===
sourceCode.getTokenBefore(node.body, { includeComments: true })) {
return fixer.removeRange([node.range[0], node.body.range[0]]);
}
return null;
}
});
}
scopeInfo = scopeInfo.upper;
}
/**
* Marks the label of a given node as used.
2020-03-31 20:40:00 +08:00
* @param {ASTNode} node A node to mark. This is a BreakStatement or
2020-03-07 11:45:40 +08:00
* ContinueStatement.
* @returns {void}
*/
function markAsUsed(node) {
if (!node.label) {
return;
}
const label = node.label.name;
let info = scopeInfo;
while (info) {
if (info.label === label) {
info.used = true;
break;
}
info = info.upper;
}
}
return {
LabeledStatement: enterLabeledScope,
"LabeledStatement:exit": exitLabeledScope,
BreakStatement: markAsUsed,
ContinueStatement: markAsUsed
};
}
};