Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(semantic): AstNodeParentIter fetch nodes lazily #4533

Merged
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
16 changes: 9 additions & 7 deletions crates/oxc_semantic/src/node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,9 @@ impl<'a> AstNodes<'a> {
///
/// The first node produced by this iterator is the first parent of the node
/// pointed to by `node_id`. The last node will usually be a `Program`.
#[inline]
pub fn iter_parents(&self, node_id: AstNodeId) -> impl Iterator<Item = &AstNode<'a>> + '_ {
let curr = Some(self.get_node(node_id));
AstNodeParentIter { curr, nodes: self }
AstNodeParentIter { current_node_id: Some(node_id), nodes: self }
}

#[inline]
Expand Down Expand Up @@ -197,17 +197,19 @@ impl<'a> AstNodes<'a> {

#[derive(Debug)]
pub struct AstNodeParentIter<'s, 'a> {
curr: Option<&'s AstNode<'a>>,
current_node_id: Option<AstNodeId>,
nodes: &'s AstNodes<'a>,
}

impl<'s, 'a> Iterator for AstNodeParentIter<'s, 'a> {
type Item = &'s AstNode<'a>;

fn next(&mut self) -> Option<Self::Item> {
let next = self.curr;
self.curr = self.curr.and_then(|curr| self.nodes.parent_node(curr.id()));

next
if let Some(node_id) = self.current_node_id {
self.current_node_id = self.nodes.parent_ids[node_id];
Some(self.nodes.get_node(node_id))
} else {
None
}
}
}