aboutsummaryrefslogtreecommitdiff
path: root/src/traverse.rs
blob: df13f5d95cd6ad7ed58a6b666facdc8a97a28e76 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// Lazy pre-order traversal over arbitrary tree-sitter trees

// extern
use tree_sitter::{Node, Tree, TreeCursor};

pub struct PreOrder<'a> {
    cursor: TreeCursor<'a>,
    done: bool,
}

impl<'a> PreOrder<'a> {
    pub fn new(tree: &'a Tree) -> Self {
        Self {
            cursor: tree.walk(),
            done: false,
        }
    }
}

// Traverse the tree in root-left-right fashion
impl<'a> Iterator for PreOrder<'a> {
    type Item = Node<'a>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        // capture the root node
        let node = self.cursor.node();

        // if this node has a child, move there and return the root, or
        // if this node has a sibling, move there and return the root
        if self.cursor.goto_first_child() || self.cursor.goto_next_sibling() {
            return Some(node);
        }

        loop {
            // we are done retracing all the way back to the root node
            if !self.cursor.goto_parent() {
                self.done = true;
                break;
            }

            if self.cursor.goto_next_sibling() {
                break;
            }
        }
        Some(node)
    }
}