arbor-graph 3.1.1

Graph schema and relationship tracking for Arbor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
//! Cross-file symbol resolution.
//!
//! Maps Fully Qualified Names (FQNs) to graph nodes and resolves bare or
//! partially-qualified references against them.
//!
//! # Determinism
//!
//! Every lookup path in this module is order-independent. Candidate lists are
//! sorted by `(file, node index)` before any pick is made, and no decision ever
//! depends on `HashMap` iteration order — Rust seeds `RandomState` per process,
//! so iterating a map to choose a winner would make graph construction vary
//! between runs of the same binary on the same input.
//!
//! # Collisions
//!
//! An FQN can legitimately map to several nodes: `handler` in twelve route
//! files, `new` on forty structs, `process` in both `utils.py` and `helpers.py`.
//! The table keeps every entry and reports ambiguity to the caller rather than
//! silently overwriting, which would orphan the loser and produce a false
//! negative in blast radius.

use crate::graph::NodeId;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// One definition of a symbol.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SymbolEntry {
    pub id: NodeId,
    pub file: PathBuf,
}

/// How a reference was matched, ordered from most to least trustworthy.
///
/// The variant determines the confidence stamped on the resulting edge, so a
/// downstream consumer can tell a certain call from an educated guess.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Resolution {
    /// Exact FQN match with exactly one definition.
    Exact(NodeId),
    /// Matched a symbol defined in the referencing file.
    SameFile(NodeId),
    /// Suffix match with exactly one definition repo-wide.
    UniqueSuffix(NodeId),
    /// Several candidates; the referencing file's own import statement names
    /// exactly one module, and one candidate came from it.
    ///
    /// Stronger evidence than `SameDir`: the author wrote down which module they
    /// meant. Ranked accordingly in `confidence`.
    ViaImport(NodeId),
    /// Several candidates; exactly one lives in the referencing file's directory.
    SameDir(NodeId),
    /// Several equally-plausible candidates, sorted deterministically.
    Ambiguous(Vec<NodeId>),
    /// No definition in this repository (external or stdlib).
    Unresolved,
}

impl Resolution {
    /// Confidence to stamp on an edge created from this resolution.
    ///
    /// `Ambiguous` is deliberately low rather than zero: the reference does
    /// point at *something* in the repo, we just cannot say which. Consumers
    /// that need certainty should filter on this value.
    pub fn confidence(&self) -> f32 {
        match self {
            Resolution::Exact(_) => 1.0,
            Resolution::SameFile(_) => 0.95,
            Resolution::UniqueSuffix(_) => 0.80,
            Resolution::ViaImport(_) => 0.93,
            Resolution::SameDir(_) => 0.55,
            Resolution::Ambiguous(_) => 0.25,
            Resolution::Unresolved => 0.0,
        }
    }

    /// The single resolved node, if this resolution picked one.
    pub fn node(&self) -> Option<NodeId> {
        match self {
            Resolution::Exact(id)
            | Resolution::SameFile(id)
            | Resolution::UniqueSuffix(id)
            | Resolution::ViaImport(id)
            | Resolution::SameDir(id) => Some(*id),
            Resolution::Ambiguous(_) | Resolution::Unresolved => None,
        }
    }

    /// Every candidate this resolution considered plausible.
    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)
    }
}

/// A global symbol table for resolving cross-file references.
#[derive(Debug, Default, Clone)]
pub struct SymbolTable {
    /// FQN → every node defining it.
    by_fqn: HashMap<String, Vec<SymbolEntry>>,

    /// Segment-aligned suffix → FQNs ending with it.
    ///
    /// `pkg.Utils.helper` is indexed under `helper`, `Utils.helper`, and
    /// `pkg.Utils.helper`, so resolving a bare `helper` is an O(1) lookup
    /// instead of a scan over every FQN in the repository.
    by_suffix: HashMap<String, Vec<String>>,

    /// File → FQNs it defines.
    exports_by_file: HashMap<PathBuf, Vec<String>>,
}

