Skip to content

Commit f9b2ab9

Browse files
committed
OrderedImports: Fix trivia placement for trailing comments.
Trailing comments were being appended to the next token's leading trivia instead of staying as trailing trivia; I forgot to make this adjustment when removing the legacy trivia workaround. Interestingly, this didn't surface as a problem in either the `OrderedImports` rule's unit tests or the pretty printer unit tests. Only the interaction between the two would surface the error.
1 parent ec39c44 commit f9b2ab9

File tree

1 file changed

+9
-11
lines changed

1 file changed

+9
-11
lines changed

Sources/SwiftFormat/Rules/OrderedImports.swift

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -342,20 +342,18 @@ fileprivate func generateLines(codeBlockItemList: CodeBlockItemListSyntax, conte
342342
/// replacing the trivia appropriately to ensure comments appear in the right location.
343343
fileprivate func convertToCodeBlockItems(lines: [Line]) -> [CodeBlockItemSyntax] {
344344
var output: [CodeBlockItemSyntax] = []
345-
var triviaBuffer: [TriviaPiece] = []
345+
var pendingLeadingTrivia: [TriviaPiece] = []
346346

347347
for line in lines {
348-
triviaBuffer += line.leadingTrivia
348+
pendingLeadingTrivia += line.leadingTrivia
349349

350350
func append(codeBlockItem: CodeBlockItemSyntax) {
351-
// Comments and newlines are always located in the leading trivia of an AST node, so we need
352-
// not deal with trailing trivia.
353351
var codeBlockItem = codeBlockItem
354-
codeBlockItem.leadingTrivia = Trivia(pieces: triviaBuffer)
352+
codeBlockItem.leadingTrivia = Trivia(pieces: pendingLeadingTrivia)
353+
codeBlockItem.trailingTrivia = Trivia(pieces: line.trailingTrivia)
355354
output.append(codeBlockItem)
356355

357-
triviaBuffer = []
358-
triviaBuffer += line.trailingTrivia
356+
pendingLeadingTrivia = []
359357
}
360358

361359
if let syntaxNode = line.syntaxNode {
@@ -367,11 +365,11 @@ fileprivate func convertToCodeBlockItems(lines: [Line]) -> [CodeBlockItemSyntax]
367365
}
368366
}
369367

370-
// Merge multiple newlines together into a single trivia piece by updating it's N value.
371-
if let lastPiece = triviaBuffer.last, case .newlines(let N) = lastPiece {
372-
triviaBuffer[triviaBuffer.endIndex - 1] = TriviaPiece.newlines(N + 1)
368+
// Merge multiple newlines together into a single trivia piece by updating its count.
369+
if let lastPiece = pendingLeadingTrivia.last, case .newlines(let count) = lastPiece {
370+
pendingLeadingTrivia[pendingLeadingTrivia.endIndex - 1] = .newlines(count + 1)
373371
} else {
374-
triviaBuffer.append(TriviaPiece.newlines(1))
372+
pendingLeadingTrivia.append(.newlines(1))
375373
}
376374
}
377375

0 commit comments

Comments
 (0)