Treesitter query syntax to match the first child

36 Views Asked by At

I'm looking to write a treesitter query syntax https://tree-sitter.github.io/tree-sitter/using-parsers#query-syntax to match the first sibling.

This is my code.

if method_call
  [:meth_fields]
elsif true
  [:flag_fields]
elsif another_method_call
  [:another_meth_fields]
else
  [:default_fields]
end

And this is the generated tree.

program [0, 0] - [9, 0]
  if [0, 0] - [8, 3]
    condition: identifier [0, 3] - [0, 14]
    consequence: then [0, 14] - [1, 16]
      array [1, 2] - [1, 16]
        simple_symbol [1, 3] - [1, 15]
    alternative: elsif [2, 0] - [7, 19]
      condition: true [2, 6] - [2, 10]
      consequence: then [2, 10] - [3, 16]
        array [3, 2] - [3, 16]
          simple_symbol [3, 3] - [3, 15]
      alternative: elsif [4, 0] - [7, 19]
        condition: identifier [4, 6] - [4, 25]
        consequence: then [4, 25] - [5, 24]
          array [5, 2] - [5, 24]
            simple_symbol [5, 3] - [5, 23]
        alternative: else [6, 0] - [7, 19]
          array [7, 2] - [7, 19]
            simple_symbol [7, 3] - [7, 18]

When I try this query

(elsif 
  condition: (true)
)@elsif

It matches both the elsif's however I want to match the first occurrence. Current matches.

[
{
    "captureName": "elsif",
    "type": "elsif",
    "text": "elsif true\n  [:flag_fields]\nelsif true\n  [:another_flag_fields]\nelse\n  [:default_fields]",
    "startPosition": {
        "row": 4,
        "column": 0
    },
    "endPosition": {
        "row": 9,
        "column": 19
    }
},
{
    "captureName": "elsif",
    "type": "elsif",
    "text": "elsif true\n  [:another_flag_fields]\nelse\n  [:default_fields]",
    "startPosition": {
        "row": 6,
        "column": 0
    },
    "endPosition": {
        "row": 9,
        "column": 19
    }
}

]

From the documentation I can understand that using anchors is the way to go but I'm nota

0

There are 0 best solutions below