impl SymbolTable {
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers a symbol definition.
    ///
    /// Repeated FQNs accumulate instead of overwriting.
    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();
        // Guard against the same definition being indexed twice (incremental
        // re-parse of an unchanged file).
        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);
        }
    }

    /// Resolves an exact FQN, but only when the definition is unambiguous.
    ///
    /// Returns `None` for a colliding FQN so the caller can fall back to
    /// context-aware resolution rather than picking a definition at random.
    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,
        }
    }

    /// All nodes defining this exact FQN, in deterministic order.
    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()
    }

    /// Returns all symbols exported by a file.
    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();
    }

    /// Resolves a reference, preferring locality and reporting ambiguity.
    ///
    /// Order:
    ///   1. Exact FQN, unique → `Exact`
    ///   2. Candidate gathering: exact-FQN entries plus every segment-aligned
    ///      suffix match, deduplicated and sorted
    ///   3. Single candidate → `Exact` / `UniqueSuffix`
    ///   4. Exactly one candidate in the referencing file → `SameFile`
    ///   5. Exactly one candidate in the referencing directory → `SameDir`
    ///   6. Otherwise → `Ambiguous`
    pub fn resolve_ref(&self, name: &str, context_file: &Path) -> Resolution {
        self.resolve_ref_with_imports(name, context_file, None)
    }

    /// Resolve a reference, allowing the referencing file's imports to break ties.
    ///
    /// Without `imports`, a bare name matching definitions in several modules
    /// falls through to `Ambiguous` whenever no candidate shares a file or a
    /// directory with the caller — and the builder drops ambiguous edges. On a
    /// codebase that reuses a name across modules that is the common case, not
    /// the rare one: every call to it is discarded, and the module those calls
    /// belonged to reports no callers at all.
    ///
    /// The disambiguating fact is usually written at the top of the file.
    /// `from deep.l0.m14 import value_m14` says exactly which `value_m14` is
    /// meant here. `import_map` already carries that, but only
    /// `apply_import_validation` consumed it, and that runs *after* a candidate
    /// has been chosen — so it never saw the references that were being thrown
    /// away. Consulting it during disambiguation instead of after it is the
    /// whole change.
    ///
    /// `imports` maps a locally-visible name to the module it came from, so an
    /// aliased import (`from x import y as z`) is keyed on `z`.
    pub fn resolve_ref_with_imports(
        &self,
        name: &str,
        context_file: &Path,
        imports: Option<&HashMap<String, String>>,
    ) -> Resolution {
        // A call never crosses languages: a Rust `enqueue` isn't called by a
        // TypeScript `enqueue(...)`. Definitions in another language are not
        // candidates at all, so they can neither win nor make a match ambiguous.
        let family = language_family(context_file);
        let visible = |e: &SymbolEntry| same_family(family, &e.file);

        let exact: Option<Vec<&SymbolEntry>> = self
            .by_fqn
            .get(name)
            .map(|entries| entries.iter().filter(|e| visible(e)).collect::<Vec<_>>())
            .filter(|entries| !entries.is_empty());
        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) {
            // `by_suffix` values are insertion-ordered Vecs, but sort the FQN
            // list anyway so candidate order never depends on parse order.
            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 visible(e) && !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);
        }

        // The referencing file said which module it meant. Believe it.
        //
        // Checked after same-file (a local definition shadows an import) and
        // before same-directory (a written import is better evidence than mere
        // adjacency). Matching is done on the module path so it works whether
        // the source records `deep.l0.m14` or a path-like `deep/l0/m14`.
        if let Some(map) = imports {
            if let Some(source_module) = map.get(name) {
                let wanted = normalize_module_path(source_module);
                if !wanted.is_empty() {
                    let from_import: Vec<&SymbolEntry> = candidates
                        .iter()
                        .copied()
                        .filter(|e| entry_belongs_to_module(e, &wanted))
                        .collect();
                    if from_import.len() == 1 {
                        return Resolution::ViaImport(from_import[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())
    }

    /// Resolves `name` imported from `module` under another name
    /// (`from money import money_to_minor_units as to_minor`).
    ///
    /// The import says where the definition lives, so only definitions of
    /// `name` in that module are candidates: the module's own file first
    /// (`money.py`, or a package's `__init__.py` or `index.ts`), then anything
    /// inside a package of that name. A same-named function elsewhere is not
    /// the target. A module this project doesn't define (`numpy`) leaves the
    /// call unresolved, unless a project file or directory, or a directory
    /// above the project, has the module's name: modules are matched by name,
    /// so it then binds there, as an unaliased import of the name does.
    ///
    /// A relative module (`./format`, `../route`, `.money`, `..core.money`)
    /// names one place, read from the importing file's directory, so a
    /// same-named file elsewhere (every `route.ts` in a Next.js app) is never a
    /// candidate.
    ///
    /// An import binds a module-level name, so `name` is matched exactly and a
    /// method (`Class.name`) is never a candidate. Neither is the importing
    /// file: in a wrapper that keeps the imported function's name
    /// (`from money import f as _f` then `def f(): _f()`), `_f` is money's.
    pub fn resolve_imported(&self, name: &str, module: &str, context_file: &Path) -> Resolution {
        self.resolve_in_module(name, module, context_file, true)
    }

    /// Resolves `name` in the module's own file only: `module.ts`, or a
    /// package's `index.ts` or `__init__.py`, never another file inside the
    /// package.
    ///
    /// For a name a file took from a value the module produced (a hook's or
    /// factory's return value), not from its exports. A barrel that only
    /// re-exports the hook says nothing about the other files under it.
    pub fn resolve_in_module_file(
        &self,
        name: &str,
        module: &str,
        context_file: &Path,
    ) -> Resolution {
        self.resolve_in_module(name, module, context_file, false)
    }

    /// [`Self::resolve_imported`], and with `whole_package` false,
    /// [`Self::resolve_in_module_file`].
    fn resolve_in_module(
        &self,
        name: &str,
        module: &str,
        context_file: &Path,
        whole_package: bool,
    ) -> Resolution {
        let family = language_family(context_file);
        let defined: Vec<&SymbolEntry> = self
            .by_fqn
            .get(name)
            .into_iter()
            .flatten()
            .filter(|e| same_family(family, &e.file) && e.file != context_file)
            .collect();

        if module.starts_with('.') {
            let Some(target) = relative_module_path(module, context_file) else {
                return Resolution::Unresolved;
            };
            let in_module: Vec<&SymbolEntry> = defined
                .iter()
                .copied()
                .filter(|e| is_module_file(&e.file, &target))
                .collect();
            if !in_module.is_empty() {
                return pick(in_module, context_file, Resolution::ViaImport);
            }
            if !whole_package || target.as_os_str().is_empty() {
                return Resolution::Unresolved;
            }
            let in_package: Vec<&SymbolEntry> = defined
                .into_iter()
                .filter(|e| e.file.starts_with(&target))
                .collect();
            return pick(in_package, context_file, Resolution::ViaImport);
        }

        let wanted = normalize_module_path(module);
        if wanted.is_empty() {
            return Resolution::Unresolved;
        }
        let in_module: Vec<&SymbolEntry> = defined
            .iter()
            .copied()
            .filter(|e| module_is(e, &wanted) || package_init_is(e, &wanted))
            .collect();
        if !in_module.is_empty() {
            return pick(in_module, context_file, Resolution::ViaImport);
        }
        if !whole_package {
            return Resolution::Unresolved;
        }
        let in_package: Vec<&SymbolEntry> = defined
            .into_iter()
            .filter(|e| entry_belongs_to_module(e, &wanted))
            .collect();
        pick(in_package, context_file, Resolution::ViaImport)
    }

    /// Resolves a `::` path reference: `jobs::enqueue`, `Provider::new`,
    /// `crate::db::queries::get_user`, `my_app::app::create`.
    ///
    /// The path says where the definition lives, so it is matched on that
    /// rather than on the bare name:
    ///
    /// - a path some parser recorded verbatim (C++ `ns::fn`) matches directly;
    /// - a capitalised owner is a type, and `Type::new` is stored as `Type.new`;
    /// - anything else is a module, matched against the definition's file
    ///   (`jobs.rs`, `app/mod.rs`). Leading segments are dropped until one
    ///   matches, so a crate-name prefix (`my_app::app::…`) works,
    ///   and a definition re-exported from a submodule is found at lower
    ///   confidence.
    ///
    /// A path into an external crate (`sqlx::query`, `std::fs::read`) matches
    /// nothing here and stays unresolved, instead of binding to an unrelated
    /// local function that shares the last name.
    pub fn resolve_path(&self, path: &str, context_file: &Path) -> Resolution {
        let family = language_family(context_file);
        let visible = |e: &&SymbolEntry| same_family(family, &e.file);

        let verbatim = self.entries_with_suffix(path, &visible);
        if !verbatim.is_empty() {
            return pick(verbatim, context_file, Resolution::Exact);
        }

        let segments: Vec<&str> = path
            .split("::")
            .map(str::trim)
            .filter(|s| !s.is_empty() && !matches!(*s, "crate" | "self" | "super"))
            .collect();
        let Some((name, qualifiers)) = segments.split_last() else {
            return Resolution::Unresolved;
        };
        let Some(owner) = qualifiers.last() else {
            return self.resolve_ref(name, context_file);
        };

        if owner.starts_with(|c: char| c.is_uppercase()) {
            let mut entries = self.entries_with_suffix(&format!("{owner}.{name}"), &visible);
            entries.extend(self.entries_with_suffix(&format!("{owner}::{name}"), &visible));
            // Nothing: an enum variant (`Error::NotFound(e)`) or an external type.
            return pick(entries, context_file, Resolution::Exact);
        }

        // Free functions are stored under their bare name.
        let named: Vec<&SymbolEntry> = self
            .by_fqn
            .get(*name)
            .into_iter()
            .flatten()
            .filter(|e| visible(e))
            .collect();
        for start in 0..qualifiers.len() {
            let wanted = normalize_module_path(&qualifiers[start..].join("."));
            if wanted.is_empty() {
                continue;
            }
            let in_module: Vec<&SymbolEntry> = named
                .iter()
                .copied()
                .filter(|e| module_is(e, &wanted))
                .collect();
            if !in_module.is_empty() {
                return pick(in_module, context_file, Resolution::ViaImport);
            }
            let re_exported: Vec<&SymbolEntry> = named
                .iter()
                .copied()
                .filter(|e| entry_belongs_to_module(e, &wanted))
                .collect();
            if !re_exported.is_empty() {
                return pick(re_exported, context_file, Resolution::UniqueSuffix);
            }
        }
        Resolution::Unresolved
    }

    /// Entries whose FQN is `fqn` or ends with it on a segment boundary.
    fn entries_with_suffix(
        &self,
        fqn: &str,
        visible: &dyn Fn(&&SymbolEntry) -> bool,
    ) -> Vec<&SymbolEntry> {
        let mut fqns: Vec<&String> = self.by_suffix.get(fqn).into_iter().flatten().collect();
        fqns.sort();
        fqns.into_iter()
            .filter_map(|f| self.by_fqn.get(f))
            .flatten()
            .filter(|e| visible(e))
            .collect()
    }

    /// Back-compatible wrapper returning only a confidently-resolved node.
    pub fn resolve_with_context(&self, name: &str, context_file: &Path) -> Option<NodeId> {
        self.resolve_ref(name, context_file).node()
    }

    /// Number of distinct FQNs registered.
    pub fn len(&self) -> usize {
        self.by_fqn.len()
    }

    pub fn is_empty(&self) -> bool {
        self.by_fqn.is_empty()
    }
}

/// Reduce a module reference to dot-separated segments for comparison.
///
/// `deep.l0.m14`, `deep/l0/m14`, `./deep/l0/m14.py` and `crate::deep::l0::m14`
/// all normalize to `deep.l0.m14`, so the same check works across the languages
/// this engine parses without a per-language branch.
fn normalize_module_path(raw: &str) -> String {
    let cleaned = raw.replace("::", ".").replace(['/', '\\'], ".");
    let cleaned = cleaned
        .trim_start_matches('.')
        .trim_end_matches(".py")
        .trim_end_matches(".ts")
        .trim_end_matches(".js")
        .trim_end_matches(".rs")
        .trim_end_matches(".go");
    cleaned
        .split('.')
        .filter(|seg| {
            !seg.is_empty()
                && *seg != "index"
                && *seg != "mod"
                && *seg != "crate"
                && *seg != "self"
                && *seg != "super"
        })
        .collect::<Vec<_>>()
        .join(".")
}

/// The path, without extension, that a relative import names, read from the
/// importing file's directory: `./format` and `../route` in TypeScript and
/// JavaScript, `.money` and `..core.money` in Python (one dot is the
/// importing file's package, each further dot its parent). `None` when the
/// import climbs out of the tree.
fn relative_module_path(module: &str, context_file: &Path) -> Option<PathBuf> {
    let mut path = context_file.parent()?.to_path_buf();
    if module.contains('/') {
        for segment in module.split('/') {
            match segment {
                "" | "." => {}
                ".." => {
                    if !path.pop() {
                        return None;
                    }
                }
                name => path.push(name),
            }
        }
        // `./format.js` names `format.ts` under TypeScript's ESM resolution.
        if matches!(
            path.extension().and_then(|e| e.to_str()),
            Some("js" | "jsx" | "mjs" | "cjs" | "ts" | "tsx" | "mts" | "cts")
        ) {
            path.set_extension("");
        }
        return Some(path);
    }

    let rest = module.strip_prefix('.')?;
    let name = rest.trim_start_matches('.');
    for _ in 0..rest.len() - name.len() {
        if !path.pop() {
            return None;
        }
    }
    for segment in name.split('.').filter(|s| !s.is_empty()) {
        path.push(segment);
    }
    Some(path)
}

/// Is `file` the module at `target`: `target.ts` / `target.py`, or the
/// package's own `index` / `__init__` file?
fn is_module_file(file: &Path, target: &Path) -> bool {
    file.with_extension("").as_path() == target
        || (file.parent() == Some(target)
            && matches!(
                file.file_stem().and_then(|s| s.to_str()),
                Some("index" | "__init__")
            ))
}

/// Picks among entries that all match the reference equally well: one is
/// `unique`, otherwise the referencing file, then its directory, break ties.
fn pick(
    mut entries: Vec<&SymbolEntry>,
    context_file: &Path,
    unique: fn(NodeId) -> Resolution,
) -> Resolution {
    sort_entries(&mut entries);
    entries.dedup_by_key(|e| e.id);
    match entries.as_slice() {
        [] => Resolution::Unresolved,
        [only] => unique(only.id),
        _ => {
            let same_file: Vec<&&SymbolEntry> =
                entries.iter().filter(|e| e.file == context_file).collect();
            if same_file.len() == 1 {
                return Resolution::SameFile(same_file[0].id);
            }
            let dir = context_file.parent();
            let same_dir: Vec<&&SymbolEntry> =
                entries.iter().filter(|e| e.file.parent() == dir).collect();
            if same_dir.len() == 1 {
                return Resolution::SameDir(same_dir[0].id);
            }
            Resolution::Ambiguous(entries.into_iter().map(|e| e.id).collect())
        }
    }
}

/// Is this symbol defined in exactly `module` (`jobs.rs`, `jobs/mod.rs`)?
fn module_is(entry: &SymbolEntry, module: &str) -> bool {
    let file_norm = normalize_module_path(&entry.file.to_string_lossy());
    file_norm == module || file_norm.ends_with(&format!(".{module}"))
}

/// Is this symbol defined in the package `module`'s own `__init__.py`?
///
/// `module_is` already matches `pkg/index.ts` and `pkg/mod.rs`, because
/// `normalize_module_path` drops `index` and `mod`, but `pkg/__init__.py`
/// normalizes to `pkg.__init__`. The package directory is compared the way
/// `module_is` compares a file. Only `__init__.py` counts: an `__init__.pyi`
/// is a type stub, not the module that runs, and the implementation it
/// describes usually lives in a submodule.
fn package_init_is(entry: &SymbolEntry, module: &str) -> bool {
    entry.file.file_name().and_then(|s| s.to_str()) == Some("__init__.py")
        && entry.file.parent().is_some_and(|dir| {
            let dir_norm = normalize_module_path(&dir.to_string_lossy());
            dir_norm == module || dir_norm.ends_with(&format!(".{module}"))
        })
}

/// Source languages that can call each other directly. Calls are never
/// resolved across families; a name shared by a Rust and a TypeScript
/// definition is two symbols, not one.
fn language_family(path: &Path) -> Option<&'static str> {
    let ext = path.extension()?.to_str()?.to_ascii_lowercase();
    Some(match ext.as_str() {
        "rs" => "rust",
        "ts" | "tsx" | "mts" | "cts" | "js" | "jsx" | "mjs" | "cjs" | "vue" | "svelte" => "js",
        "py" | "pyi" => "python",
        "go" => "go",
        "java" | "kt" | "kts" | "scala" => "jvm",
        "c" | "h" | "cc" | "cpp" | "cxx" | "hh" | "hpp" | "hxx" | "m" | "mm" => "c",
        "cs" => "csharp",
        "rb" => "ruby",
        "php" | "phtml" => "php",
        "swift" => "swift",
        "dart" => "dart",
        "sh" | "bash" | "zsh" => "shell",
        _ => return None,
    })
}

/// Unknown extensions on either side don't filter anything out.
/// Whether two files are in the same language family (an unknown extension
/// matches anything).
pub(crate) fn same_language(a: &Path, b: &Path) -> bool {
    same_family(language_family(a), b)
}

fn same_family(family: Option<&'static str>, file: &Path) -> bool {
    match (family, language_family(file)) {
        (Some(a), Some(b)) => a == b,
        _ => true,
    }
}

/// Did this symbol come from `module`?
///
/// A `SymbolEntry` carries only its id and its file, so the file path is the
/// module identity. Requires a segment-aligned match, so a reference to
/// `l0.m14` is never satisfied by `l0.m1`.
fn entry_belongs_to_module(entry: &SymbolEntry, module: &str) -> bool {
    let file_norm = normalize_module_path(&entry.file.to_string_lossy());
    segment_aligned_contains(&file_norm, module)
}

/// True when `needle` appears in `haystack` on segment boundaries.
fn segment_aligned_contains(haystack: &str, needle: &str) -> bool {
    if haystack == needle {
        return true;
    }
    haystack.starts_with(&format!("{needle}."))
        || haystack.ends_with(&format!(".{needle}"))
        || haystack.contains(&format!(".{needle}."))
}

/// Sorts entries by `(file, node index)` for a total, parse-order-independent order.
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()))
    });
}

