aft-parse 0.67.1

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

use crate::calls::extract_type_references;
use crate::imports::{parse_imports, specifier_imported_name, specifier_local_name};
use crate::parser::{grammar_for, LangId};
use serde::{Deserialize, Serialize};
use std::collections::{hash_map::Entry, BTreeMap, BTreeSet, HashMap};
use std::path::Path;
use std::sync::OnceLock;

#[derive(Default)]
pub struct FactParsers {
    parsers: HashMap<LangId, tree_sitter::Parser>,
}

impl FactParsers {
    pub fn parse_source(&mut self, lang: LangId, source: &str) -> Option<tree_sitter::Tree> {
        // Markdown nested too deeply would abort the process in its grammar.
        if crate::parser::markdown_too_deep_to_parse(lang, source) {
            return None;
        }
        let parser = match self.parsers.entry(lang) {
            Entry::Occupied(entry) => entry.into_mut(),
            Entry::Vacant(entry) => {
                let grammar = grammar_for(lang).ok()?;
                let mut parser = tree_sitter::Parser::new();
                if parser.set_language(&grammar).is_err() {
                    return None;
                }
                entry.insert(parser)
            }
        };

        parser.parse(source, None)
    }
}

pub const RUST_MACRO_REF_SHAPE_CALL: &str = "call";
pub const RUST_MACRO_REF_SHAPE_METHOD: &str = "method";
pub const RUST_MACRO_REF_SHAPE_STRUCT: &str = "struct";
pub const TOP_LEVEL_SYMBOL: &str = "<top-level>";
#[derive(Debug, Default)]
pub struct FileAnalysis {
    pub oversized: bool,
    pub freshness: Option<crate::cache_freshness::FileFreshness>,
    pub rust_api: Option<RustApiFacts>,
    pub go_dispatch: Option<GoDispatchFacts>,
    pub raw_imports: Vec<RawImportContribution>,
    pub rust_imports: Vec<RawImportContribution>,
    pub raw_reexports: Vec<RawReexportContribution>,
    pub attribute_entry_points: Vec<String>,
    pub macro_token_refs: Vec<MacroTokenRefContribution>,
    pub cfg_test_ranges: Vec<RustCfgTestRange>,
    pub cfg_test_module_files: Vec<String>,
    pub globs_parent_module: bool,
    pub trait_impl_methods: Vec<String>,
    pub type_ref_names: BTreeSet<String>,
}

/// What dead-code analysis reads from one file's syntax tree, recorded
/// once per content when the data layer parses the file, so an analysis
/// reads it from the file's content record instead of parsing again.
///
/// Records are shared by every path with the same content, so nothing here
/// depends on the file's path: what does (the files of out-of-line modules,
/// a Go file's module) is completed for each path by
/// [`StoredFileFacts::into_analysis`].
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct StoredFileFacts {
    /// The source is not UTF-8 text, so analysis reads nothing from it.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub not_text: bool,
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub type_ref_names: BTreeSet<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub js: Option<StoredJsFacts>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rust: Option<StoredRustFacts>,
    /// A Go file's dispatch facts, without its module.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub go: Option<GoDispatchFacts>,
}

/// A JavaScript or TypeScript file's imports and re-exports, read when the
/// Oxc engine has no facts for the file.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct StoredJsFacts {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub raw_imports: Vec<RawImportContribution>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub raw_reexports: Vec<RawReexportContribution>,
}

/// A Rust file's facts.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct StoredRustFacts {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub imports: Vec<RawImportContribution>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub raw_reexports: Vec<RawReexportContribution>,
    /// Its API facts. A module declared out of line has a placeholder file
    /// until the file's path completes it.
    pub api: RustApiFacts,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub attribute_entry_points: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub macro_token_refs: Vec<MacroTokenRefContribution>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cfg_test_ranges: Vec<RustCfgTestRange>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cfg_test_modules: Vec<RustCfgTestModule>,
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub globs_parent_module: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub trait_impl_methods: Vec<String>,
}

impl StoredFileFacts {
    /// Whether analysis reads anything from a file in `lang`.
    pub fn read_for(lang: LangId) -> bool {
        supports_type_refs(lang)
    }

    /// The facts of `source` in `lang`, encoded for a content record:
    /// `source` as stored (the bytes of the file) and `tree`, the tree the
    /// data layer parsed it to.
    pub fn encode_for_record(source: &[u8], lang: LangId, tree: &tree_sitter::Tree) -> Vec<u8> {
        let facts = match std::str::from_utf8(source) {
            Ok(source) => Self::extract(source, lang, Some(tree)),
            Err(_) => Self {
                not_text: true,
                ..Self::default()
            },
        };
        serde_json::to_vec(&facts).unwrap_or_default()
    }

    /// Decodes facts [`Self::encode_for_record`] wrote.
    ///
    /// # Errors
    ///
    /// When the bytes are not such facts.
    pub fn decode(bytes: &[u8]) -> Result<Self, String> {
        serde_json::from_slice(bytes).map_err(|error| error.to_string())
    }

    /// The facts of `source` in `lang`, from `tree`, its syntax tree (`None`
    /// when parsing failed).
    pub fn extract(source: &str, lang: LangId, tree: Option<&tree_sitter::Tree>) -> Self {
        if !Self::read_for(lang) {
            return Self::default();
        }
        let type_ref_names = tree
            .map(|tree| extract_type_references(source, tree.root_node(), lang))
            .unwrap_or_default();
        // Oxc FileFacts are the raw TS/JS import/re-export/dynamic-import
        // facts; these are read only for a file Oxc has no facts for.
        let js = matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript).then(|| {
            StoredJsFacts {
                raw_imports: tree
                    .map(|tree| raw_imports_from_tree(source, tree, lang))
                    .unwrap_or_default(),
                raw_reexports: tree
                    .map(|tree| ts_raw_reexport_contributions(source, tree.root_node()))
                    .unwrap_or_default(),
            }
        });
        let rust = (lang == LangId::Rust).then(|| {
            // Module files depend on the file's path; they are completed
            // per path from the placeholder.
            let api = tree
                .map(|tree| rust_api_facts(source, tree.root_node(), ""))
                .unwrap_or_default();
            let attribute_entry_points = tree
                .map(|tree| {
                    let mut roots = BTreeSet::new();
                    for entry in
                        crate::parser::rust_attribute_entry_points(source, tree.root_node())
                    {
                        roots.insert(entry.name);
                        roots.insert(entry.scoped_name);
                    }
                    roots.extend(rust_serde_function_references(
                        source,
                        tree.root_node(),
                        api.items.as_slice(),
                    ));
                    roots.into_iter().collect()
                })
                .unwrap_or_default();
            StoredRustFacts {
                imports: tree
                    .map(|tree| rust_raw_import_contributions(source, tree))
                    .unwrap_or_default(),
                raw_reexports: rust_raw_reexport_contributions(source),
                attribute_entry_points,
                macro_token_refs: tree
                    .map(|tree| rust_macro_token_refs(source, tree.root_node()))
                    .unwrap_or_default(),
                cfg_test_ranges: tree
                    .map(|tree| rust_cfg_test_ranges(source, tree.root_node()))
                    .unwrap_or_default(),
                cfg_test_modules: tree
                    .map(|tree| rust_cfg_test_modules(source, tree.root_node()))
                    .unwrap_or_default(),
                globs_parent_module: tree
                    .is_some_and(|tree| rust_globs_parent_module(source, tree.root_node())),
                trait_impl_methods: tree
                    .map(|tree| rust_trait_impl_methods(source, tree.root_node()))
                    .unwrap_or_default(),
                api,
            }
        });
        let go = (lang == LangId::Go).then(|| {
            tree.map(|tree| go_dispatch_facts(source, tree.root_node()))
                .unwrap_or_default()
        });
        Self {
            not_text: false,
            type_ref_names,
            js,
            rust,
            go,
        }
    }

    /// The analysis of the file at `file` (`relative_file` from the project
    /// root), whose language is `lang`, from its facts. `has_oxc_file` says
    /// the Oxc engine has facts for it, which replace its raw imports and
    /// re-exports.
    pub fn into_analysis(
        self,
        lang: LangId,
        file: &Path,
        relative_file: &str,
        has_oxc_file: bool,
    ) -> FileAnalysis {
        if self.not_text || !Self::read_for(lang) {
            return FileAnalysis::default();
        }
        let needs_ts_raw_facts =
            matches!(lang, LangId::TypeScript | LangId::Tsx | LangId::JavaScript) && !has_oxc_file;
        let js = self.js.unwrap_or_default();
        let rust = (lang == LangId::Rust).then(|| {
            let mut rust = self.rust.unwrap_or_default();
            for module in &mut rust.api.modules {
                if module.file.is_some() {
                    let mut nested = module.scope.clone();
                    nested.push(module.name.clone());
                    module.file = Some(rust_module_file(
                        relative_file,
                        &nested,
                        module.path_override.as_deref(),
                    ));
                }
            }
            rust
        });
        let go_dispatch = (lang == LangId::Go).then(|| {
            let mut facts = self.go.unwrap_or_default();
            facts.module = go_module_dir(file, relative_file);
            facts
        });
        let raw_reexports = if needs_ts_raw_facts {
            js.raw_reexports
        } else {
            rust.as_ref()
                .map(|rust| rust.raw_reexports.clone())
                .unwrap_or_default()
        };
        let Some(rust) = rust else {
            return FileAnalysis {
                go_dispatch,
                raw_imports: if needs_ts_raw_facts {
                    js.raw_imports
                } else {
                    Vec::new()
                },
                raw_reexports,
                type_ref_names: self.type_ref_names,
                ..FileAnalysis::default()
            };
        };
        FileAnalysis {
            oversized: false,
            freshness: None,
            go_dispatch,
            raw_imports: Vec::new(),
            raw_reexports,
            cfg_test_module_files: rust_cfg_test_module_files_for(
                relative_file,
                &rust.cfg_test_modules,
            ),
            rust_api: Some(rust.api),
            rust_imports: rust.imports,
            attribute_entry_points: rust.attribute_entry_points,
            macro_token_refs: rust.macro_token_refs,
            cfg_test_ranges: rust.cfg_test_ranges,
            globs_parent_module: rust.globs_parent_module,
            trait_impl_methods: rust.trait_impl_methods,
            type_ref_names: self.type_ref_names,
        }
    }
}

