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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
use tree_sitter::Node as OtherNode;

use crate::traits::Search;

/// An `AST` node.
#[derive(Clone, Copy)]
pub struct Node<'a>(OtherNode<'a>);

impl<'a> Node<'a> {
    /// Checks if a node represents a syntax error or contains any syntax errors
    /// anywhere within it.
    pub fn has_error(&self) -> bool {
        self.0.has_error()
    }

    pub(crate) fn new(node: OtherNode<'a>) -> Self {
        Node(node)
    }

    pub(crate) fn object(&self) -> OtherNode<'a> {
        self.0
    }
}

impl<'a> Search<'a> for Node<'a> {
    fn first_occurence(&self, pred: fn(u16) -> bool) -> Option<Node<'a>> {
        let mut cursor = self.0.walk();
        let mut stack = Vec::new();
        let mut children = Vec::new();

        stack.push(*self);

        while let Some(node) = stack.pop() {
            if pred(node.0.kind_id()) {
                return Some(node);
            }
            cursor.reset(node.0);
            if cursor.goto_first_child() {
                loop {
                    children.push(Node::new(cursor.node()));
                    if !cursor.goto_next_sibling() {
                        break;
                    }
                }
                for child in children.drain(..).rev() {
                    stack.push(child);
                }
            }
        }

        None
    }

    fn act_on_node(&self, action: &mut dyn FnMut(&Node<'a>)) {
        let mut cursor = self.0.walk();
        let mut stack = Vec::new();
        let mut children = Vec::new();

        stack.push(*self);

        while let Some(node) = stack.pop() {
            action(&node);
            cursor.reset(node.0);
            if cursor.goto_first_child() {
                loop {
                    children.push(Node::new(cursor.node()));
                    if !cursor.goto_next_sibling() {
                        break;
                    }
                }
                for child in children.drain(..).rev() {
                    stack.push(child);
                }
            }
        }
    }

    fn first_child(&self, pred: fn(u16) -> bool) -> Option<Node<'a>> {
        let mut cursor = self.0.walk();
        for child in self.0.children(&mut cursor) {
            if pred(child.kind_id()) {
                return Some(Node::new(child));
            }
        }
        None
    }

    fn act_on_child(&self, action: &mut dyn FnMut(&Node<'a>)) {
        let mut cursor = self.0.walk();
        for child in self.0.children(&mut cursor) {
            action(&Node::new(child));
        }
    }
}