/// Every segment-aligned suffix of an FQN, including the FQN itself.
///
/// `a.b.c` → `["a.b.c", "b.c", "c"]`; `a::b::c` → `["a::b::c", "b::c", "c"]`.
///
/// Only positions immediately after a `.` or `:` qualify, so `helper` never
/// matches the tail of `my_helper`. A suffix that would itself start with a
/// separator (the middle of Rust's `::`) is skipped.
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;
        }
        // `i` is a char boundary, so `bytes[i - 1]` is either the whole
        // previous char (ASCII) or a UTF-8 continuation byte (>= 0x80),
        // which can never equal `.` or `:`.
        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"),
        );

        // `helper` is a character-suffix of `my_helper` but not a segment.
        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"));

        // Both live in `src/`, so same-dir cannot disambiguate — same-file must.
        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"),
        );

        // The old table overwrote here, orphaning one node entirely.
        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() {
        // Same definitions inserted in opposite orders must resolve identically.
        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))
        );
    }
}

#[cfg(test)]
mod import_resolution_tests {
    use super::*;

    fn nid(i: usize) -> NodeId {
        NodeId::new(i)
    }

    /// The exact shape that returned zero on the torture fixture: one bare name
    /// defined in ten modules, called from an eleventh that imported one of them.
    #[test]
    fn import_breaks_a_tie_that_would_otherwise_be_ambiguous() {
        let mut table = SymbolTable::default();
        for layer in 0usize..10 {
            table.insert(
                format!("deep.l{layer}.m14.value_m14"),
                nid(layer),
                PathBuf::from(format!("/repo/deep/l{layer}/m14.py")),
            );
        }

        let caller = Path::new("/repo/deep/l1/m03.py");

        // Without imports the resolver does NOT report ambiguity — it picks the
        // sibling sitting in the caller's own directory and reports SameDir at
        // 0.55 confidence. That is the real defect: the edge is not dropped, it
        // is confidently attached to the wrong module. Every caller in `l1/`
        // resolves to `l1/m14.py`, which is why `l0/m14.py` ends up with no
        // callers at all while an unrelated layer inherits its centrality.
        let bare = table.resolve_ref("value_m14", caller);
        assert_eq!(
            bare,
            Resolution::SameDir(nid(1)),
            "expected the same-directory sibling to be mis-picked, got {bare:?}"
        );

        // With the import the caller actually wrote, exactly one survives.
        let mut imports = HashMap::new();
        imports.insert("value_m14".to_string(), "deep.l0.m14".to_string());
        let resolved = table.resolve_ref_with_imports("value_m14", caller, Some(&imports));

        match resolved {
            Resolution::ViaImport(id) => {
                assert_eq!(id, nid(0), "resolved to the wrong layer");
            }
            other => panic!("expected ViaImport(l0), got {other:?}"),
        }
    }

