Document query anchor operator (#771)

This was taken more or less directly from @maxbrunsfeld's PR comments
in https://github.com/tree-sitter/tree-sitter/pull/549. 🎩
This commit is contained in:
Patrick Thomson 2020-10-23 14:34:56 -04:00
parent 5caa83e020
commit b5d20f07b6

View file

@ -585,6 +585,38 @@ For example, this pattern would match any node inside a call:
(call (_) @call.inner)
```
#### Anchor Nodes
The anchor operator, `.`, is used to constrain the ways in which child patterns are matched. It has different behaviors depending on where it's placed inside a query.
When `.` is placed before the _first_ child within a parent pattern, the child will only match when it is the first named node in the parent. For example, the below pattern matches a given `array` node at most once, assigning the `@the-element` capture to the first `identifier` node in the parent `array`:
```
(array . (identifier) @the-element)
```
Were this anchor operator elided, the pattern would match once for every identifier in the array, with `@the-element` bound to each matched identifier.
Similarly, an anchor placed after a pattern's _last_ child will cause that child pattern to only match nodes that are the last named child of their parent. The below pattern matches only nodes that are the last named child within a `block`.
```
(block (_) @last-expression .)
```
Finally, an anchor _between_ two child patterns will cause the patterns to only match nodes that are immediate siblings. The pattern below, given a long dotted name like `a.b.c.d`, will only match pairs of consecutive identifiers: `a, b`, `b, c`, and `c, d`.
```
(dotted_name
(identifier) @prev-id
.
(identifier) @next-id)
```
Were the anchor elided, non-consecutive pairs like `a, c` and `b, d` would be matched.
The restrictions placed on a pattern by an anchor operator ignore anonymous nodes.
#### Predicates
You can also specify arbitrary metadata and conditions associed with a pattern by adding _predicate_ S-expressions anywhere within your pattern. Predicate S-expressions start with a _predicate name_ beginning with a `#` character. After that, they can contain an arbitrary number of `@`-prefixed capture names or strings.