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.
523/// Whether two files are in the same language family (an unknown extension
524/// matches anything).
525pub(crate) fn same_language(a: &Path, b: &Path) -> bool {
526    same_family(language_family(a), b)
527}
528
529fn same_family(family: Option<&'static str>, file: &Path) -> bool {
530    match (family, language_family(file)) {
531        (Some(a), Some(b)) => a == b,
532        _ => true,
533    }
534}
535
536/// Did this symbol come from `module`?
537///
538/// A `SymbolEntry` carries only its id and its file, so the file path is the
539/// module identity. Requires a segment-aligned match, so a reference to
540/// `l0.m14` is never satisfied by `l0.m1`.
541fn entry_belongs_to_module(entry: &SymbolEntry, module: &str) -> bool {
542    let file_norm = normalize_module_path(&entry.file.to_string_lossy());
543    segment_aligned_contains(&file_norm, module)
544}
545
546/// True when `needle` appears in `haystack` on segment boundaries.
547fn segment_aligned_contains(haystack: &str, needle: &str) -> bool {
548    if haystack == needle {
549        return true;
550    }
551    haystack.starts_with(&format!("{needle}."))
552        || haystack.ends_with(&format!(".{needle}"))
553        || haystack.contains(&format!(".{needle}."))
554}
555
556/// Sorts entries by `(file, node index)` for a total, parse-order-independent order.
557fn sort_entries(entries: &mut [&SymbolEntry]) {
558    entries.sort_by(|a, b| {
559        a.file
560            .cmp(&b.file)
561            .then_with(|| a.id.index().cmp(&b.id.index()))
562    });
563}
564
565/// Every segment-aligned suffix of an FQN, including the FQN itself.
566///
567/// `a.b.c` → `["a.b.c", "b.c", "c"]`; `a::b::c` → `["a::b::c", "b::c", "c"]`.
568///
569/// Only positions immediately after a `.` or `:` qualify, so `helper` never
570/// matches the tail of `my_helper`. A suffix that would itself start with a
571/// separator (the middle of Rust's `::`) is skipped.
572fn segment_suffixes(fqn: &str) -> Vec<&str> {
573    let mut out = vec![fqn];
574    let bytes = fqn.as_bytes();
575
576    for (i, c) in fqn.char_indices().skip(1) {
577        if c == '.' || c == ':' {
578            continue;
579        }
580        // `i` is a char boundary, so `bytes[i - 1]` is either the whole
581        // previous char (ASCII) or a UTF-8 continuation byte (>= 0x80),
582        // which can never equal `.` or `:`.
583        let prev = bytes[i - 1];
584        if prev == b'.' || prev == b':' {
585            out.push(&fqn[i..]);
586        }
587    }
588
589    out
590}
591
592#[cfg(test)]
593mod tests {
594    use super::*;
595
596    fn nid(n: usize) -> NodeId {
597        petgraph::graph::NodeIndex::new(n)
598    }
599
600    #[test]
601    fn insert_resolve() {
602        let mut table = SymbolTable::new();
603        let path = PathBuf::from("main.rs");
604        table.insert("main::foo".to_string(), nid(1), path.clone());
605
606        assert_eq!(table.resolve("main::foo"), Some(nid(1)));
607        assert_eq!(table.resolve("main::bar"), None);
608        assert_eq!(table.get_file_exports(&path).unwrap(), &vec!["main::foo"]);
609    }
610
611    #[test]
612    fn exact_match_from_any_context() {
613        let mut table = SymbolTable::new();
614        table.insert(
615            "pkg.utils.helper".to_string(),
616            nid(1),
617            PathBuf::from("src/utils.rs"),
618        );
619
620        let r = table.resolve_ref("pkg.utils.helper", Path::new("other/file.rs"));
621        assert_eq!(r, Resolution::Exact(nid(1)));
622        assert_eq!(r.confidence(), 1.0);
623    }
624
625    #[test]
626    fn unique_suffix_match() {
627        let mut table = SymbolTable::new();
628        table.insert(
629            "pkg.utils.helper".to_string(),
630            nid(1),
631            PathBuf::from("src/utils.rs"),
632        );
633
634        let r = table.resolve_ref("helper", Path::new("other/file.rs"));
635        assert_eq!(r, Resolution::UniqueSuffix(nid(1)));
636    }
637
638    #[test]
639    fn multi_segment_suffix_match() {
640        let mut table = SymbolTable::new();
641        table.insert(
642            "pkg.Utils.helper".to_string(),
643            nid(1),
644            PathBuf::from("src/utils.rs"),
645        );
646
647        let r = table.resolve_ref("Utils.helper", Path::new("other/file.rs"));
648        assert_eq!(r, Resolution::UniqueSuffix(nid(1)));
649    }
650
651    #[test]
652    fn suffix_must_be_segment_aligned() {
653        let mut table = SymbolTable::new();
654        table.insert(
655            "pkg.my_helper".to_string(),
656            nid(1),
657            PathBuf::from("src/utils.rs"),
658        );
659
660        // `helper` is a character-suffix of `my_helper` but not a segment.
661        assert_eq!(
662            table.resolve_ref("helper", Path::new("other/file.rs")),
663            Resolution::Unresolved
664        );
665    }
666
667    #[test]
668    fn ambiguous_reports_all_candidates() {
669        let mut table = SymbolTable::new();
670        table.insert(
671            "pkg.a.helper".to_string(),
672            nid(1),
673            PathBuf::from("src/a/mod.rs"),
674        );
675        table.insert(
676            "pkg.b.helper".to_string(),
677            nid(2),
678            PathBuf::from("src/b/mod.rs"),
679        );
680
681        let r = table.resolve_ref("helper", Path::new("src/c/caller.rs"));
682        assert_eq!(r, Resolution::Ambiguous(vec![nid(1), nid(2)]));
683        assert!(r.node().is_none());
684        assert_eq!(r.candidates().len(), 2);
685    }
686
687    #[test]
688    fn locality_preference_same_dir() {
689        let mut table = SymbolTable::new();
690        table.insert(
691            "pkg.a.helper".to_string(),
692            nid(1),
693            PathBuf::from("src/a/mod.rs"),
694        );
695        table.insert(
696            "pkg.b.helper".to_string(),
697            nid(2),
698            PathBuf::from("src/b/mod.rs"),
699        );
700
701        assert_eq!(
702            table.resolve_ref("helper", Path::new("src/a/caller.rs")),
703            Resolution::SameDir(nid(1))
704        );
705        assert_eq!(
706            table.resolve_ref("helper", Path::new("src/b/caller.rs")),
707            Resolution::SameDir(nid(2))
708        );
709    }
710
711    #[test]
712    fn same_file_beats_same_dir() {
713        let mut table = SymbolTable::new();
714        table.insert("A.run".to_string(), nid(1), PathBuf::from("src/a.rs"));
715        table.insert("B.run".to_string(), nid(2), PathBuf::from("src/b.rs"));
716
717        // Both live in `src/`, so same-dir cannot disambiguate — same-file must.
718        assert_eq!(
719            table.resolve_ref("run", Path::new("src/a.rs")),
720            Resolution::SameFile(nid(1))
721        );
722    }
723
724    #[test]
725    fn colliding_fqn_keeps_both_definitions() {
726        let mut table = SymbolTable::new();
727        table.insert("process".to_string(), nid(1), PathBuf::from("src/utils.py"));
728        table.insert(
729            "process".to_string(),
730            nid(2),
731            PathBuf::from("src/helpers.py"),
732        );
733
734        // The old table overwrote here, orphaning one node entirely.
735        assert_eq!(table.resolve_all("process"), vec![nid(2), nid(1)]);
736        assert_eq!(
737            table.resolve("process"),
738            None,
739            "collision is not unambiguous"
740        );
741
742        let r = table.resolve_ref("process", Path::new("src/other.py"));
743        assert_eq!(r, Resolution::Ambiguous(vec![nid(2), nid(1)]));
744    }
745
746    #[test]
747    fn duplicate_insert_is_idempotent() {
748        let mut table = SymbolTable::new();
749        table.insert("a.b".to_string(), nid(1), PathBuf::from("x.rs"));
750        table.insert("a.b".to_string(), nid(1), PathBuf::from("x.rs"));
751
752        assert_eq!(table.resolve_all("a.b"), vec![nid(1)]);
753        assert_eq!(
754            table
755                .get_file_exports(&PathBuf::from("x.rs"))
756                .unwrap()
757                .len(),
758            1
759        );
760    }
761
762    #[test]
763    fn resolution_confidence_is_ordered() {
764        assert!(Resolution::Exact(nid(0)).confidence() > Resolution::SameFile(nid(0)).confidence());
765        assert!(
766            Resolution::SameFile(nid(0)).confidence()
767                > Resolution::UniqueSuffix(nid(0)).confidence()
768        );
769        assert!(
770            Resolution::UniqueSuffix(nid(0)).confidence()
771                > Resolution::SameDir(nid(0)).confidence()
772        );
773        assert!(
774            Resolution::SameDir(nid(0)).confidence() > Resolution::Ambiguous(vec![]).confidence()
775        );
776        assert_eq!(Resolution::Unresolved.confidence(), 0.0);
777    }
778
779    #[test]
780    fn resolution_is_order_independent() {
781        // Same definitions inserted in opposite orders must resolve identically.
782        let mut a = SymbolTable::new();
783        a.insert("p.x.run".into(), nid(1), PathBuf::from("src/x/mod.rs"));
784        a.insert("p.y.run".into(), nid(2), PathBuf::from("src/y/mod.rs"));
785        a.insert("p.z.run".into(), nid(3), PathBuf::from("src/z/mod.rs"));
786
787        let mut b = SymbolTable::new();
788        b.insert("p.z.run".into(), nid(3), PathBuf::from("src/z/mod.rs"));
789        b.insert("p.y.run".into(), nid(2), PathBuf::from("src/y/mod.rs"));
790        b.insert("p.x.run".into(), nid(1), PathBuf::from("src/x/mod.rs"));
791
792        let ctx = Path::new("src/other/caller.rs");
793        assert_eq!(a.resolve_ref("run", ctx), b.resolve_ref("run", ctx));
794    }
795
796    #[test]
797    fn segment_suffixes_shapes() {
798        assert_eq!(segment_suffixes("a.b.c"), vec!["a.b.c", "b.c", "c"]);
799        assert_eq!(segment_suffixes("a::b::c"), vec!["a::b::c", "b::c", "c"]);
800        assert_eq!(segment_suffixes("solo"), vec!["solo"]);
801    }
802
803    #[test]
804    fn unicode_fqn_does_not_panic() {
805        let mut table = SymbolTable::new();
806        table.insert("módulo.función".to_string(), nid(1), PathBuf::from("a.py"));
807        assert_eq!(
808            table.resolve_ref("función", Path::new("b.py")),
809            Resolution::UniqueSuffix(nid(1))
810        );
811    }
812}
813
814#[cfg(test)]
815mod import_resolution_tests {
816    use super::*;
817
818    fn nid(i: usize) -> NodeId {
819        NodeId::new(i)
820    }
821
822    /// The exact shape that returned zero on the torture fixture: one bare name
823    /// defined in ten modules, called from an eleventh that imported one of them.
824    #[test]
825    fn import_breaks_a_tie_that_would_otherwise_be_ambiguous() {
826        let mut table = SymbolTable::default();
827        for layer in 0usize..10 {
828            table.insert(
829                format!("deep.l{layer}.m14.value_m14"),
830                nid(layer),
831                PathBuf::from(format!("/repo/deep/l{layer}/m14.py")),
832            );
833        }
834
835        let caller = Path::new("/repo/deep/l1/m03.py");
836
837        // Without imports the resolver does NOT report ambiguity — it picks the
838        // sibling sitting in the caller's own directory and reports SameDir at
839        // 0.55 confidence. That is the real defect: the edge is not dropped, it
840        // is confidently attached to the wrong module. Every caller in `l1/`
841        // resolves to `l1/m14.py`, which is why `l0/m14.py` ends up with no
842        // callers at all while an unrelated layer inherits its centrality.
843        let bare = table.resolve_ref("value_m14", caller);
844        assert_eq!(
845            bare,
846            Resolution::SameDir(nid(1)),
847            "expected the same-directory sibling to be mis-picked, got {bare:?}"
848        );
849
850        // With the import the caller actually wrote, exactly one survives.
851        let mut imports = HashMap::new();
852        imports.insert("value_m14".to_string(), "deep.l0.m14".to_string());
853        let resolved = table.resolve_ref_with_imports("value_m14", caller, Some(&imports));
854
855        match resolved {
856            Resolution::ViaImport(id) => {
857                assert_eq!(id, nid(0), "resolved to the wrong layer");
858            }
859            other => panic!("expected ViaImport(l0), got {other:?}"),
860        }
861    }
862
863    /// A definition in the caller's own file outranks an import of the same name.
864    #[test]
865    fn local_definition_still_shadows_an_import() {
866        let mut table = SymbolTable::default();
867        table.insert(
868            "a.mod.process".to_string(),
869            nid(0),
870            PathBuf::from("/repo/a/mod.py"),
871        );
872        table.insert(
873            "b.other.process".to_string(),
874            nid(1),
875            PathBuf::from("/repo/b/other.py"),
876        );
877
878        let caller = Path::new("/repo/a/mod.py");
879        let mut imports = HashMap::new();
880        imports.insert("process".to_string(), "b.other".to_string());
881
882        let r = table.resolve_ref_with_imports("process", caller, Some(&imports));
883        assert!(
884            matches!(r, Resolution::SameFile(_)),
885            "a local definition must win over an import, got {r:?}"
886        );
887    }
888
889    #[test]
890    fn module_paths_normalize_across_separator_styles() {
891        assert_eq!(normalize_module_path("deep/l0/m14.py"), "deep.l0.m14");
892        assert_eq!(normalize_module_path("crate::deep::l0::m14"), "deep.l0.m14");
893        assert_eq!(normalize_module_path("./deep/l0/m14"), "deep.l0.m14");
894    }
895
896    /// `l0.m1` must never satisfy a request for `l0.m14`.
897    #[test]
898    fn module_matching_is_segment_aligned() {
899        assert!(segment_aligned_contains("x.deep.l0.m14", "deep.l0.m14"));
900        assert!(!segment_aligned_contains("x.deep.l0.m140", "deep.l0.m14"));
901        assert!(!segment_aligned_contains("x.deep.l0.m1", "deep.l0.m14"));
902    }
903}