Skip to main content

Module pattern

Module pattern 

Source
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 ?? $DEFAULT

compiles to

  ((binary_expression
     left: (member_expression object: (_) @SRC (optional_chain) property: (_) @KEY)
     "??"
     right: (_) @DEFAULT) @__match)

§How it works

  1. Each $VAR is replaced with a unique placeholder identifier so the snippet parses as ordinary code in the target grammar.
  2. 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.
  3. 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 (_) @VAR wildcard capture.
  4. Repeated metavariables unify: the second and later occurrences get helper captures plus an (#eq? …) predicate so $X … $X only matches when both holes carry identical text.

§Typed placeholders ($VAR:kind, #2839)

A metavariable may carry a syntactic-class constraint so it matches only nodes of a given kind (rust-analyzer SSR $x:expr):

  $FN($ARG:identifier)   // matches `f(x)`, not `f(g())`
  $X:expression          // matches any expression-position node

:kind is either a small semantic alias (expr/expression, stmt/statement, ty/type, ident/identifier) resolved to the grammar’s supertype, or an exact tree-sitter node kind. The constraint lowers a (_) @VAR wildcard to (kind) @VAR, so it narrows what binds. A constraint that names no kind in the target grammar is a compile error (the alias supertypes exist only in some grammars — e.g. expression in TypeScript/JS/Python but not Rust/Go, where exact kinds are used instead).

Variadic $$$ holes are not yet supported (tracked for the relational tier, #2833); they compile to a clear error.

Structs§

CompiledPattern
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 pattern snippet for language into a tree-sitter query.