Skip to content

Add SyntaxProtocol.token(at:) to find the token at an absolute position #1031

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 27, 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
19 changes: 19 additions & 0 deletions Sources/SwiftSyntax/Syntax.swift
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,25 @@ public extension SyntaxProtocol {
return nil
}

/// Find the syntax token at the given absolute position within this
/// syntax node or any of its children.
func token(at position: AbsolutePosition) -> TokenSyntax? {
// If the position isn't within this node at all, return early.
guard position >= self.position && position < self.endPosition else {
return nil
}

// If we are a token syntax, that's it!
if let token = Syntax(self).as(TokenSyntax.self) {
return token
}

// Otherwise, it must be one of our children.
return children(viewMode: .sourceAccurate).lazy.compactMap { child in
child.token(at: position)
}.first
}

/// The absolute position of the starting point of this node. If the first token
/// is with leading trivia, the position points to the start of the leading
/// trivia.
Expand Down
37 changes: 37 additions & 0 deletions Tests/SwiftParserTest/AbsolutePositionTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@

//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import XCTest
import SwiftSyntax
import SwiftParser
import _SwiftSyntaxTestSupport

public class AbsolutePositionTests: XCTestCase {
public func testTokenAt() {
let source =
"""
func f(a: Int) { }
"""

let parsed = Parser.parse(source: source)
for expectedToken in parsed.tokens(viewMode: .sourceAccurate) {
let tokenStart = expectedToken.position.utf8Offset
let tokenEnd = expectedToken.endPosition.utf8Offset
for offset in tokenStart..<tokenEnd {
let token = parsed.token(at: AbsolutePosition(utf8Offset: offset))
XCTAssertEqual(token, expectedToken)
}
}
}
}