/// The directory of the Go module the file at `file` (`relative_file` from
/// the project root) belongs to, relative to the root: the nearest
/// directory above it holding a `go.mod`, or the root's own when none does.
pub fn go_module_dir(file: &Path, relative_file: &str) -> String {
    let mut module = String::new();
    let mut relative = Path::new(relative_file).parent().unwrap_or(Path::new(""));
    let mut absolute = file.parent().unwrap_or(Path::new(""));
    loop {
        if absolute.join("go.mod").is_file() {
            module = relative.to_string_lossy().replace('\\', "/");
            break;
        }
        let (Some(next_relative), Some(next_absolute)) = (relative.parent(), absolute.parent())
        else {
            break;
        };
        relative = next_relative;
        absolute = next_absolute;
    }
    module
}

#[derive(Debug, Clone)]
pub struct RustMacroToken<'a> {
    pub text: &'a str,
    pub kind: &'a str,
    pub line: u32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct RustCfgTestRange {
    pub start_line: u32,
    pub end_line: u32,
}

impl RustCfgTestRange {
    pub fn contains(self, line: u32) -> bool {
        self.start_line <= line && line <= self.end_line
    }
}

/// Whether the file has a file-level `use super::*;` (the import parser keeps
/// no record of glob imports, so this reads the syntax tree directly).
pub fn rust_globs_parent_module(source: &str, root: tree_sitter::Node) -> bool {
    let mut cursor = root.walk();
    let globs = root.children(&mut cursor).any(|node| {
        node.kind() == "use_declaration"
            && node_text(source, node)
                .chars()
                .filter(|ch| !ch.is_whitespace())
                .collect::<String>()
                .ends_with("usesuper::*;")
    });
    globs
}

/// Functions named by serde field attributes (`deserialize_with = "f"`,
/// `serialize_with`, `default`, `skip_serializing_if`). serde calls them from
/// derived code the callgraph never sees, so they are liveness roots. Each
/// root is the declaration identity the path names from the attribute's
/// module, so `"parse"` inside `mod config` roots `config::parse` (see
/// `rust_serde_root_identity`).
pub fn rust_serde_function_references(
    source: &str,
    root: tree_sitter::Node,
    items: &[RustApiItem],
) -> Vec<String> {
    static SERDE_FUNCTION_ATTRIBUTE: OnceLock<regex::Regex> = OnceLock::new();
    let pattern = SERDE_FUNCTION_ATTRIBUTE.get_or_init(|| {
        regex::Regex::new(
            r#"\b(?:deserialize_with|serialize_with|default|skip_serializing_if)\s*=\s*"([A-Za-z_][A-Za-z0-9_:]*)""#,
        )
        .expect("serde function attribute pattern compiles")
    });
    let identities = items
        .iter()
        .filter(|item| item.owner.is_none())
        .map(rust_qualified_item_name)
        .collect::<BTreeSet<_>>();
    pattern
        .captures_iter(source)
        .filter_map(|captures| captures.get(1))
        .map(|path| {
            let scope = root
                .descendant_for_byte_range(path.start(), path.end())
                .map(|node| rust_mod_scope_chain(&node, source))
                .unwrap_or_default();
            rust_serde_root_identity(path.as_str(), &scope, &identities)
        })
        .collect()
}

/// The declaration identity a serde callback path names from module `scope`.
/// `helpers::parse` inside `mod config` is `config::helpers::parse`; a leading
/// `self`, `super` or `crate` fixes the starting module. A relative path that
/// is not declared in `scope` is looked up in each enclosing module in turn,
/// as a `use super::...` import usually brings it from there, and a bare name
/// declared exactly once in the file resolves to that declaration. A path
/// that names no declaration in this file keeps only its last segment.
pub fn rust_serde_root_identity(
    path: &str,
    scope: &[String],
    identities: &BTreeSet<String>,
) -> String {
    let mut segments = rust_path_segments(path);
    let short = segments.last().cloned().unwrap_or_default();
    let mut scope = scope.to_vec();
    let mut anchored = false;
    while let Some(first) = segments.first().map(String::as_str) {
        match first {
            "self" => {}
            "super" => {
                scope.pop();
            }
            "crate" => scope.clear(),
            _ => break,
        }
        segments.remove(0);
        anchored = true;
    }
    loop {
        let candidate = scope
            .iter()
            .chain(&segments)
            .cloned()
            .collect::<Vec<_>>()
            .join("::");
        if identities.contains(&candidate) {
            return candidate;
        }
        if anchored || scope.pop().is_none() {
            break;
        }
    }
    if !anchored && segments.len() == 1 {
        let suffix = format!("::{short}");
        let mut matches = identities
            .iter()
            .filter(|identity| identity.ends_with(&suffix));
        if let (Some(only), None) = (matches.next(), matches.next()) {
            return only.clone();
        }
    }
    short
}

/// Names of the methods defined inside `impl Trait for Type` blocks anywhere
/// in the file (including inline modules).
pub fn rust_trait_impl_methods(source: &str, root: tree_sitter::Node) -> Vec<String> {
    let mut names = BTreeSet::new();
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if node.kind() == "impl_item" && node.child_by_field_name("trait").is_some() {
            if let Some(body) = node.child_by_field_name("body") {
                let mut cursor = body.walk();
                for item in body.children(&mut cursor) {
                    if item.kind() == "function_item" {
                        if let Some(name) = item.child_by_field_name("name") {
                            names.insert(node_text(source, name).to_string());
                        }
                    }
                }
            }
            continue;
        }
        let mut cursor = node.walk();
        stack.extend(node.children(&mut cursor));
    }
    names.into_iter().collect()
}

pub fn rust_path_segments(path: &str) -> Vec<String> {
    path.split("::")
        .map(str::trim)
        .filter(|segment| !segment.is_empty())
        .map(str::to_string)
        .collect()
}

pub fn macro_scoped_symbol(path: &[String], name: &str) -> String {
    if path.is_empty() {
        name.to_string()
    } else {
        format!("{}::{name}", path.join("::"))
    }
}

pub fn raw_imports_from_tree(
    source: &str,
    tree: &tree_sitter::Tree,
    lang: LangId,
) -> Vec<RawImportContribution> {
    parse_imports(source, tree, lang)
        .imports
        .into_iter()
        .map(|import| RawImportContribution {
            source: import.module_path,
            names: import.names,
            default_import: import.default_import,
            namespace_import: import.namespace_import,
        })
        .collect()
}

pub fn rust_raw_import_contributions(
    source: &str,
    tree: &tree_sitter::Tree,
) -> Vec<RawImportContribution> {
    parse_imports(source, tree, LangId::Rust)
        .imports
        .into_iter()
        .map(|import| RawImportContribution {
            source: crate::imports::rust_use_tree(&import),
            names: import.names,
            default_import: None,
            namespace_import: None,
        })
        .collect()
}

