1use super::types::{DepGraph, IndexSymbol, IndexSymbolKind, SymbolIndex, Visibility};
7use serde::Serialize;
8
9#[derive(Debug, Clone, Serialize)]
11pub struct SymbolInfo {
12 pub id: u32,
14 pub name: String,
16 pub kind: String,
18 pub file: String,
20 pub line: u32,
22 pub end_line: u32,
24 pub signature: Option<String>,
26 pub visibility: String,
28}
29
30#[derive(Debug, Clone, Serialize)]
32pub struct ReferenceInfo {
33 pub symbol: SymbolInfo,
35 pub kind: String,
37}
38
39#[derive(Debug, Clone, Serialize)]
41pub struct CallGraphEdge {
42 pub caller_id: u32,
44 pub callee_id: u32,
46 pub caller: String,
48 pub callee: String,
50 pub file: String,
52 pub line: u32,
54}
55
56#[derive(Debug, Clone, Serialize)]
58pub struct CallGraph {
59 pub nodes: Vec<SymbolInfo>,
61 pub edges: Vec<CallGraphEdge>,
63 pub stats: CallGraphStats,
65}
66
67#[derive(Debug, Clone, Serialize)]
69pub struct CallGraphStats {
70 pub total_symbols: usize,
72 pub total_calls: usize,
74 pub functions: usize,
76 pub classes: usize,
78}
79
80impl SymbolInfo {
81 pub fn from_index_symbol(sym: &IndexSymbol, index: &SymbolIndex) -> Self {
83 let file_path = index
84 .get_file_by_id(sym.file_id.as_u32())
85 .map(|f| f.path.clone())
86 .unwrap_or_else(|| "<unknown>".to_owned());
87
88 Self {
89 id: sym.id.as_u32(),
90 name: sym.name.clone(),
91 kind: format_symbol_kind(sym.kind),
92 file: file_path,
93 line: sym.span.start_line,
94 end_line: sym.span.end_line,
95 signature: sym.signature.clone(),
96 visibility: format_visibility(sym.visibility),
97 }
98 }
99}
100
101pub fn find_symbol(index: &SymbolIndex, name: &str) -> Vec<SymbolInfo> {
106 let mut results: Vec<SymbolInfo> = index
107 .find_symbols(name)
108 .into_iter()
109 .map(|sym| SymbolInfo::from_index_symbol(sym, index))
110 .collect();
111
112 results.sort_by(|a, b| (&a.file, a.line).cmp(&(&b.file, b.line)));
114 results.dedup_by(|a, b| a.file == b.file && a.line == b.line);
115
116 results
117}
118
119pub fn get_callers_by_name(index: &SymbolIndex, graph: &DepGraph, name: &str) -> Vec<SymbolInfo> {
123 let mut callers = Vec::new();
124
125 for sym in index.find_symbols(name) {
127 let symbol_id = sym.id.as_u32();
128
129 for caller_id in graph.get_callers(symbol_id) {
131 if let Some(caller_sym) = index.get_symbol(caller_id) {
132 callers.push(SymbolInfo::from_index_symbol(caller_sym, index));
133 }
134 }
135 }
136
137 callers.sort_by_key(|s| s.id);
139 callers.dedup_by_key(|s| s.id);
140
141 callers
142}
143
144pub fn get_callees_by_name(index: &SymbolIndex, graph: &DepGraph, name: &str) -> Vec<SymbolInfo> {
148 let mut callees = Vec::new();
149
150 for sym in index.find_symbols(name) {
152 let symbol_id = sym.id.as_u32();
153
154 for callee_id in graph.get_callees(symbol_id) {
156 if let Some(callee_sym) = index.get_symbol(callee_id) {
157 callees.push(SymbolInfo::from_index_symbol(callee_sym, index));
158 }
159 }
160 }
161
162 callees.sort_by_key(|s| s.id);
164 callees.dedup_by_key(|s| s.id);
165
166 callees
167}
168
169pub fn get_references_by_name(
174 index: &SymbolIndex,
175 graph: &DepGraph,
176 name: &str,
177) -> Vec<ReferenceInfo> {
178 let mut references = Vec::new();
179
180 for sym in index.find_symbols(name) {
182 let symbol_id = sym.id.as_u32();
183
184 for caller_id in graph.get_callers(symbol_id) {
186 if let Some(caller_sym) = index.get_symbol(caller_id) {
187 references.push(ReferenceInfo {
188 symbol: SymbolInfo::from_index_symbol(caller_sym, index),
189 kind: "call".to_owned(),
190 });
191 }
192 }
193
194 for ref_id in graph.get_referencers(symbol_id) {
196 if let Some(ref_sym) = index.get_symbol(ref_id) {
197 if !graph.get_callers(symbol_id).contains(&ref_id) {
199 references.push(ReferenceInfo {
200 symbol: SymbolInfo::from_index_symbol(ref_sym, index),
201 kind: "reference".to_owned(),
202 });
203 }
204 }
205 }
206 }
207
208 references.sort_by_key(|r| r.symbol.id);
210 references.dedup_by_key(|r| r.symbol.id);
211
212 references
213}
214
215pub fn get_call_graph(index: &SymbolIndex, graph: &DepGraph) -> CallGraph {
220 get_call_graph_filtered(index, graph, None, None)
221}
222
223pub fn get_call_graph_filtered(
229 index: &SymbolIndex,
230 graph: &DepGraph,
231 max_nodes: Option<usize>,
232 max_edges: Option<usize>,
233) -> CallGraph {
234 let mut nodes: Vec<SymbolInfo> = index
236 .symbols
237 .iter()
238 .map(|sym| SymbolInfo::from_index_symbol(sym, index))
239 .collect();
240
241 if let Some(limit) = max_nodes {
243 nodes.truncate(limit);
244 }
245
246 let node_ids: std::collections::HashSet<u32> = nodes.iter().map(|n| n.id).collect();
248
249 let mut edges: Vec<CallGraphEdge> = graph
251 .calls
252 .iter()
253 .filter(|(caller, callee)| {
254 max_nodes.is_none() || (node_ids.contains(caller) && node_ids.contains(callee))
256 })
257 .filter_map(|&(caller_id, callee_id)| {
258 let caller_sym = index.get_symbol(caller_id)?;
259 let callee_sym = index.get_symbol(callee_id)?;
260
261 let file_path = index
262 .get_file_by_id(caller_sym.file_id.as_u32())
263 .map(|f| f.path.clone())
264 .unwrap_or_else(|| "<unknown>".to_owned());
265
266 Some(CallGraphEdge {
267 caller_id,
268 callee_id,
269 caller: caller_sym.name.clone(),
270 callee: callee_sym.name.clone(),
271 file: file_path,
272 line: caller_sym.span.start_line,
273 })
274 })
275 .collect();
276
277 if let Some(limit) = max_edges {
279 edges.truncate(limit);
280 }
281
282 let functions = nodes
284 .iter()
285 .filter(|n| n.kind == "function" || n.kind == "method")
286 .count();
287 let classes = nodes
288 .iter()
289 .filter(|n| n.kind == "class" || n.kind == "struct")
290 .count();
291
292 let stats =
293 CallGraphStats { total_symbols: nodes.len(), total_calls: edges.len(), functions, classes };
294
295 CallGraph { nodes, edges, stats }
296}
297
298pub fn get_callers_by_id(index: &SymbolIndex, graph: &DepGraph, symbol_id: u32) -> Vec<SymbolInfo> {
300 graph
301 .get_callers(symbol_id)
302 .into_iter()
303 .filter_map(|id| index.get_symbol(id))
304 .map(|sym| SymbolInfo::from_index_symbol(sym, index))
305 .collect()
306}
307
308pub fn get_callees_by_id(index: &SymbolIndex, graph: &DepGraph, symbol_id: u32) -> Vec<SymbolInfo> {
310 graph
311 .get_callees(symbol_id)
312 .into_iter()
313 .filter_map(|id| index.get_symbol(id))
314 .map(|sym| SymbolInfo::from_index_symbol(sym, index))
315 .collect()
316}
317
318fn format_symbol_kind(kind: IndexSymbolKind) -> String {
321 match kind {
322 IndexSymbolKind::Function => "function",
323 IndexSymbolKind::Method => "method",
324 IndexSymbolKind::Class => "class",
325 IndexSymbolKind::Struct => "struct",
326 IndexSymbolKind::Interface => "interface",
327 IndexSymbolKind::Trait => "trait",
328 IndexSymbolKind::Enum => "enum",
329 IndexSymbolKind::Constant => "constant",
330 IndexSymbolKind::Variable => "variable",
331 IndexSymbolKind::Module => "module",
332 IndexSymbolKind::Import => "import",
333 IndexSymbolKind::Export => "export",
334 IndexSymbolKind::TypeAlias => "type_alias",
335 IndexSymbolKind::Macro => "macro",
336 }
337 .to_owned()
338}
339
340fn format_visibility(vis: Visibility) -> String {
341 match vis {
342 Visibility::Public => "public",
343 Visibility::Private => "private",
344 Visibility::Protected => "protected",
345 Visibility::Internal => "internal",
346 }
347 .to_owned()
348}
349
350#[cfg(test)]
351mod tests {
352 use super::*;
353 use crate::index::types::{FileEntry, FileId, Language, Span, SymbolId};
354
355 fn create_test_index() -> (SymbolIndex, DepGraph) {
356 let mut index = SymbolIndex::default();
357
358 index.files.push(FileEntry {
360 id: FileId::new(0),
361 path: "test.py".to_string(),
362 language: Language::Python,
363 symbols: 0..2,
364 imports: vec![],
365 content_hash: [0u8; 32],
366 lines: 25,
367 tokens: 100,
368 });
369
370 index.symbols.push(IndexSymbol {
372 id: SymbolId::new(0),
373 name: "main".to_string(),
374 kind: IndexSymbolKind::Function,
375 file_id: FileId::new(0),
376 span: Span { start_line: 1, start_col: 0, end_line: 10, end_col: 0 },
377 signature: Some("def main()".to_string()),
378 parent: None,
379 visibility: Visibility::Public,
380 docstring: None,
381 });
382
383 index.symbols.push(IndexSymbol {
384 id: SymbolId::new(1),
385 name: "helper".to_string(),
386 kind: IndexSymbolKind::Function,
387 file_id: FileId::new(0),
388 span: Span { start_line: 12, start_col: 0, end_line: 20, end_col: 0 },
389 signature: Some("def helper()".to_string()),
390 parent: None,
391 visibility: Visibility::Private,
392 docstring: None,
393 });
394
395 index.symbols_by_name.insert("main".to_string(), vec![0]);
397 index.symbols_by_name.insert("helper".to_string(), vec![1]);
398
399 let mut graph = DepGraph::new();
401 graph.add_call(0, 1); (index, graph)
404 }
405
406 #[test]
407 fn test_find_symbol() {
408 let (index, _graph) = create_test_index();
409
410 let results = find_symbol(&index, "main");
411 assert_eq!(results.len(), 1);
412 assert_eq!(results[0].name, "main");
413 assert_eq!(results[0].kind, "function");
414 assert_eq!(results[0].file, "test.py");
415 }
416
417 #[test]
418 fn test_get_callers() {
419 let (index, graph) = create_test_index();
420
421 let callers = get_callers_by_name(&index, &graph, "helper");
423 assert_eq!(callers.len(), 1);
424 assert_eq!(callers[0].name, "main");
425 }
426
427 #[test]
428 fn test_get_callees() {
429 let (index, graph) = create_test_index();
430
431 let callees = get_callees_by_name(&index, &graph, "main");
433 assert_eq!(callees.len(), 1);
434 assert_eq!(callees[0].name, "helper");
435 }
436
437 #[test]
438 fn test_get_call_graph() {
439 let (index, graph) = create_test_index();
440
441 let call_graph = get_call_graph(&index, &graph);
442 assert_eq!(call_graph.nodes.len(), 2);
443 assert_eq!(call_graph.edges.len(), 1);
444 assert_eq!(call_graph.stats.functions, 2);
445
446 assert_eq!(call_graph.edges[0].caller, "main");
448 assert_eq!(call_graph.edges[0].callee, "helper");
449 }
450}