Skip to content

Commit 840e43a

Browse files
committed
Fixes incorrect formatting when attributes contain line comments by preserving linebreaks
1 parent e70ab31 commit 840e43a

File tree

2 files changed

+47
-2
lines changed

2 files changed

+47
-2
lines changed

Sources/SwiftFormat/PrettyPrint/TokenStreamCreator.swift

+9-2
Original file line numberDiff line numberDiff line change
@@ -3073,12 +3073,19 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
30733073
}
30743074
}
30753075
} else {
3076-
after(element.lastToken(viewMode: .sourceAccurate), tokens: .break(.same, newlines: behavior))
3076+
let lastToken = element.lastToken(viewMode: .sourceAccurate)
3077+
if lastToken?.trailingTrivia.hasLineComment == true {
3078+
after(element.lastToken(viewMode: .sourceAccurate), tokens: .break(.same, newlines: .hard))
3079+
} else {
3080+
after(element.lastToken(viewMode: .sourceAccurate), tokens: .break(.same, newlines: behavior))
3081+
}
30773082
}
30783083
}
30793084
}
30803085
var afterAttributeTokens = [Token.close]
3081-
if !suppressFinalBreak {
3086+
if attributes.lastToken(viewMode: .sourceAccurate)?.trailingTrivia.hasLineComment == true {
3087+
afterAttributeTokens.append(.break(.same, newlines: .hard))
3088+
} else if !suppressFinalBreak {
30823089
afterAttributeTokens.append(.break(.same, newlines: behavior))
30833090
}
30843091
after(attributes.lastToken(viewMode: .sourceAccurate), tokens: afterAttributeTokens)

Tests/SwiftFormatTests/PrettyPrint/AttributeTests.swift

+38
Original file line numberDiff line numberDiff line change
@@ -623,4 +623,42 @@ final class AttributeTests: PrettyPrintTestCase {
623623

624624
assertPrettyPrintEqual(input: input, expected: expected, linelength: 45)
625625
}
626+
627+
func testAttributesWithComment() {
628+
let input =
629+
"""
630+
@foo // comment
631+
@bar
632+
import Baz
633+
634+
"""
635+
let expected =
636+
"""
637+
@foo // comment
638+
@bar import Baz
639+
640+
"""
641+
642+
assertPrettyPrintEqual(input: input, expected: expected, linelength: 45)
643+
}
644+
645+
func testAttributesWithLineAndBlockComments() {
646+
let input =
647+
"""
648+
@foo // comment
649+
@bar /* comment */
650+
@zoo // comment
651+
import Baz
652+
653+
"""
654+
let expected =
655+
"""
656+
@foo // comment
657+
@bar /* comment */ @zoo // comment
658+
import Baz
659+
660+
"""
661+
662+
assertPrettyPrintEqual(input: input, expected: expected, linelength: 45)
663+
}
626664
}

0 commit comments

Comments
 (0)