1use streaming_iterator::StreamingIterator;
4use tree_sitter::{Parser, QueryCursor};
5
6use crate::lang::support_for;
7use crate::model::{EdgeKind, SymbolKind};
8
9pub struct RawSymbol {
10 pub name: String,
11 pub kind: SymbolKind,
12 pub start_line: u32,
13 pub end_line: u32,
14 pub signature: Option<String>,
15 pub container: Option<String>,
18}
19
20pub struct RawEdge {
21 pub src_name: Option<String>,
22 pub dst_name: String,
23 pub kind: EdgeKind,
24 pub src_container: Option<String>,
28}
29
30pub fn extract(lang: &str, source: &str) -> Option<(Vec<RawSymbol>, Vec<RawEdge>)> {
31 let support = support_for(lang)?;
32 let mut parser = Parser::new();
33 parser.set_language(&support.language()).ok()?;
34 let tree = parser.parse(source, None)?;
35 let query = support.query();
36 let mut symbols = Vec::new();
37 let mut edges = Vec::new();
38 walk(query, &tree, source.as_bytes(), &mut symbols, &mut edges);
39 Some((symbols, edges))
40}
41
42fn kind_from_suffix(suffix: &str) -> Option<SymbolKind> {
43 match suffix {
44 "function" => Some(SymbolKind::Function),
45 "method" => Some(SymbolKind::Method),
46 "class" => Some(SymbolKind::Class),
47 "struct" => Some(SymbolKind::Struct),
48 "enum" => Some(SymbolKind::Enum),
49 "trait" => Some(SymbolKind::Trait),
50 "interface" => Some(SymbolKind::Interface),
51 "module" => Some(SymbolKind::Module),
52 _ => None,
53 }
54}
55
56fn enclosing_symbol_name<'a>(
57 mut node: tree_sitter::Node<'a>,
58 query: &tree_sitter::Query,
59 source: &[u8],
60) -> Option<String> {
61 let def_kinds = [
66 "function_item", "function_definition", "function_declaration", "method_definition", "arrow_function", ];
72
73 let cap_names: Vec<&str> = query.capture_names().iter().map(|s| s.as_ref()).collect();
75 let has_def_function = cap_names.contains(&"def.function");
76 let has_def_method = cap_names.contains(&"def.method");
77
78 if !has_def_function && !has_def_method {
79 return None;
80 }
81
82 while let Some(parent) = node.parent() {
83 let kind = parent.kind();
84 if def_kinds.contains(&kind) {
85 if let Some(name_node) = parent.child_by_field_name("name") {
87 let name = name_node.utf8_text(source).ok()?.to_string();
88 return Some(name);
89 }
90 }
91 node = parent;
92 }
93 None
94}
95
96fn container_of(name_node: tree_sitter::Node<'_>, source: &[u8]) -> Option<String> {
105 let mut node = name_node;
106 while let Some(parent) = node.parent() {
107 match parent.kind() {
108 "impl_item" => {
111 if let Some(ty) = parent.child_by_field_name("type") {
112 return ty.utf8_text(source).ok().map(str::to_string);
113 }
114 }
115 "mod_item" => {
117 if let Some(n) = parent.child_by_field_name("name") {
118 return n.utf8_text(source).ok().map(str::to_string);
119 }
120 }
121 "class_declaration" | "class_definition" | "class" | "interface_declaration" => {
123 if let Some(n) = parent.child_by_field_name("name") {
124 return n.utf8_text(source).ok().map(str::to_string);
125 }
126 }
127 _ => {}
128 }
129 node = parent;
130 }
131 None
132}
133
134fn walk(
135 query: &tree_sitter::Query,
136 tree: &tree_sitter::Tree,
137 source: &[u8],
138 symbols: &mut Vec<RawSymbol>,
139 edges: &mut Vec<RawEdge>,
140) {
141 let mut cursor = QueryCursor::new();
142 let mut matches = cursor.matches(query, tree.root_node(), source);
143
144 while let Some(m) = matches.next() {
145 for cap in m.captures {
146 let cap_name = &query.capture_names()[cap.index as usize];
147 let node = cap.node;
148
149 if let Some(suffix) = cap_name.strip_prefix("def.") {
150 let Some(kind) = kind_from_suffix(suffix) else {
151 continue;
152 };
153 let def_node = node.parent().unwrap_or(node);
155 let name = node.utf8_text(source).unwrap_or("").to_string();
156 if name.is_empty() {
157 continue;
158 }
159 let start_byte = def_node.start_byte();
161 let end_byte = def_node.end_byte();
162 let def_text = std::str::from_utf8(&source[start_byte..end_byte]).unwrap_or("");
163 let signature = def_text.lines().next().map(|l| l.trim().to_string());
164
165 let start_line = def_node.start_position().row as u32 + 1;
166 let end_line = def_node.end_position().row as u32 + 1;
167
168 if let Some(existing) = symbols
173 .iter_mut()
174 .find(|s: &&mut RawSymbol| s.name == name && s.start_line == start_line)
175 {
176 if kind == SymbolKind::Method && existing.kind == SymbolKind::Function {
177 existing.kind = SymbolKind::Method;
178 existing.container = container_of(node, source);
181 }
182 continue;
183 }
184
185 let container = container_of(node, source);
191
192 symbols.push(RawSymbol {
193 name,
194 kind,
195 start_line,
196 end_line,
197 signature,
198 container,
199 });
200 } else if cap_name.starts_with("call.") {
201 let dst_name = node.utf8_text(source).unwrap_or("").to_string();
202 if dst_name.is_empty() {
203 continue;
204 }
205 let src_name = enclosing_symbol_name(node, query, source);
206 let src_container = container_of(node, source);
207 edges.push(RawEdge {
208 src_name,
209 dst_name,
210 kind: EdgeKind::Calls,
211 src_container,
212 });
213 } else if cap_name.starts_with("import.") {
214 let dst_name = node.utf8_text(source).unwrap_or("").to_string();
215 if dst_name.is_empty() {
216 continue;
217 }
218 edges.push(RawEdge {
219 src_name: None,
220 dst_name,
221 kind: EdgeKind::Imports,
222 src_container: None,
223 });
224 }
225 }
226 }
227}
228
229#[cfg(test)]
230mod tests {
231 use super::*;
232
233 #[test]
234 fn extracts_rust_functions_and_calls() {
235 let src = "fn helper() {}\nfn main() { helper(); }\n";
236 let (symbols, edges) = extract("rust", src).expect("rust supported");
237 let names: Vec<_> = symbols.iter().map(|s| s.name.as_str()).collect();
238 assert!(names.contains(&"helper"));
239 assert!(names.contains(&"main"));
240 assert!(edges
241 .iter()
242 .any(|e| e.dst_name == "helper" && e.src_name.as_deref() == Some("main")));
243 }
244
245 #[test]
246 fn impl_methods_are_not_duplicated() {
247 let src = "struct S;\nimpl S {\n fn method(&self) {}\n}\n";
251 let (symbols, _edges) = extract("rust", src).unwrap();
252 let methods: Vec<_> = symbols.iter().filter(|s| s.name == "method").collect();
253 assert_eq!(methods.len(), 1, "impl method must not be double-counted");
254 assert_eq!(methods[0].kind, SymbolKind::Method);
255 }
256
257 #[test]
258 fn extracts_python_defs() {
259 let src = "def a():\n b()\ndef b():\n pass\n";
260 let (symbols, edges) = extract("python", src).unwrap();
261 assert!(symbols.iter().any(|s| s.name == "a"));
262 assert!(edges
263 .iter()
264 .any(|e| e.dst_name == "b" && e.src_name.as_deref() == Some("a")));
265 }
266
267 #[test]
268 fn extracts_typescript_functions() {
269 let src = "function f() { g(); }\nfunction g() {}\n";
270 let (symbols, edges) = extract("typescript", src).unwrap();
271 assert!(symbols.iter().any(|s| s.name == "f"));
272 assert!(edges
273 .iter()
274 .any(|e| e.dst_name == "g" && e.src_name.as_deref() == Some("f")));
275 }
276}