2 * @fileoverview Rule to disallow unused labels.
3 * @author Toru Nagashima
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
17 description: "disallow unused labels",
18 category: "Best Practices",
20 url: "https://eslint.org/docs/rules/no-unused-labels"
28 unused: "'{{name}}:' is defined but never used."
33 const sourceCode = context.getSourceCode();
37 * Adds a scope info to the stack.
38 * @param {ASTNode} node A node to add. This is a LabeledStatement.
41 function enterLabeledScope(node) {
43 label: node.label.name,
50 * Removes the top of the stack.
51 * At the same time, this reports the label if it's never used.
52 * @param {ASTNode} node A node to report. This is a LabeledStatement.
55 function exitLabeledScope(node) {
56 if (!scopeInfo.used) {
64 * Only perform a fix if there are no comments between the label and the body. This will be the case
65 * when there is exactly one token/comment (the ":") between the label and the body.
67 if (sourceCode.getTokenAfter(node.label, { includeComments: true }) ===
68 sourceCode.getTokenBefore(node.body, { includeComments: true })) {
69 return fixer.removeRange([node.range[0], node.body.range[0]]);
77 scopeInfo = scopeInfo.upper;
81 * Marks the label of a given node as used.
82 * @param {ASTNode} node A node to mark. This is a BreakStatement or
86 function markAsUsed(node) {
91 const label = node.label.name;
95 if (info.label === label) {
104 LabeledStatement: enterLabeledScope,
105 "LabeledStatement:exit": exitLabeledScope,
106 BreakStatement: markAsUsed,
107 ContinueStatement: markAsUsed