Skip to content

Commit

Permalink
Adopt Rintaro's improved implementation of comment/#sourceLocation re…
Browse files Browse the repository at this point in the history
…moval
  • Loading branch information
DougGregor committed Sep 6, 2024
1 parent a3e1604 commit 740199b
Showing 1 changed file with 17 additions and 21 deletions.
38 changes: 17 additions & 21 deletions Sources/SwiftIfConfig/ActiveSyntaxRewriter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -443,33 +443,29 @@ extension IfConfigDeclSyntax {
}
}

/// Syntax visitor that writes out a syntax tree without comments or #sourceLocations.
fileprivate class DescriptionWithoutCommentsAndSourceLocationsVisitor: SyntaxVisitor {
var result: String = ""
override func visit(_ token: TokenSyntax) -> SyntaxVisitorContinueKind {
token.leadingTrivia.writeWithoutComments(to: &result)
token.text.write(to: &result)
token.trailingTrivia.writeWithoutComments(to: &result)
return .skipChildren
}
override func visit(_ node: PoundSourceLocationSyntax) -> SyntaxVisitorContinueKind {
return .skipChildren
}
}

extension SyntaxProtocol {
// Produce the source code for this syntax node with all of the comments
// and #sourceLocations removed. Each comment will be replaced with either
// a newline or a space, depending on whether the comment involved a newline.
@_spi(Compiler)
public var descriptionWithoutCommentsAndSourceLocations: String {
var result = ""
var skipUntilRParen = false
for token in tokens(viewMode: .sourceAccurate) {
// Skip #sourceLocation(...).
if token.tokenKind == .poundSourceLocation {
skipUntilRParen = true
continue
}

if skipUntilRParen {
if token.tokenKind == .rightParen {
skipUntilRParen = false
}
continue
}

token.leadingTrivia.writeWithoutComments(to: &result)
token.text.write(to: &result)
token.trailingTrivia.writeWithoutComments(to: &result)
}
return result
let visitor = DescriptionWithoutCommentsAndSourceLocationsVisitor(viewMode: .sourceAccurate)
visitor.walk(self)
return visitor.result
}
}

Expand Down

0 comments on commit 740199b

Please sign in to comment.