1use crate::edge::{Edge, EdgeKind};
8use crate::graph::{ArborGraph, NodeId};
9use crate::symbol_table::SymbolTable;
10use arbor_core::{CodeNode, NodeKind};
11use std::collections::HashMap;
12use std::path::{Path, PathBuf};
13use tracing::debug;
14
15const MAX_AMBIGUOUS_FANOUT: usize = 4;
18
19const MAX_UNKNOWN_RECEIVER_FANOUT: usize = 2;
21
22const UNKNOWN_RECEIVER_PENALTY: f32 = 0.55;
26
27pub struct GraphBuilder {
29 graph: ArborGraph,
30 symbol_table: SymbolTable,
31 name_to_id: HashMap<String, String>,
32
33 import_map: HashMap<String, HashMap<String, String>>,
43
44 namespace_imports: HashMap<String, HashMap<String, String>>,
54}
55
56impl Default for GraphBuilder {
57 fn default() -> Self {
58 Self::new()
59 }
60}
61
62impl GraphBuilder {
63 pub fn new() -> Self {
64 Self {
65 graph: ArborGraph::new(),
66 symbol_table: SymbolTable::new(),
67 name_to_id: HashMap::new(),
68 import_map: HashMap::new(),
69 namespace_imports: HashMap::new(),
70 }
71 }
72
73 pub fn add_nodes(&mut self, nodes: Vec<CodeNode>) {
81 for node in nodes {
82 if node.kind == NodeKind::Import {
85 let file = node.file.clone();
86 let module = node.name.clone();
87
88 for imported_name in &node.references {
89 if let Some(alias) = imported_name.strip_prefix("*as:") {
90 self.namespace_imports
92 .entry(file.clone())
93 .or_default()
94 .insert(alias.to_string(), module.clone());
95 } else {
96 self.import_map
98 .entry(file.clone())
99 .or_default()
100 .insert(imported_name.clone(), module.clone());
101 }
102 }
103 continue;
108 }
109
110 let id_str = node.id.clone();
111 let name = node.name.clone();
112 let qualified = node.qualified_name.clone();
113 let file = PathBuf::from(&node.file);
114
115 let node_idx = self.graph.add_node(node);
116
117 if !qualified.is_empty() {
118 self.symbol_table
119 .insert(qualified.clone(), node_idx, file.clone());
120 }
121
122 self.name_to_id.insert(name.clone(), id_str.clone());
123 self.name_to_id.insert(qualified, id_str);
124 }
125 }
126
127 pub fn resolve_edges(&mut self) {
143 let mut edges_to_add: Vec<(NodeId, NodeId, f32)> = Vec::new();
144
145 let node_indices: Vec<NodeId> = self.graph.node_indexes().collect();
146
147 for from_idx in node_indices {
148 let (references, from_file) = {
149 let node = self.graph.get(from_idx).unwrap();
150 (node.references.clone(), PathBuf::from(&node.file))
151 };
152
153 let from_file_str = from_file.to_string_lossy().to_string();
154
155 for reference in references {
156 let (lookup, receiver_unknown) = match reference.strip_prefix('.') {
160 Some(method) => (method, true),
161 None => (reference.as_str(), false),
162 };
163
164 if lookup.is_empty() {
165 continue;
166 }
167
168 let resolution = self.symbol_table.resolve_ref(lookup, &from_file);
169
170 if !resolution.is_resolved() {
171 debug!(
175 "Unresolved reference '{}' in {} (likely external/stdlib)",
176 reference,
177 from_file.display()
178 );
179 continue;
180 }
181
182 let mut base_confidence = resolution.confidence();
183 if receiver_unknown {
184 base_confidence *= UNKNOWN_RECEIVER_PENALTY;
185 }
186 let candidates = resolution.candidates();
187
188 let fanout_limit = if receiver_unknown {
192 MAX_UNKNOWN_RECEIVER_FANOUT
193 } else {
194 MAX_AMBIGUOUS_FANOUT
195 };
196
197 if candidates.len() > fanout_limit {
198 debug!(
204 "Reference '{}' in {} has {} candidate definitions — too ambiguous to link",
205 reference,
206 from_file.display(),
207 candidates.len()
208 );
209 continue;
210 }
211
212 for to_idx in candidates {
213 if from_idx == to_idx {
214 continue;
215 }
216
217 let confidence = if receiver_unknown {
221 base_confidence
222 } else {
223 self.apply_import_validation(
224 &reference,
225 &from_file,
226 &from_file_str,
227 to_idx,
228 base_confidence,
229 )
230 };
231
232 if confidence <= 0.0 {
233 continue;
234 }
235
236 edges_to_add.push((from_idx, to_idx, confidence));
237 }
238 }
239 }
240
241 for (from_id, to_id, confidence) in edges_to_add {
242 self.graph.add_edge(
243 from_id,
244 to_id,
245 Edge::new(EdgeKind::Calls).with_confidence(confidence),
246 );
247 }
248 }
249
250 fn apply_import_validation(
261 &self,
262 reference: &str,
263 from_file: &Path,
264 from_file_str: &str,
265 to_idx: NodeId,
266 base_confidence: f32,
267 ) -> f32 {
268 let Some(file_imports) = self.import_map.get(from_file_str) else {
269 return base_confidence;
270 };
271 if file_imports.is_empty() || reference.contains('.') {
272 return base_confidence;
273 }
274 if file_imports.contains_key(reference) {
275 return base_confidence.max(0.95);
277 }
278
279 let Some(to_node) = self.graph.get(to_idx) else {
280 return 0.0;
281 };
282 let to_file = PathBuf::from(&to_node.file);
283
284 if to_file == from_file {
285 return base_confidence;
287 }
288
289 if to_file.parent() == from_file.parent() {
290 return base_confidence * 0.6;
293 }
294
295 debug!(
297 "Downgrading unimported cross-module reference '{}' in {} → {}",
298 reference,
299 from_file.display(),
300 to_file.display()
301 );
302 base_confidence * 0.3
303 }
304
305 pub fn build(mut self) -> ArborGraph {
307 self.resolve_edges();
308 self.graph
309 }
310
311 pub fn build_without_resolve(self) -> ArborGraph {
313 self.graph
314 }
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320 use arbor_core::NodeKind;
321
322 #[test]
323 fn test_builder_adds_nodes() {
324 let mut builder = GraphBuilder::new();
325 let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "test.rs");
326 let node2 = CodeNode::new("bar", "bar", NodeKind::Function, "test.rs");
327 builder.add_nodes(vec![node1, node2]);
328 let graph = builder.build();
329 assert_eq!(graph.node_count(), 2);
330 }
331
332 #[test]
333 fn test_builder_resolves_edges() {
334 let mut builder = GraphBuilder::new();
335 let caller = CodeNode::new("caller", "caller", NodeKind::Function, "test.rs")
336 .with_references(vec!["callee".to_string()]);
337 let callee = CodeNode::new("callee", "callee", NodeKind::Function, "test.rs");
338 builder.add_nodes(vec![caller, callee]);
339 let graph = builder.build();
340 assert_eq!(graph.node_count(), 2);
341 assert_eq!(graph.edge_count(), 1);
342 }
343
344 #[test]
345 fn test_cross_file_resolution() {
346 let mut builder = GraphBuilder::new();
347 let caller = CodeNode::new("main", "main", NodeKind::Function, "main.rs")
348 .with_references(vec!["pkg.Utils.helper".to_string()]);
349 let mut callee = CodeNode::new("helper", "helper", NodeKind::Method, "utils.rs");
350 callee.qualified_name = "pkg.Utils.helper".to_string();
351 builder.add_nodes(vec![caller]);
352 builder.add_nodes(vec![callee]);
353 let graph = builder.build();
354 assert_eq!(graph.node_count(), 2);
355 assert_eq!(
356 graph.edge_count(),
357 1,
358 "Should resolve cross-file edge via FQN"
359 );
360 }
361
362 #[test]
363 fn test_unresolved_references_no_false_edges() {
364 let mut builder = GraphBuilder::new();
365 let node = CodeNode::new("caller", "caller", NodeKind::Function, "a.rs")
366 .with_references(vec!["nonexistent_function".to_string()]);
367 builder.add_nodes(vec![node]);
368 let graph = builder.build();
369 assert_eq!(graph.node_count(), 1);
370 assert_eq!(
371 graph.edge_count(),
372 0,
373 "Unresolved references must not create edges"
374 );
375 }
376
377 #[test]
378 fn test_import_nodes_not_added_to_graph() {
379 let mut builder = GraphBuilder::new();
380 let import_node = CodeNode::new("./utils", "./utils", NodeKind::Import, "main.ts")
381 .with_references(vec!["validate".to_string()]);
382 let func = CodeNode::new("main", "main", NodeKind::Function, "main.ts");
383 builder.add_nodes(vec![import_node, func]);
384 let graph = builder.build();
385 assert_eq!(graph.node_count(), 1);
387 }
388
389 #[test]
390 fn test_import_map_built_correctly() {
391 let mut builder = GraphBuilder::new();
392 let import_node =
393 CodeNode::new("@babel/types", "@babel/types", NodeKind::Import, "file.ts")
394 .with_references(vec!["validate".to_string(), "clone".to_string()]);
395 builder.add_nodes(vec![import_node]);
396 assert_eq!(
397 builder
398 .import_map
399 .get("file.ts")
400 .and_then(|m| m.get("validate")),
401 Some(&"@babel/types".to_string())
402 );
403 assert_eq!(
404 builder
405 .import_map
406 .get("file.ts")
407 .and_then(|m| m.get("clone")),
408 Some(&"@babel/types".to_string())
409 );
410 }
411
412 #[test]
413 fn test_namespace_import_map() {
414 let mut builder = GraphBuilder::new();
415 let import_node =
416 CodeNode::new("@babel/types", "@babel/types", NodeKind::Import, "file.ts")
417 .with_references(vec!["*as:types".to_string()]);
418 builder.add_nodes(vec![import_node]);
419 assert_eq!(
420 builder
421 .namespace_imports
422 .get("file.ts")
423 .and_then(|m| m.get("types")),
424 Some(&"@babel/types".to_string())
425 );
426 }
427
428 #[test]
429 fn test_build_empty_graph() {
430 let builder = GraphBuilder::new();
431 let graph = builder.build();
432 assert_eq!(graph.node_count(), 0);
433 assert_eq!(graph.edge_count(), 0);
434 }
435
436 fn only_edge_confidence(graph: &ArborGraph) -> f32 {
438 let edges = graph.export_edges();
439 assert_eq!(edges.len(), 1, "expected exactly one edge");
440 graph
441 .graph
442 .edge_weights()
443 .next()
444 .expect("edge weight")
445 .confidence
446 }
447
448 #[test]
449 fn exact_fqn_match_is_full_confidence() {
450 let mut b = GraphBuilder::new();
451 let caller = CodeNode::new("main", "main", NodeKind::Function, "main.rs")
452 .with_references(vec!["pkg.Utils.helper".to_string()]);
453 let mut callee = CodeNode::new("helper", "helper", NodeKind::Method, "utils.rs");
454 callee.qualified_name = "pkg.Utils.helper".to_string();
455 b.add_nodes(vec![caller, callee]);
456 let graph = b.build();
457
458 assert_eq!(only_edge_confidence(&graph), 1.0);
459 }
460
461 #[test]
462 fn unknown_receiver_call_creates_a_weak_edge() {
463 let mut b = GraphBuilder::new();
465 let caller = CodeNode::new("handler", "handler", NodeKind::Function, "api.ts")
466 .with_references(vec![".findOne".to_string()]);
467 let callee = CodeNode::new("findOne", "UserRepo.findOne", NodeKind::Method, "repo.ts");
468 b.add_nodes(vec![caller, callee]);
469 let graph = b.build();
470
471 let confidence = only_edge_confidence(&graph);
472 assert!(
473 confidence > 0.0 && confidence < Edge::CONFIDENT_THRESHOLD,
474 "edge should exist but not be treated as proven, got {confidence}"
475 );
476 }
477
478 #[test]
479 fn unknown_receiver_with_many_candidates_is_not_linked() {
480 let mut b = GraphBuilder::new();
482 let caller = CodeNode::new("handler", "handler", NodeKind::Function, "api.ts")
483 .with_references(vec![".get".to_string()]);
484 b.add_nodes(vec![caller]);
485 for (i, owner) in ["Cache", "Store", "Config"].iter().enumerate() {
486 b.add_nodes(vec![CodeNode::new(
487 "get",
488 format!("{owner}.get"),
489 NodeKind::Method,
490 format!("m{i}.ts"),
491 )]);
492 }
493 let graph = b.build();
494
495 assert_eq!(
496 graph.edge_count(),
497 0,
498 "over the fan-out cap, so no edge should be guessed"
499 );
500 }
501
502 #[test]
503 fn colliding_symbols_both_remain_reachable() {
504 let mut b = GraphBuilder::new();
506 let caller = CodeNode::new("main", "main", NodeKind::Function, "src/main.py")
507 .with_references(vec!["process".to_string()]);
508 b.add_nodes(vec![caller]);
509 b.add_nodes(vec![CodeNode::new(
510 "process",
511 "process",
512 NodeKind::Function,
513 "src/utils.py",
514 )]);
515 b.add_nodes(vec![CodeNode::new(
516 "process",
517 "process",
518 NodeKind::Function,
519 "src/helpers.py",
520 )]);
521 let graph = b.build();
522
523 assert_eq!(graph.edge_count(), 2);
525 for weight in graph.graph.edge_weights() {
526 assert!(
527 !weight.is_confident(),
528 "ambiguous resolution must not claim certainty"
529 );
530 }
531 }
532
533 #[test]
534 fn unimported_cross_module_reference_is_downgraded_not_dropped() {
535 let mut b = GraphBuilder::new();
536 let import = CodeNode::new("./other", "./other", NodeKind::Import, "src/a/main.ts")
537 .with_references(vec!["somethingElse".to_string()]);
538 let caller = CodeNode::new("main", "main", NodeKind::Function, "src/a/main.ts")
539 .with_references(vec!["validate".to_string()]);
540 let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/z/far.ts");
541 b.add_nodes(vec![import, caller, callee]);
542 let graph = b.build();
543
544 let confidence = only_edge_confidence(&graph);
545 assert!(
546 confidence > 0.0 && confidence < 0.5,
547 "not imported and in another module — weak, got {confidence}"
548 );
549 }
550
551 #[test]
552 fn explicitly_imported_reference_is_strong() {
553 let mut b = GraphBuilder::new();
554 let import = CodeNode::new("./far", "./far", NodeKind::Import, "src/a/main.ts")
555 .with_references(vec!["validate".to_string()]);
556 let caller = CodeNode::new("main", "main", NodeKind::Function, "src/a/main.ts")
557 .with_references(vec!["validate".to_string()]);
558 let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/z/far.ts");
559 b.add_nodes(vec![import, caller, callee]);
560 let graph = b.build();
561
562 assert!(
563 only_edge_confidence(&graph) >= Edge::CONFIDENT_THRESHOLD,
564 "an explicit import is strong corroboration"
565 );
566 }
567
568 #[test]
569 fn same_dir_unimported_reference_is_no_longer_a_free_pass() {
570 let mut b = GraphBuilder::new();
573 let import = CodeNode::new("./x", "./x", NodeKind::Import, "src/main.ts")
574 .with_references(vec!["other".to_string()]);
575 let caller = CodeNode::new("main", "main", NodeKind::Function, "src/main.ts")
576 .with_references(vec!["validate".to_string()]);
577 let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/sibling.ts");
578 b.add_nodes(vec![import, caller, callee]);
579 let graph = b.build();
580
581 let confidence = only_edge_confidence(&graph);
582 assert!(
583 confidence < Edge::CONFIDENT_THRESHOLD,
584 "same-dir but unimported should carry doubt, got {confidence}"
585 );
586 }
587
588 #[test]
589 fn build_is_deterministic_across_insertion_orders() {
590 let make = |reverse: bool| {
591 let mut b = GraphBuilder::new();
592 let mut defs = vec![
593 CodeNode::new("run", "A.run", NodeKind::Method, "src/a/a.ts"),
594 CodeNode::new("run", "B.run", NodeKind::Method, "src/b/b.ts"),
595 ];
596 if reverse {
597 defs.reverse();
598 }
599 b.add_nodes(vec![CodeNode::new(
600 "main",
601 "main",
602 NodeKind::Function,
603 "src/c/main.ts",
604 )
605 .with_references(vec!["run".to_string()])]);
606 b.add_nodes(defs);
607 let graph = b.build();
608 let mut sig: Vec<String> = graph
609 .export_edges()
610 .into_iter()
611 .map(|e| format!("{}->{}", e.source, e.target))
612 .collect();
613 sig.sort();
614 sig
615 };
616
617 assert_eq!(make(false), make(true));
618 }
619
620 #[test]
621 fn test_qualified_static_call_resolves_to_correct_class() {
622 let mut b = GraphBuilder::new();
626 let caller = CodeNode::new("compute", "Calc.compute", NodeKind::Method, "src/Calc.java")
627 .with_references(vec!["MathUtils.add".to_string()]);
628 let sibling = CodeNode::new("add", "Sibling.add", NodeKind::Method, "src/Sibling.java");
630 let target = CodeNode::new(
631 "add",
632 "MathUtils.add",
633 NodeKind::Method,
634 "src/util/MathUtils.java",
635 );
636 b.add_nodes(vec![caller, sibling, target]);
637 let graph = b.build();
638
639 let compute_idx = graph
640 .node_indexes()
641 .find(|&i| graph.get(i).unwrap().name == "compute")
642 .unwrap();
643 let callees = graph.get_callees(compute_idx);
644 assert_eq!(callees.len(), 1, "exactly one resolved callee");
645 assert_eq!(
646 callees[0].qualified_name, "MathUtils.add",
647 "static call must resolve to the qualified class, not a same-named sibling"
648 );
649 }
650}