bonsai-ninja-resolve 0.2.3

Module and name resolution.
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
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
//! Module + name resolution.
//!
//! Resolution is inherently language-specific; this crate provides the
//! shared data model and a simple import-graph traversal that most
//! adapters can reuse.

use ahash::{AHashMap, AHashSet};
use bonsai_common::{qualified_name_segments, short_qualified_tail, FileId, SymbolId};
use bonsai_index::GlobalIndex;
use bonsai_lang_api::{
    module_local_binding, AliasTarget, DeclKind, ImportSpec, ModulePath, ModulePathSyntax, Visibility,
    WILDCARD_IMPORT_ALIAS_PREFIX,
};
use std::{borrow::Cow, sync::Arc};

/// Caller-side context the resolver consults when narrowing a
/// candidate set. Built by callgraph / taint / matcher at edge-
/// construction or propagation time. See
/// `docs/contributing/design-patterns.mdx::Semantic Resolution Always`.
///
/// Required fields:
///
/// - `caller_file`: which file the call site lives in. Used to
///   filter `Visibility::Private` candidates declared in other files.
/// - `caller_module`: the caller's module / package / crate path.
///   Used to filter `Visibility::Module` and `Visibility::Crate`
///   candidates whose `module_path` does not match.
///
/// Optional narrowings:
///
/// - `receiver_type`: when the call site is `obj.method(...)` and
///   `typeof(obj)` is known, the resolver retains only candidates
///   whose `Decl.parent` is the receiver type (or in its subtype
///   chain). When `None`, no receiver-type filter applies.
/// - `alias_map`: caller-local imports; the resolver may rewrite
///   `name` through this map before lookup.
/// - `file_path_lookup`: workspace file paths used only as a
///   semantic backstop when an import path is more precise than an
///   adapter-populated module path.
#[derive(Clone, Debug)]
pub struct ResolveContext<'a> {
    pub caller_file: FileId,
    pub caller_module: &'a ModulePath,
    pub receiver_type: Option<SymbolId>,
    pub alias_map: Option<&'a AHashMap<String, AliasTarget>>,
    pub file_path_lookup: Option<FilePathLookup<'a>>,
    pub file_path_match_lookup: Option<FilePathMatchLookup<'a>>,
    /// Adapter-owned syntax/linkage fact. When false, unqualified calls do
    /// not cross a file module merely because another declaration is nearby.
    pub same_directory_unqualified_calls: bool,
    /// Adapter-owned source prefixes for rooted qualified names.
    pub module_path_syntax: ModulePathSyntax,
}

impl<'a> ResolveContext<'a> {
    #[must_use]
    pub fn new(caller_file: FileId, caller_module: &'a ModulePath) -> Self {
        Self {
            caller_file,
            caller_module,
            receiver_type: None,
            alias_map: None,
            file_path_lookup: None,
            file_path_match_lookup: None,
            same_directory_unqualified_calls: false,
            module_path_syntax: ModulePathSyntax::none(),
        }
    }

    #[must_use]
    pub fn with_receiver_type(mut self, receiver_type: SymbolId) -> Self {
        self.receiver_type = Some(receiver_type);
        self
    }

    #[must_use]
    pub fn with_alias_map(mut self, alias_map: &'a AHashMap<String, AliasTarget>) -> Self {
        self.alias_map = Some(alias_map);
        self
    }

    #[must_use]
    pub fn with_file_path_lookup(mut self, lookup: &'a dyn Fn(FileId) -> Option<String>) -> Self {
        self.file_path_lookup = Some(FilePathLookup { lookup });
        self
    }

    #[must_use]
    pub fn with_file_path_match_lookup(mut self, lookup: &'a dyn Fn(&str, FileId) -> bool) -> Self {
        self.file_path_match_lookup = Some(FilePathMatchLookup { lookup });
        self
    }

    #[must_use]
    pub fn with_same_directory_unqualified_calls(mut self, enabled: bool) -> Self {
        self.same_directory_unqualified_calls = enabled;
        self
    }

    #[must_use]
    pub fn with_module_path_syntax(mut self, syntax: ModulePathSyntax) -> Self {
        self.module_path_syntax = syntax;
        self
    }
}

#[derive(Clone, Copy)]
pub struct FilePathLookup<'a> {
    lookup: &'a dyn Fn(FileId) -> Option<String>,
}

impl<'a> FilePathLookup<'a> {
    fn path_for(self, file: FileId) -> Option<String> {
        (self.lookup)(file)
    }
}

impl std::fmt::Debug for FilePathLookup<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("FilePathLookup(..)")
    }
}

#[derive(Clone, Copy)]
pub struct FilePathMatchLookup<'a> {
    lookup: &'a dyn Fn(&str, FileId) -> bool,
}

impl<'a> FilePathMatchLookup<'a> {
    fn matches(self, target_module: &str, file: FileId) -> bool {
        (self.lookup)(target_module, file)
    }
}

impl std::fmt::Debug for FilePathMatchLookup<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("FilePathMatchLookup(..)")
    }
}

/// Returns true when `decl` is reachable from the caller described
/// by `ctx`, given the decl's `Visibility` and `module_path`. This
/// is the central semantic-identity filter: it never inspects
/// identifier text.
#[must_use]
pub fn visibility_allows(
    decl: &bonsai_lang_api::Decl,
    decl_file: FileId,
    decl_module: &ModulePath,
    ctx: &ResolveContext<'_>,
) -> bool {
    match decl.visibility {
        Visibility::Public | Visibility::Protected | Visibility::Internal => true,
        Visibility::Private => {
            // Private is file-scoped. When the adapter has not yet
            // populated `module_path`, both sides are empty and we
            // treat private as file-only — the strictest correct
            // interpretation. Once `module_path` is populated,
            // file-equality is still the right test for `Private`
            // in every supported language.
            decl_file == ctx.caller_file
        }
        Visibility::Module => {
            // Module-private. Empty caller_module or empty
            // decl_module means "no module boundary applicable" —
            // we fall back to file-equality so we never widen a
            // private candidate to the whole workspace.
            if decl_module.is_empty() || ctx.caller_module.is_empty() {
                decl_file == ctx.caller_file
            } else {
                decl_module.matches(ctx.caller_module)
            }
        }
        Visibility::Crate => {
            // Crate-private. Reuse the top-level segment as the
            // crate boundary (Rust `pub(crate)`, Kotlin
            // `internal`). Empty falls back to file-equality.
            if decl_module.is_empty() || ctx.caller_module.is_empty() {
                decl_file == ctx.caller_file
            } else {
                decl_module.shares_top_segment(ctx.caller_module)
            }
        }
    }
}

/// Resolve a callee identifier to every matching callable decl in
/// the workspace, narrowed by caller context.
///
/// This is the semantic-identity entry point. It consults
/// `Decl.visibility`, `Decl.module_path`, and (when `ctx.receiver_type`
/// is `Some`) `Decl.parent` to drop candidates that are not reachable
/// from the call site. Empty result means the call escapes the
/// workspace; the inter pass treats that as external.
///
/// See `docs/contributing/design-patterns.mdx::Semantic Resolution Always`. Drift
/// guard `engine_resolves_via_context_not_bare_name` enforces that
/// no engine path bypasses this primitive.
#[must_use]
pub fn resolve_callable_with_context(
    global: &GlobalIndex,
    name: &str,
    ctx: &ResolveContext<'_>,
) -> Vec<bonsai_common::FuncId> {
    use bonsai_lang_api::DeclKind;
    let collect = |lookup: &str| {
        global
            // CONTEXTLESS_LOOKUP_JUSTIFICATION: this is the semantic
            // resolver primitive; ResolveContext filtering is applied
            // immediately below before any candidate leaves the
            // function.
            .find_by_name(lookup)
            .iter()
            .filter_map(|symbol| {
                let decl = global.decl_of(*symbol)?;
                let decl_file = global.declaring_file(*symbol)?;
                Some((decl, decl_file))
            })
            .filter(|(decl, _)| {
                matches!(
                    decl.kind,
                    DeclKind::Function | DeclKind::Method | DeclKind::Constructor
                )
            })
            .filter(|(decl, decl_file)| visibility_allows(decl, *decl_file, &decl.module_path, ctx))
            .filter(|(decl, _)| match ctx.receiver_type {
                Some(recv) => method_parent_matches_receiver_type(global, decl.parent, recv, ctx),
                None => true,
            })
            .map(|(decl, _)| bonsai_common::FuncId::new(decl.symbol.raw()))
            .collect::<Vec<_>>()
    };
    let collect_caller_lexical_scope = |lookup: &str| {
        let mut out = collect(lookup);
        retain_caller_lexical_func_candidates(global, &mut out, ctx);
        out
    };
    let resolve_alias = |lookup: &str| {
        let mut out = Vec::new();
        if let Some(rewrite) = rewrite_through_alias_map_with_target(lookup, ctx) {
            out = collect(&rewrite.rewritten);
            if out.is_empty() {
                // Only module/namespace aliases get a bare-tail retry,
                // and even then candidates are retained only when they
                // live in that module. Type aliases such as
                // `value -> String` must not turn `value.equals` into a
                // workspace-wide `equals` lookup.
                let tail = bonsai_common::short_qualified_tail(&rewrite.rewritten);
                if let (Some(target_module), true) =
                    (rewrite.target_module.as_deref(), tail != rewrite.rewritten)
                {
                    out = collect(tail);
                    out.retain(|func| candidate_in_alias_target(global, *func, target_module, ctx));
                }
            }
        }
        out
    };

    let mut out = collect_caller_lexical_scope(name);
    // Walk the alias map: `cp.exec` where `cp = require("child_process")`
    // should resolve to `child_process.exec`. Without this rewrite,
    // in-workspace aliased calls miss and entry-point inference
    // flags called functions as unreferenced sources. The exact
    // rewrite trusts the rewrite — if the resolver finds a decl
    // by the rewritten name, that IS the match. The bare-name
    // fallback (when the exact rewrite doesn't hit) is the only
    // path that needs the alias-target filter, because
    // `collect(tail)` is a workspace-wide leaf lookup that would
    // otherwise stitch together unrelated workspace functions.
    if out.is_empty() {
        out = resolve_alias(name);
    }
    if out.is_empty() && unqualified_lookup_name(name) {
        for target_module in wildcard_import_modules(ctx) {
            let mut candidates = collect(name);
            candidates.retain(|func| candidate_in_alias_target(global, *func, target_module, ctx));
            out.extend(candidates);
        }
        dedup_func_ids(&mut out);
    }
    if out.is_empty() {
        if let Some((receiver, method)) = split_member_head_tail(name) {
            out = resolve_callable_member_with_context(global, receiver, method, ctx);
        }
    }
    // Workspace-rooted qualified call: `crate::X::Y` (Rust),
    // `\Foo\Bar::baz` (PHP global namespace), `::ns::fn` (C++) —
    // strip the language-specific absolute-path prefix and treat
    // the remainder as `<module_path>::<fn>` against workspace
    // decls whose canonical `module_path` matches. This is the
    // catch-all for languages where the path itself names the
    // target without going through an `import` or `use` alias.
    if out.is_empty() {
        out = resolve_workspace_rooted_call(global, name, ctx);
    }
    out
}

