query {treesitter}R Documentation

Queries

Description

query() lets you specify a query source string for use with query_captures() and query_matches(). The source string is written in a way that is somewhat similar to the idea of capture groups in regular expressions. You write out a pattern that matches a node in a tree, and then you "capture" parts of that pattern with ⁠@name⁠ tags. The captures are the values returned by query_captures() and query_matches(). There are also a series of predicates that can be used to further refine the query. Those are described in the query_matches() help page.

Read the tree-sitter documentation to learn more about the query syntax.

Usage

query(language, source)

Arguments

language

⁠[tree_sitter_language]⁠

A language.

source

⁠[string]⁠

A query source string.

Value

A query.

Examples


# This query looks for binary operators where the left hand side is an
# identifier named `fn`, and the right hand side is a function definition.
# The operator can be `<-` or `=` (technically it can also be things like
# `+` as well in this example).
source <- '(binary_operator
  lhs: (identifier) @lhs
  operator: _ @operator
  rhs: (function_definition) @rhs
  (#eq? @lhs "fn")
)'

language <- treesitter.r::language()

query <- query(language, source)

text <- "
  fn <- function() {}
  fn2 <- function() {}
  fn <- 5
  fn = function(a, b, c) { a + b + c }
"
parser <- parser(language)
tree <- parser_parse(parser, text)
node <- tree_root_node(tree)

query_matches(query, node)


[Package treesitter version 0.1.0 Index]