1use crate::graph::NodeId;
23use std::collections::HashMap;
24use std::path::{Path, PathBuf};
25
26#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct SymbolEntry {
29 pub id: NodeId,
30 pub file: PathBuf,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum Resolution {
39 Exact(NodeId),
41 SameFile(NodeId),
43 UniqueSuffix(NodeId),
45 SameDir(NodeId),
47 Ambiguous(Vec<NodeId>),
49 Unresolved,
51}
52
53impl Resolution {
54 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 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 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#[derive(Debug, Default, Clone)]
96pub struct SymbolTable {
97 by_fqn: HashMap<String, Vec<SymbolEntry>>,
99
100 by_suffix: HashMap<String, Vec<String>>,
106
107 exports_by_file: HashMap<PathBuf, Vec<String>>,
109}
110
111impl SymbolTable {
112 pub fn new() -> Self {
113 Self::default()
114 }
115
116 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 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 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 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 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 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 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 pub fn resolve_with_context(&self, name: &str, context_file: &Path) -> Option<NodeId> {
263 self.resolve_ref(name, context_file).node()
264 }
265
266 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
276fn 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
285fn 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 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 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 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 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 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}