fn unqualified_lookup_name(name: &str) -> bool {
    let trimmed = name.trim();
    !trimmed.is_empty() && bonsai_common::qualified_name_owner(trimmed).is_none()
}

fn wildcard_import_modules<'a>(ctx: &'a ResolveContext<'_>) -> Vec<&'a str> {
    let Some(map) = ctx.alias_map else {
        return Vec::new();
    };
    let mut modules = Vec::new();
    for (key, target) in map {
        if !key.starts_with(WILDCARD_IMPORT_ALIAS_PREFIX) {
            continue;
        }
        if let AliasTarget::Namespace { module } = target {
            if !module.is_empty() && !modules.iter().any(|seen| seen == module) {
                modules.push(module.as_str());
            }
        }
    }
    modules
}

/// Retain only declarations that an unqualified reference can reach
/// without import / receiver / module-qualifier evidence. A public
/// declaration elsewhere in the workspace is not enough: visibility
/// answers "may this be called once named", not "does this call name
/// that declaration".
fn retain_caller_lexical_func_candidates(
    global: &GlobalIndex,
    candidates: &mut Vec<bonsai_common::FuncId>,
    ctx: &ResolveContext<'_>,
) {
    candidates.retain(|func| {
        let sym = SymbolId::new(func.raw());
        let Some(decl) = global.decl_of(sym) else {
            return false;
        };
        let Some(decl_file) = global.declaring_file(sym) else {
            return false;
        };
        candidate_in_caller_lexical_scope(decl, decl_file, ctx)
    });
}

fn retain_caller_lexical_symbol_candidates(
    global: &GlobalIndex,
    candidates: &mut Vec<SymbolId>,
    ctx: &ResolveContext<'_>,
) {
    candidates.retain(|symbol| {
        let Some(decl) = global.decl_of(*symbol) else {
            return false;
        };
        let Some(decl_file) = global.declaring_file(*symbol) else {
            return false;
        };
        candidate_in_caller_lexical_scope(decl, decl_file, ctx)
    });
}

fn candidate_in_caller_lexical_scope(
    decl: &bonsai_lang_api::Decl,
    decl_file: FileId,
    ctx: &ResolveContext<'_>,
) -> bool {
    if matches!(
        decl.kind,
        bonsai_lang_api::DeclKind::Method | bonsai_lang_api::DeclKind::Constructor
    ) {
        return decl_file == ctx.caller_file;
    }
    decl_file == ctx.caller_file
        || (!decl.module_path.is_empty() && decl.module_path.matches(ctx.caller_module))
        || same_directory_unqualified_module_candidate(decl, decl_file, ctx)
}

fn same_directory_unqualified_module_candidate(
    decl: &bonsai_lang_api::Decl,
    decl_file: FileId,
    ctx: &ResolveContext<'_>,
) -> bool {
    if decl_file == ctx.caller_file {
        return false;
    }
    let Some(lookup) = ctx.file_path_lookup else {
        return false;
    };
    let Some(decl_path) = lookup.path_for(decl_file) else {
        return false;
    };
    let Some(caller_path) = lookup.path_for(ctx.caller_file) else {
        return false;
    };
    if (!decl.module_path.is_empty() || !ctx.caller_module.is_empty())
        && !ctx.same_directory_unqualified_calls
    {
        return false;
    }
    file_parent_dir(&decl_path).is_some_and(|decl_dir| file_parent_dir(&caller_path) == Some(decl_dir))
}

fn file_parent_dir(path: &str) -> Option<&str> {
    let trimmed = path.trim();
    let idx = trimmed.rfind(['/', '\\'])?;
    Some(&trimmed[..idx])
}

/// Final-fallback resolver for fully-qualified workspace paths
/// that don't go through the alias map. Handles Rust `crate::`,
/// PHP / C++ `\Foo\Bar` / `::ns::fn`, and bare `<mod>::<fn>` calls
/// where the head segment IS a workspace module identifier.
///
/// The search is constrained by
/// [`module_target_matches_decl_module_path`] so a workspace decl
/// is only returned when its `module_path` actually suffix-matches
/// the call's module head — no bare-name fan-out across unrelated
/// workspace functions.
fn resolve_workspace_rooted_call(
    global: &GlobalIndex,
    name: &str,
    ctx: &ResolveContext<'_>,
) -> Vec<bonsai_common::FuncId> {
    use bonsai_lang_api::DeclKind;
    let stripped = strip_module_path_prefix(name, ctx.module_path_syntax);
    if stripped.is_empty() {
        return Vec::new();
    }
    let Some((mod_path, fn_name)) = split_module_call_tail(stripped) else {
        return Vec::new();
    };
    if mod_path.is_empty() || fn_name.is_empty() {
        return Vec::new();
    }
    let mut out = Vec::new();
    // CONTEXTLESS_LOOKUP_JUSTIFICATION: workspace-rooted resolver
    // primitive. Caller already split a `<mod_path>::<fn_name>`
    // shape; the candidate list is then narrowed by
    // `module_target_matches_decl_module_path` + `visibility_allows`
    // so no bare-name fan-out leaves this function.
    for sym in global.find_by_name(fn_name) {
        let Some(decl) = global.decl_of(*sym) else {
            continue;
        };
        if !matches!(
            decl.kind,
            DeclKind::Function | DeclKind::Method | DeclKind::Constructor
        ) {
            continue;
        }
        let Some(decl_file) = global.declaring_file(*sym) else {
            continue;
        };
        if !visibility_allows(decl, decl_file, &decl.module_path, ctx) {
            continue;
        }
        if !module_target_matches_decl_module_path(mod_path, &decl.module_path)
            && !alias_target_matches_file(ctx, mod_path, decl_file)
        {
            continue;
        }
        out.push(bonsai_common::FuncId::new(decl.symbol.raw()));
    }
    dedup_func_ids(&mut out);
    out
}

/// Remove only rooted-name syntax declared by the active language adapter.
/// This is source normalization at the compiler boundary, not a global token
/// inventory: an empty syntax descriptor leaves the name unchanged.
#[must_use]
pub fn strip_module_path_prefix(name: &str, syntax: ModulePathSyntax) -> &str {
    let trimmed = name.trim();
    let mut rest = trimmed;
    let mut stripped_repeatable = false;
    loop {
        let Some(next) = syntax
            .repeatable_rooted_prefixes
            .iter()
            .find_map(|prefix| rest.strip_prefix(prefix))
        else {
            break;
        };
        rest = next;
        stripped_repeatable = true;
    }
    if stripped_repeatable {
        return rest;
    }
    syntax
        .rooted_prefixes
        .iter()
        .find_map(|prefix| trimmed.strip_prefix(prefix))
        .unwrap_or(trimmed)
}

/// Split a compiler-qualified callable into its module owner and terminal
/// name without interpreting source-language punctuation.
fn split_module_call_tail(name: &str) -> Option<(&str, &str)> {
    bonsai_common::split_qualified_name_owner_tail(name)
}

fn resolve_callable_member_with_context(
    global: &GlobalIndex,
    receiver: &str,
    method: &str,
    ctx: &ResolveContext<'_>,
) -> Vec<bonsai_common::FuncId> {
    use bonsai_lang_api::DeclKind;
    if receiver.trim().is_empty() || method.trim().is_empty() {
        return Vec::new();
    }
    let mut out = Vec::new();
    for class_sym in resolve_class(global, receiver, ctx) {
        let Some(class_file) = global.declaring_file(class_sym) else {
            continue;
        };
        for decl in global.decls_in(class_file) {
            if decl.parent != Some(class_sym) {
                continue;
            }
            if !matches!(
                decl.kind,
                DeclKind::Function | DeclKind::Method | DeclKind::Constructor
            ) {
                continue;
            }
            if decl.name != method && short_qualified_tail(&decl.name) != method {
                continue;
            }
            let Some(decl_file) = global.declaring_file(decl.symbol) else {
                continue;
            };
            if !visibility_allows(decl, decl_file, &decl.module_path, ctx) {
                continue;
            }
            out.push(bonsai_common::FuncId::new(decl.symbol.raw()));
        }
    }
    dedup_func_ids(&mut out);
    out
}

fn split_member_head_tail(name: &str) -> Option<(&str, &str)> {
    bonsai_common::split_qualified_name_owner_tail(name)
}

fn method_parent_matches_receiver_type(
    global: &GlobalIndex,
    method_parent: Option<SymbolId>,
    receiver_type: SymbolId,
    ctx: &ResolveContext<'_>,
) -> bool {
    let Some(method_parent) = method_parent else {
        return false;
    };
    if method_parent == receiver_type {
        return true;
    }
    let mut seen = AHashSet::new();
    let mut stack = vec![receiver_type];
    while let Some(class_sym) = stack.pop() {
        if !seen.insert(class_sym) {
            continue;
        }
        let Some(class_decl) = global.decl_of(class_sym) else {
            continue;
        };
        for base in &class_decl.bases {
            for base_sym in resolve_class(global, base, ctx) {
                if base_sym == method_parent {
                    return true;
                }
                stack.push(base_sym);
            }
        }
    }
    false
}