/// Line ranges compiled only for tests: `#[cfg(test)]` items (modules,
/// functions, impls, types, traits, constants and statics), plus
/// `#[cfg(test)]` statements, blocks and nested items inside a function body.
/// Calls on these lines are test usage, and declarations on them are test
/// code.
pub fn rust_cfg_test_ranges(source: &str, root: tree_sitter::Node) -> Vec<RustCfgTestRange> {
    let mut ranges = Vec::new();
    // Each node with whether its parent is a block. The walk carries this
    // down rather than asking `Node::parent`, which searches from the root
    // and is quadratic over a file of many top-level nodes.
    let mut stack = vec![(root, false)];
    while let Some((node, parent_is_block)) = stack.pop() {
        let in_function_body = parent_is_block
            && !matches!(
                node.kind(),
                "attribute_item" | "inner_attribute_item" | "line_comment" | "block_comment"
            );
        let item = matches!(
            node.kind(),
            "mod_item"
                | "function_item"
                | "impl_item"
                | "struct_item"
                | "enum_item"
                | "union_item"
                | "trait_item"
                | "type_item"
                | "const_item"
                | "static_item"
        );
        if (in_function_body || item) && rust_node_has_cfg_test_attribute(source, node) {
            ranges.push(RustCfgTestRange {
                // Symbol ranges include preceding attributes, not just the fn
                // token. Include them so declaration and call classification
                // agree on a cfg-gated item's first line.
                start_line: rust_item_start_line(node),
                end_line: node.end_position().row as u32 + 1,
            });
        }

        let mut cursor = node.walk();
        if cursor.goto_first_child() {
            let is_block = node.kind() == "block";
            loop {
                stack.push((cursor.node(), is_block));
                if !cursor.goto_next_sibling() {
                    break;
                }
            }
        }
    }
    ranges.sort_by_key(|range| (range.start_line, range.end_line));
    ranges.dedup();
    ranges
}

pub fn rust_item_start_line(node: tree_sitter::Node<'_>) -> u32 {
    let mut first = node;
    while let Some(previous) = first.prev_sibling() {
        if !matches!(
            previous.kind(),
            "attribute_item" | "line_comment" | "block_comment"
        ) {
            break;
        }
        first = previous;
    }
    first.start_position().row as u32 + 1
}

/// An out-of-line module a file declares under `#[cfg(test)]`, by the
/// `#[path]` it gives or by its name.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum RustCfgTestModule {
    Path(String),
    Name(String),
}

/// The file-level `#[cfg(test)]` out-of-line module declarations of a
/// file, in source order.
pub fn rust_cfg_test_modules(source: &str, root: tree_sitter::Node) -> Vec<RustCfgTestModule> {
    let mut modules = Vec::new();
    let mut cursor = root.walk();
    for node in root.children(&mut cursor) {
        // Only file-level declarations: nested inline modules change the base
        // directory, and test-only nested declarations are rare.
        if node.kind() != "mod_item"
            || node.child_by_field_name("body").is_some()
            || !rust_node_has_cfg_test_attribute(source, node)
        {
            continue;
        }
        if let Some(path) = rust_path_attribute_value(source, node) {
            modules.push(RustCfgTestModule::Path(path));
            continue;
        }
        let Some(name) = node
            .child_by_field_name("name")
            .map(|name| node_text(source, name).to_string())
        else {
            continue;
        };
        modules.push(RustCfgTestModule::Name(name));
    }
    modules
}

/// The project-relative candidate files of `modules`, declared in the file
/// at `relative_file`.
pub fn rust_cfg_test_module_files_for(
    relative_file: &str,
    modules: &[RustCfgTestModule],
) -> Vec<String> {
    let normalized = relative_file.replace('\\', "/");
    let (dir, file_name) = normalized
        .rsplit_once('/')
        .map_or(("", normalized.as_str()), |(dir, name)| (dir, name));
    // `mod x;` in `mod.rs`, `lib.rs` or `main.rs` resolves next to the file;
    // in `foo.rs` it resolves under `foo/`.
    let module_dir = match file_name.strip_suffix(".rs") {
        Some("mod" | "lib" | "main") | None => dir.to_string(),
        Some(stem) if dir.is_empty() => stem.to_string(),
        Some(stem) => format!("{dir}/{stem}"),
    };
    let join = |base: &str, rest: &str| {
        if base.is_empty() {
            rest.to_string()
        } else {
            format!("{base}/{rest}")
        }
    };

    let mut files = Vec::new();
    for module in modules {
        match module {
            RustCfgTestModule::Path(path) => {
                // A `#[path]` on a file-level declaration is relative to the
                // directory of the declaring file.
                files.push(normalize_relative_segments(&join(dir, path)));
            }
            RustCfgTestModule::Name(name) => {
                files.push(join(&module_dir, &format!("{name}.rs")));
                files.push(join(&module_dir, &format!("{name}/mod.rs")));
            }
        }
    }
    files
}

/// The string value of a `#[path = "../../../aft/src/parser/..."]` attribute attached to `node`.
pub fn rust_path_attribute_value(source: &str, node: tree_sitter::Node<'_>) -> Option<String> {
    let mut previous = node.prev_sibling();
    while let Some(attribute) = previous {
        match attribute.kind() {
            "attribute_item" => {
                let text = &source[attribute.byte_range()];
                let inner = text
                    .trim()
                    .strip_prefix("#[")
                    .and_then(|inner| inner.strip_suffix(']'))
                    .map(str::trim);
                if let Some(value) = inner
                    .and_then(|inner| inner.strip_prefix("path"))
                    .map(str::trim_start)
                    .and_then(|rest| rest.strip_prefix('='))
                    .map(str::trim)
                    .and_then(|rest| rest.strip_prefix('"'))
                    .and_then(|rest| rest.strip_suffix('"'))
                {
                    return Some(value.replace('\\', "/"));
                }
                previous = attribute.prev_sibling();
            }
            "line_comment" | "block_comment" => previous = attribute.prev_sibling(),
            _ => break,
        }
    }
    None
}

/// Resolves `.` and `..` segments of a project-relative path textually.
pub fn normalize_relative_segments(path: &str) -> String {
    let mut segments: Vec<&str> = Vec::new();
    // Joined PathBufs use backslashes on Windows, but contribution keys always
    // use forward slashes. Normalize before resolving dot segments.
    for segment in path.split(['/', '\\']) {
        match segment {
            "" | "." => {}
            ".." => {
                segments.pop();
            }
            other => segments.push(other),
        }
    }
    segments.join("/")
}

pub fn rust_node_has_cfg_test_attribute(source: &str, node: tree_sitter::Node<'_>) -> bool {
    let mut previous = node.prev_sibling();
    while let Some(attribute) = previous {
        match attribute.kind() {
            "attribute_item" => {
                if rust_attribute_requires_test(source, attribute) {
                    return true;
                }
                previous = attribute.prev_sibling();
            }
            "line_comment" | "block_comment" => previous = attribute.prev_sibling(),
            _ => break,
        }
    }
    false
}

/// `parent`'s named children, each with whether
/// [`rust_node_has_cfg_test_attribute`] holds for it, worked out in one pass
/// over the children. Asking each child separately walks back over every
/// comment before it, which is quadratic in a file of many comment lines.
pub fn rust_children_cfg_test_gated<'t>(
    source: &str,
    parent: tree_sitter::Node<'t>,
) -> Vec<(tree_sitter::Node<'t>, bool)> {
    let mut children = Vec::new();
    // Whether an attribute requiring `test` is in the run of attributes and
    // comments right before the current child.
    let mut run_requires_test = false;
    let mut cursor = parent.walk();
    for node in parent.children(&mut cursor) {
        if node.is_named() {
            children.push((node, run_requires_test));
        }
        match node.kind() {
            "attribute_item" => {
                run_requires_test = run_requires_test || rust_attribute_requires_test(source, node);
            }
            "line_comment" | "block_comment" => {}
            _ => run_requires_test = false,
        }
    }
    children
}

/// Whether `attribute` is `#[cfg(...)]` with a predicate requiring `test`.
pub fn rust_attribute_requires_test(source: &str, attribute: tree_sitter::Node<'_>) -> bool {
    let compact = source[attribute.byte_range()]
        .chars()
        .filter(|ch| !ch.is_whitespace())
        .collect::<String>();
    compact
        .strip_prefix("#[cfg(")
        .and_then(|inner| inner.strip_suffix(")]"))
        .is_some_and(cfg_predicate_requires_test)
}

pub fn cfg_predicate_requires_test(predicate: &str) -> bool {
    if predicate == "test" {
        return true;
    }
    if let Some(inner) = predicate
        .strip_prefix("all(")
        .and_then(|inner| inner.strip_suffix(')'))
    {
        return split_cfg_predicates(inner)
            .into_iter()
            .any(cfg_predicate_requires_test);
    }
    if let Some(inner) = predicate
        .strip_prefix("any(")
        .and_then(|inner| inner.strip_suffix(')'))
    {
        let predicates = split_cfg_predicates(inner);
        return !predicates.is_empty() && predicates.into_iter().all(cfg_predicate_requires_test);
    }
    false
}

pub fn split_cfg_predicates(input: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut depth = 0usize;
    let mut start = 0usize;
    for (index, ch) in input.char_indices() {
        match ch {
            '(' => depth += 1,
            ')' => depth = depth.saturating_sub(1),
            ',' if depth == 0 => {
                parts.push(input[start..index].trim());
                start = index + ch.len_utf8();
            }
            _ => {}
        }
    }
    let tail = input[start..].trim();
    if !tail.is_empty() {
        parts.push(tail);
    }
    parts
}

