Expand description
The pattern compiler: a code snippet with metavariable holes → a tree-sitter query.
This is the atomic-tier pattern form. The idea (from ast-grep) is to
let rule authors write a snippet of real code with $VAR holes
instead of hand-authoring a tree-sitter S-expression query:
$SRC?.$KEY ?? $DEFAULTcompiles to
((binary_expression
left: (member_expression object: (_) @SRC (optional_chain) property: (_) @KEY)
"??"
right: (_) @DEFAULT) @__match)§How it works
- Each
$VARis replaced with a unique placeholder identifier so the snippet parses as ordinary code in the target grammar. - We parse the substituted snippet — bare, then in a per-language wrapper context (e.g. a function body) when the fragment is not a valid compilation unit — and locate the snippet’s own subtree by its byte range in the parsed source.
- We walk that subtree and mirror it into a query: every named child is
emitted with its field name, every anonymous token (operators,
keywords, punctuation) is emitted as a quoted literal so the structure
is matched precisely, and every placeholder becomes a
(_) @VARwildcard capture. - Repeated metavariables unify: the second and later occurrences get
helper captures plus an
(#eq? …)predicate so$X … $Xonly matches when both holes carry identical text.
Variadic $$$ holes are not yet supported (tracked for the relational
tier, #2833); they compile to a clear error.
Structs§
- Compiled
Pattern - A snippet pattern compiled to a tree-sitter query string.
Constants§
- ROOT_
CAPTURE - The capture name bound to the whole matched pattern, used for range
extraction. Chosen to not collide with a user metavar (which are
uppercase by convention and never start with
__).
Functions§
- compile_
pattern - Compile a
patternsnippet forlanguageinto a tree-sitter query.