/// Rewrite `name` through `ctx.alias_map` and return both the
/// qualified rewrite (e.g. `child_process.exec`) and the alias
/// target descriptor so callers can constrain the bare-name
/// fallback to the workspace location the alias actually points
/// at — closing the hole that would otherwise stitch together any
/// workspace function with a matching leaf identifier.
///
/// The head/tail split is `::`-aware so qualified-call shapes like
/// Rust / C++'s `pipeline::orchestrate` yield the right tail
/// (`orchestrate`) instead of being chopped at the first `:`. The
/// dotted/colon fallback covers JS / Python / PHP shapes.
fn rewrite_through_alias_map_with_target(name: &str, ctx: &ResolveContext<'_>) -> Option<AliasRewrite> {
    rewrite_through_alias_map_with_mode(name, ctx, AliasRewriteMode::Callable)
}

fn rewrite_through_alias_map_with_type_target(name: &str, ctx: &ResolveContext<'_>) -> Option<AliasRewrite> {
    rewrite_through_alias_map_with_mode(name, ctx, AliasRewriteMode::Type)
}

#[derive(Clone, Copy)]
enum AliasRewriteMode {
    Callable,
    Type,
}

fn rewrite_through_alias_map_with_mode(
    name: &str,
    ctx: &ResolveContext<'_>,
    mode: AliasRewriteMode,
) -> Option<AliasRewrite> {
    let map = ctx.alias_map?;
    // Whole-name alias: `req` → `flask.request`.
    if let Some(target) = map.get(name) {
        return Some(alias_rewrite_from_target(target, None, mode, map));
    }
    let (head, tail) = split_alias_head_tail(name)?;
    let target = map.get(head)?;
    Some(alias_rewrite_from_target(target, Some(tail), mode, map))
}

fn alias_rewrite_from_target(
    target: &AliasTarget,
    tail: Option<&str>,
    mode: AliasRewriteMode,
    map: &AHashMap<String, AliasTarget>,
) -> AliasRewrite {
    let mut current = target;
    let mut seen_type_names = AHashSet::new();
    while let AliasTarget::Type { type_name } = current {
        if !seen_type_names.insert(type_name.as_str()) {
            break;
        }
        let Some(resolved) = map.get(type_name) else {
            break;
        };
        current = resolved;
    }
    let rewritten = match tail {
        Some(tail) => current.rewrite_with_tail(tail),
        None => match mode {
            AliasRewriteMode::Callable => current.callable_target_text(),
            AliasRewriteMode::Type => current.target_text(),
        },
    };
    AliasRewrite::from_target(
        current,
        rewritten,
        matches!(mode, AliasRewriteMode::Type) && tail.is_some(),
    )
}

/// Split `name` into (head, tail) using the longest-form module
/// separator first so `pipeline::orchestrate` yields `("pipeline",
/// "orchestrate")` rather than `("pipeline", ":orchestrate")`.
fn split_alias_head_tail(name: &str) -> Option<(&str, &str)> {
    if let Some((head, tail)) = name.split_once("::") {
        return Some((head, tail));
    }
    if let Some((head, tail)) = name.split_once('.') {
        return Some((head, tail));
    }
    if let Some((head, tail)) = name.split_once(':') {
        return Some((head, tail));
    }
    None
}

/// Result of an alias-map rewrite, including the workspace target
/// the alias points at (when it's a module-path target) so callers
/// can constrain the bare-name fallback to that target.
#[derive(Clone, Debug)]
struct AliasRewrite {
    rewritten: String,
    /// `Some(module)` for [`AliasTarget::Namespace`] and
    /// [`AliasTarget::Member`] aliases — the dotted module identity
    /// the alias points at. `None` for [`AliasTarget::Type`] aliases
    /// so unresolved external types cannot fall back to a bare method
    /// name elsewhere in the workspace.
    target_module: Option<String>,
}

impl AliasRewrite {
    fn from_target(target: &AliasTarget, rewritten: String, nested_type_member: bool) -> Self {
        let target_module = match target {
            AliasTarget::Namespace { module } if !module.trim().is_empty() => Some(module.clone()),
            AliasTarget::Member { module, member }
                if nested_type_member && !module.trim().is_empty() && !member.trim().is_empty() =>
            {
                // `use parent::{child}` followed by `child::Type` makes the
                // imported member a namespace segment. Constraining a bare
                // fallback to only `parent` would admit same-named types from
                // sibling modules (for example `runtime::Handle` for
                // `runtime::scheduler::Handle`).
                Some(format!("{module}.{member}"))
            }
            AliasTarget::Member { module, .. } if !module.trim().is_empty() => Some(module.clone()),
            _ => None,
        };
        Self {
            rewritten,
            target_module,
        }
    }
}

trait AliasTargetExt {
    fn target_text(&self) -> String;
    fn callable_target_text(&self) -> String;
    fn rewrite_with_tail(&self, tail: &str) -> String;
}

impl AliasTargetExt for AliasTarget {
    fn target_text(&self) -> String {
        match self {
            AliasTarget::Member { module, member } => format!("{module}.{member}"),
            AliasTarget::Namespace { module } => module.clone(),
            AliasTarget::Type { type_name } => type_name.clone(),
        }
    }

    fn callable_target_text(&self) -> String {
        match self {
            AliasTarget::Member { module, member } => format!("{module}.{member}"),
            // A namespace import denotes the module object, not a callable
            // default export. Adapters that lower a real default import emit
            // `AliasTarget::Member { member: <adapter export name> }`; the
            // language-neutral resolver must not invent that member.
            AliasTarget::Namespace { module } => module.clone(),
            AliasTarget::Type { type_name } => type_name.clone(),
        }
    }

    fn rewrite_with_tail(&self, tail: &str) -> String {
        let prefix = match self {
            AliasTarget::Namespace { module } => module.clone(),
            AliasTarget::Member { module, member } => format!("{module}.{member}"),
            AliasTarget::Type { type_name } => type_name.clone(),
        };
        format!("{prefix}.{tail}")
    }
}

/// True when `target_module` (a dotted module identity from an
/// alias target) is a suffix of `decl_module`'s segments. A bare
/// leaf alias (`AuthService`) hits a decl declared inside
/// `MyApp.AuthService`; a fully-qualified alias is matched by the
/// equality case of the same suffix test.
///
/// The check is tolerant of two divergences between the alias
/// text and the decl's canonical module identity:
///
/// 1. Path-style separators (`/`) and dot-style separators (`.`)
///    both split into segments, so Dart `package:foo/foo.dart`
///    (after the `package:` strip) and Java `com.example.Utils`
///    both decompose correctly.
/// 2. A trailing segment that doesn't appear in the decl's
///    module_path is dropped before retrying the suffix match.
///    This handles two real shapes uniformly:
///     - file-extension-only trailers (Dart `storage.dart` vs
///       decl `storage`),
///     - class-name trailers in dotted package-qualified imports
///       (Java `com.example.Utils` vs decl module `com.example`,
///       since the class name lives in `decl.name`/`decl.parent`,
///       not the module_path).
///
///    The drop is unconditional rather than driven by a
///    file-extension allow-list — the suffix match itself
///    enforces the constraint.
#[must_use]
pub fn module_target_matches_decl_module_path(
    target_module: &str,
    decl_module: &bonsai_lang_api::ModulePath,
) -> bool {
    module_target_matches_decl_module_path_with_syntax(target_module, decl_module, ModulePathSyntax::none())
}

/// Adapter-aware form of [`module_target_matches_decl_module_path`].
#[must_use]
pub fn module_target_matches_decl_module_path_with_syntax(
    target_module: &str,
    decl_module: &bonsai_lang_api::ModulePath,
    syntax: ModulePathSyntax,
) -> bool {
    module_target_matches_decl_module_path_impl(target_module, decl_module, syntax, true)
}

/// Match a source qualifier to a declaration module without dropping its
/// final segment. Use this for a raw qualified call receiver: unlike a
/// compiler-resolved import target, `value.field.method()` carries no evidence
/// that `field` is a file extension or class-name trailer.
#[must_use]
pub fn module_target_exactly_matches_decl_module_path_with_syntax(
    target_module: &str,
    decl_module: &bonsai_lang_api::ModulePath,
    syntax: ModulePathSyntax,
) -> bool {
    module_target_matches_decl_module_path_impl(target_module, decl_module, syntax, false)
}

fn module_target_matches_decl_module_path_impl(
    target_module: &str,
    decl_module: &bonsai_lang_api::ModulePath,
    syntax: ModulePathSyntax,
    allow_terminal_trailer: bool,
) -> bool {
    if target_module.is_empty() || decl_module.is_empty() {
        return false;
    }
    // Import targets are adapter-classified names. Split their top-level
    // identifier runs structurally; the resolver must not carry a union of
    // source-language namespace separators.
    let target_module = strip_module_path_prefix(target_module, syntax);
    let target_module = target_module.trim_matches(bonsai_common::is_name_punctuation);
    let target_segments = bonsai_common::qualified_name_segments(target_module);
    if target_segments.is_empty() {
        return false;
    }
    let decl_segments = &decl_module.segments;
    if try_suffix_match(&target_segments, decl_segments) {
        return true;
    }
    if allow_terminal_trailer && target_segments.len() > 1 {
        let trimmed = &target_segments[..target_segments.len() - 1];
        if try_suffix_match(trimmed, decl_segments) {
            return true;
        }
    }
    false
}

fn try_suffix_match(target: &[&str], decl: &[String]) -> bool {
    if target.is_empty() || target.len() > decl.len() {
        return false;
    }
    let suffix_start = decl.len() - target.len();
    decl[suffix_start..]
        .iter()
        .zip(target.iter())
        .all(|(decl_seg, target_seg)| decl_seg == target_seg)
}

