Skip to content

Commit 6c906b0

Browse files
committed
[BuilderTransform] Explicitly disallow empty case statements in switch
1 parent 0cac079 commit 6c906b0

File tree

2 files changed

+25
-0
lines changed

2 files changed

+25
-0
lines changed

lib/Sema/BuilderTransform.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -759,6 +759,18 @@ class BuilderClosureVisitor
759759
}
760760

761761
VarDecl *visitCaseStmt(CaseStmt *caseStmt, Expr *subjectExpr) {
762+
auto *body = caseStmt->getBody();
763+
764+
// Explicitly disallow `case` statements with empty bodies
765+
// since that helps to diagnose other issues with switch
766+
// statements by excluding invalid cases.
767+
if (auto *BS = dyn_cast<BraceStmt>(body)) {
768+
if (BS->getNumElements() == 0) {
769+
hadError = true;
770+
return nullptr;
771+
}
772+
}
773+
762774
// If needed, generate constraints for everything in the case statement.
763775
if (cs) {
764776
auto locator = cs->getConstraintLocator(

test/Constraints/function_builder_diags.swift

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -589,4 +589,17 @@ struct MyView {
589589
switch Optional.some(1) { // expected-error {{'switch' statement body must have at least one 'case' or 'default' block; do you want to add a default case?}}
590590
}
591591
}
592+
593+
@TupleBuilder var invalidSwitchOne: some P {
594+
switch Optional.some(1) {
595+
case . // expected-error {{expected ':' after 'case'}}
596+
} // expected-error {{expected identifier after '.' expression}}
597+
}
598+
599+
@TupleBuilder var invalidSwitchMultiple: some P {
600+
switch Optional.some(1) {
601+
case .none: // expected-error {{'case' label in a 'switch' should have at least one executable statement}}
602+
case . // expected-error {{expected ':' after 'case'}}
603+
} // expected-error {{expected identifier after '.' expression}}
604+
}
592605
}

0 commit comments

Comments
 (0)