1use crate::edge::{Edge, EdgeKind};
8use crate::graph::{ArborGraph, NodeId};
9use crate::symbol_table::{Resolution, SymbolTable};
10use arbor_core::{
11 clean_type_name, field_type_ref, import_alias, local_binding, return_type_ref, runtime_binding,
12 type_relation_ref, typed_receiver, CodeNode, NodeKind, TypeRelationKind, MODULE_FILE_REF,
13};
14use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
15use std::path::{Path, PathBuf};
16use tracing::debug;
17
18const MAX_AMBIGUOUS_FANOUT: usize = 4;
21
22const MAX_UNKNOWN_RECEIVER_FANOUT: usize = 2;
24
25const UNKNOWN_RECEIVER_PENALTY: f32 = 0.55;
29
30const TYPED_RECEIVER_CONFIDENCE: f32 = 0.9;
33
34enum TypedReceiver {
36 Found(Vec<NodeId>),
38 External,
41 Unknown,
44}
45
46pub struct GraphBuilder {
48 graph: ArborGraph,
49 symbol_table: SymbolTable,
50 name_to_id: HashMap<String, String>,
51
52 import_map: HashMap<String, HashMap<String, String>>,
62
63 namespace_imports: HashMap<String, HashMap<String, String>>,
73
74 import_aliases: HashMap<String, HashMap<String, String>>,
82
83 go_packages: HashMap<String, String>,
86
87 import_nodes: Vec<CodeNode>,
90
91 module_files: HashSet<String>,
96
97 runtime_bindings: HashMap<String, HashMap<String, (String, String)>>,
102
103 local_bindings: HashMap<String, HashSet<String>>,
107
108 conflicting_bindings: HashMap<String, HashSet<String>>,
112}
113
114impl Default for GraphBuilder {
115 fn default() -> Self {
116 Self::new()
117 }
118}
119
120impl GraphBuilder {
121 pub fn new() -> Self {
122 Self {
123 graph: ArborGraph::new(),
124 symbol_table: SymbolTable::new(),
125 name_to_id: HashMap::new(),
126 import_map: HashMap::new(),
127 namespace_imports: HashMap::new(),
128 import_aliases: HashMap::new(),
129 go_packages: HashMap::new(),
130 import_nodes: Vec::new(),
131 module_files: HashSet::new(),
132 runtime_bindings: HashMap::new(),
133 local_bindings: HashMap::new(),
134 conflicting_bindings: HashMap::new(),
135 }
136 }
137
138 pub fn add_nodes(&mut self, nodes: Vec<CodeNode>) {
146 for node in nodes {
147 if node.kind == NodeKind::Module && is_go_file(Path::new(&node.file)) {
149 self.go_packages
150 .entry(node.file.clone())
151 .or_insert_with(|| node.name.clone());
152 }
153
154 if node.kind == NodeKind::Import {
157 let file = node.file.clone();
158 let module = node.name.clone();
159 let js = is_js_family_file(Path::new(&file));
160
161 for imported_name in &node.references {
162 if imported_name == MODULE_FILE_REF {
163 self.module_files.insert(file.clone());
164 continue;
165 }
166 if let Some(name) = local_binding(imported_name) {
167 self.local_bindings
168 .entry(file.clone())
169 .or_default()
170 .insert(name.to_string());
171 continue;
172 }
173 if let Some((local, name)) = runtime_binding(imported_name) {
174 self.bind_at_run_time(&file, local, name, &module);
175 continue;
176 }
177 let local = import_alias(imported_name)
178 .map_or(imported_name.as_str(), |(local, _)| local);
179 if js && local != "*" && !imported_name.starts_with("*as:") {
180 if self.binds_from_another_module(&file, local, &module) {
181 self.mark_conflicting(&file, local);
182 continue;
183 }
184 if let Some(bindings) = self.runtime_bindings.get_mut(&file) {
186 bindings.remove(local);
187 }
188 }
189 if let Some(alias) = imported_name.strip_prefix("*as:") {
190 self.namespace_imports
192 .entry(file.clone())
193 .or_default()
194 .insert(alias.to_string(), module.clone());
195 } else if let Some((local, imported)) = import_alias(imported_name) {
196 self.import_map
199 .entry(file.clone())
200 .or_default()
201 .insert(local.to_string(), module.clone());
202 self.import_aliases
203 .entry(file.clone())
204 .or_default()
205 .insert(local.to_string(), imported.to_string());
206 } else {
207 self.import_map
209 .entry(file.clone())
210 .or_default()
211 .insert(imported_name.clone(), module.clone());
212 if let Some(aliases) = self.import_aliases.get_mut(&file) {
214 aliases.remove(imported_name);
215 }
216 }
217 }
218 self.import_nodes.push(node);
224 continue;
225 }
226
227 let id_str = node.id.clone();
228 let name = node.name.clone();
229 let qualified = node.qualified_name.clone();
230 let file = PathBuf::from(&node.file);
231
232 let node_idx = self.graph.add_node(node);
233
234 if !qualified.is_empty() {
235 self.symbol_table
236 .insert(qualified.clone(), node_idx, file.clone());
237 }
238
239 self.name_to_id.insert(name.clone(), id_str.clone());
240 self.name_to_id.insert(qualified, id_str);
241 }
242 }
243
244 pub fn resolve_edges(&mut self) {
260 let mut edges_to_add: Vec<(NodeId, NodeId, f32)> = Vec::new();
261
262 let node_indices: Vec<NodeId> = self.graph.node_indexes().collect();
263
264 for from_idx in node_indices {
265 let (references, from_file) = {
266 let node = self.graph.get(from_idx).unwrap();
267 (node.references.clone(), PathBuf::from(&node.file))
268 };
269
270 let from_file_str = from_file.to_string_lossy().to_string();
271
272 for reference in references {
273 if type_relation_ref(&reference).is_some()
279 || receiver_method(&reference).is_some()
280 || field_type_ref(&reference).is_some()
281 || return_type_ref(&reference).is_some()
282 {
283 continue;
284 }
285
286 if let Some((method, receiver)) = typed_receiver(&reference) {
289 match self.resolve_typed_receiver(method, receiver, &from_file) {
290 TypedReceiver::Found(targets) => {
291 for to_idx in targets {
292 if to_idx != from_idx {
293 edges_to_add.push((
294 from_idx,
295 to_idx,
296 TYPED_RECEIVER_CONFIDENCE,
297 ));
298 }
299 }
300 continue;
301 }
302 TypedReceiver::External => continue,
303 TypedReceiver::Unknown => {}
304 }
305 }
306
307 let (lookup, receiver_unknown) = match typed_receiver(&reference) {
311 Some((method, _)) => (method, true),
312 None => match reference.strip_prefix('.') {
313 Some(method) => (method, true),
314 None => (reference.as_str(), false),
315 },
316 };
317
318 if lookup.is_empty() {
319 continue;
320 }
321
322 let file_imports = self.import_map.get(&from_file_str);
328 let alias = if receiver_unknown {
333 None
334 } else {
335 self.resolve_alias(lookup, &from_file, &from_file_str)
336 };
337 let runtime = if receiver_unknown || alias.is_some() {
340 None
341 } else {
342 self.resolve_runtime_binding(lookup, &from_file, &from_file_str)
343 };
344 let bound_at_run_time = runtime.is_some();
345 let resolution = match alias.or(runtime) {
349 Some(resolution) => resolution,
350 None if !receiver_unknown && lookup.contains("::") => {
351 self.symbol_table.resolve_path(lookup, &from_file)
352 }
353 None => {
354 self.symbol_table
355 .resolve_ref_with_imports(lookup, &from_file, file_imports)
356 }
357 };
358
359 if !resolution.is_resolved() {
360 debug!(
364 "Unresolved reference '{}' in {} (likely external/stdlib)",
365 reference,
366 from_file.display()
367 );
368 continue;
369 }
370
371 let mut base_confidence = resolution.confidence();
372 if receiver_unknown {
373 base_confidence *= UNKNOWN_RECEIVER_PENALTY;
374 }
375 let mut candidates = resolution.candidates();
376 if receiver_unknown && from_file_str.ends_with(".rs") {
380 candidates.retain(|id| {
381 self.graph
382 .get(*id)
383 .is_some_and(|n| n.kind == NodeKind::Method)
384 });
385 if candidates.is_empty() {
386 continue;
387 }
388 }
389
390 let fanout_limit = if receiver_unknown {
394 MAX_UNKNOWN_RECEIVER_FANOUT
395 } else {
396 MAX_AMBIGUOUS_FANOUT
397 };
398
399 if candidates.len() > fanout_limit {
400 debug!(
406 "Reference '{}' in {} has {} candidate definitions — too ambiguous to link",
407 reference,
408 from_file.display(),
409 candidates.len()
410 );
411 continue;
412 }
413
414 for to_idx in candidates {
415 if from_idx == to_idx {
416 continue;
417 }
418
419 let confidence = if receiver_unknown || bound_at_run_time {
425 base_confidence
426 } else {
427 self.apply_import_validation(
428 &reference,
429 &from_file,
430 &from_file_str,
431 to_idx,
432 base_confidence,
433 )
434 };
435
436 if confidence <= 0.0 {
437 continue;
438 }
439
440 edges_to_add.push((from_idx, to_idx, confidence));
441 }
442 }
443 }
444
445 for (from_id, to_id, confidence) in edges_to_add {
446 self.graph.add_edge(
447 from_id,
448 to_id,
449 Edge::new(EdgeKind::Calls).with_confidence(confidence),
450 );
451 }
452 }
453
454 fn resolve_alias(
459 &self,
460 reference: &str,
461 from_file: &Path,
462 from_file_str: &str,
463 ) -> Option<Resolution> {
464 let imported = self.import_aliases.get(from_file_str)?.get(reference)?;
465 let module = self.import_map.get(from_file_str)?.get(reference)?;
466 let defined_here = self
467 .symbol_table
468 .get_file_exports(&from_file.to_path_buf())
469 .is_some_and(|fqns| fqns.iter().any(|fqn| fqn == reference));
470 if defined_here {
471 return None;
472 }
473 Some(
474 self.symbol_table
475 .resolve_imported(imported, module, from_file),
476 )
477 }
478
479 fn resolve_runtime_binding(
488 &self,
489 reference: &str,
490 from_file: &Path,
491 from_file_str: &str,
492 ) -> Option<Resolution> {
493 let (name, module) = self.runtime_bindings.get(from_file_str)?.get(reference)?;
494 let defined_here = self
495 .symbol_table
496 .get_file_exports(&from_file.to_path_buf())
497 .is_some_and(|fqns| fqns.iter().any(|fqn| fqn == reference));
498 if defined_here {
499 return None;
500 }
501 Some(
502 self.symbol_table
503 .resolve_in_module_file(name, module, from_file),
504 )
505 .filter(Resolution::is_resolved)
506 }
507
508 fn bind_at_run_time(&mut self, file: &str, local: &str, name: &str, module: &str) {
512 if self.binds_from_another_module(file, local, module) {
513 self.mark_conflicting(file, local);
514 return;
515 }
516 if self
517 .import_map
518 .get(file)
519 .is_some_and(|imports| imports.contains_key(local))
520 {
521 return;
522 }
523 self.runtime_bindings
524 .entry(file.to_string())
525 .or_default()
526 .insert(local.to_string(), (name.to_string(), module.to_string()));
527 }
528
529 fn binds_from_another_module(&self, file: &str, local: &str, module: &str) -> bool {
532 self.import_map
533 .get(file)
534 .and_then(|imports| imports.get(local))
535 .is_some_and(|bound| bound != module)
536 || self
537 .runtime_bindings
538 .get(file)
539 .and_then(|bindings| bindings.get(local))
540 .is_some_and(|(_, bound)| bound != module)
541 || self
542 .conflicting_bindings
543 .get(file)
544 .is_some_and(|names| names.contains(local))
545 }
546
547 fn mark_conflicting(&mut self, file: &str, local: &str) {
549 if let Some(imports) = self.import_map.get_mut(file) {
550 imports.remove(local);
551 }
552 if let Some(aliases) = self.import_aliases.get_mut(file) {
553 aliases.remove(local);
554 }
555 if let Some(bindings) = self.runtime_bindings.get_mut(file) {
556 bindings.remove(local);
557 }
558 self.conflicting_bindings
559 .entry(file.to_string())
560 .or_default()
561 .insert(local.to_string());
562 }
563
564 fn binds_locally(&self, file: &str, name: &str) -> bool {
567 let has = |names: Option<&HashSet<String>>| names.is_some_and(|n| n.contains(name));
568 has(self.local_bindings.get(file))
569 || has(self.conflicting_bindings.get(file))
570 || self
571 .runtime_bindings
572 .get(file)
573 .is_some_and(|bindings| bindings.contains_key(name))
574 }
575
576 fn is_possible_script(&self, file: &str) -> bool {
585 is_js_family_file(Path::new(file))
586 && !self.module_files.contains(file)
587 && self.import_map.get(file).is_none_or(HashMap::is_empty)
588 && self
589 .namespace_imports
590 .get(file)
591 .is_none_or(HashMap::is_empty)
592 && self
593 .runtime_bindings
594 .get(file)
595 .is_none_or(HashMap::is_empty)
596 }
597
598 fn apply_import_validation(
611 &self,
612 reference: &str,
613 from_file: &Path,
614 from_file_str: &str,
615 to_idx: NodeId,
616 base_confidence: f32,
617 ) -> f32 {
618 if reference.contains('.') || reference.contains("::") {
619 return base_confidence;
620 }
621
622 if is_go_file(from_file) {
623 return self.validate_go_package_visibility(
624 reference,
625 from_file,
626 from_file_str,
627 to_idx,
628 base_confidence,
629 );
630 }
631
632 if bare_name_requires_import(from_file) {
633 return self.validate_bare_import_visibility(
634 reference,
635 from_file,
636 from_file_str,
637 to_idx,
638 base_confidence,
639 );
640 }
641
642 let Some(file_imports) = self.import_map.get(from_file_str) else {
643 return base_confidence;
644 };
645 if file_imports.is_empty() {
646 return base_confidence;
647 }
648 if file_imports.contains_key(reference) {
649 return base_confidence.max(0.95);
651 }
652
653 let Some(to_node) = self.graph.get(to_idx) else {
654 return 0.0;
655 };
656 let to_file = PathBuf::from(&to_node.file);
657
658 if to_file == from_file {
659 return base_confidence;
661 }
662
663 debug!(
664 "Downgrading unimported cross-module reference '{}' in {} → {}",
665 reference,
666 from_file.display(),
667 to_file.display()
668 );
669 unimported_confidence(from_file, &to_file, base_confidence)
670 }
671
672 fn validate_bare_import_visibility(
689 &self,
690 reference: &str,
691 from_file: &Path,
692 from_file_str: &str,
693 to_idx: NodeId,
694 base_confidence: f32,
695 ) -> f32 {
696 let Some(to_node) = self.graph.get(to_idx) else {
697 return 0.0;
698 };
699 let to_file = PathBuf::from(&to_node.file);
700 if to_file == from_file {
701 return base_confidence;
702 }
703
704 if let Some(file_imports) = self.import_map.get(from_file_str) {
705 if file_imports.contains_key(reference) {
706 return base_confidence.max(0.95);
707 }
708 if file_imports.contains_key("*") {
709 return unimported_confidence(from_file, &to_file, base_confidence);
710 }
711 }
712
713 if is_js_family_file(from_file) {
714 let to_script = self.is_possible_script(&to_node.file);
715 if to_script && self.is_possible_script(from_file_str) {
716 return base_confidence;
717 }
718 if to_script || to_node.is_exported || self.binds_locally(from_file_str, reference) {
719 debug!(
720 "Downgrading unimported reference '{}' in {} → {}, a local binding or a script's global",
721 reference,
722 from_file.display(),
723 to_file.display()
724 );
725 return unimported_confidence(from_file, &to_file, base_confidence);
726 }
727 }
728
729 debug!(
730 "Dropping unimported cross-file reference '{}' in {} → {}",
731 reference,
732 from_file.display(),
733 to_file.display()
734 );
735 0.0
736 }
737
738 fn validate_go_package_visibility(
745 &self,
746 reference: &str,
747 from_file: &Path,
748 from_file_str: &str,
749 to_idx: NodeId,
750 base_confidence: f32,
751 ) -> f32 {
752 let Some(to_node) = self.graph.get(to_idx) else {
753 return 0.0;
754 };
755 let to_file = PathBuf::from(&to_node.file);
756 if to_file == from_file {
757 return base_confidence;
758 }
759
760 let to_file_str = to_file.to_string_lossy().to_string();
761 let same_package = self
762 .go_packages
763 .get(from_file_str)
764 .zip(self.go_packages.get(&to_file_str))
765 .is_some_and(|(caller_pkg, callee_pkg)| {
766 caller_pkg == callee_pkg && to_file.parent() == from_file.parent()
767 });
768 if same_package {
769 return base_confidence;
770 }
771
772 debug!(
773 "Dropping bare Go reference '{}' in {} → {}",
774 reference,
775 from_file.display(),
776 to_file.display()
777 );
778 0.0
779 }
780
781 fn resolve_inheritance(&mut self) {
791 let indices: Vec<NodeId> = self.graph.node_indexes().collect();
792 let types = inherited_types(&self.graph, &indices);
793 let (methods_of, method_owner) = index_methods(&self.graph, &indices, &types);
794 let mut pending = Vec::new();
795 let parents = self.link_type_parents(&types, &mut pending);
796 link_inherited_methods(&types, &parents, &methods_of, &mut pending);
797 link_receiver_calls(
798 &self.graph,
799 &indices,
800 &method_owner,
801 &parents,
802 &methods_of,
803 &mut pending,
804 );
805 self.commit_inheritance_edges(pending);
806 }
807
808 fn link_type_parents(
810 &self,
811 types: &[InheritedType],
812 pending: &mut Vec<PendingEdge>,
813 ) -> HashMap<NodeId, Vec<NodeId>> {
814 let mut parents: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
815 for ty in types {
816 let file = PathBuf::from(&ty.file);
817 let mut resolved = Vec::new();
818 let relations = ty
819 .extends
820 .iter()
821 .map(|name| (TypeRelationKind::Extends, name))
822 .chain(
823 ty.implements
824 .iter()
825 .map(|name| (TypeRelationKind::Implements, name)),
826 );
827 for (recorded, name) in relations {
828 let Some(target) = self.resolve_type_name(name, &file) else {
829 continue;
830 };
831 if target == ty.id || resolved.contains(&target) {
832 continue;
833 }
834 resolved.push(target);
835 pending.push(type_edge(self, ty, recorded, target));
836 }
837 if !resolved.is_empty() {
838 parents.insert(ty.id, resolved);
839 }
840 }
841 parents
842 }
843
844 fn commit_inheritance_edges(&mut self, pending: Vec<PendingEdge>) {
845 let mut seen: HashSet<(NodeId, NodeId, u8)> = HashSet::new();
846 for (from, to, kind, confidence) in pending {
847 if from == to || !seen.insert((from, to, edge_tag(kind))) {
848 continue;
849 }
850 self.graph
851 .add_edge(from, to, Edge::new(kind).with_confidence(confidence));
852 }
853 }
854
855 fn resolve_typed_receiver(&self, method: &str, receiver: &str, file: &Path) -> TypedReceiver {
859 let mut segments = receiver.split('.');
860 let Some(base) = segments.next() else {
861 return TypedReceiver::Unknown;
862 };
863 let mut current = match base.strip_suffix("()") {
864 Some(callee) => match self.returned_type(self.callable(callee, file)) {
865 Ok(id) => id,
866 Err(outcome) => return outcome,
867 },
868 None => match self.type_named(base, file) {
869 Ok(id) => id,
870 Err(outcome) => return outcome,
871 },
872 };
873 for segment in segments {
874 let Some(node) = self.graph.get(current) else {
875 return TypedReceiver::Unknown;
876 };
877 let owner_file = PathBuf::from(&node.file);
878 if let Some(called) = segment.strip_suffix("()") {
879 let path = format!("{}::{called}", node.name);
881 current = match self.returned_type(self.callable(&path, &owner_file)) {
882 Ok(id) => id,
883 Err(outcome) => return outcome,
884 };
885 continue;
886 }
887 let field_type = node
888 .references
889 .iter()
890 .filter_map(|reference| field_type_ref(reference))
891 .find(|(name, _)| *name == segment)
892 .map(|(_, type_name)| type_name.to_string());
893 let Some(field_type) = field_type else {
894 return TypedReceiver::Unknown;
895 };
896 current = match self.type_named(&field_type, &owner_file) {
897 Ok(id) => id,
898 Err(outcome) => return outcome,
899 };
900 }
901
902 let Some(owner) = self.graph.get(current) else {
903 return TypedReceiver::Unknown;
904 };
905 let owner_file = PathBuf::from(&owner.file);
906 let mut owners = vec![owner.name.clone()];
907 if owner.kind == NodeKind::Interface {
908 owners.extend(self.implementors(&owner.name, &owner_file));
910 } else {
911 owners.extend(
913 owner.references.iter().filter_map(|reference| {
914 match type_relation_ref(reference) {
915 Some((TypeRelationKind::Implements, name)) => Some(name.to_string()),
916 _ => None,
917 }
918 }),
919 );
920 }
921 let mut targets = Vec::new();
922 for owner_name in owners {
923 let resolution = self
924 .symbol_table
925 .resolve_path(&format!("{owner_name}::{method}"), &owner_file);
926 for id in resolution.candidates() {
927 let is_method = self
928 .graph
929 .get(id)
930 .is_some_and(|n| matches!(n.kind, NodeKind::Method | NodeKind::Function));
931 if is_method && !targets.contains(&id) {
932 targets.push(id);
933 }
934 }
935 }
936 if targets.is_empty() || targets.len() > MAX_AMBIGUOUS_FANOUT {
937 TypedReceiver::Unknown
938 } else {
939 TypedReceiver::Found(targets)
940 }
941 }
942
943 fn type_named(&self, name: &str, file: &Path) -> Result<NodeId, TypedReceiver> {
945 match self.resolve_type_name(name, file) {
946 Some(id) => Ok(id),
947 None if self.defines_type(name, file) => Err(TypedReceiver::Unknown),
948 None => Err(TypedReceiver::External),
949 }
950 }
951
952 fn callable(&self, path: &str, file: &Path) -> Vec<NodeId> {
955 let resolution = if path.contains("::") {
956 self.symbol_table.resolve_path(path, file)
957 } else {
958 let imports = self.import_map.get(&file.to_string_lossy().to_string());
959 self.symbol_table
960 .resolve_ref_with_imports(path, file, imports)
961 };
962 resolution
963 .candidates()
964 .into_iter()
965 .filter(|id| {
966 self.graph
967 .get(*id)
968 .is_some_and(|n| matches!(n.kind, NodeKind::Function | NodeKind::Method))
969 })
970 .collect()
971 }
972
973 fn returned_type(&self, functions: Vec<NodeId>) -> Result<NodeId, TypedReceiver> {
975 let mut returned: Option<(String, PathBuf)> = None;
976 for id in functions {
977 let Some(function) = self.graph.get(id) else {
978 continue;
979 };
980 let Some(type_name) = function.references.iter().find_map(|r| return_type_ref(r))
981 else {
982 return Err(TypedReceiver::Unknown);
984 };
985 match &returned {
986 Some((seen, _)) if seen != type_name => return Err(TypedReceiver::Unknown),
987 Some(_) => {}
988 None => returned = Some((type_name.to_string(), PathBuf::from(&function.file))),
989 }
990 }
991 let Some((type_name, file)) = returned else {
994 return Err(TypedReceiver::Unknown);
995 };
996 self.type_named(&type_name, &file)
997 }
998
999 fn defines_type(&self, name: &str, file: &Path) -> bool {
1002 self.symbol_table
1003 .resolve_ref_with_imports(name, file, None)
1004 .candidates()
1005 .into_iter()
1006 .any(|id| {
1007 self.graph
1008 .get(id)
1009 .is_some_and(|node| is_inheritable_type(node.kind) && node.name == name)
1010 })
1011 }
1012
1013 fn implementors(&self, name: &str, file: &Path) -> Vec<String> {
1015 let mut found = Vec::new();
1016 for idx in self.graph.node_indexes() {
1017 let Some(node) = self.graph.get(idx) else {
1018 continue;
1019 };
1020 let implements = node.references.iter().any(|reference| {
1021 matches!(type_relation_ref(reference),
1022 Some((TypeRelationKind::Implements, target)) if target == name)
1023 });
1024 if implements
1025 && crate::symbol_table::same_language(file, Path::new(&node.file))
1026 && !found.contains(&node.name)
1027 {
1028 found.push(node.name.clone());
1029 }
1030 }
1031 found
1032 }
1033
1034 fn resolve_type_name(&self, name: &str, file: &Path) -> Option<NodeId> {
1040 let file_str = file.to_string_lossy().to_string();
1041 let imports = self.import_map.get(&file_str);
1042 let mut candidates_names = vec![name.to_string()];
1043 if let Some(last) = name.rsplit(['.', ':']).find(|segment| !segment.is_empty()) {
1044 if last != name {
1045 candidates_names.push(last.to_string());
1046 }
1047 }
1048
1049 for candidate in &candidates_names {
1050 let resolution = self
1051 .symbol_table
1052 .resolve_ref_with_imports(candidate, file, imports);
1053 let type_ids: Vec<NodeId> = resolution
1054 .candidates()
1055 .into_iter()
1056 .filter(|id| {
1057 self.graph
1058 .get(*id)
1059 .is_some_and(|node| is_inheritable_type(node.kind))
1060 })
1061 .collect();
1062 if type_ids.len() == 1 {
1063 return Some(type_ids[0]);
1064 }
1065 let same_file: Vec<NodeId> = type_ids
1066 .into_iter()
1067 .filter(|id| {
1068 self.graph
1069 .get(*id)
1070 .is_some_and(|node| Path::new(&node.file) == file)
1071 })
1072 .collect();
1073 if same_file.len() == 1 {
1074 return Some(same_file[0]);
1075 }
1076 }
1077 None
1078 }
1079
1080 pub fn build(mut self) -> ArborGraph {
1082 self.resolve_edges();
1083 self.resolve_inheritance();
1084 self.graph.set_import_nodes(self.import_nodes);
1085 self.graph
1086 }
1087
1088 pub fn build_without_resolve(mut self) -> ArborGraph {
1090 self.graph.set_import_nodes(self.import_nodes);
1091 self.graph
1092 }
1093}
1094
1095fn unimported_confidence(from_file: &Path, to_file: &Path, base_confidence: f32) -> f32 {
1099 if to_file.parent() == from_file.parent() {
1100 base_confidence * 0.6
1101 } else {
1102 base_confidence * 0.3
1103 }
1104}
1105
1106fn is_go_file(file: &Path) -> bool {
1108 file.extension()
1109 .and_then(|ext| ext.to_str())
1110 .is_some_and(|ext| ext.eq_ignore_ascii_case("go"))
1111}
1112
1113fn bare_name_requires_import(file: &Path) -> bool {
1119 let Some(ext) = file.extension().and_then(|ext| ext.to_str()) else {
1120 return false;
1121 };
1122 matches!(
1123 ext.to_ascii_lowercase().as_str(),
1124 "py" | "pyi" | "ts" | "tsx" | "js" | "jsx" | "mts" | "cts" | "mjs" | "cjs"
1125 )
1126}
1127
1128fn is_js_family_file(file: &Path) -> bool {
1130 let Some(ext) = file.extension().and_then(|ext| ext.to_str()) else {
1131 return false;
1132 };
1133 matches!(
1134 ext.to_ascii_lowercase().as_str(),
1135 "ts" | "tsx" | "js" | "jsx" | "mts" | "cts" | "mjs" | "cjs"
1136 )
1137}
1138
1139struct InheritedType {
1140 id: NodeId,
1141 file: String,
1142 qualified_len: usize,
1144 clean_name: String,
1145 clean_qualified: String,
1146 extends: Vec<String>,
1147 implements: Vec<String>,
1148}
1149
1150type PendingEdge = (NodeId, NodeId, EdgeKind, f32);
1151
1152fn inherited_types(graph: &ArborGraph, indices: &[NodeId]) -> Vec<InheritedType> {
1153 let mut types = Vec::new();
1154 for id in indices {
1155 let Some(node) = graph.get(*id) else {
1156 continue;
1157 };
1158 if !is_inheritable_type(node.kind) {
1159 continue;
1160 }
1161 let mut extends = Vec::new();
1162 let mut implements = Vec::new();
1163 for reference in &node.references {
1164 if let Some((kind, name)) = type_relation_ref(reference) {
1165 match kind {
1166 TypeRelationKind::Extends => extends.push(name.to_string()),
1167 TypeRelationKind::Implements => implements.push(name.to_string()),
1168 }
1169 }
1170 }
1171 types.push(InheritedType {
1172 id: *id,
1173 file: node.file.clone(),
1174 qualified_len: node.qualified_name.len(),
1175 clean_name: clean_type_name(&node.name),
1176 clean_qualified: clean_type_name(&node.qualified_name),
1177 extends,
1178 implements,
1179 });
1180 }
1181 types
1182}
1183
1184fn index_methods(
1185 graph: &ArborGraph,
1186 indices: &[NodeId],
1187 types: &[InheritedType],
1188) -> (
1189 HashMap<NodeId, BTreeMap<String, NodeId>>,
1190 HashMap<NodeId, NodeId>,
1191) {
1192 let mut types_by_file: HashMap<&str, Vec<&InheritedType>> = HashMap::new();
1193 let mut rust_types_by_name: HashMap<&str, Vec<&InheritedType>> = HashMap::new();
1194 for ty in types {
1195 types_by_file.entry(ty.file.as_str()).or_default().push(ty);
1196 if ty.file.ends_with(".rs") {
1197 rust_types_by_name
1198 .entry(ty.clean_name.as_str())
1199 .or_default()
1200 .push(ty);
1201 }
1202 }
1203
1204 let mut methods_of: HashMap<NodeId, BTreeMap<String, NodeId>> = HashMap::new();
1205 let mut method_owner: HashMap<NodeId, NodeId> = HashMap::new();
1206 for id in indices {
1207 let Some(node) = graph.get(*id) else {
1208 continue;
1209 };
1210 if node.kind != NodeKind::Method {
1211 continue;
1212 }
1213 let Some((parent, method_name)) = split_owner(&node.qualified_name) else {
1214 continue;
1215 };
1216 let parent = clean_type_name(parent);
1217 if parent.is_empty() || method_name.is_empty() {
1218 continue;
1219 }
1220 let file_types = types_by_file
1221 .get(node.file.as_str())
1222 .map(Vec::as_slice)
1223 .unwrap_or_default();
1224 let owners: Vec<NodeId> = file_types
1225 .iter()
1226 .filter(|ty| ty.clean_name == parent || ty.clean_qualified == parent)
1227 .map(|ty| ty.id)
1228 .collect();
1229 let owner = unique_owner(&owners, |id| {
1230 file_types
1231 .iter()
1232 .find(|ty| ty.id == id)
1233 .map(|ty| ty.qualified_len)
1234 .unwrap_or(0)
1235 })
1236 .or_else(|| {
1237 if !node.file.ends_with(".rs") || !owners.is_empty() {
1244 return None;
1245 }
1246 let candidates = rust_types_by_name.get(parent.as_str())?;
1247 let mut dir = Path::new(&node.file).parent();
1248 while let Some(current) = dir {
1249 let here: Vec<NodeId> = candidates
1250 .iter()
1251 .filter(|ty| Path::new(&ty.file).parent() == Some(current))
1252 .map(|ty| ty.id)
1253 .collect();
1254 match here.as_slice() {
1255 [] => dir = current.parent(),
1256 [only] => return Some(*only),
1257 _ => return None,
1258 }
1259 }
1260 None
1261 });
1262 let Some(owner) = owner else {
1263 continue;
1264 };
1265 methods_of
1266 .entry(owner)
1267 .or_default()
1268 .entry(method_name.to_string())
1269 .or_insert(*id);
1270 method_owner.insert(*id, owner);
1271 }
1272 (methods_of, method_owner)
1273}
1274
1275fn type_edge(
1276 builder: &GraphBuilder,
1277 ty: &InheritedType,
1278 recorded: TypeRelationKind,
1279 target: NodeId,
1280) -> PendingEdge {
1281 let target_kind = builder.graph.get(target).map(|node| node.kind);
1282 let edge_kind = match (recorded, target_kind) {
1283 (TypeRelationKind::Implements, _) | (_, Some(NodeKind::Interface)) => EdgeKind::Implements,
1284 _ => EdgeKind::Extends,
1285 };
1286 let same_file = builder
1287 .graph
1288 .get(target)
1289 .is_some_and(|node| node.file == ty.file);
1290 let confidence = if same_file { 0.95 } else { 0.85 };
1291 (ty.id, target, edge_kind, confidence)
1292}
1293
1294fn link_inherited_methods(
1295 types: &[InheritedType],
1296 parents: &HashMap<NodeId, Vec<NodeId>>,
1297 methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
1298 pending: &mut Vec<PendingEdge>,
1299) {
1300 for ty in types {
1301 let own = methods_of.get(&ty.id);
1302 for (name, method_id) in inherited_methods(ty.id, parents, methods_of) {
1303 if own.and_then(|methods| methods.get(&name)).is_some() {
1304 continue;
1305 }
1306 pending.push((ty.id, method_id, EdgeKind::References, 0.9));
1307 }
1308 }
1309}
1310
1311fn link_receiver_calls(
1312 graph: &ArborGraph,
1313 indices: &[NodeId],
1314 method_owner: &HashMap<NodeId, NodeId>,
1315 parents: &HashMap<NodeId, Vec<NodeId>>,
1316 methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
1317 pending: &mut Vec<PendingEdge>,
1318) {
1319 for id in indices {
1320 let Some(node) = graph.get(*id) else {
1321 continue;
1322 };
1323 if node.kind != NodeKind::Method {
1324 continue;
1325 }
1326 let Some(&owner) = method_owner.get(id) else {
1327 continue;
1328 };
1329 for reference in &node.references {
1330 let Some((is_super, method_name)) = receiver_method(reference) else {
1331 continue;
1332 };
1333 let Some(target) = nearest_method(owner, method_name, is_super, parents, methods_of)
1334 else {
1335 continue;
1336 };
1337 if target != *id {
1338 pending.push((*id, target, EdgeKind::Calls, 0.95));
1339 }
1340 }
1341 }
1342}
1343
1344fn is_inheritable_type(kind: NodeKind) -> bool {
1345 matches!(
1346 kind,
1347 NodeKind::Class | NodeKind::Struct | NodeKind::Interface | NodeKind::Enum
1348 )
1349}
1350
1351fn split_owner(qualified: &str) -> Option<(&str, &str)> {
1356 let dot = qualified.rfind('.');
1357 let colon = qualified.rfind("::");
1358 match (dot, colon) {
1359 (Some(dot_at), Some(colon_at)) if colon_at > dot_at => {
1360 Some((&qualified[..colon_at], &qualified[colon_at + 2..]))
1361 }
1362 (Some(dot_at), _) => Some((&qualified[..dot_at], &qualified[dot_at + 1..])),
1363 (None, Some(colon_at)) => Some((&qualified[..colon_at], &qualified[colon_at + 2..])),
1364 (None, None) => None,
1365 }
1366}
1367
1368fn unique_owner(owners: &[NodeId], qualified_len: impl Fn(NodeId) -> usize) -> Option<NodeId> {
1369 match owners {
1370 [] => None,
1371 [only] => Some(*only),
1372 _ => {
1373 let mut best_len = 0usize;
1374 let mut best: Option<NodeId> = None;
1375 let mut tied = false;
1376 for id in owners {
1377 let len = qualified_len(*id);
1378 if len > best_len {
1379 best_len = len;
1380 best = Some(*id);
1381 tied = false;
1382 } else if len == best_len {
1383 tied = true;
1384 }
1385 }
1386 if tied {
1387 None
1388 } else {
1389 best
1390 }
1391 }
1392 }
1393}
1394
1395fn inherited_methods(
1398 start: NodeId,
1399 parents: &HashMap<NodeId, Vec<NodeId>>,
1400 methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
1401) -> BTreeMap<String, NodeId> {
1402 let mut found = BTreeMap::new();
1403 let mut seen = HashSet::new();
1404 let mut queue = VecDeque::new();
1405 if let Some(bases) = parents.get(&start) {
1406 queue.extend(bases.iter().copied());
1407 }
1408 while let Some(current) = queue.pop_front() {
1409 if !seen.insert(current) {
1410 continue;
1411 }
1412 if let Some(methods) = methods_of.get(¤t) {
1413 for (name, id) in methods {
1414 found.entry(name.clone()).or_insert(*id);
1415 }
1416 }
1417 if let Some(bases) = parents.get(¤t) {
1418 for base in bases {
1419 if !seen.contains(base) {
1420 queue.push_back(*base);
1421 }
1422 }
1423 }
1424 }
1425 found
1426}
1427
1428fn nearest_method(
1430 start: NodeId,
1431 name: &str,
1432 skip_self: bool,
1433 parents: &HashMap<NodeId, Vec<NodeId>>,
1434 methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
1435) -> Option<NodeId> {
1436 let own = if skip_self {
1437 None
1438 } else {
1439 methods_of.get(&start).and_then(|methods| methods.get(name))
1440 };
1441 if let Some(id) = own {
1442 return Some(*id);
1443 }
1444 let mut seen = HashSet::new();
1445 let mut queue = VecDeque::new();
1446 if let Some(bases) = parents.get(&start) {
1447 queue.extend(bases.iter().copied());
1448 }
1449 while let Some(current) = queue.pop_front() {
1450 if !seen.insert(current) {
1451 continue;
1452 }
1453 if let Some(id) = methods_of
1454 .get(¤t)
1455 .and_then(|methods| methods.get(name))
1456 {
1457 return Some(*id);
1458 }
1459 if let Some(bases) = parents.get(¤t) {
1460 for base in bases {
1461 if !seen.contains(base) {
1462 queue.push_back(*base);
1463 }
1464 }
1465 }
1466 }
1467 None
1468}
1469
1470fn receiver_method(reference: &str) -> Option<(bool, &str)> {
1473 const SUPER_PREFIXES: &[&str] = &["super().", "super.", "base."];
1474 const SAME_PREFIXES: &[&str] = &["self.", "this->", "this.", "Self::"];
1475 let reference = reference.trim();
1476 for prefix in SUPER_PREFIXES {
1477 if let Some(method) = reference.strip_prefix(prefix) {
1478 if is_plain_method(method) {
1479 return Some((true, method));
1480 }
1481 }
1482 }
1483 for prefix in SAME_PREFIXES {
1484 if let Some(method) = reference.strip_prefix(prefix) {
1485 if is_plain_method(method) {
1486 return Some((false, method));
1487 }
1488 }
1489 }
1490 None
1491}
1492
1493fn is_plain_method(name: &str) -> bool {
1494 !name.is_empty()
1495 && name
1496 .chars()
1497 .next()
1498 .is_some_and(|c| c.is_alphabetic() || c == '_')
1499 && name.chars().all(|c| c.is_alphanumeric() || c == '_')
1500}
1501
1502fn edge_tag(kind: EdgeKind) -> u8 {
1503 match kind {
1504 EdgeKind::Calls => 1,
1505 EdgeKind::Extends => 2,
1506 EdgeKind::Implements => 3,
1507 EdgeKind::References => 4,
1508 EdgeKind::Imports => 5,
1509 EdgeKind::UsesType => 6,
1510 EdgeKind::Contains => 7,
1511 EdgeKind::FlowsTo => 8,
1512 EdgeKind::DataDependency => 9,
1513 }
1514}
1515
1516#[cfg(test)]
1517mod tests {
1518 use super::*;
1519 use arbor_core::NodeKind;
1520 use petgraph::visit::{EdgeRef, IntoEdgeReferences};
1521 use std::path::Path;
1522
1523 #[test]
1524 fn test_builder_adds_nodes() {
1525 let mut builder = GraphBuilder::new();
1526 let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "test.rs");
1527 let node2 = CodeNode::new("bar", "bar", NodeKind::Function, "test.rs");
1528 builder.add_nodes(vec![node1, node2]);
1529 let graph = builder.build();
1530 assert_eq!(graph.node_count(), 2);
1531 }
1532
1533 #[test]
1534 fn test_builder_resolves_edges() {
1535 let mut builder = GraphBuilder::new();
1536 let caller = CodeNode::new("caller", "caller", NodeKind::Function, "test.rs")
1537 .with_references(vec!["callee".to_string()]);
1538 let callee = CodeNode::new("callee", "callee", NodeKind::Function, "test.rs");
1539 builder.add_nodes(vec![caller, callee]);
1540 let graph = builder.build();
1541 assert_eq!(graph.node_count(), 2);
1542 assert_eq!(graph.edge_count(), 1);
1543 }
1544
1545 #[test]
1546 fn test_cross_file_resolution() {
1547 let mut builder = GraphBuilder::new();
1548 let caller = CodeNode::new("main", "main", NodeKind::Function, "main.rs")
1549 .with_references(vec!["pkg.Utils.helper".to_string()]);
1550 let mut callee = CodeNode::new("helper", "helper", NodeKind::Method, "utils.rs");
1551 callee.qualified_name = "pkg.Utils.helper".to_string();
1552 builder.add_nodes(vec![caller]);
1553 builder.add_nodes(vec![callee]);
1554 let graph = builder.build();
1555 assert_eq!(graph.node_count(), 2);
1556 assert_eq!(
1557 graph.edge_count(),
1558 1,
1559 "Should resolve cross-file edge via FQN"
1560 );
1561 }
1562
1563 #[test]
1564 fn test_unresolved_references_no_false_edges() {
1565 let mut builder = GraphBuilder::new();
1566 let node = CodeNode::new("caller", "caller", NodeKind::Function, "a.rs")
1567 .with_references(vec!["nonexistent_function".to_string()]);
1568 builder.add_nodes(vec![node]);
1569 let graph = builder.build();
1570 assert_eq!(graph.node_count(), 1);
1571 assert_eq!(
1572 graph.edge_count(),
1573 0,
1574 "Unresolved references must not create edges"
1575 );
1576 }
1577
1578 #[test]
1579 fn test_import_nodes_not_added_to_graph() {
1580 let mut builder = GraphBuilder::new();
1581 let import_node = CodeNode::new("./utils", "./utils", NodeKind::Import, "main.ts")
1582 .with_references(vec!["validate".to_string()]);
1583 let func = CodeNode::new("main", "main", NodeKind::Function, "main.ts");
1584 builder.add_nodes(vec![import_node, func]);
1585 let graph = builder.build();
1586 assert_eq!(graph.node_count(), 1);
1588 }
1589
1590 #[test]
1591 fn test_import_map_built_correctly() {
1592 let mut builder = GraphBuilder::new();
1593 let import_node =
1594 CodeNode::new("@babel/types", "@babel/types", NodeKind::Import, "file.ts")
1595 .with_references(vec!["validate".to_string(), "clone".to_string()]);
1596 builder.add_nodes(vec![import_node]);
1597 assert_eq!(
1598 builder
1599 .import_map
1600 .get("file.ts")
1601 .and_then(|m| m.get("validate")),
1602 Some(&"@babel/types".to_string())
1603 );
1604 assert_eq!(
1605 builder
1606 .import_map
1607 .get("file.ts")
1608 .and_then(|m| m.get("clone")),
1609 Some(&"@babel/types".to_string())
1610 );
1611 }
1612
1613 #[test]
1614 fn test_namespace_import_map() {
1615 let mut builder = GraphBuilder::new();
1616 let import_node =
1617 CodeNode::new("@babel/types", "@babel/types", NodeKind::Import, "file.ts")
1618 .with_references(vec!["*as:types".to_string()]);
1619 builder.add_nodes(vec![import_node]);
1620 assert_eq!(
1621 builder
1622 .namespace_imports
1623 .get("file.ts")
1624 .and_then(|m| m.get("types")),
1625 Some(&"@babel/types".to_string())
1626 );
1627 }
1628
1629 #[test]
1630 fn test_alias_import_map() {
1631 let mut builder = GraphBuilder::new();
1632 let import_node = CodeNode::new("money", "money", NodeKind::Import, "orders.py")
1633 .with_references(vec!["alias:to_minor:money_to_minor_units".to_string()]);
1634 builder.add_nodes(vec![import_node]);
1635 assert_eq!(
1636 builder
1637 .import_map
1638 .get("orders.py")
1639 .and_then(|m| m.get("to_minor")),
1640 Some(&"money".to_string())
1641 );
1642 assert_eq!(
1643 builder
1644 .import_aliases
1645 .get("orders.py")
1646 .and_then(|m| m.get("to_minor")),
1647 Some(&"money_to_minor_units".to_string())
1648 );
1649 }
1650
1651 #[test]
1652 fn aliased_call_reaches_the_imported_name_with_import_confidence() {
1653 let mut builder = GraphBuilder::new();
1654 let import = CodeNode::new("money", "money", NodeKind::Import, "orders.py")
1655 .with_references(vec!["alias:to_minor:money_to_minor_units".to_string()]);
1656 let caller = CodeNode::new(
1657 "total_cents",
1658 "total_cents",
1659 NodeKind::Function,
1660 "orders.py",
1661 )
1662 .with_references(vec!["to_minor".to_string()]);
1663 let callee = CodeNode::new(
1664 "money_to_minor_units",
1665 "money_to_minor_units",
1666 NodeKind::Function,
1667 "money.py",
1668 );
1669 builder.add_nodes(vec![import, caller, callee]);
1670 let graph = builder.build();
1671 assert!(
1672 only_edge_confidence(&graph) >= 0.95,
1673 "an aliased import is as strong as an unaliased one"
1674 );
1675 }
1676
1677 #[test]
1679 fn a_plain_import_rebinds_an_earlier_alias() {
1680 let mut builder = GraphBuilder::new();
1681 let aliased = CodeNode::new("a", "a", NodeKind::Import, "main.py")
1682 .with_references(vec!["alias:y:x".to_string()]);
1683 let plain = CodeNode::new("b", "b", NodeKind::Import, "main.py")
1684 .with_references(vec!["y".to_string()]);
1685 let caller = CodeNode::new("run", "run", NodeKind::Function, "main.py")
1686 .with_references(vec!["y".to_string()]);
1687 let x = CodeNode::new("x", "x", NodeKind::Function, "a.py");
1688 let y = CodeNode::new("y", "y", NodeKind::Function, "b.py");
1689 builder.add_nodes(vec![aliased, plain, caller, x, y]);
1690 let graph = builder.build();
1691 let edges = graph.export_edges();
1692 assert_eq!(edges.len(), 1, "{edges:?}");
1693 let target = graph.get_index(&edges[0].target).expect("target");
1694 assert_eq!(graph.get(target).unwrap().file, "b.py");
1695 }
1696
1697 #[test]
1698 fn test_build_empty_graph() {
1699 let builder = GraphBuilder::new();
1700 let graph = builder.build();
1701 assert_eq!(graph.node_count(), 0);
1702 assert_eq!(graph.edge_count(), 0);
1703 }
1704
1705 fn only_edge_confidence(graph: &ArborGraph) -> f32 {
1707 let edges = graph.export_edges();
1708 assert_eq!(edges.len(), 1, "expected exactly one edge");
1709 graph
1710 .graph
1711 .edge_weights()
1712 .next()
1713 .expect("edge weight")
1714 .confidence
1715 }
1716
1717 #[test]
1718 fn exact_fqn_match_is_full_confidence() {
1719 let mut b = GraphBuilder::new();
1720 let caller = CodeNode::new("main", "main", NodeKind::Function, "main.rs")
1721 .with_references(vec!["pkg.Utils.helper".to_string()]);
1722 let mut callee = CodeNode::new("helper", "helper", NodeKind::Method, "utils.rs");
1723 callee.qualified_name = "pkg.Utils.helper".to_string();
1724 b.add_nodes(vec![caller, callee]);
1725 let graph = b.build();
1726
1727 assert_eq!(only_edge_confidence(&graph), 1.0);
1728 }
1729
1730 #[test]
1731 fn unknown_receiver_call_creates_a_weak_edge() {
1732 let mut b = GraphBuilder::new();
1734 let caller = CodeNode::new("handler", "handler", NodeKind::Function, "api.ts")
1735 .with_references(vec![".findOne".to_string()]);
1736 let callee = CodeNode::new("findOne", "UserRepo.findOne", NodeKind::Method, "repo.ts");
1737 b.add_nodes(vec![caller, callee]);
1738 let graph = b.build();
1739
1740 let confidence = only_edge_confidence(&graph);
1741 assert!(
1742 confidence > 0.0 && confidence < Edge::CONFIDENT_THRESHOLD,
1743 "edge should exist but not be treated as proven, got {confidence}"
1744 );
1745 }
1746
1747 fn receiver_fixture(caller_refs: &[&str]) -> ArborGraph {
1749 let mut b = GraphBuilder::new();
1750 let mut nodes = vec![
1751 CodeNode::new("on_key", "on_key", NodeKind::Function, "src/lib.rs")
1752 .with_references(caller_refs.iter().map(|r| r.to_string()).collect()),
1753 CodeNode::new("AppState", "AppState", NodeKind::Struct, "src/state.rs")
1754 .with_references(vec![arbor_core::field_ref("draft", "Draft")]),
1755 CodeNode::new("Draft", "Draft", NodeKind::Struct, "src/draft.rs"),
1756 CodeNode::new(
1757 "Telemetry",
1758 "Telemetry",
1759 NodeKind::Struct,
1760 "src/telemetry.rs",
1761 ),
1762 CodeNode::new("Logger", "Logger", NodeKind::Struct, "src/observer.rs"),
1763 CodeNode::new(
1764 "RunObserver",
1765 "RunObserver",
1766 NodeKind::Interface,
1767 "src/observer.rs",
1768 ),
1769 ];
1770 nodes[4].add_type_relation(TypeRelationKind::Implements, "RunObserver");
1771 nodes[3].add_type_relation(TypeRelationKind::Implements, "RunObserver");
1772 for (owner, file) in [
1773 ("Draft", "src/draft.rs"),
1774 ("Telemetry", "src/telemetry.rs"),
1775 ("Logger", "src/observer.rs"),
1776 ] {
1777 nodes.push(CodeNode::new(
1778 "run_started",
1779 format!("{owner}.run_started"),
1780 NodeKind::Method,
1781 file,
1782 ));
1783 }
1784 b.add_nodes(nodes);
1785 b.build()
1786 }
1787
1788 fn callees(graph: &ArborGraph) -> Vec<String> {
1789 use petgraph::visit::EdgeRef;
1790 let mut names: Vec<String> = graph
1791 .graph
1792 .edge_references()
1793 .filter(|edge| edge.weight().kind == EdgeKind::Calls)
1794 .filter_map(|edge| graph.get(edge.target()).map(|n| n.qualified_name.clone()))
1795 .collect();
1796 names.sort();
1797 names
1798 }
1799
1800 #[test]
1801 fn typed_receiver_reaches_only_its_own_type() {
1802 assert!(callees(&receiver_fixture(&[".run_started"])).is_empty());
1804 let graph = receiver_fixture(&[".run_started@Draft"]);
1805 assert_eq!(callees(&graph), ["Draft.run_started"]);
1806 let call = graph
1807 .graph
1808 .edge_weights()
1809 .find(|edge| edge.kind == EdgeKind::Calls)
1810 .expect("the call edge");
1811 assert!((call.confidence - TYPED_RECEIVER_CONFIDENCE).abs() < 1e-6);
1812 }
1813
1814 #[test]
1815 fn typed_receiver_follows_fields_into_other_files() {
1816 let graph = receiver_fixture(&[".run_started@AppState.draft"]);
1817 assert_eq!(callees(&graph), ["Draft.run_started"]);
1818 }
1819
1820 #[test]
1821 fn trait_typed_receiver_reaches_each_implementor() {
1822 let graph = receiver_fixture(&[".run_started@RunObserver"]);
1823 assert_eq!(
1824 callees(&graph),
1825 ["Logger.run_started", "Telemetry.run_started"]
1826 );
1827 }
1828
1829 #[test]
1830 fn external_receiver_never_binds_to_a_project_method() {
1831 assert!(callees(&receiver_fixture(&[".run_started@Client"])).is_empty());
1833 }
1834
1835 #[test]
1836 fn project_type_without_the_method_falls_back_to_the_name() {
1837 assert!(callees(&receiver_fixture(&[".run_started@AppState.missing"])).is_empty());
1840 let mut b = GraphBuilder::new();
1841 b.add_nodes(vec![
1842 CodeNode::new("on_key", "on_key", NodeKind::Function, "src/lib.rs")
1843 .with_references(vec![".flush@Draft".to_string()]),
1844 CodeNode::new("Draft", "Draft", NodeKind::Struct, "src/draft.rs"),
1845 CodeNode::new("flush", "Buffer.flush", NodeKind::Method, "src/buffer.rs"),
1846 ]);
1847 let graph = b.build();
1848 assert_eq!(callees(&graph), ["Buffer.flush"]);
1850 assert!(only_edge_confidence(&graph) < TYPED_RECEIVER_CONFIDENCE);
1851 }
1852
1853 #[test]
1854 fn typed_receiver_follows_return_types() {
1855 let mut b = GraphBuilder::new();
1856 let mut prepare = CodeNode::new("prepare", "prepare", NodeKind::Function, "src/lib.rs")
1857 .with_references(vec![arbor_core::returns_ref("Prepared")]);
1858 prepare.line_end = 0;
1859 b.add_nodes(vec![
1860 CodeNode::new("on_key", "on_key", NodeKind::Function, "src/lib.rs").with_references(
1861 vec![
1862 ".run_started@prepare()".to_string(),
1863 ".flush@mac::Prepared::capture().buffer()".to_string(),
1864 ],
1865 ),
1866 prepare,
1867 CodeNode::new("Prepared", "Prepared", NodeKind::Struct, "src/mac.rs"),
1868 CodeNode::new("Buffer", "Buffer", NodeKind::Struct, "src/buffer.rs"),
1869 CodeNode::new(
1870 "capture",
1871 "Prepared.capture",
1872 NodeKind::Method,
1873 "src/mac.rs",
1874 )
1875 .with_references(vec![arbor_core::returns_ref("Prepared")]),
1876 CodeNode::new("buffer", "Prepared.buffer", NodeKind::Method, "src/mac.rs")
1877 .with_references(vec![arbor_core::returns_ref("Buffer")]),
1878 CodeNode::new(
1879 "run_started",
1880 "Prepared.run_started",
1881 NodeKind::Method,
1882 "src/mac.rs",
1883 ),
1884 CodeNode::new(
1885 "run_started",
1886 "Other.run_started",
1887 NodeKind::Method,
1888 "src/other.rs",
1889 ),
1890 CodeNode::new(
1891 "run_started",
1892 "Third.run_started",
1893 NodeKind::Method,
1894 "src/third.rs",
1895 ),
1896 CodeNode::new("flush", "Buffer.flush", NodeKind::Method, "src/buffer.rs"),
1897 CodeNode::new("flush", "Pipe.flush", NodeKind::Method, "src/pipe.rs"),
1898 CodeNode::new("flush", "Sink.flush", NodeKind::Method, "src/sink.rs"),
1899 ]);
1900 let graph = b.build();
1901 assert_eq!(callees(&graph), ["Buffer.flush", "Prepared.run_started"]);
1902 }
1903
1904 #[test]
1905 fn field_types_are_not_calls() {
1906 assert!(
1907 callees(&receiver_fixture(&[])).is_empty(),
1908 "a field: reference is not a call"
1909 );
1910 }
1911
1912 #[test]
1913 fn unknown_receiver_with_many_candidates_is_not_linked() {
1914 let mut b = GraphBuilder::new();
1916 let caller = CodeNode::new("handler", "handler", NodeKind::Function, "api.ts")
1917 .with_references(vec![".get".to_string()]);
1918 b.add_nodes(vec![caller]);
1919 for (i, owner) in ["Cache", "Store", "Config"].iter().enumerate() {
1920 b.add_nodes(vec![CodeNode::new(
1921 "get",
1922 format!("{owner}.get"),
1923 NodeKind::Method,
1924 format!("m{i}.ts"),
1925 )]);
1926 }
1927 let graph = b.build();
1928
1929 assert_eq!(
1930 graph.edge_count(),
1931 0,
1932 "over the fan-out cap, so no edge should be guessed"
1933 );
1934 }
1935
1936 #[test]
1937 fn unimported_python_bare_call_links_neither_definition() {
1938 let mut b = GraphBuilder::new();
1939 let caller = CodeNode::new("main", "main", NodeKind::Function, "src/main.py")
1940 .with_references(vec!["process".to_string()]);
1941 b.add_nodes(vec![caller]);
1942 b.add_nodes(vec![CodeNode::new(
1943 "process",
1944 "process",
1945 NodeKind::Function,
1946 "src/utils.py",
1947 )]);
1948 b.add_nodes(vec![CodeNode::new(
1949 "process",
1950 "process",
1951 NodeKind::Function,
1952 "src/helpers.py",
1953 )]);
1954 let graph = b.build();
1955
1956 assert_eq!(graph.node_count(), 3, "both definitions stay in the graph");
1957 assert_eq!(
1958 graph.edge_count(),
1959 0,
1960 "an unimported bare call links to neither"
1961 );
1962 }
1963
1964 #[test]
1967 fn unimported_ts_cross_file_call_to_a_private_function_is_dropped() {
1968 let mut b = GraphBuilder::new();
1969 let import = CodeNode::new("./other", "./other", NodeKind::Import, "src/a/main.ts")
1970 .with_references(vec!["somethingElse".to_string()]);
1971 let caller = CodeNode::new("main", "main", NodeKind::Function, "src/a/main.ts")
1972 .with_references(vec!["validate".to_string()]);
1973 let callee_import = CodeNode::new("./util", "./util", NodeKind::Import, "src/z/far.ts")
1974 .with_references(vec!["util".to_string()]);
1975 let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/z/far.ts");
1976 b.add_nodes(vec![import, caller, callee_import, callee]);
1977 let graph = b.build();
1978
1979 assert_eq!(graph.edge_count(), 0);
1980 }
1981
1982 #[test]
1983 fn explicitly_imported_reference_is_strong() {
1984 let mut b = GraphBuilder::new();
1985 let import = CodeNode::new("./far", "./far", NodeKind::Import, "src/a/main.ts")
1986 .with_references(vec!["validate".to_string()]);
1987 let caller = CodeNode::new("main", "main", NodeKind::Function, "src/a/main.ts")
1988 .with_references(vec!["validate".to_string()]);
1989 let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/z/far.ts");
1990 b.add_nodes(vec![import, caller, callee]);
1991 let graph = b.build();
1992
1993 assert!(
1994 only_edge_confidence(&graph) >= Edge::CONFIDENT_THRESHOLD,
1995 "an explicit import is strong corroboration"
1996 );
1997 }
1998
1999 #[test]
2000 fn unimported_ts_same_dir_call_to_a_private_function_is_dropped() {
2001 let mut b = GraphBuilder::new();
2002 let import = CodeNode::new("./x", "./x", NodeKind::Import, "src/main.ts")
2003 .with_references(vec!["other".to_string()]);
2004 let caller = CodeNode::new("main", "main", NodeKind::Function, "src/main.ts")
2005 .with_references(vec!["validate".to_string()]);
2006 let callee_import = CodeNode::new("./util", "./util", NodeKind::Import, "src/sibling.ts")
2007 .with_references(vec!["util".to_string()]);
2008 let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/sibling.ts");
2009 b.add_nodes(vec![import, caller, callee_import, callee]);
2010 let graph = b.build();
2011
2012 assert_eq!(graph.edge_count(), 0);
2013 }
2014
2015 #[test]
2016 fn ts_same_file_bare_call_binds() {
2017 let mut b = GraphBuilder::new();
2018 let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/main.ts");
2019 let caller = CodeNode::new("main", "main", NodeKind::Function, "src/main.ts")
2020 .with_references(vec!["validate".to_string()]);
2021 b.add_nodes(vec![callee, caller]);
2022 let graph = b.build();
2023
2024 assert_eq!(graph.edge_count(), 1);
2025 }
2026
2027 #[test]
2028 fn build_is_deterministic_across_insertion_orders() {
2029 let make = |reverse: bool| {
2030 let mut b = GraphBuilder::new();
2031 let mut defs = vec![
2032 CodeNode::new("run", "A.run", NodeKind::Method, "src/a/a.ts"),
2033 CodeNode::new("run", "B.run", NodeKind::Method, "src/b/b.ts"),
2034 ];
2035 if reverse {
2036 defs.reverse();
2037 }
2038 b.add_nodes(vec![CodeNode::new(
2039 "main",
2040 "main",
2041 NodeKind::Function,
2042 "src/c/main.ts",
2043 )
2044 .with_references(vec!["run".to_string()])]);
2045 b.add_nodes(defs);
2046 let graph = b.build();
2047 let mut sig: Vec<String> = graph
2048 .export_edges()
2049 .into_iter()
2050 .map(|e| format!("{}->{}", e.source, e.target))
2051 .collect();
2052 sig.sort();
2053 sig
2054 };
2055
2056 assert_eq!(make(false), make(true));
2057 }
2058
2059 #[test]
2060 fn test_qualified_static_call_resolves_to_correct_class() {
2061 let mut b = GraphBuilder::new();
2065 let caller = CodeNode::new("compute", "Calc.compute", NodeKind::Method, "src/Calc.java")
2066 .with_references(vec!["MathUtils.add".to_string()]);
2067 let sibling = CodeNode::new("add", "Sibling.add", NodeKind::Method, "src/Sibling.java");
2069 let target = CodeNode::new(
2070 "add",
2071 "MathUtils.add",
2072 NodeKind::Method,
2073 "src/util/MathUtils.java",
2074 );
2075 b.add_nodes(vec![caller, sibling, target]);
2076 let graph = b.build();
2077
2078 let compute_idx = graph
2079 .node_indexes()
2080 .find(|&i| graph.get(i).unwrap().name == "compute")
2081 .unwrap();
2082 let callees = graph.get_callees(compute_idx);
2083 assert_eq!(callees.len(), 1, "exactly one resolved callee");
2084 assert_eq!(
2085 callees[0].qualified_name, "MathUtils.add",
2086 "static call must resolve to the qualified class, not a same-named sibling"
2087 );
2088 }
2089
2090 fn kinds_between(graph: &ArborGraph, from_q: &str, to_q: &str) -> Vec<EdgeKind> {
2091 let mut kinds = Vec::new();
2092 for edge in graph.graph.edge_references() {
2093 let source = graph.get(edge.source()).unwrap();
2094 let target = graph.get(edge.target()).unwrap();
2095 if source.qualified_name == from_q && target.qualified_name == to_q {
2096 kinds.push(edge.weight().kind);
2097 }
2098 }
2099 kinds
2100 }
2101
2102 fn inheritance_fixture() -> ArborGraph {
2103 let file = "hard/inheritance.py";
2104 let mut b = GraphBuilder::new();
2105 b.add_nodes(vec![
2106 CodeNode::new("Base", "Base", NodeKind::Class, file),
2107 CodeNode::new("compute", "Base.compute", NodeKind::Method, file),
2108 CodeNode::new("shared", "Base.shared", NodeKind::Method, file),
2109 CodeNode::new("Middle", "Middle", NodeKind::Class, file).with_extends(["Base"]),
2110 CodeNode::new("compute", "Middle.compute", NodeKind::Method, file)
2111 .with_references(vec!["super().compute".to_string()]),
2112 CodeNode::new("Derived", "Derived", NodeKind::Class, file).with_extends(["Middle"]),
2113 CodeNode::new("shared", "Derived.shared", NodeKind::Method, file),
2114 CodeNode::new("Leaf", "Leaf", NodeKind::Class, file).with_extends(["Derived"]),
2115 CodeNode::new("run", "Leaf.run", NodeKind::Method, file).with_references(vec![
2116 "self.compute".to_string(),
2117 "self.shared".to_string(),
2118 "len".to_string(),
2119 ]),
2120 CodeNode::new("UserService", "UserService", NodeKind::Class, file),
2122 ]);
2123 b.build()
2124 }
2125
2126 #[test]
2127 fn subclass_extends_its_base() {
2128 let graph = inheritance_fixture();
2129 assert_eq!(
2130 kinds_between(&graph, "Middle", "Base"),
2131 vec![EdgeKind::Extends]
2132 );
2133 assert_eq!(
2134 kinds_between(&graph, "Derived", "Middle"),
2135 vec![EdgeKind::Extends]
2136 );
2137 assert_eq!(
2138 kinds_between(&graph, "Leaf", "Derived"),
2139 vec![EdgeKind::Extends]
2140 );
2141 assert!(
2142 kinds_between(&graph, "UserService", "Base").is_empty(),
2143 "a class with no base is not an extender"
2144 );
2145
2146 let base = graph
2147 .node_indexes()
2148 .find(|&id| graph.get(id).unwrap().qualified_name == "Base")
2149 .unwrap();
2150 let reachers: Vec<_> = graph
2151 .direct_dependents(base)
2152 .into_iter()
2153 .map(|node| node.qualified_name.as_str())
2154 .collect();
2155 assert!(
2156 reachers.contains(&"Middle"),
2157 "Base is reached by Middle, got {reachers:?}"
2158 );
2159 assert!(graph.get_callers(base).is_empty(), "extends is not a call");
2160 }
2161
2162 #[test]
2163 fn inherited_method_reaches_the_defining_class_until_overridden() {
2164 let graph = inheritance_fixture();
2165
2166 assert_eq!(
2168 kinds_between(&graph, "Leaf.run", "Middle.compute"),
2169 vec![EdgeKind::Calls]
2170 );
2171 assert!(kinds_between(&graph, "Leaf.run", "Base.compute").is_empty());
2172
2173 assert_eq!(
2175 kinds_between(&graph, "Middle.compute", "Base.compute"),
2176 vec![EdgeKind::Calls]
2177 );
2178
2179 assert_eq!(
2181 kinds_between(&graph, "Leaf", "Middle.compute"),
2182 vec![EdgeKind::References]
2183 );
2184 assert!(kinds_between(&graph, "Leaf", "Base.compute").is_empty());
2185
2186 assert!(kinds_between(&graph, "Derived", "Base.shared").is_empty());
2188 assert!(kinds_between(&graph, "Leaf", "Base.shared").is_empty());
2189 assert_eq!(
2190 kinds_between(&graph, "Leaf.run", "Derived.shared"),
2191 vec![EdgeKind::Calls]
2192 );
2193 assert!(kinds_between(&graph, "Leaf.run", "Base.shared").is_empty());
2194
2195 assert_eq!(
2197 kinds_between(&graph, "Middle", "Base.shared"),
2198 vec![EdgeKind::References]
2199 );
2200
2201 let base_compute = graph
2202 .node_indexes()
2203 .find(|&id| graph.get(id).unwrap().qualified_name == "Base.compute")
2204 .unwrap();
2205 let impact = graph.analyze_impact(base_compute, 5);
2206 let upstream: Vec<_> = impact
2207 .upstream
2208 .iter()
2209 .map(|node| node.node_info.qualified_name.as_str())
2210 .collect();
2211 assert!(
2212 upstream.contains(&"Leaf"),
2213 "changing Base.compute must reach Leaf, got {upstream:?}"
2214 );
2215
2216 let base_shared = graph
2217 .node_indexes()
2218 .find(|&id| graph.get(id).unwrap().qualified_name == "Base.shared")
2219 .unwrap();
2220 let shared_impact = graph.analyze_impact(base_shared, 5);
2221 let direct: Vec<_> = shared_impact
2222 .direct_only()
2223 .into_iter()
2224 .map(|node| node.node_info.qualified_name.clone())
2225 .collect();
2226 assert!(
2227 direct.iter().any(|name| name == "Middle"),
2228 "Middle inherits shared, got {direct:?}"
2229 );
2230 assert!(
2231 direct
2232 .iter()
2233 .all(|name| name != "Derived" && name != "Leaf" && name != "Leaf.run"),
2234 "Derived's override must not make Base.shared a direct dependency, got {direct:?}"
2235 );
2236 }
2237
2238 #[test]
2239 fn diamond_inherits_the_nearest_override() {
2240 let file = "diamond.py";
2241 let mut b = GraphBuilder::new();
2242 b.add_nodes(vec![
2243 CodeNode::new("A", "A", NodeKind::Class, file),
2244 CodeNode::new("f", "A.f", NodeKind::Method, file),
2245 CodeNode::new("B", "B", NodeKind::Class, file).with_extends(["A"]),
2246 CodeNode::new("C", "C", NodeKind::Class, file).with_extends(["A"]),
2247 CodeNode::new("f", "C.f", NodeKind::Method, file),
2248 CodeNode::new("D", "D", NodeKind::Class, file).with_extends(["B", "C"]),
2249 ]);
2250 let graph = b.build();
2251 assert_eq!(
2252 kinds_between(&graph, "D", "C.f"),
2253 vec![EdgeKind::References],
2254 "D(B, C) sees C.f before A.f"
2255 );
2256 assert!(kinds_between(&graph, "D", "A.f").is_empty());
2257 }
2258
2259 #[test]
2260 fn super_stops_at_the_intermediate_override() {
2261 let file = "super_chain.py";
2262 let mut b = GraphBuilder::new();
2263 b.add_nodes(vec![
2264 CodeNode::new("A", "A", NodeKind::Class, file),
2265 CodeNode::new("foo", "A.foo", NodeKind::Method, file),
2266 CodeNode::new("B", "B", NodeKind::Class, file).with_extends(["A"]),
2267 CodeNode::new("foo", "B.foo", NodeKind::Method, file),
2268 CodeNode::new("C", "C", NodeKind::Class, file).with_extends(["B"]),
2269 CodeNode::new("foo", "C.foo", NodeKind::Method, file)
2270 .with_references(vec!["super().foo".to_string()]),
2271 ]);
2272 let graph = b.build();
2273 assert_eq!(
2274 kinds_between(&graph, "C.foo", "B.foo"),
2275 vec![EdgeKind::Calls],
2276 "super() in C must reach B's override"
2277 );
2278 assert!(
2279 kinds_between(&graph, "C.foo", "A.foo").is_empty(),
2280 "super() must not skip B and land on A"
2281 );
2282 }
2283
2284 #[test]
2285 fn python_unimported_len_has_no_callers() {
2286 let mut b = GraphBuilder::new();
2287 b.add_nodes(vec![CodeNode::new(
2288 "len",
2289 "len",
2290 NodeKind::Function,
2291 "hard/stdlib_shadow.py",
2292 )]);
2293 b.add_nodes(vec![CodeNode::new(
2294 "process",
2295 "process",
2296 NodeKind::Function,
2297 "hard/shadowed.py",
2298 )
2299 .with_references(vec!["len".to_string()])]);
2300 let import = CodeNode::new(
2301 "app.core.db",
2302 "app.core.db",
2303 NodeKind::Import,
2304 "app/services/auth.py",
2305 )
2306 .with_references(vec!["connect".to_string()]);
2307 let verify = CodeNode::new(
2308 "verify_token",
2309 "verify_token",
2310 NodeKind::Function,
2311 "app/services/auth.py",
2312 )
2313 .with_references(vec!["len".to_string()]);
2314 b.add_nodes(vec![import, verify]);
2315 let graph = b.build();
2316
2317 assert!(
2318 callers_of(&graph, "len", "stdlib_shadow.py").is_empty(),
2319 "a user len must not absorb builtin-shaped calls"
2320 );
2321 }
2322
2323 #[test]
2324 fn python_local_len_binds_to_its_own_definition() {
2325 let mut b = GraphBuilder::new();
2326 let len_def = CodeNode::new("len", "len", NodeKind::Function, "hard/stdlib_shadow.py");
2327 let uses = CodeNode::new(
2328 "uses_len",
2329 "uses_len",
2330 NodeKind::Function,
2331 "hard/stdlib_shadow.py",
2332 )
2333 .with_references(vec!["len".to_string()]);
2334 b.add_nodes(vec![len_def, uses]);
2335 let graph = b.build();
2336
2337 let callers = callers_of(&graph, "len", "stdlib_shadow.py");
2338 assert_eq!(callers.len(), 1);
2339 assert_eq!(callers[0].name, "uses_len");
2340 }
2341
2342 #[test]
2343 fn python_imported_len_binds_to_the_imported_definition() {
2344 let mut b = GraphBuilder::new();
2345 b.add_nodes(vec![CodeNode::new(
2346 "len",
2347 "len",
2348 NodeKind::Function,
2349 "hard/stdlib_shadow.py",
2350 )]);
2351 let import = CodeNode::new(
2352 "hard.stdlib_shadow",
2353 "hard.stdlib_shadow",
2354 NodeKind::Import,
2355 "app/caller.py",
2356 )
2357 .with_references(vec!["len".to_string()]);
2358 let caller = CodeNode::new("use", "use", NodeKind::Function, "app/caller.py")
2359 .with_references(vec!["len".to_string()]);
2360 b.add_nodes(vec![import, caller]);
2361 let graph = b.build();
2362
2363 let callers = callers_of(&graph, "len", "stdlib_shadow.py");
2364 assert_eq!(callers.len(), 1);
2365 assert_eq!(callers[0].name, "use");
2366 }
2367
2368 #[test]
2369 fn python_star_import_keeps_a_bare_cross_file_call() {
2370 let mut b = GraphBuilder::new();
2371 b.add_nodes(vec![CodeNode::new(
2372 "len",
2373 "len",
2374 NodeKind::Function,
2375 "hard/stdlib_shadow.py",
2376 )]);
2377 let import = CodeNode::new("helpers", "helpers", NodeKind::Import, "app/caller.py")
2378 .with_references(vec!["*".to_string()]);
2379 let caller = CodeNode::new("use", "use", NodeKind::Function, "app/caller.py")
2380 .with_references(vec!["len".to_string()]);
2381 b.add_nodes(vec![import, caller]);
2382 let graph = b.build();
2383
2384 assert_eq!(callers_of(&graph, "len", "stdlib_shadow.py").len(), 1);
2385 assert!(only_edge_confidence(&graph) < Edge::CONFIDENT_THRESHOLD);
2388 }
2389
2390 #[test]
2391 fn qualified_module_call_does_not_bind_bare_len() {
2392 let mut b = GraphBuilder::new();
2393 b.add_nodes(vec![CodeNode::new(
2394 "len",
2395 "len",
2396 NodeKind::Function,
2397 "hard/stdlib_shadow.py",
2398 )]);
2399 let import = CodeNode::new(
2401 "len_module",
2402 "len_module",
2403 NodeKind::Import,
2404 "app/caller.py",
2405 );
2406 let caller = CodeNode::new("use", "use", NodeKind::Function, "app/caller.py")
2407 .with_references(vec!["len_module.len".to_string()]);
2408 b.add_nodes(vec![import, caller]);
2409 let graph = b.build();
2410
2411 assert!(callers_of(&graph, "len", "stdlib_shadow.py").is_empty());
2412 }
2413
2414 #[test]
2415 fn shadowed_process_keeps_local_and_explicitly_imported_callers() {
2416 let mut b = GraphBuilder::new();
2417 b.add_nodes(vec![
2418 CodeNode::new("process", "process", NodeKind::Function, "hard/shadowed.py"),
2419 CodeNode::new("caller", "caller", NodeKind::Function, "hard/shadowed.py")
2420 .with_references(vec!["process".to_string()]),
2421 CodeNode::new(
2422 "process",
2423 "process",
2424 NodeKind::Function,
2425 "hard/shadow_other.py",
2426 ),
2427 CodeNode::new(
2428 "other_caller",
2429 "other_caller",
2430 NodeKind::Function,
2431 "hard/shadow_other.py",
2432 )
2433 .with_references(vec!["process".to_string()]),
2434 ]);
2435 let import = CodeNode::new(
2436 "hard.shadowed",
2437 "hard.shadowed",
2438 NodeKind::Import,
2439 "hard/conditional.py",
2440 )
2441 .with_references(vec!["process".to_string()]);
2442 let imported_caller = CodeNode::new(
2443 "function_local_import",
2444 "function_local_import",
2445 NodeKind::Function,
2446 "hard/conditional.py",
2447 )
2448 .with_references(vec!["process".to_string()]);
2449 b.add_nodes(vec![import, imported_caller]);
2450 let graph = b.build();
2451
2452 let shadowed = callers_of(&graph, "process", "hard/shadowed.py");
2453 let other = callers_of(&graph, "process", "hard/shadow_other.py");
2454 assert_eq!(shadowed.len(), 2, "local caller plus the explicit import");
2455 assert_eq!(
2456 other.len(),
2457 1,
2458 "the sibling call stays on its own definition"
2459 );
2460 let mut shadowed_names: Vec<&str> = shadowed.iter().map(|n| n.name.as_str()).collect();
2461 shadowed_names.sort();
2462 assert_eq!(shadowed_names, vec!["caller", "function_local_import"]);
2463 assert_eq!(other[0].name, "other_caller");
2464 }
2465
2466 #[test]
2472 fn an_alias_reaches_the_original_function_and_a_module_alias_call_does_not() {
2473 let mut b = GraphBuilder::new();
2474 b.add_nodes(vec![CodeNode::new(
2475 "original_function",
2476 "original_function",
2477 NodeKind::Function,
2478 "hard/reexport_base.py",
2479 )]);
2480 let import = CodeNode::new(
2481 "hard.reexport_base",
2482 "hard.reexport_base",
2483 NodeKind::Import,
2484 "hard/aliased.py",
2485 )
2486 .with_references(vec![arbor_core::import_alias_ref(
2487 "renamed",
2488 "original_function",
2489 )]);
2490 let via_alias = CodeNode::new(
2491 "via_alias",
2492 "via_alias",
2493 NodeKind::Function,
2494 "hard/aliased.py",
2495 )
2496 .with_references(vec!["renamed".to_string()]);
2497 let via_module = CodeNode::new(
2498 "via_module_alias",
2499 "via_module_alias",
2500 NodeKind::Function,
2501 "hard/aliased.py",
2502 )
2503 .with_references(vec!["base_mod.original_function".to_string()]);
2504 b.add_nodes(vec![import, via_alias, via_module]);
2505 let graph = b.build();
2506
2507 let callers: Vec<&str> = callers_of(&graph, "original_function", "reexport_base.py")
2508 .iter()
2509 .map(|n| n.name.as_str())
2510 .collect();
2511 assert_eq!(callers, vec!["via_alias"]);
2512 }
2513
2514 fn callers_of<'a>(
2515 graph: &'a ArborGraph,
2516 name: &str,
2517 file_frag: &str,
2518 ) -> Vec<&'a arbor_core::CodeNode> {
2519 graph
2520 .node_indexes()
2521 .filter_map(|idx| {
2522 let node = graph.get(idx)?;
2523 if node.name == name && node.file.contains(file_frag) {
2524 Some(graph.get_callers(idx))
2525 } else {
2526 None
2527 }
2528 })
2529 .next()
2530 .unwrap_or_default()
2531 }
2532
2533 #[test]
2534 fn go_same_package_bare_call_is_kept() {
2535 let mut b = GraphBuilder::new();
2536 let import = CodeNode::new("fmt", "fmt", NodeKind::Import, "pkg/a.go");
2537 let caller = CodeNode::new("main", "main", NodeKind::Function, "pkg/a.go")
2538 .with_references(vec!["helper".to_string()]);
2539 let callee = CodeNode::new("helper", "helper", NodeKind::Function, "pkg/b.go");
2540 b.add_nodes(vec![
2541 go_package("handler", "pkg/a.go"),
2542 go_package("handler", "pkg/b.go"),
2543 import,
2544 caller,
2545 callee,
2546 ]);
2547 let graph = b.build();
2548
2549 assert_eq!(graph.edge_count(), 1);
2550 }
2551
2552 #[test]
2553 fn go_same_clause_in_another_directory_is_dropped() {
2554 let mut b = GraphBuilder::new();
2555 let caller = CodeNode::new("main", "main", NodeKind::Function, "cmd/a.go")
2556 .with_references(vec!["helper".to_string()]);
2557 let callee = CodeNode::new("helper", "helper", NodeKind::Function, "pkg/b.go");
2558 b.add_nodes(vec![
2559 go_package("main", "cmd/a.go"),
2560 go_package("main", "pkg/b.go"),
2561 caller,
2562 callee,
2563 ]);
2564 let graph = b.build();
2565
2566 assert_eq!(graph.edge_count(), 0);
2567 }
2568
2569 #[test]
2570 fn go_external_test_package_does_not_bind_a_bare_name() {
2571 let mut b = GraphBuilder::new();
2572 let caller = CodeNode::new(
2573 "TestHelper",
2574 "TestHelper",
2575 NodeKind::Function,
2576 "pkg/a_test.go",
2577 )
2578 .with_references(vec!["helper".to_string()]);
2579 let callee = CodeNode::new("helper", "helper", NodeKind::Function, "pkg/a.go");
2580 b.add_nodes(vec![
2581 go_package("foo_test", "pkg/a_test.go"),
2582 go_package("foo", "pkg/a.go"),
2583 caller,
2584 callee,
2585 ]);
2586 let graph = b.build();
2587
2588 assert_eq!(graph.edge_count(), 0);
2589 }
2590
2591 #[test]
2592 fn go_len_does_not_bind_to_a_python_definition() {
2593 let mut b = GraphBuilder::new();
2594 b.add_nodes(vec![CodeNode::new(
2595 "len",
2596 "len",
2597 NodeKind::Function,
2598 "hard/stdlib_shadow.py",
2599 )]);
2600 let caller = CodeNode::new(
2601 "HandleRequest",
2602 "HandleRequest",
2603 NodeKind::Function,
2604 "poly/go/handler/handler.go",
2605 )
2606 .with_references(vec!["len".to_string()]);
2607 b.add_nodes(vec![
2608 go_package("handler", "poly/go/handler/handler.go"),
2609 caller,
2610 ]);
2611 let graph = b.build();
2612
2613 assert!(callers_of(&graph, "len", "stdlib_shadow.py").is_empty());
2614 }
2615
2616 #[test]
2617 fn rust_use_does_not_drop_a_bare_cross_file_call() {
2618 assert_residual_bare_call_links("crate::helper", "src/main.rs", "src/helper.rs");
2619 }
2620
2621 #[test]
2622 fn c_include_does_not_drop_a_bare_cross_file_call() {
2623 assert_residual_bare_call_links("foo.h", "src/main.c", "src/foo.c");
2624 }
2625
2626 #[test]
2627 fn java_import_does_not_drop_a_bare_cross_file_call() {
2628 assert_residual_bare_call_links("com.example.Helper", "src/Main.java", "src/Helper.java");
2629 }
2630
2631 #[test]
2632 fn csharp_using_does_not_drop_a_bare_cross_file_call() {
2633 assert_residual_bare_call_links("Example", "src/Main.cs", "src/Helper.cs");
2634 }
2635
2636 #[test]
2637 fn dart_import_does_not_drop_a_bare_cross_file_call() {
2638 assert_residual_bare_call_links(
2639 "package:app/helper.dart",
2640 "lib/main.dart",
2641 "lib/helper.dart",
2642 );
2643 }
2644
2645 fn go_package(name: &str, file: &str) -> CodeNode {
2646 CodeNode::new(name, name, NodeKind::Module, file)
2647 }
2648
2649 fn assert_residual_bare_call_links(import_name: &str, caller_file: &str, callee_file: &str) {
2652 let mut b = GraphBuilder::new();
2653 let import = CodeNode::new(import_name, import_name, NodeKind::Import, caller_file);
2654 let caller = CodeNode::new("main", "main", NodeKind::Function, caller_file)
2655 .with_references(vec!["helper".to_string()]);
2656 let callee = CodeNode::new("helper", "helper", NodeKind::Function, callee_file);
2657 b.add_nodes(vec![import, caller, callee]);
2658 let graph = b.build();
2659 assert_eq!(
2660 graph.edge_count(),
2661 1,
2662 "{caller_file} should still call {callee_file}"
2663 );
2664 }
2665
2666 #[test]
2667 fn bare_name_visibility_matches_python_and_js_extensions() {
2668 assert!(bare_name_requires_import(Path::new(
2669 "hard/stdlib_shadow.py"
2670 )));
2671 assert!(bare_name_requires_import(Path::new("stubs/mod.pyi")));
2672 assert!(bare_name_requires_import(Path::new("HARD/LEN.PY")));
2673 assert!(bare_name_requires_import(Path::new("src/main.ts")));
2674 assert!(bare_name_requires_import(Path::new("src/App.tsx")));
2675 assert!(bare_name_requires_import(Path::new("src/app.js")));
2676 assert!(bare_name_requires_import(Path::new("src/app.jsx")));
2677 assert!(bare_name_requires_import(Path::new("src/app.mts")));
2678 assert!(bare_name_requires_import(Path::new("src/app.cts")));
2679 assert!(bare_name_requires_import(Path::new("src/app.mjs")));
2680 assert!(bare_name_requires_import(Path::new("src/app.cjs")));
2681 assert!(!bare_name_requires_import(Path::new("pkg/a.go")));
2682 assert!(!bare_name_requires_import(Path::new("src/main.rs")));
2683 assert!(!bare_name_requires_import(Path::new("src/Main.java")));
2684 assert!(!bare_name_requires_import(Path::new("src/Main.cs")));
2685 assert!(!bare_name_requires_import(Path::new("lib/main.dart")));
2686 assert!(!bare_name_requires_import(Path::new("src/main.c")));
2687 assert!(!bare_name_requires_import(Path::new("Makefile")));
2688 }
2689}
2690
2691#[cfg(test)]
2692mod rust_path_tests {
2693 use super::*;
2694 use arbor_core::NodeKind;
2695
2696 fn function(name: &str, file: &str, calls: &[&str]) -> CodeNode {
2697 CodeNode::new(name, name, NodeKind::Function, file)
2698 .with_references(calls.iter().map(|c| c.to_string()).collect())
2699 }
2700
2701 fn method(owner: &str, name: &str, file: &str, calls: &[&str]) -> CodeNode {
2702 CodeNode::new(name, format!("{owner}.{name}"), NodeKind::Method, file)
2703 .with_references(calls.iter().map(|c| c.to_string()).collect())
2704 }
2705
2706 fn callers_of(graph: &ArborGraph, name: &str, file: &str) -> Vec<String> {
2707 let id = graph
2708 .node_indexes()
2709 .find(|id| {
2710 graph
2711 .get(*id)
2712 .is_some_and(|n| n.name == name && n.file == file)
2713 })
2714 .unwrap_or_else(|| panic!("no {name} in {file}"));
2715 let mut names: Vec<String> = graph
2716 .get_callers(id)
2717 .into_iter()
2718 .map(|n| n.name.clone())
2719 .collect();
2720 names.sort();
2721 names
2722 }
2723
2724 #[test]
2725 fn module_paths_resolve_to_the_named_module_and_never_across_languages() {
2726 let mut b = GraphBuilder::new();
2727 b.add_nodes(vec![
2728 function("enqueue", "src/app/jobs.rs", &[]),
2729 function("enqueue", "src/billing/jobs_old.rs", &[]),
2730 function("enqueue", "web/src/components/Toast.tsx", &[]),
2731 function("dispatch", "src/app/dispatch.rs", &["jobs::enqueue"]),
2732 function("start", "web/src/lib/bridge.ts", &["enqueue"]),
2733 ]);
2734 let graph = b.build();
2735 assert_eq!(
2736 callers_of(&graph, "enqueue", "src/app/jobs.rs"),
2737 vec!["dispatch"]
2738 );
2739 assert!(callers_of(&graph, "enqueue", "src/billing/jobs_old.rs").is_empty());
2740 assert_eq!(
2742 callers_of(&graph, "enqueue", "web/src/components/Toast.tsx"),
2743 vec!["start"]
2744 );
2745 }
2746
2747 #[test]
2748 fn mod_rs_crate_prefixes_and_re_exports_resolve() {
2749 let mut b = GraphBuilder::new();
2750 b.add_nodes(vec![
2751 function("create_project", "src/app/mod.rs", &[]),
2752 function("record", "src/app/audit/writer.rs", &[]),
2753 function(
2754 "handler",
2755 "src/routes/mod.rs",
2756 &["app::create_project", "app::audit::record"],
2757 ),
2758 function(
2759 "persistence_test",
2760 "tests/integration.rs",
2761 &["my_app::app::create_project", "app::record"],
2762 ),
2763 ]);
2764 let graph = b.build();
2765 assert_eq!(
2766 callers_of(&graph, "create_project", "src/app/mod.rs"),
2767 vec!["handler", "persistence_test"]
2768 );
2769 assert_eq!(
2771 callers_of(&graph, "record", "src/app/audit/writer.rs"),
2772 vec!["handler", "persistence_test"]
2773 );
2774 }
2775
2776 #[test]
2777 fn external_crate_paths_do_not_bind_to_local_names() {
2778 let mut b = GraphBuilder::new();
2779 b.add_nodes(vec![
2780 function("query", "src/db/queries.rs", &[]),
2781 function("load", "src/routes/mod.rs", &["sqlx::query"]),
2782 ]);
2783 let graph = b.build();
2784 assert!(callers_of(&graph, "query", "src/db/queries.rs").is_empty());
2785 }
2786
2787 #[test]
2788 fn type_paths_resolve_to_the_types_method() {
2789 let mut b = GraphBuilder::new();
2790 b.add_nodes(vec![
2791 CodeNode::new(
2792 "Provider",
2793 "Provider",
2794 NodeKind::Struct,
2795 "src/billing/mod.rs",
2796 ),
2797 method("Provider", "new", "src/billing/mod.rs", &[]),
2798 method("Fixture", "new", "tests/fixture.rs", &[]),
2799 function("boot", "src/main.rs", &["Provider::new"]),
2800 ]);
2801 let graph = b.build();
2802 assert_eq!(
2803 callers_of(&graph, "new", "src/billing/mod.rs"),
2804 vec!["boot"]
2805 );
2806 assert!(callers_of(&graph, "new", "tests/fixture.rs").is_empty());
2807 }
2808
2809 #[test]
2810 fn a_mock_struct_with_the_same_name_does_not_hide_the_real_owner() {
2811 let mut b = GraphBuilder::new();
2812 b.add_nodes(vec![
2813 CodeNode::new(
2814 "Provider",
2815 "Provider",
2816 NodeKind::Struct,
2817 "src/payments/mod.rs",
2818 ),
2819 CodeNode::new("Provider", "Provider", NodeKind::Struct, "tests/mocks.rs"),
2820 method("Provider", "owner_of", "src/payments/checkout.rs", &[]),
2821 method(
2822 "Provider",
2823 "order_history",
2824 "src/payments/cancellation.rs",
2825 &["self.owner_of", ".bind"],
2826 ),
2827 function("bind", "src/payments/tests.rs", &[]),
2828 ]);
2829 let graph = b.build();
2830 assert_eq!(
2831 callers_of(&graph, "owner_of", "src/payments/checkout.rs"),
2832 vec!["order_history"]
2833 );
2834 assert!(callers_of(&graph, "bind", "src/payments/tests.rs").is_empty());
2836 }
2837
2838 #[test]
2839 fn self_calls_reach_methods_whose_impl_is_in_another_file() {
2840 let mut b = GraphBuilder::new();
2841 b.add_nodes(vec![
2842 CodeNode::new(
2843 "Provider",
2844 "Provider",
2845 NodeKind::Struct,
2846 "src/payments/mod.rs",
2847 ),
2848 method("Provider", "owner_of", "src/payments/checkout.rs", &[]),
2849 method(
2850 "Provider",
2851 "order_history",
2852 "src/payments/cancellation.rs",
2853 &["self.owner_of"],
2854 ),
2855 ]);
2856 let graph = b.build();
2857 assert_eq!(
2858 callers_of(&graph, "owner_of", "src/payments/checkout.rs"),
2859 vec!["order_history"]
2860 );
2861 }
2862}
2863
2864#[cfg(test)]
2867mod import_alias_tests {
2868 use super::*;
2869 use petgraph::visit::{EdgeRef, IntoEdgeReferences};
2870 use std::collections::BTreeSet;
2871
2872 pub(super) fn index(files: &[(&str, &str)]) -> ArborGraph {
2875 let mut builder = GraphBuilder::new();
2876 for (path, source) in files {
2877 let ext = Path::new(path)
2878 .extension()
2879 .and_then(|e| e.to_str())
2880 .expect("extension");
2881 let parser = arbor_core::languages::get_parser(ext).expect("parser");
2882 builder
2883 .add_nodes(arbor_core::parse_source(source, path, parser.as_ref()).expect("parse"));
2884 }
2885 builder.build()
2886 }
2887
2888 pub(super) fn calls(graph: &ArborGraph) -> BTreeSet<String> {
2890 graph
2891 .graph
2892 .edge_references()
2893 .filter(|e| e.weight().kind == EdgeKind::Calls)
2894 .map(|e| {
2895 let from = &graph.graph[e.source()];
2896 let to = &graph.graph[e.target()];
2897 format!("{}::{} -> {}::{}", from.file, from.name, to.file, to.name)
2898 })
2899 .collect()
2900 }
2901
2902 pub(super) fn edges(expected: &[&str]) -> BTreeSet<String> {
2903 expected.iter().map(|e| e.to_string()).collect()
2904 }
2905
2906 const MONEY: &str = "\
2907def money_to_minor_units(amount, currency):
2908 return int(round(amount * 100))
2909
2910
2911def minor_unit_scale(currency):
2912 return 2
2913";
2914
2915 #[test]
2917 fn aliased_import_call_reaches_the_imported_function() {
2918 let graph = index(&[
2919 ("money.py", MONEY),
2920 (
2921 "orders.py",
2922 "\
2923from money import money_to_minor_units as to_minor
2924
2925
2926def total_cents(items):
2927 return sum(to_minor(item[\"price\"], \"USD\") for item in items)
2928",
2929 ),
2930 ]);
2931 assert_eq!(
2932 calls(&graph),
2933 edges(&["orders.py::total_cents -> money.py::money_to_minor_units"])
2934 );
2935 }
2936
2937 #[test]
2938 fn alias_from_a_dotted_module_reaches_that_module_only() {
2939 let graph = index(&[
2940 ("billing/money.py", MONEY),
2941 ("legacy/money.py", MONEY),
2942 (
2943 "app/orders.py",
2944 "\
2945from billing.money import money_to_minor_units as to_minor
2946
2947
2948def total_cents(items):
2949 return sum(to_minor(item, \"USD\") for item in items)
2950",
2951 ),
2952 ]);
2953 assert_eq!(
2954 calls(&graph),
2955 edges(&["app/orders.py::total_cents -> billing/money.py::money_to_minor_units"])
2956 );
2957 }
2958
2959 #[test]
2960 fn alias_from_a_relative_module_reaches_the_sibling_module() {
2961 let graph = index(&[
2962 ("shop/money.py", MONEY),
2963 ("other/money.py", MONEY),
2964 (
2965 "shop/orders.py",
2966 "\
2967from .money import money_to_minor_units as to_minor
2968
2969
2970def total_cents(items):
2971 return sum(to_minor(item, \"USD\") for item in items)
2972",
2973 ),
2974 ]);
2975 assert_eq!(
2976 calls(&graph),
2977 edges(&["shop/orders.py::total_cents -> shop/money.py::money_to_minor_units"])
2978 );
2979 }
2980
2981 #[test]
2982 fn several_aliases_in_one_import_each_reach_their_own_target() {
2983 let graph = index(&[
2984 ("money.py", MONEY),
2985 (
2986 "orders.py",
2987 "\
2988from money import money_to_minor_units as to_minor, minor_unit_scale as scale
2989
2990
2991def total_cents(amount):
2992 return to_minor(amount, \"USD\") * scale(\"USD\")
2993",
2994 ),
2995 (
2996 "invoices.py",
2997 "\
2998from money import (
2999 money_to_minor_units as cents,
3000 minor_unit_scale as digits,
3001)
3002
3003
3004def invoice_total(amount):
3005 return cents(amount, \"EUR\") + digits(\"EUR\")
3006",
3007 ),
3008 ]);
3009 assert_eq!(
3010 calls(&graph),
3011 edges(&[
3012 "invoices.py::invoice_total -> money.py::minor_unit_scale",
3013 "invoices.py::invoice_total -> money.py::money_to_minor_units",
3014 "orders.py::total_cents -> money.py::minor_unit_scale",
3015 "orders.py::total_cents -> money.py::money_to_minor_units",
3016 ])
3017 );
3018 }
3019
3020 #[test]
3023 fn alias_reaches_its_target_not_a_function_named_like_the_alias() {
3024 let graph = index(&[
3025 ("fmt_a.py", "def render(value):\n return f\"A{value}\"\n"),
3026 ("fmt_b.py", "def fmt(value):\n return f\"B{value}\"\n"),
3027 (
3028 "app.py",
3029 "\
3030from fmt_a import render as fmt
3031
3032
3033def show(value):
3034 return fmt(value)
3035",
3036 ),
3037 ]);
3038 assert_eq!(calls(&graph), edges(&["app.py::show -> fmt_a.py::render"]));
3039 }
3040
3041 #[test]
3044 fn an_alias_that_is_never_called_adds_no_edge() {
3045 let graph = index(&[
3046 ("money.py", MONEY),
3047 (
3048 "orders.py",
3049 "\
3050from money import money_to_minor_units as to_minor, minor_unit_scale as scale
3051
3052
3053def total_cents(amount):
3054 return to_minor(amount, \"USD\")
3055
3056
3057def describe(order):
3058 return str(order)
3059",
3060 ),
3061 ]);
3062 assert_eq!(
3063 calls(&graph),
3064 edges(&["orders.py::total_cents -> money.py::money_to_minor_units"])
3065 );
3066 }
3067
3068 #[test]
3071 fn a_wrapper_named_like_the_imported_function_reaches_the_import() {
3072 let graph = index(&[
3073 ("money.py", MONEY),
3074 (
3075 "compat.py",
3076 "\
3077from money import money_to_minor_units as _impl
3078
3079
3080def money_to_minor_units(amount):
3081 return _impl(amount, \"USD\")
3082",
3083 ),
3084 ]);
3085 assert_eq!(
3086 calls(&graph),
3087 edges(&["compat.py::money_to_minor_units -> money.py::money_to_minor_units"])
3088 );
3089 }
3090
3091 #[test]
3094 fn a_local_definition_of_the_alias_name_still_shadows_the_import() {
3095 let graph = index(&[
3096 ("money.py", MONEY),
3097 (
3098 "orders.py",
3099 "\
3100from money import money_to_minor_units as to_minor
3101
3102
3103def to_minor(amount, currency):
3104 return amount
3105
3106
3107def total_cents(amount):
3108 return to_minor(amount, \"USD\")
3109",
3110 ),
3111 ]);
3112 assert_eq!(
3113 calls(&graph),
3114 edges(&["orders.py::total_cents -> orders.py::to_minor"])
3115 );
3116 }
3117
3118 #[test]
3120 fn an_alias_of_an_external_name_links_nothing() {
3121 let graph = index(&[
3122 (
3123 "helpers.py",
3124 "def array(values):\n return list(values)\n",
3125 ),
3126 (
3127 "calc.py",
3128 "\
3129from numpy import array as arr
3130
3131
3132def build(values):
3133 return arr(values)
3134",
3135 ),
3136 ]);
3137 assert_eq!(calls(&graph), edges(&[]));
3138 }
3139
3140 #[test]
3145 fn a_package_stub_does_not_hide_the_implementation_from_an_alias() {
3146 let graph = index(&[
3147 ("attr/__init__.pyi", "def evolve(inst, **changes): ...\n"),
3148 ("attr/__init__.py", "from ._funcs import evolve\n"),
3149 (
3150 "attr/_funcs.py",
3151 "def evolve(inst, **changes):\n return inst\n",
3152 ),
3153 (
3154 "app.py",
3155 "\
3156from attr import evolve as ev
3157
3158
3159def run(x):
3160 return ev(x)
3161",
3162 ),
3163 (
3164 "plain.py",
3165 "\
3166from attr import evolve
3167
3168
3169def run2(x):
3170 return evolve(x)
3171",
3172 ),
3173 ]);
3174 let reached = |caller: &str| -> BTreeSet<String> {
3175 calls(&graph)
3176 .into_iter()
3177 .filter_map(|e| e.strip_prefix(&format!("{caller} -> ")).map(str::to_string))
3178 .collect()
3179 };
3180 assert!(reached("app.py::run").contains("attr/_funcs.py::evolve"));
3181 assert_eq!(reached("app.py::run"), reached("plain.py::run2"));
3182 }
3183
3184 #[test]
3188 fn an_external_module_named_like_a_project_file_binds_like_a_plain_import() {
3189 let graph = index(&[
3190 (
3191 "src/lib/http.ts",
3192 "export function request(url: string): string {\n return url;\n}\n",
3193 ),
3194 (
3195 "src/aliased.ts",
3196 "\
3197import { request as httpRequest } from \"http\";
3198
3199export function go(url: string): string {
3200 return httpRequest(url);
3201}
3202",
3203 ),
3204 (
3205 "src/plain.ts",
3206 "\
3207import { request } from \"http\";
3208
3209export function go(url: string): string {
3210 return request(url);
3211}
3212",
3213 ),
3214 ]);
3215 assert_eq!(
3216 calls(&graph),
3217 edges(&[
3218 "src/aliased.ts::go -> src/lib/http.ts::request",
3219 "src/plain.ts::go -> src/lib/http.ts::request",
3220 ])
3221 );
3222 }
3223
3224 #[test]
3227 fn typescript_named_import_alias_reaches_the_imported_function() {
3228 let graph = index(&[
3229 (
3230 "format.ts",
3231 "export function formatName(first: string, last: string): string {\n return `${last}, ${first}`;\n}\n",
3232 ),
3233 (
3234 "legacy/fmt.ts",
3235 "export function fmt(value: string): string {\n return value;\n}\n",
3236 ),
3237 (
3238 "app.ts",
3239 "\
3240import { formatName as fmt } from \"./format\";
3241
3242export function label(first: string, last: string): string {
3243 return fmt(first, last);
3244}
3245",
3246 ),
3247 ]);
3248 assert_eq!(
3249 calls(&graph),
3250 edges(&["app.ts::label -> format.ts::formatName"])
3251 );
3252 }
3253
3254 #[test]
3257 fn a_relative_typescript_alias_reaches_only_the_file_it_names() {
3258 let post = "export async function POST(req: Request) {\n return req;\n}\n";
3259 let graph = index(&[
3260 ("app/api/subscribe/route.ts", post),
3261 ("app/api/waitlist/route.ts", post),
3262 ("app/api/admin/route.ts", post),
3263 (
3264 "app/api/subscribe/__tests__/route.test.ts",
3265 "\
3266import { POST as subscribe } from \"../route\";
3267
3268export async function postsTheForm(req: Request) {
3269 return subscribe(req);
3270}
3271",
3272 ),
3273 ]);
3274 assert_eq!(
3275 calls(&graph),
3276 edges(&[
3277 "app/api/subscribe/__tests__/route.test.ts::postsTheForm -> app/api/subscribe/route.ts::POST"
3278 ])
3279 );
3280 }
3281
3282 #[test]
3284 fn a_relative_python_alias_reaches_only_the_module_it_names() {
3285 let graph = index(&[
3286 ("shop/money.py", MONEY),
3287 ("other/money.py", MONEY),
3288 (
3289 "shop/checkout/orders.py",
3290 "\
3291from ..money import money_to_minor_units as to_minor
3292
3293
3294def total_cents(amount):
3295 return to_minor(amount, \"USD\")
3296",
3297 ),
3298 ]);
3299 assert_eq!(
3300 calls(&graph),
3301 edges(&["shop/checkout/orders.py::total_cents -> shop/money.py::money_to_minor_units"])
3302 );
3303 }
3304
3305 #[test]
3308 fn an_alias_from_a_package_reaches_its_init_not_a_submodule() {
3309 let graph = index(&[
3310 ("pkg/__init__.py", "def f(x):\n return x\n"),
3311 ("pkg/sub.py", "def f(x):\n return -x\n"),
3312 (
3313 "app.py",
3314 "\
3315from pkg import f as g
3316
3317
3318def run(x):
3319 return g(x)
3320",
3321 ),
3322 ]);
3323 assert_eq!(calls(&graph), edges(&["app.py::run -> pkg/__init__.py::f"]));
3324 }
3325
3326 #[test]
3330 fn a_relative_alias_to_a_re_export_links_nothing_else() {
3331 let post = "export async function POST(req: Request) {\n return req;\n}\n";
3332 let graph = index(&[
3333 (
3334 "app/api/subscribe/route.ts",
3335 "export { POST } from \"../waitlist/route\";\n",
3336 ),
3337 ("app/api/admin/route.ts", post),
3338 ("app/api/reports/route.ts", post),
3339 (
3340 "app/api/subscribe/__tests__/route.test.ts",
3341 "\
3342import { POST as subscribe } from \"../route\";
3343
3344export async function postsTheForm(req: Request) {
3345 return subscribe(req);
3346}
3347",
3348 ),
3349 ]);
3350 assert_eq!(calls(&graph), edges(&[]));
3351 }
3352}
3353
3354#[cfg(test)]
3359mod commonjs_visibility_tests {
3360 use super::import_alias_tests::{calls, edges, index};
3361
3362 const DECOY_HELPER_JS: &str =
3365 "const fs = require(\"fs\");\n\nfunction helper(x) {\n return fs.existsSync(x);\n}\n";
3366
3367 const UTILS: &str = "\
3368function helper(x) {
3369 return x * 2;
3370}
3371
3372module.exports = { helper };
3373";
3374
3375 #[test]
3377 fn a_destructured_require_keeps_the_call() {
3378 let graph = index(&[
3379 ("utils.js", UTILS),
3380 (
3381 "index.js",
3382 "\
3383const { helper } = require(\"./utils\");
3384
3385function main() {
3386 return helper(21);
3387}
3388",
3389 ),
3390 ]);
3391 assert_eq!(
3392 calls(&graph),
3393 edges(&["index.js::main -> utils.js::helper"])
3394 );
3395 }
3396
3397 #[test]
3400 fn a_renamed_destructured_require_reaches_the_exported_name() {
3401 let graph = index(&[
3402 ("utils.js", UTILS),
3403 (
3404 "legacy/twice.js",
3405 "function twice(x) {\n return x + x;\n}\n",
3406 ),
3407 (
3408 "index.js",
3409 "\
3410const { helper: twice } = require(\"./utils\");
3411
3412function main() {
3413 return twice(21);
3414}
3415",
3416 ),
3417 ]);
3418 assert_eq!(
3419 calls(&graph),
3420 edges(&["index.js::main -> utils.js::helper"])
3421 );
3422 }
3423
3424 #[test]
3426 fn a_property_of_a_required_module_reaches_that_export() {
3427 let graph = index(&[
3428 ("utils.js", UTILS),
3429 (
3430 "legacy/twice.js",
3431 "function twice(x) {\n return x + x;\n}\n",
3432 ),
3433 (
3434 "index.js",
3435 "\
3436const twice = require(\"./utils\").helper;
3437
3438function main() {
3439 return twice(21);
3440}
3441",
3442 ),
3443 ]);
3444 assert_eq!(
3445 calls(&graph),
3446 edges(&["index.js::main -> utils.js::helper"])
3447 );
3448 }
3449
3450 #[test]
3453 fn a_required_module_called_directly_keeps_the_call() {
3454 let graph = index(&[
3455 (
3456 "helper.js",
3457 "function helper(x) {\n return x * 2;\n}\n\nmodule.exports = helper;\n",
3458 ),
3459 ("lib/helper.js", DECOY_HELPER_JS),
3460 (
3461 "index.js",
3462 "\
3463const helper = require(\"./helper\");
3464
3465function main() {
3466 return helper(21);
3467}
3468",
3469 ),
3470 ]);
3471 assert_eq!(
3472 calls(&graph),
3473 edges(&["index.js::main -> helper.js::helper"])
3474 );
3475 assert!(confidence(&graph, "index.js::main", "helper.js::helper").unwrap() >= 0.95);
3476 }
3477
3478 #[test]
3481 fn names_destructured_from_a_required_factory_keep_the_call() {
3482 let graph = index(&[
3483 (
3484 "services/paged.js",
3485 "\
3486const db = require(\"./db\");
3487
3488function createPagedReads(prisma) {
3489 async function getOrderDetail(id) {
3490 return prisma.find(id);
3491 }
3492 return { getOrderDetail };
3493}
3494
3495module.exports = { createPagedReads };
3496",
3497 ),
3498 (
3499 "services/orders.js",
3500 "\
3501const prisma = require(\"./prisma\");
3502const { getOrderDetail } = require(\"./paged\").createPagedReads(prisma);
3503
3504async function getOrderById(id) {
3505 return getOrderDetail(id);
3506}
3507",
3508 ),
3509 ]);
3510 assert_eq!(
3511 calls(&graph),
3512 edges(&["services/orders.js::getOrderById -> services/paged.js::getOrderDetail"])
3513 );
3514 }
3515
3516 #[test]
3520 fn names_destructured_from_an_imported_hook_reach_the_hook_module() {
3521 let graph = index(&[
3522 (
3523 "hooks/useListState.js",
3524 "\
3525export function useListFilters(defaults) {
3526 function setFilters(patch) {
3527 return { ...defaults, ...patch };
3528 }
3529 return { setFilters };
3530}
3531",
3532 ),
3533 (
3534 "components/Search.jsx",
3535 "export function setFilters(event) {\n return event;\n}\n",
3536 ),
3537 (
3538 "pages/Orders.jsx",
3539 "\
3540import { useListFilters } from \"../hooks/useListState\";
3541
3542export function Orders() {
3543 const { setFilters } = useListFilters({});
3544 return setFilters({ q: \"\" });
3545}
3546",
3547 ),
3548 ]);
3549 assert_eq!(
3550 calls(&graph),
3551 edges(&[
3552 "pages/Orders.jsx::Orders -> hooks/useListState.js::setFilters",
3553 "pages/Orders.jsx::Orders -> hooks/useListState.js::useListFilters",
3554 ])
3555 );
3556 }
3557
3558 #[test]
3562 fn names_destructured_from_an_external_hook_keep_only_a_weak_edge() {
3563 let graph = index(&[
3564 (
3565 "components/Other.jsx",
3566 "export function handleSubmit(event) {\n return event;\n}\n",
3567 ),
3568 (
3569 "components/Form.jsx",
3570 "\
3571import { useForm } from \"react-hook-form\";
3572
3573export function Form({ save }) {
3574 const { handleSubmit } = useForm();
3575 return handleSubmit(save);
3576}
3577",
3578 ),
3579 ]);
3580 assert_eq!(
3581 calls(&graph),
3582 edges(&["components/Form.jsx::Form -> components/Other.jsx::handleSubmit"])
3583 );
3584 let weak = confidence(
3585 &graph,
3586 "components/Form.jsx::Form",
3587 "components/Other.jsx::handleSubmit",
3588 )
3589 .unwrap();
3590 assert!(weak < super::Edge::CONFIDENT_THRESHOLD, "{weak}");
3591 }
3592
3593 const AUTH_CONTEXT: &str = "\
3594import { createContext } from \"react\";
3595
3596export const AuthContext = createContext(null);
3597
3598export function AuthProvider({ children }) {
3599 function login(email) {
3600 return email;
3601 }
3602 return <AuthContext.Provider value={{ login }}>{children}</AuthContext.Provider>;
3603}
3604";
3605
3606 #[test]
3610 fn a_name_from_use_context_keeps_a_weak_edge_to_the_provider() {
3611 let graph = index(&[
3612 ("context/AuthContext.jsx", AUTH_CONTEXT),
3613 (
3614 "pages/Login.jsx",
3615 "\
3616import { useContext } from \"react\";
3617import { AuthContext } from \"../context/AuthContext\";
3618
3619export function Login() {
3620 const { login } = useContext(AuthContext);
3621 return login(\"a@b.c\");
3622}
3623",
3624 ),
3625 ]);
3626 assert_eq!(
3627 calls(&graph),
3628 edges(&["pages/Login.jsx::Login -> context/AuthContext.jsx::login"])
3629 );
3630 let weak = confidence(
3631 &graph,
3632 "pages/Login.jsx::Login",
3633 "context/AuthContext.jsx::login",
3634 )
3635 .unwrap();
3636 assert!(weak < super::Edge::CONFIDENT_THRESHOLD, "{weak}");
3637 }
3638
3639 #[test]
3643 fn a_hook_apart_from_its_provider_keeps_a_weak_edge() {
3644 let graph = index(&[
3645 ("context/AuthContext.jsx", AUTH_CONTEXT),
3646 (
3647 "hooks/useAuth.js",
3648 "\
3649import { useContext } from \"react\";
3650import { AuthContext } from \"../context/AuthContext\";
3651
3652export function useAuth() {
3653 return useContext(AuthContext);
3654}
3655",
3656 ),
3657 (
3658 "pages/Login.jsx",
3659 "\
3660import { useAuth } from \"../hooks/useAuth\";
3661
3662export function Login() {
3663 const { login } = useAuth();
3664 return login(\"a@b.c\");
3665}
3666",
3667 ),
3668 ]);
3669 assert_eq!(
3670 calls(&graph),
3671 edges(&[
3672 "pages/Login.jsx::Login -> context/AuthContext.jsx::login",
3673 "pages/Login.jsx::Login -> hooks/useAuth.js::useAuth",
3674 ])
3675 );
3676 let weak = confidence(
3677 &graph,
3678 "pages/Login.jsx::Login",
3679 "context/AuthContext.jsx::login",
3680 )
3681 .unwrap();
3682 assert!(weak < super::Edge::CONFIDENT_THRESHOLD, "{weak}");
3683 }
3684
3685 #[test]
3690 fn a_name_bound_from_two_modules_in_two_functions_is_not_pinned() {
3691 let handler = "const fs = require(\"fs\");\n\nasync function handler(event) {\n return fs.existsSync(event);\n}\n\nmodule.exports = { handler };\n";
3692 let graph = index(&[
3693 ("lambdas/a.js", handler),
3694 ("lambdas/b.js", handler),
3695 (
3696 "test/handlers.test.js",
3697 "\
3698const assert = require(\"assert\");
3699
3700async function runA() {
3701 const { handler } = require(\"../lambdas/a\");
3702 return handler({});
3703}
3704
3705async function runB() {
3706 const { handler } = require(\"../lambdas/b\");
3707 return handler({});
3708}
3709",
3710 ),
3711 ]);
3712 assert_eq!(
3713 calls(&graph),
3714 edges(&[
3715 "test/handlers.test.js::runA -> lambdas/a.js::handler",
3716 "test/handlers.test.js::runA -> lambdas/b.js::handler",
3717 "test/handlers.test.js::runB -> lambdas/a.js::handler",
3718 "test/handlers.test.js::runB -> lambdas/b.js::handler",
3719 ])
3720 );
3721 for run in ["runA", "runB"] {
3722 for module in ["a", "b"] {
3723 let weak = confidence(
3724 &graph,
3725 &format!("test/handlers.test.js::{run}"),
3726 &format!("lambdas/{module}.js::handler"),
3727 )
3728 .unwrap();
3729 assert!(
3730 weak < super::Edge::CONFIDENT_THRESHOLD,
3731 "{run} -> {module}: {weak}"
3732 );
3733 }
3734 }
3735 }
3736
3737 #[test]
3740 fn a_call_through_a_parameter_keeps_a_weak_edge() {
3741 let graph = index(&[
3742 (
3743 "components/Editor.jsx",
3744 "\
3745import { useState } from \"react\";
3746
3747export function Editor() {
3748 function onSave(value) {
3749 return value;
3750 }
3751 return <Button onSave={onSave} />;
3752}
3753",
3754 ),
3755 (
3756 "components/Button.jsx",
3757 "\
3758import { useRef } from \"react\";
3759
3760export function Button({ onSave }) {
3761 return onSave(1);
3762}
3763",
3764 ),
3765 ]);
3766 let weak = confidence(
3767 &graph,
3768 "components/Button.jsx::Button",
3769 "components/Editor.jsx::onSave",
3770 )
3771 .expect("the parameter call keeps an edge");
3772 assert!(weak < super::Edge::CONFIDENT_THRESHOLD, "{weak}");
3773 }
3774
3775 #[test]
3779 fn a_commonjs_module_without_requires_is_not_a_script() {
3780 let graph = index(&[
3781 (
3782 "scripts/verify.cjs",
3783 "function expect(path, status) {\n return path;\n}\n\nmodule.exports = { expect };\n",
3784 ),
3785 (
3786 "src/add.ts",
3787 "export function add(a: number, b: number): number {\n return a + b;\n}\n",
3788 ),
3789 (
3790 "src/__tests__/add.test.ts",
3791 "\
3792import { add } from \"../add\";
3793
3794export function addsTwoNumbers() {
3795 return expect(add(1, 2)).toBe(3);
3796}
3797",
3798 ),
3799 ]);
3800 assert_eq!(
3801 calls(&graph),
3802 edges(&["src/__tests__/add.test.ts::addsTwoNumbers -> src/add.ts::add"])
3803 );
3804 }
3805
3806 #[test]
3808 fn a_typescript_import_require_keeps_the_call() {
3809 let graph = index(&[
3810 (
3811 "helper.ts",
3812 "function helper(x: number): number {\n return x * 2;\n}\n\nexport = helper;\n",
3813 ),
3814 (
3815 "lib/helper.ts",
3816 "import fs from \"fs\";\n\nfunction helper(x: number): number {\n return x;\n}\n",
3817 ),
3818 (
3819 "index.ts",
3820 "\
3821import helper = require(\"./helper\");
3822
3823export function main(): number {
3824 return helper(21);
3825}
3826",
3827 ),
3828 ]);
3829 assert_eq!(
3830 calls(&graph),
3831 edges(&["index.ts::main -> helper.ts::helper"])
3832 );
3833 assert!(confidence(&graph, "index.ts::main", "helper.ts::helper").unwrap() >= 0.95);
3834 }
3835
3836 #[test]
3838 fn a_destructured_dynamic_import_keeps_the_call() {
3839 let graph = index(&[
3840 (
3841 "utils.mjs",
3842 "export function helper(x) {\n return x * 2;\n}\n",
3843 ),
3844 (
3845 "lib/other.mjs",
3846 "import fs from \"fs\";\n\nexport function helper(x) {\n return x;\n}\n",
3847 ),
3848 (
3849 "index.mjs",
3850 "\
3851export async function main() {
3852 const { helper } = await import(\"./utils.mjs\");
3853 return helper(21);
3854}
3855",
3856 ),
3857 ]);
3858 assert_eq!(
3859 calls(&graph),
3860 edges(&["index.mjs::main -> utils.mjs::helper"])
3861 );
3862 assert!(confidence(&graph, "index.mjs::main", "utils.mjs::helper").unwrap() >= 0.95);
3863 }
3864
3865 #[test]
3867 fn a_name_the_file_does_not_require_is_still_dropped() {
3868 let graph = index(&[
3869 ("utils.js", UTILS),
3870 (
3871 "other.js",
3872 "const path = require(\"path\");\n\nfunction other(x) {\n return path.basename(x);\n}\n\nmodule.exports = { other };\n",
3873 ),
3874 (
3875 "index.js",
3876 "\
3877const { helper } = require(\"./utils\");
3878
3879function main() {
3880 return other(helper(21));
3881}
3882",
3883 ),
3884 ]);
3885 assert_eq!(
3886 calls(&graph),
3887 edges(&["index.js::main -> utils.js::helper"])
3888 );
3889 }
3890
3891 #[test]
3894 fn a_script_with_no_imports_keeps_its_bare_calls() {
3895 let graph = index(&[
3896 (
3897 "legacy/format.js",
3898 "function formatPrice(x) {\n return \"$\" + x;\n}\n",
3899 ),
3900 (
3901 "legacy/cart.js",
3902 "function render(total) {\n return formatPrice(total);\n}\n",
3903 ),
3904 ]);
3905 assert_eq!(
3906 calls(&graph),
3907 edges(&["legacy/cart.js::render -> legacy/format.js::formatPrice"])
3908 );
3909 }
3910
3911 fn confidence(graph: &super::ArborGraph, from: &str, to: &str) -> Option<f32> {
3913 use petgraph::visit::{EdgeRef, IntoEdgeReferences};
3914 graph
3915 .graph
3916 .edge_references()
3917 .filter(|e| e.weight().kind == super::EdgeKind::Calls)
3918 .find(|e| {
3919 let source = &graph.graph[e.source()];
3920 let target = &graph.graph[e.target()];
3921 format!("{}::{}", source.file, source.name) == from
3922 && format!("{}::{}", target.file, target.name) == to
3923 })
3924 .map(|e| e.weight().confidence)
3925 }
3926
3927 #[test]
3932 fn an_exported_function_bound_through_a_helper_keeps_a_weak_edge() {
3933 let graph = index(&[
3934 (
3935 "lib/razorpay.ts",
3936 "export function verifyPaymentSignature(sig: string): boolean {\n return sig.length > 0;\n}\n",
3937 ),
3938 (
3939 "lib/__tests__/razorpay.test.ts",
3940 "\
3941import crypto from \"crypto\";
3942
3943async function loadModule() {
3944 return await import(\"../razorpay\");
3945}
3946
3947export async function acceptsAValidSignature() {
3948 const { verifyPaymentSignature } = await loadModule();
3949 return verifyPaymentSignature(crypto.randomUUID());
3950}
3951",
3952 ),
3953 ]);
3954 let test = "lib/__tests__/razorpay.test.ts::acceptsAValidSignature";
3955 assert_eq!(
3956 calls(&graph),
3957 edges(&[
3958 "lib/__tests__/razorpay.test.ts::acceptsAValidSignature -> lib/__tests__/razorpay.test.ts::loadModule",
3959 "lib/__tests__/razorpay.test.ts::acceptsAValidSignature -> lib/razorpay.ts::verifyPaymentSignature",
3960 ])
3961 );
3962 let weak = confidence(&graph, test, "lib/razorpay.ts::verifyPaymentSignature").unwrap();
3963 assert!(
3964 weak > 0.0 && weak < super::Edge::CONFIDENT_THRESHOLD,
3965 "unproven, so weak: {weak}"
3966 );
3967 }
3968
3969 #[test]
3971 fn an_exported_component_loaded_with_next_dynamic_keeps_a_weak_edge() {
3972 let graph = index(&[
3973 (
3974 "components/TrendsChart.tsx",
3975 "export function TrendsChart({ points }: { points: number[] }) {\n return <svg>{points.length}</svg>;\n}\n",
3976 ),
3977 (
3978 "app/trends/page.tsx",
3979 "\
3980import dynamic from \"next/dynamic\";
3981
3982const TrendsChart = dynamic(() =>
3983 import(\"../../components/TrendsChart\").then((m) => ({ default: m.TrendsChart })),
3984);
3985
3986export function TrendsPage() {
3987 return <TrendsChart points={[]} />;
3988}
3989",
3990 ),
3991 ]);
3992 assert_eq!(
3993 calls(&graph),
3994 edges(&["app/trends/page.tsx::TrendsPage -> components/TrendsChart.tsx::TrendsChart"])
3995 );
3996 let weak = confidence(
3997 &graph,
3998 "app/trends/page.tsx::TrendsPage",
3999 "components/TrendsChart.tsx::TrendsChart",
4000 )
4001 .unwrap();
4002 assert!(weak < super::Edge::CONFIDENT_THRESHOLD, "{weak}");
4003 }
4004
4005 #[test]
4009 fn a_module_private_function_is_not_reached_from_another_module() {
4010 let graph = index(&[
4011 (
4012 "scripts/verify-site.mjs",
4013 "\
4014import { strict as assert } from \"node:assert\";
4015
4016async function expect(path, status) {
4017 assert.ok(path, status);
4018}
4019",
4020 ),
4021 (
4022 "src/add.ts",
4023 "export function add(a: number, b: number): number {\n return a + b;\n}\n",
4024 ),
4025 (
4026 "src/__tests__/add.test.ts",
4027 "\
4028import { add } from \"../add\";
4029
4030export function addsTwoNumbers() {
4031 return expect(add(1, 2)).toBe(3);
4032}
4033",
4034 ),
4035 ]);
4036 assert_eq!(
4037 calls(&graph),
4038 edges(&["src/__tests__/add.test.ts::addsTwoNumbers -> src/add.ts::add"])
4039 );
4040 }
4041
4042 #[test]
4045 fn a_classic_script_function_keeps_a_weak_edge_from_a_module() {
4046 let graph = index(&[
4047 (
4048 "legacy/format.js",
4049 "function formatPrice(x) {\n return \"$\" + x;\n}\n",
4050 ),
4051 (
4052 "src/cart.ts",
4053 "\
4054import { total } from \"./total\";
4055
4056export function render(): string {
4057 return formatPrice(total());
4058}
4059",
4060 ),
4061 (
4062 "src/total.ts",
4063 "export function total(): number {\n return 1;\n}\n",
4064 ),
4065 ]);
4066 assert_eq!(
4067 calls(&graph),
4068 edges(&[
4069 "src/cart.ts::render -> legacy/format.js::formatPrice",
4070 "src/cart.ts::render -> src/total.ts::total",
4071 ])
4072 );
4073 let weak = confidence(
4074 &graph,
4075 "src/cart.ts::render",
4076 "legacy/format.js::formatPrice",
4077 )
4078 .unwrap();
4079 assert!(
4080 weak > 0.0 && weak < super::Edge::CONFIDENT_THRESHOLD,
4081 "{weak}"
4082 );
4083 }
4084
4085 #[test]
4089 fn a_file_with_only_a_namespace_import_is_a_module() {
4090 let graph = index(&[
4091 (
4092 "format.ts",
4093 "export function pad(x: string): string {\n return x;\n}\n",
4094 ),
4095 (
4096 "helpers.ts",
4097 "import * as fmt from \"./format\";\n\nfunction other(x: string): string {\n return fmt.pad(x);\n}\n",
4098 ),
4099 (
4100 "app.ts",
4101 "\
4102import { pad } from \"./format\";
4103
4104export function show(x: string): string {
4105 return other(pad(x));
4106}
4107",
4108 ),
4109 ]);
4110 assert!(
4111 confidence(&graph, "app.ts::show", "helpers.ts::other").is_none(),
4112 "{:?}",
4113 calls(&graph)
4114 );
4115 }
4116
4117 #[test]
4122 fn merged_namespace_members_in_script_files_keep_their_calls() {
4123 let graph = index(&[
4124 (
4125 "src/factory.ts",
4126 "namespace ts {\n export function createNode(kind: number) {\n return { kind };\n }\n}\n",
4127 ),
4128 (
4129 "src/parser.ts",
4130 "namespace ts {\n export function parseSourceFile() {\n return createNode(1);\n }\n}\n",
4131 ),
4132 ]);
4133 assert_eq!(
4134 calls(&graph),
4135 edges(&["src/parser.ts::parseSourceFile -> src/factory.ts::createNode"])
4136 );
4137 }
4138
4139 #[test]
4144 fn a_binding_from_a_barrel_is_not_pinned_to_a_sibling_file() {
4145 let graph = index(&[
4146 ("src/app/index.ts", "export { useApp } from \"./context\";\n"),
4147 (
4148 "src/app/context.tsx",
4149 "import { useContext } from \"react\";\n\nexport function useApp() {\n return useContext(AppContext);\n}\n",
4150 ),
4151 (
4152 "src/app/admin/session.ts",
4153 "export function logout() {\n return 1;\n}\n",
4154 ),
4155 (
4156 "src/lib/auth/session.ts",
4157 "export async function logout() {\n return 2;\n}\n",
4158 ),
4159 (
4160 "src/app/settings/Account.tsx",
4161 "\
4162import { useApp } from \"..\";
4163
4164export function Account() {
4165 const { logout } = useApp();
4166 return logout();
4167}
4168",
4169 ),
4170 ]);
4171 let account = "src/app/settings/Account.tsx::Account";
4172 for target in [
4173 "src/app/admin/session.ts::logout",
4174 "src/lib/auth/session.ts::logout",
4175 ] {
4176 let weak = confidence(&graph, account, target)
4177 .unwrap_or_else(|| panic!("{target}: {:?}", calls(&graph)));
4178 assert!(weak < super::Edge::CONFIDENT_THRESHOLD, "{target}: {weak}");
4179 }
4180 }
4181
4182 #[test]
4186 fn a_global_call_to_an_exported_function_keeps_a_weak_edge() {
4187 let graph = index(&[
4188 (
4189 "composables/useUser.ts",
4190 "export const useUser = () => useState(\"user\", () => null);\n",
4191 ),
4192 (
4193 "composables/useCart.ts",
4194 "export const useCart = () => {\n const user = useUser();\n return { user };\n};\n",
4195 ),
4196 ]);
4197 let weak = confidence(
4198 &graph,
4199 "composables/useCart.ts::useCart",
4200 "composables/useUser.ts::useUser",
4201 )
4202 .unwrap_or_else(|| panic!("{:?}", calls(&graph)));
4203 assert!(weak < super::Edge::CONFIDENT_THRESHOLD, "{weak}");
4204 }
4205
4206 #[test]
4211 fn imports_of_one_module_survive_the_cache() {
4212 let files = [
4213 (
4214 "hooks.ts",
4215 "export function useListFilters() {\n function setFilters(patch: object) {\n return patch;\n }\n return { setFilters };\n}\n",
4216 ),
4217 (
4218 "List.tsx",
4219 "import { useListFilters } from \"./hooks\";\n\nexport function List() {\n const { setFilters } = useListFilters();\n return setFilters({});\n}\n",
4220 ),
4221 (
4222 "api.ts",
4223 "export function fetchUser() {\n return 1;\n}\n\nexport interface User {\n id: number;\n}\n",
4224 ),
4225 (
4226 "load.ts",
4227 "import { fetchUser } from \"./api\";\nimport type { User } from \"./api\";\n\nexport function load(): User {\n return { id: fetchUser() };\n}\n",
4228 ),
4229 ("money.py", "def a():\n return 1\n\n\ndef b():\n return 2\n"),
4230 (
4231 "orders.py",
4232 "from money import a\n\n\ndef first():\n return a()\n\n\nfrom money import b\n\n\ndef second():\n return b()\n",
4233 ),
4234 ];
4235 let fresh = calls(&index(&files));
4236 for expected in [
4237 "List.tsx::List -> hooks.ts::useListFilters",
4238 "List.tsx::List -> hooks.ts::setFilters",
4239 "load.ts::load -> api.ts::fetchUser",
4240 "orders.py::first -> money.py::a",
4241 "orders.py::second -> money.py::b",
4242 ] {
4243 assert!(fresh.contains(expected), "{expected}: {fresh:?}");
4244 }
4245
4246 let dir = tempfile::tempdir().unwrap();
4247 let store = crate::store::GraphStore::open(dir.path()).unwrap();
4248 for (path, source) in &files {
4249 let ext = std::path::Path::new(path)
4250 .extension()
4251 .and_then(|e| e.to_str())
4252 .unwrap();
4253 let parser = arbor_core::languages::get_parser(ext).unwrap();
4254 let nodes = arbor_core::parse_source(source, path, parser.as_ref()).unwrap();
4255 store.update_file(path, &nodes, 1).unwrap();
4256 }
4257 let mut builder = super::GraphBuilder::new();
4258 for (path, _) in &files {
4259 builder.add_nodes(store.get_file_nodes(path).unwrap().unwrap());
4260 }
4261 assert_eq!(calls(&builder.build()), fresh);
4262 }
4263}