/// Filter the alias-rewrite bare-name fallback candidates to those
/// whose decl actually lives in the alias's target module. Without
/// this constraint the `collect(tail)` retry inside the rewrite
/// path would stitch together any workspace function with a
/// matching leaf identifier — turning `Envelope::method` (where
/// `Envelope` was a type-only import) into an entry pointing at
/// some unrelated `method()` decl elsewhere in the workspace.
fn candidate_in_alias_target(
    global: &GlobalIndex,
    func: bonsai_common::FuncId,
    target_module: &str,
    ctx: &ResolveContext<'_>,
) -> bool {
    symbol_in_alias_target(global, SymbolId::new(func.raw()), target_module, ctx)
}

fn symbol_in_alias_target(
    global: &GlobalIndex,
    symbol: SymbolId,
    target_module: &str,
    ctx: &ResolveContext<'_>,
) -> bool {
    let Some(decl) = global.decl_of(symbol) else {
        return false;
    };
    if module_target_matches_decl_module_path_from_context(target_module, &decl.module_path, ctx) {
        return true;
    }
    let Some(decl_file) = global.declaring_file(symbol) else {
        return false;
    };
    alias_target_matches_file(ctx, target_module, decl_file)
}

fn alias_target_matches_file(ctx: &ResolveContext<'_>, target_module: &str, file: FileId) -> bool {
    let target_module = strip_module_path_prefix(target_module, ctx.module_path_syntax);
    if let Some(lookup) = ctx.file_path_match_lookup {
        return lookup.matches(target_module, file);
    }
    ctx.file_path_lookup
        .and_then(|lookup| lookup.path_for(file))
        .is_some_and(|path| module_target_matches_path(target_module, &path))
}

fn module_target_matches_decl_module_path_from_context(
    target_module: &str,
    decl_module: &bonsai_lang_api::ModulePath,
    ctx: &ResolveContext<'_>,
) -> bool {
    if let Some(target_segments) = relative_module_target_segments(target_module, ctx.caller_module) {
        return decl_module.segments == target_segments;
    }
    module_target_matches_decl_module_path_with_syntax(target_module, decl_module, ctx.module_path_syntax)
}

fn relative_module_target_segments(
    target_module: &str,
    caller_module: &bonsai_lang_api::ModulePath,
) -> Option<Vec<String>> {
    let target = target_module.trim();
    if !(target == "."
        || target == ".."
        || target.starts_with("./")
        || target.starts_with("../")
        || target.starts_with(".\\")
        || target.starts_with("..\\"))
    {
        return None;
    }
    if caller_module.segments.is_empty() {
        return None;
    }
    let normalized = target.replace('\\', "/");
    let mut segments = caller_module.segments.clone();
    segments.pop();
    for raw in normalized.split('/') {
        let part = raw.trim();
        if part.is_empty() || part == "." {
            continue;
        }
        if part == ".." {
            segments.pop()?;
            continue;
        }
        segments.push(strip_extension(part).to_string());
    }
    (!segments.is_empty()).then_some(segments)
}

/// Trim the call-argument list off a callee text. `Foo(arg)` →
/// `Foo`, `pkg::Bar(x, y)` → `pkg::Bar`. Used at sites that want to
/// compare the callee identifier to a workspace symbol without
/// being thrown off by inline arguments.
#[must_use]
pub fn callee_without_call_args(callee: &str) -> &str {
    callee.split('(').next().unwrap_or(callee).trim()
}

/// Append `func` to `out` only when it isn't already present. Tiny
/// helper but called from enough hot loops that hand-inlining the
/// `contains` check obscures intent at every call site.
pub fn push_unique_func(out: &mut Vec<bonsai_common::FuncId>, func: bonsai_common::FuncId) {
    if !out.contains(&func) {
        out.push(func);
    }
}

/// String version of [`push_unique_func`] — append `value` only if
/// not already in `out`. Used by helpers that accumulate type
/// names / candidate identifiers without producing duplicates.
pub fn push_unique_string(out: &mut Vec<String>, value: String) {
    if !value.is_empty() && !out.iter().any(|existing| existing == &value) {
        out.push(value);
    }
}

/// Strip a qualified prefix and adapter-emitted leading punctuation, then
/// drop a trailing `()`. Produces the bare
/// type-identifier form used for cross-class dispatch comparison.
/// Mirrors what callgraph and taint both used to compute inline.
#[must_use]
pub fn canonical_dispatch_type_name(name: &str) -> String {
    short_tail(name)
        .trim_start_matches(bonsai_common::is_name_punctuation)
        .trim_end_matches("()")
        .trim()
        .to_string()
}

/// Split a compiler-qualified name on its first structural boundary. Used by
/// alias-target lookups to decide whether the head names a known import alias.
#[must_use]
pub fn split_qualified_head_tail(name: &str) -> Option<(&str, &str)> {
    bonsai_common::split_qualified_name_head_tail(name)
}

/// When `name`'s head segment names a `Namespace` alias, return
/// `(module, tail)` so the caller can resolve `tail` against the
/// alias's target module. Returns `None` for any other shape.
#[must_use]
pub fn namespace_alias_target_tail<'a>(
    name: &'a str,
    alias_targets: &'a AHashMap<String, AliasTarget>,
) -> Option<(&'a str, &'a str)> {
    let (head, tail) = split_qualified_head_tail(name)?;
    match alias_targets.get(head)? {
        AliasTarget::Namespace { module } if !module.is_empty() && !tail.is_empty() => {
            Some((module.as_str(), tail))
        }
        _ => None,
    }
}

/// True when `name` is a `module_or_alias.tail` shape AND the head
/// is a known import alias. Used at edge-construction time to
/// detect calls that must be expanded through the file's alias map
/// before any direct candidate lookup.
#[must_use]
pub fn qualified_module_alias_call(name: &str, aliases: &AHashMap<String, String>) -> bool {
    let Some((head, _)) = split_qualified_head_tail(name) else {
        return false;
    };
    aliases.contains_key(head)
}

/// Expand a bare exported name into every receiver-qualified form
/// the caller's adapter declares via
/// `LanguageCapabilities::module_export_aliases`. JS/TS declare
/// `["exports", "module.exports"]`, so `foo` becomes
/// `[exports.foo, module.exports.foo, foo]`. The explicit exported
/// receiver forms are tried first because CommonJS adapters can emit
/// both `exports.foo = ...` and a bare `foo` alias for the same span;
/// the receiver-qualified fact is the higher-fidelity semantic target.
/// Languages without the convention pass `&[]` and the result is a
/// single-element vec.
#[must_use]
pub fn export_name_variants(alias_tail: &str, caller_export_aliases: &[&'static str]) -> Vec<String> {
    let mut variants = Vec::new();
    for receiver in caller_export_aliases {
        push_unique(&mut variants, format!("{receiver}.{alias_tail}"));
    }
    push_unique(&mut variants, alias_tail.to_string());
    variants
}

/// Context-free callers cannot infer super-receiver syntax. Production
/// resolution passes the owning adapter's exact token slice to
/// [`is_super_receiver_with_tokens`].
#[must_use]
pub fn is_super_receiver(receiver: &str) -> bool {
    is_super_receiver_with_tokens(receiver, &[])
}

/// Adapter-aware variant of [`is_super_receiver`]: uses the supplied
/// token slice (typically
/// `LanguageCapabilities::effective_super_receiver_tokens()`).
#[must_use]
pub fn is_super_receiver_with_tokens(receiver: &str, tokens: &[&str]) -> bool {
    let receiver = receiver
        .trim()
        .trim_start_matches(bonsai_common::is_name_punctuation);
    tokens.contains(&receiver)
}

/// True when `decl`'s parent in the global index is a class-like
/// kind (Class / Struct / Trait / Interface). Helper used by both
/// the callgraph and the taint engine when deciding whether a
/// method belongs to a virtual-dispatch hierarchy.
#[must_use]
pub fn enclosing_class_for_decl<'a>(
    global: &'a GlobalIndex,
    decl: &bonsai_lang_api::Decl,
) -> Option<&'a bonsai_lang_api::Decl> {
    use bonsai_lang_api::DeclKind;
    if let Some(parent) = decl.parent {
        if let Some(parent_decl) = global.decl_of(parent) {
            if matches!(
                parent_decl.kind,
                DeclKind::Class | DeclKind::Struct | DeclKind::Trait | DeclKind::Interface | DeclKind::Enum
            ) {
                return Some(parent_decl);
            }
        }
    }
    None
}

/// Walk every transitive base of `class_sym`, accumulating canonical
/// type names into `out`. Used to detect when one element of a
/// receiver-type set inherits from another so the more-specific
/// receiver can be retained while the broader one is dropped.
pub fn collect_transitive_base_type_names(
    global: &GlobalIndex,
    class_sym: bonsai_common::SymbolId,
    ctx: &ResolveContext<'_>,
    out: &mut AHashSet<String>,
) {
    let Some(class_decl) = global.decl_of(class_sym) else {
        return;
    };
    let Some(class_file) = global.declaring_file(class_sym) else {
        return;
    };
    let base_ctx = class_decl_context(ctx, class_file, &class_decl.module_path);
    for base in &class_decl.bases {
        let canonical = canonical_dispatch_type_name(base);
        if !out.insert(canonical) {
            continue;
        }
        for base_sym in resolve_class(global, base, &base_ctx) {
            collect_transitive_base_type_names(global, base_sym, &base_ctx, out);
        }
    }
}

/// Drop receiver type names that are super-types of another
/// receiver in the same set. When `[Child, Base]` are both
/// candidates, virtual dispatch should prefer `Child` because the
/// base is reachable transitively through the inheritance chain.
#[must_use]
pub fn prune_receiver_type_names_for_dispatch(
    type_names: Vec<String>,
    global: &GlobalIndex,
    ctx: &ResolveContext<'_>,
) -> Vec<String> {
    if type_names.len() < 2 {
        return type_names;
    }
    let canonical_types: Vec<String> = type_names
        .iter()
        .map(|name| canonical_dispatch_type_name(name))
        .collect();
    let mut inherited = AHashSet::new();
    for type_name in &type_names {
        for class_sym in resolve_class(global, type_name, ctx) {
            collect_transitive_base_type_names(global, class_sym, ctx, &mut inherited);
        }
    }
    let mut out = Vec::new();
    for (idx, type_name) in type_names.into_iter().enumerate() {
        if inherited.contains(&canonical_types[idx])
            && canonical_types
                .iter()
                .enumerate()
                .any(|(other_idx, other)| other_idx != idx && other != &canonical_types[idx])
        {
            continue;
        }
        push_unique_string(&mut out, type_name);
    }
    out
}

