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
47 const options = context.options[0];
48 const allowLoop = options && options.allowLoop;
49 const allowSwitch = options && options.allowSwitch;
53 * Gets the kind of a given node.
54 * @param {ASTNode} node A node to get.
55 * @returns {string} The kind of the node.
57 function getBodyKind(node) {
58 if (astUtils.isLoop(node)) {
61 if (node.type === "SwitchStatement") {
68 * Checks whether the label of a given kind is allowed or not.
69 * @param {string} kind A kind to check.
70 * @returns {boolean} `true` if the kind is allowed.
72 function isAllowed(kind) {
74 case "loop": return allowLoop;
75 case "switch": return allowSwitch;
76 default: return false;
81 * Checks whether a given name is a label of a loop or not.
82 * @param {string} label A name of a label to check.
83 * @returns {boolean} `true` if the name is a label of a loop.
85 function getKind(label) {
89 if (info.label === label) {
95 /* istanbul ignore next: syntax error */
99 //--------------------------------------------------------------------------
101 //--------------------------------------------------------------------------
104 LabeledStatement(node) {
106 label: node.label.name,
107 kind: getBodyKind(node.body),
112 "LabeledStatement:exit"(node) {
113 if (!isAllowed(scopeInfo.kind)) {
116 message: "Unexpected labeled statement."
120 scopeInfo = scopeInfo.upper;
123 BreakStatement(node) {
124 if (node.label && !isAllowed(getKind(node.label.name))) {
127 message: "Unexpected label in break statement."
132 ContinueStatement(node) {
133 if (node.label && !isAllowed(getKind(node.label.name))) {
136 message: "Unexpected label in continue statement."