Skip to content

Ensure newline after trailing line comments to prevent formatting issues #1015

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
9 changes: 8 additions & 1 deletion Sources/SwiftFormat/PrettyPrint/PrettyPrint.swift
Original file line number Diff line number Diff line change
Expand Up @@ -434,7 +434,14 @@ public class PrettyPrinter {
mustBreak = true
}

let suppressBreaking = isBreakingSuppressed && !overrideBreakingSuppressed
let previousToken = idx > 0 ? tokens[idx - 1] : nil
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure if checking the previous token in this way is the right approach 🤔

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 {
Expand Down
38 changes: 38 additions & 0 deletions Tests/SwiftFormatTests/PrettyPrint/AttributeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -623,4 +623,42 @@ final class AttributeTests: PrettyPrintTestCase {

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

func testAttributesWithComment() {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I considered moving the test case to CommentTests, but it felt more appropriate to keep it where it is 🤔

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)
}
}
Loading