From 868a7cd2411ad87eb34e7040d90a48524ad1b9ad Mon Sep 17 00:00:00 2001 From: ttozzi Date: Sun, 11 May 2025 16:07:16 +0900 Subject: [PATCH] Ensure newline after trailing line comments to prevent formatting issues --- .../SwiftFormat/PrettyPrint/PrettyPrint.swift | 9 ++++- .../PrettyPrint/AttributeTests.swift | 38 +++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/Sources/SwiftFormat/PrettyPrint/PrettyPrint.swift b/Sources/SwiftFormat/PrettyPrint/PrettyPrint.swift index b8700014f..dca170cac 100644 --- a/Sources/SwiftFormat/PrettyPrint/PrettyPrint.swift +++ b/Sources/SwiftFormat/PrettyPrint/PrettyPrint.swift @@ -434,7 +434,14 @@ public class PrettyPrinter { mustBreak = true } - let suppressBreaking = isBreakingSuppressed && !overrideBreakingSuppressed + let previousToken = idx > 0 ? tokens[idx - 1] : nil + let isAfterLineComment: Bool + if case .comment(let comment, _) = previousToken { + isAfterLineComment = comment.kind == .line || comment.kind == .docLine + } else { + isAfterLineComment = false + } + let suppressBreaking = !isAfterLineComment && isBreakingSuppressed && !overrideBreakingSuppressed if !suppressBreaking && (!canFit(length) || mustBreak) { currentLineIsContinuation = isContinuationIfBreakFires if case .escaped = newline { diff --git a/Tests/SwiftFormatTests/PrettyPrint/AttributeTests.swift b/Tests/SwiftFormatTests/PrettyPrint/AttributeTests.swift index 4419d6f05..020d81611 100644 --- a/Tests/SwiftFormatTests/PrettyPrint/AttributeTests.swift +++ b/Tests/SwiftFormatTests/PrettyPrint/AttributeTests.swift @@ -623,4 +623,42 @@ final class AttributeTests: PrettyPrintTestCase { assertPrettyPrintEqual(input: input, expected: expected, linelength: 45) } + + func testAttributesWithComment() { + let input = + """ + @foo // comment + @bar + import Baz + + """ + let expected = + """ + @foo // comment + @bar import Baz + + """ + + assertPrettyPrintEqual(input: input, expected: expected, linelength: 45) + } + + func testAttributesWithLineAndBlockComments() { + let input = + """ + @foo // comment + @bar /* comment */ + @zoo // comment + import Baz + + """ + let expected = + """ + @foo // comment + @bar /* comment */ @zoo // comment + import Baz + + """ + + assertPrettyPrintEqual(input: input, expected: expected, linelength: 45) + } }