pub fn rust_macro_token_refs(
    source: &str,
    root: tree_sitter::Node,
) -> Vec<MacroTokenRefContribution> {
    let mut refs = BTreeSet::new();
    let mut scope_stack = Vec::new();
    collect_rust_macro_token_refs(source, root, &mut scope_stack, &mut refs);
    // Preserve lexical paths and owners even when the stored callgraph uses a
    // short name. This also retains every cfg-alternative function body.
    let mut functions: BTreeMap<String, Vec<tree_sitter::Node>> = BTreeMap::new();
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if node.kind() == "function_item" {
            if let Some(name) = rust_function_symbol_name(source, &node) {
                functions.entry(name).or_default().push(node);
            }
        }
        let mut cursor = node.walk();
        stack.extend(node.named_children(&mut cursor));
    }
    for (caller_symbol, variants) in functions {
        for node in variants {
            for (full, _, line, _, _) in rust_function_body_calls(source, node) {
                if full.contains('.') || full.ends_with('!') {
                    continue;
                }
                let mut path = rust_path_segments(&full);
                let Some(name) = path.pop() else {
                    continue;
                };
                refs.insert(MacroTokenRefContribution {
                    caller_symbol: caller_symbol.clone(),
                    name,
                    line,
                    path: macro_ref_path(path),
                    shape: RUST_MACRO_REF_SHAPE_CALL.into(),
                });
            }
        }
    }
    refs.into_iter().collect()
}

/// Calls that run when this Rust function body runs.
///
/// A call written in a `macro_rules!` template that is defined inside the body
/// runs only where that macro is expanded, not where it is defined. Such a
/// call therefore counts only when the body invokes the macro (`name!(..)`),
/// directly or through another local macro whose template is itself expanded.
/// A local macro that nothing invokes contributes no calls. An invocation in a
/// nested `fn` item counts for the enclosing body, as the stored call graph
/// also attributes a nested item's calls to the function around it.
pub fn rust_function_body_calls(
    source: &str,
    function: tree_sitter::Node,
) -> Vec<crate::calls::CallTuple> {
    let (calls, facts) = crate::calls::extract_rust_calls_with_macro_facts(
        source,
        function,
        function.start_byte(),
        function.end_byte(),
    );
    if facts.bodies.is_empty() {
        return calls;
    }

    // Templates can nest; the innermost one holding a call owns it.
    let owner = |start: usize, end: usize| {
        facts
            .bodies
            .iter()
            .filter(|body| body.byte_start <= start && end <= body.byte_end)
            .min_by_key(|body| body.byte_end - body.byte_start)
            .map(|body| body.name.as_str())
    };

    let mut direct_invocations = Vec::new();
    let mut template_invocations: BTreeMap<&str, Vec<String>> = BTreeMap::new();
    for (full, _, _, start, end) in &calls {
        let Some(path) = full.strip_suffix('!') else {
            continue;
        };
        // A path-qualified invocation (`self::m!`) is matched by its last
        // segment: a same-named macro elsewhere may make an unused local
        // macro look invoked, which only keeps its calls live.
        let name = path.rsplit("::").next().unwrap_or(path).trim().to_string();
        match owner(*start, *end) {
            Some(macro_name) => template_invocations
                .entry(macro_name)
                .or_default()
                .push(name),
            None => direct_invocations.push(name),
        }
    }

    let mut invoked = BTreeSet::new();
    let mut pending = direct_invocations;
    while let Some(name) = pending.pop() {
        if !invoked.insert(name.clone()) {
            continue;
        }
        if let Some(nested) = template_invocations.get(name.as_str()) {
            pending.extend(nested.iter().cloned());
        }
    }
    // An expanded template that invokes a macro through a metavariable
    // (`$m!(..)`) can name any local macro, and which one is decided only by
    // the arguments at each expansion. The scanner cannot resolve that, so
    // every template call in this body stays live: a function wrongly reported
    // dead costs more than a dead one that goes unreported. A template whose
    // token tree cannot be read (its node is not found, or tree-sitter could
    // not parse it cleanly) may hide such an invocation, so it is treated the
    // same way and keeps the calls live.
    let unresolved_invocation = facts.bodies.iter().any(|body| {
        invoked.contains(&body.name)
            && rust_template_token_tree(function, body.byte_start - 1, body.byte_end + 1)
                .is_none_or(|tree| {
                    tree.has_error() || rust_token_tree_invokes_metavariable_macro(tree)
                })
    });
    if unresolved_invocation {
        return calls;
    }
    calls
        .into_iter()
        .filter(|(_, _, _, start, end)| {
            owner(*start, *end).is_none_or(|macro_name| invoked.contains(macro_name))
        })
        .collect()
}

/// The `token_tree` node spanning exactly `start..end`, including its
/// delimiters. Templates nested in another template are token trees of the
/// outer one, so they are found the same way.
pub fn rust_template_token_tree(
    root: tree_sitter::Node<'_>,
    start: usize,
    end: usize,
) -> Option<tree_sitter::Node<'_>> {
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        let range = node.byte_range();
        if range.start > start || range.end < end {
            continue;
        }
        if node.kind() == "token_tree" && range.start == start && range.end == end {
            return Some(node);
        }
        let mut cursor = node.walk();
        stack.extend(node.children(&mut cursor));
    }
    None
}

/// Whether a template token tree, at any depth, invokes a macro named by a
/// metavariable: a `$name` token followed by `!`, with comments and whitespace
/// allowed in between, as in `$callback /* note */ !(..)`.
pub fn rust_token_tree_invokes_metavariable_macro(token_tree: tree_sitter::Node<'_>) -> bool {
    let mut stack = vec![token_tree];
    while let Some(node) = stack.pop() {
        let mut cursor = node.walk();
        // Comments are tree-sitter extras; dropping them lets the `!` after a
        // comment sit next to the metavariable it follows.
        let tokens = node
            .children(&mut cursor)
            .filter(|child| !child.is_extra())
            .collect::<Vec<_>>();
        for (index, token) in tokens.iter().enumerate() {
            if token.child_count() > 0 {
                stack.push(*token);
            }
            if token.kind() != "metavariable" {
                continue;
            }
            // The grammar's metavariable token covers only an ASCII name, so a
            // name like `$mé` continues as identifier tokens that start exactly
            // where the previous token ends.
            let mut next = index + 1;
            let mut name_end = token.end_byte();
            while let Some(part) = tokens
                .get(next)
                .filter(|part| part.kind() == "identifier" && part.start_byte() == name_end)
            {
                name_end = part.end_byte();
                next += 1;
            }
            if tokens.get(next).is_some_and(|bang| bang.kind() == "!") {
                return true;
            }
        }
    }
    false
}

/// Adds to `refs` the references the macro invocations under `root` make
/// through their tokens, each attributed to the function around it (the
/// innermost of `scope_stack` and the function items above the invocation).
///
/// The walk keeps its pending nodes on the heap rather than recursing: a
/// file can nest tens of thousands of levels deep, and a stack overflow
/// aborts the process. Leaving a node is queued as a step of its own, so
/// the function a node opened is popped off `scope_stack` after its
/// subtree, as a recursive walk would.
pub fn collect_rust_macro_token_refs(
    source: &str,
    root: tree_sitter::Node,
    scope_stack: &mut Vec<String>,
    refs: &mut BTreeSet<MacroTokenRefContribution>,
) {
    enum Step<'tree> {
        Enter(tree_sitter::Node<'tree>),
        /// Restore `scope_stack` to this length.
        Leave(usize),
    }
    let mut pending = vec![Step::Enter(root)];
    while let Some(step) = pending.pop() {
        let node = match step {
            Step::Enter(node) => node,
            Step::Leave(scope_len) => {
                scope_stack.truncate(scope_len);
                continue;
            }
        };
        pending.push(Step::Leave(scope_stack.len()));
        if node.kind() == "function_item" {
            if let Some(symbol) = rust_function_symbol_name(source, &node) {
                scope_stack.push(symbol);
            }
        }

        if node.kind() == "macro_invocation" {
            if let Some(token_tree) = find_child_by_kind(node, "token_tree") {
                let caller_symbol = scope_stack
                    .last()
                    .cloned()
                    .unwrap_or_else(|| TOP_LEVEL_SYMBOL.to_string());
                let mut tokens = Vec::new();
                collect_rust_macro_tokens(source, token_tree, &mut tokens);
                let mut shadowed = BTreeSet::new();
                for token in &tokens {
                    if rust_macro_token_is_identifier(token)
                        && crate::calls::rust_name_is_shadowed_at(node, source, token.text)
                    {
                        shadowed.insert(token.text.to_string());
                    }
                }
                let mut binding = false;
                for token in &tokens {
                    if token.text == "let" {
                        binding = true;
                    } else if token.text == "=" {
                        binding = false;
                    } else if binding && rust_macro_token_is_identifier(token) {
                        shadowed.insert(token.text.to_string());
                    }
                }
                extract_rust_macro_token_refs(&tokens, &caller_symbol, &shadowed, refs);
            }
        }

        let start = pending.len();
        let mut cursor = node.walk();
        pending.extend(node.children(&mut cursor).map(Step::Enter));
        pending[start..].reverse();
    }
}

