Skip to content

Commit b5b62af

Browse files
authored
Merge pull request #499 from stackotter/issue-473
Fix fatal error caused by switch cases without any statements (#473)
2 parents 4b7b315 + a0801d9 commit b5b62af

File tree

2 files changed

+50
-3
lines changed

2 files changed

+50
-3
lines changed

Sources/SwiftFormatPrettyPrint/TokenStreamCreator.swift

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -718,13 +718,23 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
718718
after(node.unknownAttr?.lastToken, tokens: .space)
719719
after(node.label.lastToken, tokens: .break(.reset, size: 0), .break(.open), .open)
720720

721-
// If switch/case labels were configured to be indented, insert an extra `close` break after the
722-
// case body to match the `open` break above
721+
// If switch/case labels were configured to be indented, insert an extra `close` break after
722+
// the case body to match the `open` break above
723723
var afterLastTokenTokens: [Token] = [.break(.close, size: 0), .close]
724724
if config.indentSwitchCaseLabels {
725725
afterLastTokenTokens.append(.break(.close, size: 0))
726726
}
727-
after(node.lastToken, tokens: afterLastTokenTokens)
727+
728+
// If the case contains statements, add the closing tokens after the last token of the case.
729+
// Otherwise, add the closing tokens before the next case (or the end of the switch) to have the
730+
// same effect. If instead the opening and closing tokens were omitted completely in the absence
731+
// of statements, comments within the empty case would be incorrectly indented to the same level
732+
// as the case label.
733+
if node.label.lastToken != node.lastToken {
734+
after(node.lastToken, tokens: afterLastTokenTokens)
735+
} else {
736+
before(node.nextToken, tokens: afterLastTokenTokens)
737+
}
728738

729739
return .visitChildren
730740
}

Tests/SwiftFormatPrettyPrintTests/SwitchStmtTests.swift

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,43 @@ final class SwitchStmtTests: PrettyPrintTestCase {
7878
assertPrettyPrintEqual(input: input, expected: expected, linelength: 35)
7979
}
8080

81+
func testSwitchEmptyCases() {
82+
let input =
83+
"""
84+
switch a {
85+
case b:
86+
default:
87+
print("Not b")
88+
}
89+
90+
switch a {
91+
case b:
92+
// Comment but no statements
93+
default:
94+
print("Not b")
95+
}
96+
"""
97+
98+
let expected =
99+
"""
100+
switch a {
101+
case b:
102+
default:
103+
print("Not b")
104+
}
105+
106+
switch a {
107+
case b:
108+
// Comment but no statements
109+
default:
110+
print("Not b")
111+
}
112+
113+
"""
114+
115+
assertPrettyPrintEqual(input: input, expected: expected, linelength: 35)
116+
}
117+
81118
func testSwitchCompoundCases() {
82119
let input =
83120
"""

0 commit comments

Comments
 (0)