Skip to main content

arbor_graph/
symbol_table.rs

1//! Cross-file symbol resolution.
2//!
3//! Maps Fully Qualified Names (FQNs) to graph nodes and resolves bare or
4//! partially-qualified references against them.
5//!
6//! # Determinism
7//!
8//! Every lookup path in this module is order-independent. Candidate lists are
9//! sorted by `(file, node index)` before any pick is made, and no decision ever
10//! depends on `HashMap` iteration order — Rust seeds `RandomState` per process,
11//! so iterating a map to choose a winner would make graph construction vary
12//! between runs of the same binary on the same input.
13//!
14//! # Collisions
15//!
16//! An FQN can legitimately map to several nodes: `handler` in twelve route
17//! files, `new` on forty structs, `process` in both `utils.py` and `helpers.py`.
18//! The table keeps every entry and reports ambiguity to the caller rather than
19//! silently overwriting, which would orphan the loser and produce a false
20//! negative in blast radius.
21
22use crate::graph::NodeId;
23use std::collections::HashMap;
24use std::path::{Path, PathBuf};
25
26/// One definition of a symbol.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct SymbolEntry {
29    pub id: NodeId,
30    pub file: PathBuf,
31}
32
33/// How a reference was matched, ordered from most to least trustworthy.
34///
35/// The variant determines the confidence stamped on the resulting edge, so a
36/// downstream consumer can tell a certain call from an educated guess.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum Resolution {
39    /// Exact FQN match with exactly one definition.
40    Exact(NodeId),
41    /// Matched a symbol defined in the referencing file.
42    SameFile(NodeId),
43    /// Suffix match with exactly one definition repo-wide.
44    UniqueSuffix(NodeId),
45    /// Several candidates; the referencing file's own import statement names
46    /// exactly one module, and one candidate came from it.
47    ///
48    /// Stronger evidence than `SameDir`: the author wrote down which module they
49    /// meant. Ranked accordingly in `confidence`.
50    ViaImport(NodeId),
51    /// Several candidates; exactly one lives in the referencing file's directory.
52    SameDir(NodeId),
53    /// Several equally-plausible candidates, sorted deterministically.
54    Ambiguous(Vec<NodeId>),
55    /// No definition in this repository (external or stdlib).
56    Unresolved,
57}
58
59impl Resolution {
60    /// Confidence to stamp on an edge created from this resolution.
61    ///
62    /// `Ambiguous` is deliberately low rather than zero: the reference does
63    /// point at *something* in the repo, we just cannot say which. Consumers
64    /// that need certainty should filter on this value.
65    pub fn confidence(&self) -> f32 {
66        match self {
67            Resolution::Exact(_) => 1.0,
68            Resolution::SameFile(_) => 0.95,
69            Resolution::UniqueSuffix(_) => 0.80,
70            Resolution::ViaImport(_) => 0.93,
71            Resolution::SameDir(_) => 0.55,
72            Resolution::Ambiguous(_) => 0.25,
73            Resolution::Unresolved => 0.0,
74        }
75    }
76
77    /// The single resolved node, if this resolution picked one.
78    pub fn node(&self) -> Option<NodeId> {
79        match self {
80            Resolution::Exact(id)
81            | Resolution::SameFile(id)
82            | Resolution::UniqueSuffix(id)
83            | Resolution::ViaImport(id)
84            | Resolution::SameDir(id) => Some(*id),
85            Resolution::Ambiguous(_) | Resolution::Unresolved => None,
86        }
87    }
88
89    /// Every candidate this resolution considered plausible.
90    pub fn candidates(&self) -> Vec<NodeId> {
91        match self {
92            Resolution::Ambiguous(ids) => ids.clone(),
93            other => other.node().into_iter().collect(),
94        }
95    }
96
97    pub fn is_resolved(&self) -> bool {
98        !matches!(self, Resolution::Unresolved)
99    }
100}
101
102/// A global symbol table for resolving cross-file references.
103#[derive(Debug, Default, Clone)]
104pub struct SymbolTable {
105    /// FQN → every node defining it.
106    by_fqn: HashMap<String, Vec<SymbolEntry>>,
107
108    /// Segment-aligned suffix → FQNs ending with it.
109    ///
110    /// `pkg.Utils.helper` is indexed under `helper`, `Utils.helper`, and
111    /// `pkg.Utils.helper`, so resolving a bare `helper` is an O(1) lookup
112    /// instead of a scan over every FQN in the repository.
113    by_suffix: HashMap<String, Vec<String>>,
114
115    /// File → FQNs it defines.
116    exports_by_file: HashMap<PathBuf, Vec<String>>,
117}
118
119impl SymbolTable {
120    pub fn new() -> Self {
121        Self::default()
122    }
123
124    /// Registers a symbol definition.
125    ///
126    /// Repeated FQNs accumulate instead of overwriting.
127    pub fn insert(&mut self, fqn: String, id: NodeId, file: PathBuf) {
128        let entry = SymbolEntry {
129            id,
130            file: file.clone(),
131        };
132
133        let entries = self.by_fqn.entry(fqn.clone()).or_default();
134        // Guard against the same definition being indexed twice (incremental
135        // re-parse of an unchanged file).
136        if !entries.contains(&entry) {
137            entries.push(entry);
138        }
139
140        for suffix in segment_suffixes(&fqn) {
141            let fqns = self.by_suffix.entry(suffix.to_string()).or_default();
142            if !fqns.iter().any(|f| f == &fqn) {
143                fqns.push(fqn.clone());
144            }
145        }
146
147        let exports = self.exports_by_file.entry(file).or_default();
148        if !exports.contains(&fqn) {
149            exports.push(fqn);
150        }
151    }
152
153    /// Resolves an exact FQN, but only when the definition is unambiguous.
154    ///
155    /// Returns `None` for a colliding FQN so the caller can fall back to
156    /// context-aware resolution rather than picking a definition at random.
157    pub fn resolve(&self, fqn: &str) -> Option<NodeId> {
158        match self.by_fqn.get(fqn) {
159            Some(entries) if entries.len() == 1 => Some(entries[0].id),
160            _ => None,
161        }
162    }
163
164    /// All nodes defining this exact FQN, in deterministic order.
165    pub fn resolve_all(&self, fqn: &str) -> Vec<NodeId> {
166        let Some(entries) = self.by_fqn.get(fqn) else {
167            return Vec::new();
168        };
169        let mut entries: Vec<&SymbolEntry> = entries.iter().collect();
170        sort_entries(&mut entries);
171        entries.into_iter().map(|e| e.id).collect()
172    }
173
174    /// Returns all symbols exported by a file.
175    pub fn get_file_exports(&self, file: &PathBuf) -> Option<&Vec<String>> {
176        self.exports_by_file.get(file)
177    }
178
179    pub fn clear(&mut self) {
180        self.by_fqn.clear();
181        self.by_suffix.clear();
182        self.exports_by_file.clear();
183    }
184
185    /// Resolves a reference, preferring locality and reporting ambiguity.
186    ///
187    /// Order:
188    ///   1. Exact FQN, unique → `Exact`
189    ///   2. Candidate gathering: exact-FQN entries plus every segment-aligned
190    ///      suffix match, deduplicated and sorted
191    ///   3. Single candidate → `Exact` / `UniqueSuffix`
192    ///   4. Exactly one candidate in the referencing file → `SameFile`
193    ///   5. Exactly one candidate in the referencing directory → `SameDir`
194    ///   6. Otherwise → `Ambiguous`
195    pub fn resolve_ref(&self, name: &str, context_file: &Path) -> Resolution {
196        self.resolve_ref_with_imports(name, context_file, None)
197    }
198
199    /// Resolve a reference, allowing the referencing file's imports to break ties.
200    ///
201    /// Without `imports`, a bare name matching definitions in several modules
202    /// falls through to `Ambiguous` whenever no candidate shares a file or a
203    /// directory with the caller — and the builder drops ambiguous edges. On a
204    /// codebase that reuses a name across modules that is the common case, not
205    /// the rare one: every call to it is discarded, and the module those calls
206    /// belonged to reports no callers at all.
207    ///
208    /// The disambiguating fact is usually written at the top of the file.
209    /// `from deep.l0.m14 import value_m14` says exactly which `value_m14` is
210    /// meant here. `import_map` already carries that, but only
211    /// `apply_import_validation` consumed it, and that runs *after* a candidate
212    /// has been chosen — so it never saw the references that were being thrown
213    /// away. Consulting it during disambiguation instead of after it is the
214    /// whole change.
215    ///
216    /// `imports` maps a locally-visible name to the module it came from, so an
217    /// aliased import (`from x import y as z`) is keyed on `z`.
218    pub fn resolve_ref_with_imports(
219        &self,
220        name: &str,
221        context_file: &Path,
222        imports: Option<&HashMap<String, String>>,
223    ) -> Resolution {
224        // A call never crosses languages: a Rust `enqueue` isn't called by a
225        // TypeScript `enqueue(...)`. Definitions in another language are not
226        // candidates at all, so they can neither win nor make a match ambiguous.
227        let family = language_family(context_file);
228        let visible = |e: &SymbolEntry| same_family(family, &e.file);
229
230        let exact: Option<Vec<&SymbolEntry>> = self
231            .by_fqn
232            .get(name)
233            .map(|entries| entries.iter().filter(|e| visible(e)).collect::<Vec<_>>())
234            .filter(|entries| !entries.is_empty());
235        if let Some(entries) = &exact {
236            if entries.len() == 1 {
237                return Resolution::Exact(entries[0].id);
238            }
239        }
240        let had_exact = exact.is_some();
241
242        let mut candidates: Vec<&SymbolEntry> = Vec::new();
243        let mut seen: Vec<NodeId> = Vec::new();
244
245        if let Some(entries) = exact {
246            for e in entries {
247                if !seen.contains(&e.id) {
248                    seen.push(e.id);
249                    candidates.push(e);
250                }
251            }
252        }
253
254        if let Some(fqns) = self.by_suffix.get(name) {
255            // `by_suffix` values are insertion-ordered Vecs, but sort the FQN
256            // list anyway so candidate order never depends on parse order.
257            let mut fqns: Vec<&String> = fqns.iter().collect();
258            fqns.sort();
259            for fqn in fqns {
260                if let Some(entries) = self.by_fqn.get(fqn) {
261                    for e in entries {
262                        if visible(e) && !seen.contains(&e.id) {
263                            seen.push(e.id);
264                            candidates.push(e);
265                        }
266                    }
267                }
268            }
269        }
270
271        if candidates.is_empty() {
272            return Resolution::Unresolved;
273        }
274
275        sort_entries(&mut candidates);
276
277        if candidates.len() == 1 {
278            return if had_exact {
279                Resolution::Exact(candidates[0].id)
280            } else {
281                Resolution::UniqueSuffix(candidates[0].id)
282            };
283        }
284
285        let same_file: Vec<&SymbolEntry> = candidates
286            .iter()
287            .copied()
288            .filter(|e| e.file == context_file)
289            .collect();
290        if same_file.len() == 1 {
291            return Resolution::SameFile(same_file[0].id);
292        }
293
294        // The referencing file said which module it meant. Believe it.
295        //
296        // Checked after same-file (a local definition shadows an import) and
297        // before same-directory (a written import is better evidence than mere
298        // adjacency). Matching is done on the module path so it works whether
299        // the source records `deep.l0.m14` or a path-like `deep/l0/m14`.
300        if let Some(map) = imports {
301            if let Some(source_module) = map.get(name) {
302                let wanted = normalize_module_path(source_module);
303                if !wanted.is_empty() {
304                    let from_import: Vec<&SymbolEntry> = candidates
305                        .iter()
306                        .copied()
307                        .filter(|e| entry_belongs_to_module(e, &wanted))
308                        .collect();
309                    if from_import.len() == 1 {
310                        return Resolution::ViaImport(from_import[0].id);
311                    }
312                }
313            }
314        }
315
316        let context_dir = context_file.parent();
317        let same_dir: Vec<&SymbolEntry> = candidates
318            .iter()
319            .copied()
320            .filter(|e| e.file.parent() == context_dir)
321            .collect();
322        if same_dir.len() == 1 {
323            return Resolution::SameDir(same_dir[0].id);
324        }
325
326        Resolution::Ambiguous(candidates.into_iter().map(|e| e.id).collect())
327    }
328
329    /// Resolves a `::` path reference: `jobs::enqueue`, `Provider::new`,
330    /// `crate::db::queries::get_user`, `my_app::app::create`.
331    ///
332    /// The path says where the definition lives, so it is matched on that
333    /// rather than on the bare name:
334    ///
335    /// - a path some parser recorded verbatim (C++ `ns::fn`) matches directly;
336    /// - a capitalised owner is a type, and `Type::new` is stored as `Type.new`;
337    /// - anything else is a module, matched against the definition's file
338    ///   (`jobs.rs`, `app/mod.rs`). Leading segments are dropped until one
339    ///   matches, so a crate-name prefix (`my_app::app::…`) works,
340    ///   and a definition re-exported from a submodule is found at lower
341    ///   confidence.
342    ///
343    /// A path into an external crate (`sqlx::query`, `std::fs::read`) matches
344    /// nothing here and stays unresolved, instead of binding to an unrelated
345    /// local function that shares the last name.
346    pub fn resolve_path(&self, path: &str, context_file: &Path) -> Resolution {
347        let family = language_family(context_file);
348        let visible = |e: &&SymbolEntry| same_family(family, &e.file);
349
350        let verbatim = self.entries_with_suffix(path, &visible);
351        if !verbatim.is_empty() {
352            return pick(verbatim, context_file, Resolution::Exact);
353        }
354
355        let segments: Vec<&str> = path
356            .split("::")
357            .map(str::trim)
358            .filter(|s| !s.is_empty() && !matches!(*s, "crate" | "self" | "super"))
359            .collect();
360        let Some((name, qualifiers)) = segments.split_last() else {
361            return Resolution::Unresolved;
362        };
363        let Some(owner) = qualifiers.last() else {
364            return self.resolve_ref(name, context_file);
365        };
366
367        if owner.starts_with(|c: char| c.is_uppercase()) {
368            let mut entries = self.entries_with_suffix(&format!("{owner}.{name}"), &visible);
369            entries.extend(self.entries_with_suffix(&format!("{owner}::{name}"), &visible));
370            // Nothing: an enum variant (`Error::NotFound(e)`) or an external type.
371            return pick(entries, context_file, Resolution::Exact);
372        }
373
374        // Free functions are stored under their bare name.
375        let named: Vec<&SymbolEntry> = self
376            .by_fqn
377            .get(*name)
378            .into_iter()
379            .flatten()
380            .filter(|e| visible(e))
381            .collect();
382        for start in 0..qualifiers.len() {
383            let wanted = normalize_module_path(&qualifiers[start..].join("."));
384            if wanted.is_empty() {
385                continue;
386            }
387            let in_module: Vec<&SymbolEntry> = named
388                .iter()
389                .copied()
390                .filter(|e| module_is(e, &wanted))
391                .collect();
392            if !in_module.is_empty() {
393                return pick(in_module, context_file, Resolution::ViaImport);
394            }
395            let re_exported: Vec<&SymbolEntry> = named
396                .iter()
397                .copied()
398                .filter(|e| entry_belongs_to_module(e, &wanted))
399                .collect();
400            if !re_exported.is_empty() {
401                return pick(re_exported, context_file, Resolution::UniqueSuffix);
402            }
403        }
404        Resolution::Unresolved
405    }
406
407    /// Entries whose FQN is `fqn` or ends with it on a segment boundary.
408    fn entries_with_suffix(
409        &self,
410        fqn: &str,
411        visible: &dyn Fn(&&SymbolEntry) -> bool,
412    ) -> Vec<&SymbolEntry> {
413        let mut fqns: Vec<&String> = self.by_suffix.get(fqn).into_iter().flatten().collect();
414        fqns.sort();
415        fqns.into_iter()
416            .filter_map(|f| self.by_fqn.get(f))
417            .flatten()
418            .filter(|e| visible(e))
419            .collect()
420    }
421
422    /// Back-compatible wrapper returning only a confidently-resolved node.
423    pub fn resolve_with_context(&self, name: &str, context_file: &Path) -> Option<NodeId> {
424        self.resolve_ref(name, context_file).node()
425    }
426
427    /// Number of distinct FQNs registered.
428    pub fn len(&self) -> usize {
429        self.by_fqn.len()
430    }
431
432    pub fn is_empty(&self) -> bool {
433        self.by_fqn.is_empty()
434    }
435}
436
437/// Reduce a module reference to dot-separated segments for comparison.
438///
439/// `deep.l0.m14`, `deep/l0/m14`, `./deep/l0/m14.py` and `crate::deep::l0::m14`
440/// all normalize to `deep.l0.m14`, so the same check works across the languages
441/// this engine parses without a per-language branch.
442fn normalize_module_path(raw: &str) -> String {
443    let cleaned = raw.replace("::", ".").replace(['/', '\\'], ".");
444    let cleaned = cleaned
445        .trim_start_matches('.')
446        .trim_end_matches(".py")
447        .trim_end_matches(".ts")
448        .trim_end_matches(".js")
449        .trim_end_matches(".rs")
450        .trim_end_matches(".go");
451    cleaned
452        .split('.')
453        .filter(|seg| {
454            !seg.is_empty()
455                && *seg != "index"
456                && *seg != "mod"
457                && *seg != "crate"
458                && *seg != "self"
459                && *seg != "super"
460        })
461        .collect::<Vec<_>>()
462        .join(".")
463}
464
465/// Picks among entries that all match the reference equally well: one is
466/// `unique`, otherwise the referencing file, then its directory, break ties.
467fn pick(
468    mut entries: Vec<&SymbolEntry>,
469    context_file: &Path,
470    unique: fn(NodeId) -> Resolution,
471) -> Resolution {
472    sort_entries(&mut entries);
473    entries.dedup_by_key(|e| e.id);
474    match entries.as_slice() {
475        [] => Resolution::Unresolved,
476        [only] => unique(only.id),
477        _ => {
478            let same_file: Vec<&&SymbolEntry> =
479                entries.iter().filter(|e| e.file == context_file).collect();
480            if same_file.len() == 1 {
481                return Resolution::SameFile(same_file[0].id);
482            }
483            let dir = context_file.parent();
484            let same_dir: Vec<&&SymbolEntry> =
485                entries.iter().filter(|e| e.file.parent() == dir).collect();
486            if same_dir.len() == 1 {
487                return Resolution::SameDir(same_dir[0].id);
488            }
489            Resolution::Ambiguous(entries.into_iter().map(|e| e.id).collect())
490        }
491    }
492}
493
494/// Is this symbol defined in exactly `module` (`jobs.rs`, `jobs/mod.rs`)?
495fn module_is(entry: &SymbolEntry, module: &str) -> bool {
496    let file_norm = normalize_module_path(&entry.file.to_string_lossy());
497    file_norm == module || file_norm.ends_with(&format!(".{module}"))
498}
499
500/// Source languages that can call each other directly. Calls are never
501/// resolved across families; a name shared by a Rust and a TypeScript
502/// definition is two symbols, not one.
503fn language_family(path: &Path) -> Option<&'static str> {
504    let ext = path.extension()?.to_str()?.to_ascii_lowercase();
505    Some(match ext.as_str() {
506        "rs" => "rust",
507        "ts" | "tsx" | "mts" | "cts" | "js" | "jsx" | "mjs" | "cjs" | "vue" | "svelte" => "js",
508        "py" | "pyi" => "python",
509        "go" => "go",
510        "java" | "kt" | "kts" | "scala" => "jvm",
511        "c" | "h" | "cc" | "cpp" | "cxx" | "hh" | "hpp" | "hxx" | "m" | "mm" => "c",
512        "cs" => "csharp",
513        "rb" => "ruby",
514        "php" | "phtml" => "php",
515        "swift" => "swift",
516        "dart" => "dart",
517        "sh" | "bash" | "zsh" => "shell",
518        _ => return None,
519    })
520}
521
522/// Unknown extensions on either side don't filter anything out.
523fn same_family(family: Option<&'static str>, file: &Path) -> bool {
524    match (family, language_family(file)) {
525        (Some(a), Some(b)) => a == b,
526        _ => true,
527    }
528}
529
530/// Did this symbol come from `module`?
531///
532/// A `SymbolEntry` carries only its id and its file, so the file path is the
533/// module identity. Requires a segment-aligned match, so a reference to
534/// `l0.m14` is never satisfied by `l0.m1`.
535fn entry_belongs_to_module(entry: &SymbolEntry, module: &str) -> bool {
536    let file_norm = normalize_module_path(&entry.file.to_string_lossy());
537    segment_aligned_contains(&file_norm, module)
538}
539
540/// True when `needle` appears in `haystack` on segment boundaries.
541fn segment_aligned_contains(haystack: &str, needle: &str) -> bool {
542    if haystack == needle {
543        return true;
544    }
545    haystack.starts_with(&format!("{needle}."))
546        || haystack.ends_with(&format!(".{needle}"))
547        || haystack.contains(&format!(".{needle}."))
548}
549
550/// Sorts entries by `(file, node index)` for a total, parse-order-independent order.
551fn sort_entries(entries: &mut [&SymbolEntry]) {
552    entries.sort_by(|a, b| {
553        a.file
554            .cmp(&b.file)
555            .then_with(|| a.id.index().cmp(&b.id.index()))
556    });
557}
558
559/// Every segment-aligned suffix of an FQN, including the FQN itself.
560///
561/// `a.b.c` → `["a.b.c", "b.c", "c"]`; `a::b::c` → `["a::b::c", "b::c", "c"]`.
562///
563/// Only positions immediately after a `.` or `:` qualify, so `helper` never
564/// matches the tail of `my_helper`. A suffix that would itself start with a
565/// separator (the middle of Rust's `::`) is skipped.
566fn segment_suffixes(fqn: &str) -> Vec<&str> {
567    let mut out = vec![fqn];
568    let bytes = fqn.as_bytes();
569
570    for (i, c) in fqn.char_indices().skip(1) {
571        if c == '.' || c == ':' {
572            continue;
573        }
574        // `i` is a char boundary, so `bytes[i - 1]` is either the whole
575        // previous char (ASCII) or a UTF-8 continuation byte (>= 0x80),
576        // which can never equal `.` or `:`.
577        let prev = bytes[i - 1];
578        if prev == b'.' || prev == b':' {
579            out.push(&fqn[i..]);
580        }
581    }
582
583    out
584}
585
586#[cfg(test)]
587mod tests {
588    use super::*;
589
590    fn nid(n: usize) -> NodeId {
591        petgraph::graph::NodeIndex::new(n)
592    }
593
594    #[test]
595    fn insert_resolve() {
596        let mut table = SymbolTable::new();
597        let path = PathBuf::from("main.rs");
598        table.insert("main::foo".to_string(), nid(1), path.clone());
599
600        assert_eq!(table.resolve("main::foo"), Some(nid(1)));
601        assert_eq!(table.resolve("main::bar"), None);
602        assert_eq!(table.get_file_exports(&path).unwrap(), &vec!["main::foo"]);
603    }
604
605    #[test]
606    fn exact_match_from_any_context() {
607        let mut table = SymbolTable::new();
608        table.insert(
609            "pkg.utils.helper".to_string(),
610            nid(1),
611            PathBuf::from("src/utils.rs"),
612        );
613
614        let r = table.resolve_ref("pkg.utils.helper", Path::new("other/file.rs"));
615        assert_eq!(r, Resolution::Exact(nid(1)));
616        assert_eq!(r.confidence(), 1.0);
617    }
618
619    #[test]
620    fn unique_suffix_match() {
621        let mut table = SymbolTable::new();
622        table.insert(
623            "pkg.utils.helper".to_string(),
624            nid(1),
625            PathBuf::from("src/utils.rs"),
626        );
627
628        let r = table.resolve_ref("helper", Path::new("other/file.rs"));
629        assert_eq!(r, Resolution::UniqueSuffix(nid(1)));
630    }
631
632    #[test]
633    fn multi_segment_suffix_match() {
634        let mut table = SymbolTable::new();
635        table.insert(
636            "pkg.Utils.helper".to_string(),
637            nid(1),
638            PathBuf::from("src/utils.rs"),
639        );
640
641        let r = table.resolve_ref("Utils.helper", Path::new("other/file.rs"));
642        assert_eq!(r, Resolution::UniqueSuffix(nid(1)));
643    }
644
645    #[test]
646    fn suffix_must_be_segment_aligned() {
647        let mut table = SymbolTable::new();
648        table.insert(
649            "pkg.my_helper".to_string(),
650            nid(1),
651            PathBuf::from("src/utils.rs"),
652        );
653
654        // `helper` is a character-suffix of `my_helper` but not a segment.
655        assert_eq!(
656            table.resolve_ref("helper", Path::new("other/file.rs")),
657            Resolution::Unresolved
658        );
659    }
660
661    #[test]
662    fn ambiguous_reports_all_candidates() {
663        let mut table = SymbolTable::new();
664        table.insert(
665            "pkg.a.helper".to_string(),
666            nid(1),
667            PathBuf::from("src/a/mod.rs"),
668        );
669        table.insert(
670            "pkg.b.helper".to_string(),
671            nid(2),
672            PathBuf::from("src/b/mod.rs"),
673        );
674
675        let r = table.resolve_ref("helper", Path::new("src/c/caller.rs"));
676        assert_eq!(r, Resolution::Ambiguous(vec![nid(1), nid(2)]));
677        assert!(r.node().is_none());
678        assert_eq!(r.candidates().len(), 2);
679    }
680
681    #[test]
682    fn locality_preference_same_dir() {
683        let mut table = SymbolTable::new();
684        table.insert(
685            "pkg.a.helper".to_string(),
686            nid(1),
687            PathBuf::from("src/a/mod.rs"),
688        );
689        table.insert(
690            "pkg.b.helper".to_string(),
691            nid(2),
692            PathBuf::from("src/b/mod.rs"),
693        );
694
695        assert_eq!(
696            table.resolve_ref("helper", Path::new("src/a/caller.rs")),
697            Resolution::SameDir(nid(1))
698        );
699        assert_eq!(
700            table.resolve_ref("helper", Path::new("src/b/caller.rs")),
701            Resolution::SameDir(nid(2))
702        );
703    }
704
705    #[test]
706    fn same_file_beats_same_dir() {
707        let mut table = SymbolTable::new();
708        table.insert("A.run".to_string(), nid(1), PathBuf::from("src/a.rs"));
709        table.insert("B.run".to_string(), nid(2), PathBuf::from("src/b.rs"));
710
711        // Both live in `src/`, so same-dir cannot disambiguate — same-file must.
712        assert_eq!(
713            table.resolve_ref("run", Path::new("src/a.rs")),
714            Resolution::SameFile(nid(1))
715        );
716    }
717
718    #[test]
719    fn colliding_fqn_keeps_both_definitions() {
720        let mut table = SymbolTable::new();
721        table.insert("process".to_string(), nid(1), PathBuf::from("src/utils.py"));
722        table.insert(
723            "process".to_string(),
724            nid(2),
725            PathBuf::from("src/helpers.py"),
726        );
727
728        // The old table overwrote here, orphaning one node entirely.
729        assert_eq!(table.resolve_all("process"), vec![nid(2), nid(1)]);
730        assert_eq!(
731            table.resolve("process"),
732            None,
733            "collision is not unambiguous"
734        );
735
736        let r = table.resolve_ref("process", Path::new("src/other.py"));
737        assert_eq!(r, Resolution::Ambiguous(vec![nid(2), nid(1)]));
738    }
739
740    #[test]
741    fn duplicate_insert_is_idempotent() {
742        let mut table = SymbolTable::new();
743        table.insert("a.b".to_string(), nid(1), PathBuf::from("x.rs"));
744        table.insert("a.b".to_string(), nid(1), PathBuf::from("x.rs"));
745
746        assert_eq!(table.resolve_all("a.b"), vec![nid(1)]);
747        assert_eq!(
748            table
749                .get_file_exports(&PathBuf::from("x.rs"))
750                .unwrap()
751                .len(),
752            1
753        );
754    }
755
756    #[test]
757    fn resolution_confidence_is_ordered() {
758        assert!(Resolution::Exact(nid(0)).confidence() > Resolution::SameFile(nid(0)).confidence());
759        assert!(
760            Resolution::SameFile(nid(0)).confidence()
761                > Resolution::UniqueSuffix(nid(0)).confidence()
762        );
763        assert!(
764            Resolution::UniqueSuffix(nid(0)).confidence()
765                > Resolution::SameDir(nid(0)).confidence()
766        );
767        assert!(
768            Resolution::SameDir(nid(0)).confidence() > Resolution::Ambiguous(vec![]).confidence()
769        );
770        assert_eq!(Resolution::Unresolved.confidence(), 0.0);
771    }
772
773    #[test]
774    fn resolution_is_order_independent() {
775        // Same definitions inserted in opposite orders must resolve identically.
776        let mut a = SymbolTable::new();
777        a.insert("p.x.run".into(), nid(1), PathBuf::from("src/x/mod.rs"));
778        a.insert("p.y.run".into(), nid(2), PathBuf::from("src/y/mod.rs"));
779        a.insert("p.z.run".into(), nid(3), PathBuf::from("src/z/mod.rs"));
780
781        let mut b = SymbolTable::new();
782        b.insert("p.z.run".into(), nid(3), PathBuf::from("src/z/mod.rs"));
783        b.insert("p.y.run".into(), nid(2), PathBuf::from("src/y/mod.rs"));
784        b.insert("p.x.run".into(), nid(1), PathBuf::from("src/x/mod.rs"));
785
786        let ctx = Path::new("src/other/caller.rs");
787        assert_eq!(a.resolve_ref("run", ctx), b.resolve_ref("run", ctx));
788    }
789
790    #[test]
791    fn segment_suffixes_shapes() {
792        assert_eq!(segment_suffixes("a.b.c"), vec!["a.b.c", "b.c", "c"]);
793        assert_eq!(segment_suffixes("a::b::c"), vec!["a::b::c", "b::c", "c"]);
794        assert_eq!(segment_suffixes("solo"), vec!["solo"]);
795    }
796
797    #[test]
798    fn unicode_fqn_does_not_panic() {
799        let mut table = SymbolTable::new();
800        table.insert("módulo.función".to_string(), nid(1), PathBuf::from("a.py"));
801        assert_eq!(
802            table.resolve_ref("función", Path::new("b.py")),
803            Resolution::UniqueSuffix(nid(1))
804        );
805    }
806}
807
808#[cfg(test)]
809mod import_resolution_tests {
810    use super::*;
811
812    fn nid(i: usize) -> NodeId {
813        NodeId::new(i)
814    }
815
816    /// The exact shape that returned zero on the torture fixture: one bare name
817    /// defined in ten modules, called from an eleventh that imported one of them.
818    #[test]
819    fn import_breaks_a_tie_that_would_otherwise_be_ambiguous() {
820        let mut table = SymbolTable::default();
821        for layer in 0usize..10 {
822            table.insert(
823                format!("deep.l{layer}.m14.value_m14"),
824                nid(layer),
825                PathBuf::from(format!("/repo/deep/l{layer}/m14.py")),
826            );
827        }
828
829        let caller = Path::new("/repo/deep/l1/m03.py");
830
831        // Without imports the resolver does NOT report ambiguity — it picks the
832        // sibling sitting in the caller's own directory and reports SameDir at
833        // 0.55 confidence. That is the real defect: the edge is not dropped, it
834        // is confidently attached to the wrong module. Every caller in `l1/`
835        // resolves to `l1/m14.py`, which is why `l0/m14.py` ends up with no
836        // callers at all while an unrelated layer inherits its centrality.
837        let bare = table.resolve_ref("value_m14", caller);
838        assert_eq!(
839            bare,
840            Resolution::SameDir(nid(1)),
841            "expected the same-directory sibling to be mis-picked, got {bare:?}"
842        );
843
844        // With the import the caller actually wrote, exactly one survives.
845        let mut imports = HashMap::new();
846        imports.insert("value_m14".to_string(), "deep.l0.m14".to_string());
847        let resolved = table.resolve_ref_with_imports("value_m14", caller, Some(&imports));
848
849        match resolved {
850            Resolution::ViaImport(id) => {
851                assert_eq!(id, nid(0), "resolved to the wrong layer");
852            }
853            other => panic!("expected ViaImport(l0), got {other:?}"),
854        }
855    }
856
857    /// A definition in the caller's own file outranks an import of the same name.
858    #[test]
859    fn local_definition_still_shadows_an_import() {
860        let mut table = SymbolTable::default();
861        table.insert(
862            "a.mod.process".to_string(),
863            nid(0),
864            PathBuf::from("/repo/a/mod.py"),
865        );
866        table.insert(
867            "b.other.process".to_string(),
868            nid(1),
869            PathBuf::from("/repo/b/other.py"),
870        );
871
872        let caller = Path::new("/repo/a/mod.py");
873        let mut imports = HashMap::new();
874        imports.insert("process".to_string(), "b.other".to_string());
875
876        let r = table.resolve_ref_with_imports("process", caller, Some(&imports));
877        assert!(
878            matches!(r, Resolution::SameFile(_)),
879            "a local definition must win over an import, got {r:?}"
880        );
881    }
882
883    #[test]
884    fn module_paths_normalize_across_separator_styles() {
885        assert_eq!(normalize_module_path("deep/l0/m14.py"), "deep.l0.m14");
886        assert_eq!(normalize_module_path("crate::deep::l0::m14"), "deep.l0.m14");
887        assert_eq!(normalize_module_path("./deep/l0/m14"), "deep.l0.m14");
888    }
889
890    /// `l0.m1` must never satisfy a request for `l0.m14`.
891    #[test]
892    fn module_matching_is_segment_aligned() {
893        assert!(segment_aligned_contains("x.deep.l0.m14", "deep.l0.m14"));
894        assert!(!segment_aligned_contains("x.deep.l0.m140", "deep.l0.m14"));
895        assert!(!segment_aligned_contains("x.deep.l0.m1", "deep.l0.m14"));
896    }
897}