UNPKG

3.3 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to disallow unused labels.
3 * @author Toru Nagashima
4 */
5
6"use strict";
7
8//------------------------------------------------------------------------------
9// Rule Definition
10//------------------------------------------------------------------------------
11
12module.exports = {
13 meta: {
14 type: "suggestion",
15
16 docs: {
17 description: "disallow unused labels",
18 category: "Best Practices",
19 recommended: true,
20 url: "https://eslint.org/docs/rules/no-unused-labels"
21 },
22
23 schema: [],
24
25 fixable: "code",
26
27 messages: {
28 unused: "'{{name}}:' is defined but never used."
29 }
30 },
31
32 create(context) {
33 const sourceCode = context.getSourceCode();
34 let scopeInfo = null;
35
36 /**
37 * Adds a scope info to the stack.
38 *
39 * @param {ASTNode} node - A node to add. This is a LabeledStatement.
40 * @returns {void}
41 */
42 function enterLabeledScope(node) {
43 scopeInfo = {
44 label: node.label.name,
45 used: false,
46 upper: scopeInfo
47 };
48 }
49
50 /**
51 * Removes the top of the stack.
52 * At the same time, this reports the label if it's never used.
53 *
54 * @param {ASTNode} node - A node to report. This is a LabeledStatement.
55 * @returns {void}
56 */
57 function exitLabeledScope(node) {
58 if (!scopeInfo.used) {
59 context.report({
60 node: node.label,
61 messageId: "unused",
62 data: node.label,
63 fix(fixer) {
64
65 /*
66 * Only perform a fix if there are no comments between the label and the body. This will be the case
67 * when there is exactly one token/comment (the ":") between the label and the body.
68 */
69 if (sourceCode.getTokenAfter(node.label, { includeComments: true }) ===
70 sourceCode.getTokenBefore(node.body, { includeComments: true })) {
71 return fixer.removeRange([node.range[0], node.body.range[0]]);
72 }
73
74 return null;
75 }
76 });
77 }
78
79 scopeInfo = scopeInfo.upper;
80 }
81
82 /**
83 * Marks the label of a given node as used.
84 *
85 * @param {ASTNode} node - A node to mark. This is a BreakStatement or
86 * ContinueStatement.
87 * @returns {void}
88 */
89 function markAsUsed(node) {
90 if (!node.label) {
91 return;
92 }
93
94 const label = node.label.name;
95 let info = scopeInfo;
96
97 while (info) {
98 if (info.label === label) {
99 info.used = true;
100 break;
101 }
102 info = info.upper;
103 }
104 }
105
106 return {
107 LabeledStatement: enterLabeledScope,
108 "LabeledStatement:exit": exitLabeledScope,
109 BreakStatement: markAsUsed,
110 ContinueStatement: markAsUsed
111 };
112 }
113};