Skip to content

Commit cf99151

Browse files
committed
[SourceLocationConverter] Use SyntaxVisitor to visit tokens
1 parent 5e288d6 commit cf99151

File tree

1 file changed

+22
-13
lines changed

1 file changed

+22
-13
lines changed

Sources/SwiftSyntax/SourceLocation.swift

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -512,20 +512,29 @@ extension SyntaxProtocol {
512512
fileprivate func computeLines(
513513
tree: Syntax
514514
) -> ([AbsolutePosition], AbsolutePosition) {
515-
var lines: [AbsolutePosition] = []
516-
// First line starts from the beginning.
517-
lines.append(.startOfFile)
518-
var position: AbsolutePosition = .startOfFile
519-
let addLine = { (lineLength: SourceLength) in
520-
position += lineLength
521-
lines.append(position)
522-
}
523-
var curPrefix: SourceLength = .zero
524-
for token in tree.tokens(viewMode: .sourceAccurate) {
525-
curPrefix = token.forEachLineLength(prefix: curPrefix, body: addLine)
515+
class ComputeLineVisitor: SyntaxVisitor {
516+
var lines: [AbsolutePosition] = [.startOfFile]
517+
var position: AbsolutePosition = .startOfFile
518+
var curPrefix: SourceLength = .zero
519+
520+
init() {
521+
super.init(viewMode: .sourceAccurate)
522+
}
523+
524+
private func addLine(_ lineLength: SourceLength) {
525+
position += lineLength
526+
lines.append(position)
527+
}
528+
529+
override func visit(_ token: TokenSyntax) -> SyntaxVisitorContinueKind {
530+
curPrefix = token.forEachLineLength(prefix: curPrefix, body: addLine)
531+
return .skipChildren
532+
}
526533
}
527-
position += curPrefix
528-
return (lines, position)
534+
535+
let visitor = ComputeLineVisitor()
536+
visitor.walk(tree)
537+
return (visitor.lines, visitor.position + visitor.curPrefix)
529538
}
530539

531540
fileprivate func computeLines(_ source: SyntaxText) -> ([AbsolutePosition], AbsolutePosition) {

0 commit comments

Comments
 (0)