swiftlang / swiftlang/swift-syntax

Introduce Efficient Node Localization in Syntax Tree for Unit Tests

Open
#2,251 2 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
Swift
Stars
3.7k
Forks
553
Avg merge
5d 13h
Merged PRs (30d)
16

Description

### Description

Currently, there is no mechanism to efficiently refer to specific node in syntax tree for the need of unit test. For example to create `Diagnostic.highlights` and attach them to a specific node in a syntax tree within diagnostic formatters unit tests. The absence of such a feature makes it cumbersome to identify and highlight syntax nodes for diagnostic or verification purposes.

### [Proposed Solution by @ahoppen](https://github.com/apple/swift-syntax/pull/2238#discussion_r1337731784):

Introduce a `NodeLocator` struct to facilitate the process. Below is a proposed implementation idea:

```swift
/// Refers to the first node in a syntax tree after `marker` that satisfies `match`.
///
/// For example, if you have
/// ```swift
/// var x: Int
/// 1️⃣func foo() {}
/// ```
///
/// Then `NodeLocator(marker: "1️⃣")` refers to the `CodeBlockItemSyntax` that
/// contains the function declaration and
/// `NodeLocator(marker: "1️⃣", matches: { $0.is(FunctionDeclSyntax.self) })`
/// refers to the function within.
struct NodeLocator {
let marker: String
let match: (Syntax) -> Bool = { _ in true }

func findNode(in tree: Syntax) -> Syntax? {
// TODO: Implement
}
}
```

> [!note]
> Before starting implementation, let's discuss this approach here.

This feature could be a significant step towards enabling more precise and easier-to-write unit tests, especially those involving diagnostic highlights.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.