Skip to content

Introduce Efficient Node Localization in Syntax Tree for Unit Tests #2251

Open
@Matejkob

Description

@Matejkob

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:

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

/// 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions