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; exactly one lives in the referencing file's directory.
46    SameDir(NodeId),
47    /// Several equally-plausible candidates, sorted deterministically.
48    Ambiguous(Vec<NodeId>),
49    /// No definition in this repository (external or stdlib).
50    Unresolved,
51}
52
53impl Resolution {
54    /// Confidence to stamp on an edge created from this resolution.
55    ///
56    /// `Ambiguous` is deliberately low rather than zero: the reference does
57    /// point at *something* in the repo, we just cannot say which. Consumers
58    /// that need certainty should filter on this value.
59    pub fn confidence(&self) -> f32 {
60        match self {
61            Resolution::Exact(_) => 1.0,
62            Resolution::SameFile(_) => 0.95,
63            Resolution::UniqueSuffix(_) => 0.80,
64            Resolution::SameDir(_) => 0.55,
65            Resolution::Ambiguous(_) => 0.25,
66            Resolution::Unresolved => 0.0,
67        }
68    }
69
70    /// The single resolved node, if this resolution picked one.
71    pub fn node(&self) -> Option<NodeId> {
72        match self {
73            Resolution::Exact(id)
74            | Resolution::SameFile(id)
75            | Resolution::UniqueSuffix(id)
76            | Resolution::SameDir(id) => Some(*id),
77            Resolution::Ambiguous(_) | Resolution::Unresolved => None,
78        }
79    }
80
81    /// Every candidate this resolution considered plausible.
82    pub fn candidates(&self) -> Vec<NodeId> {
83        match self {
84            Resolution::Ambiguous(ids) => ids.clone(),
85            other => other.node().into_iter().collect(),
86        }
87    }
88
89    pub fn is_resolved(&self) -> bool {
90        !matches!(self, Resolution::Unresolved)
91    }
92}
93
94/// A global symbol table for resolving cross-file references.
95#[derive(Debug, Default, Clone)]
96pub struct SymbolTable {
97    /// FQN → every node defining it.
98    by_fqn: HashMap<String, Vec<SymbolEntry>>,
99
100    /// Segment-aligned suffix → FQNs ending with it.
101    ///
102    /// `pkg.Utils.helper` is indexed under `helper`, `Utils.helper`, and
103    /// `pkg.Utils.helper`, so resolving a bare `helper` is an O(1) lookup
104    /// instead of a scan over every FQN in the repository.
105    by_suffix: HashMap<String, Vec<String>>,
106
107    /// File → FQNs it defines.
108    exports_by_file: HashMap<PathBuf, Vec<String>>,
109}
110
111impl SymbolTable {
112    pub fn new() -> Self {
113        Self::default()
114    }
115
116    /// Registers a symbol definition.
117    ///
118    /// Repeated FQNs accumulate instead of overwriting.
119    pub fn insert(&mut self, fqn: String, id: NodeId, file: PathBuf) {
120        let entry = SymbolEntry {
121            id,
122            file: file.clone(),
123        };
124
125        let entries = self.by_fqn.entry(fqn.clone()).or_default();
126        // Guard against the same definition being indexed twice (incremental
127        // re-parse of an unchanged file).
128        if !entries.contains(&entry) {
129            entries.push(entry);
130        }
131
132        for suffix in segment_suffixes(&fqn) {
133            let fqns = self.by_suffix.entry(suffix.to_string()).or_default();
134            if !fqns.iter().any(|f| f == &fqn) {
135                fqns.push(fqn.clone());
136            }
137        }
138
139        let exports = self.exports_by_file.entry(file).or_default();
140        if !exports.contains(&fqn) {
141            exports.push(fqn);
142        }
143    }
144
145    /// Resolves an exact FQN, but only when the definition is unambiguous.
146    ///
147    /// Returns `None` for a colliding FQN so the caller can fall back to
148    /// context-aware resolution rather than picking a definition at random.
149    pub fn resolve(&self, fqn: &str) -> Option<NodeId> {
150        match self.by_fqn.get(fqn) {
151            Some(entries) if entries.len() == 1 => Some(entries[0].id),
152            _ => None,
153        }
154    }
155
156    /// All nodes defining this exact FQN, in deterministic order.
157    pub fn resolve_all(&self, fqn: &str) -> Vec<NodeId> {
158        let Some(entries) = self.by_fqn.get(fqn) else {
159            return Vec::new();
160        };
161        let mut entries: Vec<&SymbolEntry> = entries.iter().collect();
162        sort_entries(&mut entries);
163        entries.into_iter().map(|e| e.id).collect()
164    }
165
166    /// Returns all symbols exported by a file.
167    pub fn get_file_exports(&self, file: &PathBuf) -> Option<&Vec<String>> {
168        self.exports_by_file.get(file)
169    }
170
171    pub fn clear(&mut self) {
172        self.by_fqn.clear();
173        self.by_suffix.clear();
174        self.exports_by_file.clear();
175    }
176
177    /// Resolves a reference, preferring locality and reporting ambiguity.
178    ///
179    /// Order:
180    ///   1. Exact FQN, unique → `Exact`
181    ///   2. Candidate gathering: exact-FQN entries plus every segment-aligned
182    ///      suffix match, deduplicated and sorted
183    ///   3. Single candidate → `Exact` / `UniqueSuffix`
184    ///   4. Exactly one candidate in the referencing file → `SameFile`
185    ///   5. Exactly one candidate in the referencing directory → `SameDir`
186    ///   6. Otherwise → `Ambiguous`
187    pub fn resolve_ref(&self, name: &str, context_file: &Path) -> Resolution {
188        let exact = self.by_fqn.get(name);
189        if let Some(entries) = exact {
190            if entries.len() == 1 {
191                return Resolution::Exact(entries[0].id);
192            }
193        }
194        let had_exact = exact.is_some();
195
196        let mut candidates: Vec<&SymbolEntry> = Vec::new();
197        let mut seen: Vec<NodeId> = Vec::new();
198
199        if let Some(entries) = exact {
200            for e in entries {
201                if !seen.contains(&e.id) {
202                    seen.push(e.id);
203                    candidates.push(e);
204                }
205            }
206        }
207
208        if let Some(fqns) = self.by_suffix.get(name) {
209            // `by_suffix` values are insertion-ordered Vecs, but sort the FQN
210            // list anyway so candidate order never depends on parse order.
211            let mut fqns: Vec<&String> = fqns.iter().collect();
212            fqns.sort();
213            for fqn in fqns {
214                if let Some(entries) = self.by_fqn.get(fqn) {
215                    for e in entries {
216                        if !seen.contains(&e.id) {
217                            seen.push(e.id);
218                            candidates.push(e);
219                        }
220                    }
221                }
222            }
223        }
224
225        if candidates.is_empty() {
226            return Resolution::Unresolved;
227        }
228
229        sort_entries(&mut candidates);
230
231        if candidates.len() == 1 {
232            return if had_exact {
233                Resolution::Exact(candidates[0].id)
234            } else {
235                Resolution::UniqueSuffix(candidates[0].id)
236            };
237        }
238
239        let same_file: Vec<&SymbolEntry> = candidates
240            .iter()
241            .copied()
242            .filter(|e| e.file == context_file)
243            .collect();
244        if same_file.len() == 1 {
245            return Resolution::SameFile(same_file[0].id);
246        }
247
248        let context_dir = context_file.parent();
249        let same_dir: Vec<&SymbolEntry> = candidates
250            .iter()
251            .copied()
252            .filter(|e| e.file.parent() == context_dir)
253            .collect();
254        if same_dir.len() == 1 {
255            return Resolution::SameDir(same_dir[0].id);
256        }
257
258        Resolution::Ambiguous(candidates.into_iter().map(|e| e.id).collect())
259    }
260
261    /// Back-compatible wrapper returning only a confidently-resolved node.
262    pub fn resolve_with_context(&self, name: &str, context_file: &Path) -> Option<NodeId> {
263        self.resolve_ref(name, context_file).node()
264    }
265
266    /// Number of distinct FQNs registered.
267    pub fn len(&self) -> usize {
268        self.by_fqn.len()
269    }
270
271    pub fn is_empty(&self) -> bool {
272        self.by_fqn.is_empty()
273    }
274}
275
276/// Sorts entries by `(file, node index)` for a total, parse-order-independent order.
277fn sort_entries(entries: &mut [&SymbolEntry]) {
278    entries.sort_by(|a, b| {
279        a.file
280            .cmp(&b.file)
281            .then_with(|| a.id.index().cmp(&b.id.index()))
282    });
283}
284
285/// Every segment-aligned suffix of an FQN, including the FQN itself.
286///
287/// `a.b.c` → `["a.b.c", "b.c", "c"]`; `a::b::c` → `["a::b::c", "b::c", "c"]`.
288///
289/// Only positions immediately after a `.` or `:` qualify, so `helper` never
290/// matches the tail of `my_helper`. A suffix that would itself start with a
291/// separator (the middle of Rust's `::`) is skipped.
292fn segment_suffixes(fqn: &str) -> Vec<&str> {
293    let mut out = vec![fqn];
294    let bytes = fqn.as_bytes();
295
296    for (i, c) in fqn.char_indices().skip(1) {
297        if c == '.' || c == ':' {
298            continue;
299        }
300        // `i` is a char boundary, so `bytes[i - 1]` is either the whole
301        // previous char (ASCII) or a UTF-8 continuation byte (>= 0x80),
302        // which can never equal `.` or `:`.
303        let prev = bytes[i - 1];
304        if prev == b'.' || prev == b':' {
305            out.push(&fqn[i..]);
306        }
307    }
308
309    out
310}
311
312#[cfg(test)]
313mod tests {
314    use super::*;
315
316    fn nid(n: usize) -> NodeId {
317        petgraph::graph::NodeIndex::new(n)
318    }
319
320    #[test]
321    fn insert_resolve() {
322        let mut table = SymbolTable::new();
323        let path = PathBuf::from("main.rs");
324        table.insert("main::foo".to_string(), nid(1), path.clone());
325
326        assert_eq!(table.resolve("main::foo"), Some(nid(1)));
327        assert_eq!(table.resolve("main::bar"), None);
328        assert_eq!(table.get_file_exports(&path).unwrap(), &vec!["main::foo"]);
329    }
330
331    #[test]
332    fn exact_match_from_any_context() {
333        let mut table = SymbolTable::new();
334        table.insert(
335            "pkg.utils.helper".to_string(),
336            nid(1),
337            PathBuf::from("src/utils.rs"),
338        );
339
340        let r = table.resolve_ref("pkg.utils.helper", Path::new("other/file.rs"));
341        assert_eq!(r, Resolution::Exact(nid(1)));
342        assert_eq!(r.confidence(), 1.0);
343    }
344
345    #[test]
346    fn unique_suffix_match() {
347        let mut table = SymbolTable::new();
348        table.insert(
349            "pkg.utils.helper".to_string(),
350            nid(1),
351            PathBuf::from("src/utils.rs"),
352        );
353
354        let r = table.resolve_ref("helper", Path::new("other/file.rs"));
355        assert_eq!(r, Resolution::UniqueSuffix(nid(1)));
356    }
357
358    #[test]
359    fn multi_segment_suffix_match() {
360        let mut table = SymbolTable::new();
361        table.insert(
362            "pkg.Utils.helper".to_string(),
363            nid(1),
364            PathBuf::from("src/utils.rs"),
365        );
366
367        let r = table.resolve_ref("Utils.helper", Path::new("other/file.rs"));
368        assert_eq!(r, Resolution::UniqueSuffix(nid(1)));
369    }
370
371    #[test]
372    fn suffix_must_be_segment_aligned() {
373        let mut table = SymbolTable::new();
374        table.insert(
375            "pkg.my_helper".to_string(),
376            nid(1),
377            PathBuf::from("src/utils.rs"),
378        );
379
380        // `helper` is a character-suffix of `my_helper` but not a segment.
381        assert_eq!(
382            table.resolve_ref("helper", Path::new("other/file.rs")),
383            Resolution::Unresolved
384        );
385    }
386
387    #[test]
388    fn ambiguous_reports_all_candidates() {
389        let mut table = SymbolTable::new();
390        table.insert(
391            "pkg.a.helper".to_string(),
392            nid(1),
393            PathBuf::from("src/a/mod.rs"),
394        );
395        table.insert(
396            "pkg.b.helper".to_string(),
397            nid(2),
398            PathBuf::from("src/b/mod.rs"),
399        );
400
401        let r = table.resolve_ref("helper", Path::new("src/c/caller.rs"));
402        assert_eq!(r, Resolution::Ambiguous(vec![nid(1), nid(2)]));
403        assert!(r.node().is_none());
404        assert_eq!(r.candidates().len(), 2);
405    }
406
407    #[test]
408    fn locality_preference_same_dir() {
409        let mut table = SymbolTable::new();
410        table.insert(
411            "pkg.a.helper".to_string(),
412            nid(1),
413            PathBuf::from("src/a/mod.rs"),
414        );
415        table.insert(
416            "pkg.b.helper".to_string(),
417            nid(2),
418            PathBuf::from("src/b/mod.rs"),
419        );
420
421        assert_eq!(
422            table.resolve_ref("helper", Path::new("src/a/caller.rs")),
423            Resolution::SameDir(nid(1))
424        );
425        assert_eq!(
426            table.resolve_ref("helper", Path::new("src/b/caller.rs")),
427            Resolution::SameDir(nid(2))
428        );
429    }
430
431    #[test]
432    fn same_file_beats_same_dir() {
433        let mut table = SymbolTable::new();
434        table.insert("A.run".to_string(), nid(1), PathBuf::from("src/a.rs"));
435        table.insert("B.run".to_string(), nid(2), PathBuf::from("src/b.rs"));
436
437        // Both live in `src/`, so same-dir cannot disambiguate — same-file must.
438        assert_eq!(
439            table.resolve_ref("run", Path::new("src/a.rs")),
440            Resolution::SameFile(nid(1))
441        );
442    }
443
444    #[test]
445    fn colliding_fqn_keeps_both_definitions() {
446        let mut table = SymbolTable::new();
447        table.insert("process".to_string(), nid(1), PathBuf::from("src/utils.py"));
448        table.insert(
449            "process".to_string(),
450            nid(2),
451            PathBuf::from("src/helpers.py"),
452        );
453
454        // The old table overwrote here, orphaning one node entirely.
455        assert_eq!(table.resolve_all("process"), vec![nid(2), nid(1)]);
456        assert_eq!(
457            table.resolve("process"),
458            None,
459            "collision is not unambiguous"
460        );
461
462        let r = table.resolve_ref("process", Path::new("src/other.py"));
463        assert_eq!(r, Resolution::Ambiguous(vec![nid(2), nid(1)]));
464    }
465
466    #[test]
467    fn duplicate_insert_is_idempotent() {
468        let mut table = SymbolTable::new();
469        table.insert("a.b".to_string(), nid(1), PathBuf::from("x.rs"));
470        table.insert("a.b".to_string(), nid(1), PathBuf::from("x.rs"));
471
472        assert_eq!(table.resolve_all("a.b"), vec![nid(1)]);
473        assert_eq!(
474            table
475                .get_file_exports(&PathBuf::from("x.rs"))
476                .unwrap()
477                .len(),
478            1
479        );
480    }
481
482    #[test]
483    fn resolution_confidence_is_ordered() {
484        assert!(Resolution::Exact(nid(0)).confidence() > Resolution::SameFile(nid(0)).confidence());
485        assert!(
486            Resolution::SameFile(nid(0)).confidence()
487                > Resolution::UniqueSuffix(nid(0)).confidence()
488        );
489        assert!(
490            Resolution::UniqueSuffix(nid(0)).confidence()
491                > Resolution::SameDir(nid(0)).confidence()
492        );
493        assert!(
494            Resolution::SameDir(nid(0)).confidence() > Resolution::Ambiguous(vec![]).confidence()
495        );
496        assert_eq!(Resolution::Unresolved.confidence(), 0.0);
497    }
498
499    #[test]
500    fn resolution_is_order_independent() {
501        // Same definitions inserted in opposite orders must resolve identically.
502        let mut a = SymbolTable::new();
503        a.insert("p.x.run".into(), nid(1), PathBuf::from("src/x/mod.rs"));
504        a.insert("p.y.run".into(), nid(2), PathBuf::from("src/y/mod.rs"));
505        a.insert("p.z.run".into(), nid(3), PathBuf::from("src/z/mod.rs"));
506
507        let mut b = SymbolTable::new();
508        b.insert("p.z.run".into(), nid(3), PathBuf::from("src/z/mod.rs"));
509        b.insert("p.y.run".into(), nid(2), PathBuf::from("src/y/mod.rs"));
510        b.insert("p.x.run".into(), nid(1), PathBuf::from("src/x/mod.rs"));
511
512        let ctx = Path::new("src/other/caller.rs");
513        assert_eq!(a.resolve_ref("run", ctx), b.resolve_ref("run", ctx));
514    }
515
516    #[test]
517    fn segment_suffixes_shapes() {
518        assert_eq!(segment_suffixes("a.b.c"), vec!["a.b.c", "b.c", "c"]);
519        assert_eq!(segment_suffixes("a::b::c"), vec!["a::b::c", "b::c", "c"]);
520        assert_eq!(segment_suffixes("solo"), vec!["solo"]);
521    }
522
523    #[test]
524    fn unicode_fqn_does_not_panic() {
525        let mut table = SymbolTable::new();
526        table.insert("módulo.función".to_string(), nid(1), PathBuf::from("a.py"));
527        assert_eq!(
528            table.resolve_ref("función", Path::new("b.py")),
529            Resolution::UniqueSuffix(nid(1))
530        );
531    }
532}