Skip to content

Commit 4fd796f

Browse files
author
David Brunow
committed
Improve implementation
1 parent d7b390f commit 4fd796f

File tree

1 file changed

+22
-4
lines changed

1 file changed

+22
-4
lines changed

Sources/SwiftFormatPrettyPrint/TokenStreamCreator.swift

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1309,14 +1309,15 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
13091309

13101310
if isNestedInPostfixIfConfig(node: Syntax(node)) {
13111311
let breakToken: Token
1312-
let previousToken = node.parent?.parent?.previousToken
1312+
let currentIfConfigDecl = node.parent?.parent?.as(IfConfigDeclSyntax.self)
1313+
let tokenBeforeCurrentIfConfigDecl = currentIfConfigDecl?.previousToken
13131314

1314-
if previousToken?.parent?.parent?.parent?.parent?.syntaxNodeType == IfConfigClauseSyntax.self ||
1315-
previousToken?.text == "}" {
1315+
if isNestedInIfConfig(Syntax(tokenBeforeCurrentIfConfigDecl)) ||
1316+
tokenBeforeCurrentIfConfigDecl?.text == "}" {
13161317
breakToken = .break(.reset)
13171318
} else {
13181319
breakToken = .break
1319-
before(node.parent?.parent?.as(IfConfigDeclSyntax.self)?.poundEndif, tokens: [.break])
1320+
before(currentIfConfigDecl?.poundEndif, tokens: [.break])
13201321
}
13211322

13221323
before(
@@ -3525,6 +3526,9 @@ private func isNestedInPostfixIfConfig(node: Syntax) -> Bool {
35253526
var this: Syntax? = node
35263527

35273528
while this?.parent != nil {
3529+
// This guard handles the situation where a type with its own modifiers
3530+
// is nested inside of an if config. That type should not count as being
3531+
// in a postfix if config because its entire body is inside the if config.
35283532
if this?.is(TupleExprElementSyntax.self) == true {
35293533
return false
35303534
}
@@ -3540,6 +3544,20 @@ private func isNestedInPostfixIfConfig(node: Syntax) -> Bool {
35403544
return false
35413545
}
35423546

3547+
private func isNestedInIfConfig(node: Syntax) -> Bool {
3548+
var this: Syntax? = node
3549+
3550+
while this?.parent != nil {
3551+
if this?.is(IfConfigClauseSyntax.self) == true {
3552+
return true
3553+
}
3554+
3555+
this = this?.parent
3556+
}
3557+
3558+
return false
3559+
}
3560+
35433561
extension Syntax {
35443562
/// Creates a pretty-printable token stream for the provided Syntax node.
35453563
func makeTokenStream(configuration: Configuration, operatorContext: OperatorContext) -> [Token] {

0 commit comments

Comments
 (0)