Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions shared/yeast-macros/src/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,9 +318,9 @@ impl Pattern {
vec![captured]
} else {
let repetition = match (cardinality.multiple, cardinality.required) {
(true, false) => quote! { yeast::query::Rep::ZeroOrMore },
(true, true) => quote! { yeast::query::Rep::OneOrMore },
(false, false) => quote! { yeast::query::Rep::ZeroOrOne },
(true, false) => quote! { yeast::query::Repetition::ZeroOrMore },
(true, true) => quote! { yeast::query::Repetition::OneOrMore },
(false, false) => quote! { yeast::query::Repetition::ZeroOrOne },
(false, true) => unreachable!("single cardinality handled above"),
};
vec![quote! {
Expand All @@ -337,9 +337,9 @@ impl Pattern {
} => {
let children = pattern.lower_list();
let repetition = match (cardinality.multiple, cardinality.required) {
(true, false) => quote! { yeast::query::Rep::ZeroOrMore },
(true, true) => quote! { yeast::query::Rep::OneOrMore },
(false, false) => quote! { yeast::query::Rep::ZeroOrOne },
(true, false) => quote! { yeast::query::Repetition::ZeroOrMore },
(true, true) => quote! { yeast::query::Repetition::OneOrMore },
(false, false) => quote! { yeast::query::Repetition::ZeroOrOne },
(false, true) => unreachable!("single patterns are not wrapped as repeated"),
};
vec![quote! {
Expand Down
48 changes: 24 additions & 24 deletions shared/yeast/doc/yeast.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,25 +19,25 @@ so that CodeQL queries only need to reason about the `.each` form.
## Architecture

```
Source code
│
▼
┌──────────────┐
│ tree-sitter │ Parse source into a concrete syntax tree
│ parser │
└──────┬───────┘
│ tree_sitter::Tree
▼
┌──────────────┐
│ YEAST │ Apply desugaring rules, producing a new AST
│ Runner │
└──────┬───────┘
│ yeast::Ast
▼
┌──────────────┐
│ TRAP │ Walk the (possibly rewritten) AST and emit TRAP tuples
│ extractor │
└──────────────┘
Source code
│
▼
┌──────────────┐
│ tree-sitter │ Parse source into a concrete syntax tree
│ parser │
└──────┬───────┘
│ tree_sitter::Tree
▼
┌──────────────┐
│ YEAST │ Apply desugaring rules, producing a new AST
│ Runner │
└──────┬───────┘
│ yeast::Ast
▼
┌──────────────┐
│ TRAP │ Walk the (possibly rewritten) AST and emit TRAP tuples
│ extractor │
└──────────────┘
```

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

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

The suffix mirrors the `?` / `*` markers used elsewhere in the schema
DSL (see [`ast_types.yml`](../../../unified/extractor/ast_types.yml)):
Expand Down
40 changes: 21 additions & 19 deletions shared/yeast/src/captures.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@ use std::collections::{BTreeMap, BTreeSet};

use crate::{OutputId, TreeId};

/// If `values` contains exactly one element, return it. Otherwise, return `None`.
fn single_id<T: Copy>(values: &[T]) -> Option<T> {
match values {
[value] => Some(*value),
_ => None,
}
}

#[derive(Debug, Clone)]
pub struct Captures<Id: TreeId = crate::Id> {
captures: BTreeMap<&'static str, Vec<Id>>,
Expand All @@ -21,33 +29,27 @@ impl<Id: TreeId> Captures<Id> {
}

pub fn get_var(&self, key: &str) -> Result<Id, String> {
let ids = self.captures.get(key);
if let Some(ids) = ids {
if ids.len() == 1 {
Ok(ids[0])
} else {
Err(format!(
"Variable {} has {} matches, use * to allow repetition",
key,
ids.len()
))
}
} else {
Err(format!("No variable named {key}"))
}
let ids = self
.captures
.get(key)
.ok_or_else(|| format!("No variable named {key}"))?;
single_id(ids).ok_or_else(|| {
format!(
"Variable {key} has {} matches, use * to allow repetition",
ids.len()
)
})
}

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

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

pub fn insert(&mut self, key: &'static str, id: Id) {
Expand Down
108 changes: 26 additions & 82 deletions shared/yeast/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -550,26 +550,17 @@ impl<Id: TreeId> Iterator for ChildrenIter<'_, Id> {
type Item = Id;

fn next(&mut self) -> Option<Self::Item> {
match self.field_children.as_mut() {
None => match self.field_order.next() {
Some(field) => {
self.current_field = Some(field);
self.field_children = Some(self.fields[&field].iter());
self.next()
}
None => None,
},
Some(children) => match children.next() {
None => match self.field_order.next() {
None => None,
Some(field) => {
self.current_field = Some(field);
self.field_children = Some(self.fields[&field].iter());
self.next()
}
},
Some(child_id) => Some(*child_id),
},
loop {
if let Some(child_id) = self
.field_children
.as_mut()
.and_then(|children| children.next())
{
return Some(*child_id);
}
let field = self.field_order.next()?;
self.current_field = Some(field);
self.field_children = Some(self.fields[&field].iter());
Comment thread
paldepind marked this conversation as resolved.
Resolved
}
}
}
Expand Down Expand Up @@ -884,55 +875,11 @@ impl<Id: TreeId> Ast<Id> {
}

fn union_source_range_of_children(&self, fields: &BTreeMap<FieldId, Vec<Id>>) -> Option<Range> {
let mut start_byte: Option<usize> = None;
let mut end_byte: Option<usize> = None;
let mut start_point = Point { row: 0, column: 0 };
let mut end_point = Point { row: 0, column: 0 };

for child_ids in fields.values() {
for &child_id in child_ids {
let Some(child) = self.get_node(child_id) else {
continue;
};
let Some(child_range) = child.source_range() else {
continue;
};

match start_byte {
None => {
start_byte = Some(child_range.start_byte);
start_point = child_range.start_point;
}
Some(current_start) if child_range.start_byte < current_start => {
start_byte = Some(child_range.start_byte);
start_point = child_range.start_point;
}
_ => {}
}

match end_byte {
None => {
end_byte = Some(child_range.end_byte);
end_point = child_range.end_point;
}
Some(current_end) if child_range.end_byte > current_end => {
end_byte = Some(child_range.end_byte);
end_point = child_range.end_point;
}
_ => {}
}
}
}

match (start_byte, end_byte) {
(Some(start_byte), Some(end_byte)) => Some(Range {
start_byte,
end_byte,
start_point,
end_point,
}),
_ => None,
}
fields
.values()
.flatten()
.filter_map(|&id| self.get_node(id)?.source_range())
.reduce(Range::union)
}

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

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

pub fn id_for_unnamed_node_kind(&self, kind: &str) -> Option<KindId> {
let id = self.schema.id_for_unnamed_node_kind(kind).unwrap_or(0);
if id == 0 { None } else { Some(id) }
self.schema
.id_for_unnamed_node_kind(kind)
.filter(|&id| id != 0)
}
}

Expand Down Expand Up @@ -1259,20 +1206,17 @@ impl<C> Rule<C> {
/// transform.
fn match_query(&self, ast: &Ast, node: Id) -> Option<Captures> {
let mut captures = Captures::new();
if !self.query.do_match(ast, node, &mut captures) {
return None;
}
Some(captures)
self.query
.do_match(ast, node, &mut captures)
.then_some(captures)
}

/// Evaluate this rule's guard against a successful query match. An
/// unguarded rule always succeeds.
fn guard_matches(&self, ast: &Ast, captures: &Captures, user_ctx: &C) -> bool {
if let Some(guard) = &self.guard {
guard(ast, captures, user_ctx)
} else {
true
}
self.guard
.as_ref()
.is_none_or(|guard| guard(ast, captures, user_ctx))
}

/// Run this rule's transform with the given captures, making `node`'s
Expand Down
13 changes: 8 additions & 5 deletions shared/yeast/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,18 @@ impl QueryNode {
pub enum QueryListElem {
Repeated {
children: Vec<QueryListElem>,
rep: Rep,
rep: Repetition,
},
SingleNode(QueryNode),
}

#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum Rep {
pub enum Repetition {
/// Corresponds to `*`
ZeroOrMore,
/// Corresponds to `+`
OneOrMore,
/// Corresponds to `?`
ZeroOrOne,
}
Comment thread
paldepind marked this conversation as resolved.
Resolved

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

let mut iters = 0;
Expand All @@ -180,11 +183,11 @@ impl QueryListElem {
break;
}
iters += 1;
if *rep == Rep::ZeroOrOne {
if *rep == Repetition::ZeroOrOne {
break;
}
}
*rep != Rep::OneOrMore || iters > 0
*rep != Repetition::OneOrMore || iters > 0
}
QueryListElem::SingleNode(sub_query) => {
// Forward-scan semantics: advance through the iterator until
Expand Down
Loading
Loading