    /// A definition in the caller's own file outranks an import of the same name.
    #[test]
    fn local_definition_still_shadows_an_import() {
        let mut table = SymbolTable::default();
        table.insert(
            "a.mod.process".to_string(),
            nid(0),
            PathBuf::from("/repo/a/mod.py"),
        );
        table.insert(
            "b.other.process".to_string(),
            nid(1),
            PathBuf::from("/repo/b/other.py"),
        );

        let caller = Path::new("/repo/a/mod.py");
        let mut imports = HashMap::new();
        imports.insert("process".to_string(), "b.other".to_string());

        let r = table.resolve_ref_with_imports("process", caller, Some(&imports));
        assert!(
            matches!(r, Resolution::SameFile(_)),
            "a local definition must win over an import, got {r:?}"
        );
    }

    #[test]
    fn module_paths_normalize_across_separator_styles() {
        assert_eq!(normalize_module_path("deep/l0/m14.py"), "deep.l0.m14");
        assert_eq!(normalize_module_path("crate::deep::l0::m14"), "deep.l0.m14");
        assert_eq!(normalize_module_path("./deep/l0/m14"), "deep.l0.m14");
    }

    /// `l0.m1` must never satisfy a request for `l0.m14`.
    #[test]
    fn module_matching_is_segment_aligned() {
        assert!(segment_aligned_contains("x.deep.l0.m14", "deep.l0.m14"));
        assert!(!segment_aligned_contains("x.deep.l0.m140", "deep.l0.m14"));
        assert!(!segment_aligned_contains("x.deep.l0.m1", "deep.l0.m14"));
    }

