Skip to content

Workaround new trivia behavior in SwiftSyntax. #434

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

Merged
merged 1 commit into from
Oct 21, 2022
Merged
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
3 changes: 2 additions & 1 deletion Sources/SwiftFormat/Parsing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import Foundation
import SwiftDiagnostics
import SwiftFormatCore
import SwiftOperators
import SwiftParser
import SwiftSyntax
Expand Down Expand Up @@ -54,5 +55,5 @@ func parseAndEmitDiagnostics(
throw SwiftFormatError.fileContainsInvalidSyntax
}

return sourceFile
return restoringLegacyTriviaBehavior(sourceFile)
}
44 changes: 44 additions & 0 deletions Sources/SwiftFormatCore/LegacyTriviaBehavior.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import SwiftSyntax

/// Rewrites the trivia on tokens in the given source file to restore the legacy trivia behavior
/// before https://github.com/apple/swift-syntax/pull/985 was merged.
///
/// Eventually we should get rid of this and update the core formatting code to adjust to the new
/// behavior, but this workaround lets us keep the current implementation without larger changes.
public func restoringLegacyTriviaBehavior(_ sourceFile: SourceFileSyntax) -> SourceFileSyntax {
return LegacyTriviaBehaviorRewriter().visit(sourceFile).as(SourceFileSyntax.self)!
}

private final class LegacyTriviaBehaviorRewriter: SyntaxRewriter {
/// Trivia that was extracted from the trailing trivia of a token to be prepended to the leading
/// trivia of the next token.
private var pendingLeadingTrivia: Trivia?

override func visit(_ token: TokenSyntax) -> TokenSyntax {
var token = token
if let pendingLeadingTrivia = pendingLeadingTrivia {
token = token.withLeadingTrivia(pendingLeadingTrivia + token.leadingTrivia)
self.pendingLeadingTrivia = nil
}
if token.nextToken != nil,
let firstIndexToMove = token.trailingTrivia.firstIndex(where: shouldTriviaPieceBeMoved)
{
pendingLeadingTrivia = Trivia(pieces: Array(token.trailingTrivia[firstIndexToMove...]))
token =
token.withTrailingTrivia(Trivia(pieces: Array(token.trailingTrivia[..<firstIndexToMove])))
}
return token
}
}

/// Returns a value indicating whether the given trivia piece should be moved from a token's
/// trailing trivia to the leading trivia of the following token to restore the legacy trivia
/// behavior.
private func shouldTriviaPieceBeMoved(_ piece: TriviaPiece) -> Bool {
switch piece {
case .spaces, .tabs, .unexpectedText:
return false
default:
return true
}
}
15 changes: 12 additions & 3 deletions Sources/SwiftFormatPrettyPrint/TokenStreamCreator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -1249,6 +1249,15 @@ fileprivate final class TokenStreamCreator: SyntaxVisitor {
return .visitChildren
}

override func visit(_ node: MacroExpansionExprSyntax) -> SyntaxVisitorContinueKind {
arrangeFunctionCallArgumentList(
node.argumentList,
leftDelimiter: node.leftParen,
rightDelimiter: node.rightParen,
forcesBreakBeforeRightDelimiter: false)
return .visitChildren
}

override func visit(_ node: ParameterClauseSyntax) -> SyntaxVisitorContinueKind {
// Prioritize keeping ") throws -> <return_type>" together. We can only do this if the function
// has arguments.
Expand Down Expand Up @@ -3595,11 +3604,11 @@ class CommentMovingRewriter: SyntaxRewriter {
return super.visit(node)
}

override func visit(_ token: TokenSyntax) -> Syntax {
override func visit(_ token: TokenSyntax) -> TokenSyntax {
if let rewrittenTrivia = rewriteTokenTriviaMap[token] {
return Syntax(token.withLeadingTrivia(rewrittenTrivia))
return token.withLeadingTrivia(rewrittenTrivia)
}
return Syntax(token)
return token
}

override func visit(_ node: InfixOperatorExprSyntax) -> ExprSyntax {
Expand Down
8 changes: 4 additions & 4 deletions Sources/SwiftFormatRules/ReplaceTrivia.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@ fileprivate final class ReplaceTrivia: SyntaxRewriter {
self.trailingTrivia = trailingTrivia
}

override func visit(_ token: TokenSyntax) -> Syntax {
guard token == self.token else { return Syntax(token) }
let newNode = token.withLeadingTrivia(leadingTrivia ?? token.leadingTrivia)
override func visit(_ token: TokenSyntax) -> TokenSyntax {
guard token == self.token else { return token }
return token
.withLeadingTrivia(leadingTrivia ?? token.leadingTrivia)
.withTrailingTrivia(trailingTrivia ?? token.trailingTrivia)
return Syntax(newNode)
}
}

Expand Down
5 changes: 3 additions & 2 deletions Tests/SwiftFormatPrettyPrintTests/PrettyPrintTestCase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,9 @@ class PrettyPrintTestCase: DiagnosingTestCase {
) -> String? {
// Ignore folding errors for unrecognized operators so that we fallback to a reasonable default.
let sourceFileSyntax =
OperatorTable.standardOperators.foldAll(Parser.parse(source: source)) { _ in }
.as(SourceFileSyntax.self)!
restoringLegacyTriviaBehavior(
OperatorTable.standardOperators.foldAll(Parser.parse(source: source)) { _ in }
.as(SourceFileSyntax.self)!)
let context = makeContext(sourceFileSyntax: sourceFileSyntax, configuration: configuration)
let printer = PrettyPrinter(
context: context,
Expand Down
4 changes: 2 additions & 2 deletions Tests/SwiftFormatRulesTests/LintOrFormatRuleTestCase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class LintOrFormatRuleTestCase: DiagnosingTestCase {
file: StaticString = #file,
line: UInt = #line
) {
let sourceFileSyntax = Parser.parse(source: input)
let sourceFileSyntax = restoringLegacyTriviaBehavior(Parser.parse(source: input))

// Force the rule to be enabled while we test it.
var configuration = Configuration()
Expand Down Expand Up @@ -56,7 +56,7 @@ class LintOrFormatRuleTestCase: DiagnosingTestCase {
file: StaticString = #file,
line: UInt = #line
) {
let sourceFileSyntax = Parser.parse(source: input)
let sourceFileSyntax = restoringLegacyTriviaBehavior(Parser.parse(source: input))

// Force the rule to be enabled while we test it.
var configuration = configuration ?? Configuration()
Expand Down