/// Walk a class's hierarchy, accumulating callable candidates that
/// share `method_name`. The initial method visibility is filtered
/// through the call-site `ctx`, while base-class names are resolved
/// from each class declaration's own file/module context. That keeps
/// inherited dispatch semantic for imported subclasses:
/// `pipeline.py` may know `AuditedRepository`, but
/// `AuditedRepository(Repository)` must resolve `Repository` in
/// `storage.py`, not in the caller's lexical scope. Memoisation
/// across both methods and classes prevents cycles in `bases` from
/// looping. Stops walking up the chain once a class declares the
/// method locally — the parent class's same-named method is shadowed.
pub fn collect_method_candidates_for_class(
    global: &GlobalIndex,
    class_sym: bonsai_common::SymbolId,
    method_name: &str,
    ctx: &ResolveContext<'_>,
    seen: &mut AHashSet<bonsai_common::SymbolId>,
    out: &mut Vec<bonsai_common::FuncId>,
) {
    let mut seen_classes = AHashSet::new();
    collect_method_candidates_for_class_inner(
        global,
        class_sym,
        method_name,
        ctx,
        seen,
        &mut seen_classes,
        out,
    );
}

/// Per-callgraph-build cache for class-method dispatch candidate walks.
///
/// Large Java workspaces can ask the resolver for the same
/// `(class, method, caller context)` thousands of times while building
/// the resolved call graph. Caching the completed hierarchy walk keeps
/// typed dispatch semantic without recomputing inherited method
/// candidates for every call site.
#[derive(Debug, Default)]
pub struct MethodCandidateCache {
    entries: AHashMap<MethodCandidateCacheKey, Vec<bonsai_common::FuncId>>,
    peer_class_index: Option<Arc<PeerClassIndex>>,
}

pub type PeerClassIndex = AHashMap<(String, ModulePath), Vec<SymbolId>>;

impl MethodCandidateCache {
    #[must_use]
    pub fn with_peer_class_index(peer_class_index: Arc<PeerClassIndex>) -> Self {
        Self {
            entries: AHashMap::new(),
            peer_class_index: Some(peer_class_index),
        }
    }
}