    fn money_table() -> SymbolTable {
        let mut table = SymbolTable::default();
        table.insert(
            "convert".to_string(),
            nid(0),
            PathBuf::from("billing/money.py"),
        );
        table.insert(
            "convert".to_string(),
            nid(1),
            PathBuf::from("legacy/money.py"),
        );
        table.insert(
            "convert".to_string(),
            nid(2),
            PathBuf::from("payments/rates/convert_impl.py"),
        );
        table.insert(
            "Ledger.convert".to_string(),
            nid(3),
            PathBuf::from("ledger.py"),
        );
        table
    }

    #[test]
    fn an_aliased_import_resolves_in_the_named_module_only() {
        let table = money_table();
        let caller = Path::new("app/orders.py");
        assert_eq!(
            table.resolve_imported("convert", "billing.money", caller),
            Resolution::ViaImport(nid(0))
        );
        assert_eq!(
            table.resolve_imported("convert", "legacy.money", caller),
            Resolution::ViaImport(nid(1))
        );
    }

    /// `from payments import convert as c`, where `payments/__init__.py`
    /// re-exports it from a submodule.
    #[test]
    fn an_aliased_import_from_a_package_reaches_its_submodule() {
        let table = money_table();
        assert_eq!(
            table.resolve_imported("convert", "payments", Path::new("app/orders.py")),
            Resolution::ViaImport(nid(2))
        );
    }