/// Appends the leaf tokens under `root` to `tokens`, in source order,
/// skipping the subtrees [`rust_macro_token_node_is_opaque`] names. The
/// walk keeps its place in a tree cursor rather than recursing, so deeply
/// nested token trees cannot overflow the stack.
pub fn collect_rust_macro_tokens<'a>(
    source: &'a str,
    root: tree_sitter::Node,
    tokens: &mut Vec<RustMacroToken<'a>>,
) {
    let mut cursor = root.walk();
    loop {
        let node = cursor.node();
        if !rust_macro_token_node_is_opaque(node.kind()) {
            if node.child_count() == 0 {
                let text = node_text(source, node).trim();
                if !text.is_empty() {
                    tokens.push(RustMacroToken {
                        text,
                        kind: node.kind(),
                        line: node.start_position().row as u32 + 1,
                    });
                }
            } else if cursor.goto_first_child() {
                continue;
            }
        }
        // Move past this subtree: to the next sibling, or up until an
        // ancestor has one. The cursor cannot climb above `root`.
        while !cursor.goto_next_sibling() {
            if !cursor.goto_parent() {
                return;
            }
        }
    }
}

pub fn rust_macro_token_node_is_opaque(kind: &str) -> bool {
    matches!(
        kind,
        "string_literal" | "raw_string_literal" | "char_literal" | "line_comment" | "block_comment"
    )
}

pub fn extract_rust_macro_token_refs(
    tokens: &[RustMacroToken<'_>],
    caller_symbol: &str,
    shadowed: &BTreeSet<String>,
    refs: &mut BTreeSet<MacroTokenRefContribution>,
) {
    for index in 0..tokens.len() {
        let token = &tokens[index];
        if !rust_macro_token_is_identifier(token) || rust_macro_token_is_keyword(token.text) {
            continue;
        }
        if index > 0 && tokens[index - 1].text == "." {
            continue;
        }
        if tokens.get(index + 1).is_some_and(|next| next.text == "!") {
            continue;
        }

        let path = rust_macro_path_before(tokens, index);
        let next = rust_macro_next_after_optional_turbofish(tokens, index + 1);
        // A single bare argument can be a function item passed to a method
        // such as is_ok_and. Resolve it only locally or through imports, and
        // never credit a name bound by the enclosing function or macro body.
        if index > 0
            && tokens[index - 1].text == "("
            && tokens
                .get(next)
                .is_some_and(|next| matches!(next.text, ")" | ","))
            && !shadowed.contains(token.text)
        {
            refs.insert(MacroTokenRefContribution {
                caller_symbol: caller_symbol.to_string(),
                line: token.line,
                name: token.text.to_string(),
                path: macro_ref_path(path.clone()),
                shape: RUST_MACRO_REF_SHAPE_CALL.into(),
            });
        }
        if tokens.get(next).is_some_and(|next| next.text == "(") {
            let shape = if path
                .last()
                .is_some_and(|segment| rust_macro_name_is_upper_camel(segment))
            {
                RUST_MACRO_REF_SHAPE_METHOD
            } else {
                RUST_MACRO_REF_SHAPE_CALL
            };
            refs.insert(MacroTokenRefContribution {
                caller_symbol: caller_symbol.to_string(),
                line: token.line,
                name: token.text.to_string(),
                path: macro_ref_path(path),
                shape: shape.to_string(),
            });
            continue;
        }

        if rust_macro_name_is_upper_camel(token.text)
            && tokens.get(index + 1).is_some_and(|next| next.text == "{")
        {
            refs.insert(MacroTokenRefContribution {
                caller_symbol: caller_symbol.to_string(),
                line: token.line,
                name: token.text.to_string(),
                path: macro_ref_path(path),
                shape: RUST_MACRO_REF_SHAPE_STRUCT.to_string(),
            });
        }
    }
}

pub fn rust_macro_path_before(tokens: &[RustMacroToken<'_>], index: usize) -> Vec<String> {
    let mut segments = Vec::new();
    let mut cursor = index;
    while cursor >= 2
        && tokens[cursor - 1].text == "::"
        && rust_macro_token_is_path_segment(&tokens[cursor - 2])
    {
        segments.push(tokens[cursor - 2].text.to_string());
        cursor -= 2;
    }
    segments.reverse();
    segments
}

pub fn rust_macro_next_after_optional_turbofish(
    tokens: &[RustMacroToken<'_>],
    index: usize,
) -> usize {
    if tokens.get(index).is_none_or(|token| token.text != "::")
        || tokens.get(index + 1).is_none_or(|token| token.text != "<")
    {
        return index;
    }

    let mut depth = 0usize;
    let mut cursor = index + 1;
    while let Some(token) = tokens.get(cursor) {
        match token.text {
            "<" => depth += 1,
            ">" => {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    return cursor + 1;
                }
            }
            _ => {}
        }
        cursor += 1;
    }
    index
}

pub fn macro_ref_path(path: Vec<String>) -> Option<Vec<String>> {
    (!path.is_empty()).then_some(path)
}

pub fn rust_macro_token_is_identifier(token: &RustMacroToken<'_>) -> bool {
    matches!(token.kind, "identifier" | "type_identifier")
        || rust_macro_text_is_identifier(token.text)
}

pub fn rust_macro_token_is_path_segment(token: &RustMacroToken<'_>) -> bool {
    rust_macro_token_is_identifier(token)
        && (!rust_macro_token_is_keyword(token.text)
            || matches!(token.text, "crate" | "self" | "super"))
}

pub fn rust_macro_text_is_identifier(text: &str) -> bool {
    let mut chars = text.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    (first == '_' || first.is_ascii_alphabetic())
        && chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric())
}

pub fn rust_macro_name_is_upper_camel(name: &str) -> bool {
    name.chars().next().is_some_and(char::is_uppercase)
}

pub fn rust_macro_token_is_keyword(text: &str) -> bool {
    matches!(
        text,
        "as" | "async"
            | "await"
            | "break"
            | "const"
            | "continue"
            | "crate"
            | "dyn"
            | "else"
            | "enum"
            | "extern"
            | "false"
            | "fn"
            | "for"
            | "if"
            | "impl"
            | "in"
            | "let"
            | "loop"
            | "match"
            | "mod"
            | "move"
            | "mut"
            | "pub"
            | "ref"
            | "return"
            | "self"
            | "Self"
            | "static"
            | "struct"
            | "super"
            | "trait"
            | "true"
            | "type"
            | "unsafe"
            | "use"
            | "where"
            | "while"
    )
}

pub fn rust_function_symbol_name(
    source: &str,
    function_node: &tree_sitter::Node<'_>,
) -> Option<String> {
    let name_node = function_node.child_by_field_name("name")?;
    let name = node_text(source, name_node).to_string();
    let declaration_list_owner = rust_function_declaration_list_owner(function_node);

    match declaration_list_owner.as_ref().map(tree_sitter::Node::kind) {
        Some("impl_item") => {
            let scope_name = rust_impl_scope_name(declaration_list_owner.as_ref().unwrap(), source);
            if scope_name.is_empty() {
                Some(name)
            } else {
                Some(format!("{scope_name}::{name}"))
            }
        }
        Some(owner_kind) if owner_kind != "mod_item" => None,
        _ => {
            let scope_chain = rust_mod_scope_chain(function_node, source);
            if scope_chain.is_empty() {
                Some(name)
            } else {
                Some(format!("{}::{name}", scope_chain.join("::")))
            }
        }
    }
}

pub fn rust_function_declaration_list_owner<'a>(
    function_node: &tree_sitter::Node<'a>,
) -> Option<tree_sitter::Node<'a>> {
    function_node
        .parent()
        .filter(|parent| parent.kind() == "declaration_list")
        .and_then(|parent| parent.parent())
}

pub fn rust_mod_scope_chain(node: &tree_sitter::Node<'_>, source: &str) -> Vec<String> {
    let mut scopes = Vec::new();
    let mut current = node.parent();
    while let Some(parent) = current {
        if parent.kind() == "mod_item" {
            if let Some(name_node) = parent.child_by_field_name("name") {
                scopes.push(node_text(source, name_node).to_string());
            }
        }
        current = parent.parent();
    }
    scopes.reverse();
    scopes
}

pub fn rust_impl_scope_name(impl_node: &tree_sitter::Node<'_>, source: &str) -> String {
    let Some(self_type) = impl_node.child_by_field_name("type") else {
        return String::new();
    };
    let self_name = node_text(source, self_type);
    match impl_node.child_by_field_name("trait") {
        Some(trait_type) => format!("{} for {self_name}", node_text(source, trait_type)),
        None => self_name.to_string(),
    }
}

