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 ViaImport(NodeId),
51 SameDir(NodeId),
53 Ambiguous(Vec<NodeId>),
55 Unresolved,
57}
58
59impl Resolution {
60 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 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 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#[derive(Debug, Default, Clone)]
104pub struct SymbolTable {
105 by_fqn: HashMap<String, Vec<SymbolEntry>>,
107
108 by_suffix: HashMap<String, Vec<String>>,
114
115 exports_by_file: HashMap<PathBuf, Vec<String>>,
117}
118
119impl SymbolTable {
120 pub fn new() -> Self {
121 Self::default()
122 }
123
124 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 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 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 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 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 pub fn resolve_ref(&self, name: &str, context_file: &Path) -> Resolution {
196 self.resolve_ref_with_imports(name, context_file, None)
197 }
198
199 pub fn resolve_ref_with_imports(
219 &self,
220 name: &str,
221 context_file: &Path,
222 imports: Option<&HashMap<String, String>>,
223 ) -> Resolution {
224 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 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 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 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 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 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 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 return pick(entries, context_file, Resolution::Exact);
475 }
476
477 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 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 pub fn resolve_with_context(&self, name: &str, context_file: &Path) -> Option<NodeId> {
527 self.resolve_ref(name, context_file).node()
528 }
529
530 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
540fn 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
568fn 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 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
610fn 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
621fn 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
650fn 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
656fn 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
672fn 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
694pub(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
708fn 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
718fn 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
728fn 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
737fn 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 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 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 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 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 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 #[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 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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}