Skip to content

Commit 0b57b92

Browse files
authored
Merge pull request #23292 from github/yeast/tweaks
Yeast: A few straightforward refactors
2 parents 4471041 + 95a4dba commit 0b57b92

7 files changed

Lines changed: 140 additions & 169 deletions

File tree

‎shared/yeast-macros/src/lower.rs‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -318,9 +318,9 @@ impl Pattern {
318318
vec![captured]
319319
} else {
320320
let repetition = match (cardinality.multiple, cardinality.required) {
321-
(true, false) => quote! { yeast::query::Rep::ZeroOrMore },
322-
(true, true) => quote! { yeast::query::Rep::OneOrMore },
323-
(false, false) => quote! { yeast::query::Rep::ZeroOrOne },
321+
(true, false) => quote! { yeast::query::Repetition::ZeroOrMore },
322+
(true, true) => quote! { yeast::query::Repetition::OneOrMore },
323+
(false, false) => quote! { yeast::query::Repetition::ZeroOrOne },
324324
(false, true) => unreachable!("single cardinality handled above"),
325325
};
326326
vec![quote! {
@@ -337,9 +337,9 @@ impl Pattern {
337337
} => {
338338
let children = pattern.lower_list();
339339
let repetition = match (cardinality.multiple, cardinality.required) {
340-
(true, false) => quote! { yeast::query::Rep::ZeroOrMore },
341-
(true, true) => quote! { yeast::query::Rep::OneOrMore },
342-
(false, false) => quote! { yeast::query::Rep::ZeroOrOne },
340+
(true, false) => quote! { yeast::query::Repetition::ZeroOrMore },
341+
(true, true) => quote! { yeast::query::Repetition::OneOrMore },
342+
(false, false) => quote! { yeast::query::Repetition::ZeroOrOne },
343343
(false, true) => unreachable!("single patterns are not wrapped as repeated"),
344344
};
345345
vec![quote! {

‎shared/yeast/doc/yeast.md‎

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -19,25 +19,25 @@ so that CodeQL queries only need to reason about the `.each` form.
1919
## Architecture
2020

2121
```
22-
Source code
23-
│
24-
▼
25-
┌──────────────┐
26-
│ tree-sitter │ Parse source into a concrete syntax tree
27-
│ parser │
28-
└──────┬───────┘
29-
│ tree_sitter::Tree
30-
▼
31-
┌──────────────┐
32-
│ YEAST │ Apply desugaring rules, producing a new AST
33-
│ Runner │
34-
└──────┬───────┘
35-
│ yeast::Ast
36-
▼
37-
┌──────────────┐
38-
│ TRAP │ Walk the (possibly rewritten) AST and emit TRAP tuples
39-
│ extractor │
40-
└──────────────┘
22+
Source code
23+
│
24+
▼
25+
┌──────────────┐
26+
│ tree-sitter │ Parse source into a concrete syntax tree
27+
│ parser │
28+
└──────┬───────┘
29+
│ tree_sitter::Tree
30+
▼
31+
┌──────────────┐
32+
│ YEAST │ Apply desugaring rules, producing a new AST
33+
│ Runner │
34+
└──────┬───────┘
35+
│ yeast::Ast
36+
▼
37+
┌──────────────┐
38+
│ TRAP │ Walk the (possibly rewritten) AST and emit TRAP tuples
39+
│ extractor │
40+
└──────────────┘
4141
```
4242

4343
The entry point is `extract()` in the shared tree-sitter extractor. When
@@ -699,11 +699,11 @@ iteration, computing intermediate values, or looping over captures —
699699
use the annotation form. It has three shapes distinguished by a suffix
700700
on the output-kind identifier:
701701

702-
| Syntax | Body must evaluate to | Meaning |
703-
|---------------------|-------------------------------------|--------------------------------|
704-
| `=> kind { ... }` | a single node id of `kind` | Emit exactly one node. |
705-
| `=> kind? { ... }` | an `Option` of a node id of `kind` | Emit 0 or 1 nodes (`None`/`Some`). |
706-
| `=> kind* { ... }` | an iterable of node ids of `kind` | Emit 0+ nodes; flattens into the enclosing splice slot. |
702+
| Syntax | Body must evaluate to | Meaning |
703+
| ------------------ | ---------------------------------- | ------------------------------------------------------- |
704+
| `=> kind { ... }` | a single node id of `kind` | Emit exactly one node. |
705+
| `=> kind? { ... }` | an `Option` of a node id of `kind` | Emit 0 or 1 nodes (`None`/`Some`). |
706+
| `=> kind* { ... }` | an iterable of node ids of `kind` | Emit 0+ nodes; flattens into the enclosing splice slot. |
707707

708708
The suffix mirrors the `?` / `*` markers used elsewhere in the schema
709709
DSL (see [`ast_types.yml`](../../../unified/extractor/ast_types.yml)):

‎shared/yeast/src/captures.rs‎

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,14 @@ use std::collections::{BTreeMap, BTreeSet};
22

33
use crate::{OutputId, TreeId};
44

5+
/// If `values` contains exactly one element, return it. Otherwise, return `None`.
6+
fn single_id<T: Copy>(values: &[T]) -> Option<T> {
7+
match values {
8+
[value] => Some(*value),
9+
_ => None,
10+
}
11+
}
12+
513
#[derive(Debug, Clone)]
614
pub struct Captures<Id: TreeId = crate::Id> {
715
captures: BTreeMap<&'static str, Vec<Id>>,
@@ -21,33 +29,27 @@ impl<Id: TreeId> Captures<Id> {
2129
}
2230

2331
pub fn get_var(&self, key: &str) -> Result<Id, String> {
24-
let ids = self.captures.get(key);
25-
if let Some(ids) = ids {
26-
if ids.len() == 1 {
27-
Ok(ids[0])
28-
} else {
29-
Err(format!(
30-
"Variable {} has {} matches, use * to allow repetition",
31-
key,
32-
ids.len()
33-
))
34-
}
35-
} else {
36-
Err(format!("No variable named {key}"))
37-
}
32+
let ids = self
33+
.captures
34+
.get(key)
35+
.ok_or_else(|| format!("No variable named {key}"))?;
36+
single_id(ids).ok_or_else(|| {
37+
format!(
38+
"Variable {key} has {} matches, use * to allow repetition",
39+
ids.len()
40+
)
41+
})
3842
}
3943

4044
/// Get all values of a capture variable (for repeated captures).
4145
pub fn get_all(&self, key: &str) -> Vec<Id> {
4246
self.captures.get(key).cloned().unwrap_or_default()
4347
}
4448

45-
/// Get an optional capture variable. Returns None if unmatched,
46-
/// Some(id) if matched exactly once.
49+
/// Get an optional capture variable. Returns `None` if unmatched,
50+
/// `Some(id)` if matched exactly once.
4751
pub fn get_opt(&self, key: &str) -> Option<Id> {
48-
self.captures
49-
.get(key)
50-
.and_then(|ids| (ids.len() == 1).then(|| ids[0]))
52+
self.captures.get(key).and_then(|ids| single_id(ids))
5153
}
5254

5355
pub fn insert(&mut self, key: &'static str, id: Id) {

‎shared/yeast/src/lib.rs‎

Lines changed: 26 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -550,26 +550,17 @@ impl<Id: TreeId> Iterator for ChildrenIter<'_, Id> {
550550
type Item = Id;
551551

552552
fn next(&mut self) -> Option<Self::Item> {
553-
match self.field_children.as_mut() {
554-
None => match self.field_order.next() {
555-
Some(field) => {
556-
self.current_field = Some(field);
557-
self.field_children = Some(self.fields[&field].iter());
558-
self.next()
559-
}
560-
None => None,
561-
},
562-
Some(children) => match children.next() {
563-
None => match self.field_order.next() {
564-
None => None,
565-
Some(field) => {
566-
self.current_field = Some(field);
567-
self.field_children = Some(self.fields[&field].iter());
568-
self.next()
569-
}
570-
},
571-
Some(child_id) => Some(*child_id),
572-
},
553+
loop {
554+
if let Some(child_id) = self
555+
.field_children
556+
.as_mut()
557+
.and_then(|children| children.next())
558+
{
559+
return Some(*child_id);
560+
}
561+
let field = self.field_order.next()?;
562+
self.current_field = Some(field);
563+
self.field_children = Some(self.fields[&field].iter());
573564
}
574565
}
575566
}
@@ -884,55 +875,11 @@ impl<Id: TreeId> Ast<Id> {
884875
}
885876

886877
fn union_source_range_of_children(&self, fields: &BTreeMap<FieldId, Vec<Id>>) -> Option<Range> {
887-
let mut start_byte: Option<usize> = None;
888-
let mut end_byte: Option<usize> = None;
889-
let mut start_point = Point { row: 0, column: 0 };
890-
let mut end_point = Point { row: 0, column: 0 };
891-
892-
for child_ids in fields.values() {
893-
for &child_id in child_ids {
894-
let Some(child) = self.get_node(child_id) else {
895-
continue;
896-
};
897-
let Some(child_range) = child.source_range() else {
898-
continue;
899-
};
900-
901-
match start_byte {
902-
None => {
903-
start_byte = Some(child_range.start_byte);
904-
start_point = child_range.start_point;
905-
}
906-
Some(current_start) if child_range.start_byte < current_start => {
907-
start_byte = Some(child_range.start_byte);
908-
start_point = child_range.start_point;
909-
}
910-
_ => {}
911-
}
912-
913-
match end_byte {
914-
None => {
915-
end_byte = Some(child_range.end_byte);
916-
end_point = child_range.end_point;
917-
}
918-
Some(current_end) if child_range.end_byte > current_end => {
919-
end_byte = Some(child_range.end_byte);
920-
end_point = child_range.end_point;
921-
}
922-
_ => {}
923-
}
924-
}
925-
}
926-
927-
match (start_byte, end_byte) {
928-
(Some(start_byte), Some(end_byte)) => Some(Range {
929-
start_byte,
930-
end_byte,
931-
start_point,
932-
end_point,
933-
}),
934-
_ => None,
935-
}
878+
fields
879+
.values()
880+
.flatten()
881+
.filter_map(|&id| self.get_node(id)?.source_range())
882+
.reduce(Range::union)
936883
}
937884

938885
pub fn create_named_token(&mut self, kind: &'static str, content: String) -> Id {
@@ -1008,13 +955,13 @@ impl<Id: TreeId> Ast<Id> {
1008955
}
1009956

1010957
pub fn id_for_node_kind(&self, kind: &str) -> Option<KindId> {
1011-
let id = self.schema.id_for_node_kind(kind).unwrap_or(0);
1012-
if id == 0 { None } else { Some(id) }
958+
self.schema.id_for_node_kind(kind).filter(|&id| id != 0)
1013959
}
1014960

1015961
pub fn id_for_unnamed_node_kind(&self, kind: &str) -> Option<KindId> {
1016-
let id = self.schema.id_for_unnamed_node_kind(kind).unwrap_or(0);
1017-
if id == 0 { None } else { Some(id) }
962+
self.schema
963+
.id_for_unnamed_node_kind(kind)
964+
.filter(|&id| id != 0)
1018965
}
1019966
}
1020967

@@ -1259,20 +1206,17 @@ impl<C> Rule<C> {
12591206
/// transform.
12601207
fn match_query(&self, ast: &Ast, node: Id) -> Option<Captures> {
12611208
let mut captures = Captures::new();
1262-
if !self.query.do_match(ast, node, &mut captures) {
1263-
return None;
1264-
}
1265-
Some(captures)
1209+
self.query
1210+
.do_match(ast, node, &mut captures)
1211+
.then_some(captures)
12661212
}
12671213

12681214
/// Evaluate this rule's guard against a successful query match. An
12691215
/// unguarded rule always succeeds.
12701216
fn guard_matches(&self, ast: &Ast, captures: &Captures, user_ctx: &C) -> bool {
1271-
if let Some(guard) = &self.guard {
1272-
guard(ast, captures, user_ctx)
1273-
} else {
1274-
true
1275-
}
1217+
self.guard
1218+
.as_ref()
1219+
.is_none_or(|guard| guard(ast, captures, user_ctx))
12761220
}
12771221

12781222
/// Run this rule's transform with the given captures, making `node`'s

‎shared/yeast/src/query.rs‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -56,15 +56,18 @@ impl QueryNode {
5656
pub enum QueryListElem {
5757
Repeated {
5858
children: Vec<QueryListElem>,
59-
rep: Rep,
59+
rep: Repetition,
6060
},
6161
SingleNode(QueryNode),
6262
}
6363

6464
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
65-
pub enum Rep {
65+
pub enum Repetition {
66+
/// Corresponds to `*`
6667
ZeroOrMore,
68+
/// Corresponds to `+`
6769
OneOrMore,
70+
/// Corresponds to `?`
6871
ZeroOrOne,
6972
}
7073

@@ -159,7 +162,7 @@ impl QueryListElem {
159162
if children.is_empty() {
160163
// Macro parsing rejects empty groups. Retain safe
161164
// zero-width behavior for manually constructed queries.
162-
return *rep != Rep::OneOrMore;
165+
return *rep != Repetition::OneOrMore;
163166
}
164167

165168
let mut iters = 0;
@@ -180,11 +183,11 @@ impl QueryListElem {
180183
break;
181184
}
182185
iters += 1;
183-
if *rep == Rep::ZeroOrOne {
186+
if *rep == Repetition::ZeroOrOne {
184187
break;
185188
}
186189
}
187-
*rep != Rep::OneOrMore || iters > 0
190+
*rep != Repetition::OneOrMore || iters > 0
188191
}
189192
QueryListElem::SingleNode(sub_query) => {
190193
// Forward-scan semantics: advance through the iterator until

0 commit comments

Comments
 (0)