Use Query to define patterns in a syntax tree using a query language. To execute the query, use a QueryCursor.
There are two ways to retrieve results:
QueryCursor.captures(node): Returns a dictionary where keys are capture names and values are lists of nodes. This is useful for getting all nodes tagged with a specific name.QueryCursor.matches(node): Returns a list of matches. Each match is a tuple containing the match index and a dictionary of captures. This is preferred when captures within a query are related (e.g., a function name and its body) and you want to process them as a single unit.
query = Query(
PY_LANGUAGE,
"""
(function_definition
name: (identifier) @function.def
body: (block) @function.block)
"""
)
query_cursor = QueryCursor(query)
# Get all captures
captures = query_cursor.captures(tree.root_node)
# captures['function.def'] -> [node, ...]
# Get grouped matches
matches = query_cursor.matches(tree.root_node)
# matches[0][1]['function.def'] -> [node, ...]