aft_parse/callgraph_store/
syntax_index.rs1use rustc_hash::FxHashMap;
19use tree_sitter::Node;
20
21const NONE: u32 = u32::MAX;
23
24pub trait Nav<'tree>: Copy {
27 fn kind(self, node: Node<'tree>) -> &'static str;
29 fn parent(self, node: Node<'tree>) -> Option<Node<'tree>>;
31 fn prev_sibling(self, node: Node<'tree>) -> Option<Node<'tree>>;
33 fn prev_named_sibling(self, node: Node<'tree>) -> Option<Node<'tree>>;
35 fn next_named_sibling(self, node: Node<'tree>) -> Option<Node<'tree>>;
37 fn walk(self, root: Node<'tree>, visit: impl FnMut(Node<'tree>, &'static str) -> bool);
40 fn walk_with_parent_kind(
44 self,
45 root: Node<'tree>,
46 visit: impl FnMut(Node<'tree>, &'static str, Option<&'static str>),
47 );
48 fn walk_named(self, root: Node<'tree>, visit: impl FnMut(Node<'tree>, &'static str) -> bool);
52 fn for_each_child(self, node: Node<'tree>, visit: impl FnMut(Node<'tree>));
54 fn for_each_named_child(self, node: Node<'tree>, visit: impl FnMut(Node<'tree>));
56 fn reverse_named_preorder(self, root: Node<'tree>) -> Vec<Node<'tree>>;
59
60 fn enclosing(self, mut node: Node<'tree>, kinds: &[&str]) -> Option<Node<'tree>> {
62 loop {
63 if kinds.contains(&self.kind(node)) {
64 return Some(node);
65 }
66 node = self.parent(node)?;
67 }
68 }
69}
70
71#[derive(Clone, Copy)]
73pub struct Direct;
74
75impl<'tree> Nav<'tree> for Direct {
76 fn kind(self, node: Node<'tree>) -> &'static str {
77 node.kind()
78 }
79
80 fn parent(self, node: Node<'tree>) -> Option<Node<'tree>> {
81 node.parent()
82 }
83
84 fn prev_sibling(self, node: Node<'tree>) -> Option<Node<'tree>> {
85 node.prev_sibling()
86 }
87
88 fn prev_named_sibling(self, node: Node<'tree>) -> Option<Node<'tree>> {
89 node.prev_named_sibling()
90 }
91
92 fn next_named_sibling(self, node: Node<'tree>) -> Option<Node<'tree>> {
93 node.next_named_sibling()
94 }
95
96 fn walk(self, root: Node<'tree>, mut visit: impl FnMut(Node<'tree>, &'static str) -> bool) {
97 let mut cursor = root.walk();
98 loop {
99 let node = cursor.node();
100 if visit(node, node.kind()) && cursor.goto_first_child() {
101 continue;
102 }
103 while !cursor.goto_next_sibling() {
104 if !cursor.goto_parent() {
105 return;
106 }
107 }
108 }
109 }
110
111 fn walk_with_parent_kind(
112 self,
113 root: Node<'tree>,
114 mut visit: impl FnMut(Node<'tree>, &'static str, Option<&'static str>),
115 ) {
116 let mut cursor = root.walk();
117 let mut parents: Vec<&'static str> = Vec::new();
118 'walk: loop {
119 let node = cursor.node();
120 let kind = node.kind();
121 visit(node, kind, parents.last().copied());
122 if cursor.goto_first_child() {
123 parents.push(kind);
124 continue;
125 }
126 loop {
127 if cursor.goto_next_sibling() {
128 break;
129 }
130 if !cursor.goto_parent() {
131 break 'walk;
132 }
133 parents.pop();
134 }
135 }
136 }
137
138 fn walk_named(
139 self,
140 root: Node<'tree>,
141 mut visit: impl FnMut(Node<'tree>, &'static str) -> bool,
142 ) {
143 let mut stack = vec![root];
144 while let Some(node) = stack.pop() {
145 if visit(node, node.kind()) {
146 stack.extend(node.named_children(&mut node.walk()));
147 }
148 }
149 }
150
151 fn for_each_child(self, node: Node<'tree>, mut visit: impl FnMut(Node<'tree>)) {
152 let mut cursor = node.walk();
153 for child in node.children(&mut cursor) {
154 visit(child);
155 }
156 }
157
158 fn for_each_named_child(self, node: Node<'tree>, mut visit: impl FnMut(Node<'tree>)) {
159 let mut cursor = node.walk();
160 for child in node.named_children(&mut cursor) {
161 visit(child);
162 }
163 }
164
165 fn reverse_named_preorder(self, root: Node<'tree>) -> Vec<Node<'tree>> {
166 let mut result = Vec::new();
167 let mut cursor = root.walk();
168 let mut depth = 0;
169 loop {
170 result.push(cursor.node());
171 if cursor.goto_last_child() {
172 while !cursor.node().is_named() && cursor.goto_previous_sibling() {}
173 if cursor.node().is_named() {
174 depth += 1;
175 continue;
176 }
177 cursor.goto_parent();
178 }
179 loop {
180 if depth == 0 {
181 return result;
182 }
183 let mut previous = cursor.goto_previous_sibling();
184 while previous && !cursor.node().is_named() {
185 previous = cursor.goto_previous_sibling();
186 }
187 if previous {
188 break;
189 }
190 cursor.goto_parent();
191 depth -= 1;
192 }
193 }
194 }
195}
196
197pub struct SyntaxIndex<'tree> {
201 nodes: Vec<Node<'tree>>,
202 kinds: Vec<&'static str>,
203 named: Vec<bool>,
204 parents: Vec<u32>,
205 previous_siblings: Vec<u32>,
206 next_siblings: Vec<u32>,
207 subtree_ends: Vec<u32>,
209 positions: std::cell::OnceCell<FxHashMap<usize, u32>>,
212 reverse_named: Vec<Node<'tree>>,
213 kind_names: Vec<Option<&'static str>>,
216}
217
218impl<'tree> SyntaxIndex<'tree> {
219 pub fn new(root: Node<'tree>) -> Self {
221 let language = root.language();
222 let kind_names = (0..language.node_kind_count())
223 .map(|id| {
224 u16::try_from(id)
225 .ok()
226 .and_then(|id| language.node_kind_for_id(id))
227 })
228 .collect();
229 let mut index = Self {
230 nodes: Vec::new(),
231 kinds: Vec::new(),
232 named: Vec::new(),
233 parents: Vec::new(),
234 previous_siblings: Vec::new(),
235 next_siblings: Vec::new(),
236 subtree_ends: Vec::new(),
237 positions: std::cell::OnceCell::new(),
238 reverse_named: Vec::new(),
239 kind_names,
240 };
241 let mut cursor = root.walk();
242 let mut ancestors: Vec<(u32, u32)> = Vec::new();
245 'walk: loop {
246 let node = cursor.node();
247 let position = index.nodes.len() as u32;
248 let (parent, previous) = match ancestors.last_mut() {
249 Some((parent, last_child)) => {
250 let previous = std::mem::replace(last_child, position);
251 (*parent, previous)
252 }
253 None => (NONE, NONE),
254 };
255 if previous != NONE {
256 index.next_siblings[previous as usize] = position;
257 }
258 index.nodes.push(node);
259 index.kinds.push(index.kind_name(node));
260 index.named.push(node.is_named());
261 index.parents.push(parent);
262 index.previous_siblings.push(previous);
263 index.next_siblings.push(NONE);
264 index.subtree_ends.push(position + 1);
265 if cursor.goto_first_child() {
266 ancestors.push((position, NONE));
267 continue;
268 }
269 loop {
270 if cursor.goto_next_sibling() {
271 break;
272 }
273 if !cursor.goto_parent() {
274 break 'walk;
275 }
276 let (closed, _) = ancestors.pop().expect("every parent was entered");
277 index.subtree_ends[closed as usize] = index.nodes.len() as u32;
278 }
279 }
280 index.reverse_named = index.reverse_named_from(0);
281 index
282 }
283
284 pub fn preorder_kinds(&self) -> impl Iterator<Item = (Node<'tree>, &'static str)> + '_ {
286 self.nodes.iter().copied().zip(self.kinds.iter().copied())
287 }
288
289 fn kind_name(&self, node: Node<'tree>) -> &'static str {
290 match self.kind_names.get(usize::from(node.kind_id())) {
291 Some(Some(name)) => name,
292 _ => node.kind(),
294 }
295 }
296
297 fn position(&self, node: Node<'tree>) -> Option<u32> {
298 if self.nodes.first() == Some(&node) {
299 return Some(0);
300 }
301 self.positions
302 .get_or_init(|| {
303 self.nodes
304 .iter()
305 .enumerate()
306 .map(|(position, node)| (node.id(), position as u32))
307 .collect()
308 })
309 .get(&node.id())
310 .copied()
311 }
312
313 fn reverse_named_from(&self, root: u32) -> Vec<Node<'tree>> {
314 let mut order = Vec::new();
315 let mut stack = vec![root];
316 while let Some(position) = stack.pop() {
317 order.push(self.nodes[position as usize]);
318 let end = self.subtree_ends[position as usize];
320 let mut child = position + 1;
321 while child < end {
322 if self.named[child as usize] {
323 stack.push(child);
324 }
325 child = self.subtree_ends[child as usize];
326 }
327 }
328 order
329 }
330
331 fn neighbour(&self, position: u32) -> Result<Option<Node<'tree>>, ()> {
335 if position == NONE {
336 return Ok(None);
337 }
338 let node = self.nodes[position as usize];
339 if node.start_byte() == node.end_byte() {
340 return Err(());
341 }
342 Ok(Some(node))
343 }
344
345 fn step(&self, node: Node<'tree>, links: &[u32]) -> Option<Option<Node<'tree>>> {
348 if node.start_byte() == node.end_byte() {
349 return None;
350 }
351 let position = self.position(node)?;
352 self.neighbour(links[position as usize]).ok()
353 }
354
355 fn named_step(&self, node: Node<'tree>, links: &[u32]) -> Option<Option<Node<'tree>>> {
358 if node.start_byte() == node.end_byte() {
359 return None;
360 }
361 let mut position = links[self.position(node)? as usize];
362 loop {
363 let sibling = self.neighbour(position).ok()?;
364 match sibling {
365 None => return Some(None),
366 Some(sibling) if self.named[position as usize] => return Some(Some(sibling)),
367 Some(_) => position = links[position as usize],
368 }
369 }
370 }
371}
372
373impl<'tree> Nav<'tree> for &SyntaxIndex<'tree> {
374 fn kind(self, node: Node<'tree>) -> &'static str {
375 self.kind_name(node)
376 }
377
378 fn parent(self, node: Node<'tree>) -> Option<Node<'tree>> {
379 if node.start_byte() == node.end_byte() {
380 return node.parent();
381 }
382 match self.position(node) {
383 Some(position) => {
384 let parent = self.parents[position as usize];
385 (parent != NONE).then(|| self.nodes[parent as usize])
386 }
387 None => node.parent(),
388 }
389 }
390
391 fn prev_sibling(self, node: Node<'tree>) -> Option<Node<'tree>> {
392 self.step(node, &self.previous_siblings)
393 .unwrap_or_else(|| node.prev_sibling())
394 }
395
396 fn prev_named_sibling(self, node: Node<'tree>) -> Option<Node<'tree>> {
397 self.named_step(node, &self.previous_siblings)
398 .unwrap_or_else(|| node.prev_named_sibling())
399 }
400
401 fn next_named_sibling(self, node: Node<'tree>) -> Option<Node<'tree>> {
402 self.named_step(node, &self.next_siblings)
403 .unwrap_or_else(|| node.next_named_sibling())
404 }
405
406 fn walk(self, root: Node<'tree>, mut visit: impl FnMut(Node<'tree>, &'static str) -> bool) {
407 let Some(start) = self.position(root) else {
408 return Direct.walk(root, visit);
409 };
410 let end = self.subtree_ends[start as usize];
411 let mut position = start;
412 while position < end {
413 let index = position as usize;
414 position = if visit(self.nodes[index], self.kinds[index]) {
415 position + 1
416 } else {
417 self.subtree_ends[index]
418 };
419 }
420 }
421
422 fn walk_with_parent_kind(
423 self,
424 root: Node<'tree>,
425 mut visit: impl FnMut(Node<'tree>, &'static str, Option<&'static str>),
426 ) {
427 let Some(start) = self.position(root) else {
428 return Direct.walk_with_parent_kind(root, visit);
429 };
430 visit(root, self.kinds[start as usize], None);
431 for position in start + 1..self.subtree_ends[start as usize] {
432 let index = position as usize;
433 let parent = self.parents[index] as usize;
434 visit(
435 self.nodes[index],
436 self.kinds[index],
437 Some(self.kinds[parent]),
438 );
439 }
440 }
441
442 fn walk_named(
443 self,
444 root: Node<'tree>,
445 mut visit: impl FnMut(Node<'tree>, &'static str) -> bool,
446 ) {
447 let Some(start) = self.position(root) else {
448 return Direct.walk_named(root, visit);
449 };
450 let mut stack = vec![start];
451 while let Some(position) = stack.pop() {
452 let index = position as usize;
453 if visit(self.nodes[index], self.kinds[index]) {
454 let end = self.subtree_ends[index];
455 let mut child = position + 1;
456 while child < end {
457 if self.named[child as usize] {
458 stack.push(child);
459 }
460 child = self.subtree_ends[child as usize];
461 }
462 }
463 }
464 }
465
466 fn for_each_child(self, node: Node<'tree>, mut visit: impl FnMut(Node<'tree>)) {
467 let Some(position) = self.position(node) else {
468 return Direct.for_each_child(node, visit);
469 };
470 let end = self.subtree_ends[position as usize];
471 let mut child = position + 1;
472 while child < end {
473 visit(self.nodes[child as usize]);
474 child = self.subtree_ends[child as usize];
475 }
476 }
477
478 fn for_each_named_child(self, node: Node<'tree>, mut visit: impl FnMut(Node<'tree>)) {
479 let Some(position) = self.position(node) else {
480 return Direct.for_each_named_child(node, visit);
481 };
482 let end = self.subtree_ends[position as usize];
483 let mut child = position + 1;
484 while child < end {
485 if self.named[child as usize] {
486 visit(self.nodes[child as usize]);
487 }
488 child = self.subtree_ends[child as usize];
489 }
490 }
491
492 fn reverse_named_preorder(self, root: Node<'tree>) -> Vec<Node<'tree>> {
493 match self.position(root) {
494 Some(0) => self.reverse_named.clone(),
495 Some(position) => self.reverse_named_from(position),
496 None => Direct.reverse_named_preorder(root),
497 }
498 }
499}