#[must_use]
pub fn build_shared_peer_class_index(global: &GlobalIndex) -> Arc<PeerClassIndex> {
    Arc::new(build_peer_class_index(global))
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
struct MethodCandidateCacheKey {
    class_sym: SymbolId,
    method_name: String,
    caller_file: FileId,
    caller_module: ModulePath,
}

impl MethodCandidateCacheKey {
    fn new(class_sym: SymbolId, method_name: &str, ctx: &ResolveContext<'_>) -> Self {
        Self {
            class_sym,
            method_name: method_name.to_string(),
            caller_file: ctx.caller_file,
            caller_module: ctx.caller_module.clone(),
        }
    }
}

/// Cached variant of [`collect_method_candidates_for_class`].
pub fn collect_method_candidates_for_class_cached(
    global: &GlobalIndex,
    class_sym: bonsai_common::SymbolId,
    method_name: &str,
    ctx: &ResolveContext<'_>,
    seen: &mut AHashSet<bonsai_common::SymbolId>,
    out: &mut Vec<bonsai_common::FuncId>,
    cache: &mut MethodCandidateCache,
) {
    let mut seen_classes = AHashSet::new();
    for func in collect_method_candidates_for_class_cached_inner(
        global,
        class_sym,
        method_name,
        ctx,
        &mut seen_classes,
        cache,
    ) {
        let sym = SymbolId::new(func.raw());
        if seen.insert(sym) {
            out.push(func);
        }
    }
}

fn collect_method_candidates_for_class_cached_inner(
    global: &GlobalIndex,
    class_sym: bonsai_common::SymbolId,
    method_name: &str,
    ctx: &ResolveContext<'_>,
    seen_classes: &mut AHashSet<bonsai_common::SymbolId>,
    cache: &mut MethodCandidateCache,
) -> Vec<bonsai_common::FuncId> {
    if !seen_classes.insert(class_sym) {
        return Vec::new();
    }
    let key = MethodCandidateCacheKey::new(class_sym, method_name, ctx);
    if let Some(cached) = cache.entries.get(&key) {
        return cached.clone();
    }
    let Some(class_decl) = global.decl_of(class_sym) else {
        return Vec::new();
    };
    if !matches!(
        class_decl.kind,
        DeclKind::Class
            | DeclKind::Struct
            | DeclKind::Trait
            | DeclKind::Interface
            | DeclKind::Enum
            | DeclKind::Import
    ) {
        return Vec::new();
    }
    let Some(class_file) = global.declaring_file(class_sym) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    let mut local_fallback = Vec::new();
    for decl in global.decls_in(class_file) {
        if decl.name != method_name {
            continue;
        }
        if !matches!(
            decl.kind,
            DeclKind::Function | DeclKind::Method | DeclKind::Constructor
        ) {
            continue;
        }
        let Some(decl_file) = global.declaring_file(decl.symbol) else {
            continue;
        };
        if !visibility_allows(decl, decl_file, &decl.module_path, ctx) {
            continue;
        }
        if decl_belongs_to_class(decl, class_sym, class_decl) {
            let func = bonsai_common::FuncId::new(decl.symbol.raw());
            if callable_decl_has_body(decl) {
                push_unique_func(&mut out, func);
            } else {
                push_unique_func(&mut local_fallback, func);
            }
        }
    }
    if !out.is_empty() {
        cache.entries.insert(key, out.clone());
        return out;
    }
    if !class_decl_has_owned_callable_body(global, class_sym, class_decl) {
        collect_peer_partial_class_method_candidates_cached(
            global,
            class_sym,
            class_decl,
            method_name,
            ctx,
            seen_classes,
            &mut out,
            cache,
        );
        if !out.is_empty() {
            cache.entries.insert(key, out.clone());
            return out;
        }
    }
    let base_ctx = class_decl_context(ctx, class_file, &class_decl.module_path);
    for base in &class_decl.bases {
        for base_sym in resolve_class(global, base, &base_ctx) {
            for func in collect_method_candidates_for_class_cached_inner(
                global,
                base_sym,
                method_name,
                ctx,
                seen_classes,
                cache,
            ) {
                push_unique_func(&mut out, func);
            }
        }
    }
    if out.is_empty() {
        out = local_fallback;
    }
    cache.entries.insert(key, out.clone());
    out
}

fn collect_method_candidates_for_class_inner(
    global: &GlobalIndex,
    class_sym: bonsai_common::SymbolId,
    method_name: &str,
    ctx: &ResolveContext<'_>,
    seen_methods: &mut AHashSet<bonsai_common::SymbolId>,
    seen_classes: &mut AHashSet<bonsai_common::SymbolId>,
    out: &mut Vec<bonsai_common::FuncId>,
) {
    use bonsai_lang_api::DeclKind;
    if !seen_classes.insert(class_sym) {
        return;
    }
    let Some(class_decl) = global.decl_of(class_sym) else {
        return;
    };
    if !matches!(
        class_decl.kind,
        DeclKind::Class
            | DeclKind::Struct
            | DeclKind::Trait
            | DeclKind::Interface
            | DeclKind::Enum
            | DeclKind::Import
    ) {
        return;
    }
    let Some(class_file) = global.declaring_file(class_sym) else {
        return;
    };
    let before = out.len();
    let mut matched_local_method = false;
    let mut local_fallback = Vec::new();
    for decl in global.decls_in(class_file) {
        if decl.name != method_name {
            continue;
        }
        if !matches!(
            decl.kind,
            DeclKind::Function | DeclKind::Method | DeclKind::Constructor
        ) {
            continue;
        }
        let Some(decl_file) = global.declaring_file(decl.symbol) else {
            continue;
        };
        if !visibility_allows(decl, decl_file, &decl.module_path, ctx) {
            continue;
        }
        if decl_belongs_to_class(decl, class_sym, class_decl) {
            if callable_decl_has_body(decl) {
                if seen_methods.insert(decl.symbol) {
                    matched_local_method = true;
                    out.push(bonsai_common::FuncId::new(decl.symbol.raw()));
                }
            } else {
                local_fallback.push(decl.symbol);
            }
        }
    }
    if matched_local_method {
        return;
    }
    if !class_decl_has_owned_callable_body(global, class_sym, class_decl)
        && collect_peer_partial_class_method_candidates(
            global,
            class_sym,
            class_decl,
            method_name,
            ctx,
            seen_methods,
            seen_classes,
            out,
        )
    {
        return;
    }
    let base_ctx = class_decl_context(ctx, class_file, &class_decl.module_path);
    for base in &class_decl.bases {
        for base_sym in resolve_class(global, base, &base_ctx) {
            collect_method_candidates_for_class_inner(
                global,
                base_sym,
                method_name,
                ctx,
                seen_methods,
                seen_classes,
                out,
            );
        }
    }
    if out.len() == before {
        for symbol in local_fallback {
            if seen_methods.insert(symbol) {
                out.push(bonsai_common::FuncId::new(symbol.raw()));
            }
        }
    }
}

#[allow(clippy::too_many_arguments)] // Mirrors the recursive class walk state.
fn collect_peer_partial_class_method_candidates(
    global: &GlobalIndex,
    class_sym: SymbolId,
    class_decl: &bonsai_lang_api::Decl,
    method_name: &str,
    ctx: &ResolveContext<'_>,
    seen_methods: &mut AHashSet<SymbolId>,
    seen_classes: &mut AHashSet<SymbolId>,
    out: &mut Vec<bonsai_common::FuncId>,
) -> bool {
    let before = out.len();
    // CONTEXTLESS_LOOKUP_JUSTIFICATION: peer partial-class stitching
    // only runs after a same-symbol class has no owned callable; the
    // candidates are narrowed to the same class-like name, visibility,
    // and semantic method ownership before any method leaves this helper.
    for peer_sym in peer_partial_class_symbols(global, class_sym, class_decl, None) {
        if peer_sym == class_sym || seen_classes.contains(&peer_sym) {
            continue;
        }
        let Some(peer_decl) = global.decl_of(peer_sym) else {
            continue;
        };
        let Some(peer_file) = global.declaring_file(peer_sym) else {
            continue;
        };
        if !matches!(
            peer_decl.kind,
            DeclKind::Class | DeclKind::Struct | DeclKind::Trait | DeclKind::Interface | DeclKind::Enum
        ) || peer_decl.name != class_decl.name
            || !peer_partial_class_matches(class_decl, class_sym, peer_decl, peer_sym, global)
            || !visibility_allows(peer_decl, peer_file, &peer_decl.module_path, ctx)
        {
            continue;
        }
        collect_method_candidates_for_class_inner(
            global,
            peer_sym,
            method_name,
            ctx,
            seen_methods,
            seen_classes,
            out,
        );
    }
    out.len() > before
}

#[allow(clippy::too_many_arguments)] // Mirrors the cached recursive class walk state.
fn collect_peer_partial_class_method_candidates_cached(
    global: &GlobalIndex,
    class_sym: SymbolId,
    class_decl: &bonsai_lang_api::Decl,
    method_name: &str,
    ctx: &ResolveContext<'_>,
    seen_classes: &mut AHashSet<SymbolId>,
    out: &mut Vec<bonsai_common::FuncId>,
    cache: &mut MethodCandidateCache,
) {
    // CONTEXTLESS_LOOKUP_JUSTIFICATION: peer partial-class stitching
    // only runs after a same-symbol class has no owned callable; the
    // candidates are narrowed to the same class-like name, visibility,
    // and semantic method ownership before any method leaves this helper.
    for peer_sym in peer_partial_class_symbols(global, class_sym, class_decl, Some(cache)) {
        if peer_sym == class_sym || seen_classes.contains(&peer_sym) {
            continue;
        }
        let Some(peer_decl) = global.decl_of(peer_sym) else {
            continue;
        };
        let Some(peer_file) = global.declaring_file(peer_sym) else {
            continue;
        };
        if !matches!(
            peer_decl.kind,
            DeclKind::Class | DeclKind::Struct | DeclKind::Trait | DeclKind::Interface | DeclKind::Enum
        ) || peer_decl.name != class_decl.name
            || !peer_partial_class_matches(class_decl, class_sym, peer_decl, peer_sym, global)
            || !visibility_allows(peer_decl, peer_file, &peer_decl.module_path, ctx)
        {
            continue;
        }
        for func in collect_method_candidates_for_class_cached_inner(
            global,
            peer_sym,
            method_name,
            ctx,
            seen_classes,
            cache,
        ) {
            push_unique_func(out, func);
        }
    }
}

fn peer_partial_class_symbols(
    global: &GlobalIndex,
    class_sym: SymbolId,
    class_decl: &bonsai_lang_api::Decl,
    cache: Option<&mut MethodCandidateCache>,
) -> Vec<SymbolId> {
    if class_decl.module_path.is_empty() {
        let Some(class_file) = global.declaring_file(class_sym) else {
            return Vec::new();
        };
        return global
            .decls_in(class_file)
            .iter()
            .filter(|decl| {
                decl.symbol != class_sym
                    && decl.name == class_decl.name
                    && matches!(
                        decl.kind,
                        DeclKind::Class
                            | DeclKind::Struct
                            | DeclKind::Trait
                            | DeclKind::Interface
                            | DeclKind::Enum
                    )
            })
            .map(|decl| decl.symbol)
            .collect();
    }

    let key = (class_decl.name.clone(), class_decl.module_path.clone());
    if let Some(cache) = cache {
        let index = cache
            .peer_class_index
            .get_or_insert_with(|| build_shared_peer_class_index(global));
        return index.get(&key).cloned().unwrap_or_default();
    }
    build_peer_class_index(global).remove(&key).unwrap_or_default()
}

fn build_peer_class_index(global: &GlobalIndex) -> PeerClassIndex {
    let mut index: PeerClassIndex = AHashMap::new();
    for file in global.all_files() {
        for decl in global.decls_in(file) {
            if decl.module_path.is_empty()
                || !matches!(
                    decl.kind,
                    DeclKind::Class
                        | DeclKind::Struct
                        | DeclKind::Trait
                        | DeclKind::Interface
                        | DeclKind::Enum
                )
            {
                continue;
            }
            index
                .entry((decl.name.clone(), decl.module_path.clone()))
                .or_default()
                .push(decl.symbol);
        }
    }
    index
}

fn peer_partial_class_matches(
    class_decl: &bonsai_lang_api::Decl,
    class_sym: SymbolId,
    peer_decl: &bonsai_lang_api::Decl,
    peer_sym: SymbolId,
    global: &GlobalIndex,
) -> bool {
    let Some(class_file) = global.declaring_file(class_sym) else {
        return false;
    };
    let Some(peer_file) = global.declaring_file(peer_sym) else {
        return false;
    };
    if class_file == peer_file {
        return true;
    }
    class_decl.module_path.matches(&peer_decl.module_path)
}

/// Whether two class-like declarations denote the same semantic type family.
///
/// Languages with split declarations (for example an Objective-C interface
/// and implementation, or C# partial classes) intentionally assign each CST
/// declaration a distinct [`SymbolId`]. Receiver-evidence filters must compare
/// their compiler identity rather than the raw symbol or they can resolve a
/// method through one declaration and then discard it because its parent is a
/// peer declaration. Empty module identities remain file-local; non-empty
/// identities must match exactly under [`ModulePath::matches`].
#[must_use]
pub fn class_symbols_share_semantic_identity(global: &GlobalIndex, left: SymbolId, right: SymbolId) -> bool {
    if left == right {
        return true;
    }
    let Some(left_decl) = global.decl_of(left) else {
        return false;
    };
    let Some(right_decl) = global.decl_of(right) else {
        return false;
    };
    let class_like = |decl: &bonsai_lang_api::Decl| {
        matches!(
            decl.kind,
            DeclKind::Class | DeclKind::Struct | DeclKind::Trait | DeclKind::Interface | DeclKind::Enum
        )
    };
    class_like(left_decl)
        && class_like(right_decl)
        && left_decl.name == right_decl.name
        && peer_partial_class_matches(left_decl, left, right_decl, right, global)
}

fn class_decl_has_owned_callable_body(
    global: &GlobalIndex,
    class_sym: SymbolId,
    class_decl: &bonsai_lang_api::Decl,
) -> bool {
    let Some(class_file) = global.declaring_file(class_sym) else {
        return false;
    };
    global.decls_in(class_file).iter().any(|decl| {
        matches!(
            decl.kind,
            DeclKind::Function | DeclKind::Method | DeclKind::Constructor
        ) && callable_decl_has_body(decl)
            && decl_belongs_to_class(decl, class_sym, class_decl)
    })
}

fn callable_decl_has_body(decl: &bonsai_lang_api::Decl) -> bool {
    decl.body_span.is_some() || !decl.flow_events.is_empty()
}

fn decl_belongs_to_class(
    decl: &bonsai_lang_api::Decl,
    class_sym: SymbolId,
    class_decl: &bonsai_lang_api::Decl,
) -> bool {
    if decl.parent == Some(class_sym) {
        return true;
    }
    if matches!(decl.kind, DeclKind::Method | DeclKind::Constructor) && decl.parent.is_some() {
        return false;
    }
    let class_span = class_decl.body_span.unwrap_or(class_decl.span);
    decl.name_span.file == class_span.file
        && decl.name_span.start >= class_span.start
        && decl.name_span.end <= class_span.end
}

fn class_decl_context<'a>(
    inherited: &ResolveContext<'a>,
    class_file: FileId,
    class_module: &'a ModulePath,
) -> ResolveContext<'a> {
    let mut ctx = ResolveContext::new(class_file, class_module);
    if let Some(alias_map) = inherited.alias_map {
        ctx = ctx.with_alias_map(alias_map);
    }
    if let Some(file_path_lookup) = inherited.file_path_lookup {
        ctx = ctx.with_file_path_lookup(file_path_lookup.lookup);
    }
    if let Some(file_path_match_lookup) = inherited.file_path_match_lookup {
        ctx = ctx.with_file_path_match_lookup(file_path_match_lookup.lookup);
    }
    ctx = ctx.with_same_directory_unqualified_calls(inherited.same_directory_unqualified_calls);
    ctx = ctx.with_module_path_syntax(inherited.module_path_syntax);
    ctx
}

/// Lift each `TypeAliasBinding` into the alias-target map as a
/// `Type` entry, but only when the local name isn't already bound.
/// Adapters surface decl `type_aliases`, the resolver consumes them
/// here so `var.method()` dispatches into the declared type's
/// methods even when `var`'s binding isn't otherwise threaded into
/// the alias map.
pub fn extend_alias_targets_with_declared_types(
    alias_targets: &mut AHashMap<String, AliasTarget>,
    type_aliases: &[bonsai_lang_api::TypeAliasBinding],
) {
    for alias in type_aliases {
        if alias.name.is_empty() || alias.type_name.is_empty() {
            continue;
        }
        alias_targets
            .entry(alias.name.clone())
            .or_insert_with(|| AliasTarget::Type {
                type_name: alias.type_name.clone(),
            });
    }
}

/// True when `alias_target` (a dotted / slashed module reference
/// from an import alias) plausibly identifies the file `file_path`.
/// Used by both the taint engine and the callgraph as a backstop
/// when [`module_target_matches_decl_module_path`] doesn't resolve —
/// e.g. workspace files that haven't yet had their module path
/// populated. Compares dotted-form parts to slash-form parts with
/// extension stripping, supporting Java-style `com.example.Utils`
/// matching `com/example/Utils.java`.
#[must_use]
pub fn module_target_matches_path(alias_target: &str, file_path: &str) -> bool {
    let target_parts = module_target_parts(alias_target);
    let path_parts = module_path_parts(file_path);
    module_target_parts_match_path_parts(&target_parts, &path_parts)
}

