1use tree_sitter::{Node, Tree};
7
8#[derive(Debug, Default, Clone)]
9pub struct SymbolIndex {
10 pub defs: Vec<(String, usize, usize)>,
12 pub refs: Vec<(String, usize, usize)>,
13}
14
15impl SymbolIndex {
16 pub fn from_tree(tree: &Tree, source: &[u8]) -> Self {
17 let mut idx = SymbolIndex::default();
18 walk(tree.root_node(), source, &mut idx);
19 idx
20 }
21
22 pub fn first_definition(&self, name: &str) -> Option<(usize, usize)> {
24 self.defs
25 .iter()
26 .find(|(n, _, _)| n == name)
27 .map(|(_, s, e)| (*s, *e))
28 }
29
30 pub fn all_references(&self, name: &str) -> Vec<(usize, usize)> {
31 self.refs
32 .iter()
33 .filter(|(n, _, _)| n == name)
34 .map(|(_, s, e)| (*s, *e))
35 .collect()
36 }
37
38 pub fn reference_at(&self, byte_offset: usize) -> Option<&str> {
39 self.refs
40 .iter()
41 .find(|(_, s, e)| *s <= byte_offset && byte_offset < *e)
42 .map(|(n, _, _)| n.as_str())
43 }
44
45 pub fn definition_at(&self, byte_offset: usize) -> Option<&str> {
46 self.defs
47 .iter()
48 .find(|(_, s, e)| *s <= byte_offset && byte_offset < *e)
49 .map(|(n, _, _)| n.as_str())
50 }
51}
52
53fn walk(node: Node, source: &[u8], idx: &mut SymbolIndex) {
54 match node.kind() {
55 "pattern_reference" => {
56 if let Some(id) = node.child_by_field_name("identifier") {
57 if let Ok(text) = id.utf8_text(source) {
58 idx.refs
59 .push((text.to_string(), id.start_byte(), id.end_byte()));
60 }
61 }
62 }
63 "node_pattern" => {
64 if let Some(id) = node.child_by_field_name("identifier") {
65 if let Ok(text) = id.utf8_text(source) {
66 let has_labels = node.child_by_field_name("labels").is_some();
67 let has_record = node.child_by_field_name("record").is_some();
68 if has_labels || has_record {
69 idx.defs
70 .push((text.to_string(), id.start_byte(), id.end_byte()));
71 } else if relationship_parent_field(node).is_some() {
72 idx.refs
74 .push((text.to_string(), id.start_byte(), id.end_byte()));
75 }
76 }
77 }
78 }
79 "subject_pattern" => {
80 if let Some(id) = node.child_by_field_name("identifier") {
81 if let Ok(text) = id.utf8_text(source) {
82 let has_labels = node.child_by_field_name("labels").is_some();
83 let has_record = node.child_by_field_name("record").is_some();
84 if has_labels || has_record {
85 idx.defs
86 .push((text.to_string(), id.start_byte(), id.end_byte()));
87 }
88 }
89 }
90 }
91 _ => {}
92 }
93 let mut c = node.walk();
94 for child in node.children(&mut c) {
95 walk(child, source, idx);
96 }
97}
98
99fn relationship_parent_field(node: Node) -> Option<&'static str> {
101 let parent = node.parent()?;
102 if parent.kind() != "relationship_pattern" {
103 return None;
104 }
105 for field in ["left", "right"] {
106 if let Some(ch) = parent.child_by_field_name(field) {
107 if ch.id() == node.id() {
108 return Some(field);
109 }
110 }
111 }
112 None
113}