Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
44 changes: 44 additions & 0 deletions src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,21 @@ impl<'a> Node<'a> {
}
res
}

/// Checks if this node has any ancestor that meets the given predicate.
///
/// Traverses up the tree from this node's parent to the root,
/// returning true if any ancestor satisfies the predicate.
Comment thread
marlon-costa-dc marked this conversation as resolved.
Outdated
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 +251,35 @@ impl<'a> Search<'a> for Node<'a> {
None
}

Comment thread
marlon-costa-dc marked this conversation as resolved.
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
Loading