2 * @fileoverview Disallow Labeled Statements
3 * @author Nicholas C. Zakas
7 //------------------------------------------------------------------------------
9 //------------------------------------------------------------------------------
11 const astUtils = require("./utils/ast-utils");
13 //------------------------------------------------------------------------------
15 //------------------------------------------------------------------------------
22 description: "disallow labeled statements",
23 category: "Best Practices",
25 url: "https://eslint.org/docs/rules/no-labels"
41 additionalProperties: false
46 unexpectedLabel: "Unexpected labeled statement.",
47 unexpectedLabelInBreak: "Unexpected label in break statement.",
48 unexpectedLabelInContinue: "Unexpected label in continue statement."
53 const options = context.options[0];
54 const allowLoop = options && options.allowLoop;
55 const allowSwitch = options && options.allowSwitch;
59 * Gets the kind of a given node.
60 * @param {ASTNode} node A node to get.
61 * @returns {string} The kind of the node.
63 function getBodyKind(node) {
64 if (astUtils.isLoop(node)) {
67 if (node.type === "SwitchStatement") {
74 * Checks whether the label of a given kind is allowed or not.
75 * @param {string} kind A kind to check.
76 * @returns {boolean} `true` if the kind is allowed.
78 function isAllowed(kind) {
80 case "loop": return allowLoop;
81 case "switch": return allowSwitch;
82 default: return false;
87 * Checks whether a given name is a label of a loop or not.
88 * @param {string} label A name of a label to check.
89 * @returns {boolean} `true` if the name is a label of a loop.
91 function getKind(label) {
95 if (info.label === label) {
101 /* istanbul ignore next: syntax error */
105 //--------------------------------------------------------------------------
107 //--------------------------------------------------------------------------
110 LabeledStatement(node) {
112 label: node.label.name,
113 kind: getBodyKind(node.body),
118 "LabeledStatement:exit"(node) {
119 if (!isAllowed(scopeInfo.kind)) {
122 messageId: "unexpectedLabel"
126 scopeInfo = scopeInfo.upper;
129 BreakStatement(node) {
130 if (node.label && !isAllowed(getKind(node.label.name))) {
133 messageId: "unexpectedLabelInBreak"
138 ContinueStatement(node) {
139 if (node.label && !isAllowed(getKind(node.label.name))) {
142 messageId: "unexpectedLabelInContinue"