Skip to content

Commit

Permalink
Simplify walk
Browse files Browse the repository at this point in the history
  • Loading branch information
matklad committed Aug 15, 2018
1 parent 9f6cf42 commit a7d31b5
Showing 1 changed file with 13 additions and 20 deletions.
33 changes: 13 additions & 20 deletions crates/libsyntax2/src/algo/walk.rs
Original file line number Original file line Diff line number Diff line change
@@ -1,4 +1,7 @@
use SyntaxNodeRef; use {
SyntaxNodeRef,
algo::generate,
};


pub fn preorder<'a>(root: SyntaxNodeRef<'a>) -> impl Iterator<Item = SyntaxNodeRef<'a>> { pub fn preorder<'a>(root: SyntaxNodeRef<'a>) -> impl Iterator<Item = SyntaxNodeRef<'a>> {
walk(root).filter_map(|event| match event { walk(root).filter_map(|event| match event {
Expand All @@ -14,32 +17,22 @@ pub enum WalkEvent<'a> {
} }


pub fn walk<'a>(root: SyntaxNodeRef<'a>) -> impl Iterator<Item = WalkEvent<'a>> { pub fn walk<'a>(root: SyntaxNodeRef<'a>) -> impl Iterator<Item = WalkEvent<'a>> {
let mut done = false; generate(Some(WalkEvent::Enter(root)), |pos| {
::itertools::unfold(WalkEvent::Enter(root), move |pos| { let next = match *pos {
if done {
return None;
}
let res = *pos;
*pos = match *pos {
WalkEvent::Enter(node) => match node.first_child() { WalkEvent::Enter(node) => match node.first_child() {
Some(child) => WalkEvent::Enter(child), Some(child) => WalkEvent::Enter(child),
None => WalkEvent::Exit(node), None => WalkEvent::Exit(node),
}, },
WalkEvent::Exit(node) => { WalkEvent::Exit(node) => {
if node == root { match node.next_sibling() {
done = true; Some(sibling) => WalkEvent::Enter(sibling),
WalkEvent::Exit(node) None => match node.parent() {
} else { Some(node) => WalkEvent::Exit(node),
match node.next_sibling() { None => return None,
Some(sibling) => WalkEvent::Enter(sibling), },
None => match node.parent() {
Some(node) => WalkEvent::Exit(node),
None => WalkEvent::Exit(node),
},
}
} }
} }
}; };
Some(res) Some(next)
}) })
} }

0 comments on commit a7d31b5

Please sign in to comment.