Skip to content

Commit be62588

Browse files
authored
Merge pull request #802 from kkebo/main
[pull] wasm32-wasi from main
2 parents ce77b24 + e0b1f28 commit be62588

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

Sources/SwiftFormat/Rules/OrderedImports.swift

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -476,6 +476,23 @@ private func convertToCodeBlockItems(lines: [Line]) -> [CodeBlockItemSyntax] {
476476
}
477477
}
478478

479+
// If trivia accumulated past the last syntax node (e.g. a trailing comment
480+
// that import reordering left behind), attach it to the last code block
481+
// item's trailing trivia so it is preserved in the output instead of being
482+
// silently dropped. The loop above accumulates an artificial newline after
483+
// every iteration to separate the current line from the next one — those
484+
// trailing newlines are meaningless when there is no following line and are
485+
// stripped before the attachment.
486+
while let last = pendingLeadingTrivia.last, case .newlines = last {
487+
pendingLeadingTrivia.removeLast()
488+
}
489+
if Trivia(pieces: pendingLeadingTrivia).hasAnyComments, !output.isEmpty {
490+
let lastIndex = output.index(before: output.endIndex)
491+
var lastItem = output[lastIndex]
492+
lastItem.trailingTrivia = Trivia(pieces: lastItem.trailingTrivia.pieces + pendingLeadingTrivia)
493+
output[lastIndex] = lastItem
494+
}
495+
479496
return output
480497
}
481498

Tests/SwiftFormatTests/Rules/OrderedImportsTests.swift

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -288,6 +288,30 @@ final class OrderedImportsTests: LintOrFormatRuleTestCase {
288288
)
289289
}
290290

291+
func testCommentBetweenImportGroupsIsPreserved() {
292+
// A free-standing comment, separated from the surrounding imports by
293+
// blank lines, was previously dropped entirely when the rule ran the
294+
// import group through its line/trivia normalisation. See
295+
// https://github.com/swiftlang/swift-format/issues/1080.
296+
assertFormatting(
297+
OrderedImports.self,
298+
input: """
299+
import A
300+
301+
// Comment
302+
303+
import B
304+
""",
305+
expected: """
306+
import A
307+
import B
308+
309+
// Comment
310+
""",
311+
findings: []
312+
)
313+
}
314+
291315
func testMultipleCodeBlocksPerLine() {
292316
assertFormatting(
293317
OrderedImports.self,

0 commit comments

Comments
 (0)