pub fn ts_raw_reexport_contributions(
    source: &str,
    root: tree_sitter::Node,
) -> Vec<RawReexportContribution> {
    let mut reexports = Vec::new();
    let mut cursor = root.walk();
    if !cursor.goto_first_child() {
        return reexports;
    }

    loop {
        let node = cursor.node();
        if node.kind() == "export_statement" {
            if let Some(module_path) = export_source_module(source, node) {
                let line = (node.start_position().row + 1) as u32;
                let raw_export = node_text(source, node).trim();
                for specifier in ts_reexport_specifiers(raw_export) {
                    reexports.push(RawReexportContribution {
                        language: "ts".to_string(),
                        source: module_path.clone(),
                        kind: "named".to_string(),
                        imported: Some(specifier.imported),
                        exported: Some(specifier.exported),
                        line,
                    });
                }
                if raw_export.contains('*') {
                    if let Some(namespace_export) = ts_namespace_reexport_name(raw_export) {
                        reexports.push(RawReexportContribution {
                            language: "ts".to_string(),
                            source: module_path.clone(),
                            kind: "namespace".to_string(),
                            imported: Some("*".to_string()),
                            exported: Some(namespace_export),
                            line,
                        });
                    } else {
                        reexports.push(RawReexportContribution {
                            language: "ts".to_string(),
                            source: module_path.clone(),
                            kind: "star".to_string(),
                            imported: Some("*".to_string()),
                            exported: None,
                            line,
                        });
                    }
                }
            }
        }

        if !cursor.goto_next_sibling() {
            break;
        }
    }

    reexports
}

