Skip to content
Open
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
52 changes: 52 additions & 0 deletions src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,27 @@ impl<'a> Node<'a> {
}
res
}

/// Checks if this node has any ancestor that meets the given predicate.
///
/// This method walks up the tree from this node's parent to the root,
/// returning `true` as soon as it finds any ancestor for which `pred`
/// returns `true`.
///
/// Note: This differs from [`Node::has_ancestors`], which checks for a
/// specific pattern of ancestors (immediate parent and grandparent
/// satisfying two separate predicates). `has_ancestor` instead uses a
/// single predicate and considers all ancestors in the hierarchy.
pub fn has_ancestor<F: Fn(&Node) -> bool>(&self, pred: F) -> bool {
let mut node = *self;
while let Some(parent) = node.parent() {
if pred(&parent) {
return true;
}
node = parent;
}
false
}
}

/// An `AST` cursor.
Expand Down Expand Up @@ -236,6 +257,37 @@ impl<'a> Search<'a> for Node<'a> {
None
}

/// Performs a depth-first search starting from this node (including `self`)
/// and returns all descendant nodes whose `kind_id` satisfies the given predicate.
fn all_occurrences(&self, pred: fn(u16) -> bool) -> Vec<Node<'a>> {
let mut cursor = self.cursor();
let mut stack = Vec::new();
let mut children = Vec::new();
let mut results = Vec::new();

stack.push(*self);

while let Some(node) = stack.pop() {
if pred(node.kind_id()) {
results.push(node);
}
cursor.reset(&node);
if cursor.goto_first_child() {
loop {
children.push(cursor.node());
if !cursor.goto_next_sibling() {
break;
}
}
for child in children.drain(..).rev() {
stack.push(child);
}
}
}

results
}

fn act_on_node(&self, action: &mut dyn FnMut(&Node<'a>)) {
let mut cursor = self.cursor();
let mut stack = Vec::new();
Expand Down
1 change: 1 addition & 0 deletions src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ pub trait ParserTrait {

pub(crate) trait Search<'a> {
fn first_occurrence(&self, pred: fn(u16) -> bool) -> Option<Node<'a>>;
fn all_occurrences(&self, pred: fn(u16) -> bool) -> Vec<Node<'a>>;
fn act_on_node(&self, pred: &mut dyn FnMut(&Node<'a>));
fn first_child(&self, pred: fn(u16) -> bool) -> Option<Node<'a>>;
fn act_on_child(&self, action: &mut dyn FnMut(&Node<'a>));
Expand Down