    /// `pkg/__init__.py` is `pkg` itself, so it outranks a submodule's
    /// definition of the same name. `arbor index` stores absolute paths, so
    /// both path shapes are checked, and a package whose name only ends like
    /// the module's (`mypkg`) is not `pkg`.
    #[test]
    fn an_aliased_import_from_a_package_prefers_its_init() {
        for root in ["", "/repo/"] {
            let mut table = SymbolTable::default();
            for (i, file) in ["pkg/__init__.py", "pkg/sub.py", "mypkg/__init__.py"]
                .iter()
                .enumerate()
            {
                table.insert(
                    "f".to_string(),
                    nid(i),
                    PathBuf::from(format!("{root}{file}")),
                );
            }
            let caller = PathBuf::from(format!("{root}app.py"));
            assert_eq!(
                table.resolve_imported("f", "pkg", &caller),
                Resolution::ViaImport(nid(0)),
                "root {root:?}"
            );

            table.insert(
                "f".to_string(),
                nid(3),
                PathBuf::from(format!("{root}shop/cart/__init__.py")),
            );
            table.insert(
                "f".to_string(),
                nid(4),
                PathBuf::from(format!("{root}shop/cart/items.py")),
            );
            assert_eq!(
                table.resolve_imported("f", "shop.cart", &caller),
                Resolution::ViaImport(nid(3)),
                "root {root:?}: a dotted package's own __init__"
            );
        }
    }

