1use calcit_core::calcit::Calcit;
8use calcit_core::program::{PROGRAM_CODE_DATA, ProgramCodeData};
9use serde::{Deserialize, Serialize};
10use std::collections::{HashMap, HashSet};
11
12#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct CallTreeNode {
15 pub ns: String,
17 pub def: String,
19 pub fqn: String,
21 #[serde(skip_serializing_if = "Option::is_none")]
23 pub doc: Option<String>,
24 #[serde(skip_serializing_if = "Vec::is_empty")]
26 pub calls: Vec<CallTreeNode>,
27 #[serde(skip_serializing_if = "std::ops::Not::not")]
29 pub circular: bool,
30 #[serde(skip_serializing_if = "std::ops::Not::not")]
32 pub seen: bool,
33 pub source: String,
35}
36
37#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct CallTreeResult {
40 pub entry: String,
42 pub tree: CallTreeNode,
44 pub stats: CallTreeStats,
46 #[serde(skip_serializing_if = "Option::is_none")]
48 pub unused_definitions: Option<Vec<UnusedDefinition>>,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
53pub struct CallTreeStats {
54 pub reachable_count: usize,
56 pub circular_count: usize,
58 pub project_defs: usize,
60 pub core_defs: usize,
62 pub max_depth: usize,
64}
65
66#[derive(Debug, Clone, Serialize, Deserialize)]
68pub struct UnusedDefinition {
69 pub ns: String,
71 pub def: String,
73 pub fqn: String,
75 #[serde(skip_serializing_if = "Option::is_none")]
77 pub doc: Option<String>,
78}
79
80#[derive(Debug, Clone, Default)]
82pub struct CallTreeConfig {
83 pub include_core: bool,
85 pub max_depth: usize,
87 pub show_unused: bool,
89 pub package_name: Option<String>,
91 pub ns_prefix: Option<String>,
93}
94
95pub struct CallTreeAnalyzer {
97 config: CallTreeConfig,
98 visited: HashSet<String>,
100 expanded: HashMap<String, bool>,
102 reachable: HashSet<String>,
104 circular_count: usize,
106 max_depth: usize,
108}
109
110impl CallTreeAnalyzer {
111 pub fn new(config: CallTreeConfig) -> Self {
112 CallTreeAnalyzer {
113 config,
114 visited: HashSet::new(),
115 expanded: HashMap::new(),
116 reachable: HashSet::new(),
117 circular_count: 0,
118 max_depth: 0,
119 }
120 }
121
122 pub fn analyze(&mut self, entry_ns: &str, entry_def: &str) -> Result<CallTreeResult, String> {
124 let fqn = format!("{entry_ns}/{entry_def}");
125
126 let mut tree = self.build_tree(entry_ns, entry_def, 0)?;
128
129 let full_reachable = if self.config.show_unused && self.config.max_depth > 0 {
132 let mut full_analyzer = Self::new(CallTreeConfig {
133 max_depth: 0,
134 show_unused: false,
135 ..self.config.clone()
136 });
137 let _ = full_analyzer.build_tree(entry_ns, entry_def, 0)?;
138 Some(full_analyzer.reachable)
139 } else {
140 None
141 };
142
143 if let Some(ref prefix) = self.config.ns_prefix {
146 tree = prune_tree_by_ns_prefix(tree, prefix);
147 }
148
149 let program_code = PROGRAM_CODE_DATA.read().map_err(|e| format!("Failed to read program code: {e}"))?;
151
152 let (reachable_count, project_defs, core_defs, circular_count, max_depth) = if self.config.ns_prefix.is_some() {
154 compute_stats_from_tree(&tree, |ns| self.is_core_ns(ns))
155 } else {
156 let (project_defs, core_defs) = self.count_def_types(&program_code);
157 (self.reachable.len(), project_defs, core_defs, self.circular_count, self.max_depth)
158 };
159
160 let stats = CallTreeStats {
161 reachable_count,
162 circular_count,
163 project_defs,
164 core_defs,
165 max_depth,
166 };
167
168 let unused_definitions = if self.config.show_unused {
170 Some(self.find_unused_definitions(&program_code, full_reachable.as_ref().unwrap_or(&self.reachable)))
171 } else {
172 None
173 };
174
175 Ok(CallTreeResult {
176 entry: fqn,
177 tree,
178 stats,
179 unused_definitions,
180 })
181 }
182
183 fn build_tree(&mut self, ns: &str, def: &str, depth: usize) -> Result<CallTreeNode, String> {
184 let fqn = format!("{ns}/{def}");
185
186 if depth > self.max_depth {
188 self.max_depth = depth;
189 }
190
191 if self.config.max_depth > 0 && depth >= self.config.max_depth {
193 return Ok(CallTreeNode {
194 ns: ns.to_string(),
195 def: def.to_string(),
196 fqn: fqn.clone(),
197 doc: None,
198 calls: vec![],
199 circular: false,
200 seen: false,
201 source: self.get_source_type(ns),
202 });
203 }
204
205 if self.visited.contains(&fqn) {
207 self.circular_count += 1;
208 return Ok(CallTreeNode {
209 ns: ns.to_string(),
210 def: def.to_string(),
211 fqn: fqn.clone(),
212 doc: None,
213 calls: vec![],
214 circular: true,
215 seen: false,
216 source: self.get_source_type(ns),
217 });
218 }
219
220 if let Some(&had_children) = self.expanded.get(&fqn) {
222 return Ok(CallTreeNode {
223 ns: ns.to_string(),
224 def: def.to_string(),
225 fqn: fqn.clone(),
226 doc: None,
227 calls: vec![],
228 circular: false,
229 seen: had_children,
231 source: self.get_source_type(ns),
232 });
233 }
234
235 self.visited.insert(fqn.clone());
237 self.reachable.insert(fqn.clone());
238
239 let program_code = PROGRAM_CODE_DATA.read().map_err(|e| format!("Failed to read program code: {e}"))?;
240
241 let (code_entry, doc) = match program_code.get(ns) {
243 Some(file_data) => match file_data.defs.get(def) {
244 Some(entry) => {
245 let doc = if entry.doc.is_empty() { None } else { Some(entry.doc.to_string()) };
246 (Some(&entry.code), doc)
247 }
248 None => (None, None),
249 },
250 None => (None, None),
251 };
252
253 let mut calls = vec![];
255 if let Some(code) = code_entry {
256 let call_refs = self.extract_calls(code, ns);
257
258 drop(program_code);
260
261 for (call_ns, call_def) in call_refs {
262 if !self.config.include_core && self.is_core_ns(&call_ns) {
264 continue;
265 }
266
267 if call_ns == ns && call_def == def {
269 continue;
270 }
271
272 let child_tree = self.build_tree(&call_ns, &call_def, depth + 1)?;
273 calls.push(child_tree);
274 }
275 } else {
276 drop(program_code);
277 }
278
279 self.visited.remove(&fqn);
281
282 self.expanded.insert(fqn.clone(), !calls.is_empty());
284
285 Ok(CallTreeNode {
286 ns: ns.to_string(),
287 def: def.to_string(),
288 fqn,
289 doc,
290 calls,
291 circular: false,
292 seen: false,
293 source: self.get_source_type(ns),
294 })
295 }
296
297 fn is_quote_head(head: &Calcit) -> bool {
298 matches!(head, Calcit::Syntax(calcit_core::calcit::CalcitSyntax::Quote, _))
299 || matches!(head, Calcit::Symbol { sym, .. } if sym.as_ref() == "quote")
300 }
301
302 fn is_quasiquote_head(head: &Calcit) -> bool {
303 matches!(head, Calcit::Syntax(calcit_core::calcit::CalcitSyntax::Quasiquote, _))
304 || matches!(head, Calcit::Symbol { sym, .. } if sym.as_ref() == "quasiquote")
305 }
306
307 fn is_unquote_head(head: &Calcit) -> bool {
308 matches!(
309 head,
310 Calcit::Syntax(
311 calcit_core::calcit::CalcitSyntax::MacroInterpolate | calcit_core::calcit::CalcitSyntax::MacroInterpolateSpread,
312 _,
313 )
314 ) || matches!(head, Calcit::Symbol { sym, .. } if matches!(sym.as_ref(), "~" | "~@" | "unquote" | "unquote-splicing"))
315 }
316
317 fn extract_quasiquote_unquotes_recursive(code: &Calcit, current_ns: &str, calls: &mut Vec<(String, String)>) {
318 if let Calcit::List(list) = code {
319 if let Some(head) = list.first() {
320 if Self::is_quote_head(head) {
321 return;
322 }
323 if Self::is_unquote_head(head) {
324 for item in list.iter().skip(1) {
325 Self::extract_calls_recursive(item, current_ns, calls);
326 }
327 return;
328 }
329 }
330 for item in list.iter() {
331 Self::extract_quasiquote_unquotes_recursive(item, current_ns, calls);
332 }
333 }
334 }
335
336 fn extract_calls(&self, code: &Calcit, current_ns: &str) -> Vec<(String, String)> {
338 let mut calls = vec![];
339 Self::extract_calls_recursive(code, current_ns, &mut calls);
340 let mut seen = HashSet::new();
342 calls.retain(|item| seen.insert(item.clone()));
343 calls
344 }
345
346 fn extract_calls_recursive(code: &Calcit, current_ns: &str, calls: &mut Vec<(String, String)>) {
347 match code {
348 Calcit::Import(import) => {
349 calls.push((import.ns.to_string(), import.def.to_string()));
350 }
351 Calcit::Symbol { sym, info, .. } => {
352 let program_code = PROGRAM_CODE_DATA.read().ok();
354 if let Some(ref code_data) = program_code {
355 let mut found = false;
356
357 if let Some(file_data) = code_data.get(current_ns)
359 && file_data.defs.contains_key(sym.as_ref())
360 {
361 calls.push((current_ns.to_string(), sym.to_string()));
362 found = true;
363 }
364
365 if !found
367 && let Some(file_data) = code_data.get(info.at_ns.as_ref())
368 && let Some(import_rule) = file_data.import_map.get(sym.as_ref())
369 {
370 match &**import_rule {
371 calcit_core::program::ImportRule::NsReferDef(ns, def) => {
372 calls.push((ns.to_string(), def.to_string()));
373 found = true;
374 }
375 calcit_core::program::ImportRule::NsAs(ns) => {
376 let _ = ns;
379 }
380 calcit_core::program::ImportRule::NsDefault(ns) => {
381 calls.push((ns.to_string(), "default".to_string()));
382 found = true;
383 }
384 }
385 }
386
387 if !found
389 && let Some((prefix, target_def)) = sym.split_once('/')
390 && let Some(file_data) = code_data.get(info.at_ns.as_ref())
391 && let Some(import_rule) = file_data.import_map.get(prefix)
392 && let calcit_core::program::ImportRule::NsAs(ns) = &**import_rule
393 && code_data
394 .get(ns.as_ref())
395 .is_some_and(|target_file| target_file.defs.contains_key(target_def))
396 {
397 calls.push((ns.to_string(), target_def.to_string()));
398 found = true;
399 }
400
401 if !found
404 && current_ns != "calcit.core"
405 && let Some(core_data) = code_data.get("calcit.core")
406 && core_data.defs.contains_key(sym.as_ref())
407 {
408 calls.push(("calcit.core".to_string(), sym.to_string()));
409 }
410 }
411 }
412 Calcit::List(list) => {
413 if let Some(head) = list.first() {
414 if Self::is_quote_head(head) {
415 return;
416 }
417 if Self::is_quasiquote_head(head) {
418 for item in list.iter().skip(1) {
419 Self::extract_quasiquote_unquotes_recursive(item, current_ns, calls);
420 }
421 return;
422 }
423 }
424 list
425 .traverse_result::<String>(&mut |item| {
426 Self::extract_calls_recursive(item, current_ns, calls);
427 Ok(())
428 })
429 .ok();
430 }
431 Calcit::Fn { info, .. } => {
432 for expr in info.body.iter() {
434 Self::extract_calls_recursive(expr, current_ns, calls);
435 }
436 }
437 Calcit::Macro { info, .. } => {
438 for expr in info.body.iter() {
440 Self::extract_calls_recursive(expr, current_ns, calls);
441 }
442 }
443 Calcit::Thunk(thunk) => match thunk {
444 calcit_core::calcit::CalcitThunk::Code { code, .. } => {
445 Self::extract_calls_recursive(code, current_ns, calls);
446 }
447 },
448 Calcit::Enum(enum_value) => {
449 for item in enum_value.extra.iter() {
450 Self::extract_calls_recursive(item, current_ns, calls);
451 }
452 }
453 Calcit::Map(map) => {
454 for (k, v) in map.iter() {
455 Self::extract_calls_recursive(k, current_ns, calls);
456 Self::extract_calls_recursive(v, current_ns, calls);
457 }
458 }
459 Calcit::Set(set) => {
460 for item in set.iter() {
461 Self::extract_calls_recursive(item, current_ns, calls);
462 }
463 }
464 _ => {}
466 }
467 }
468
469 fn get_source_type(&self, ns: &str) -> String {
470 if self.is_core_ns(ns) {
471 "core".to_string()
472 } else if let Some(ref pkg) = self.config.package_name {
473 if ns.starts_with(pkg) || ns.starts_with(&format!("{pkg}.")) {
474 "project".to_string()
475 } else {
476 "external".to_string()
477 }
478 } else {
479 "project".to_string()
480 }
481 }
482
483 fn is_core_ns(&self, ns: &str) -> bool {
484 calcit_core::calcit::is_bundled_core_ns(ns)
485 }
486
487 fn count_def_types(&self, _program_code: &ProgramCodeData) -> (usize, usize) {
488 let mut project = 0;
489 let mut core = 0;
490
491 for fqn in &self.reachable {
492 if let Some((ns, _)) = fqn.split_once('/') {
493 if self.is_core_ns(ns) {
494 core += 1;
495 } else {
496 project += 1;
497 }
498 }
499 }
500
501 (project, core)
502 }
503
504 fn find_unused_definitions(&self, program_code: &ProgramCodeData, reachable: &HashSet<String>) -> Vec<UnusedDefinition> {
505 let mut unused = vec![];
506
507 for (ns, file_data) in program_code.iter() {
508 if self.is_core_ns(ns) {
510 continue;
511 }
512
513 if let Some(ref pkg) = self.config.package_name
515 && !ns.starts_with(pkg)
516 && !ns.starts_with(&format!("{pkg}."))
517 {
518 continue;
519 }
520
521 if let Some(ref prefix) = self.config.ns_prefix
523 && !ns.starts_with(prefix)
524 {
525 continue;
526 }
527
528 for (def, entry) in &file_data.defs {
529 let fqn = format!("{ns}/{def}");
530 if !reachable.contains(&fqn) {
531 unused.push(UnusedDefinition {
532 ns: ns.to_string(),
533 def: def.to_string(),
534 fqn,
535 doc: if entry.doc.is_empty() { None } else { Some(entry.doc.to_string()) },
536 });
537 }
538 }
539 }
540
541 unused.sort_by(|a, b| match a.ns.cmp(&b.ns) {
543 std::cmp::Ordering::Equal => a.def.cmp(&b.def),
544 other => other,
545 });
546
547 unused
548 }
549}
550
551fn prune_tree_by_ns_prefix(mut node: CallTreeNode, prefix: &str) -> CallTreeNode {
554 let children = std::mem::take(&mut node.calls);
556 let pruned_children: Vec<CallTreeNode> = children
557 .into_iter()
558 .map(|child| prune_tree_by_ns_prefix(child, prefix))
559 .filter(|child| tree_contains_ns_prefix(child, prefix))
560 .collect();
561
562 node.calls = pruned_children;
564
565 node
566}
567
568fn tree_contains_ns_prefix(node: &CallTreeNode, prefix: &str) -> bool {
569 if node.ns.starts_with(prefix) {
570 return true;
571 }
572 for c in &node.calls {
573 if tree_contains_ns_prefix(c, prefix) {
574 return true;
575 }
576 }
577 false
578}
579
580fn compute_stats_from_tree<F>(root: &CallTreeNode, is_core_ns: F) -> (usize, usize, usize, usize, usize)
582where
583 F: Fn(&str) -> bool,
584{
585 use std::collections::HashSet;
586
587 struct WalkState {
588 visited: HashSet<String>,
589 project: usize,
590 core: usize,
591 circular: usize,
592 max_depth: usize,
593 }
594
595 fn walk<F>(n: &CallTreeNode, depth: usize, state: &mut WalkState, is_core_ns: &F)
596 where
597 F: Fn(&str) -> bool,
598 {
599 if depth > state.max_depth {
600 state.max_depth = depth;
601 }
602 if n.circular {
603 state.circular += 1;
604 }
605 if !state.visited.contains(&n.fqn) {
606 state.visited.insert(n.fqn.clone());
607 if is_core_ns(&n.ns) {
608 state.core += 1;
609 } else {
610 state.project += 1;
611 }
612 }
613 for c in &n.calls {
614 walk(c, depth + 1, state, is_core_ns);
615 }
616 }
617
618 let mut state = WalkState {
619 visited: HashSet::new(),
620 project: 0,
621 core: 0,
622 circular: 0,
623 max_depth: 0,
624 };
625
626 walk(root, 0, &mut state, &is_core_ns);
627
628 (state.visited.len(), state.project, state.core, state.circular, state.max_depth)
629}
630
631pub fn format_for_llm(result: &CallTreeResult) -> String {
633 let mut output = String::new();
634
635 output.push_str("# Call Tree Analysis\n\n");
636 output.push_str(&format!("**Entry Point:** `{}`\n\n", result.entry));
637
638 output.push_str("## Statistics\n\n");
639 output.push_str(&format!("- Reachable definitions: {}\n", result.stats.reachable_count));
640 output.push_str(&format!("- Project definitions: {}\n", result.stats.project_defs));
641 output.push_str(&format!("- Core/library definitions: {}\n", result.stats.core_defs));
642 output.push_str(&format!("- Maximum call depth: {}\n", result.stats.max_depth));
643 if result.stats.circular_count > 0 {
644 output.push_str(&format!("- Circular references: {}\n", result.stats.circular_count));
645 }
646 output.push('\n');
647
648 output.push_str("## Call Tree Structure\n\n");
649 output.push_str("```\n");
650 format_tree_node(&result.tree, &mut output, "", true);
651 output.push_str("```\n\n");
652
653 if let Some(ref unused) = result.unused_definitions {
654 output.push_str("## Definitions Unreachable from This Entry\n\n");
655 if unused.is_empty() {
656 output.push_str("Every analyzed definition is reachable from this entry.\n");
657 } else {
658 output.push_str(&format!(
659 "Found {} definition(s) unreachable from this entry. They may be dead code, or entry points called externally:\n\n",
660 unused.len()
661 ));
662 for def in unused {
663 output.push_str(&format!("- `{}`", def.fqn));
664 if let Some(ref doc) = def.doc {
665 output.push_str(&format!(" - {doc}"));
666 }
667 output.push('\n');
668 }
669 }
670 }
671
672 output
673}
674
675fn format_tree_node(node: &CallTreeNode, output: &mut String, prefix: &str, is_last: bool) {
676 let connector = if is_last { "└── " } else { "├── " };
677 let marker = if node.circular {
678 " [CIRCULAR]"
679 } else if node.seen {
680 " [seen]"
681 } else if node.source == "core" {
682 " [core]"
683 } else if node.source == "external" {
684 " [ext]"
685 } else {
686 ""
687 };
688
689 output.push_str(&format!("{}{}{}{}\n", prefix, connector, node.fqn, marker));
690
691 let child_prefix = format!("{}{} ", prefix, if is_last { " " } else { "│" });
692
693 for (i, child) in node.calls.iter().enumerate() {
694 let is_last_child = i == node.calls.len() - 1;
695 format_tree_node(child, output, &child_prefix, is_last_child);
696 }
697}
698
699pub fn format_as_json(result: &CallTreeResult) -> Result<String, String> {
701 serde_json::to_string_pretty(result).map_err(|e| format!("Failed to serialize to JSON: {e}"))
702}
703
704pub fn analyze_call_graph(
706 entry_ns: &str,
707 entry_def: &str,
708 include_core: bool,
709 max_depth: usize,
710 show_unused: bool,
711 package_name: Option<String>,
712 ns_prefix: Option<String>,
713) -> Result<CallTreeResult, String> {
714 let config = CallTreeConfig {
715 include_core,
716 max_depth,
717 show_unused,
718 package_name,
719 ns_prefix,
720 };
721
722 let mut analyzer = CallTreeAnalyzer::new(config);
723 analyzer.analyze(entry_ns, entry_def)
724}
725
726pub fn reachable_definitions(roots: &[(String, String)]) -> HashSet<(String, String)> {
730 let mut reachable = HashSet::new();
731 let mut pending: Vec<(String, String)> = roots.to_vec();
732 while let Some((ns, def)) = pending.pop() {
733 if calcit_core::calcit::is_bundled_core_ns(&ns) || !reachable.insert((ns.clone(), def.clone())) {
734 continue;
735 }
736 let code = {
737 let Ok(program_code) = PROGRAM_CODE_DATA.read() else {
738 break;
739 };
740 match program_code.get(ns.as_str()).and_then(|file| file.defs.get(def.as_str())) {
741 Some(entry) => entry.code.to_owned(),
742 None => continue,
743 }
744 };
745 let mut calls = vec![];
746 CallTreeAnalyzer::extract_calls_recursive(&code, &ns, &mut calls);
747 collect_qualified_references(&code, &mut calls);
748 pending.extend(calls.into_iter().filter(|call| !reachable.contains(call)));
749 }
750 reachable
751}
752
753fn collect_qualified_references(code: &Calcit, calls: &mut Vec<(String, String)>) {
754 match code {
755 Calcit::Symbol { sym, info, .. } => {
756 let Some((prefix, def)) = sym.split_once('/') else {
757 return;
758 };
759 if prefix.is_empty() || def.is_empty() {
760 return;
761 }
762 let Ok(program_code) = PROGRAM_CODE_DATA.read() else {
763 return;
764 };
765 let target_ns = match program_code
766 .get(info.at_ns.as_ref())
767 .and_then(|file| file.import_map.get(prefix))
768 .map(|rule| &**rule)
769 {
770 Some(calcit_core::program::ImportRule::NsAs(ns)) => Some(ns.to_string()),
771 _ => program_code.contains_key(prefix).then(|| prefix.to_owned()),
772 };
773 if let Some(target_ns) = target_ns
774 && program_code.get(target_ns.as_str()).is_some_and(|file| file.defs.contains_key(def))
775 {
776 calls.push((target_ns, def.to_owned()));
777 }
778 }
779 Calcit::List(list) => {
780 list
781 .traverse_result::<String>(&mut |item| {
782 collect_qualified_references(item, calls);
783 Ok(())
784 })
785 .ok();
786 }
787 _ => {}
788 }
789}
790
791#[derive(Debug, Clone, Serialize, Deserialize)]
797pub struct CallCountResult {
798 pub entry: String,
800 pub counts: Vec<CallCountEntry>,
802 pub total_definitions: usize,
804 pub total_calls: usize,
806}
807
808#[derive(Debug, Clone, Serialize, Deserialize)]
810pub struct CallCountEntry {
811 pub fqn: String,
813 pub ns: String,
815 pub def: String,
817 pub count: usize,
819 pub source: String,
821 pub has_doc: bool,
823 pub examples_count: usize,
825}
826
827struct CallCountAnalyzer {
829 include_core: bool,
831 ns_prefix: Option<String>,
833 visited: HashSet<String>,
835 call_counts: HashMap<String, usize>,
837}
838
839impl CallCountAnalyzer {
840 fn new(include_core: bool, ns_prefix: Option<String>) -> Self {
841 CallCountAnalyzer {
842 include_core,
843 ns_prefix,
844 visited: HashSet::new(),
845 call_counts: HashMap::new(),
846 }
847 }
848
849 fn analyze(&mut self, entry_ns: &str, entry_def: &str) -> Result<CallCountResult, String> {
850 let fqn = format!("{entry_ns}/{entry_def}");
851
852 let entry_is_core = self.is_core_ns(entry_ns);
854 let entry_matches_core = self.include_core || !entry_is_core;
855 let entry_matches_prefix = self.ns_prefix.as_deref().is_none_or(|p| entry_ns.starts_with(p));
856 if entry_matches_core && entry_matches_prefix {
857 *self.call_counts.entry(fqn).or_insert(0) += 1;
858 }
859
860 self.traverse(entry_ns, entry_def)?;
862
863 let program_code = PROGRAM_CODE_DATA.read().map_err(|e| format!("Failed to read program code: {e}"))?;
865
866 let mut counts: Vec<CallCountEntry> = self
867 .call_counts
868 .iter()
869 .map(|(fqn, &count)| {
870 let (ns, def) = fqn.split_once('/').unwrap_or(("", fqn));
871
872 let (has_doc, examples_count) = program_code
874 .get(ns)
875 .and_then(|file_data| file_data.defs.get(def))
876 .map(|code_entry| {
877 let has_doc = !code_entry.doc.is_empty();
878 let examples_count = code_entry.examples.len();
879 (has_doc, examples_count)
880 })
881 .unwrap_or((false, 0));
882
883 CallCountEntry {
884 fqn: fqn.clone(),
885 ns: ns.to_string(),
886 def: def.to_string(),
887 count,
888 source: self.get_source_type(ns),
889 has_doc,
890 examples_count,
891 }
892 })
893 .collect();
894
895 counts.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.fqn.cmp(&b.fqn)));
897
898 let total_calls: usize = counts.iter().map(|e| e.count).sum();
899
900 Ok(CallCountResult {
901 entry: format!("{entry_ns}/{entry_def}"),
902 total_definitions: counts.len(),
903 total_calls,
904 counts,
905 })
906 }
907
908 fn traverse(&mut self, ns: &str, def: &str) -> Result<(), String> {
909 let fqn = format!("{ns}/{def}");
910
911 if self.visited.contains(&fqn) {
913 return Ok(());
914 }
915 self.visited.insert(fqn);
916
917 let program_code = PROGRAM_CODE_DATA.read().map_err(|e| format!("Failed to read program code: {e}"))?;
918
919 let code_entry = match program_code.get(ns) {
921 Some(file_data) => file_data.defs.get(def).map(|e| &e.code),
922 None => None,
923 };
924
925 if let Some(code) = code_entry {
927 let call_refs = self.extract_calls(code, ns);
928
929 drop(program_code);
931
932 for (call_ns, call_def) in call_refs {
933 let is_core = self.is_core_ns(&call_ns);
934 let matches_core = self.include_core || !is_core;
935 let matches_prefix = self.ns_prefix.as_deref().is_none_or(|p| call_ns.starts_with(p));
936
937 if matches_core && matches_prefix {
939 let call_fqn = format!("{call_ns}/{call_def}");
940 *self.call_counts.entry(call_fqn).or_insert(0) += 1;
941 }
942
943 self.traverse(&call_ns, &call_def)?;
945 }
946 }
947
948 Ok(())
949 }
950
951 fn extract_calls(&self, code: &Calcit, current_ns: &str) -> Vec<(String, String)> {
952 let mut calls = vec![];
953 CallTreeAnalyzer::extract_calls_recursive(code, current_ns, &mut calls);
954 calls
955 }
956
957 fn is_core_ns(&self, ns: &str) -> bool {
958 calcit_core::calcit::is_bundled_core_ns(ns)
959 }
960
961 fn get_source_type(&self, ns: &str) -> String {
962 if self.is_core_ns(ns) {
963 "core".to_string()
964 } else {
965 "project".to_string()
966 }
967 }
968}
969
970pub fn count_calls(entry_ns: &str, entry_def: &str, include_core: bool, ns_prefix: Option<String>) -> Result<CallCountResult, String> {
972 let mut analyzer = CallCountAnalyzer::new(include_core, ns_prefix);
973 analyzer.analyze(entry_ns, entry_def)
974}
975
976#[derive(Debug, Clone, Copy, PartialEq, Eq)]
978pub enum CallCountSort {
979 Count,
981 Name,
983}
984
985impl CallCountSort {
986 pub fn parse(raw: &str) -> Result<Self, String> {
987 match raw {
988 "count" => Ok(Self::Count),
989 "name" => Ok(Self::Name),
990 other => Err(format!("Unknown call count sort `{other}`; expected `count` or `name`.")),
991 }
992 }
993}
994
995fn sorted_counts(result: &CallCountResult, sort: CallCountSort) -> Vec<CallCountEntry> {
996 let mut counts = result.counts.clone();
997 match sort {
998 CallCountSort::Name => counts.sort_by(|a, b| a.fqn.cmp(&b.fqn)),
999 CallCountSort::Count => counts.sort_by(|a, b| b.count.cmp(&a.count).then_with(|| a.fqn.cmp(&b.fqn))),
1000 }
1001 counts
1002}
1003
1004pub fn format_count_for_display(result: &CallCountResult, sort: CallCountSort) -> String {
1006 let mut output = String::new();
1007
1008 output.push_str("# Call Count Analysis\n\n");
1009 output.push_str(&format!("**Entry Point:** `{}`\n\n", result.entry));
1010 output.push_str(&format!("**Total Definitions:** {}\n", result.total_definitions));
1011 output.push_str(&format!("**Total Calls:** {}\n\n", result.total_calls));
1012
1013 output.push_str("## Call Counts\n\n");
1014 output.push_str("| Count | Definition | Doc | Examples |\n");
1015 output.push_str("|------:|:-----------------------------------------|:---:|:--------:|\n");
1016
1017 let counts = sorted_counts(result, sort);
1018
1019 for entry in &counts {
1020 let doc_mark = if entry.has_doc { "✓" } else { " " };
1021 let examples_str = if entry.examples_count > 0 {
1022 format!("{:>8}", entry.examples_count)
1023 } else {
1024 format!("{:>8}", "")
1025 };
1026
1027 let count_str = format!("{:>5}", entry.count);
1029
1030 let def_str = format!("{:<40}", entry.fqn);
1032
1033 output.push_str(&format!("| {count_str} | {def_str} | {doc_mark} | {examples_str} |\n"));
1034 }
1035
1036 output
1037}
1038
1039pub fn format_count_as_json(result: &CallCountResult, sort: CallCountSort) -> Result<String, String> {
1041 let sorted = CallCountResult {
1042 counts: sorted_counts(result, sort),
1043 ..result.clone()
1044 };
1045 serde_json::to_string_pretty(&sorted).map_err(|e| format!("Failed to serialize to JSON: {e}"))
1046}
1047
1048#[cfg(test)]
1049mod tests {
1050 use super::*;
1051
1052 #[test]
1053 fn unused_report_explains_entry_relative_limit() {
1054 let result = CallTreeResult {
1055 entry: "app.main/main!".to_string(),
1056 tree: CallTreeNode {
1057 ns: "app.main".to_string(),
1058 def: "main!".to_string(),
1059 fqn: "app.main/main!".to_string(),
1060 doc: None,
1061 calls: vec![],
1062 circular: false,
1063 seen: false,
1064 source: "project".to_string(),
1065 },
1066 stats: CallTreeStats {
1067 reachable_count: 1,
1068 circular_count: 0,
1069 project_defs: 1,
1070 core_defs: 0,
1071 max_depth: 0,
1072 },
1073 unused_definitions: Some(vec![UnusedDefinition {
1074 ns: "app.api".to_string(),
1075 def: "handler".to_string(),
1076 fqn: "app.api/handler".to_string(),
1077 doc: None,
1078 }]),
1079 };
1080
1081 let output = format_for_llm(&result);
1082 assert!(output.contains("Definitions Unreachable from This Entry"));
1083 assert!(output.contains("may be dead code, or entry points called externally"));
1084 }
1085}