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 `name` imported from `module` under another name
330    /// (`from money import money_to_minor_units as to_minor`).
331    ///
332    /// The import says where the definition lives, so only definitions of
333    /// `name` in that module are candidates: the module's own file first
334    /// (`money.py`, or a package's `__init__.py` or `index.ts`), then anything
335    /// inside a package of that name. A same-named function elsewhere is not
336    /// the target. A module this project doesn't define (`numpy`) leaves the
337    /// call unresolved, unless a project file or directory, or a directory
338    /// above the project, has the module's name: modules are matched by name,
339    /// so it then binds there, as an unaliased import of the name does.
340    ///
341    /// A relative module (`./format`, `../route`, `.money`, `..core.money`)
342    /// names one place, read from the importing file's directory, so a
343    /// same-named file elsewhere (every `route.ts` in a Next.js app) is never a
344    /// candidate.
345    ///
346    /// An import binds a module-level name, so `name` is matched exactly and a
347    /// method (`Class.name`) is never a candidate. Neither is the importing
348    /// file: in a wrapper that keeps the imported function's name
349    /// (`from money import f as _f` then `def f(): _f()`), `_f` is money's.
350    pub fn resolve_imported(&self, name: &str, module: &str, context_file: &Path) -> Resolution {
351        self.resolve_in_module(name, module, context_file, true)
352    }
353
354    /// Resolves `name` in the module's own file only: `module.ts`, or a
355    /// package's `index.ts` or `__init__.py`, never another file inside the
356    /// package.
357    ///
358    /// For a name a file took from a value the module produced (a hook's or
359    /// factory's return value), not from its exports. A barrel that only
360    /// re-exports the hook says nothing about the other files under it.
361    pub fn resolve_in_module_file(
362        &self,
363        name: &str,
364        module: &str,
365        context_file: &Path,
366    ) -> Resolution {
367        self.resolve_in_module(name, module, context_file, false)
368    }
369
370    /// [`Self::resolve_imported`], and with `whole_package` false,
371    /// [`Self::resolve_in_module_file`].
372    fn resolve_in_module(
373        &self,
374        name: &str,
375        module: &str,
376        context_file: &Path,
377        whole_package: bool,
378    ) -> Resolution {
379        let family = language_family(context_file);
380        let defined: Vec<&SymbolEntry> = self
381            .by_fqn
382            .get(name)
383            .into_iter()
384            .flatten()
385            .filter(|e| same_family(family, &e.file) && e.file != context_file)
386            .collect();
387
388        if module.starts_with('.') {
389            let Some(target) = relative_module_path(module, context_file) else {
390                return Resolution::Unresolved;
391            };
392            let in_module: Vec<&SymbolEntry> = defined
393                .iter()
394                .copied()
395                .filter(|e| is_module_file(&e.file, &target))
396                .collect();
397            if !in_module.is_empty() {
398                return pick(in_module, context_file, Resolution::ViaImport);
399            }
400            if !whole_package || target.as_os_str().is_empty() {
401                return Resolution::Unresolved;
402            }
403            let in_package: Vec<&SymbolEntry> = defined
404                .into_iter()
405                .filter(|e| e.file.starts_with(&target))
406                .collect();
407            return pick(in_package, context_file, Resolution::ViaImport);
408        }
409
410        let wanted = normalize_module_path(module);
411        if wanted.is_empty() {
412            return Resolution::Unresolved;
413        }
414        let in_module: Vec<&SymbolEntry> = defined
415            .iter()
416            .copied()
417            .filter(|e| module_is(e, &wanted) || package_init_is(e, &wanted))
418            .collect();
419        if !in_module.is_empty() {
420            return pick(in_module, context_file, Resolution::ViaImport);
421        }
422        if !whole_package {
423            return Resolution::Unresolved;
424        }
425        let in_package: Vec<&SymbolEntry> = defined
426            .into_iter()
427            .filter(|e| entry_belongs_to_module(e, &wanted))
428            .collect();
429        pick(in_package, context_file, Resolution::ViaImport)
430    }
431
432    /// Resolves a `::` path reference: `jobs::enqueue`, `Provider::new`,
433    /// `crate::db::queries::get_user`, `my_app::app::create`.
434    ///
435    /// The path says where the definition lives, so it is matched on that
436    /// rather than on the bare name:
437    ///
438    /// - a path some parser recorded verbatim (C++ `ns::fn`) matches directly;
439    /// - a capitalised owner is a type, and `Type::new` is stored as `Type.new`;
440    /// - anything else is a module, matched against the definition's file
441    ///   (`jobs.rs`, `app/mod.rs`). Leading segments are dropped until one
442    ///   matches, so a crate-name prefix (`my_app::app::…`) works,
443    ///   and a definition re-exported from a submodule is found at lower
444    ///   confidence.
445    ///
446    /// A path into an external crate (`sqlx::query`, `std::fs::read`) matches
447    /// nothing here and stays unresolved, instead of binding to an unrelated
448    /// local function that shares the last name.
449    pub fn resolve_path(&self, path: &str, context_file: &Path) -> Resolution {
450        let family = language_family(context_file);
451        let visible = |e: &&SymbolEntry| same_family(family, &e.file);
452
453        let verbatim = self.entries_with_suffix(path, &visible);
454        if !verbatim.is_empty() {
455            return pick(verbatim, context_file, Resolution::Exact);
456        }
457
458        let segments: Vec<&str> = path
459            .split("::")
460            .map(str::trim)
461            .filter(|s| !s.is_empty() && !matches!(*s, "crate" | "self" | "super"))
462            .collect();
463        let Some((name, qualifiers)) = segments.split_last() else {
464            return Resolution::Unresolved;
465        };
466        let Some(owner) = qualifiers.last() else {
467            return self.resolve_ref(name, context_file);
468        };
469
470        if owner.starts_with(|c: char| c.is_uppercase()) {
471            let mut entries = self.entries_with_suffix(&format!("{owner}.{name}"), &visible);
472            entries.extend(self.entries_with_suffix(&format!("{owner}::{name}"), &visible));
473            // Nothing: an enum variant (`Error::NotFound(e)`) or an external type.
474            return pick(entries, context_file, Resolution::Exact);
475        }
476
477        // Free functions are stored under their bare name.
478        let named: Vec<&SymbolEntry> = self
479            .by_fqn
480            .get(*name)
481            .into_iter()
482            .flatten()
483            .filter(|e| visible(e))
484            .collect();
485        for start in 0..qualifiers.len() {
486            let wanted = normalize_module_path(&qualifiers[start..].join("."));
487            if wanted.is_empty() {
488                continue;
489            }
490            let in_module: Vec<&SymbolEntry> = named
491                .iter()
492                .copied()
493                .filter(|e| module_is(e, &wanted))
494                .collect();
495            if !in_module.is_empty() {
496                return pick(in_module, context_file, Resolution::ViaImport);
497            }
498            let re_exported: Vec<&SymbolEntry> = named
499                .iter()
500                .copied()
501                .filter(|e| entry_belongs_to_module(e, &wanted))
502                .collect();
503            if !re_exported.is_empty() {
504                return pick(re_exported, context_file, Resolution::UniqueSuffix);
505            }
506        }
507        Resolution::Unresolved
508    }
509
510    /// Entries whose FQN is `fqn` or ends with it on a segment boundary.
511    fn entries_with_suffix(
512        &self,
513        fqn: &str,
514        visible: &dyn Fn(&&SymbolEntry) -> bool,
515    ) -> Vec<&SymbolEntry> {
516        let mut fqns: Vec<&String> = self.by_suffix.get(fqn).into_iter().flatten().collect();
517        fqns.sort();
518        fqns.into_iter()
519            .filter_map(|f| self.by_fqn.get(f))
520            .flatten()
521            .filter(|e| visible(e))
522            .collect()
523    }
524
525    /// Back-compatible wrapper returning only a confidently-resolved node.
526    pub fn resolve_with_context(&self, name: &str, context_file: &Path) -> Option<NodeId> {
527        self.resolve_ref(name, context_file).node()
528    }
529
530    /// Number of distinct FQNs registered.
531    pub fn len(&self) -> usize {
532        self.by_fqn.len()
533    }
534
535    pub fn is_empty(&self) -> bool {
536        self.by_fqn.is_empty()
537    }
538}
539
540/// Reduce a module reference to dot-separated segments for comparison.
541///
542/// `deep.l0.m14`, `deep/l0/m14`, `./deep/l0/m14.py` and `crate::deep::l0::m14`
543/// all normalize to `deep.l0.m14`, so the same check works across the languages
544/// this engine parses without a per-language branch.
545fn normalize_module_path(raw: &str) -> String {
546    let cleaned = raw.replace("::", ".").replace(['/', '\\'], ".");
547    let cleaned = cleaned
548        .trim_start_matches('.')
549        .trim_end_matches(".py")
550        .trim_end_matches(".ts")
551        .trim_end_matches(".js")
552        .trim_end_matches(".rs")
553        .trim_end_matches(".go");
554    cleaned
555        .split('.')
556        .filter(|seg| {
557            !seg.is_empty()
558                && *seg != "index"
559                && *seg != "mod"
560                && *seg != "crate"
561                && *seg != "self"
562                && *seg != "super"
563        })
564        .collect::<Vec<_>>()
565        .join(".")
566}
567
568/// The path, without extension, that a relative import names, read from the
569/// importing file's directory: `./format` and `../route` in TypeScript and
570/// JavaScript, `.money` and `..core.money` in Python (one dot is the
571/// importing file's package, each further dot its parent). `None` when the
572/// import climbs out of the tree.
573fn relative_module_path(module: &str, context_file: &Path) -> Option<PathBuf> {
574    let mut path = context_file.parent()?.to_path_buf();
575    if module.contains('/') {
576        for segment in module.split('/') {
577            match segment {
578                "" | "." => {}
579                ".." => {
580                    if !path.pop() {
581                        return None;
582                    }
583                }
584                name => path.push(name),
585            }
586        }
587        // `./format.js` names `format.ts` under TypeScript's ESM resolution.
588        if matches!(
589            path.extension().and_then(|e| e.to_str()),
590            Some("js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "mts" | "cts")
591        ) {
592            path.set_extension("");
593        }
594        return Some(path);
595    }
596
597    let rest = module.strip_prefix('.')?;
598    let name = rest.trim_start_matches('.');
599    for _ in 0..rest.len() - name.len() {
600        if !path.pop() {
601            return None;
602        }
603    }
604    for segment in name.split('.').filter(|s| !s.is_empty()) {
605        path.push(segment);
606    }
607    Some(path)
608}
609
610/// Is `file` the module at `target`: `target.ts` / `target.py`, or the
611/// package's own `index` / `__init__` file?
612fn is_module_file(file: &Path, target: &Path) -> bool {
613    file.with_extension("").as_path() == target
614        || (file.parent() == Some(target)
615            && matches!(
616                file.file_stem().and_then(|s| s.to_str()),
617                Some("index" | "__init__")
618            ))
619}
620
621/// Picks among entries that all match the reference equally well: one is
622/// `unique`, otherwise the referencing file, then its directory, break ties.
623fn pick(
624    mut entries: Vec<&SymbolEntry>,
625    context_file: &Path,
626    unique: fn(NodeId) -> Resolution,
627) -> Resolution {
628    sort_entries(&mut entries);
629    entries.dedup_by_key(|e| e.id);
630    match entries.as_slice() {
631        [] => Resolution::Unresolved,
632        [only] => unique(only.id),
633        _ => {
634            let same_file: Vec<&&SymbolEntry> =
635                entries.iter().filter(|e| e.file == context_file).collect();
636            if same_file.len() == 1 {
637                return Resolution::SameFile(same_file[0].id);
638            }
639            let dir = context_file.parent();
640            let same_dir: Vec<&&SymbolEntry> =
641                entries.iter().filter(|e| e.file.parent() == dir).collect();
642            if same_dir.len() == 1 {
643                return Resolution::SameDir(same_dir[0].id);
644            }
645            Resolution::Ambiguous(entries.into_iter().map(|e| e.id).collect())
646        }
647    }
648}
649
650/// Is this symbol defined in exactly `module` (`jobs.rs`, `jobs/mod.rs`)?
651fn module_is(entry: &SymbolEntry, module: &str) -> bool {
652    let file_norm = normalize_module_path(&entry.file.to_string_lossy());
653    file_norm == module || file_norm.ends_with(&format!(".{module}"))
654}
655
656/// Is this symbol defined in the package `module`'s own `__init__.py`?
657///
658/// `module_is` already matches `pkg/index.ts` and `pkg/mod.rs`, because
659/// `normalize_module_path` drops `index` and `mod`, but `pkg/__init__.py`
660/// normalizes to `pkg.__init__`. The package directory is compared the way
661/// `module_is` compares a file. Only `__init__.py` counts: an `__init__.pyi`
662/// is a type stub, not the module that runs, and the implementation it
663/// describes usually lives in a submodule.
664fn package_init_is(entry: &SymbolEntry, module: &str) -> bool {
665    entry.file.file_name().and_then(|s| s.to_str()) == Some("__init__.py")
666        && entry.file.parent().is_some_and(|dir| {
667            let dir_norm = normalize_module_path(&dir.to_string_lossy());
668            dir_norm == module || dir_norm.ends_with(&format!(".{module}"))
669        })
670}
671
672/// Source languages that can call each other directly. Calls are never
673/// resolved across families; a name shared by a Rust and a TypeScript
674/// definition is two symbols, not one.
675fn language_family(path: &Path) -> Option<&'static str> {
676    let ext = path.extension()?.to_str()?.to_ascii_lowercase();
677    Some(match ext.as_str() {
678        "rs" => "rust",
679        "ts" | "tsx" | "mts" | "cts" | "js" | "jsx" | "mjs" | "cjs" | "vue" | "svelte" => "js",
680        "py" | "pyi" => "python",
681        "go" => "go",
682        "java" | "kt" | "kts" | "scala" => "jvm",
683        "c" | "h" | "cc" | "cpp" | "cxx" | "hh" | "hpp" | "hxx" | "m" | "mm" => "c",
684        "cs" => "csharp",
685        "rb" => "ruby",
686        "php" | "phtml" => "php",
687        "swift" => "swift",
688        "dart" => "dart",
689        "sh" | "bash" | "zsh" => "shell",
690        _ => return None,
691    })
692}
693
694/// Unknown extensions on either side don't filter anything out.
695/// Whether two files are in the same language family (an unknown extension
696/// matches anything).
697pub(crate) fn same_language(a: &Path, b: &Path) -> bool {
698    same_family(language_family(a), b)
699}
700
701fn same_family(family: Option<&'static str>, file: &Path) -> bool {
702    match (family, language_family(file)) {
703        (Some(a), Some(b)) => a == b,
704        _ => true,
705    }
706}
707
708/// Did this symbol come from `module`?
709///
710/// A `SymbolEntry` carries only its id and its file, so the file path is the
711/// module identity. Requires a segment-aligned match, so a reference to
712/// `l0.m14` is never satisfied by `l0.m1`.
713fn entry_belongs_to_module(entry: &SymbolEntry, module: &str) -> bool {
714    let file_norm = normalize_module_path(&entry.file.to_string_lossy());
715    segment_aligned_contains(&file_norm, module)
716}
717
718/// True when `needle` appears in `haystack` on segment boundaries.
719fn segment_aligned_contains(haystack: &str, needle: &str) -> bool {
720    if haystack == needle {
721        return true;
722    }
723    haystack.starts_with(&format!("{needle}."))
724        || haystack.ends_with(&format!(".{needle}"))
725        || haystack.contains(&format!(".{needle}."))
726}
727
728/// Sorts entries by `(file, node index)` for a total, parse-order-independent order.
729fn sort_entries(entries: &mut [&SymbolEntry]) {
730    entries.sort_by(|a, b| {
731        a.file
732            .cmp(&b.file)
733            .then_with(|| a.id.index().cmp(&b.id.index()))
734    });
735}
736
737/// Every segment-aligned suffix of an FQN, including the FQN itself.
738///
739/// `a.b.c` → `["a.b.c", "b.c", "c"]`; `a::b::c` → `["a::b::c", "b::c", "c"]`.
740///
741/// Only positions immediately after a `.` or `:` qualify, so `helper` never
742/// matches the tail of `my_helper`. A suffix that would itself start with a
743/// separator (the middle of Rust's `::`) is skipped.
744fn segment_suffixes(fqn: &str) -> Vec<&str> {
745    let mut out = vec![fqn];
746    let bytes = fqn.as_bytes();
747
748    for (i, c) in fqn.char_indices().skip(1) {
749        if c == '.' || c == ':' {
750            continue;
751        }
752        // `i` is a char boundary, so `bytes[i - 1]` is either the whole
753        // previous char (ASCII) or a UTF-8 continuation byte (>= 0x80),
754        // which can never equal `.` or `:`.
755        let prev = bytes[i - 1];
756        if prev == b'.' || prev == b':' {
757            out.push(&fqn[i..]);
758        }
759    }
760
761    out
762}
763
764#[cfg(test)]
765mod tests {
766    use super::*;
767
768    fn nid(n: usize) -> NodeId {
769        petgraph::graph::NodeIndex::new(n)
770    }
771
772    #[test]
773    fn insert_resolve() {
774        let mut table = SymbolTable::new();
775        let path = PathBuf::from("main.rs");
776        table.insert("main::foo".to_string(), nid(1), path.clone());
777
778        assert_eq!(table.resolve("main::foo"), Some(nid(1)));
779        assert_eq!(table.resolve("main::bar"), None);
780        assert_eq!(table.get_file_exports(&path).unwrap(), &vec!["main::foo"]);
781    }
782
783    #[test]
784    fn exact_match_from_any_context() {
785        let mut table = SymbolTable::new();
786        table.insert(
787            "pkg.utils.helper".to_string(),
788            nid(1),
789            PathBuf::from("src/utils.rs"),
790        );
791
792        let r = table.resolve_ref("pkg.utils.helper", Path::new("other/file.rs"));
793        assert_eq!(r, Resolution::Exact(nid(1)));
794        assert_eq!(r.confidence(), 1.0);
795    }
796
797    #[test]
798    fn unique_suffix_match() {
799        let mut table = SymbolTable::new();
800        table.insert(
801            "pkg.utils.helper".to_string(),
802            nid(1),
803            PathBuf::from("src/utils.rs"),
804        );
805
806        let r = table.resolve_ref("helper", Path::new("other/file.rs"));
807        assert_eq!(r, Resolution::UniqueSuffix(nid(1)));
808    }
809
810    #[test]
811    fn multi_segment_suffix_match() {
812        let mut table = SymbolTable::new();
813        table.insert(
814            "pkg.Utils.helper".to_string(),
815            nid(1),
816            PathBuf::from("src/utils.rs"),
817        );
818
819        let r = table.resolve_ref("Utils.helper", Path::new("other/file.rs"));
820        assert_eq!(r, Resolution::UniqueSuffix(nid(1)));
821    }
822
823    #[test]
824    fn suffix_must_be_segment_aligned() {
825        let mut table = SymbolTable::new();
826        table.insert(
827            "pkg.my_helper".to_string(),
828            nid(1),
829            PathBuf::from("src/utils.rs"),
830        );
831
832        // `helper` is a character-suffix of `my_helper` but not a segment.
833        assert_eq!(
834            table.resolve_ref("helper", Path::new("other/file.rs")),
835            Resolution::Unresolved
836        );
837    }
838
839    #[test]
840    fn ambiguous_reports_all_candidates() {
841        let mut table = SymbolTable::new();
842        table.insert(
843            "pkg.a.helper".to_string(),
844            nid(1),
845            PathBuf::from("src/a/mod.rs"),
846        );
847        table.insert(
848            "pkg.b.helper".to_string(),
849            nid(2),
850            PathBuf::from("src/b/mod.rs"),
851        );
852
853        let r = table.resolve_ref("helper", Path::new("src/c/caller.rs"));
854        assert_eq!(r, Resolution::Ambiguous(vec![nid(1), nid(2)]));
855        assert!(r.node().is_none());
856        assert_eq!(r.candidates().len(), 2);
857    }
858
859    #[test]
860    fn locality_preference_same_dir() {
861        let mut table = SymbolTable::new();
862        table.insert(
863            "pkg.a.helper".to_string(),
864            nid(1),
865            PathBuf::from("src/a/mod.rs"),
866        );
867        table.insert(
868            "pkg.b.helper".to_string(),
869            nid(2),
870            PathBuf::from("src/b/mod.rs"),
871        );
872
873        assert_eq!(
874            table.resolve_ref("helper", Path::new("src/a/caller.rs")),
875            Resolution::SameDir(nid(1))
876        );
877        assert_eq!(
878            table.resolve_ref("helper", Path::new("src/b/caller.rs")),
879            Resolution::SameDir(nid(2))
880        );
881    }
882
883    #[test]
884    fn same_file_beats_same_dir() {
885        let mut table = SymbolTable::new();
886        table.insert("A.run".to_string(), nid(1), PathBuf::from("src/a.rs"));
887        table.insert("B.run".to_string(), nid(2), PathBuf::from("src/b.rs"));
888
889        // Both live in `src/`, so same-dir cannot disambiguate — same-file must.
890        assert_eq!(
891            table.resolve_ref("run", Path::new("src/a.rs")),
892            Resolution::SameFile(nid(1))
893        );
894    }
895
896    #[test]
897    fn colliding_fqn_keeps_both_definitions() {
898        let mut table = SymbolTable::new();
899        table.insert("process".to_string(), nid(1), PathBuf::from("src/utils.py"));
900        table.insert(
901            "process".to_string(),
902            nid(2),
903            PathBuf::from("src/helpers.py"),
904        );
905
906        // The old table overwrote here, orphaning one node entirely.
907        assert_eq!(table.resolve_all("process"), vec![nid(2), nid(1)]);
908        assert_eq!(
909            table.resolve("process"),
910            None,
911            "collision is not unambiguous"
912        );
913
914        let r = table.resolve_ref("process", Path::new("src/other.py"));
915        assert_eq!(r, Resolution::Ambiguous(vec![nid(2), nid(1)]));
916    }
917
918    #[test]
919    fn duplicate_insert_is_idempotent() {
920        let mut table = SymbolTable::new();
921        table.insert("a.b".to_string(), nid(1), PathBuf::from("x.rs"));
922        table.insert("a.b".to_string(), nid(1), PathBuf::from("x.rs"));
923
924        assert_eq!(table.resolve_all("a.b"), vec![nid(1)]);
925        assert_eq!(
926            table
927                .get_file_exports(&PathBuf::from("x.rs"))
928                .unwrap()
929                .len(),
930            1
931        );
932    }
933
934    #[test]
935    fn resolution_confidence_is_ordered() {
936        assert!(Resolution::Exact(nid(0)).confidence() > Resolution::SameFile(nid(0)).confidence());
937        assert!(
938            Resolution::SameFile(nid(0)).confidence()
939                > Resolution::UniqueSuffix(nid(0)).confidence()
940        );
941        assert!(
942            Resolution::UniqueSuffix(nid(0)).confidence()
943                > Resolution::SameDir(nid(0)).confidence()
944        );
945        assert!(
946            Resolution::SameDir(nid(0)).confidence() > Resolution::Ambiguous(vec![]).confidence()
947        );
948        assert_eq!(Resolution::Unresolved.confidence(), 0.0);
949    }
950
951    #[test]
952    fn resolution_is_order_independent() {
953        // Same definitions inserted in opposite orders must resolve identically.
954        let mut a = SymbolTable::new();
955        a.insert("p.x.run".into(), nid(1), PathBuf::from("src/x/mod.rs"));
956        a.insert("p.y.run".into(), nid(2), PathBuf::from("src/y/mod.rs"));
957        a.insert("p.z.run".into(), nid(3), PathBuf::from("src/z/mod.rs"));
958
959        let mut b = SymbolTable::new();
960        b.insert("p.z.run".into(), nid(3), PathBuf::from("src/z/mod.rs"));
961        b.insert("p.y.run".into(), nid(2), PathBuf::from("src/y/mod.rs"));
962        b.insert("p.x.run".into(), nid(1), PathBuf::from("src/x/mod.rs"));
963
964        let ctx = Path::new("src/other/caller.rs");
965        assert_eq!(a.resolve_ref("run", ctx), b.resolve_ref("run", ctx));
966    }
967
968    #[test]
969    fn segment_suffixes_shapes() {
970        assert_eq!(segment_suffixes("a.b.c"), vec!["a.b.c", "b.c", "c"]);
971        assert_eq!(segment_suffixes("a::b::c"), vec!["a::b::c", "b::c", "c"]);
972        assert_eq!(segment_suffixes("solo"), vec!["solo"]);
973    }
974
975    #[test]
976    fn unicode_fqn_does_not_panic() {
977        let mut table = SymbolTable::new();
978        table.insert("módulo.función".to_string(), nid(1), PathBuf::from("a.py"));
979        assert_eq!(
980            table.resolve_ref("función", Path::new("b.py")),
981            Resolution::UniqueSuffix(nid(1))
982        );
983    }
984}
985
986#[cfg(test)]
987mod import_resolution_tests {
988    use super::*;
989
990    fn nid(i: usize) -> NodeId {
991        NodeId::new(i)
992    }
993
994    /// The exact shape that returned zero on the torture fixture: one bare name
995    /// defined in ten modules, called from an eleventh that imported one of them.
996    #[test]
997    fn import_breaks_a_tie_that_would_otherwise_be_ambiguous() {
998        let mut table = SymbolTable::default();
999        for layer in 0usize..10 {
1000            table.insert(
1001                format!("deep.l{layer}.m14.value_m14"),
1002                nid(layer),
1003                PathBuf::from(format!("/repo/deep/l{layer}/m14.py")),
1004            );
1005        }
1006
1007        let caller = Path::new("/repo/deep/l1/m03.py");
1008
1009        // Without imports the resolver does NOT report ambiguity — it picks the
1010        // sibling sitting in the caller's own directory and reports SameDir at
1011        // 0.55 confidence. That is the real defect: the edge is not dropped, it
1012        // is confidently attached to the wrong module. Every caller in `l1/`
1013        // resolves to `l1/m14.py`, which is why `l0/m14.py` ends up with no
1014        // callers at all while an unrelated layer inherits its centrality.
1015        let bare = table.resolve_ref("value_m14", caller);
1016        assert_eq!(
1017            bare,
1018            Resolution::SameDir(nid(1)),
1019            "expected the same-directory sibling to be mis-picked, got {bare:?}"
1020        );
1021
1022        // With the import the caller actually wrote, exactly one survives.
1023        let mut imports = HashMap::new();
1024        imports.insert("value_m14".to_string(), "deep.l0.m14".to_string());
1025        let resolved = table.resolve_ref_with_imports("value_m14", caller, Some(&imports));
1026
1027        match resolved {
1028            Resolution::ViaImport(id) => {
1029                assert_eq!(id, nid(0), "resolved to the wrong layer");
1030            }
1031            other => panic!("expected ViaImport(l0), got {other:?}"),
1032        }
1033    }
1034
1035    /// A definition in the caller's own file outranks an import of the same name.
1036    #[test]
1037    fn local_definition_still_shadows_an_import() {
1038        let mut table = SymbolTable::default();
1039        table.insert(
1040            "a.mod.process".to_string(),
1041            nid(0),
1042            PathBuf::from("/repo/a/mod.py"),
1043        );
1044        table.insert(
1045            "b.other.process".to_string(),
1046            nid(1),
1047            PathBuf::from("/repo/b/other.py"),
1048        );
1049
1050        let caller = Path::new("/repo/a/mod.py");
1051        let mut imports = HashMap::new();
1052        imports.insert("process".to_string(), "b.other".to_string());
1053
1054        let r = table.resolve_ref_with_imports("process", caller, Some(&imports));
1055        assert!(
1056            matches!(r, Resolution::SameFile(_)),
1057            "a local definition must win over an import, got {r:?}"
1058        );
1059    }
1060
1061    #[test]
1062    fn module_paths_normalize_across_separator_styles() {
1063        assert_eq!(normalize_module_path("deep/l0/m14.py"), "deep.l0.m14");
1064        assert_eq!(normalize_module_path("crate::deep::l0::m14"), "deep.l0.m14");
1065        assert_eq!(normalize_module_path("./deep/l0/m14"), "deep.l0.m14");
1066    }
1067
1068    /// `l0.m1` must never satisfy a request for `l0.m14`.
1069    #[test]
1070    fn module_matching_is_segment_aligned() {
1071        assert!(segment_aligned_contains("x.deep.l0.m14", "deep.l0.m14"));
1072        assert!(!segment_aligned_contains("x.deep.l0.m140", "deep.l0.m14"));
1073        assert!(!segment_aligned_contains("x.deep.l0.m1", "deep.l0.m14"));
1074    }
1075
1076    fn money_table() -> SymbolTable {
1077        let mut table = SymbolTable::default();
1078        table.insert(
1079            "convert".to_string(),
1080            nid(0),
1081            PathBuf::from("billing/money.py"),
1082        );
1083        table.insert(
1084            "convert".to_string(),
1085            nid(1),
1086            PathBuf::from("legacy/money.py"),
1087        );
1088        table.insert(
1089            "convert".to_string(),
1090            nid(2),
1091            PathBuf::from("payments/rates/convert_impl.py"),
1092        );
1093        table.insert(
1094            "Ledger.convert".to_string(),
1095            nid(3),
1096            PathBuf::from("ledger.py"),
1097        );
1098        table
1099    }
1100
1101    #[test]
1102    fn an_aliased_import_resolves_in_the_named_module_only() {
1103        let table = money_table();
1104        let caller = Path::new("app/orders.py");
1105        assert_eq!(
1106            table.resolve_imported("convert", "billing.money", caller),
1107            Resolution::ViaImport(nid(0))
1108        );
1109        assert_eq!(
1110            table.resolve_imported("convert", "legacy.money", caller),
1111            Resolution::ViaImport(nid(1))
1112        );
1113    }
1114
1115    /// `from payments import convert as c`, where `payments/__init__.py`
1116    /// re-exports it from a submodule.
1117    #[test]
1118    fn an_aliased_import_from_a_package_reaches_its_submodule() {
1119        let table = money_table();
1120        assert_eq!(
1121            table.resolve_imported("convert", "payments", Path::new("app/orders.py")),
1122            Resolution::ViaImport(nid(2))
1123        );
1124    }
1125
1126    /// `pkg/__init__.py` is `pkg` itself, so it outranks a submodule's
1127    /// definition of the same name. `arbor index` stores absolute paths, so
1128    /// both path shapes are checked, and a package whose name only ends like
1129    /// the module's (`mypkg`) is not `pkg`.
1130    #[test]
1131    fn an_aliased_import_from_a_package_prefers_its_init() {
1132        for root in ["", "/repo/"] {
1133            let mut table = SymbolTable::default();
1134            for (i, file) in ["pkg/__init__.py", "pkg/sub.py", "mypkg/__init__.py"]
1135                .iter()
1136                .enumerate()
1137            {
1138                table.insert(
1139                    "f".to_string(),
1140                    nid(i),
1141                    PathBuf::from(format!("{root}{file}")),
1142                );
1143            }
1144            let caller = PathBuf::from(format!("{root}app.py"));
1145            assert_eq!(
1146                table.resolve_imported("f", "pkg", &caller),
1147                Resolution::ViaImport(nid(0)),
1148                "root {root:?}"
1149            );
1150
1151            table.insert(
1152                "f".to_string(),
1153                nid(3),
1154                PathBuf::from(format!("{root}shop/cart/__init__.py")),
1155            );
1156            table.insert(
1157                "f".to_string(),
1158                nid(4),
1159                PathBuf::from(format!("{root}shop/cart/items.py")),
1160            );
1161            assert_eq!(
1162                table.resolve_imported("f", "shop.cart", &caller),
1163                Resolution::ViaImport(nid(3)),
1164                "root {root:?}: a dotted package's own __init__"
1165            );
1166        }
1167    }
1168
1169    /// `resolve_in_module_file` stops at the module's own file. A barrel
1170    /// (`index.ts`) that doesn't define the name leaves it unresolved, where
1171    /// an import reaches into the package.
1172    #[test]
1173    fn a_module_file_lookup_never_reaches_into_the_package() {
1174        let mut table = SymbolTable::default();
1175        table.insert(
1176            "logout".to_string(),
1177            nid(0),
1178            PathBuf::from("src/app/admin/session.ts"),
1179        );
1180        table.insert(
1181            "useApp".to_string(),
1182            nid(1),
1183            PathBuf::from("src/app/index.ts"),
1184        );
1185        let caller = Path::new("src/app/settings/Account.tsx");
1186        assert_eq!(
1187            table.resolve_imported("logout", "..", caller),
1188            Resolution::ViaImport(nid(0))
1189        );
1190        assert_eq!(
1191            table.resolve_in_module_file("logout", "..", caller),
1192            Resolution::Unresolved
1193        );
1194        assert_eq!(
1195            table.resolve_in_module_file("useApp", "..", caller),
1196            Resolution::ViaImport(nid(1))
1197        );
1198    }
1199
1200    /// Known limit: `flask` is not part of this project, but a checkout under
1201    /// `/home/u/flask/` has a directory named `flask`, so the module matches
1202    /// it, as it does for an unaliased import.
1203    #[test]
1204    fn an_external_module_named_like_a_directory_above_the_project_matches_it() {
1205        let mut table = SymbolTable::default();
1206        table.insert(
1207            "render_template".to_string(),
1208            nid(0),
1209            PathBuf::from("/home/u/flask/app/views.py"),
1210        );
1211        assert_eq!(
1212            table.resolve_imported(
1213                "render_template",
1214                "flask",
1215                Path::new("/home/u/flask/app/main.py")
1216            ),
1217            Resolution::ViaImport(nid(0))
1218        );
1219    }
1220
1221    #[test]
1222    fn an_aliased_import_from_an_external_module_is_unresolved() {
1223        let table = money_table();
1224        assert_eq!(
1225            table.resolve_imported("convert", "numpy", Path::new("app/orders.py")),
1226            Resolution::Unresolved
1227        );
1228    }
1229
1230    /// Relative Python modules are read from the importing file's package.
1231    /// The importing file itself is never the import.
1232    #[test]
1233    fn a_relative_python_alias_is_read_from_the_importing_package() {
1234        let table = money_table();
1235        assert_eq!(
1236            table.resolve_imported("convert", ".", Path::new("legacy/orders.py")),
1237            Resolution::ViaImport(nid(1))
1238        );
1239        assert_eq!(
1240            table.resolve_imported("convert", ".money", Path::new("billing/orders.py")),
1241            Resolution::ViaImport(nid(0))
1242        );
1243        assert_eq!(
1244            table.resolve_imported("convert", "..money", Path::new("billing/api/orders.py")),
1245            Resolution::ViaImport(nid(0))
1246        );
1247        assert_eq!(
1248            table.resolve_imported("convert", ".", Path::new("legacy/money.py")),
1249            Resolution::Unresolved
1250        );
1251        // `shop/money.py` does not exist; `billing` and `legacy` are not it.
1252        assert_eq!(
1253            table.resolve_imported("convert", ".money", Path::new("shop/orders.py")),
1254            Resolution::Unresolved
1255        );
1256    }
1257
1258    #[test]
1259    fn a_relative_typescript_alias_is_read_from_the_importing_directory() {
1260        let mut table = SymbolTable::default();
1261        table.insert(
1262            "convert".to_string(),
1263            nid(0),
1264            PathBuf::from("src/format.ts"),
1265        );
1266        table.insert(
1267            "convert".to_string(),
1268            nid(1),
1269            PathBuf::from("lib/format.ts"),
1270        );
1271        table.insert(
1272            "convert".to_string(),
1273            nid(2),
1274            PathBuf::from("src/utils/index.ts"),
1275        );
1276        let caller = Path::new("src/app.ts");
1277        assert_eq!(
1278            table.resolve_imported("convert", "./format", caller),
1279            Resolution::ViaImport(nid(0))
1280        );
1281        assert_eq!(
1282            table.resolve_imported("convert", "../lib/format.js", caller),
1283            Resolution::ViaImport(nid(1))
1284        );
1285        assert_eq!(
1286            table.resolve_imported("convert", "./utils", caller),
1287            Resolution::ViaImport(nid(2))
1288        );
1289        assert_eq!(
1290            table.resolve_imported("convert", "./missing", caller),
1291            Resolution::Unresolved
1292        );
1293        assert_eq!(
1294            table.resolve_imported("convert", "../../../format", caller),
1295            Resolution::Unresolved
1296        );
1297    }
1298
1299    #[test]
1300    fn methods_and_other_languages_are_not_imported_names() {
1301        let mut table = SymbolTable::default();
1302        table.insert(
1303            "Ledger.convert".to_string(),
1304            nid(0),
1305            PathBuf::from("money.py"),
1306        );
1307        table.insert("convert".to_string(), nid(1), PathBuf::from("money.ts"));
1308        assert_eq!(
1309            table.resolve_imported("convert", "money", Path::new("orders.py")),
1310            Resolution::Unresolved
1311        );
1312    }
1313}