Skip to main content

arbor_graph/
builder.rs

1//! Graph builder for constructing the code graph from parsed nodes.
2//!
3//! Two-pass construction:
4//!   1. Add all nodes — populates symbol table and import map
5//!   2. Resolve edges — uses import context to create accurate edges
6
7use crate::edge::{Edge, EdgeKind};
8use crate::graph::{ArborGraph, NodeId};
9use crate::symbol_table::SymbolTable;
10use arbor_core::{clean_type_name, type_relation_ref, CodeNode, NodeKind, TypeRelationKind};
11use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
12use std::path::{Path, PathBuf};
13use tracing::debug;
14
15/// Beyond this many candidate definitions, a bare name carries no information
16/// and linking to all of them would swamp the graph with noise.
17const MAX_AMBIGUOUS_FANOUT: usize = 4;
18
19/// Tighter fan-out cap for calls whose receiver type is unknown.
20const MAX_UNKNOWN_RECEIVER_FANOUT: usize = 2;
21
22/// Confidence multiplier for a call on a receiver we could not type
23/// (`userService.findOne()`). The method name is real evidence, but which
24/// `findOne` it reaches is a guess.
25const UNKNOWN_RECEIVER_PENALTY: f32 = 0.55;
26
27/// Builds an ArborGraph from parsed code nodes.
28pub struct GraphBuilder {
29    graph: ArborGraph,
30    symbol_table: SymbolTable,
31    name_to_id: HashMap<String, String>,
32
33    /// Per-file map of locally-bound name → source module specifier.
34    /// Built from Import nodes that carry their imported names in `references`.
35    ///
36    /// Example:
37    ///   `import { validate } from '@babel/types'`
38    ///   → import_map["file.ts"]["validate"] = "@babel/types"
39    ///
40    /// Used during edge resolution to verify that a direct call like `validate()`
41    /// is indeed an intentional import, not a same-name coincidence.
42    import_map: HashMap<String, HashMap<String, String>>,
43
44    /// Namespace import aliases: file → alias → source module.
45    ///
46    /// Example:
47    ///   `import * as types from '@babel/types'`
48    ///   → namespace_imports["file.ts"]["types"] = "@babel/types"
49    ///
50    /// Used to resolve calls like `types.validate()` — though since we now DROP
51    /// those calls at parse time, this is reserved for future use when we add
52    /// a richer call-site representation.
53    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    /// Adds nodes from a parsed file to the graph.
74    ///
75    /// This pass does two things:
76    ///   - Adds real code entities (functions, classes, etc.) to the graph and symbol table
77    ///   - Processes Import nodes to build the per-file import map
78    ///
79    /// Call this for all files before calling `build()`.
80    pub fn add_nodes(&mut self, nodes: Vec<CodeNode>) {
81        for node in nodes {
82            // Import nodes carry the import map — process them but don't add to graph
83            // (they are not code entities we want in centrality analysis)
84            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                        // `import * as alias from 'module'`
91                        self.namespace_imports
92                            .entry(file.clone())
93                            .or_default()
94                            .insert(alias.to_string(), module.clone());
95                    } else {
96                        // `import { name } from 'module'` or `import DefaultName from 'module'`
97                        self.import_map
98                            .entry(file.clone())
99                            .or_default()
100                            .insert(imported_name.clone(), module.clone());
101                    }
102                }
103                // Import nodes are intentionally NOT added to the graph.
104                // They caused misleading centrality scores (e.g. "psycopg.types.range [Import]
105                // 330 callers") because every call to a symbol named after the import path
106                // was attributed to the import node itself.
107                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    /// Resolves references into actual graph edges.
128    ///
129    /// Each reference `R` from file `F` resolves through
130    /// [`SymbolTable::resolve_ref`], which reports *how* it matched. That
131    /// quality becomes the edge's confidence, so a downstream consumer can
132    /// distinguish a proven call from an educated guess instead of treating
133    /// every edge as fact.
134    ///
135    /// Ambiguous references (several equally-plausible definitions) produce a
136    /// low-confidence edge to each candidate, capped at
137    /// [`MAX_AMBIGUOUS_FANOUT`]. Dropping them outright would silently hide
138    /// real call paths; emitting them unlabelled would overstate certainty.
139    ///
140    /// References with no definition in the repository are dropped — they are
141    /// external or stdlib symbols.
142    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                // Inheritance is not a call. `extends:` / `implements:` and
157                // `self.method` / `super.method` are resolved in
158                // [`resolve_inheritance`](Self::resolve_inheritance), where an
159                // override can hide a base method. Falling through to a bare
160                // name here would attach the edge to the wrong definition.
161                if type_relation_ref(&reference).is_some() || receiver_method(&reference).is_some()
162                {
163                    continue;
164                }
165
166                // A leading `.` marks a call on a receiver whose type we could
167                // not determine (`userService.findOne()`). Resolve it by method
168                // name, but never let it claim the confidence of a real match.
169                let (lookup, receiver_unknown) = match reference.strip_prefix('.') {
170                    Some(method) => (method, true),
171                    None => (reference.as_str(), false),
172                };
173
174                if lookup.is_empty() {
175                    continue;
176                }
177
178                // Hand the referencing file's imports to the resolver so a bare
179                // name that matches several modules can be pinned to the one
180                // the author actually imported. Without this the resolver
181                // falls through to SameDir and attaches the edge to whichever
182                // definition happens to sit in the caller's own directory.
183                let file_imports = self.import_map.get(&from_file_str);
184                // `jobs::enqueue` / `Provider::new` name where the definition
185                // lives; matching only the last segment would drop the call or
186                // bind it to a same-named function in the wrong module.
187                let resolution = if !receiver_unknown && lookup.contains("::") {
188                    self.symbol_table.resolve_path(lookup, &from_file)
189                } else {
190                    self.symbol_table
191                        .resolve_ref_with_imports(lookup, &from_file, file_imports)
192                };
193
194                if !resolution.is_resolved() {
195                    // The overwhelming majority of references are stdlib or
196                    // third-party and have no definition here. Expected, not
197                    // notable.
198                    debug!(
199                        "Unresolved reference '{}' in {} (likely external/stdlib)",
200                        reference,
201                        from_file.display()
202                    );
203                    continue;
204                }
205
206                let mut base_confidence = resolution.confidence();
207                if receiver_unknown {
208                    base_confidence *= UNKNOWN_RECEIVER_PENALTY;
209                }
210                let mut candidates = resolution.candidates();
211                // In Rust `x.f()` is always a method call (modules use `::`),
212                // so it can't reach a free function that shares the name:
213                // sqlx's `.bind(...)` is not a test helper called `bind`.
214                if receiver_unknown && from_file_str.ends_with(".rs") {
215                    candidates.retain(|id| {
216                        self.graph
217                            .get(*id)
218                            .is_some_and(|n| n.kind == NodeKind::Method)
219                    });
220                    if candidates.is_empty() {
221                        continue;
222                    }
223                }
224
225                // A receiver-unknown call to a name shared by many symbols
226                // (`get`, `run`, `execute`) is pure noise; hold it to a tighter
227                // fan-out than a properly-qualified reference.
228                let fanout_limit = if receiver_unknown {
229                    MAX_UNKNOWN_RECEIVER_FANOUT
230                } else {
231                    MAX_AMBIGUOUS_FANOUT
232                };
233
234                if candidates.len() > fanout_limit {
235                    // A name like `new`, `get`, or `run` with dozens of
236                    // definitions carries no information. Linking to all of
237                    // them would swamp the graph.
238                    // Routine on any real codebase — `.get`, `.encode`, `.match`
239                    // are shared by many types. Diagnostic, not a user problem.
240                    debug!(
241                        "Reference '{}' in {} has {} candidate definitions — too ambiguous to link",
242                        reference,
243                        from_file.display(),
244                        candidates.len()
245                    );
246                    continue;
247                }
248
249                for to_idx in candidates {
250                    if from_idx == to_idx {
251                        continue;
252                    }
253
254                    // Method names are never in the import map — importing
255                    // `UserService` does not import `findOne` — so import
256                    // validation only applies to bare and qualified references.
257                    let confidence = if receiver_unknown {
258                        base_confidence
259                    } else {
260                        self.apply_import_validation(
261                            &reference,
262                            &from_file,
263                            &from_file_str,
264                            to_idx,
265                            base_confidence,
266                        )
267                    };
268
269                    if confidence <= 0.0 {
270                        continue;
271                    }
272
273                    edges_to_add.push((from_idx, to_idx, confidence));
274                }
275            }
276        }
277
278        for (from_id, to_id, confidence) in edges_to_add {
279            self.graph.add_edge(
280                from_id,
281                to_id,
282                Edge::new(EdgeKind::Calls).with_confidence(confidence),
283            );
284        }
285    }
286
287    /// Downgrades (rather than drops) an edge whose name is not imported.
288    ///
289    /// If the referencing file declares imports and this bare name is not among
290    /// them, a cross-module match is probably a same-name coincidence. The old
291    /// behaviour dropped such edges unless the target was in the same directory
292    /// — which meant that in a flat `src/` layout, the common case for JS and
293    /// Python projects, the check never fired at all. Confidence-weighting
294    /// applies the same suspicion uniformly instead of exempting whole layouts.
295    ///
296    /// Returns `0.0` to drop the edge entirely.
297    fn apply_import_validation(
298        &self,
299        reference: &str,
300        from_file: &Path,
301        from_file_str: &str,
302        to_idx: NodeId,
303        base_confidence: f32,
304    ) -> f32 {
305        let Some(file_imports) = self.import_map.get(from_file_str) else {
306            return base_confidence;
307        };
308        if file_imports.is_empty() || reference.contains('.') || reference.contains("::") {
309            return base_confidence;
310        }
311        if file_imports.contains_key(reference) {
312            // Explicitly imported — the strongest possible corroboration.
313            return base_confidence.max(0.95);
314        }
315
316        let Some(to_node) = self.graph.get(to_idx) else {
317            return 0.0;
318        };
319        let to_file = PathBuf::from(&to_node.file);
320
321        if to_file == from_file {
322            // Defined in this very file; imports are irrelevant.
323            return base_confidence;
324        }
325
326        if to_file.parent() == from_file.parent() {
327            // Same directory but never imported. Plausible in languages with
328            // implicit module scope, suspicious everywhere else.
329            return base_confidence * 0.6;
330        }
331
332        // Different module and not imported: almost certainly a name collision.
333        debug!(
334            "Downgrading unimported cross-module reference '{}' in {} → {}",
335            reference,
336            from_file.display(),
337            to_file.display()
338        );
339        base_confidence * 0.3
340    }
341
342    /// Emits `extends` / `implements` edges and inherited-method reachability.
343    ///
344    /// A subclass reaches each base it names. A method the subclass does not
345    /// define is reachable from the subclass; an override blocks that path.
346    /// `self`/`this` calls bind to the nearest definition, including the
347    /// enclosing type. `super`/`base` calls start at the parents, so an
348    /// override that calls `super` still reaches the base method.
349    ///
350    /// These type edges are not `Calls`. PageRank stays on the call graph.
351    fn resolve_inheritance(&mut self) {
352        let indices: Vec<NodeId> = self.graph.node_indexes().collect();
353        let types = inherited_types(&self.graph, &indices);
354        let (methods_of, method_owner) = index_methods(&self.graph, &indices, &types);
355        let mut pending = Vec::new();
356        let parents = self.link_type_parents(&types, &mut pending);
357        link_inherited_methods(&types, &parents, &methods_of, &mut pending);
358        link_receiver_calls(
359            &self.graph,
360            &indices,
361            &method_owner,
362            &parents,
363            &methods_of,
364            &mut pending,
365        );
366        self.commit_inheritance_edges(pending);
367    }
368
369    /// Resolves each written base to a type node and records the parent list.
370    fn link_type_parents(
371        &self,
372        types: &[InheritedType],
373        pending: &mut Vec<PendingEdge>,
374    ) -> HashMap<NodeId, Vec<NodeId>> {
375        let mut parents: HashMap<NodeId, Vec<NodeId>> = HashMap::new();
376        for ty in types {
377            let file = PathBuf::from(&ty.file);
378            let mut resolved = Vec::new();
379            let relations = ty
380                .extends
381                .iter()
382                .map(|name| (TypeRelationKind::Extends, name))
383                .chain(
384                    ty.implements
385                        .iter()
386                        .map(|name| (TypeRelationKind::Implements, name)),
387                );
388            for (recorded, name) in relations {
389                let Some(target) = self.resolve_type_name(name, &file) else {
390                    continue;
391                };
392                if target == ty.id || resolved.contains(&target) {
393                    continue;
394                }
395                resolved.push(target);
396                pending.push(type_edge(self, ty, recorded, target));
397            }
398            if !resolved.is_empty() {
399                parents.insert(ty.id, resolved);
400            }
401        }
402        parents
403    }
404
405    fn commit_inheritance_edges(&mut self, pending: Vec<PendingEdge>) {
406        let mut seen: HashSet<(NodeId, NodeId, u8)> = HashSet::new();
407        for (from, to, kind, confidence) in pending {
408            if from == to || !seen.insert((from, to, edge_tag(kind))) {
409                continue;
410            }
411            self.graph
412                .add_edge(from, to, Edge::new(kind).with_confidence(confidence));
413        }
414    }
415
416    /// Resolves a base or interface name to one type node.
417    ///
418    /// A path like `pkg.Base` is tried whole, then as its last segment, so a
419    /// class recorded under the simple name `Base` still matches. Several
420    /// equally plausible types are dropped rather than guessed.
421    fn resolve_type_name(&self, name: &str, file: &Path) -> Option<NodeId> {
422        let file_str = file.to_string_lossy().to_string();
423        let imports = self.import_map.get(&file_str);
424        let mut candidates_names = vec![name.to_string()];
425        if let Some(last) = name.rsplit(['.', ':']).find(|segment| !segment.is_empty()) {
426            if last != name {
427                candidates_names.push(last.to_string());
428            }
429        }
430
431        for candidate in &candidates_names {
432            let resolution = self
433                .symbol_table
434                .resolve_ref_with_imports(candidate, file, imports);
435            let type_ids: Vec<NodeId> = resolution
436                .candidates()
437                .into_iter()
438                .filter(|id| {
439                    self.graph
440                        .get(*id)
441                        .is_some_and(|node| is_inheritable_type(node.kind))
442                })
443                .collect();
444            if type_ids.len() == 1 {
445                return Some(type_ids[0]);
446            }
447            let same_file: Vec<NodeId> = type_ids
448                .into_iter()
449                .filter(|id| {
450                    self.graph
451                        .get(*id)
452                        .is_some_and(|node| Path::new(&node.file) == file)
453                })
454                .collect();
455            if same_file.len() == 1 {
456                return Some(same_file[0]);
457            }
458        }
459        None
460    }
461
462    /// Finishes building and returns the graph.
463    pub fn build(mut self) -> ArborGraph {
464        self.resolve_edges();
465        self.resolve_inheritance();
466        self.graph
467    }
468
469    /// Builds without resolving edges (for incremental updates).
470    pub fn build_without_resolve(self) -> ArborGraph {
471        self.graph
472    }
473}
474
475struct InheritedType {
476    id: NodeId,
477    file: String,
478    /// Length of the raw qualified name. Tie-breaking uses this, not the cleaned form.
479    qualified_len: usize,
480    clean_name: String,
481    clean_qualified: String,
482    extends: Vec<String>,
483    implements: Vec<String>,
484}
485
486type PendingEdge = (NodeId, NodeId, EdgeKind, f32);
487
488fn inherited_types(graph: &ArborGraph, indices: &[NodeId]) -> Vec<InheritedType> {
489    let mut types = Vec::new();
490    for id in indices {
491        let Some(node) = graph.get(*id) else {
492            continue;
493        };
494        if !is_inheritable_type(node.kind) {
495            continue;
496        }
497        let mut extends = Vec::new();
498        let mut implements = Vec::new();
499        for reference in &node.references {
500            if let Some((kind, name)) = type_relation_ref(reference) {
501                match kind {
502                    TypeRelationKind::Extends => extends.push(name.to_string()),
503                    TypeRelationKind::Implements => implements.push(name.to_string()),
504                }
505            }
506        }
507        types.push(InheritedType {
508            id: *id,
509            file: node.file.clone(),
510            qualified_len: node.qualified_name.len(),
511            clean_name: clean_type_name(&node.name),
512            clean_qualified: clean_type_name(&node.qualified_name),
513            extends,
514            implements,
515        });
516    }
517    types
518}
519
520fn index_methods(
521    graph: &ArborGraph,
522    indices: &[NodeId],
523    types: &[InheritedType],
524) -> (
525    HashMap<NodeId, BTreeMap<String, NodeId>>,
526    HashMap<NodeId, NodeId>,
527) {
528    let mut types_by_file: HashMap<&str, Vec<&InheritedType>> = HashMap::new();
529    let mut rust_types_by_name: HashMap<&str, Vec<&InheritedType>> = HashMap::new();
530    for ty in types {
531        types_by_file.entry(ty.file.as_str()).or_default().push(ty);
532        if ty.file.ends_with(".rs") {
533            rust_types_by_name
534                .entry(ty.clean_name.as_str())
535                .or_default()
536                .push(ty);
537        }
538    }
539
540    let mut methods_of: HashMap<NodeId, BTreeMap<String, NodeId>> = HashMap::new();
541    let mut method_owner: HashMap<NodeId, NodeId> = HashMap::new();
542    for id in indices {
543        let Some(node) = graph.get(*id) else {
544            continue;
545        };
546        if node.kind != NodeKind::Method {
547            continue;
548        }
549        let Some((parent, method_name)) = split_owner(&node.qualified_name) else {
550            continue;
551        };
552        let parent = clean_type_name(parent);
553        if parent.is_empty() || method_name.is_empty() {
554            continue;
555        }
556        let file_types = types_by_file
557            .get(node.file.as_str())
558            .map(Vec::as_slice)
559            .unwrap_or_default();
560        let owners: Vec<NodeId> = file_types
561            .iter()
562            .filter(|ty| ty.clean_name == parent || ty.clean_qualified == parent)
563            .map(|ty| ty.id)
564            .collect();
565        let owner = unique_owner(&owners, |id| {
566            file_types
567                .iter()
568                .find(|ty| ty.id == id)
569                .map(|ty| ty.qualified_len)
570                .unwrap_or(0)
571        })
572        .or_else(|| {
573            // A Rust `impl Provider` block may sit in any file of the crate,
574            // far from `struct Provider`. Without this its methods have no
575            // owner, and every `self.method()` call inside them is lost.
576            // Look where Rust puts it: the impl file's own module directory
577            // first, then its parents. Tests often declare their own mock
578            // `struct Provider`, so a repo-wide unique name is too strict.
579            if !node.file.ends_with(".rs") || !owners.is_empty() {
580                return None;
581            }
582            let candidates = rust_types_by_name.get(parent.as_str())?;
583            let mut dir = Path::new(&node.file).parent();
584            while let Some(current) = dir {
585                let here: Vec<NodeId> = candidates
586                    .iter()
587                    .filter(|ty| Path::new(&ty.file).parent() == Some(current))
588                    .map(|ty| ty.id)
589                    .collect();
590                match here.as_slice() {
591                    [] => dir = current.parent(),
592                    [only] => return Some(*only),
593                    _ => return None,
594                }
595            }
596            None
597        });
598        let Some(owner) = owner else {
599            continue;
600        };
601        methods_of
602            .entry(owner)
603            .or_default()
604            .entry(method_name.to_string())
605            .or_insert(*id);
606        method_owner.insert(*id, owner);
607    }
608    (methods_of, method_owner)
609}
610
611fn type_edge(
612    builder: &GraphBuilder,
613    ty: &InheritedType,
614    recorded: TypeRelationKind,
615    target: NodeId,
616) -> PendingEdge {
617    let target_kind = builder.graph.get(target).map(|node| node.kind);
618    let edge_kind = match (recorded, target_kind) {
619        (TypeRelationKind::Implements, _) | (_, Some(NodeKind::Interface)) => EdgeKind::Implements,
620        _ => EdgeKind::Extends,
621    };
622    let same_file = builder
623        .graph
624        .get(target)
625        .is_some_and(|node| node.file == ty.file);
626    let confidence = if same_file { 0.95 } else { 0.85 };
627    (ty.id, target, edge_kind, confidence)
628}
629
630fn link_inherited_methods(
631    types: &[InheritedType],
632    parents: &HashMap<NodeId, Vec<NodeId>>,
633    methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
634    pending: &mut Vec<PendingEdge>,
635) {
636    for ty in types {
637        let own = methods_of.get(&ty.id);
638        for (name, method_id) in inherited_methods(ty.id, parents, methods_of) {
639            if own.and_then(|methods| methods.get(&name)).is_some() {
640                continue;
641            }
642            pending.push((ty.id, method_id, EdgeKind::References, 0.9));
643        }
644    }
645}
646
647fn link_receiver_calls(
648    graph: &ArborGraph,
649    indices: &[NodeId],
650    method_owner: &HashMap<NodeId, NodeId>,
651    parents: &HashMap<NodeId, Vec<NodeId>>,
652    methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
653    pending: &mut Vec<PendingEdge>,
654) {
655    for id in indices {
656        let Some(node) = graph.get(*id) else {
657            continue;
658        };
659        if node.kind != NodeKind::Method {
660            continue;
661        }
662        let Some(&owner) = method_owner.get(id) else {
663            continue;
664        };
665        for reference in &node.references {
666            let Some((is_super, method_name)) = receiver_method(reference) else {
667                continue;
668            };
669            let Some(target) = nearest_method(owner, method_name, is_super, parents, methods_of)
670            else {
671                continue;
672            };
673            if target != *id {
674                pending.push((*id, target, EdgeKind::Calls, 0.95));
675            }
676        }
677    }
678}
679
680fn is_inheritable_type(kind: NodeKind) -> bool {
681    matches!(
682        kind,
683        NodeKind::Class | NodeKind::Struct | NodeKind::Interface | NodeKind::Enum
684    )
685}
686
687/// `Class.method` or `Class::method` → `("Class", "method")`.
688///
689/// When both separators appear, the later one wins, so `mod.Class::method`
690/// is `("mod.Class", "method")`.
691fn split_owner(qualified: &str) -> Option<(&str, &str)> {
692    let dot = qualified.rfind('.');
693    let colon = qualified.rfind("::");
694    match (dot, colon) {
695        (Some(dot_at), Some(colon_at)) if colon_at > dot_at => {
696            Some((&qualified[..colon_at], &qualified[colon_at + 2..]))
697        }
698        (Some(dot_at), _) => Some((&qualified[..dot_at], &qualified[dot_at + 1..])),
699        (None, Some(colon_at)) => Some((&qualified[..colon_at], &qualified[colon_at + 2..])),
700        (None, None) => None,
701    }
702}
703
704fn unique_owner(owners: &[NodeId], qualified_len: impl Fn(NodeId) -> usize) -> Option<NodeId> {
705    match owners {
706        [] => None,
707        [only] => Some(*only),
708        _ => {
709            let mut best_len = 0usize;
710            let mut best: Option<NodeId> = None;
711            let mut tied = false;
712            for id in owners {
713                let len = qualified_len(*id);
714                if len > best_len {
715                    best_len = len;
716                    best = Some(*id);
717                    tied = false;
718                } else if len == best_len {
719                    tied = true;
720                }
721            }
722            if tied {
723                None
724            } else {
725                best
726            }
727        }
728    }
729}
730
731/// Breadth-first, nearest base wins. This approximates C3 linearization and
732/// agrees with it for single inheritance and simple diamonds.
733fn inherited_methods(
734    start: NodeId,
735    parents: &HashMap<NodeId, Vec<NodeId>>,
736    methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
737) -> BTreeMap<String, NodeId> {
738    let mut found = BTreeMap::new();
739    let mut seen = HashSet::new();
740    let mut queue = VecDeque::new();
741    if let Some(bases) = parents.get(&start) {
742        queue.extend(bases.iter().copied());
743    }
744    while let Some(current) = queue.pop_front() {
745        if !seen.insert(current) {
746            continue;
747        }
748        if let Some(methods) = methods_of.get(&current) {
749            for (name, id) in methods {
750                found.entry(name.clone()).or_insert(*id);
751            }
752        }
753        if let Some(bases) = parents.get(&current) {
754            for base in bases {
755                if !seen.contains(base) {
756                    queue.push_back(*base);
757                }
758            }
759        }
760    }
761    found
762}
763
764/// Same nearest-base walk as [`inherited_methods`].
765fn nearest_method(
766    start: NodeId,
767    name: &str,
768    skip_self: bool,
769    parents: &HashMap<NodeId, Vec<NodeId>>,
770    methods_of: &HashMap<NodeId, BTreeMap<String, NodeId>>,
771) -> Option<NodeId> {
772    let own = if skip_self {
773        None
774    } else {
775        methods_of.get(&start).and_then(|methods| methods.get(name))
776    };
777    if let Some(id) = own {
778        return Some(*id);
779    }
780    let mut seen = HashSet::new();
781    let mut queue = VecDeque::new();
782    if let Some(bases) = parents.get(&start) {
783        queue.extend(bases.iter().copied());
784    }
785    while let Some(current) = queue.pop_front() {
786        if !seen.insert(current) {
787            continue;
788        }
789        if let Some(id) = methods_of
790            .get(&current)
791            .and_then(|methods| methods.get(name))
792        {
793            return Some(*id);
794        }
795        if let Some(bases) = parents.get(&current) {
796            for base in bases {
797                if !seen.contains(base) {
798                    queue.push_back(*base);
799                }
800            }
801        }
802    }
803    None
804}
805
806/// `self.compute` / `this.compute` search from the enclosing type.
807/// `super().compute` / `super.compute` / `base.compute` start at the parents.
808fn receiver_method(reference: &str) -> Option<(bool, &str)> {
809    const SUPER_PREFIXES: &[&str] = &["super().", "super.", "base."];
810    const SAME_PREFIXES: &[&str] = &["self.", "this->", "this.", "Self::"];
811    let reference = reference.trim();
812    for prefix in SUPER_PREFIXES {
813        if let Some(method) = reference.strip_prefix(prefix) {
814            if is_plain_method(method) {
815                return Some((true, method));
816            }
817        }
818    }
819    for prefix in SAME_PREFIXES {
820        if let Some(method) = reference.strip_prefix(prefix) {
821            if is_plain_method(method) {
822                return Some((false, method));
823            }
824        }
825    }
826    None
827}
828
829fn is_plain_method(name: &str) -> bool {
830    !name.is_empty()
831        && name
832            .chars()
833            .next()
834            .is_some_and(|c| c.is_alphabetic() || c == '_')
835        && name.chars().all(|c| c.is_alphanumeric() || c == '_')
836}
837
838fn edge_tag(kind: EdgeKind) -> u8 {
839    match kind {
840        EdgeKind::Calls => 1,
841        EdgeKind::Extends => 2,
842        EdgeKind::Implements => 3,
843        EdgeKind::References => 4,
844        EdgeKind::Imports => 5,
845        EdgeKind::UsesType => 6,
846        EdgeKind::Contains => 7,
847        EdgeKind::FlowsTo => 8,
848        EdgeKind::DataDependency => 9,
849    }
850}
851
852#[cfg(test)]
853mod tests {
854    use super::*;
855    use arbor_core::NodeKind;
856    use petgraph::visit::{EdgeRef, IntoEdgeReferences};
857
858    #[test]
859    fn test_builder_adds_nodes() {
860        let mut builder = GraphBuilder::new();
861        let node1 = CodeNode::new("foo", "foo", NodeKind::Function, "test.rs");
862        let node2 = CodeNode::new("bar", "bar", NodeKind::Function, "test.rs");
863        builder.add_nodes(vec![node1, node2]);
864        let graph = builder.build();
865        assert_eq!(graph.node_count(), 2);
866    }
867
868    #[test]
869    fn test_builder_resolves_edges() {
870        let mut builder = GraphBuilder::new();
871        let caller = CodeNode::new("caller", "caller", NodeKind::Function, "test.rs")
872            .with_references(vec!["callee".to_string()]);
873        let callee = CodeNode::new("callee", "callee", NodeKind::Function, "test.rs");
874        builder.add_nodes(vec![caller, callee]);
875        let graph = builder.build();
876        assert_eq!(graph.node_count(), 2);
877        assert_eq!(graph.edge_count(), 1);
878    }
879
880    #[test]
881    fn test_cross_file_resolution() {
882        let mut builder = GraphBuilder::new();
883        let caller = CodeNode::new("main", "main", NodeKind::Function, "main.rs")
884            .with_references(vec!["pkg.Utils.helper".to_string()]);
885        let mut callee = CodeNode::new("helper", "helper", NodeKind::Method, "utils.rs");
886        callee.qualified_name = "pkg.Utils.helper".to_string();
887        builder.add_nodes(vec![caller]);
888        builder.add_nodes(vec![callee]);
889        let graph = builder.build();
890        assert_eq!(graph.node_count(), 2);
891        assert_eq!(
892            graph.edge_count(),
893            1,
894            "Should resolve cross-file edge via FQN"
895        );
896    }
897
898    #[test]
899    fn test_unresolved_references_no_false_edges() {
900        let mut builder = GraphBuilder::new();
901        let node = CodeNode::new("caller", "caller", NodeKind::Function, "a.rs")
902            .with_references(vec!["nonexistent_function".to_string()]);
903        builder.add_nodes(vec![node]);
904        let graph = builder.build();
905        assert_eq!(graph.node_count(), 1);
906        assert_eq!(
907            graph.edge_count(),
908            0,
909            "Unresolved references must not create edges"
910        );
911    }
912
913    #[test]
914    fn test_import_nodes_not_added_to_graph() {
915        let mut builder = GraphBuilder::new();
916        let import_node = CodeNode::new("./utils", "./utils", NodeKind::Import, "main.ts")
917            .with_references(vec!["validate".to_string()]);
918        let func = CodeNode::new("main", "main", NodeKind::Function, "main.ts");
919        builder.add_nodes(vec![import_node, func]);
920        let graph = builder.build();
921        // Only the function should be in the graph, not the import node
922        assert_eq!(graph.node_count(), 1);
923    }
924
925    #[test]
926    fn test_import_map_built_correctly() {
927        let mut builder = GraphBuilder::new();
928        let import_node =
929            CodeNode::new("@babel/types", "@babel/types", NodeKind::Import, "file.ts")
930                .with_references(vec!["validate".to_string(), "clone".to_string()]);
931        builder.add_nodes(vec![import_node]);
932        assert_eq!(
933            builder
934                .import_map
935                .get("file.ts")
936                .and_then(|m| m.get("validate")),
937            Some(&"@babel/types".to_string())
938        );
939        assert_eq!(
940            builder
941                .import_map
942                .get("file.ts")
943                .and_then(|m| m.get("clone")),
944            Some(&"@babel/types".to_string())
945        );
946    }
947
948    #[test]
949    fn test_namespace_import_map() {
950        let mut builder = GraphBuilder::new();
951        let import_node =
952            CodeNode::new("@babel/types", "@babel/types", NodeKind::Import, "file.ts")
953                .with_references(vec!["*as:types".to_string()]);
954        builder.add_nodes(vec![import_node]);
955        assert_eq!(
956            builder
957                .namespace_imports
958                .get("file.ts")
959                .and_then(|m| m.get("types")),
960            Some(&"@babel/types".to_string())
961        );
962    }
963
964    #[test]
965    fn test_build_empty_graph() {
966        let builder = GraphBuilder::new();
967        let graph = builder.build();
968        assert_eq!(graph.node_count(), 0);
969        assert_eq!(graph.edge_count(), 0);
970    }
971
972    /// Confidence of the single edge in the graph.
973    fn only_edge_confidence(graph: &ArborGraph) -> f32 {
974        let edges = graph.export_edges();
975        assert_eq!(edges.len(), 1, "expected exactly one edge");
976        graph
977            .graph
978            .edge_weights()
979            .next()
980            .expect("edge weight")
981            .confidence
982    }
983
984    #[test]
985    fn exact_fqn_match_is_full_confidence() {
986        let mut b = GraphBuilder::new();
987        let caller = CodeNode::new("main", "main", NodeKind::Function, "main.rs")
988            .with_references(vec!["pkg.Utils.helper".to_string()]);
989        let mut callee = CodeNode::new("helper", "helper", NodeKind::Method, "utils.rs");
990        callee.qualified_name = "pkg.Utils.helper".to_string();
991        b.add_nodes(vec![caller, callee]);
992        let graph = b.build();
993
994        assert_eq!(only_edge_confidence(&graph), 1.0);
995    }
996
997    #[test]
998    fn unknown_receiver_call_creates_a_weak_edge() {
999        // `.findOne` — the shape the TS parser used to discard entirely.
1000        let mut b = GraphBuilder::new();
1001        let caller = CodeNode::new("handler", "handler", NodeKind::Function, "api.ts")
1002            .with_references(vec![".findOne".to_string()]);
1003        let callee = CodeNode::new("findOne", "UserRepo.findOne", NodeKind::Method, "repo.ts");
1004        b.add_nodes(vec![caller, callee]);
1005        let graph = b.build();
1006
1007        let confidence = only_edge_confidence(&graph);
1008        assert!(
1009            confidence > 0.0 && confidence < Edge::CONFIDENT_THRESHOLD,
1010            "edge should exist but not be treated as proven, got {confidence}"
1011        );
1012    }
1013
1014    #[test]
1015    fn unknown_receiver_with_many_candidates_is_not_linked() {
1016        // `.get` defined on three different types is noise, not evidence.
1017        let mut b = GraphBuilder::new();
1018        let caller = CodeNode::new("handler", "handler", NodeKind::Function, "api.ts")
1019            .with_references(vec![".get".to_string()]);
1020        b.add_nodes(vec![caller]);
1021        for (i, owner) in ["Cache", "Store", "Config"].iter().enumerate() {
1022            b.add_nodes(vec![CodeNode::new(
1023                "get",
1024                format!("{owner}.get"),
1025                NodeKind::Method,
1026                format!("m{i}.ts"),
1027            )]);
1028        }
1029        let graph = b.build();
1030
1031        assert_eq!(
1032            graph.edge_count(),
1033            0,
1034            "over the fan-out cap, so no edge should be guessed"
1035        );
1036    }
1037
1038    #[test]
1039    fn colliding_symbols_both_remain_reachable() {
1040        // The old table overwrote one of these, orphaning it with zero callers.
1041        let mut b = GraphBuilder::new();
1042        let caller = CodeNode::new("main", "main", NodeKind::Function, "src/main.py")
1043            .with_references(vec!["process".to_string()]);
1044        b.add_nodes(vec![caller]);
1045        b.add_nodes(vec![CodeNode::new(
1046            "process",
1047            "process",
1048            NodeKind::Function,
1049            "src/utils.py",
1050        )]);
1051        b.add_nodes(vec![CodeNode::new(
1052            "process",
1053            "process",
1054            NodeKind::Function,
1055            "src/helpers.py",
1056        )]);
1057        let graph = b.build();
1058
1059        // Both candidates are linked, each flagged as uncertain.
1060        assert_eq!(graph.edge_count(), 2);
1061        for weight in graph.graph.edge_weights() {
1062            assert!(
1063                !weight.is_confident(),
1064                "ambiguous resolution must not claim certainty"
1065            );
1066        }
1067    }
1068
1069    #[test]
1070    fn unimported_cross_module_reference_is_downgraded_not_dropped() {
1071        let mut b = GraphBuilder::new();
1072        let import = CodeNode::new("./other", "./other", NodeKind::Import, "src/a/main.ts")
1073            .with_references(vec!["somethingElse".to_string()]);
1074        let caller = CodeNode::new("main", "main", NodeKind::Function, "src/a/main.ts")
1075            .with_references(vec!["validate".to_string()]);
1076        let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/z/far.ts");
1077        b.add_nodes(vec![import, caller, callee]);
1078        let graph = b.build();
1079
1080        let confidence = only_edge_confidence(&graph);
1081        assert!(
1082            confidence > 0.0 && confidence < 0.5,
1083            "not imported and in another module — weak, got {confidence}"
1084        );
1085    }
1086
1087    #[test]
1088    fn explicitly_imported_reference_is_strong() {
1089        let mut b = GraphBuilder::new();
1090        let import = CodeNode::new("./far", "./far", NodeKind::Import, "src/a/main.ts")
1091            .with_references(vec!["validate".to_string()]);
1092        let caller = CodeNode::new("main", "main", NodeKind::Function, "src/a/main.ts")
1093            .with_references(vec!["validate".to_string()]);
1094        let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/z/far.ts");
1095        b.add_nodes(vec![import, caller, callee]);
1096        let graph = b.build();
1097
1098        assert!(
1099            only_edge_confidence(&graph) >= Edge::CONFIDENT_THRESHOLD,
1100            "an explicit import is strong corroboration"
1101        );
1102    }
1103
1104    #[test]
1105    fn same_dir_unimported_reference_is_no_longer_a_free_pass() {
1106        // Flat `src/` layouts made the old filter a no-op, so same-name
1107        // collisions sailed through at full strength.
1108        let mut b = GraphBuilder::new();
1109        let import = CodeNode::new("./x", "./x", NodeKind::Import, "src/main.ts")
1110            .with_references(vec!["other".to_string()]);
1111        let caller = CodeNode::new("main", "main", NodeKind::Function, "src/main.ts")
1112            .with_references(vec!["validate".to_string()]);
1113        let callee = CodeNode::new("validate", "validate", NodeKind::Function, "src/sibling.ts");
1114        b.add_nodes(vec![import, caller, callee]);
1115        let graph = b.build();
1116
1117        let confidence = only_edge_confidence(&graph);
1118        assert!(
1119            confidence < Edge::CONFIDENT_THRESHOLD,
1120            "same-dir but unimported should carry doubt, got {confidence}"
1121        );
1122    }
1123
1124    #[test]
1125    fn build_is_deterministic_across_insertion_orders() {
1126        let make = |reverse: bool| {
1127            let mut b = GraphBuilder::new();
1128            let mut defs = vec![
1129                CodeNode::new("run", "A.run", NodeKind::Method, "src/a/a.ts"),
1130                CodeNode::new("run", "B.run", NodeKind::Method, "src/b/b.ts"),
1131            ];
1132            if reverse {
1133                defs.reverse();
1134            }
1135            b.add_nodes(vec![CodeNode::new(
1136                "main",
1137                "main",
1138                NodeKind::Function,
1139                "src/c/main.ts",
1140            )
1141            .with_references(vec!["run".to_string()])]);
1142            b.add_nodes(defs);
1143            let graph = b.build();
1144            let mut sig: Vec<String> = graph
1145                .export_edges()
1146                .into_iter()
1147                .map(|e| format!("{}->{}", e.source, e.target))
1148                .collect();
1149            sig.sort();
1150            sig
1151        };
1152
1153        assert_eq!(make(false), make(true));
1154    }
1155
1156    #[test]
1157    fn test_qualified_static_call_resolves_to_correct_class() {
1158        // Regression: `MathUtils.add()` in Calc must link to MathUtils.add, NOT to a
1159        // same-named `add` on a sibling class. Relies on the parser keeping the class
1160        // qualifier so the builder gets an exact FQN match.
1161        let mut b = GraphBuilder::new();
1162        let caller = CodeNode::new("compute", "Calc.compute", NodeKind::Method, "src/Calc.java")
1163            .with_references(vec!["MathUtils.add".to_string()]);
1164        // Same-dir sibling with a colliding bare name — the old bug linked here.
1165        let sibling = CodeNode::new("add", "Sibling.add", NodeKind::Method, "src/Sibling.java");
1166        let target = CodeNode::new(
1167            "add",
1168            "MathUtils.add",
1169            NodeKind::Method,
1170            "src/util/MathUtils.java",
1171        );
1172        b.add_nodes(vec![caller, sibling, target]);
1173        let graph = b.build();
1174
1175        let compute_idx = graph
1176            .node_indexes()
1177            .find(|&i| graph.get(i).unwrap().name == "compute")
1178            .unwrap();
1179        let callees = graph.get_callees(compute_idx);
1180        assert_eq!(callees.len(), 1, "exactly one resolved callee");
1181        assert_eq!(
1182            callees[0].qualified_name, "MathUtils.add",
1183            "static call must resolve to the qualified class, not a same-named sibling"
1184        );
1185    }
1186
1187    fn kinds_between(graph: &ArborGraph, from_q: &str, to_q: &str) -> Vec<EdgeKind> {
1188        let mut kinds = Vec::new();
1189        for edge in graph.graph.edge_references() {
1190            let source = graph.get(edge.source()).unwrap();
1191            let target = graph.get(edge.target()).unwrap();
1192            if source.qualified_name == from_q && target.qualified_name == to_q {
1193                kinds.push(edge.weight().kind);
1194            }
1195        }
1196        kinds
1197    }
1198
1199    fn inheritance_fixture() -> ArborGraph {
1200        let file = "hard/inheritance.py";
1201        let mut b = GraphBuilder::new();
1202        b.add_nodes(vec![
1203            CodeNode::new("Base", "Base", NodeKind::Class, file),
1204            CodeNode::new("compute", "Base.compute", NodeKind::Method, file),
1205            CodeNode::new("shared", "Base.shared", NodeKind::Method, file),
1206            CodeNode::new("Middle", "Middle", NodeKind::Class, file).with_extends(["Base"]),
1207            CodeNode::new("compute", "Middle.compute", NodeKind::Method, file)
1208                .with_references(vec!["super().compute".to_string()]),
1209            CodeNode::new("Derived", "Derived", NodeKind::Class, file).with_extends(["Middle"]),
1210            CodeNode::new("shared", "Derived.shared", NodeKind::Method, file),
1211            CodeNode::new("Leaf", "Leaf", NodeKind::Class, file).with_extends(["Derived"]),
1212            CodeNode::new("run", "Leaf.run", NodeKind::Method, file).with_references(vec![
1213                "self.compute".to_string(),
1214                "self.shared".to_string(),
1215                "len".to_string(),
1216            ]),
1217            // Same simple name, no superclass. Must not become an extender.
1218            CodeNode::new("UserService", "UserService", NodeKind::Class, file),
1219        ]);
1220        b.build()
1221    }
1222
1223    #[test]
1224    fn subclass_extends_its_base() {
1225        let graph = inheritance_fixture();
1226        assert_eq!(
1227            kinds_between(&graph, "Middle", "Base"),
1228            vec![EdgeKind::Extends]
1229        );
1230        assert_eq!(
1231            kinds_between(&graph, "Derived", "Middle"),
1232            vec![EdgeKind::Extends]
1233        );
1234        assert_eq!(
1235            kinds_between(&graph, "Leaf", "Derived"),
1236            vec![EdgeKind::Extends]
1237        );
1238        assert!(
1239            kinds_between(&graph, "UserService", "Base").is_empty(),
1240            "a class with no base is not an extender"
1241        );
1242
1243        let base = graph
1244            .node_indexes()
1245            .find(|&id| graph.get(id).unwrap().qualified_name == "Base")
1246            .unwrap();
1247        let reachers: Vec<_> = graph
1248            .direct_dependents(base)
1249            .into_iter()
1250            .map(|node| node.qualified_name.as_str())
1251            .collect();
1252        assert!(
1253            reachers.contains(&"Middle"),
1254            "Base is reached by Middle, got {reachers:?}"
1255        );
1256        assert!(graph.get_callers(base).is_empty(), "extends is not a call");
1257    }
1258
1259    #[test]
1260    fn inherited_method_reaches_the_defining_class_until_overridden() {
1261        let graph = inheritance_fixture();
1262
1263        // Leaf.run's self.compute binds to Middle.compute, not Base.compute.
1264        assert_eq!(
1265            kinds_between(&graph, "Leaf.run", "Middle.compute"),
1266            vec![EdgeKind::Calls]
1267        );
1268        assert!(kinds_between(&graph, "Leaf.run", "Base.compute").is_empty());
1269
1270        // super() in the override still reaches the base method.
1271        assert_eq!(
1272            kinds_between(&graph, "Middle.compute", "Base.compute"),
1273            vec![EdgeKind::Calls]
1274        );
1275
1276        // Leaf inherits compute from Middle (the nearest definition).
1277        assert_eq!(
1278            kinds_between(&graph, "Leaf", "Middle.compute"),
1279            vec![EdgeKind::References]
1280        );
1281        assert!(kinds_between(&graph, "Leaf", "Base.compute").is_empty());
1282
1283        // Derived overrides shared, so neither Derived nor Leaf reaches Base.shared.
1284        assert!(kinds_between(&graph, "Derived", "Base.shared").is_empty());
1285        assert!(kinds_between(&graph, "Leaf", "Base.shared").is_empty());
1286        assert_eq!(
1287            kinds_between(&graph, "Leaf.run", "Derived.shared"),
1288            vec![EdgeKind::Calls]
1289        );
1290        assert!(kinds_between(&graph, "Leaf.run", "Base.shared").is_empty());
1291
1292        // Middle does not override shared, so it reaches Base.shared.
1293        assert_eq!(
1294            kinds_between(&graph, "Middle", "Base.shared"),
1295            vec![EdgeKind::References]
1296        );
1297
1298        let base_compute = graph
1299            .node_indexes()
1300            .find(|&id| graph.get(id).unwrap().qualified_name == "Base.compute")
1301            .unwrap();
1302        let impact = graph.analyze_impact(base_compute, 5);
1303        let upstream: Vec<_> = impact
1304            .upstream
1305            .iter()
1306            .map(|node| node.node_info.qualified_name.as_str())
1307            .collect();
1308        assert!(
1309            upstream.contains(&"Leaf"),
1310            "changing Base.compute must reach Leaf, got {upstream:?}"
1311        );
1312
1313        let base_shared = graph
1314            .node_indexes()
1315            .find(|&id| graph.get(id).unwrap().qualified_name == "Base.shared")
1316            .unwrap();
1317        let shared_impact = graph.analyze_impact(base_shared, 5);
1318        let direct: Vec<_> = shared_impact
1319            .direct_only()
1320            .into_iter()
1321            .map(|node| node.node_info.qualified_name.clone())
1322            .collect();
1323        assert!(
1324            direct.iter().any(|name| name == "Middle"),
1325            "Middle inherits shared, got {direct:?}"
1326        );
1327        assert!(
1328            direct
1329                .iter()
1330                .all(|name| name != "Derived" && name != "Leaf" && name != "Leaf.run"),
1331            "Derived's override must not make Base.shared a direct dependency, got {direct:?}"
1332        );
1333    }
1334
1335    #[test]
1336    fn diamond_inherits_the_nearest_override() {
1337        let file = "diamond.py";
1338        let mut b = GraphBuilder::new();
1339        b.add_nodes(vec![
1340            CodeNode::new("A", "A", NodeKind::Class, file),
1341            CodeNode::new("f", "A.f", NodeKind::Method, file),
1342            CodeNode::new("B", "B", NodeKind::Class, file).with_extends(["A"]),
1343            CodeNode::new("C", "C", NodeKind::Class, file).with_extends(["A"]),
1344            CodeNode::new("f", "C.f", NodeKind::Method, file),
1345            CodeNode::new("D", "D", NodeKind::Class, file).with_extends(["B", "C"]),
1346        ]);
1347        let graph = b.build();
1348        assert_eq!(
1349            kinds_between(&graph, "D", "C.f"),
1350            vec![EdgeKind::References],
1351            "D(B, C) sees C.f before A.f"
1352        );
1353        assert!(kinds_between(&graph, "D", "A.f").is_empty());
1354    }
1355
1356    #[test]
1357    fn super_stops_at_the_intermediate_override() {
1358        let file = "super_chain.py";
1359        let mut b = GraphBuilder::new();
1360        b.add_nodes(vec![
1361            CodeNode::new("A", "A", NodeKind::Class, file),
1362            CodeNode::new("foo", "A.foo", NodeKind::Method, file),
1363            CodeNode::new("B", "B", NodeKind::Class, file).with_extends(["A"]),
1364            CodeNode::new("foo", "B.foo", NodeKind::Method, file),
1365            CodeNode::new("C", "C", NodeKind::Class, file).with_extends(["B"]),
1366            CodeNode::new("foo", "C.foo", NodeKind::Method, file)
1367                .with_references(vec!["super().foo".to_string()]),
1368        ]);
1369        let graph = b.build();
1370        assert_eq!(
1371            kinds_between(&graph, "C.foo", "B.foo"),
1372            vec![EdgeKind::Calls],
1373            "super() in C must reach B's override"
1374        );
1375        assert!(
1376            kinds_between(&graph, "C.foo", "A.foo").is_empty(),
1377            "super() must not skip B and land on A"
1378        );
1379    }
1380}
1381
1382#[cfg(test)]
1383mod rust_path_tests {
1384    use super::*;
1385    use arbor_core::NodeKind;
1386
1387    fn function(name: &str, file: &str, calls: &[&str]) -> CodeNode {
1388        CodeNode::new(name, name, NodeKind::Function, file)
1389            .with_references(calls.iter().map(|c| c.to_string()).collect())
1390    }
1391
1392    fn method(owner: &str, name: &str, file: &str, calls: &[&str]) -> CodeNode {
1393        CodeNode::new(name, format!("{owner}.{name}"), NodeKind::Method, file)
1394            .with_references(calls.iter().map(|c| c.to_string()).collect())
1395    }
1396
1397    fn callers_of(graph: &ArborGraph, name: &str, file: &str) -> Vec<String> {
1398        let id = graph
1399            .node_indexes()
1400            .find(|id| {
1401                graph
1402                    .get(*id)
1403                    .is_some_and(|n| n.name == name && n.file == file)
1404            })
1405            .unwrap_or_else(|| panic!("no {name} in {file}"));
1406        let mut names: Vec<String> = graph
1407            .get_callers(id)
1408            .into_iter()
1409            .map(|n| n.name.clone())
1410            .collect();
1411        names.sort();
1412        names
1413    }
1414
1415    #[test]
1416    fn module_paths_resolve_to_the_named_module_and_never_across_languages() {
1417        let mut b = GraphBuilder::new();
1418        b.add_nodes(vec![
1419            function("enqueue", "src/app/jobs.rs", &[]),
1420            function("enqueue", "src/billing/jobs_old.rs", &[]),
1421            function("enqueue", "web/src/components/Toast.tsx", &[]),
1422            function("dispatch", "src/app/dispatch.rs", &["jobs::enqueue"]),
1423            function("start", "web/src/lib/bridge.ts", &["enqueue"]),
1424        ]);
1425        let graph = b.build();
1426        assert_eq!(
1427            callers_of(&graph, "enqueue", "src/app/jobs.rs"),
1428            vec!["dispatch"]
1429        );
1430        assert!(callers_of(&graph, "enqueue", "src/billing/jobs_old.rs").is_empty());
1431        // The TypeScript call binds to the TypeScript definition only.
1432        assert_eq!(
1433            callers_of(&graph, "enqueue", "web/src/components/Toast.tsx"),
1434            vec!["start"]
1435        );
1436    }
1437
1438    #[test]
1439    fn mod_rs_crate_prefixes_and_re_exports_resolve() {
1440        let mut b = GraphBuilder::new();
1441        b.add_nodes(vec![
1442            function("create_project", "src/app/mod.rs", &[]),
1443            function("record", "src/app/audit/writer.rs", &[]),
1444            function(
1445                "handler",
1446                "src/routes/mod.rs",
1447                &["app::create_project", "app::audit::record"],
1448            ),
1449            function(
1450                "persistence_test",
1451                "tests/integration.rs",
1452                &["my_app::app::create_project", "app::record"],
1453            ),
1454        ]);
1455        let graph = b.build();
1456        assert_eq!(
1457            callers_of(&graph, "create_project", "src/app/mod.rs"),
1458            vec!["handler", "persistence_test"]
1459        );
1460        // `app::record` is a `pub use audit::writer::record` re-export.
1461        assert_eq!(
1462            callers_of(&graph, "record", "src/app/audit/writer.rs"),
1463            vec!["handler", "persistence_test"]
1464        );
1465    }
1466
1467    #[test]
1468    fn external_crate_paths_do_not_bind_to_local_names() {
1469        let mut b = GraphBuilder::new();
1470        b.add_nodes(vec![
1471            function("query", "src/db/queries.rs", &[]),
1472            function("load", "src/routes/mod.rs", &["sqlx::query"]),
1473        ]);
1474        let graph = b.build();
1475        assert!(callers_of(&graph, "query", "src/db/queries.rs").is_empty());
1476    }
1477
1478    #[test]
1479    fn type_paths_resolve_to_the_types_method() {
1480        let mut b = GraphBuilder::new();
1481        b.add_nodes(vec![
1482            CodeNode::new(
1483                "Provider",
1484                "Provider",
1485                NodeKind::Struct,
1486                "src/billing/mod.rs",
1487            ),
1488            method("Provider", "new", "src/billing/mod.rs", &[]),
1489            method("Fixture", "new", "tests/fixture.rs", &[]),
1490            function("boot", "src/main.rs", &["Provider::new"]),
1491        ]);
1492        let graph = b.build();
1493        assert_eq!(
1494            callers_of(&graph, "new", "src/billing/mod.rs"),
1495            vec!["boot"]
1496        );
1497        assert!(callers_of(&graph, "new", "tests/fixture.rs").is_empty());
1498    }
1499
1500    #[test]
1501    fn a_mock_struct_with_the_same_name_does_not_hide_the_real_owner() {
1502        let mut b = GraphBuilder::new();
1503        b.add_nodes(vec![
1504            CodeNode::new(
1505                "Provider",
1506                "Provider",
1507                NodeKind::Struct,
1508                "src/payments/mod.rs",
1509            ),
1510            CodeNode::new("Provider", "Provider", NodeKind::Struct, "tests/mocks.rs"),
1511            method("Provider", "owner_of", "src/payments/checkout.rs", &[]),
1512            method(
1513                "Provider",
1514                "order_history",
1515                "src/payments/cancellation.rs",
1516                &["self.owner_of", ".bind"],
1517            ),
1518            function("bind", "src/payments/tests.rs", &[]),
1519        ]);
1520        let graph = b.build();
1521        assert_eq!(
1522            callers_of(&graph, "owner_of", "src/payments/checkout.rs"),
1523            vec!["order_history"]
1524        );
1525        // `.bind(...)` is a method call; it can't reach a free function.
1526        assert!(callers_of(&graph, "bind", "src/payments/tests.rs").is_empty());
1527    }
1528
1529    #[test]
1530    fn self_calls_reach_methods_whose_impl_is_in_another_file() {
1531        let mut b = GraphBuilder::new();
1532        b.add_nodes(vec![
1533            CodeNode::new(
1534                "Provider",
1535                "Provider",
1536                NodeKind::Struct,
1537                "src/payments/mod.rs",
1538            ),
1539            method("Provider", "owner_of", "src/payments/checkout.rs", &[]),
1540            method(
1541                "Provider",
1542                "order_history",
1543                "src/payments/cancellation.rs",
1544                &["self.owner_of"],
1545            ),
1546        ]);
1547        let graph = b.build();
1548        assert_eq!(
1549            callers_of(&graph, "owner_of", "src/payments/checkout.rs"),
1550            vec!["order_history"]
1551        );
1552    }
1553}