class
Noir::TreeSitter::Query
- Noir::TreeSitter::Query
- Reference
- Object
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.crConstructors
Instance Method Summary
-
#close
Free the underlying TSQuery.
-
#each_match(node : LibTreeSitter::TSNode, source_text : String, & : Hash(String, LibTreeSitter::TSNode) -> )
Runs the query against
nodeand yields oneHash(String, TSNode)per match. -
#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. - #finalize
Constructor Detail
Instance Method Detail
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.
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.