Skip to content

Commit 3f0ed45

Browse files
authored
Merge pull request #497 from bnbarham/empty-trivia
Update to non-optional leading/trailingTrivia swift-syntax API
2 parents 89a0b6f + 2910f57 commit 3f0ed45

7 files changed

+25
-38
lines changed

Sources/SwiftFormatCore/SyntaxProtocol+Convenience.swift

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ extension SyntaxProtocol {
2525
/// be returned.
2626
/// - Returns: The absolute position of the trivia piece.
2727
public func position(ofLeadingTriviaAt index: Trivia.Index) -> AbsolutePosition {
28-
let leadingTrivia = self.leadingTrivia ?? []
2928
guard leadingTrivia.indices.contains(index) else {
3029
preconditionFailure("Index was out of bounds in the node's leading trivia.")
3130
}

Sources/SwiftFormatPrettyPrint/TokenStreamCreator.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -876,7 +876,7 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
876876
// The node's content is either a `DictionaryElementListSyntax` or a `TokenSyntax` for a colon
877877
// token (for an empty dictionary).
878878
if !(node.content.as(DictionaryElementListSyntax.self)?.isEmpty ?? true)
879-
|| node.content.leadingTrivia?.numberOfComments ?? 0 > 0
879+
|| node.content.leadingTrivia.numberOfComments > 0
880880
|| node.rightSquare.leadingTrivia.numberOfComments > 0
881881
{
882882
after(node.leftSquare, tokens: .break(.open, size: 0), .open)
@@ -2161,7 +2161,7 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
21612161
appendToken(.syntax(segmentText))
21622162
}
21632163

2164-
if node.trailingTrivia?.containsBackslashes == true {
2164+
if node.trailingTrivia.containsBackslashes {
21652165
// Segments with trailing backslashes won't end with a literal newline; the backslash is
21662166
// considered trivia. To preserve the original text and wrapping, we need to manually render
21672167
// the backslash and a break into the token stream.

Sources/SwiftFormatRules/NoAssignmentInExpressions.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,15 +60,15 @@ public final class NoAssignmentInExpressions: SyntaxFormatRule {
6060
semicolon: nil
6161
)
6262
.with(\.leadingTrivia,
63-
(returnStmt.leadingTrivia ?? []) + (assignmentExpr.leadingTrivia ?? []))
63+
(returnStmt.leadingTrivia) + (assignmentExpr.leadingTrivia))
6464
.with(\.trailingTrivia, []))
6565
newItems.append(
6666
CodeBlockItemSyntax(
6767
item: .stmt(StmtSyntax(returnStmt.with(\.expression, nil))),
6868
semicolon: nil
6969
)
7070
.with(\.leadingTrivia, [.newlines(1)])
71-
.with(\.trailingTrivia, returnStmt.trailingTrivia?.withoutLeadingSpaces() ?? []))
71+
.with(\.trailingTrivia, returnStmt.trailingTrivia.withoutLeadingSpaces()))
7272

7373
default:
7474
newItems.append(newItem)

Sources/SwiftFormatRules/NoCasesWithOnlyFallthrough.swift

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -139,13 +139,11 @@ public final class NoCasesWithOnlyFallthrough: SyntaxFormatRule {
139139
}
140140

141141
// Check for any comments that are adjacent to the case or fallthrough statement.
142-
if let leadingTrivia = switchCase.leadingTrivia,
143-
leadingTrivia.drop(while: { !$0.isNewline }).contains(where: { $0.isComment })
142+
if switchCase.leadingTrivia.drop(while: { !$0.isNewline }).contains(where: { $0.isComment })
144143
{
145144
return false
146145
}
147-
if let leadingTrivia = onlyStatement.leadingTrivia,
148-
leadingTrivia.drop(while: { !$0.isNewline }).contains(where: { $0.isComment })
146+
if onlyStatement.leadingTrivia.drop(while: { !$0.isNewline }).contains(where: { $0.isComment })
149147
{
150148
return false
151149
}
@@ -194,13 +192,7 @@ public final class NoCasesWithOnlyFallthrough: SyntaxFormatRule {
194192

195193
// Only the first violation case can have displaced trivia, because any non-whitespace
196194
// trivia in the other violation cases would've prevented collapsing.
197-
if let displacedLeadingTrivia = cases.first!.leadingTrivia?.withoutLastLine() {
198-
let existingLeadingTrivia = newCase.leadingTrivia ?? []
199-
let mergedLeadingTrivia = displacedLeadingTrivia + existingLeadingTrivia
200-
return newCase.with(\.leadingTrivia, mergedLeadingTrivia)
201-
} else {
202-
return newCase
203-
}
195+
return newCase.with(\.leadingTrivia, cases.first!.leadingTrivia.withoutLastLine() + newCase.leadingTrivia)
204196
}
205197
}
206198

