Skip to content

Commit 5a4dee5

Browse files
authored
Merge pull request #21810 from github/tausbn/yeast-forward-scan-queries
yeast: Align query semantics more closely with tree-sitter
2 parents fdef477 + af6e921 commit 5a4dee5

6 files changed

Lines changed: 293 additions & 53 deletions

File tree

shared/yeast-macros/src/lib.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,21 @@ mod parse;
99
///
1010
/// ```text
1111
/// (_) - match any named node (skips unnamed tokens)
12+
/// _ - match any node, named or unnamed
1213
/// (kind) - match a named node of the given kind
1314
/// ("literal") - match an unnamed token by its text
15+
/// "literal" - shorthand for `("literal")`
1416
/// (kind field: (pattern)) - match with named field
15-
/// (kind (pat) (pat)...) - match unnamed children (after all fields)
17+
/// (kind field: _) - bare `_` and bare literals work in field position too
18+
/// (kind (pat) (pat)...) - match unnamed children
1619
/// (pattern) @capture - capture the matched node
20+
/// "literal" @capture - capture an unnamed token
21+
/// _ @capture - capture any node
1722
/// (pattern)* @capture - capture each repeated match
1823
/// (pattern)? - zero or one
1924
/// ```
25+
///
26+
/// Named fields and bare child patterns may be intermixed in any order.
2027
#[proc_macro]
2128
pub fn query(input: TokenStream) -> TokenStream {
2229
let input2: TokenStream2 = input.into();

shared/yeast-macros/src/parse.rs

Lines changed: 35 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@ fn parse_query_node(tokens: &mut Tokens) -> Result<TokenStream> {
3838
}
3939
}
4040

