Skip to content

Commit 868a7cd

Browse files
committed
Ensure newline after trailing line comments to prevent formatting issues
1 parent e70ab31 commit 868a7cd

File tree

2 files changed

+46
-1
lines changed

2 files changed

+46
-1
lines changed

Sources/SwiftFormat/PrettyPrint/PrettyPrint.swift

+8-1
Original file line numberDiff line numberDiff line change
@@ -434,7 +434,14 @@ public class PrettyPrinter {
434434
mustBreak = true
435435
}
436436

437-
let suppressBreaking = isBreakingSuppressed && !overrideBreakingSuppressed
437+
let previousToken = idx > 0 ? tokens[idx - 1] : nil
438+
let isAfterLineComment: Bool
439+
if case .comment(let comment, _) = previousToken {
440+
isAfterLineComment = comment.kind == .line || comment.kind == .docLine
441+
} else {
442+
isAfterLineComment = false
443+
}
444+
let suppressBreaking = !isAfterLineComment && isBreakingSuppressed && !overrideBreakingSuppressed
438445
if !suppressBreaking && (!canFit(length) || mustBreak) {
439446
currentLineIsContinuation = isContinuationIfBreakFires
440447
if case .escaped = newline {

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)