Sources/SwiftFormatRules/OrderedImports.swift

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -298,23 +298,20 @@ fileprivate func generateLines(codeBlockItemList: CodeBlockItemListSyntax, conte
298298
}
299299

300300
for block in codeBlockItemList {
301-
302-
if let leadingTrivia = block.leadingTrivia {
303-
afterNewline = false
304-
305-
for piece in leadingTrivia {
306-
switch piece {
307-
// Create new Line objects when we encounter newlines.
308-
case .newlines(let N):
309-
for _ in 0..<N {
310-
appendNewLine()
311-
}
312-
default:
313-
if afterNewline || isFirstBlock {
314-
currentLine.leadingTrivia.append(piece) // This will be a standalone comment.
315-
} else {
316-
currentLine.trailingTrivia.append(piece) // This will be a trailing line comment.
317-
}
301+
afterNewline = false
302+
303+
for piece in block.leadingTrivia {
304+
switch piece {
305+
// Create new Line objects when we encounter newlines.
306+
case .newlines(let N):
307+
for _ in 0..<N {
308+
appendNewLine()
309+
}
310+
default:
311+
if afterNewline || isFirstBlock {
312+
currentLine.leadingTrivia.append(piece) // This will be a standalone comment.
313+
} else {
314+
currentLine.trailingTrivia.append(piece) // This will be a trailing line comment.
318315
}
319316
}
320317
}
@@ -491,8 +488,7 @@ fileprivate class Line {
491488
// description includes all leading and trailing trivia. It would be unusual to have any
492489
// non-whitespace trivia on the components of the import. Trim off the leading trivia, where
493490
// comments could be, and trim whitespace that might be after the import.
494-
let leadingText = importDecl.leadingTrivia?.reduce(into: "") { $1.write(to: &$0) } ?? ""
495-
return importDecl.description.dropFirst(leadingText.count)
491+
return importDecl.with(\.leadingTrivia, []).description
496492
.trimmingCharacters(in: .whitespacesAndNewlines)
497493
}
498494

Sources/SwiftFormatRules/UseShorthandTypeNames.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -338,7 +338,7 @@ public final class UseShorthandTypeNames: SyntaxFormatRule {
338338
elementList: tupleExprElementList,
339339
rightParen: TokenSyntax.rightParenToken())
340340
wrappedTypeExpr = ExprSyntax(tupleExpr)
341-
} else if let leadingTrivia = leadingTrivia {
341+
} else {
342342
// Otherwise, the argument type can safely become an optional by simply appending a "?". If
343343
// we were given leading trivia from another node (for example, from `Optional` when
344344
// converting a long-form to short-form), we need to transfer it over. By doing so, something

Sources/SwiftFormatRules/UseTripleSlashForDocumentationComments.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,13 +73,13 @@ public final class UseTripleSlashForDocumentationComments: SyntaxFormatRule {
7373
/// a docLineComment.
7474
private func convertDocBlockCommentToDocLineComment(_ decl: DeclSyntax) -> DeclSyntax {
7575
guard let commentText = decl.docComment else { return decl }
76-
guard let declLeadingTrivia = decl.leadingTrivia else { return decl }
76+
7777
let docComments = commentText.components(separatedBy: "\n")
7878
var pieces = [TriviaPiece]()
7979

8080
// Ensures the documentation comment is a docLineComment.
8181
var hasFoundDocComment = false
82-
for piece in declLeadingTrivia.reversed() {
82+
for piece in decl.leadingTrivia.reversed() {
8383
if case .docBlockComment(_) = piece, !hasFoundDocComment {
8484
hasFoundDocComment = true
8585
diagnose(.avoidDocBlockComment, on: decl)

0 commit comments

Comments
 (0)