41-
/// Parse a query atom: `(kind fields...)` or `(kind fields... bare_children...)`.
41+
/// Parse a query atom: a parenthesized node, a bare `_` (any node), or a
42+
/// bare string literal (unnamed token).
4243
/// Does not handle `@capture` — that's handled by the caller as a postfix.
4344
fn parse_query_atom(tokens: &mut Tokens) -> Result<TokenStream> {
4445
match tokens.peek() {
@@ -58,9 +59,17 @@ fn parse_query_atom(tokens: &mut Tokens) -> Result<TokenStream> {
5859
}
5960
Ok(result)
6061
}
62+
Some(TokenTree::Ident(id)) if *id == "_" => {
63+
tokens.next();
64+
Ok(quote! { yeast::query::QueryNode::Any { match_unnamed: true } })
65+
}
66+
Some(TokenTree::Literal(_)) => {
67+
let lit = expect_literal(tokens)?;
68+
Ok(quote! { yeast::query::QueryNode::UnnamedNode { kind: #lit } })
69+
}
6170
Some(tok) => Err(syn::Error::new_spanned(
6271
tok.clone(),
63-
"expected `(` in query; use `(_) @name` to capture a wildcard",
72+
"expected `(`, `_`, or string literal in query",
6473
)),
6574
}
6675
}
@@ -74,7 +83,7 @@ fn parse_query_node_inner(tokens: &mut Tokens) -> Result<TokenStream> {
7483
)),
7584
Some(TokenTree::Ident(id)) if *id == "_" => {
7685
tokens.next();
77-
Ok(quote! { yeast::query::QueryNode::Any() })
86+
Ok(quote! { yeast::query::QueryNode::Any { match_unnamed: false } })
7887
}
7988
Some(TokenTree::Literal(_)) => {
8089
let lit = expect_literal(tokens)?;
@@ -98,11 +107,14 @@ fn parse_query_node_inner(tokens: &mut Tokens) -> Result<TokenStream> {
98107
}
99108
}
100109

101-
/// Parse zero or more field specifications and trailing bare patterns.
102-
/// Named fields: `name: pattern` or `name*: (list...)`.
103-
/// Bare patterns (no field name) become implicit `child` field entries.
110+
/// Parse zero or more field specifications and bare patterns.
111+
/// Named fields: `name: pattern`. Bare patterns (no field name) become
112+
/// implicit `child` field entries. Named fields and bare patterns may
113+
/// appear in any order; bare patterns are accumulated and emitted as a
114+
/// single `("child", ...)` entry.
104115
fn parse_query_fields(tokens: &mut Tokens) -> Result<Vec<TokenStream>> {
105116
let mut fields = Vec::new();
117+
let mut bare_children: Vec<TokenStream> = Vec::new();
106118
while tokens.peek().is_some() {
107119
if peek_is_field(tokens) {
108120
let field_name = expect_ident(tokens, "expected field name")?;
@@ -115,16 +127,21 @@ fn parse_query_fields(tokens: &mut Tokens) -> Result<Vec<TokenStream>> {
115127
(#field_str, vec![yeast::query::QueryListElem::SingleNode(#child)])
116128
});
117129
} else {
118-
// Bare patterns — collect as implicit `child` field
130+
// Bare patterns — accumulate into the implicit `child` field.
131+
// We don't break here, so we can interleave with named fields.
119132
let elems = parse_query_list(tokens)?;
120-
if !elems.is_empty() {
121-
fields.push(quote! {
122-
("child", vec![#(#elems),*])
123-
});
133+
if elems.is_empty() {
134+
// Nothing more we can parse at this level.
135+
break;
124136
}
125-
break;
137+
bare_children.extend(elems);
126138
}
127139
}
140+
if !bare_children.is_empty() {
141+
fields.push(quote! {
142+
("child", vec![#(#bare_children),*])
143+
});
144+
}
128145
Ok(fields)
129146
}
130147

@@ -178,10 +195,11 @@ fn parse_query_list(tokens: &mut Tokens) -> Result<Vec<TokenStream>> {
178195
continue;
179196
}
180197

181-
// Check for string literal (unnamed node)
198+
// Check for string literal (unnamed node), optionally followed by @capture
182199
if peek_is_literal(tokens) {
183200
let lit = expect_literal(tokens)?;
184201
let node = quote! { yeast::query::QueryNode::UnnamedNode { kind: #lit } };
202+
let node = maybe_wrap_capture(tokens, node)?;
185203
let elem = maybe_wrap_repetition(
186204
tokens,
187205
quote! {
@@ -192,10 +210,12 @@ fn parse_query_list(tokens: &mut Tokens) -> Result<Vec<TokenStream>> {
192210
continue;
193211
}
194212

195-
// Check for bare _ (wildcard), possibly followed by @capture
213+
// Check for bare `_` (any node, named or unnamed), possibly followed by @capture.
214+
// Distinct from `(_)` which only matches named nodes — this matches
215+
// tree-sitter query semantics.
196216
if peek_is_underscore(tokens) {
197217
tokens.next();
198-
let node = quote! { yeast::query::QueryNode::Any() };
218+
let node = quote! { yeast::query::QueryNode::Any { match_unnamed: true } };
199219
let node = maybe_wrap_capture(tokens, node)?;
200220
let elem = maybe_wrap_repetition(
201221
tokens,

shared/yeast/doc/yeast.md

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -119,19 +119,40 @@ Captures bind matched nodes to names for use in the transform. A capture
119119
(identifier) @name // capture an identifier node
120120
(_) @value // capture any named node
121121
(identifier)* @items // capture each repeated match
122+
("=") @op // capture an unnamed token by its text
123+
"=" @op // shorthand for the line above
124+
_ @anything // capture any node, named or unnamed
122125
```
123126

124-
### Unnamed children
127+
### Named vs unnamed children
125128

126-
Patterns that appear after all named fields match unnamed (positional)
127-
children. Named node patterns like `(_)` automatically skip unnamed tokens
128-
(keywords, operators, punctuation), matching tree-sitter semantics:
129+
The two wildcard forms `(_)` and bare `_` differ:
130+
131+
- `(_)` matches only **named** nodes. When used as a positional pattern,
132+
unnamed children (keywords, operators, punctuation) are skipped over.
133+
- Bare `_` matches **any** node, named or unnamed, taking whatever is next
134+
in the child list.
135+
136+
Bare child patterns are matched **forward-scan**: each pattern advances
137+
through the iterator until it finds a child that matches, skipping
138+
non-matching children along the way. So `(foo ("baz"))` against a `foo`
139+
whose children are `[bar, baz]` succeeds — the matcher scans past `bar`
140+
and matches `baz`. The iterator advances as it goes, so subsequent
141+
patterns can never match children that appear earlier in source order
142+
than already-matched ones.
143+
144+
For named-only patterns (`(_)`, `(some_kind ...)`), the scan additionally
145+
skips past unnamed tokens without trying to match them, since they can
146+
never match anyway.
147+
148+
Anchors (`.`) for forcing immediate adjacency, like in tree-sitter
149+
queries, are not supported.
129150

130151
```rust
131152
(for
132-
pattern: (_) @pat // named field
133-
value: (in (_) @val) // "in" token is skipped automatically
134-
body: (do (_)* @body) // "do" and "end" tokens skipped
153+
pattern: (_) @pat // named field, captures any named node
154+
value: (in (_) @val) // "in" wrapper is a named node here
155+
body: (do (_)* @body) // "do" and "end" tokens skipped by (_)
135156
)
136157
```
137158

shared/yeast/src/query.rs

Lines changed: 30 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,13 @@ use crate::{captures::Captures, Ast, Id};
22

33
#[derive(Debug, Clone)]
44
pub enum QueryNode {
5-
Any(),
5+
/// A wildcard. With `match_unnamed = false` (the default for `(_)`),
6+
/// only matches named nodes when used positionally — unnamed children
7+
/// are skipped over. With `match_unnamed = true` (for bare `_`), the
8+
/// wildcard consumes whatever the next child is, named or unnamed.
9+
Any {
10+
match_unnamed: bool,
11+
},
612
Node {
713
kind: &'static str,
814
children: Vec<(&'static str, Vec<QueryListElem>)>,
@@ -24,7 +30,7 @@ impl QueryNode {
2430
QueryNode::Node { kind, .. } => Some(kind),
2531
QueryNode::UnnamedNode { kind } => Some(kind),
2632
QueryNode::Capture { node, .. } => node.root_kind(),
27-
QueryNode::Any() => None,
33+
QueryNode::Any { .. } => None,
2834
}
2935
}
3036
}
@@ -51,7 +57,7 @@ impl QueryNode {
5157
/// semantics where `(_)` only matches named nodes.
5258
fn matches_named_only(&self) -> bool {
5359
match self {
54-
QueryNode::Any() => true,
60+
QueryNode::Any { match_unnamed } => !match_unnamed,
5561
QueryNode::Node { .. } => true,
5662
QueryNode::UnnamedNode { .. } => false,
5763
QueryNode::Capture { node, .. } => node.matches_named_only(),
@@ -60,7 +66,7 @@ impl QueryNode {
6066

6167
pub fn do_match(&self, ast: &Ast, node: Id, matches: &mut Captures) -> Result<bool, String> {
6268
match self {
63-
QueryNode::Any() => Ok(true),
69+
QueryNode::Any { .. } => Ok(true),
6470
QueryNode::Node { kind, children } => {
6571
let node = ast.get_node(node).unwrap();
6672
let target_kind = ast
@@ -161,25 +167,28 @@ impl QueryListElem {
161167
}
162168
}
163169
QueryListElem::SingleNode(sub_query) => {
164-
if sub_query.matches_named_only() {
165-
// Skip unnamed children, matching tree-sitter semantics
166-
// where (_) only matches named nodes.
167-
loop {
168-
match remaining_children.next() {
169-
Some(child) => {
170-
let node = ast.get_node(child).unwrap();
171-
if node.is_named() {
172-
return sub_query.do_match(ast, child, matches);
173-
}
174-
// Skip unnamed child, continue to next
175-
}
176-
None => return Ok(false),
170+
// Forward-scan semantics: advance through the iterator until
171+
// we find a child that matches `sub_query`. Skip ahead past
172+
// unnamed children when the sub-query is named-only (so they
173+
// can never match anyway). On a match attempt that fails,
174+
// restore the captures so partial captures from a complex
175+
// sub-query don't leak.
176+
let skip_unnamed = sub_query.matches_named_only();
177+
loop {
178+
let Some(child) = remaining_children.next() else {
179+
return Ok(false);
180+
};
181+
if skip_unnamed {
182+
let node = ast.get_node(child).unwrap();
183+
if !node.is_named() {
184+
continue;
177185
}
178186
}
179-
} else if let Some(child) = remaining_children.next() {
180-
sub_query.do_match(ast, child, matches)
181-
} else {
182-
Ok(false)
187+
let snapshot = matches.clone();
188+
if sub_query.do_match(ast, child, matches)? {
189+
return Ok(true);
190+
}
191+
*matches = snapshot;
183192
}
184193
}
185194
}

shared/yeast/src/schema.rs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,10 @@ impl Schema {
6161
}
6262
}
6363
// Import all node kind names, preserving tree-sitter's IDs.
64-
// Track named and unnamed variants separately.
65-
// For named kinds, use the canonical ID from id_for_node_kind(name, true)
66-
// since some languages have multiple IDs for the same named kind.
64+
// Track named and unnamed variants separately. For both named and
65+
// unnamed kinds, use the canonical ID from id_for_node_kind, since
66+
// some languages have multiple IDs for the same name (e.g., the
67+
// reserved error token at ID 0 may share a name with a real token).
6768
for id in 0..language.node_kind_count() as u16 {
6869
if let Some(name) = language.node_kind_for_id(id) {
6970
if !name.is_empty() {
@@ -75,12 +76,13 @@ impl Schema {
7576
schema.kind_names.insert(canonical_id, name);
7677
}
7778
} else {
78-
// For unnamed kinds, only insert if we don't already have one
79-
// (some languages have multiple unnamed IDs for the same text)
80-
schema
81-
.unnamed_kind_ids
82-
.entry(name.to_string())
83-
.or_insert(id);
79+
let canonical_id = language.id_for_node_kind(name, false);
80+
if canonical_id != 0 && !schema.unnamed_kind_ids.contains_key(name) {
81+
schema
82+
.unnamed_kind_ids
83+
.insert(name.to_string(), canonical_id);
84+
schema.kind_names.insert(canonical_id, name);
85+
}
8486
}
8587
// Always track the name for any ID we encounter
8688
schema.kind_names.entry(id).or_insert(name);

0 commit comments

Comments
 (0)