Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix fatal error caused by switch cases without any statements (#473) #499

Merged
merged 1 commit into from
Apr 10, 2023
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
16 changes: 13 additions & 3 deletions Sources/SwiftFormatPrettyPrint/TokenStreamCreator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -718,13 +718,23 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
after(node.unknownAttr?.lastToken, tokens: .space)
after(node.label.lastToken, tokens: .break(.reset, size: 0), .break(.open), .open)

// If switch/case labels were configured to be indented, insert an extra `close` break after the
// case body to match the `open` break above
// If switch/case labels were configured to be indented, insert an extra `close` break after
// the case body to match the `open` break above
var afterLastTokenTokens: [Token] = [.break(.close, size: 0), .close]
if config.indentSwitchCaseLabels {
afterLastTokenTokens.append(.break(.close, size: 0))
}
after(node.lastToken, tokens: afterLastTokenTokens)

// If the case contains statements, add the closing tokens after the last token of the case.
// Otherwise, add the closing tokens before the next case (or the end of the switch) to have the
// same effect. If instead the opening and closing tokens were omitted completely in the absence
// of statements, comments within the empty case would be incorrectly indented to the same level
// as the case label.
if node.label.lastToken != node.lastToken {
after(node.lastToken, tokens: afterLastTokenTokens)
} else {
before(node.nextToken, tokens: afterLastTokenTokens)
}

return .visitChildren
}
Expand Down
37 changes: 37 additions & 0 deletions Tests/SwiftFormatPrettyPrintTests/SwitchStmtTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,43 @@ final class SwitchStmtTests: PrettyPrintTestCase {
assertPrettyPrintEqual(input: input, expected: expected, linelength: 35)
}

func testSwitchEmptyCases() {
let input =
"""
switch a {
case b:
default:
print("Not b")
}

switch a {
case b:
// Comment but no statements
default:
print("Not b")
}
"""

let expected =
"""
switch a {
case b:
default:
print("Not b")
}

switch a {
case b:
// Comment but no statements
default:
print("Not b")
}

"""

assertPrettyPrintEqual(input: input, expected: expected, linelength: 35)
}

func testSwitchCompoundCases() {
let input =
"""
Expand Down