| 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 |
|
| 148 |
self.queue.push_back(current); |
| 149 |
return Some(self.cursor.node()); |
| 150 |
} |
| 151 |
|
| 152 |
|
| 153 |
|
| 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 |
|
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
fn ts_tree_cursor_new(node: NodeRaw) -> TreeCursorRaw; |
| 182 |
|
| 183 |
fn ts_tree_cursor_delete(self_: *mut TreeCursorRaw); |
| 184 |
|
| 185 |
fn ts_tree_cursor_reset(self_: *mut TreeCursorRaw, node: NodeRaw); |
| 186 |
|
| 187 |
|
| 188 |
|
| 189 |
|
| 190 |
|
| 191 |
fn ts_tree_cursor_current_node(self_: *const TreeCursorRaw) -> NodeRaw; |
| 192 |
|
| 193 |
|
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
fn ts_tree_cursor_goto_parent(self_: *mut TreeCursorRaw) -> bool; |
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
fn ts_tree_cursor_goto_next_sibling(self_: *mut TreeCursorRaw) -> bool; |
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
fn ts_tree_cursor_goto_previous_sibling(self_: *mut TreeCursorRaw) -> bool; |
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
fn ts_tree_cursor_goto_first_child(self_: *mut TreeCursorRaw) -> bool; |
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
fn ts_tree_cursor_goto_last_child(self_: *mut TreeCursorRaw) -> bool; |
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 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 |
|
| 246 |
|
| 247 |
|
| 248 |
|
| 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 |
} |