    /// `resolve_in_module_file` stops at the module's own file. A barrel
    /// (`index.ts`) that doesn't define the name leaves it unresolved, where
    /// an import reaches into the package.
    #[test]
    fn a_module_file_lookup_never_reaches_into_the_package() {
        let mut table = SymbolTable::default();
        table.insert(
            "logout".to_string(),
            nid(0),
            PathBuf::from("src/app/admin/session.ts"),
        );
        table.insert(
            "useApp".to_string(),
            nid(1),
            PathBuf::from("src/app/index.ts"),
        );
        let caller = Path::new("src/app/settings/Account.tsx");
        assert_eq!(
            table.resolve_imported("logout", "..", caller),
            Resolution::ViaImport(nid(0))
        );
        assert_eq!(
            table.resolve_in_module_file("logout", "..", caller),
            Resolution::Unresolved
        );
        assert_eq!(
            table.resolve_in_module_file("useApp", "..", caller),
            Resolution::ViaImport(nid(1))
        );
    }

    /// Known limit: `flask` is not part of this project, but a checkout under
    /// `/home/u/flask/` has a directory named `flask`, so the module matches
    /// it, as it does for an unaliased import.
    #[test]
    fn an_external_module_named_like_a_directory_above_the_project_matches_it() {
        let mut table = SymbolTable::default();
        table.insert(
            "render_template".to_string(),
            nid(0),
            PathBuf::from("/home/u/flask/app/views.py"),
        );
        assert_eq!(
            table.resolve_imported(
                "render_template",
                "flask",
                Path::new("/home/u/flask/app/main.py")
            ),
            Resolution::ViaImport(nid(0))
        );
    }

