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",
24 url
: "https://eslint.org/docs/rules/no-labels"
40 additionalProperties
: false
45 unexpectedLabel
: "Unexpected labeled statement.",
46 unexpectedLabelInBreak
: "Unexpected label in break statement.",
47 unexpectedLabelInContinue
: "Unexpected label in continue statement."
52 const options
= context
.options
[0];
53 const allowLoop
= options
&& options
.allowLoop
;
54 const allowSwitch
= options
&& options
.allowSwitch
;
58 * Gets the kind of a given node.
59 * @param {ASTNode} node A node to get.
60 * @returns {string} The kind of the node.
62 function getBodyKind(node
) {
63 if (astUtils
.isLoop(node
)) {
66 if (node
.type
=== "SwitchStatement") {
73 * Checks whether the label of a given kind is allowed or not.
74 * @param {string} kind A kind to check.
75 * @returns {boolean} `true` if the kind is allowed.
77 function isAllowed(kind
) {
79 case "loop": return allowLoop
;
80 case "switch": return allowSwitch
;
81 default: return false;
86 * Checks whether a given name is a label of a loop or not.
87 * @param {string} label A name of a label to check.
88 * @returns {boolean} `true` if the name is a label of a loop.
90 function getKind(label
) {
94 if (info
.label
=== label
) {
100 /* istanbul ignore next: syntax error */
104 //--------------------------------------------------------------------------
106 //--------------------------------------------------------------------------
109 LabeledStatement(node
) {
111 label
: node
.label
.name
,
112 kind
: getBodyKind(node
.body
),
117 "LabeledStatement:exit"(node
) {
118 if (!isAllowed(scopeInfo
.kind
)) {
121 messageId
: "unexpectedLabel"
125 scopeInfo
= scopeInfo
.upper
;
128 BreakStatement(node
) {
129 if (node
.label
&& !isAllowed(getKind(node
.label
.name
))) {
132 messageId
: "unexpectedLabelInBreak"
137 ContinueStatement(node
) {
138 if (node
.label
&& !isAllowed(getKind(node
.label
.name
))) {
141 messageId
: "unexpectedLabelInContinue"