forked from mozilla/rust-code-analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode.rs
More file actions
104 lines (89 loc) · 2.83 KB
/
Copy pathnode.rs
File metadata and controls
104 lines (89 loc) · 2.83 KB
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
95
96
97
98
99
100
101
102
103
104
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
}
pub(crate) fn children(&self) -> impl ExactSizeIterator<Item = Node<'a>> {
let mut cursor = self.0.walk();
cursor.goto_first_child();
(0..self.object().child_count()).into_iter().map(move |_| {
let result = Node::new(cursor.node());
cursor.goto_next_sibling();
result
})
}
}
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));
}
}
}