    #[test]
    fn an_aliased_import_from_an_external_module_is_unresolved() {
        let table = money_table();
        assert_eq!(
            table.resolve_imported("convert", "numpy", Path::new("app/orders.py")),
            Resolution::Unresolved
        );
    }

    /// Relative Python modules are read from the importing file's package.
    /// The importing file itself is never the import.
    #[test]
    fn a_relative_python_alias_is_read_from_the_importing_package() {
        let table = money_table();
        assert_eq!(
            table.resolve_imported("convert", ".", Path::new("legacy/orders.py")),
            Resolution::ViaImport(nid(1))
        );
        assert_eq!(
            table.resolve_imported("convert", ".money", Path::new("billing/orders.py")),
            Resolution::ViaImport(nid(0))
        );
        assert_eq!(
            table.resolve_imported("convert", "..money", Path::new("billing/api/orders.py")),
            Resolution::ViaImport(nid(0))
        );
        assert_eq!(
            table.resolve_imported("convert", ".", Path::new("legacy/money.py")),
            Resolution::Unresolved
        );
        // `shop/money.py` does not exist; `billing` and `legacy` are not it.
        assert_eq!(
            table.resolve_imported("convert", ".money", Path::new("shop/orders.py")),
            Resolution::Unresolved
        );
    }

    #[test]
    fn a_relative_typescript_alias_is_read_from_the_importing_directory() {
        let mut table = SymbolTable::default();
        table.insert(
            "convert".to_string(),
            nid(0),
            PathBuf::from("src/format.ts"),
        );
        table.insert(
            "convert".to_string(),
            nid(1),
            PathBuf::from("lib/format.ts"),
        );
        table.insert(
            "convert".to_string(),
            nid(2),
            PathBuf::from("src/utils/index.ts"),
        );
        let caller = Path::new("src/app.ts");
        assert_eq!(
            table.resolve_imported("convert", "./format", caller),
            Resolution::ViaImport(nid(0))
        );
        assert_eq!(
            table.resolve_imported("convert", "../lib/format.js", caller),
            Resolution::ViaImport(nid(1))
        );
        assert_eq!(
            table.resolve_imported("convert", "./utils", caller),
            Resolution::ViaImport(nid(2))
        );
        assert_eq!(
            table.resolve_imported("convert", "./missing", caller),
            Resolution::Unresolved
        );
        assert_eq!(
            table.resolve_imported("convert", "../../../format", caller),
            Resolution::Unresolved
        );
    }

    #[test]
    fn methods_and_other_languages_are_not_imported_names() {
        let mut table = SymbolTable::default();
        table.insert(
            "Ledger.convert".to_string(),
            nid(0),
            PathBuf::from("money.py"),
        );
        table.insert("convert".to_string(), nid(1), PathBuf::from("money.ts"));
        assert_eq!(
            table.resolve_imported("convert", "money", Path::new("orders.py")),
            Resolution::Unresolved
        );
    }
}