feat(node): Add utility methods for AST traversal #1213
+53
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR adds utility methods to the
Nodestruct andSearchtrait for improved AST traversal capabilities:has_ancestor()- Check if any ancestor node matches a predicateall_occurrences()- Find all descendant nodes matching a predicate (extendsSearchtrait)Origin
These methods were developed to support more complex AST analysis patterns, particularly for:
What it does
has_ancestor<F: Fn(&Node) -> bool>(&self, pred: F) -> boolTraverses up the tree from the current node's parent to the root, returning
trueif any ancestor satisfies the given predicate.all_occurrences(&self, pred: fn(u16) -> bool) -> Vec<Node<'a>>Starting from the current node, finds all descendant nodes (including self) that match the predicate. Uses depth-first traversal.
Implementation decisions
has_ancestoruses a generic closure (F: Fn(&Node) -> bool) instead offn(u16) -> boolto allow more flexible predicates that can inspect the full node, not just the kind_id.all_occurrencesusesfn(u16) -> boolto match the existingfirst_occurrencesignature in theSearchtrait, maintaining API consistency.Both methods are non-recursive using explicit stacks to avoid stack overflow on deeply nested ASTs.
Test plan
🤖 Generated with Claude Code