File tree Expand file tree Collapse file tree
Sources/SwiftFormat/Rules
Tests/SwiftFormatTests/Rules Expand file tree Collapse file tree Original file line number Diff line number Diff 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
Original file line number Diff line number Diff 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,
You can’t perform that action at this time.
0 commit comments