Debian Codegraph @

Xtree-house/bindings/src/tree_cursor.rs

raw symbols SCIP
1 use ::std::os::raw;
2 use std::cell::Cell;
3 use std::collections::VecDeque;
4 use std::ffi::{c_char, CStr};
5 use std::marker::PhantomData;
6 use std::{fmt, mem};
7
8 use crate::node::NodeRaw;
9 use crate::{Node, Tree};
10
11 thread_local! {
12 static CACHE: Cell<Option<TreeCursorGuard>> = const { Cell::new(None) };
13 }
14
15 #[repr(C)]
16 #[derive(Clone)]
17 struct TreeCursorRaw {
18 tree: *const raw::c_void,
19 id: *const raw::c_void,
20 context: [u32; 3usize],
21 }
22
23 #[repr(C)]
24 struct TreeCursorGuard(TreeCursorRaw);
25
26 impl Drop for TreeCursorGuard {
27 fn drop(&mut self) {
28 unsafe { ts_tree_cursor_delete(&mut self.0) }
29 }
30 }
31
32 pub struct TreeCursor<'a> {
33 inner: TreeCursorRaw,
34 tree: PhantomData<&'a Tree>,
35 }
36
37 impl<'tree> TreeCursor<'tree> {
38 pub(crate) fn new(node: &Node<'tree>) -> Self {
39 Self {
40 inner: match CACHE.take() {
41 Some(guard) => unsafe {
42 let mut cursor = guard.0.clone();
43 mem::forget(guard);
44 ts_tree_cursor_reset(&mut cursor, node.as_raw());
45 cursor
46 },
47 None => unsafe { ts_tree_cursor_new(node.as_raw()) },
48 },
49 tree: PhantomData,
50 }
51 }
52
53 pub fn goto_parent(&mut self) -> bool {
54 unsafe { ts_tree_cursor_goto_parent(&mut self.inner) }
55 }
56
57 pub fn goto_next_sibling(&mut self) -> bool {
58 unsafe { ts_tree_cursor_goto_next_sibling(&mut self.inner) }
59 }
60
61 pub fn goto_previous_sibling(&mut self) -> bool {
62 unsafe { ts_tree_cursor_goto_previous_sibling(&mut self.inner) }
63 }
64
65 pub fn goto_first_child(&mut self) -> bool {
66 unsafe { ts_tree_cursor_goto_first_child(&mut self.inner) }
67 }
68
69 pub fn goto_last_child(&mut self) -> bool {
70 unsafe { ts_tree_cursor_goto_last_child(&mut self.inner) }
71 }
72
73 pub fn goto_first_child_for_byte(&mut self, byte_idx: u32) -> Option<u32> {
74 match unsafe { ts_tree_cursor_goto_first_child_for_byte(&mut self.inner, byte_idx) } {
75 -1 => None,
76 n => Some(n as u32),
77 }
78 }
79
80 pub fn reset(&mut self, node: &Node<'tree>) {
81 unsafe { ts_tree_cursor_reset(&mut self.inner, node.as_raw()) }
82 }
83
84 pub fn node(&self) -> Node<'tree> {
85 unsafe { Node::from_raw(ts_tree_cursor_current_node(&self.inner)).unwrap_unchecked() }
86 }
87
88 pub fn field_name(&self) -> Option<&'tree str> {
89 unsafe {
90 let ptr = ts_tree_cursor_current_field_name(&self.inner);
91 (!ptr.is_null()).then(|| CStr::from_ptr(ptr).to_str().unwrap())
92 }
93 }
94 }
95
96 impl fmt::Debug for TreeCursorRaw {
97 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98 f.debug_struct("InactiveTreeCursor").finish_non_exhaustive()
99 }
100 }
101
102 impl Drop for TreeCursor<'_> {
103 fn drop(&mut self) {
104 CACHE.set(Some(TreeCursorGuard(self.inner.clone())))
105 }
106 }
107
108 impl Clone for TreeCursor<'_> {
109 fn clone(&self) -> Self {
110 TreeCursor {
111 inner: unsafe { ts_tree_cursor_copy(&self.inner) },
112 tree: PhantomData,
113 }
114 }
115 }
116
117 impl<'cursor, 'tree: 'cursor> IntoIterator for &'cursor mut TreeCursor<'tree> {
118 type Item = Node<'tree>;
119 type IntoIter = TreeRecursiveWalker<'cursor, 'tree>;
120
121 fn into_iter(self) -> Self::IntoIter {
122 let mut queue = VecDeque::new();
123 let root = self.node();
124 queue.push_back(root.clone());
125
126 TreeRecursiveWalker {
127 cursor: self,
128 queue,
129 root,
130 }
131 }
132 }
133
134 pub struct TreeRecursiveWalker<'cursor, 'tree: 'cursor> {
135 cursor: &'cursor mut TreeCursor<'tree>,
136 queue: VecDeque<Node<'tree>>,
137 root: Node<'tree>,
138 }
139
140 impl<'tree> Iterator for TreeRecursiveWalker<'_, 'tree> {
141 type Item = Node<'tree>;
142
143 fn next(&mut self) -> Option<Self::Item> {
144 let current = self.cursor.node();
145
146 if current != self.root && self.cursor.goto_next_sibling() {
147 // Remember `current` so its children are expanded later, then move to its sibling.
148 self.queue.push_back(current);
149 return Some(self.cursor.node());
150 }
151
152 // `current` has no next sibling: it's the last node at this level. It still needs its
153 // children expanded, so enqueue it too.
154 if current != self.root {
155 self.queue.push_back(current);
156 }
157
158 while let Some(queued) = self.queue.pop_front() {
159 self.cursor.reset(&queued);
160
161 if !self.cursor.goto_first_child() {
162 continue;
163 }
164
165 return Some(self.cursor.node());
166 }
167
168 None
169 }
170 }
171
172 extern "C" {
173 /// Create a new tree cursor starting from the given node.
174 ///
175 /// A tree cursor allows you to walk a syntax tree more efficiently than is
176 /// possible using the `TSNode` functions. It is a mutable object that is always
177 /// on a certain syntax node, and can be moved imperatively to different nodes.
178 ///
179 /// Note that the given node is considered the root of the cursor,
180 /// and the cursor cannot walk outside this node.
181 fn ts_tree_cursor_new(node: NodeRaw) -> TreeCursorRaw;
182 /// Delete a tree cursor, freeing all of the memory that it used.
183 fn ts_tree_cursor_delete(self_: *mut TreeCursorRaw);
184 /// Re-initialize a tree cursor to start at a different node.
185 fn ts_tree_cursor_reset(self_: *mut TreeCursorRaw, node: NodeRaw);
186 // /// Re-initialize a tree cursor to the same position as another cursor.
187 // /// Unlike [`ts_tree_cursor_reset`], this will not lose parent information and
188 // /// allows reusing already created cursors.
189 // fn ts_tree_cursor_reset_to(dst: *mut TreeCursorRaw, src: *const TreeCursorRaw);
190 /// Get the tree cursor's current node.
191 fn ts_tree_cursor_current_node(self_: *const TreeCursorRaw) -> NodeRaw;
192 // /// Get the field name of the tree cursor's current node.
193 // /// This returns `NULL` if the current node doesn't have a field.
194 // /// See also [`ts_node_child_by_field_name`].
195 // fn ts_tree_cursor_current_field_name(self_: *const TreeCursorRaw) -> *const raw::c_char;
196 // /// Get the field id of the tree cursor's current node.
197 // /// This returns zero if the current node doesn't have a field.
198 // /// See also [`ts_node_child_by_field_id`], [`ts_language_field_id_for_name`].
199 // fn ts_tree_cursor_current_field_id(self_: *const TreeCursorRaw) -> TSFieldId;
200 /// Move the cursor to the parent of its current node.
201 /// This returns `true` if the cursor successfully moved, and returns `false`
202 /// if there was no parent node (the cursor was already on the root node).
203 fn ts_tree_cursor_goto_parent(self_: *mut TreeCursorRaw) -> bool;
204 /// Move the cursor to the next sibling of its current node.
205 /// This returns `true` if the cursor successfully moved, and returns `false`
206 /// if there was no next sibling node.
207 fn ts_tree_cursor_goto_next_sibling(self_: *mut TreeCursorRaw) -> bool;
208 /// Move the cursor to the previous sibling of its current node.
209 /// This returns `true` if the cursor successfully moved, and returns `false` if
210 /// there was no previous sibling node.
211 /// Note, that this function may be slower than
212 /// [`ts_tree_cursor_goto_next_sibling`] due to how node positions are stored. In
213 /// the worst case, this will need to iterate through all the children upto the
214 /// previous sibling node to recalculate its position.
215 fn ts_tree_cursor_goto_previous_sibling(self_: *mut TreeCursorRaw) -> bool;
216 /// Move the cursor to the first child of its current node.
217 /// This returns `true` if the cursor successfully moved, and returns `false`
218 /// if there were no children.
219 fn ts_tree_cursor_goto_first_child(self_: *mut TreeCursorRaw) -> bool;
220 /// Move the cursor to the last child of its current node.
221 /// This returns `true` if the cursor successfully moved, and returns `false` if
222 /// there were no children.
223 /// Note that this function may be slower than [`ts_tree_cursor_goto_first_child`]
224 /// because it needs to iterate through all the children to compute the child's
225 /// position.
226 fn ts_tree_cursor_goto_last_child(self_: *mut TreeCursorRaw) -> bool;
227 /*
228 /// Move the cursor to the node that is the nth descendant of
229 /// the original node that the cursor was constructed with, where
230 /// zero represents the original node itself.
231 fn ts_tree_cursor_goto_descendant(self_: *mut TreeCursorRaw, goal_descendant_index: u32);
232 /// Get the index of the cursor's current node out of all of the
233 /// descendants of the original node that the cursor was constructed with.
234 fn ts_tree_cursor_current_descendant_index(self_: *const TreeCursorRaw) -> u32;
235 /// Get the depth of the cursor's current node relative to the original
236 /// node that the cursor was constructed with.
237 fn ts_tree_cursor_current_depth(self_: *const TreeCursorRaw) -> u32;
238 */
239 /// Move the cursor to the first child of its current node that extends beyond
240 /// the given byte offset or point.
241 /// This returns the index of the child node if one was found, and returns -1
242 /// if no such child was found.
243 fn ts_tree_cursor_goto_first_child_for_byte(self_: *mut TreeCursorRaw, goal_byte: u32) -> i64;
244 fn ts_tree_cursor_copy(cursor: *const TreeCursorRaw) -> TreeCursorRaw;
245 /// Get the field name of the tree cursor's curren tnode.
246 ///
247 /// This returns `NULL` if the current node doesn't have a field. See also
248 /// `ts_node_child_by_field_name`.
249 fn ts_tree_cursor_current_field_name(cursor: *const TreeCursorRaw) -> *const c_char;
250 }
251
252 #[cfg(test)]
253 mod tests {
254 use std::collections::HashSet;
255 use std::path::Path;
256
257 use super::TreeCursor;
258 use crate::{Grammar, Input, Node, Parser};
259
260 struct StrInput<'a> {
261 src: &'a str,
262 cursor: &'a str,
263 }
264
265 impl<'a> StrInput<'a> {
266 fn new(src: &'a str) -> Self {
267 Self { src, cursor: src }
268 }
269 }
270
271 impl<'a> Input for StrInput<'a> {
272 type Cursor = &'a str;
273
274 fn cursor_at(&mut self, _offset: u32) -> &mut &'a str {
275 self.cursor = self.src;
276 &mut self.cursor
277 }
278
279 fn eq(&mut self, r1: std::ops::Range<u32>, r2: std::ops::Range<u32>) -> bool {
280 let b = self.src.as_bytes();
281 b[r1.start as usize..r1.end as usize] == b[r2.start as usize..r2.end as usize]
282 }
283 }
284
285 fn python_grammar() -> Grammar {
286 let so = Path::new(env!("CARGO_MANIFEST_DIR")).join("../test-grammars/python/python.so");
287 unsafe { Grammar::new("python", &so) }.expect("python grammar")
288 }
289
290 fn collect_descendants(node: &Node, out: &mut HashSet<usize>) {
291 for i in 0..node.child_count() {
292 let child = node.child(i).unwrap();
293 out.insert(child.id());
294 collect_descendants(&child, out);
295 }
296 }
297
298 #[test]
299 fn recursive_walker_visits_every_descendant() {
300 let grammar = python_grammar();
301 let src = "x = 1\ny = [1, 2, 3]\n";
302 let mut parser = Parser::new();
303 parser.set_grammar(grammar).unwrap();
304 let tree = parser.parse(StrInput::new(src), None).unwrap();
305 let root = tree.root_node();
306
307 let mut expected = HashSet::new();
308 collect_descendants(&root, &mut expected);
309
310 let mut cursor = TreeCursor::new(&root);
311 let visited: Vec<usize> = (&mut cursor).into_iter().map(|n| n.id()).collect();
312 let unique: HashSet<usize> = visited.iter().copied().collect();
313
314 assert_eq!(
315 visited.len(),
316 unique.len(),
317 "walker must not visit a node more than once"
318 );
319 assert_eq!(
320 unique, expected,
321 "walker must visit every descendant exactly once"
322 );
323 }
324 }