/// Split an alias target into the same normalized parts used by
/// [`module_target_matches_path`]. Callers that compare the same target
/// against many files can cache this vector and use
/// [`module_target_parts_match_path_parts`] directly.
#[must_use]
pub fn module_target_parts(alias_target: &str) -> Vec<String> {
    let target: Cow<'_, str> = if alias_target.contains('\\') {
        Cow::Owned(alias_target.replace('\\', "/"))
    } else {
        Cow::Borrowed(alias_target)
    };
    module_import_parts(&target)
}

/// Match pre-split module target parts against pre-split file path
/// parts. This is the allocation-free hot-path companion to
/// [`module_target_matches_path`].
#[must_use]
pub fn module_target_parts_match_path_parts(target_parts: &[String], path_parts: &[String]) -> bool {
    let Some(target_leaf) = target_parts.last() else {
        return false;
    };
    if target_parts.len() > 1 {
        if path_parts
            .windows(target_parts.len())
            .any(|window| window == target_parts)
        {
            return true;
        }
        // Workspaces are often opened below their language-level
        // module root (`import "app/util"` while the checked-out
        // target path is just `util/util.go`). Keep the match
        // semantic by requiring a real suffix of the import target to
        // appear in the candidate file path; this is path evidence,
        // not a bare callee-name fallback.
        for suffix_start in 1..target_parts.len() {
            let suffix = &target_parts[suffix_start..];
            if !suffix.is_empty()
                && suffix.len() <= path_parts.len()
                && path_parts_contains_workspace_suffix(path_parts, suffix)
            {
                return true;
            }
        }
        return false;
    }
    if path_parts
        .last()
        .is_some_and(|file| strip_extension(file) == target_leaf.as_str())
    {
        return true;
    }
    if path_parts
        .iter()
        .rev()
        .nth(1)
        .is_some_and(|parent| parent == target_leaf)
    {
        return true;
    }
    false
}

fn path_parts_contains_workspace_suffix(path_parts: &[String], suffix: &[String]) -> bool {
    if suffix.is_empty() || suffix.len() > path_parts.len() {
        return false;
    }
    if suffix.len() > 1 {
        return path_parts.windows(suffix.len()).any(|window| window == suffix);
    }
    let Some(leaf) = suffix.first() else {
        return false;
    };
    path_parts
        .iter()
        .take(path_parts.len().saturating_sub(1))
        .any(|part| part == leaf)
}

/// Split a module import target (`com.example.Utils`,
/// `mod/path/file.dart`) into its identifier segments. Files with
/// dotted shape are split on `.`, slash-shaped paths on `/`.
/// Trailing extensions and `.` / `..` segments are dropped.
#[must_use]
pub fn module_import_parts(text: &str) -> Vec<String> {
    let normalized = bonsai_common::normalize_qualified_name(text);
    let parts: Vec<&str> = if normalized.contains('/') {
        normalized.split('/').collect()
    } else {
        normalized.split('.').collect()
    };
    parts
        .into_iter()
        .filter_map(|part| {
            let part = part.trim();
            (!part.is_empty() && part != "." && part != ".." && part != "*")
                .then(|| strip_extension(part).to_string())
        })
        .collect()
}

/// Split an absolute or relative file path (`/abs/dir/file.py`,
/// `dir/file.py`) into its identifier segments. Each segment is
/// extension-stripped so `module_target_matches_path` can compare
/// dotted module form against slash-formed file path.
#[must_use]
pub fn module_path_parts(text: &str) -> Vec<String> {
    text.split(['/', '\\'])
        .filter_map(|part| {
            let part = part.trim();
            (!part.is_empty() && part != "." && part != "..").then(|| strip_extension(part).to_string())
        })
        .collect()
}

/// Drop the last `.<ext>` from a path part. Idempotent on bare
/// segments (`Utils` → `Utils`).
#[must_use]
pub fn strip_extension(part: &str) -> &str {
    part.rsplit_once('.').map_or(part, |(stem, _)| stem)
}

/// Resolve a class / type identifier to every matching class-like
/// decl reachable from the caller's context. Used by callgraph and
/// matcher when locating receiver classes for `[Type, method]`
/// rules. Same semantic-identity contract as
/// [`resolve_callable_with_context`].
#[must_use]
pub fn resolve_class(
    global: &GlobalIndex,
    name: &str,
    ctx: &ResolveContext<'_>,
) -> Vec<bonsai_common::SymbolId> {
    use bonsai_lang_api::DeclKind;
    let name = strip_module_path_prefix(name, ctx.module_path_syntax);
    let collect = |lookup: &str| {
        global
            // CONTEXTLESS_LOOKUP_JUSTIFICATION: this is the semantic
            // class/type resolver primitive; ResolveContext filtering
            // is applied immediately below before candidates leave
            // the function.
            .find_by_name(lookup)
            .iter()
            .filter_map(|symbol| {
                let decl = global.decl_of(*symbol)?;
                let decl_file = global.declaring_file(*symbol)?;
                Some((decl, decl_file))
            })
            .filter(|(decl, _)| {
                matches!(
                    decl.kind,
                    DeclKind::Class
                        | DeclKind::Struct
                        | DeclKind::Trait
                        | DeclKind::Interface
                        | DeclKind::Enum
                        | DeclKind::Import
                )
            })
            .filter(|(decl, decl_file)| visibility_allows(decl, *decl_file, &decl.module_path, ctx))
            .map(|(decl, _)| decl.symbol)
            .collect::<Vec<_>>()
    };
    let collect_caller_lexical_scope = |lookup: &str| {
        let mut candidates = collect(lookup);
        retain_caller_lexical_symbol_candidates(global, &mut candidates, ctx);
        candidates
    };
    let collect_caller_file_scope = |lookup: &str| {
        global
            .decls_in(ctx.caller_file)
            .iter()
            .filter(|decl| {
                decl.name == lookup
                    || decl
                        .qualified_name
                        .as_deref()
                        .is_some_and(|qualified| qualified == lookup)
            })
            .filter(|decl| {
                matches!(
                    decl.kind,
                    DeclKind::Class
                        | DeclKind::Struct
                        | DeclKind::Trait
                        | DeclKind::Interface
                        | DeclKind::Enum
                        | DeclKind::Import
                )
            })
            .filter(|decl| visibility_allows(decl, ctx.caller_file, &decl.module_path, ctx))
            .map(|decl| decl.symbol)
            .collect::<Vec<_>>()
    };
    let collect_relative_qualified_scope = |lookup: &str| {
        let wanted = qualified_name_segments(lookup);
        let Some(tail) = wanted.last().copied().filter(|_| wanted.len() > 1) else {
            return Vec::new();
        };
        // The qualifier itself is reachability evidence. Start from every
        // visible declaration with the exact terminal name, then retain only
        // complete qualified-name suffix matches. Applying the unqualified
        // lexical-scope gate here would incorrectly discard rooted or
        // explicitly qualified cross-module paths before their owner can be
        // checked (for example a Rust `crate::module::ReExport`).
        let mut candidates = collect(tail);
        candidates.retain(|symbol| {
            global
                .decl_of(*symbol)
                .and_then(|decl| decl.qualified_name.as_deref())
                .is_some_and(|qualified| {
                    let observed = qualified_name_segments(qualified);
                    relative_qualified_type_matches(&observed, &wanted, ctx.caller_module)
                })
        });
        candidates
    };
    let mut out = Vec::new();
    for lookup in type_lookup_variants(name) {
        out.extend(collect_caller_file_scope(&lookup));
        if !out.is_empty() {
            dedup_symbols(&mut out);
            return out;
        }
    }
    for lookup in type_lookup_variants(name) {
        out.extend(collect_relative_qualified_scope(&lookup));
        if !out.is_empty() {
            dedup_symbols(&mut out);
            return out;
        }
    }
    if let Some(rewrite) = rewrite_through_alias_map_with_type_target(name, ctx) {
        for lookup in type_lookup_variants(&rewrite.rewritten) {
            // Exact rewrite trusts the alias map — if the
            // resolver finds a class decl named exactly this,
            // that IS the alias's target. Trying this before the
            // workspace-wide bare-name fallback avoids scanning
            // thousands of same-named classes for imported types.
            out.extend(collect(&lookup));
            if !out.is_empty() {
                dedup_symbols(&mut out);
                return out;
            }
            if let Some(target_module) = rewrite.target_module.as_deref() {
                for exact_lookup in
                    alias_target_qualified_class_lookup_names(name, &lookup, target_module, ctx)
                {
                    out.extend(collect(&exact_lookup));
                }
                if !out.is_empty() {
                    dedup_symbols(&mut out);
                    return out;
                }
                for alias_lookup in alias_bound_class_lookup_names(name, &lookup) {
                    let mut candidates = collect(&alias_lookup);
                    candidates.retain(|sym| symbol_in_alias_target(global, *sym, target_module, ctx));
                    out.extend(candidates);
                }
                if !out.is_empty() {
                    dedup_symbols(&mut out);
                    return out;
                }
            }
            let tail = bonsai_common::short_qualified_tail(&lookup);
            if tail != lookup {
                // Bare-name fallback: workspace-wide lookup of
                // the leaf identifier. Constrain to the alias
                // target's module so an unrelated class with
                // the same leaf identifier doesn't get stitched
                // in as a spurious candidate.
                let mut candidates: Vec<SymbolId> = collect(tail);
                if let Some(target_module) = rewrite.target_module.as_deref() {
                    candidates.retain(|sym| {
                        global.decl_of(*sym).is_some_and(|decl| {
                            let path_match = global
                                .declaring_file(*sym)
                                .is_some_and(|file| alias_target_matches_file(ctx, target_module, file));
                            module_target_matches_decl_module_path_from_context(
                                target_module,
                                &decl.module_path,
                                ctx,
                            ) || path_match
                        })
                    });
                }
                out.extend(candidates);
                if !out.is_empty() {
                    dedup_symbols(&mut out);
                    return out;
                }
            }
        }
        dedup_symbols(&mut out);
        return out;
    }
    for lookup in type_lookup_variants(name) {
        out.extend(collect_caller_lexical_scope(&lookup));
        if !out.is_empty() {
            dedup_symbols(&mut out);
            return out;
        }
    }
    if out.is_empty() && unqualified_lookup_name(name) {
        for lookup in type_lookup_variants(name) {
            for target_module in wildcard_import_modules(ctx) {
                let mut candidates = collect(&lookup);
                candidates.retain(|symbol| symbol_in_alias_target(global, *symbol, target_module, ctx));
                out.extend(candidates);
            }
            if !out.is_empty() {
                dedup_symbols(&mut out);
                return out;
            }
        }
    }
    out
}

