Skip to content
This repository has been archived by the owner on Mar 25, 2021. It is now read-only.

switch-final-break: don't fail for break statement with label #2914

Merged
merged 1 commit into from
Jun 16, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions src/rules/switchFinalBreakRule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* limitations under the License.
*/

import { endsControlFlow, isBlock, isCaseBlock } from "tsutils";
import { endsControlFlow, isBlock, isBreakStatement, isLabeledStatement, isSwitchStatement } from "tsutils";
import * as ts from "typescript";

import * as Lint from "../index";
Expand Down Expand Up @@ -58,14 +58,14 @@ interface Options {
function walk(ctx: Lint.WalkContext<Options>): void {
const { sourceFile, options: { always } } = ctx;
ts.forEachChild(sourceFile, function cb(node) {
if (isCaseBlock(node)) {
if (isSwitchStatement(node)) {
check(node);
}
ts.forEachChild(node, cb);
});

function check(node: ts.CaseBlock): void {
const clause = last(node.clauses);
function check(node: ts.SwitchStatement): void {
const clause = last(node.caseBlock.clauses);
if (clause === undefined) { return; }

if (always) {
Expand All @@ -79,7 +79,14 @@ function walk(ctx: Lint.WalkContext<Options>): void {
const block = clause.statements[0];
const statements = clause.statements.length === 1 && isBlock(block) ? block.statements : clause.statements;
const lastStatement = last(statements);
if (lastStatement !== undefined && lastStatement.kind === ts.SyntaxKind.BreakStatement) {
if (lastStatement !== undefined && isBreakStatement(lastStatement)) {
if (lastStatement.label !== undefined) {
const parent = node.parent!;
if (!isLabeledStatement(parent) || parent.label === lastStatement.label) {
// break jumps somewhere else, don't complain
return;
}
}
ctx.addFailureAtNode(lastStatement, Rule.FAILURE_STRING_NEVER);
}
}
Expand Down
21 changes: 21 additions & 0 deletions test/rules/switch-final-break/default/test.ts.lint
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,25 @@ switch (x) {
case 0:
}

outer: while (true) {
switch (x) {
case 0:
x++;
break;
default:
break outer;
}
}

outer2: while (true) {
inner: switch (x) {
case 0:
++x;
break;
default:
break inner;
~~~~~~~~~~~~ [0]
}
}

[0]: Final clause in 'switch' statement should not end with 'break;'.