Skip to content
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
11 changes: 11 additions & 0 deletions Sources/SwiftFormatPrettyPrint/TokenStreamCreator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,17 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
before(node.leftBrace, tokens: .break(.reset))
after(node.leftBrace, tokens: .close)

// An if-configuration clause around a switch-case encloses the case's node, so an
// if-configuration clause requires a break here in order to be allowed on a new line.
for ifConfigDecl in node.cases.filter({ $0.is(IfConfigDeclSyntax.self) }) {
if config.indentSwitchCaseLabels {
before(ifConfigDecl.firstToken, tokens: .break(.open))
after(ifConfigDecl.lastToken, tokens: .break(.close, size: 0))
} else {
before(ifConfigDecl.firstToken, tokens: .break(.same))
}
}

let newlines: NewlineBehavior =
areBracesCompletelyEmpty(node, contentsKeyPath: \.cases) ? .elective : .soft
before(node.rightBrace, tokens: .break(.same, size: 0, newlines: newlines))
Expand Down
95 changes: 95 additions & 0 deletions Tests/SwiftFormatPrettyPrintTests/SwitchStmtTests.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import SwiftFormatConfiguration

final class SwitchStmtTests: PrettyPrintTestCase {
func testBasicSwitch() {
let input =
Expand Down Expand Up @@ -332,4 +334,97 @@ final class SwitchStmtTests: PrettyPrintTestCase {

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

func testConditionalCases() {
let input =
"""
switch foo {
#if CONDITION_A
case bar:
callForBar()
#endif
case baz:
callForBaz()
}
switch foo2 {
case bar2:
callForBar()
#if CONDITION_B
case baz2:
callForBaz()
#endif
}
"""

let expected =
"""
switch foo {
#if CONDITION_A
case bar:
callForBar()
#endif
case baz:
callForBaz()
}
switch foo2 {
case bar2:
callForBar()
#if CONDITION_B
case baz2:
callForBaz()
#endif
}

"""

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

func testConditionalCasesIndenting() {
let input =
"""
switch foo {
#if CONDITION_A
case bar:
callForBar()
#endif
case baz:
callForBaz()
}
switch foo2 {
case bar2:
callForBar()
#if CONDITION_B
case baz2:
callForBaz()
#endif
}
"""

let expected =
"""
switch foo {
#if CONDITION_A
case bar:
callForBar()
#endif
case baz:
callForBaz()
}
switch foo2 {
case bar2:
callForBar()
#if CONDITION_B
case baz2:
callForBaz()
#endif
}

"""

var configuration = Configuration()
configuration.indentSwitchCaseLabels = true
assertPrettyPrintEqual(
input: input, expected: expected, linelength: 40, configuration: configuration)
}
}