pub fn rust_raw_reexport_contributions(source: &str) -> Vec<RawReexportContribution> {
    rust_pub_use_statements(source)
        .into_iter()
        .flat_map(|(statement, line)| {
            rust_reexport_specifiers(&statement)
                .into_iter()
                .map(move |specifier| RawReexportContribution {
                    language: "rust".to_string(),
                    source: specifier.module_path.join("::"),
                    kind: if specifier.imported == "*" {
                        "star".to_string()
                    } else {
                        "named".to_string()
                    },
                    imported: Some(specifier.imported),
                    exported: Some(specifier.exported),
                    line,
                })
        })
        .collect()
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RustApiFacts {
    #[serde(default)]
    pub receiver_references: BTreeSet<String>,
    #[serde(default)]
    pub initializers: Vec<RustInitializer>,
    #[serde(default)]
    pub initializer_references: Vec<MacroTokenRefContribution>,
    pub items: Vec<RustApiItem>,
    pub modules: Vec<RustApiModule>,
    pub uses: Vec<RustApiUse>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RustInitializer {
    pub name: String,
    pub range: RustCfgTestRange,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RustApiItem {
    pub name: String,
    pub scope: Vec<String>,
    pub public: bool,
    pub line: u32,
    pub owner: Option<String>,
    pub trait_name: Option<String>,
}

pub fn rust_qualified_item_name(item: &RustApiItem) -> String {
    let mut parts = item.scope.clone();
    if let Some(owner) = &item.owner {
        parts.push(match &item.trait_name {
            Some(trait_name) => format!("{trait_name} for {owner}"),
            None => owner.clone(),
        });
    }
    parts.push(item.name.clone());
    parts.join("::")
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RustApiModule {
    pub scope: Vec<String>,
    pub name: String,
    pub public: bool,
    pub file: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path_override: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RustApiUse {
    pub scope: Vec<String>,
    pub path: Vec<String>,
    pub alias: String,
    pub public: bool,
    pub line: u32,
}

pub fn rust_unrestricted_pub(source: &str, node: tree_sitter::Node) -> bool {
    find_child_by_kind(node, "visibility_modifier")
        .is_some_and(|visibility| node_text(source, visibility).trim() == "pub")
}

pub fn rust_api_facts(source: &str, root: tree_sitter::Node, file: &str) -> RustApiFacts {
    let mut facts = RustApiFacts::default();
    rust_collect_api_facts(source, root, file, &[], &mut facts, 0);
    let mut owners = Vec::new();
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        let owner = match node.kind() {
            "function_item" => rust_function_symbol_name(source, &node),
            "static_item" | "const_item" => node.child_by_field_name("name").map(|name| {
                macro_scoped_symbol(
                    &rust_mod_scope_chain(&node, source),
                    node_text(source, name),
                )
            }),
            _ => None,
        };
        if let Some(owner) = owner {
            owners.push((node.start_byte(), node.end_byte(), owner.clone()));
            if matches!(node.kind(), "static_item" | "const_item") {
                facts.initializers.push(RustInitializer {
                    name: owner,
                    range: RustCfgTestRange {
                        start_line: rust_item_start_line(node),
                        end_line: node.end_position().row as u32 + 1,
                    },
                });
            }
        }
        let mut cursor = node.walk();
        stack.extend(node.named_children(&mut cursor));
    }
    facts.initializer_references = crate::calls::extract_rust_value_references(source, root)
        .into_iter()
        .map(|(full, name, line, start, end)| {
            let mut path = rust_path_segments(&full);
            path.pop();
            let caller_symbol = owners
                .iter()
                .filter(|(a, b, _)| *a <= start && *b >= end)
                .min_by_key(|(a, b, _)| b - a)
                .map(|(_, _, name)| name.clone())
                .unwrap_or_else(|| "<top-level>".into());
            MacroTokenRefContribution {
                caller_symbol,
                name,
                line,
                path: macro_ref_path(path),
                shape: "call".into(),
            }
        })
        .collect();
    facts
}

/// How many modules and item macros [`rust_collect_api_facts`] descends
/// through, counted together. Real code nests a handful; past the bound the
/// items are left undescribed rather than recursing further, because each
/// level costs a stack frame (a stack overflow aborts the process) and
/// copies the module path, so a file of thousands of nested modules would
/// otherwise take quadratic time and memory.
pub const MAX_RUST_API_NESTING: usize = 64;

/// Adds to `facts` the modules, uses and items declared directly in `root`
/// and, through module bodies and item macros, below it. `depth` is how many
/// modules and item macros enclose `root`.
pub fn rust_collect_api_facts(
    source: &str,
    root: tree_sitter::Node,
    file: &str,
    scope: &[String],
    facts: &mut RustApiFacts,
    depth: usize,
) {
    if depth > MAX_RUST_API_NESTING {
        return;
    }
    let gated = rust_children_cfg_test_gated(source, root);
    for (node, gated) in gated {
        if gated {
            continue;
        }
        // An impl header names its own receiver even when nothing uses it.
        // Only references outside impls are evidence of a runtime receiver.
        if !matches!(node.kind(), "impl_item" | "mod_item") {
            facts
                .receiver_references
                .extend(extract_type_references(source, node, LangId::Rust));
        }
        let name = node
            .child_by_field_name("name")
            .map(|name| node_text(source, name).to_string());
        let public = rust_unrestricted_pub(source, node);
        match node.kind() {
            "mod_item" => {
                let Some(name) = name else {
                    continue;
                };
                let body = node.child_by_field_name("body");
                let path_override = rust_path_attribute_value(source, node);
                let mut nested = scope.to_vec();
                nested.push(name.clone());
                let module_file = body
                    .is_none()
                    .then(|| rust_module_file(file, &nested, path_override.as_deref()));
                facts.modules.push(RustApiModule {
                    scope: scope.to_vec(),
                    name,
                    public,
                    file: module_file,
                    path_override,
                });
                if let Some(body) = body {
                    rust_collect_api_facts(source, body, file, &nested, facts, depth + 1);
                }
            }
            "use_declaration" => {
                let text = node_text(source, node);
                let Some((_, path)) = text.split_once("use ") else {
                    continue;
                };
                rust_api_use_paths(
                    path.trim().trim_end_matches(';'),
                    &[],
                    &mut |path, alias| {
                        facts.uses.push(RustApiUse {
                            scope: scope.to_vec(),
                            path,
                            alias,
                            public,
                            line: node.start_position().row as u32 + 1,
                        });
                    },
                );
            }
            "impl_item" => {
                let owner = node
                    .child_by_field_name("type")
                    .map(|ty| rust_api_type_path(node_text(source, ty)));
                let trait_name = node
                    .child_by_field_name("trait")
                    .map(|ty| rust_api_type_path(node_text(source, ty)));
                if let Some(body) = node.child_by_field_name("body") {
                    let mut cursor = body.walk();
                    for method in body
                        .named_children(&mut cursor)
                        .filter(|item| item.kind() == "function_item")
                    {
                        if rust_node_has_cfg_test_attribute(source, method) {
                            continue;
                        }
                        if let Some(name) = method.child_by_field_name("name") {
                            facts.items.push(RustApiItem {
                                name: node_text(source, name).to_string(),
                                scope: scope.to_vec(),
                                public: rust_unrestricted_pub(source, method)
                                    || trait_name.is_some(),
                                line: method.start_position().row as u32 + 1,
                                owner: owner.clone(),
                                trait_name: trait_name.clone(),
                            });
                        }
                    }
                }
            }
            "function_item" | "struct_item" | "enum_item" | "trait_item" | "type_item"
            | "const_item" | "static_item" => {
                if let Some(name) = name {
                    facts.items.push(RustApiItem {
                        name,
                        scope: scope.to_vec(),
                        public,
                        line: node.start_position().row as u32 + 1,
                        owner: None,
                        trait_name: None,
                    });
                }
            }
            "macro_invocation" => {
                // Declarative item macros often pass Rust items as their input.
                // Parse those items rather than making the whole module public.
                if let Some(tokens) = find_child_by_kind(node, "token_tree") {
                    rust_collect_api_macro_items(source, tokens, file, scope, facts, depth + 1);
                }
                if let Some(name) = node.child_by_field_name("macro") {
                    let mut cursor = root.walk();
                    for definition in root
                        .named_children(&mut cursor)
                        .filter(|n| n.kind() == "macro_definition")
                    {
                        if definition
                            .child_by_field_name("name")
                            .is_some_and(|n| node_text(source, n) == node_text(source, name))
                        {
                            let mut cursor = definition.walk();
                            for rule in definition
                                .named_children(&mut cursor)
                                .filter(|n| n.kind() == "macro_rule")
                            {
                                if let (Some(left), Some(right), Some(input)) = (
                                    rule.child_by_field_name("left"),
                                    rule.child_by_field_name("right"),
                                    find_child_by_kind(node, "token_tree"),
                                ) {
                                    if let Some(expanded) = rust_api_macro_expansion(
                                        node_text(source, left),
                                        node_text(source, right),
                                        node_text(source, input),
                                    ) {
                                        rust_collect_api_macro_text(
                                            &expanded,
                                            right.start_position().row,
                                            file,
                                            scope,
                                            facts,
                                            depth + 1,
                                        );
                                    }
                                }
                            }
                        }
                    }
                }
            }
            _ => {}
        }
    }
}

/// The project-relative file of the out-of-line module at `nested` (its
/// module path inside the declaring file), declared in the file at `file`,
/// with `path_override` from its `#[path]` attribute.
pub fn rust_module_file(file: &str, nested: &[String], path_override: Option<&str>) -> String {
    let base = Path::new(file);
    let dir = base.parent().unwrap_or(Path::new(""));
    let stem = base.file_stem().and_then(|s| s.to_str()).unwrap_or("");
    let dir = if matches!(stem, "lib" | "main" | "mod") {
        dir.to_path_buf()
    } else {
        dir.join(stem)
    };
    if let Some(path) = path_override {
        normalize_relative_segments(
            &base
                .parent()
                .unwrap_or(Path::new(""))
                .join(path)
                .to_string_lossy(),
        )
    } else {
        dir.join(nested.join("/"))
            .with_extension("rs")
            .to_string_lossy()
            .replace('\\', "/")
    }
}

pub fn rust_collect_api_macro_items(
    source: &str,
    tokens: tree_sitter::Node,
    file: &str,
    scope: &[String],
    facts: &mut RustApiFacts,
    depth: usize,
) {
    let text = node_text(source, tokens);
    if text.len() < 2 {
        return;
    }
    rust_collect_api_macro_text(
        &text[1..text.len() - 1],
        tokens.start_position().row,
        file,
        scope,
        facts,
        depth,
    );
}

// Expand simple ident/path captures used by re-export macros. Repetition and
// procedural macros require compiler expansion; unresolved templates are not
// evidence that every item in their module is public.
pub fn rust_api_macro_expansion(pattern: &str, template: &str, input: &str) -> Option<String> {
    let interior = |text: &str| {
        text.get(1..text.len().checked_sub(1)?)
            .map(str::trim)
            .map(str::to_string)
    };
    let pattern = interior(pattern)?;
    let input = interior(input)?;
    let mut template = interior(template)?;
    if !pattern.contains('$') {
        return (pattern == input).then_some(template);
    }
    let patterns = split_cfg_predicates(&pattern);
    let inputs = split_cfg_predicates(&input);
    if patterns.len() != inputs.len() {
        return None;
    }
    for (pattern, input) in patterns.into_iter().zip(inputs) {
        let (name, kind) = pattern.trim().strip_prefix('$')?.split_once(':')?;
        if !matches!(kind.trim(), "ident" | "path")
            || !name.chars().all(|ch| ch.is_alphanumeric() || ch == '_')
        {
            return None;
        }
        if !input
            .trim()
            .chars()
            .all(|ch| ch.is_alphanumeric() || ch == '_' || ch == ':')
        {
            return None;
        }
        template = template.replace(&format!("${}", name.trim()), input.trim());
    }
    (!template.contains('$')).then_some(template)
}

pub fn rust_collect_api_macro_text(
    interior: &str,
    row: usize,
    file: &str,
    scope: &[String],
    facts: &mut RustApiFacts,
    depth: usize,
) {
    if interior.contains('$') {
        return;
    }
    let padded = format!("{}{}", "\n".repeat(row), interior);
    let mut analyzer = FactParsers::default();
    if let Some(tree) = analyzer.parse_source(LangId::Rust, &padded) {
        if !tree.root_node().has_error() {
            rust_collect_api_facts(&padded, tree.root_node(), file, scope, facts, depth);
        }
    }
}

pub fn rust_api_type_path(text: &str) -> String {
    text.split('<').next().unwrap_or(text).trim().to_string()
}

/// How deep [`rust_api_use_paths`] follows nested `{...}` groups of one
/// `use` declaration. Real code nests a few; deeper groups are dropped
/// rather than recursed into, because each level costs a stack frame (a
/// stack overflow aborts the process) and copies the path prefix and the
/// group's text, so thousands of levels would take quadratic time and
/// memory.
pub const MAX_RUST_USE_GROUP_NESTING: usize = 64;

pub fn rust_api_use_paths(
    text: &str,
    prefix: &[String],
    emit: &mut impl FnMut(Vec<String>, String),
) {
    rust_api_use_paths_at(text, prefix, emit, 0);
}

/// [`rust_api_use_paths`] for `text`, nested `depth` groups deep.
pub fn rust_api_use_paths_at(
    text: &str,
    prefix: &[String],
    emit: &mut impl FnMut(Vec<String>, String),
    depth: usize,
) {
    let text = text.trim();
    if let Some(open) = text.find('{') {
        if depth >= MAX_RUST_USE_GROUP_NESTING {
            return;
        }
        let mut prefix = prefix.to_vec();
        prefix.extend(rust_path_segments(text[..open].trim_end_matches(':')));
        let inner = text[open + 1..].trim_end_matches('}');
        let mut depth_in_group = 0;
        let mut start = 0;
        for (index, ch) in inner.char_indices() {
            match ch {
                '{' => depth_in_group += 1,
                '}' => depth_in_group -= 1,
                ',' if depth_in_group == 0 => {
                    rust_api_use_paths_at(&inner[start..index], &prefix, emit, depth + 1);
                    start = index + 1;
                }
                _ => {}
            }
        }
        rust_api_use_paths_at(&inner[start..], &prefix, emit, depth + 1);
    } else if !text.is_empty() {
        let (path, alias) = text
            .split_once(" as ")
            .map(|(path, alias)| (path.trim(), Some(alias.trim())))
            .unwrap_or((text, None));
        let mut segments = prefix.to_vec();
        segments.extend(rust_path_segments(path));
        if segments.last().is_some_and(|s| s == "self") {
            segments.pop();
        }
        if let Some(name) = alias.or_else(|| segments.last().map(String::as_str)) {
            emit(segments.clone(), name.to_string());
        }
    }
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GoDispatchFacts {
    #[serde(default)]
    pub module: String,
    pub methods: Vec<GoMethodFact>,
    pub interfaces: Vec<Vec<String>>,
    pub used_types: BTreeSet<String>,
    #[serde(default)]
    pub live_methods: BTreeSet<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GoMethodFact {
    pub receiver: String,
    pub name: String,
    pub signature: String,
}

pub fn go_dispatch_facts(source: &str, root: tree_sitter::Node) -> GoDispatchFacts {
    let mut facts = GoDispatchFacts::default();
    let mut stack = vec![root];
    while let Some(node) = stack.pop() {
        if node.kind() == "method_declaration" {
            if let (Some(receiver), Some(name)) = (
                node.child_by_field_name("receiver"),
                node.child_by_field_name("name"),
            ) {
                let mut cursor = receiver.walk();
                if let Some(parameter) = receiver.named_children(&mut cursor).next() {
                    if let Some(ty) = parameter.child_by_field_name("type") {
                        facts.methods.push(GoMethodFact {
                            receiver: node_text(source, ty).trim_start_matches('*').to_string(),
                            name: node_text(source, name).to_string(),
                            signature: go_method_signature(source, node),
                        });
                    }
                }
                let mut cursor = node.walk();
                stack.extend(
                    node.named_children(&mut cursor)
                        .filter(|child| child.id() != receiver.id()),
                );
                continue;
            }
        }
        if node.kind() == "interface_type" {
            let mut cursor = node.walk();
            let methods = node
                .named_children(&mut cursor)
                .filter(|child| child.kind() == "method_elem")
                .map(|method| go_method_signature(source, method))
                .collect::<Vec<_>>();
            // Empty interfaces impose no method contract. Embedded/constraint
            // interfaces need their complete method set; never accept a partial
            // set as if it were the whole interface.
            let mut cursor = node.walk();
            if !methods.is_empty()
                && !node
                    .named_children(&mut cursor)
                    .any(|child| child.kind() == "type_elem")
            {
                facts.interfaces.push(methods);
            }
            continue;
        }
        if node.kind() == "type_identifier"
            && !node.parent().is_some_and(|parent| {
                parent.kind() == "type_spec"
                    && parent
                        .child_by_field_name("name")
                        .is_some_and(|name| name.id() == node.id())
            })
        {
            facts.used_types.insert(node_text(source, node).to_string());
        }
        let mut cursor = node.walk();
        stack.extend(node.named_children(&mut cursor));
    }
    facts
}

pub fn go_method_signature(source: &str, method: tree_sitter::Node) -> String {
    let name = method
        .child_by_field_name("name")
        .map(|name| node_text(source, name))
        .unwrap_or("");
    let parameters = method
        .child_by_field_name("parameters")
        .map(|node| go_signature_types(source, node))
        .unwrap_or_default();
    let result = method
        .child_by_field_name("result")
        .map(|node| go_signature_types(source, node))
        .unwrap_or_default();
    format!("{name}({parameters})({result})")
}

pub fn go_signature_types(source: &str, node: tree_sitter::Node) -> String {
    if node.kind() != "parameter_list" {
        return node_text(source, node)
            .split_whitespace()
            .collect::<String>();
    }
    let mut types = Vec::new();
    let mut cursor = node.walk();
    for parameter in node.named_children(&mut cursor) {
        let Some(ty) = parameter.child_by_field_name("type") else {
            continue;
        };
        let mut cursor = parameter.walk();
        let count = parameter
            .named_children(&mut cursor)
            .filter(|child| child.kind() == "identifier")
            .count()
            .max(1);
        let ty = format!(
            "{}{}",
            if parameter.kind() == "variadic_parameter_declaration" {
                "..."
            } else {
                ""
            },
            node_text(source, ty).split_whitespace().collect::<String>()
        );
        types.extend(std::iter::repeat_n(ty, count));
    }
    types.join(",")
}

pub fn ts_reexport_specifiers(raw_export: &str) -> Vec<ReexportSpecifier> {
    let Some(start) = raw_export.find('{').map(|index| index + 1) else {
        return Vec::new();
    };
    let Some(end) = raw_export[start..].find('}').map(|index| start + index) else {
        return Vec::new();
    };

    raw_export[start..end]
        .split(',')
        .filter_map(|specifier| {
            let specifier = specifier.trim();
            if specifier.is_empty() {
                return None;
            }
            let imported = specifier_imported_name(specifier).trim();
            let exported = specifier_local_name(specifier).trim();
            if imported.is_empty() || exported.is_empty() {
                return None;
            }
            Some(ReexportSpecifier {
                imported: imported.to_string(),
                exported: exported.to_string(),
            })
        })
        .collect()
}

pub fn ts_namespace_reexport_name(raw_export: &str) -> Option<String> {
    let after_star = raw_export.split_once('*')?.1.trim_start();
    let after_as = after_star.strip_prefix("as")?.trim_start();
    let name = after_as
        .split_whitespace()
        .next()?
        .trim_matches(|ch: char| ch == '{' || ch == '}' || ch == ';' || ch == ',');
    (!name.is_empty()).then(|| name.to_string())
}

pub fn rust_pub_use_statements(source: &str) -> Vec<(String, u32)> {
    let mut statements = Vec::new();
    let mut current = String::new();
    let mut start_line = 0u32;

    for (index, line) in source.lines().enumerate() {
        let trimmed = line.trim();
        if current.is_empty() {
            if !(trimmed.starts_with("pub use ") || trimmed.starts_with("pub(crate) use ")) {
                continue;
            }
            start_line = (index + 1) as u32;
        }

        current.push(' ');
        current.push_str(trimmed);
        if trimmed.ends_with(';') {
            statements.push((current.trim().to_string(), start_line));
            current.clear();
        }
    }

    statements
}

pub fn rust_reexport_specifiers(statement: &str) -> Vec<RustReexportSpecifier> {
    let statement = statement
        .trim()
        .trim_end_matches(';')
        .strip_prefix("pub(crate) use ")
        .or_else(|| {
            statement
                .trim()
                .trim_end_matches(';')
                .strip_prefix("pub use ")
        })
        .unwrap_or("")
        .trim();
    if statement.is_empty() {
        return Vec::new();
    }

    if let Some((module_path, grouped)) = statement.split_once("::{") {
        let grouped = grouped.trim_end_matches('}');
        return grouped
            .split(',')
            .filter_map(|specifier| rust_reexport_specifier(module_path.trim(), specifier.trim()))
            .collect();
    }

    let Some((module_path, imported)) = statement.rsplit_once("::") else {
        return Vec::new();
    };
    rust_reexport_specifier(module_path.trim(), imported.trim())
        .into_iter()
        .collect()
}

pub fn rust_reexport_specifier(
    module_path: &str,
    specifier: &str,
) -> Option<RustReexportSpecifier> {
    if specifier.is_empty() {
        return None;
    }
    let (imported, exported) = specifier
        .split_once(" as ")
        .map(|(imported, exported)| (imported.trim(), exported.trim()))
        .unwrap_or((specifier.trim(), specifier.trim()));
    if imported.is_empty() || exported.is_empty() {
        return None;
    }
    Some(RustReexportSpecifier {
        module_path: rust_normalize_module_path(module_path),
        imported: imported.to_string(),
        exported: exported.to_string(),
    })
}

pub fn rust_normalize_module_path(module_path: &str) -> Vec<String> {
    module_path
        .split("::")
        .filter_map(|segment| {
            let segment = segment.trim();
            if segment.is_empty() || matches!(segment, "self" | "crate") {
                None
            } else {
                Some(segment.to_string())
            }
        })
        .collect()
}

pub fn export_source_module(source: &str, node: tree_sitter::Node) -> Option<String> {
    node.child_by_field_name("source")
        .or_else(|| find_child_by_kind(node, "string"))
        .and_then(|source_node| string_literal_content(source, source_node))
}

/// The first node of kind `kind` below `node`, in source order (`node`
/// itself excluded). The search keeps its place in a tree cursor rather than
/// recursing, so a deeply nested file cannot overflow the stack, which
/// would abort the process.
pub fn find_child_by_kind<'tree>(
    node: tree_sitter::Node<'tree>,
    kind: &str,
) -> Option<tree_sitter::Node<'tree>> {
    let mut cursor = node.walk();
    if !cursor.goto_first_child() {
        return None;
    }
    loop {
        if cursor.node().kind() == kind {
            return Some(cursor.node());
        }
        if cursor.goto_first_child() {
            continue;
        }
        // Move past this subtree: to the next sibling, or up until an
        // ancestor has one. The cursor cannot climb above `node`.
        while !cursor.goto_next_sibling() {
            if !cursor.goto_parent() || cursor.node().id() == node.id() {
                return None;
            }
        }
    }
}

pub fn string_literal_content(source: &str, node: tree_sitter::Node) -> Option<String> {
    let raw = node_text(source, node).trim();
    let quote = raw.chars().next()?;
    if quote != '\'' && quote != '"' {
        return None;
    }
    raw.strip_prefix(quote)
        .and_then(|value| value.strip_suffix(quote))
        .map(ToOwned::to_owned)
}

pub fn node_text<'a>(source: &'a str, node: tree_sitter::Node) -> &'a str {
    &source[node.byte_range()]
}

#[derive(Debug)]
pub struct ReexportSpecifier {
    pub imported: String,
    pub exported: String,
}

#[derive(Debug)]
pub struct RustReexportSpecifier {
    pub module_path: Vec<String>,
    pub imported: String,
    pub exported: String,
}

pub fn supports_type_refs(lang: LangId) -> bool {
    matches!(
        lang,
        LangId::TypeScript
            | LangId::Tsx
            | LangId::JavaScript
            | LangId::Python
            | LangId::Rust
            | LangId::Go
    )
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawImportContribution {
    pub source: String,
    #[serde(default)]
    pub names: Vec<String>,
    #[serde(default)]
    pub default_import: Option<String>,
    #[serde(default)]
    pub namespace_import: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawReexportContribution {
    pub language: String,
    pub source: String,
    pub kind: String,
    #[serde(default)]
    pub imported: Option<String>,
    #[serde(default)]
    pub exported: Option<String>,
    pub line: u32,
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub struct MacroTokenRefContribution {
    pub caller_symbol: String,
    pub line: u32,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<Vec<String>>,
    pub shape: String,
}