class Noir::TreeSitter::Query

Overview

Compiled tree-sitter query.

Queries are S-expression patterns that describe node shapes and capture nodes by @name. They let detectors declare the shape of a route registration call once instead of hand-walking the AST.

Example: match every @<router>.route(...) decorator in Python source and capture the router identifier and the path string.

query = Noir::TreeSitter::Query.new(
  LibTreeSitter.tree_sitter_python,
  <<-SCM
    (decorator
      (call
        function: (attribute
          object: (identifier) @router
          attribute: (identifier) @verb
          (#eq? @verb "route"))
        arguments: (argument_list
          (string (string_content) @path))))
  SCM
)
Noir::TreeSitter.parse_python(source) do |root|
  query.each_match(root) do |match|
    puts "#{Noir::TreeSitter.node_text(match["router"], source)} -> " \
         "#{Noir::TreeSitter.node_text(match["path"], source)}"
  end
end
query.close

Defined in:

ext/tree_sitter/tree_sitter.cr

Constructors

Instance Method Summary

Constructor Detail

def self.new(language : LibTreeSitter::TSLanguage, source : String) #

[View source]

Instance Method Detail

def close #

Free the underlying TSQuery. Safe to call multiple times; subsequent calls are no-ops.


[View source]
def each_match(node : LibTreeSitter::TSNode, source_text : String, & : Hash(String, LibTreeSitter::TSNode) -> ) #

Runs the query against node and yields one Hash(String, TSNode) per match. source_text is the string that was parsed to produce the tree, needed to resolve captured node text when evaluating predicates like #eq? / #match?. When a pattern captures the same name multiple times, the last match wins; use #each_match_raw for the full capture list.


[View source]
def each_match_raw(node : LibTreeSitter::TSNode, source_text : String, & : Int32, Array(Tuple(String, LibTreeSitter::TSNode)) -> ) #

Lower-level variant: yields (pattern_index, Array({capture_name, TSNode})) so callers can disambiguate multiple captures sharing a name, and know which pattern in a multi-pattern query matched.


[View source]
def finalize #

[View source]