fn relative_qualified_type_matches(
    observed: &[&str],
    wanted: &[&str],
    caller_module: &bonsai_lang_api::ModulePath,
) -> bool {
    if observed == wanted {
        return true;
    }
    (1..=caller_module.segments.len()).rev().any(|prefix_len| {
        observed.len() == prefix_len + wanted.len()
            && observed[..prefix_len]
                .iter()
                .zip(&caller_module.segments[..prefix_len])
                .all(|(observed, expected)| *observed == expected)
            && observed[prefix_len..] == *wanted
    })
}

fn alias_target_qualified_class_lookup_names(
    local_name: &str,
    rewritten: &str,
    target_module: &str,
    ctx: &ResolveContext<'_>,
) -> Vec<String> {
    let Some(target_segments) = relative_module_target_segments(target_module, ctx.caller_module) else {
        return Vec::new();
    };
    if target_segments.is_empty() {
        return Vec::new();
    }
    let module_prefix = target_segments.join(".");
    let mut out = Vec::new();
    for alias_lookup in alias_bound_class_lookup_names(local_name, rewritten) {
        let tail = bonsai_common::short_qualified_tail(&alias_lookup).trim();
        if !tail.is_empty() {
            push_unique(&mut out, format!("{module_prefix}.{tail}"));
        }
    }
    if let Some(module_leaf) = target_segments.last() {
        push_unique(&mut out, format!("{module_prefix}.{module_leaf}"));
    }
    out
}

fn alias_bound_class_lookup_names(local_name: &str, rewritten: &str) -> Vec<String> {
    let mut out = Vec::new();
    for value in [local_name.trim(), rewritten.trim()] {
        push_unique(&mut out, value.to_string());
        let tail = bonsai_common::short_qualified_tail(value);
        if tail != value {
            push_unique(&mut out, tail.trim().to_string());
        }
    }
    out
}

fn type_lookup_variants(raw: &str) -> Vec<String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Vec::new();
    }
    let mut out = Vec::new();
    push_unique(&mut out, trimmed.to_string());
    let without_array = strip_trailing_array_suffixes(trimmed);
    push_unique(&mut out, without_array.to_string());
    let without_nullable = without_array.trim_end_matches('?').trim();
    push_unique(&mut out, without_nullable.to_string());
    let erased = erase_angle_generics(without_nullable);
    push_unique(&mut out, erased.trim().to_string());
    out
}

fn strip_trailing_array_suffixes(mut text: &str) -> &str {
    loop {
        let trimmed = text.trim_end();
        if let Some(rest) = trimmed.strip_suffix("[]") {
            text = rest.trim_end();
            continue;
        }
        return trimmed;
    }
}

fn erase_angle_generics(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    let mut depth = 0usize;
    for ch in text.chars() {
        match ch {
            '<' => depth = depth.saturating_add(1),
            '>' => depth = depth.saturating_sub(1),
            _ if depth == 0 => out.push(ch),
            _ => {}
        }
    }
    out
}

fn push_unique(out: &mut Vec<String>, value: String) {
    if !value.is_empty() && !out.iter().any(|existing| existing == &value) {
        out.push(value);
    }
}

fn dedup_symbols(out: &mut Vec<SymbolId>) {
    let mut seen = AHashSet::new();
    out.retain(|symbol| seen.insert(*symbol));
}

fn dedup_func_ids(out: &mut Vec<bonsai_common::FuncId>) {
    let mut seen = AHashSet::new();
    out.retain(|func| seen.insert(func.raw()));
}

/// Legacy bare-name resolver.
///
/// **Do not use in new code in `crates/resolve`, `crates/callgraph`,
/// `crates/taint`, or `crates/security/src/matcher.rs`.** This entry
/// point exists only for incremental migration to
/// [`resolve_callable_with_context`] and for display-only callers
/// (browse output, tracer printing) where cross-context candidate
/// expansion is acceptable. See
/// `docs/contributing/design-patterns.mdx::Semantic Resolution Always`.
#[doc(hidden)]
#[must_use]
pub fn resolve_callable(global: &GlobalIndex, name: &str) -> Vec<bonsai_common::FuncId> {
    use bonsai_lang_api::DeclKind;
    let collect = |lookup: &str| {
        global
            // CONTEXTLESS_LOOKUP_JUSTIFICATION: legacy display-only
            // resolver retained for callers that intentionally list
            // every name match; graph/taint/security edge builders
            // use resolve_callable_with_context instead.
            .find_by_name(lookup)
            .iter()
            .filter_map(|symbol| global.decl_of(*symbol))
            .filter(|decl| {
                matches!(
                    decl.kind,
                    DeclKind::Function | DeclKind::Method | DeclKind::Constructor
                )
            })
            .map(|decl| bonsai_common::FuncId::new(decl.symbol.raw()))
            .collect::<Vec<_>>()
    };
    collect(name)
}

/// Short tail after the last path separator in a qualified call /
/// reference name. Mirrors the CLI's `short_callee` helper so
/// resolver-driven lookups stay identical regardless of caller.
#[must_use]
pub fn short_tail(name: &str) -> &str {
    short_qualified_tail(name)
}

/// Build a `{local_name → resolved}` alias map from `ImportSpec`s.
/// Covers every symbol- and module-level alias shape adapters emit
/// (`from x import y as z`, `import os as o`, unaliased module
/// bindings such as `import os` / `use std::io`, Go `import "fmt"`
/// self-binding, Scala `{a => b}`, PHP / Kotlin renaming, etc.).
///
/// Source `imports` from `bonsai_db::AnalyzerDb::imports_for` so
/// every downstream pass (browse, matcher, taint reachability)
/// shares the adapter's canonical shape.
#[must_use]
pub fn alias_map_for_file(imports: &[ImportSpec]) -> AHashMap<String, String> {
    let mut map: AHashMap<String, String> = AHashMap::new();
    for import in imports {
        // Symbol-level alias: `from x import y as z` / Kotlin
        // `import x.y.z as Z` — bind `z` → `y`.
        if let (Some(local), Some(original)) = (import.alias.as_deref(), import.original_name.as_deref()) {
            if local != original && !local.is_empty() && !original.is_empty() {
                map.insert(local.to_string(), original.to_string());
            }
        }
        // Module-level alias: `import os as o` (no `original_name`)
        // → `o` → `os`. Self-binding aliases (Go's `import "fmt"`
        // emits `alias=Some("fmt")`) are kept so the taint engine
        // recognises `fmt` as an external package head.
        if let Some(local) = import.alias.as_deref() {
            if import.original_name.is_none() && !local.is_empty() && !import.module.is_empty() {
                map.entry(local.to_string())
                    .or_insert_with(|| import.module.clone());
            }
        }
        // Unaliased module import: derive the local binding from the
        // module path so qualified calls (`os.system`, `std::io::read`)
        // are treated as import-qualified. If the alias target cannot
        // resolve semantically, callers leave the edge unresolved
        // instead of retrying the bare tail.
        if !import.is_wildcard && import.alias.is_none() && import.original_name.is_none() {
            if let Some(local) = module_local_binding(&import.module) {
                map.entry(local).or_insert_with(|| import.module.clone());
            }
        }
    }
    map
}

/// Build the local binding table used by semantic graph construction.
///
/// Unlike [`alias_map_for_file`], which preserves the historical
/// local-to-short-name compatibility contract, this map retains the import's
/// module and member identity. A direct `from storage import Repository`
/// therefore contributes `Repository -> storage.Repository`, while a renamed
/// import contributes the same target under its local alias. IDG resolution
/// can then match that target against declaration/module facts exactly, just
/// as a compiler symbol table would.
#[must_use]
pub fn semantic_import_binding_map_for_file(imports: &[ImportSpec]) -> AHashMap<String, String> {
    let mut map = AHashMap::new();
    for import in imports {
        if import.is_wildcard {
            if let Some(alias) = import.alias.as_deref().filter(|alias| !alias.is_empty()) {
                map.insert(alias.to_string(), import.module.clone());
            }
            continue;
        }
        if let Some(member) = import
            .original_name
            .as_deref()
            .filter(|member| !member.is_empty())
        {
            let local = import.alias.as_deref().unwrap_or(member);
            if local.is_empty() {
                continue;
            }
            let target = if import.module.trim().is_empty() {
                member.to_string()
            } else {
                format!("{}.{}", import.module.trim(), member)
            };
            map.insert(local.to_string(), target);
            continue;
        }
        if let Some(local) = import.alias.as_deref().filter(|alias| !alias.is_empty()) {
            map.insert(local.to_string(), import.module.clone());
            continue;
        }
        if let Some(local) = module_local_binding(&import.module) {
            map.insert(local, import.module.clone());
        }
    }
    map
}

// Note: a previous version of this file shipped a Go-stdlib package
// allow-list (`looks_like_go_stdlib_subpackage`) plus an
// `add_go_stdlib_import_aliases` pass that re-scanned the source by
// regex to bind unaliased path-tails locally. Both have been deleted.
// The Go adapter (`crates/lang_go/src/lib.rs::parse_imports`) now
// emits `ImportSpec.alias = path_tail` for every unaliased Go import,
// which the standard alias block above handles uniformly. The fix
// keeps `crates/resolve` library/stdlib-agnostic per the
// `docs/contributing/taint-engine-spec.mdx` non-negotiable on hard-coded
// library/API tables in engine crates.

#[cfg(test)]
mod tests;