use crate::graph::NodeId;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SymbolEntry {
pub id: NodeId,
pub file: PathBuf,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Resolution {
Exact(NodeId),
SameFile(NodeId),
UniqueSuffix(NodeId),
SameDir(NodeId),
Ambiguous(Vec<NodeId>),
Unresolved,
}
impl Resolution {
pub fn confidence(&self) -> f32 {
match self {
Resolution::Exact(_) => 1.0,
Resolution::SameFile(_) => 0.95,
Resolution::UniqueSuffix(_) => 0.80,
Resolution::SameDir(_) => 0.55,
Resolution::Ambiguous(_) => 0.25,
Resolution::Unresolved => 0.0,
}
}
pub fn node(&self) -> Option<NodeId> {
match self {
Resolution::Exact(id)
| Resolution::SameFile(id)
| Resolution::UniqueSuffix(id)
| Resolution::SameDir(id) => Some(*id),
Resolution::Ambiguous(_) | Resolution::Unresolved => None,
}
}
pub fn candidates(&self) -> Vec<NodeId> {
match self {
Resolution::Ambiguous(ids) => ids.clone(),
other => other.node().into_iter().collect(),
}
}
pub fn is_resolved(&self) -> bool {
!matches!(self, Resolution::Unresolved)
}
}
#[derive(Debug, Default, Clone)]
pub struct SymbolTable {
by_fqn: HashMap<String, Vec<SymbolEntry>>,
by_suffix: HashMap<String, Vec<String>>,
exports_by_file: HashMap<PathBuf, Vec<String>>,
}
impl SymbolTable {
pub fn new() -> Self {
Self::default()
}
pub fn insert(&mut self, fqn: String, id: NodeId, file: PathBuf) {
let entry = SymbolEntry {
id,
file: file.clone(),
};
let entries = self.by_fqn.entry(fqn.clone()).or_default();
if !entries.contains(&entry) {
entries.push(entry);
}
for suffix in segment_suffixes(&fqn) {
let fqns = self.by_suffix.entry(suffix.to_string()).or_default();
if !fqns.iter().any(|f| f == &fqn) {
fqns.push(fqn.clone());
}
}
let exports = self.exports_by_file.entry(file).or_default();
if !exports.contains(&fqn) {
exports.push(fqn);
}
}
pub fn resolve(&self, fqn: &str) -> Option<NodeId> {
match self.by_fqn.get(fqn) {
Some(entries) if entries.len() == 1 => Some(entries[0].id),
_ => None,
}
}
pub fn resolve_all(&self, fqn: &str) -> Vec<NodeId> {
let Some(entries) = self.by_fqn.get(fqn) else {
return Vec::new();
};
let mut entries: Vec<&SymbolEntry> = entries.iter().collect();
sort_entries(&mut entries);
entries.into_iter().map(|e| e.id).collect()
}
pub fn get_file_exports(&self, file: &PathBuf) -> Option<&Vec<String>> {
self.exports_by_file.get(file)
}
pub fn clear(&mut self) {
self.by_fqn.clear();
self.by_suffix.clear();
self.exports_by_file.clear();
}
pub fn resolve_ref(&self, name: &str, context_file: &Path) -> Resolution {
let exact = self.by_fqn.get(name);
if let Some(entries) = exact {
if entries.len() == 1 {
return Resolution::Exact(entries[0].id);
}
}
let had_exact = exact.is_some();
let mut candidates: Vec<&SymbolEntry> = Vec::new();
let mut seen: Vec<NodeId> = Vec::new();
if let Some(entries) = exact {
for e in entries {
if !seen.contains(&e.id) {
seen.push(e.id);
candidates.push(e);
}
}
}
if let Some(fqns) = self.by_suffix.get(name) {
let mut fqns: Vec<&String> = fqns.iter().collect();
fqns.sort();
for fqn in fqns {
if let Some(entries) = self.by_fqn.get(fqn) {
for e in entries {
if !seen.contains(&e.id) {
seen.push(e.id);
candidates.push(e);
}
}
}
}
}
if candidates.is_empty() {
return Resolution::Unresolved;
}
sort_entries(&mut candidates);
if candidates.len() == 1 {
return if had_exact {
Resolution::Exact(candidates[0].id)
} else {
Resolution::UniqueSuffix(candidates[0].id)
};
}
let same_file: Vec<&SymbolEntry> = candidates
.iter()
.copied()
.filter(|e| e.file == context_file)
.collect();
if same_file.len() == 1 {
return Resolution::SameFile(same_file[0].id);
}
let context_dir = context_file.parent();
let same_dir: Vec<&SymbolEntry> = candidates
.iter()
.copied()
.filter(|e| e.file.parent() == context_dir)
.collect();
if same_dir.len() == 1 {
return Resolution::SameDir(same_dir[0].id);
}
Resolution::Ambiguous(candidates.into_iter().map(|e| e.id).collect())
}
pub fn resolve_with_context(&self, name: &str, context_file: &Path) -> Option<NodeId> {
self.resolve_ref(name, context_file).node()
}
pub fn len(&self) -> usize {
self.by_fqn.len()
}
pub fn is_empty(&self) -> bool {
self.by_fqn.is_empty()
}
}
fn sort_entries(entries: &mut [&SymbolEntry]) {
entries.sort_by(|a, b| {
a.file
.cmp(&b.file)
.then_with(|| a.id.index().cmp(&b.id.index()))
});
}
fn segment_suffixes(fqn: &str) -> Vec<&str> {
let mut out = vec![fqn];
let bytes = fqn.as_bytes();
for (i, c) in fqn.char_indices().skip(1) {
if c == '.' || c == ':' {
continue;
}
let prev = bytes[i - 1];
if prev == b'.' || prev == b':' {
out.push(&fqn[i..]);
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn nid(n: usize) -> NodeId {
petgraph::graph::NodeIndex::new(n)
}
#[test]
fn insert_resolve() {
let mut table = SymbolTable::new();
let path = PathBuf::from("main.rs");
table.insert("main::foo".to_string(), nid(1), path.clone());
assert_eq!(table.resolve("main::foo"), Some(nid(1)));
assert_eq!(table.resolve("main::bar"), None);
assert_eq!(table.get_file_exports(&path).unwrap(), &vec!["main::foo"]);
}
#[test]
fn exact_match_from_any_context() {
let mut table = SymbolTable::new();
table.insert(
"pkg.utils.helper".to_string(),
nid(1),
PathBuf::from("src/utils.rs"),
);
let r = table.resolve_ref("pkg.utils.helper", Path::new("other/file.rs"));
assert_eq!(r, Resolution::Exact(nid(1)));
assert_eq!(r.confidence(), 1.0);
}
#[test]
fn unique_suffix_match() {
let mut table = SymbolTable::new();
table.insert(
"pkg.utils.helper".to_string(),
nid(1),
PathBuf::from("src/utils.rs"),
);
let r = table.resolve_ref("helper", Path::new("other/file.rs"));
assert_eq!(r, Resolution::UniqueSuffix(nid(1)));
}
#[test]
fn multi_segment_suffix_match() {
let mut table = SymbolTable::new();
table.insert(
"pkg.Utils.helper".to_string(),
nid(1),
PathBuf::from("src/utils.rs"),
);
let r = table.resolve_ref("Utils.helper", Path::new("other/file.rs"));
assert_eq!(r, Resolution::UniqueSuffix(nid(1)));
}
#[test]
fn suffix_must_be_segment_aligned() {
let mut table = SymbolTable::new();
table.insert(
"pkg.my_helper".to_string(),
nid(1),
PathBuf::from("src/utils.rs"),
);
assert_eq!(
table.resolve_ref("helper", Path::new("other/file.rs")),
Resolution::Unresolved
);
}
#[test]
fn ambiguous_reports_all_candidates() {
let mut table = SymbolTable::new();
table.insert(
"pkg.a.helper".to_string(),
nid(1),
PathBuf::from("src/a/mod.rs"),
);
table.insert(
"pkg.b.helper".to_string(),
nid(2),
PathBuf::from("src/b/mod.rs"),
);
let r = table.resolve_ref("helper", Path::new("src/c/caller.rs"));
assert_eq!(r, Resolution::Ambiguous(vec![nid(1), nid(2)]));
assert!(r.node().is_none());
assert_eq!(r.candidates().len(), 2);
}
#[test]
fn locality_preference_same_dir() {
let mut table = SymbolTable::new();
table.insert(
"pkg.a.helper".to_string(),
nid(1),
PathBuf::from("src/a/mod.rs"),
);
table.insert(
"pkg.b.helper".to_string(),
nid(2),
PathBuf::from("src/b/mod.rs"),
);
assert_eq!(
table.resolve_ref("helper", Path::new("src/a/caller.rs")),
Resolution::SameDir(nid(1))
);
assert_eq!(
table.resolve_ref("helper", Path::new("src/b/caller.rs")),
Resolution::SameDir(nid(2))
);
}
#[test]
fn same_file_beats_same_dir() {
let mut table = SymbolTable::new();
table.insert("A.run".to_string(), nid(1), PathBuf::from("src/a.rs"));
table.insert("B.run".to_string(), nid(2), PathBuf::from("src/b.rs"));
assert_eq!(
table.resolve_ref("run", Path::new("src/a.rs")),
Resolution::SameFile(nid(1))
);
}
#[test]
fn colliding_fqn_keeps_both_definitions() {
let mut table = SymbolTable::new();
table.insert("process".to_string(), nid(1), PathBuf::from("src/utils.py"));
table.insert(
"process".to_string(),
nid(2),
PathBuf::from("src/helpers.py"),
);
assert_eq!(table.resolve_all("process"), vec![nid(2), nid(1)]);
assert_eq!(
table.resolve("process"),
None,
"collision is not unambiguous"
);
let r = table.resolve_ref("process", Path::new("src/other.py"));
assert_eq!(r, Resolution::Ambiguous(vec![nid(2), nid(1)]));
}
#[test]
fn duplicate_insert_is_idempotent() {
let mut table = SymbolTable::new();
table.insert("a.b".to_string(), nid(1), PathBuf::from("x.rs"));
table.insert("a.b".to_string(), nid(1), PathBuf::from("x.rs"));
assert_eq!(table.resolve_all("a.b"), vec![nid(1)]);
assert_eq!(
table
.get_file_exports(&PathBuf::from("x.rs"))
.unwrap()
.len(),
1
);
}
#[test]
fn resolution_confidence_is_ordered() {
assert!(Resolution::Exact(nid(0)).confidence() > Resolution::SameFile(nid(0)).confidence());
assert!(
Resolution::SameFile(nid(0)).confidence()
> Resolution::UniqueSuffix(nid(0)).confidence()
);
assert!(
Resolution::UniqueSuffix(nid(0)).confidence()
> Resolution::SameDir(nid(0)).confidence()
);
assert!(
Resolution::SameDir(nid(0)).confidence() > Resolution::Ambiguous(vec![]).confidence()
);
assert_eq!(Resolution::Unresolved.confidence(), 0.0);
}
#[test]
fn resolution_is_order_independent() {
let mut a = SymbolTable::new();
a.insert("p.x.run".into(), nid(1), PathBuf::from("src/x/mod.rs"));
a.insert("p.y.run".into(), nid(2), PathBuf::from("src/y/mod.rs"));
a.insert("p.z.run".into(), nid(3), PathBuf::from("src/z/mod.rs"));
let mut b = SymbolTable::new();
b.insert("p.z.run".into(), nid(3), PathBuf::from("src/z/mod.rs"));
b.insert("p.y.run".into(), nid(2), PathBuf::from("src/y/mod.rs"));
b.insert("p.x.run".into(), nid(1), PathBuf::from("src/x/mod.rs"));
let ctx = Path::new("src/other/caller.rs");
assert_eq!(a.resolve_ref("run", ctx), b.resolve_ref("run", ctx));
}
#[test]
fn segment_suffixes_shapes() {
assert_eq!(segment_suffixes("a.b.c"), vec!["a.b.c", "b.c", "c"]);
assert_eq!(segment_suffixes("a::b::c"), vec!["a::b::c", "b::c", "c"]);
assert_eq!(segment_suffixes("solo"), vec!["solo"]);
}
#[test]
fn unicode_fqn_does_not_panic() {
let mut table = SymbolTable::new();
table.insert("módulo.función".to_string(), nid(1), PathBuf::from("a.py"));
assert_eq!(
table.resolve_ref("función", Path::new("b.py")),
Resolution::UniqueSuffix(nid(1))
);
}
}