code2graph 0.0.0-beta.3

Purpose-neutral code-graph extraction: source files → symbols, references, and cross-file edges. Tree-sitter based, no storage opinion.
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
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
// SPDX-License-Identifier: Apache-2.0

//! Rust extractor — one tree-sitter pass yielding definitions and references.
//!
//! Definitions: ALL top-level items (`fn/struct/enum/trait/type/const/static/mod`)
//! plus `impl` blocks, each tagged with its real [`Visibility`]. `pub` items get
//! `Visibility::Public`; `pub(crate)` / `pub(super)` / `pub(in …)` get
//! `Visibility::Internal`; items with no visibility modifier get `Visibility::Private`.
//! Qualified identity follows the module path derived from the file path
//! (`src/auth/session.rs` → namespaces `auth`,`session`). References: callee
//! identifiers of `call_expression` nodes.
//!
//! Emits neutral [`FileFacts`] — no storage entries, no source bodies.

use tree_sitter::{Language as TsLanguage, Node, Parser, Query, QueryCursor, StreamingIterator};

use crate::error::{CodegraphError, Result};
use crate::graph::types::{
    Binding, BindingKind, ByteSpan, EntryPoint, FfiAbi, FfiExport, FileFacts, RefRole, Reference,
    Scope, ScopeId, ScopeKind, Symbol, SymbolKind, Visibility,
};
use crate::lang::Language;
use crate::symbol::Descriptor;

use super::{
    ExtractCtx, Extractor, MIN_REF_LEN, attach_reference_scopes, child_text,
    collect_call_references, definition_bindings, import_bindings, make_symbol, node_occurrence,
    node_span, node_text, one_line_signature, push_binding, push_ref, push_scope,
};

/// Tree-sitter query capturing call-callee identifiers (and optional qualifier).
const CALL_QUERY: &str = r#"
(call_expression
  function: [
    (identifier) @callee
    (field_expression field: (field_identifier) @callee)
    (scoped_identifier path: (_) @qualifier name: (identifier) @callee)
  ]
)
"#;

/// Tree-sitter query capturing type-position nodes for [`RefRole::TypeRef`] extraction.
///
/// Field names verified against `tree-sitter-rust-0.23.3/src/node-types.json`:
/// - `parameter` has field `type: _type`
/// - `function_item` has field `return_type: _type`
/// - `field_declaration` has field `type: _type`
/// - `ordered_field_declaration_list` has field `type: _type` (multiple = true, for tuple structs)
const TYPE_QUERY: &str = r#"
(parameter type: (_) @ty)
(function_item return_type: (_) @ty)
(field_declaration type: (_) @ty)
(ordered_field_declaration_list type: (_) @ty)
"#;

/// Extracts Rust symbols and references.
pub struct RustExtractor;

impl Extractor for RustExtractor {
    fn lang(&self) -> Language {
        Language::Rust
    }

    fn extract(&self, source: &str, file: &str) -> Result<FileFacts> {
        let ts_language = crate::grammar::rust();
        let mut parser = Parser::new();
        parser
            .set_language(&ts_language)
            .map_err(|_| CodegraphError::Parse {
                path: file.to_owned(),
            })?;
        let tree = parser
            .parse(source, None)
            .ok_or_else(|| CodegraphError::Parse {
                path: file.to_owned(),
            })?;

        let root = tree.root_node();
        let bytes = source.as_bytes();
        let namespaces = rust_namespaces(file);

        let ctx = ExtractCtx {
            bytes,
            file,
            lang: Language::Rust,
        };
        let defs = collect_symbols(&root, &ctx, &namespaces);
        let def_bindings = definition_bindings(&defs);
        let ffi_exports = collect_ffi_exports(&root, bytes, &defs);
        let mut symbols = defs;
        let mod_sym = super::module_symbol(Language::Rust, &namespaces, file, source.len());
        let module_id = mod_sym.id.to_scip_string();
        symbols.push(mod_sym);
        let mut references =
            collect_call_references(&root, &ts_language, CALL_QUERY, Language::Rust, bytes, file)?;
        collect_inheritance(&root, bytes, file, &mut references);
        collect_module_decl_refs(&root, bytes, file, &mut references);
        collect_imports(&root, bytes, file, &mut references, &module_id);
        collect_type_references(&root, &ts_language, bytes, file, &mut references)?;
        collect_read_references(&root, bytes, file, &mut references);
        collect_write_references(&root, bytes, file, &mut references);

        let scopes = collect_scopes(&root, source.len());
        attach_reference_scopes(&mut references, &scopes);
        let mut bindings = collect_bindings(&root, bytes, &scopes);
        bindings.extend(def_bindings);
        bindings.extend(import_bindings(&references, &scopes));

        Ok(FileFacts {
            file: file.to_owned(),
            lang: Language::Rust.as_str().to_owned(),
            symbols,
            references,
            scopes,
            bindings,
            ffi_exports,
        })
    }
}

/// Derive the Rust module path (namespace descriptors) from a file path.
fn rust_namespaces(file: &str) -> Vec<String> {
    let p = file.strip_suffix(".rs").unwrap_or(file);
    let p = p.strip_prefix("src/").unwrap_or(p);
    let mut segs: Vec<String> = p
        .split('/')
        .filter(|s| !s.is_empty())
        .map(str::to_owned)
        .collect();
    if let Some(last) = segs.last() {
        if matches!(last.as_str(), "mod" | "lib" | "main") {
            segs.pop();
        }
    }
    segs
}

fn collect_symbols(root: &Node, ctx: &ExtractCtx, namespaces: &[String]) -> Vec<Symbol> {
    let bytes = ctx.bytes;
    let mut out = Vec::new();
    for child in root.children(&mut root.walk()) {
        let (kind, leaf) = match child.kind() {
            "function_item" => {
                let Some(name) = child_text(&child, "identifier", bytes) else {
                    continue;
                };
                (
                    SymbolKind::Function,
                    Descriptor::Method {
                        name: name.clone(),
                        disambiguator: String::new(),
                    },
                )
            }
            "struct_item" => {
                let Some(name) = child_text(&child, "type_identifier", bytes) else {
                    continue;
                };
                (SymbolKind::Struct, Descriptor::Type(name))
            }
            "enum_item" => {
                let Some(name) = child_text(&child, "type_identifier", bytes) else {
                    continue;
                };
                (SymbolKind::Enum, Descriptor::Type(name))
            }
            "trait_item" => {
                let Some(name) = child_text(&child, "type_identifier", bytes) else {
                    continue;
                };
                (SymbolKind::Trait, Descriptor::Type(name))
            }
            "type_item" => {
                let Some(name) = child_text(&child, "type_identifier", bytes) else {
                    continue;
                };
                (SymbolKind::TypeAlias, Descriptor::Type(name))
            }
            "const_item" => {
                let Some(name) = child_text(&child, "identifier", bytes) else {
                    continue;
                };
                (SymbolKind::Const, Descriptor::Term(name))
            }
            "static_item" => {
                let Some(name) = child_text(&child, "identifier", bytes) else {
                    continue;
                };
                (SymbolKind::Static, Descriptor::Term(name))
            }
            "mod_item" => {
                // Only inline modules (`mod foo { … }`) produce a Module symbol.
                // A body-less declaration (`mod foo;`) is purely a ModuleRef
                // reference (emitted by `collect_module_decl_refs`) and must NOT
                // emit a duplicate Module symbol — that would create two `foo`
                // definitions and break `unique_match` resolution.
                if child.child_by_field_name("body").is_none() {
                    continue;
                }
                let Some(name) = child_text(&child, "identifier", bytes) else {
                    continue;
                };
                (SymbolKind::Module, Descriptor::Namespace(name))
            }
            "impl_item" => {
                let name = impl_type_name(&child, bytes);
                (SymbolKind::Impl, Descriptor::Type(name))
            }
            _ => continue,
        };

        // `impl` blocks carry no visibility modifier in Rust; they are always Public.
        let visibility = if kind == SymbolKind::Impl {
            Visibility::Public
        } else {
            read_visibility(&child, bytes)
        };

        // Extract the name before moving `leaf` into `descriptors` so no clone is needed.
        let sym_name = leaf.name().to_owned();
        let mut descriptors: Vec<Descriptor> = namespaces
            .iter()
            .cloned()
            .map(Descriptor::Namespace)
            .collect();
        descriptors.push(leaf);

        let signature = one_line_signature(node_text(&child, bytes), &['{']);
        out.push(make_symbol(
            ctx,
            &child,
            // Cloned because `sym_name` is reused below as the type/trait name
            // when descending into impl/trait members.
            sym_name.clone(),
            kind,
            visibility,
            descriptors,
            signature,
        ));
        // Populate entry-point markers for function definitions only.
        if kind == SymbolKind::Function {
            if let Some(sym) = out.last_mut() {
                sym.entry_points = entry_points_for_rust(&sym_name, &child, bytes);
            }
        }

        // For inherent impl blocks, also emit symbols for their members (all
        // visibilities). Trait-impl members are deferred: the call qualifier is
        // `self`, not the type, and method extraction risks collisions with
        // inherent methods.
        if kind == SymbolKind::Impl && child.child_by_field_name("trait").is_none() {
            collect_impl_members(&child, ctx, namespaces, &sym_name, &mut out);
        }

        // For trait definitions, emit symbols for their member methods and
        // associated consts so the conformance resolver can link inherited-method
        // calls to the trait's own definition. Trait items have no `pub` modifier
        // — they are implicitly public whenever the trait is public, so we pass
        // `Visibility::Public` for all trait members.
        if kind == SymbolKind::Trait {
            collect_trait_members(&child, ctx, namespaces, &sym_name, &mut out);
        }
    }
    out
}

/// Build the descriptor path for one member of an `impl` or `trait` body:
/// `namespaces.map(Namespace) ++ [Type(type_name), leaf]`.
///
/// Shared by [`collect_impl_members`] and [`collect_trait_members`] so the two
/// call sites don't duplicate the prefix construction. The `Symbol` itself is
/// built by [`make_symbol`] at the call site.
fn member_descriptors(namespaces: &[String], type_name: &str, leaf: Descriptor) -> Vec<Descriptor> {
    let mut descriptors: Vec<Descriptor> = namespaces
        .iter()
        .cloned()
        .map(Descriptor::Namespace)
        .collect();
    descriptors.push(Descriptor::Type(type_name.to_owned()));
    descriptors.push(leaf);
    descriptors
}

/// Walk an inherent `impl_item` node and emit member symbols (all visibilities).
///
/// Covers `function_item` members (→ [`SymbolKind::Method`]) and `const_item`
/// members (→ [`SymbolKind::Const`]) found in the `declaration_list` body.
/// Each member's real [`Visibility`] is read from its own `visibility_modifier`
/// child via [`read_visibility`] and recorded on the emitted symbol.
///
/// Descriptors: `namespaces.map(Namespace) ++ [Type(type_name), Method/Term(member_name)]`.
/// SCIP renders e.g. `…/Foo#new().` for a method and `…/Foo#MAX.` for a const.
fn collect_impl_members(
    impl_node: &Node,
    ctx: &ExtractCtx,
    namespaces: &[String],
    type_name: &str,
    out: &mut Vec<Symbol>,
) {
    let bytes = ctx.bytes;
    // The `body` field is the `declaration_list` — use the field accessor
    // (idiomatic here; `scope_dfs` / `collect_bindings_dfs` do the same).
    let Some(body) = impl_node.child_by_field_name("body") else {
        return;
    };

    for member in body.children(&mut body.walk()) {
        let (kind, leaf) = match member.kind() {
            "function_item" => {
                // Reuse the same name-extraction the top-level function_item arm uses.
                let Some(name) = child_text(&member, "identifier", bytes) else {
                    continue;
                };
                (
                    SymbolKind::Method,
                    Descriptor::Method {
                        name,
                        disambiguator: String::new(),
                    },
                )
            }
            "const_item" => {
                // Reuse the same name-extraction the top-level const_item arm uses.
                let Some(name) = child_text(&member, "identifier", bytes) else {
                    continue;
                };
                (SymbolKind::Const, Descriptor::Term(name))
            }
            _ => continue,
        };

        let visibility = read_visibility(&member, bytes);
        let member_name = leaf.name().to_owned();
        let descriptors = member_descriptors(namespaces, type_name, leaf);
        let signature = one_line_signature(node_text(&member, bytes), &['{']);
        out.push(make_symbol(
            ctx,
            &member,
            member_name,
            kind,
            visibility,
            descriptors,
            signature,
        ));
    }
}

/// Walk a `trait_item` node and emit member symbols for its body.
///
/// Covers three node kinds found inside a `declaration_list` (the `body` field
/// of `trait_item`):
/// - `function_signature_item` — a required method with no default body
///   (e.g. `fn hello(&self);`) → [`SymbolKind::Method`].
/// - `function_item` — a method with a default body
///   (e.g. `fn greet(&self) { … }`) → [`SymbolKind::Method`].
/// - `const_item` — an associated constant → [`SymbolKind::Const`].
///
/// Trait items carry no `pub` visibility modifier — their effective visibility
/// follows the trait itself. All trait members are therefore emitted with
/// [`Visibility::Public`].
///
/// Descriptors: `namespaces.map(Namespace) ++ [Type(trait_name), Method/Term(member)]`.
/// SCIP renders e.g. `…/Greet#hello().` for a method and `…/Greet#MAX.` for a const.
fn collect_trait_members(
    trait_node: &Node,
    ctx: &ExtractCtx,
    namespaces: &[String],
    trait_name: &str,
    out: &mut Vec<Symbol>,
) {
    let bytes = ctx.bytes;
    let Some(body) = trait_node.child_by_field_name("body") else {
        return;
    };

    for member in body.children(&mut body.walk()) {
        let (kind, leaf) = match member.kind() {
            // Both required methods (`fn hello(&self);`) and default-bodied methods
            // (`fn greet(&self) { … }`) map to SymbolKind::Method with identical
            // descriptor structure, so they share one arm.
            "function_signature_item" | "function_item" => {
                let Some(name) = child_text(&member, "identifier", bytes) else {
                    continue;
                };
                (
                    SymbolKind::Method,
                    Descriptor::Method {
                        name,
                        disambiguator: String::new(),
                    },
                )
            }
            // Associated constant: `const LIMIT: usize = 10;`
            "const_item" => {
                let Some(name) = child_text(&member, "identifier", bytes) else {
                    continue;
                };
                (SymbolKind::Const, Descriptor::Term(name))
            }
            _ => continue,
        };

        // Trait items have no visibility modifier; their visibility follows the
        // trait, so we tag them Public.
        let member_name = leaf.name().to_owned();
        let descriptors = member_descriptors(namespaces, trait_name, leaf);
        let signature = one_line_signature(node_text(&member, bytes), &['{']);
        out.push(make_symbol(
            ctx,
            &member,
            member_name,
            kind,
            Visibility::Public,
            descriptors,
            signature,
        ));
    }
}

/// Read the real [`Visibility`] from a node's `visibility_modifier` child.
///
/// - `"pub"` (bare) → [`Visibility::Public`].
/// - Any `pub(…)` restricted form (`pub(crate)`, `pub(super)`, `pub(self)`,
///   `pub(in …)`) → [`Visibility::Internal`]: restricted but not fully private.
/// - No `visibility_modifier` child → [`Visibility::Private`] (Rust default).
fn read_visibility(node: &Node, bytes: &[u8]) -> Visibility {
    let modifier = node
        .children(&mut node.walk())
        .find(|c| c.kind() == "visibility_modifier")
        .map(|c| node_text(&c, bytes));
    match modifier {
        Some("pub") => Visibility::Public,
        Some(text) if text.starts_with("pub(") => Visibility::Internal,
        _ => Visibility::Private,
    }
}

/// Attribute path terminal identifiers that mark a Rust function as an HTTP route
/// handler.
///
/// Detection rule (honest boundary): a function is an HTTP-route entry point when
/// one of its outer `#[...]` attributes has a path whose terminal identifier is in
/// this set. Terminal extraction: for a bare path like `#[get("/")]` the terminal
/// is the text of the first named child of `attribute` (an `identifier`); for a
/// qualified path like `#[actix_web::get("/")]` it is the `name:` field of the
/// `scoped_identifier` first named child. Attributes NOT in this set (`#[derive(...)]`,
/// `#[tokio::main]`, `#[no_mangle]`, `#[inline]`, `#[cfg(...)]`) produce no
/// marker. Note that `#[tokio::main]` has terminal `main`, which is NOT in this
/// set — it is correctly excluded. The `fn main` NAME check handles the
/// entry-function regardless of such attributes.
///
/// Covers Actix-web and Rocket route attribute conventions. Cannot detect
/// dynamically constructed route registrations or non-standard attribute aliases.
const RUST_ROUTE_ATTRS: &[&str] = &[
    "get", "post", "put", "delete", "patch", "head", "options", "route", "connect", "trace",
];

/// Compute entry-point markers for a top-level Rust function symbol.
///
/// `fn_name` is the bare function name (for `Main` detection).
/// `func` is the `function_item` node whose outer attributes (preceding
/// `attribute_item` siblings) are inspected for HTTP-route markers.
///
/// Node-kind path for route attribute detection (tree-sitter-rust grammar verified):
/// ```text
/// attribute_item                  ← preceding sibling of function_item
///   attribute                     ← single named child (no field name)
///     identifier                  ← first named child, bare: #[get("/")]
///     OR
///     scoped_identifier           ← first named child, qualified: #[actix_web::get("/")]
///       name: identifier          ← `name` field → terminal = "get"
/// ```
/// The attribute node has no `path:` field in the grammar; the path node is the
/// first named child of `attribute`. Attributes NOT in [`RUST_ROUTE_ATTRS`] (e.g.
/// `#[derive(...)]`, `#[no_mangle]`, `#[inline]`) produce no marker.  Multiple
/// matching attributes are all emitted (preserve order).
///
/// This reuses the same preceding-sibling walk that [`fn_ffi_exports`] uses —
/// the only per-attribute difference is which terminal string we match.
fn entry_points_for_rust(fn_name: &str, func: &Node, bytes: &[u8]) -> Vec<EntryPoint> {
    let mut markers: Vec<EntryPoint> = Vec::new();

    // (a) Name-based: a function literally named `main` → EntryPoint::Main.
    if fn_name == "main" {
        markers.push(EntryPoint::Main);
    }

    // (b) HTTP-route outer-attribute detection — walk preceding attribute_item siblings.
    // Outer attributes in tree-sitter-rust are preceding siblings of the item node, not
    // its children.  We walk backward until we encounter a non-attribute_item sibling,
    // matching the same traversal used by fn_ffi_exports.
    let mut sib = func.prev_sibling();
    while let Some(node) = sib {
        if node.kind() != "attribute_item" {
            break;
        }
        // attribute_item has a single named child: the `attribute` node.
        // The `attribute` node's path is its FIRST named child (an `identifier`
        // or `scoped_identifier`) — tree-sitter-rust has no `path:` field on
        // `attribute`; verified against node-types.json.
        if let Some(attr) = node.named_children(&mut node.walk()).next() {
            if attr.kind() == "attribute" {
                // First named child of `attribute` is the macro path node.
                if let Some(path_node) = attr.named_children(&mut attr.walk()).next() {
                    // Extract the terminal identifier:
                    //   - `identifier`        → its own text (bare #[get(...)])
                    //   - `scoped_identifier` → its `name` field (qualified #[a::b::get(...)])
                    let terminal = match path_node.kind() {
                        "identifier" => node_text(&path_node, bytes),
                        "scoped_identifier" => path_node
                            .child_by_field_name("name")
                            .map_or("", |n| node_text(&n, bytes)),
                        _ => "",
                    };
                    if !terminal.is_empty() && RUST_ROUTE_ATTRS.contains(&terminal) {
                        markers.push(EntryPoint::HttpRoute(terminal.to_owned()));
                    }
                }
            }
        }
        sib = node.prev_sibling();
    }

    // The preceding-sibling walk visits attributes in bottom-up order (closest
    // attribute first).  Reverse so markers appear in top-down source order.
    // Main (from the name check) is always first regardless.
    let main_count = markers
        .iter()
        .take_while(|m| matches!(m, EntryPoint::Main))
        .count();
    markers[main_count..].reverse();

    markers
}

/// Collect cross-language export markers from top-level functions.
///
/// Detected today:
/// - **C ABI** — `#[no_mangle]` / `#[unsafe(no_mangle)]` (exported under the
///   function name) and `#[export_name = "…"]` (name override). A plain
///   `extern "C"` *without* such a marker is mangled and intentionally not an
///   export.
/// - **Python ABI** — PyO3 `#[pyfunction]` (exported under the function name, or
///   a `#[pyo3(name = "…")]` / `#[pyfunction(name = "…")]` override).
/// - **Wasm/JS ABI** — `#[wasm_bindgen]` (exported under the function name, or a
///   `#[wasm_bindgen(js_name = "…")]` override).
/// - **Node.js ABI** — `#[napi]` (exported under the function name, or a
///   `#[napi(js_name = "…")]` override).
///
/// Only functions extracted as symbols (the public ones) are bridged; each
/// export is matched to its symbol by definition span, so the SCIP identity is
/// exactly the one the resolver will see. A function may export under more than
/// one ABI.
fn collect_ffi_exports(root: &Node, bytes: &[u8], defs: &[Symbol]) -> Vec<FfiExport> {
    let mut out = Vec::new();
    for child in root.children(&mut root.walk()) {
        if child.kind() != "function_item" {
            continue;
        }
        let Some(sym) = defs
            .iter()
            .find(|s| s.kind == SymbolKind::Function && s.span.start == child.start_byte())
        else {
            continue; // not an extracted symbol — no identity to bridge
        };
        for (abi, export_name) in fn_ffi_exports(&child, bytes, &sym.name) {
            out.push(FfiExport {
                symbol: sym.id.clone(),
                abi,
                export_name,
            });
        }
    }
    out
}

/// The FFI exports a function declares, derived from its attributes.
///
/// In tree-sitter-rust an item's outer attributes are its **preceding siblings**
/// (not children), so we walk back over the run of `attribute_item` nodes,
/// collecting their texts. The marker→ABI classification lives in the neutral
/// per-ABI registry ([`crate::ffi::rust_exports`]); reading attribute text keeps
/// it robust to spelling variants (`#[no_mangle]` vs `#[unsafe(no_mangle)]`).
fn fn_ffi_exports(func: &Node, bytes: &[u8], fn_name: &str) -> Vec<(FfiAbi, String)> {
    let mut attr_texts: Vec<&str> = Vec::new();
    let mut sib = func.prev_sibling();
    while let Some(node) = sib {
        if node.kind() != "attribute_item" {
            break;
        }
        attr_texts.push(node_text(&node, bytes));
        sib = node.prev_sibling();
    }
    crate::ffi::rust_exports(&attr_texts, fn_name)
}

/// Display name for an `impl` block: the last type identifier before the body.
fn impl_type_name(node: &Node, bytes: &[u8]) -> String {
    let mut name: Option<String> = None;
    for child in node.children(&mut node.walk()) {
        match child.kind() {
            "type_identifier" | "generic_type" | "scoped_type_identifier" => {
                name = Some(node_text(&child, bytes).to_owned());
            }
            "declaration_list" => break,
            _ => {}
        }
    }
    name.unwrap_or_else(|| "impl".to_owned())
}

/// Recursively walk `node` collecting `Inherit` references for every
/// `impl_item` (trait implementation) and `trait_item` (supertrait bound) in
/// the tree (including items inside `mod` blocks).
fn collect_inheritance(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    match node.kind() {
        "impl_item" => {
            // Only trait impls have a `trait` field; inherent impls do not.
            if let Some(trait_node) = node.child_by_field_name("trait") {
                super::push_ref(
                    out,
                    super::simple_type_name(node_text(&trait_node, bytes), "::"),
                    &trait_node,
                    file,
                    RefRole::IsImplementation,
                );
            }
        }
        "trait_item" => {
            // `bounds` field is a `trait_bounds` node listing supertraits.
            if let Some(bounds) = node.child_by_field_name("bounds") {
                for child in bounds.children(&mut bounds.walk()) {
                    match child.kind() {
                        "type_identifier" | "generic_type" | "scoped_type_identifier" => {
                            super::push_ref(
                                out,
                                super::simple_type_name(node_text(&child, bytes), "::"),
                                &child,
                                file,
                                RefRole::IsImplementation,
                            );
                        }
                        _ => {}
                    }
                }
            }
        }
        _ => {}
    }

    // Recurse into all children so items inside `mod` blocks are covered.
    for child in node.children(&mut node.walk()) {
        collect_inheritance(&child, bytes, file, out);
    }
}

/// Recursively walk `node` and emit a [`RefRole::ModuleRef`] reference for every
/// `mod x;` / `pub mod x;` declaration (`mod_item`), regardless of visibility.
///
/// This is a *reference* (a module-dependency fact). A body-less `mod x;`
/// declaration does NOT produce a Module [`Symbol`] — its defining symbol is
/// the file `x.rs` (emitted there via [`super::module_symbol`]). An inline
/// `mod x { … }` DOES produce a Module symbol from `collect_symbols`.
/// The resolver connects the two; the extractor only states the facts. The
/// occurrence is positioned at the module-name identifier (the `name` field) so
/// location-based oracle matching lines up with the `mod x;` site. Recurses into
/// `mod` blocks so nested declarations are also captured.
fn collect_module_decl_refs(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    if node.kind() == "mod_item" {
        if let Some(name_node) = node.child_by_field_name("name") {
            push_ref(
                out,
                node_text(&name_node, bytes),
                &name_node,
                file,
                RefRole::ModuleRef,
            );
        }
    }
    for child in node.children(&mut node.walk()) {
        collect_module_decl_refs(&child, bytes, file, out);
    }
}

/// Emit a [`RefRole::ModuleRef`] for **every** module segment that precedes the
/// imported leaf of a use-path. Given the `path` field of a leaf
/// `scoped_identifier{ path, name }` (where `name` is the imported leaf, already
/// emitted as an `Import`), this walks the entire `path` chain and emits one
/// `ModuleRef` per module segment. For `crate::a::b::helper` the leaf is
/// `helper` and the segments are `crate`, `a`, `b`; for `a::b::c::Thing` they are
/// `a`, `b`, `c`. Each occurrence is positioned at *that* segment's own node, so
/// edge locations point at the precise segment rather than the whole path.
///
/// The chain is processed deepest-first: when `path` is itself a
/// `scoped_identifier{ path: inner, name: seg }` we recurse into `inner` before
/// emitting `seg`. The innermost node determines the base case by kind:
/// - `identifier` → emit a `ModuleRef` named after it.
/// - `crate` → in a **crate-root file** (`lib.rs`, `main.rs`, `mod.rs`) it names
///   *this very file's* module, so emit a `ModuleRef` named after this file's own
///   module symbol, positioned at the `crate` keyword — letting Tier-B resolve it
///   to the file's per-file module. In a **non-root** file `crate` refers to a
///   *different* file (the crate root, which this extractor cannot identify from a
///   single file), so it is skipped — an honest limitation, not a wrong edge.
/// - `self` / `super` / `Self` / `metavariable` / anything else → skip; they
///   never name a resolvable local module.
///
/// (External roots like `std` are *not* anchors and are still emitted as plain
/// `identifier` segments; the resolver simply finds no matching local module and
/// emits no edge — an honest no-op.)
fn push_path_module_refs(path: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    match path.kind() {
        "scoped_identifier" => {
            // Process the deeper prefix first so segments are emitted in path
            // order, then the segment named by this node's `name` field.
            if let Some(inner) = path.child_by_field_name("path") {
                push_path_module_refs(&inner, bytes, file, out);
            }
            let Some(seg) = path.child_by_field_name("name") else {
                return;
            };
            let name = node_text(&seg, bytes);
            if matches!(name, "crate" | "self" | "super" | "Self") {
                return;
            }
            push_ref(out, name, &seg, file, RefRole::ModuleRef);
        }
        "identifier" => {
            push_ref(out, node_text(path, bytes), path, file, RefRole::ModuleRef);
        }
        // The `crate` keyword anchor: in a crate-root file it names this file's
        // own module, so emit a ModuleRef for it positioned at the keyword.
        "crate" if is_crate_root(file) => {
            push_ref(out, &self_module_name(file), path, file, RefRole::ModuleRef);
        }
        // `self`/`super`/`Self`/`crate`(non-root)/`metavariable`/other: skip.
        _ => {}
    }
}

/// Whether `file` is a crate-root file — its basename is `lib.rs`, `main.rs`, or
/// `mod.rs` (matches both a bare `lib.rs` and a path like `src/lib.rs`).
fn is_crate_root(file: &str) -> bool {
    let base = file.rsplit('/').next().unwrap_or(file);
    matches!(base, "lib.rs" | "main.rs" | "mod.rs")
}

/// This file's own module-symbol name, derived through the shared
/// [`super::module_name`] so the emitted ModuleRef name equals the file's module
/// symbol and therefore resolves against the Tier-B module index.
fn self_module_name(file: &str) -> String {
    super::module_name(&rust_namespaces(file), file)
}

/// Recursively collect leaf import names from a use-tree node and push an
/// [`RefRole::Import`] reference for each one.
///
/// `prefix` is the accumulated path prefix from enclosing `scoped_use_list`
/// nodes (e.g. `"std::collections"` when processing the list in
/// `use std::collections::{HashMap, BTreeMap}`). It is threaded downward so
/// bare `identifier` leaves inside a `use_list` can report their `from_path`.
///
/// The leaf is always the concrete identifier being imported:
/// - `identifier`         → `from_path = prefix` (the received prefix).
/// - `scoped_identifier`  → `from_path` = its own `path` field (authoritative).
/// - `use_as_clause`      → recurse into the `path` field (alias ignored), passing `prefix` through.
/// - `scoped_use_list`    → compute `new_prefix` from the node's `path` field, then recurse into `list`.
/// - `use_list`           → recurse each named child, passing `prefix` through.
/// - `use_wildcard` / `crate` / `self` / `super` / anything else → skip.
fn collect_use_leaves(
    node: &Node,
    bytes: &[u8],
    file: &str,
    out: &mut Vec<Reference>,
    module_id: &str,
    prefix: &str,
) {
    match node.kind() {
        "identifier" => {
            // Bare leaf inside a use_list — from_path is the enclosing prefix.
            super::push_import_ref(
                out,
                super::node_text(node, bytes),
                node,
                file,
                module_id,
                prefix,
            );
        }
        "scoped_identifier" => {
            // The node's `path` field is the authoritative from-path.
            // Bind once: used both for from_path text and for ModuleRef emission.
            let path_node = node.child_by_field_name("path");
            let from_path = path_node
                .as_ref()
                .map_or("", |n| super::node_text(n, bytes));
            // Emit a ModuleRef for every module segment preceding the leaf
            // (e.g. `crate`/`alpha` in `crate::alpha::helper`); anchors are
            // resolved/skipped inside per the file's crate-root status.
            if let Some(ref pn) = path_node {
                push_path_module_refs(pn, bytes, file, out);
            }
            if let Some(name_node) = node.child_by_field_name("name") {
                super::push_import_ref(
                    out,
                    super::node_text(&name_node, bytes),
                    &name_node,
                    file,
                    module_id,
                    from_path,
                );
            }
        }
        "use_as_clause" => {
            // Alias is ignored; recurse into the path child, passing prefix through.
            if let Some(path_node) = node.child_by_field_name("path") {
                collect_use_leaves(&path_node, bytes, file, out, module_id, prefix);
            }
        }
        "scoped_use_list" => {
            // Compute a fresh prefix from this node's `path` field, then recurse
            // into the list with that prefix so bare identifiers inside the list
            // can report the correct from_path.
            let new_prefix = node
                .child_by_field_name("path")
                .map_or("", |n| super::node_text(&n, bytes));
            if let Some(list_node) = node.child_by_field_name("list") {
                collect_use_leaves(&list_node, bytes, file, out, module_id, new_prefix);
            }
        }
        "use_list" => {
            for child in node.named_children(&mut node.walk()) {
                collect_use_leaves(&child, bytes, file, out, module_id, prefix);
            }
        }
        // use_wildcard, crate, self, super, metavariable → skip
        _ => {}
    }
}

/// Walk the full tree and emit [`RefRole::Import`] references for every
/// `use_declaration`. Recurses into `mod` blocks and function bodies so nested
/// `use` items are also captured.
fn collect_imports(
    node: &Node,
    bytes: &[u8],
    file: &str,
    out: &mut Vec<Reference>,
    module_id: &str,
) {
    if node.kind() == "use_declaration" {
        if let Some(arg) = node.child_by_field_name("argument") {
            collect_use_leaves(&arg, bytes, file, out, module_id, "");
        }
        // No need to recurse further inside a use_declaration.
        return;
    }
    for child in node.children(&mut node.walk()) {
        collect_imports(&child, bytes, file, out, module_id);
    }
}

// ── Type reference capture ────────────────────────────────────────────────────

/// Reduce a (possibly compound) type node to its base named type.
///
/// Returns `(bare_name, qualifier)` for the type forms we handle in v1.
/// Returns `None` for forms we defer (tuple, array, pointer, slice, fn pointer,
/// lifetime-only, etc.) — they produce no [`RefRole::TypeRef`] reference.
///
/// Recursion depth is bounded by type nesting depth (a handful of levels at
/// most); no panic paths, no `unwrap`.
///
/// **Primitive types are skipped** (`primitive_type` matches `None`): they
/// never resolve to a user-defined [`Symbol`], so capturing them adds noise
/// with zero benefit. E.g. `u32`, `bool`, `i64` produce no TypeRef ref.
fn base_type_name(node: &Node, bytes: &[u8]) -> Option<(String, Option<String>)> {
    match node.kind() {
        "type_identifier" => Some((node_text(node, bytes).to_owned(), None)),
        // Primitive types (u8, i32, bool, str, …) — skip to reduce noise.
        "primitive_type" => None,
        "scoped_type_identifier" => {
            // Grammar-verified fields: `name: type_identifier`, `path: ...`
            let name = node
                .child_by_field_name("name")
                .map(|n| node_text(&n, bytes).to_owned())?;
            let qual = node
                .child_by_field_name("path")
                .map(|n| node_text(&n, bytes).to_owned());
            Some((name, qual))
        }
        // Vec<Config> → base name "Vec"; the Config inside type_arguments is
        // deferred in v1 (not captured here).
        "generic_type" => node
            .child_by_field_name("type")
            .and_then(|t| base_type_name(&t, bytes)),
        // &Config / &mut Config → descend through the `type` field (grammar-verified).
        "reference_type" => node
            .child_by_field_name("type")
            .and_then(|t| base_type_name(&t, bytes)),
        // Defer: tuple_type, array_type, pointer_type, slice_type, abstract_type,
        // dynamic_type, fn types, macro_invocation types, etc.
        _ => None,
    }
}

/// Run [`TYPE_QUERY`] over the tree and push one [`RefRole::TypeRef`]
/// [`Reference`] per resolved base named type.
///
/// Mirrors [`collect_call_references`] in structure (Query + QueryCursor).
/// `primitive_type` nodes are deferred by [`base_type_name`] — they produce
/// no reference. All other unrecognised type forms (tuples, slices, …) are
/// also silently skipped per the v1 boundary.
fn collect_type_references(
    root: &Node,
    ts_lang: &TsLanguage,
    bytes: &[u8],
    file: &str,
    out: &mut Vec<Reference>,
) -> Result<()> {
    let query = Query::new(ts_lang, TYPE_QUERY).map_err(|e| CodegraphError::Query {
        lang: "rust".to_owned(),
        msg: e.to_string(),
    })?;
    let ty_idx = query
        .capture_index_for_name("ty")
        .ok_or_else(|| CodegraphError::Query {
            lang: "rust".to_owned(),
            msg: "missing @ty capture".to_owned(),
        })?;

    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(&query, *root, bytes);
    while let Some(m) = matches.next() {
        for cap in m.captures.iter().filter(|c| c.index == ty_idx) {
            if let Some((name, qualifier)) = base_type_name(&cap.node, bytes) {
                out.push(Reference {
                    name,
                    occ: node_occurrence(&cap.node, file),
                    role: RefRole::TypeRef,
                    source_module: None,
                    from_path: None,
                    qualifier,
                    scope: None, // filled in by attach_reference_scopes
                    type_ref_ctx: None,
                });
            }
        }
    }
    Ok(())
}

// ── Edge richness: Read / Write ──────────────────────────────────────────────

/// Returns `true` when `node` (an `identifier`) is in a Rust position that is
/// already captured by another collector and must NOT also be emitted as a Read.
///
/// Skipped positions:
/// - Call callee (`call_expression` `function:` field)
/// - Declaration name (`function_item`, `struct_item`, `enum_item`, `const_item`,
///   `static_item`, `mod_item`, `trait_item`, `type_item` → `name:` field)
/// - `let_declaration` pattern binding (the bound `identifier`)
/// - `parameter` pattern (`pattern:` field)
/// - `use_declaration` / `use_list` / `scoped_use_list` descendants — already
///   [`RefRole::Import`]
/// - `scoped_identifier` child (path segment — only the final tail is a read,
///   and only when the `scoped_identifier` itself is not a callee; deferred in
///   v1: skip all children of `scoped_identifier` to avoid false positives)
/// - Assignment LHS (`assignment_expression` / `compound_assignment_expr` `left:`)
///   — handled by [`collect_write_references`]
fn is_non_read_position(node: &Node) -> bool {
    let parent = match node.parent() {
        Some(p) => p,
        None => return true, // root — not a read
    };
    match parent.kind() {
        // Call callee: `helper()` — `function:` field of call_expression.
        "call_expression" => parent.child_by_field_name("function").as_ref() == Some(node),
        // Declaration names.
        "function_item" | "struct_item" | "enum_item" | "const_item" | "static_item"
        | "mod_item" | "trait_item" | "type_item" => {
            parent.child_by_field_name("name").as_ref() == Some(node)
        }
        // let binding pattern — the bound identifier.
        "let_declaration" => parent.child_by_field_name("pattern").as_ref() == Some(node),
        // parameter pattern — the bound identifier.
        "parameter" => parent.child_by_field_name("pattern").as_ref() == Some(node),
        // Bare identifier directly inside closure_parameters: `|x| …` — a binding, not a read.
        "closure_parameters" => true,
        // Pattern wrappers inside let/param patterns — the identifier is a binding, not a read.
        "mut_pattern" | "ref_pattern" => true,
        // Path segments inside scoped_identifier — skip all children to avoid
        // false positives from path qualifiers in v1.
        "scoped_identifier" => true,
        // Imports — already RefRole::Import.
        "use_declaration" | "use_list" | "scoped_use_list" | "use_as_clause" => true,
        // Assignment LHS — handled by collect_write_references.
        "assignment_expression" | "compound_assignment_expr" => {
            parent.child_by_field_name("left").as_ref() == Some(node)
        }
        _ => false,
    }
}

/// Recursively walk `node` and emit [`RefRole::Read`] references for bare
/// `identifier` nodes used in value/expression positions.
///
/// Skips identifiers that are:
/// - Call callees (already [`RefRole::Call`])
/// - Declaration names (function/struct/enum/const/static/mod/trait/type `name:` field)
/// - `let_declaration` and `parameter` pattern bindings
/// - Inside use-trees (already [`RefRole::Import`])
/// - Children of `scoped_identifier` (path qualifiers — deferred in v1)
/// - Assignment LHS (handled by [`collect_write_references`])
///
/// Note: `field_identifier` and `type_identifier` are distinct node kinds and
/// are naturally excluded — this function only examines `identifier` nodes.
/// Applies [`MIN_REF_LEN`].
fn collect_read_references(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    // Skip macro bodies — their AST is unreliable.
    if matches!(node.kind(), "macro_definition" | "macro_invocation") {
        return;
    }
    if node.kind() == "identifier" {
        let name = node_text(node, bytes);
        if name.len() >= MIN_REF_LEN && !is_non_read_position(node) {
            push_ref(out, name, node, file, RefRole::Read);
        }
        // `identifier` nodes have no meaningful children; return early.
        return;
    }
    for child in node.children(&mut node.walk()) {
        collect_read_references(&child, bytes, file, out);
    }
}

/// Recursively walk `node` and emit [`RefRole::Write`] references for the
/// bare-identifier LHS of `assignment_expression` and `compound_assignment_expr`
/// nodes (e.g. `x = 5`, `x += 1`).
///
/// Member / index LHS (`obj.field = …`, `arr[i] = …`) are not covered in v1 —
/// only bare `identifier` nodes. Applies [`MIN_REF_LEN`].
///
/// Note: `let_declaration` is a declaration, not an assignment; it is correctly
/// excluded — only `assignment_expression` / `compound_assignment_expr` are handled.
fn collect_write_references(node: &Node, bytes: &[u8], file: &str, out: &mut Vec<Reference>) {
    // Skip macro bodies — their AST is unreliable.
    if matches!(node.kind(), "macro_definition" | "macro_invocation") {
        return;
    }
    if matches!(
        node.kind(),
        "assignment_expression" | "compound_assignment_expr"
    ) {
        if let Some(lhs) = node.child_by_field_name("left") {
            if lhs.kind() == "identifier" {
                let name = node_text(&lhs, bytes);
                if name.len() >= MIN_REF_LEN {
                    push_ref(out, name, &lhs, file, RefRole::Write);
                }
            }
        }
    }
    for child in node.children(&mut node.walk()) {
        collect_write_references(&child, bytes, file, out);
    }
}

// ── Scope tree ───────────────────────────────────────────────────────────────

/// DFS that builds the scope tree for one file.
///
/// The file-root scope (`scopes[0]`) must already be pushed before calling
/// this for the root node's children. `scope_dfs` is called once per node:
/// it inspects `node`'s own kind, opens a new scope for `node` when
/// appropriate, and then recurses into whichever children carry nested scopes.
///
/// `parent_id` is the [`ScopeId`] of the innermost scope already open when
/// this node is visited; new scopes opened for `node` itself use it as their
/// parent.
fn scope_dfs(node: &Node, parent_id: ScopeId, scopes: &mut Vec<Scope>) {
    match node.kind() {
        "function_item" | "closure_expression" => {
            let fn_id = push_scope(
                scopes,
                Some(parent_id),
                node_span(node),
                ScopeKind::Function,
            );
            // Recurse into body's children to avoid double-opening the block.
            if let Some(body) = node.child_by_field_name("body") {
                for child in body.children(&mut body.walk()) {
                    scope_dfs(&child, fn_id, scopes);
                }
            } else {
                for child in node.children(&mut node.walk()) {
                    scope_dfs(&child, fn_id, scopes);
                }
            }
        }
        "mod_item" | "impl_item" | "trait_item" | "struct_item" | "enum_item" => {
            if let Some(body) = node.child_by_field_name("body") {
                let kind = if node.kind() == "mod_item" {
                    ScopeKind::Module
                } else {
                    ScopeKind::Type
                };
                let body_id = push_scope(scopes, Some(parent_id), node_span(&body), kind);
                for child in body.children(&mut body.walk()) {
                    scope_dfs(&child, body_id, scopes);
                }
            } else {
                // No body (e.g. `mod foo;` declaration) — recurse with the same parent.
                for child in node.children(&mut node.walk()) {
                    scope_dfs(&child, parent_id, scopes);
                }
            }
        }
        "block" => {
            let block_id = push_scope(scopes, Some(parent_id), node_span(node), ScopeKind::Block);
            for child in node.children(&mut node.walk()) {
                scope_dfs(&child, block_id, scopes);
            }
        }
        // Macro bodies are not reliable AST — skip entirely.
        "macro_definition" | "macro_invocation" => {}
        // All other nodes: open no scope, recurse children with the same parent.
        _ => {
            for child in node.children(&mut node.walk()) {
                scope_dfs(&child, parent_id, scopes);
            }
        }
    }
}

/// Build and return the full lexical scope tree for `source_len` bytes.
///
/// `scopes[0]` is always the file-root `Module` scope spanning `[0, source_len)`.
fn collect_scopes(root: &Node, source_len: usize) -> Vec<Scope> {
    let mut scopes = Vec::new();
    // Push the file-root scope first (index 0).
    push_scope(
        &mut scopes,
        None,
        ByteSpan {
            start: 0,
            end: source_len,
        },
        ScopeKind::Module,
    );
    // DFS from each top-level child of source_file with parent = 0.
    for child in root.children(&mut root.walk()) {
        scope_dfs(&child, 0, &mut scopes);
    }
    scopes
}

/// Resolve the bare identifier node for a pattern, unwrapping one level of
/// `mut_pattern` or `ref_pattern` if necessary.
///
/// Returns `None` for destructuring patterns (`tuple_pattern`,
/// `tuple_struct_pattern`, `struct_pattern`, slice patterns, …).
///
/// # NOTE
/// Destructuring-pattern bindings (tuple, tuple-struct, struct, slice, or-
/// pattern branches, etc.) are a known gap — this unit handles only simple
/// identifiers and single-level `mut`/`ref` wrappers.  A later unit should
/// walk the pattern recursively and emit a `Binding` for each bound leaf name.
fn resolve_pattern_ident<'tree>(pattern: &Node<'tree>) -> Option<Node<'tree>> {
    match pattern.kind() {
        "identifier" => Some(*pattern),
        "mut_pattern" | "ref_pattern" => {
            // The inner pattern is a named child (no field name); find the
            // first child that is itself an identifier.
            pattern
                .named_children(&mut pattern.walk())
                .find(|c| c.kind() == "identifier")
        }
        // Destructuring patterns — not handled in this unit (see NOTE above).
        _ => None,
    }
}

/// Walk `node` recursively, collecting parameter and local-variable [`Binding`]s.
///
/// Covers:
/// - `function_item` / `closure_expression` parameters: `parameter` children
///   of the `parameters`/`closure_parameters` node, plus `self_parameter`.
/// - `let_declaration` bindings: the `pattern` field.
///
/// All emitted bindings have `target = BindingTarget::Local`.
///
/// `intro` is always the start byte of the **identifier token** (the bound
/// name) — a neutral positional fact; visibility is the resolver's concern.
fn collect_bindings(root: &Node, bytes: &[u8], scopes: &[Scope]) -> Vec<Binding> {
    let mut out = Vec::new();
    collect_bindings_dfs(root, bytes, scopes, &mut out);
    out
}

fn collect_bindings_dfs(node: &Node, bytes: &[u8], scopes: &[Scope], out: &mut Vec<Binding>) {
    match node.kind() {
        "function_item" | "closure_expression" => {
            // Both node kinds expose their parameter list via the "parameters"
            // field (function_item → `parameters` node; closure_expression →
            // `closure_parameters` node).
            if let Some(params_node) = node.child_by_field_name("parameters") {
                collect_params(&params_node, bytes, scopes, out);
            }
            // Recurse into the body (and any other children).
            for child in node.children(&mut node.walk()) {
                collect_bindings_dfs(&child, bytes, scopes, out);
            }
        }
        "let_declaration" => {
            if let Some(pattern_node) = node.child_by_field_name("pattern") {
                if let Some(ident_node) = resolve_pattern_ident(&pattern_node) {
                    let intro = ident_node.start_byte();
                    let name = node_text(&ident_node, bytes).to_owned();
                    push_binding(out, name, intro, BindingKind::Local, scopes);
                }
                // NOTE: destructuring patterns (tuple, struct, slice, …) are
                // not handled in this unit — see `resolve_pattern_ident`.
            }
            // Recurse into children (e.g. the value expression may contain
            // closures with their own params).
            for child in node.children(&mut node.walk()) {
                collect_bindings_dfs(&child, bytes, scopes, out);
            }
        }
        _ => {
            for child in node.children(&mut node.walk()) {
                collect_bindings_dfs(&child, bytes, scopes, out);
            }
        }
    }
}

/// Emit a [`Binding`] for each parameter in a `parameters` or
/// `closure_parameters` node.
fn collect_params(params_node: &Node, bytes: &[u8], scopes: &[Scope], out: &mut Vec<Binding>) {
    for child in params_node.named_children(&mut params_node.walk()) {
        match child.kind() {
            "parameter" => {
                if let Some(pattern_node) = child.child_by_field_name("pattern") {
                    // `pattern` field can be `self` (the keyword node) or any `_pattern`.
                    if pattern_node.kind() == "self" {
                        // `fn f(self)` — typed self, no `&`.
                        let intro = pattern_node.start_byte();
                        push_binding(out, "self".to_owned(), intro, BindingKind::Param, scopes);
                    } else if let Some(ident_node) = resolve_pattern_ident(&pattern_node) {
                        let intro = ident_node.start_byte();
                        let name = node_text(&ident_node, bytes).to_owned();
                        push_binding(out, name, intro, BindingKind::Param, scopes);
                    }
                    // NOTE: destructuring patterns in params not handled — see
                    // `resolve_pattern_ident`.
                }
            }
            "self_parameter" => {
                // `&self`, `&mut self`, or `self` with a lifetime — the `self`
                // keyword is a named child (no field).
                if let Some(self_node) = child
                    .named_children(&mut child.walk())
                    .find(|c| c.kind() == "self")
                {
                    let intro = self_node.start_byte();
                    push_binding(out, "self".to_owned(), intro, BindingKind::Param, scopes);
                }
            }
            // Bare `identifier` directly inside `closure_parameters` (e.g.
            // `|x| …` where `x` has no explicit type annotation).
            "identifier" => {
                let intro = child.start_byte();
                let name = node_text(&child, bytes).to_owned();
                push_binding(out, name, intro, BindingKind::Param, scopes);
            }
            _ => {}
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::graph::types::BindingTarget;

    #[test]
    fn extracts_defs_with_scip_ids() {
        let src = r#"
pub fn validate_token(tok: &str) -> bool { helper() }
fn private_helper() {}
pub struct Config { pub value: u32 }
"#;
        let facts = RustExtractor.extract(src, "src/auth/session.rs").unwrap();
        let names: Vec<&str> = facts.symbols.iter().map(|s| s.name.as_str()).collect();
        assert!(names.contains(&"validate_token"));
        assert!(names.contains(&"Config"));
        // private_helper is now emitted (all visibilities are extracted)
        assert!(names.contains(&"private_helper"));

        let vt = facts
            .symbols
            .iter()
            .find(|s| s.name == "validate_token")
            .unwrap();
        assert_eq!(
            vt.id.to_scip_string(),
            "codegraph . . . auth/session/validate_token()."
        );
        assert_eq!(vt.kind, SymbolKind::Function);
        assert_eq!(vt.visibility, Visibility::Public);

        let ph = facts
            .symbols
            .iter()
            .find(|s| s.name == "private_helper")
            .unwrap();
        assert_eq!(ph.visibility, Visibility::Private);
    }

    #[test]
    fn extracts_call_references() {
        let src = "pub fn main() { validate_token(\"t\"); helper(); }";
        let facts = RustExtractor.extract(src, "src/main.rs").unwrap();
        let names: Vec<&str> = facts.references.iter().map(|r| r.name.as_str()).collect();
        assert!(names.contains(&"validate_token"));
        assert!(names.contains(&"helper"));
    }

    #[test]
    fn trait_impl_emits_inherit_ref_and_inherent_impl_does_not() {
        // Trait impl → one Inherit ref named "Display".
        let src_trait_impl = r#"
use std::fmt;
pub struct Point;
impl fmt::Display for Point {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Ok(()) }
}
"#;
        let facts = RustExtractor
            .extract(src_trait_impl, "src/point.rs")
            .unwrap();
        let inherit_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::IsImplementation)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            inherit_names.contains(&"Display"),
            "expected 'Display' in {inherit_names:?}"
        );

        // Inherent impl → no Inherit ref.
        let src_inherent = "pub struct Point; impl Point { pub fn new() -> Self { Point } }";
        let facts2 = RustExtractor.extract(src_inherent, "src/point.rs").unwrap();
        let inherit2: Vec<&str> = facts2
            .references
            .iter()
            .filter(|r| r.role == RefRole::IsImplementation)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            inherit2.is_empty(),
            "expected no Inherit refs, got {inherit2:?}"
        );
    }

    #[test]
    fn supertrait_bounds_emit_inherit_refs() {
        let src = "pub trait Foo: Bar + Baz {}";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let inherit_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::IsImplementation)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            inherit_names.contains(&"Bar"),
            "expected 'Bar' in {inherit_names:?}"
        );
        assert!(
            inherit_names.contains(&"Baz"),
            "expected 'Baz' in {inherit_names:?}"
        );
    }

    #[test]
    fn scoped_trait_path_emits_leaf_name() {
        // `impl std::fmt::Display for Point {}` → leaf name "Display"
        let src = r#"
pub struct Point;
impl std::fmt::Display for Point {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { Ok(()) }
}
"#;
        let facts = RustExtractor.extract(src, "src/point.rs").unwrap();
        let inherit_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::IsImplementation)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            inherit_names.contains(&"Display"),
            "expected 'Display' in {inherit_names:?}"
        );
    }

    // ── Import reference tests ────────────────────────────────────────────────

    #[test]
    fn import_scoped_identifier_emits_leaf() {
        // `use a::b::Config;` → one Import ref `Config`
        let src = "use a::b::Config;";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            import_names,
            vec!["Config"],
            "expected ['Config'], got {import_names:?}"
        );
    }

    #[test]
    fn import_use_list_emits_all_leaves() {
        // `use std::collections::{HashMap, HashSet};` → Import refs `HashMap` and `HashSet`
        let src = "use std::collections::{HashMap, HashSet};";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let mut import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        import_names.sort_unstable();
        assert_eq!(
            import_names,
            vec!["HashMap", "HashSet"],
            "expected ['HashMap', 'HashSet'], got {import_names:?}"
        );
    }

    #[test]
    fn import_use_as_clause_emits_real_leaf_not_alias() {
        // `use a::b as c;` → Import ref `b` (not `c`)
        let src = "use a::b as c;";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            import_names,
            vec!["b"],
            "expected ['b'], got {import_names:?}"
        );
    }

    #[test]
    fn import_wildcard_emits_nothing() {
        // `use a::*;` → NO Import refs
        let src = "use a::*;";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            import_names.is_empty(),
            "expected no Import refs, got {import_names:?}"
        );
    }

    #[test]
    fn import_simple_scoped_path_emits_leaf() {
        // `use std::io::Result;` → Import ref `Result`
        let src = "use std::io::Result;";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            import_names,
            vec!["Result"],
            "expected ['Result'], got {import_names:?}"
        );
    }

    #[test]
    fn import_refs_carry_source_module() {
        // `use std::io::Result;` in src/net/client.rs → Import ref carries
        // the module SCIP id of net/client.
        let src = "use std::io::Result;";
        let file = "src/net/client.rs";
        let facts = RustExtractor.extract(src, file).unwrap();

        let namespaces = rust_namespaces(file);
        let expected_module_id =
            crate::extract::module_symbol(Language::Rust, &namespaces, file, src.len())
                .id
                .to_scip_string();

        let import_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .collect();
        assert!(!import_refs.is_empty(), "expected at least one Import ref");
        for r in &import_refs {
            assert_eq!(
                r.source_module,
                Some(expected_module_id.clone()),
                "Import ref '{}' should carry source_module = {:?}",
                r.name,
                expected_module_id
            );
        }
    }

    // --- from_path tests ---

    #[test]
    fn import_scoped_identifier_carries_from_path() {
        // `use std::io::Result;` → from_path == "std::io"
        let src = "use std::io::Result;";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let r = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Import && r.name == "Result")
            .expect("expected Import ref for 'Result'");
        assert_eq!(
            r.from_path,
            Some("std::io".to_owned()),
            "from_path should be 'std::io', got {:?}",
            r.from_path
        );
    }

    #[test]
    fn import_use_list_leaves_carry_prefix_as_from_path() {
        // `use std::collections::{HashMap, BTreeMap};`
        // Both leaf refs must have from_path == "std::collections".
        let src = "use std::collections::{HashMap, BTreeMap};";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let import_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .collect();
        assert_eq!(
            import_refs.len(),
            2,
            "expected 2 Import refs, got {:?}",
            import_refs.iter().map(|r| &r.name).collect::<Vec<_>>()
        );
        for r in &import_refs {
            assert_eq!(
                r.from_path,
                Some("std::collections".to_owned()),
                "from_path for '{}' should be 'std::collections', got {:?}",
                r.name,
                r.from_path
            );
        }
    }

    // ── ModuleRef reference tests ─────────────────────────────────────────────

    #[test]
    fn mod_declaration_emits_module_ref() {
        // `mod util;` → a ModuleRef named "util" (even though it is not `pub`).
        let src = "mod util;\npub fn run() {}";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let module_refs: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::ModuleRef)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            module_refs,
            vec!["util"],
            "expected ['util'], got {module_refs:?}"
        );
    }

    #[test]
    fn use_path_segment_emits_module_ref_and_keeps_import_leaf() {
        // `use crate::alpha::helper;` in a NON-root file → ModuleRef("alpha")
        // (the `crate` anchor is skipped on non-root files) + Import("helper").
        // Uses src/foo.rs so the assertion isolates the path-segment emission
        // from the crate-root self-module ref (covered separately).
        let src = "use crate::alpha::helper;";
        let facts = RustExtractor.extract(src, "src/foo.rs").unwrap();

        let module_refs: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::ModuleRef)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            module_refs,
            vec!["alpha"],
            "expected ModuleRef ['alpha'], got {module_refs:?}"
        );

        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            import_names,
            vec!["helper"],
            "expected Import ['helper'], got {import_names:?}"
        );
    }

    #[test]
    fn use_path_anchor_emits_no_module_ref() {
        // `use crate::helper;` in a NON-root file → only the Import for
        // "helper"; the `crate` anchor produces NO ModuleRef (in a non-root
        // file `crate` names a different file, not this one).
        let src = "use crate::helper;";
        let facts = RustExtractor.extract(src, "src/foo.rs").unwrap();

        let module_refs: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::ModuleRef)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            module_refs.is_empty(),
            "expected no ModuleRef for an anchor, got {module_refs:?}"
        );

        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            import_names,
            vec!["helper"],
            "expected Import ['helper'], got {import_names:?}"
        );
    }

    #[test]
    fn crate_anchor_in_root_file_emits_self_module_ref() {
        // `use crate::alpha::helper;` in a crate-root file (lib.rs) → the
        // `crate` anchor names THIS file's own module, so we emit a ModuleRef
        // "lib" (the crate root's module-symbol name) alongside the existing
        // ModuleRef "alpha" and the Import "helper".
        let src = "use crate::alpha::helper;";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        let module_refs: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::ModuleRef)
            .map(|r| r.name.as_str())
            .collect();
        let mut sorted = module_refs.clone();
        sorted.sort_unstable();
        assert_eq!(
            sorted,
            vec!["alpha", "lib"],
            "expected ModuleRefs == {{lib, alpha}}, got {module_refs:?}"
        );

        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            import_names,
            vec!["helper"],
            "expected Import ['helper'], got {import_names:?}"
        );
    }

    #[test]
    fn crate_anchor_root_file_single_segment() {
        // `use crate::helper;` in a crate-root file (lib.rs) → the only module
        // segment is the `crate` anchor, which resolves to this file's own
        // module "lib"; the leaf "helper" stays an Import.
        let src = "use crate::helper;";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        let module_refs: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::ModuleRef)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            module_refs,
            vec!["lib"],
            "expected ModuleRef ['lib'], got {module_refs:?}"
        );

        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            import_names,
            vec!["helper"],
            "expected Import ['helper'], got {import_names:?}"
        );
    }

    #[test]
    fn deep_use_path_emits_every_module_segment() {
        // `use a::b::c::Thing;` → a ModuleRef for each of the three module
        // segments (a, b, c) and a single Import for the leaf `Thing`. The
        // recursive walk must reach the innermost `a`, not just the pre-leaf `c`.
        let src = "use a::b::c::Thing;";
        let facts = RustExtractor.extract(src, "src/foo.rs").unwrap();

        let mut module_refs: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::ModuleRef)
            .map(|r| r.name.as_str())
            .collect();
        module_refs.sort_unstable();
        assert_eq!(
            module_refs,
            vec!["a", "b", "c"],
            "expected ModuleRefs ['a','b','c'], got {module_refs:?}"
        );

        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            import_names,
            vec!["Thing"],
            "expected Import ['Thing'], got {import_names:?}"
        );
    }

    #[test]
    fn crate_anchor_in_non_root_file_skipped() {
        // Same source in a NON-root file (src/foo.rs) → the `crate` anchor
        // refers to a DIFFERENT file (the crate root), which this extractor
        // cannot identify, so NO ModuleRef is emitted for it. Only the "alpha"
        // segment ModuleRef and the "helper" Import remain.
        let src = "use crate::alpha::helper;";
        let facts = RustExtractor.extract(src, "src/foo.rs").unwrap();

        let module_refs: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::ModuleRef)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            module_refs,
            vec!["alpha"],
            "expected only ModuleRef ['alpha'] (crate anchor skipped), got {module_refs:?}"
        );

        let import_names: Vec<&str> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Import)
            .map(|r| r.name.as_str())
            .collect();
        assert_eq!(
            import_names,
            vec!["helper"],
            "expected Import ['helper'], got {import_names:?}"
        );
    }

    // ── Scope tree tests ──────────────────────────────────────────────────────

    #[test]
    fn scope_fn_with_call_has_function_scope_and_ref_attaches_to_it() {
        // A function containing a call: assert root Module scope (index 0) and a
        // Function scope; the call reference's scope should be Some(fn_scope_id),
        // not Some(0) (the root).
        let src = "pub fn greet() { helper(); }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        // scopes[0] must be the file-root Module.
        assert!(!facts.scopes.is_empty(), "scopes must not be empty");
        assert_eq!(
            facts.scopes[0].kind,
            ScopeKind::Module,
            "scopes[0] must be Module"
        );
        assert_eq!(facts.scopes[0].parent, None, "root scope has no parent");

        // There must be at least one Function scope.
        let fn_scope_pos = facts
            .scopes
            .iter()
            .position(|s| s.kind == ScopeKind::Function)
            .expect("expected a Function scope");

        // The call reference to `helper` must be attributed to the Function scope,
        // not the root.
        let helper_ref = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Call && r.name == "helper")
            .expect("expected a Call ref for 'helper'");
        assert_eq!(
            helper_ref.scope,
            Some(fn_scope_pos),
            "helper call should be attributed to the Function scope ({}), got {:?}",
            fn_scope_pos,
            helper_ref.scope
        );
    }

    #[test]
    fn nested_block_scope_parent_chains_correctly() {
        // A function whose body contains an inner bare `{ }` block:
        //   fn outer() { { inner_call(); } }
        // Scopes expected: root Module (0), Function (1), Block (2).
        // A ref inside the block must attribute to the Block scope,
        // and the Block scope's parent must be the Function scope.
        let src = "fn outer() { { inner_call(); } }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        let fn_scope_id = facts
            .scopes
            .iter()
            .position(|s| s.kind == ScopeKind::Function)
            .expect("expected a Function scope");
        let block_scope_id = facts
            .scopes
            .iter()
            .position(|s| s.kind == ScopeKind::Block)
            .expect("expected a Block scope");

        // Block's parent must be the Function scope.
        assert_eq!(
            facts.scopes[block_scope_id].parent,
            Some(fn_scope_id),
            "Block scope parent should be the Function scope"
        );

        // The call ref inside the block must attribute to the Block scope (innermost).
        let inner_ref = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Call && r.name == "inner_call")
            .expect("expected a Call ref for 'inner_call'");
        assert_eq!(
            inner_ref.scope,
            Some(block_scope_id),
            "inner_call should attribute to the Block scope ({}), got {:?}",
            block_scope_id,
            inner_ref.scope
        );
    }

    #[test]
    fn empty_source_produces_exactly_one_root_scope() {
        // Empty source → collect_scopes returns exactly one scope (the file root),
        // does not panic.
        let ts_language = crate::grammar::rust();
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&ts_language).unwrap();
        let tree = parser.parse("", None).unwrap();
        let root = tree.root_node();

        let scopes = collect_scopes(&root, 0);
        assert_eq!(
            scopes.len(),
            1,
            "empty source should produce exactly one scope"
        );
        assert_eq!(scopes[0].kind, ScopeKind::Module);
        assert_eq!(scopes[0].parent, None);
    }

    // ── Binding tests ─────────────────────────────────────────────────────────

    #[test]
    fn fn_params_emit_param_bindings() {
        // `fn f(a: u32, b: u32) { }` → two Param bindings named `a` and `b`,
        // both attributed to the Function scope, both targeting Local.
        let src = "fn f(a: u32, b: u32) { }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        let fn_scope_id = facts
            .scopes
            .iter()
            .position(|s| s.kind == ScopeKind::Function)
            .expect("expected a Function scope");

        let mut param_names: Vec<(&str, ScopeId)> = facts
            .bindings
            .iter()
            .filter(|b| b.kind == BindingKind::Param)
            .map(|b| (b.name.as_str(), b.scope))
            .collect();
        param_names.sort_by_key(|(n, _)| *n);

        assert_eq!(
            param_names,
            vec![("a", fn_scope_id), ("b", fn_scope_id)],
            "expected Param bindings for a and b in the Function scope, got {param_names:?}"
        );
        for b in facts
            .bindings
            .iter()
            .filter(|b| b.kind == BindingKind::Param)
        {
            assert_eq!(
                b.target,
                BindingTarget::Local,
                "param binding target must be Local"
            );
        }
    }

    #[test]
    fn self_parameter_emits_param_binding() {
        // `impl S { fn m(&self) {} }` → a Param binding named `"self"`.
        let src = "pub struct S; impl S { fn m(&self) {} }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        let self_binding = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Param && b.name == "self")
            .expect("expected a Param binding named 'self'");
        assert_eq!(self_binding.target, BindingTarget::Local);
        // The scope must be a Function scope.
        assert_eq!(
            facts.scopes[self_binding.scope].kind,
            ScopeKind::Function,
            "self binding should be in a Function scope"
        );
    }

    #[test]
    fn let_binding_emits_local_binding() {
        // `fn f() { let x = 1; }` → a Local binding for `x` in the Function scope.
        let src = "fn f() { let x = 1; }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        let fn_scope_id = facts
            .scopes
            .iter()
            .position(|s| s.kind == ScopeKind::Function)
            .expect("expected a Function scope");

        let x_binding = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Local && b.name == "x")
            .expect("expected a Local binding for 'x'");

        assert_eq!(
            x_binding.scope, fn_scope_id,
            "x should be in the Function scope"
        );
        assert_eq!(x_binding.target, BindingTarget::Local);

        // intro must equal the start byte of the `x` identifier in the source.
        let expected_intro = src.find('x').expect("'x' not in src");
        assert_eq!(
            x_binding.intro, expected_intro,
            "intro should point at the 'x' token"
        );
    }

    #[test]
    fn shadowing_produces_two_local_bindings_with_different_intros() {
        // `fn f() { let x = 1; let x = 2; }` → two Local bindings both named
        // `x` with DIFFERENT intro offsets (the neutral fact enabling later
        // shadowing resolution).
        let src = "fn f() { let x = 1; let x = 2; }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        let x_bindings: Vec<_> = facts
            .bindings
            .iter()
            .filter(|b| b.kind == BindingKind::Local && b.name == "x")
            .collect();

        assert_eq!(
            x_bindings.len(),
            2,
            "expected exactly two Local bindings for 'x', got {}",
            x_bindings.len()
        );
        assert_ne!(
            x_bindings[0].intro, x_bindings[1].intro,
            "shadowed bindings must have different intro offsets"
        );
    }

    #[test]
    fn nested_block_let_binding_attributes_to_inner_block_scope() {
        // `fn f() { { let y = 1; } }` → the `y` Local binding's scope is the
        // inner Block scope, not the Function scope.
        let src = "fn f() { { let y = 1; } }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        let block_scope_id = facts
            .scopes
            .iter()
            .position(|s| s.kind == ScopeKind::Block)
            .expect("expected a Block scope");

        let y_binding = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Local && b.name == "y")
            .expect("expected a Local binding for 'y'");

        assert_eq!(
            y_binding.scope, block_scope_id,
            "y should be attributed to the inner Block scope ({}), got {}",
            block_scope_id, y_binding.scope
        );
    }

    #[test]
    fn impl_block_with_method_nests_type_then_function_scope() {
        // `impl Foo { fn bar() { call(); } }`
        // Expected nesting: root Module (0) → Type (impl body) → Function (method)
        // A call inside the method attributes to the Function scope (innermost).
        let src = "pub struct Foo; impl Foo { pub fn bar(&self) { call(); } }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        let type_scope_id = facts
            .scopes
            .iter()
            .position(|s| s.kind == ScopeKind::Type)
            .expect("expected a Type scope for the impl body");
        let fn_scope_id = facts
            .scopes
            .iter()
            .position(|s| s.kind == ScopeKind::Function)
            .expect("expected a Function scope for the method");

        // Type scope's parent must be the root (0).
        assert_eq!(
            facts.scopes[type_scope_id].parent,
            Some(0),
            "impl body Type scope parent should be root (0)"
        );
        // Function scope's parent must be the Type scope.
        assert_eq!(
            facts.scopes[fn_scope_id].parent,
            Some(type_scope_id),
            "method Function scope parent should be the Type scope"
        );

        // The call ref must attribute to the Function scope (innermost).
        let call_ref = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Call && r.name == "call")
            .expect("expected a Call ref for 'call'");
        assert_eq!(
            call_ref.scope,
            Some(fn_scope_id),
            "call() should attribute to the Function scope ({}), got {:?}",
            fn_scope_id,
            call_ref.scope
        );
    }

    // ── Definition binding tests ──────────────────────────────────────────────

    #[test]
    fn pub_fn_emits_definition_binding() {
        // `pub fn foo() {}` → a Definition binding: name "foo", scope 0,
        // kind Definition, target Def(_).
        let src = "pub fn foo() {}";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        let b = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Definition && b.name == "foo")
            .expect("expected a Definition binding named 'foo'");
        assert_eq!(b.scope, 0, "top-level def must bind in scope 0");
        assert!(
            matches!(b.target, BindingTarget::Def(_)),
            "Definition binding target must be Def(_), got {:?}",
            b.target
        );
    }

    #[test]
    fn pub_struct_emits_definition_binding_in_root_scope() {
        // `pub struct Bar {}` → a Definition binding named "Bar" in scope 0
        // (not in the struct body's Type scope).
        let src = "pub struct Bar {}";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        let b = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Definition && b.name == "Bar")
            .expect("expected a Definition binding named 'Bar'");
        assert_eq!(b.scope, 0, "struct def must bind in root scope 0");
        assert!(
            matches!(b.target, BindingTarget::Def(_)),
            "Definition binding target must be Def(_)"
        );
    }

    #[test]
    fn use_stmt_emits_import_binding() {
        // `use std::io::Result;` → an Import binding: name "Result",
        // kind Import, target Import("std::io").
        let src = "use std::io::Result;";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        let b = facts
            .bindings
            .iter()
            .find(|b| b.kind == BindingKind::Import && b.name == "Result")
            .expect("expected an Import binding named 'Result'");
        assert_eq!(
            b.target,
            BindingTarget::Import("std::io".to_owned()),
            "import binding target should be Import(\"std::io\"), got {:?}",
            b.target
        );
    }

    #[test]
    fn module_file_symbol_does_not_produce_definition_binding() {
        // The synthetic module symbol pushed last in `extract` must NOT get a
        // Definition binding. Here we have exactly one real top-level def
        // (`pub fn foo`), so there must be exactly one Definition binding and
        // its name must be "foo", not the file-stem "lib".
        let src = "pub fn foo() {}";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        let def_bindings: Vec<_> = facts
            .bindings
            .iter()
            .filter(|b| b.kind == BindingKind::Definition)
            .collect();
        assert_eq!(
            def_bindings.len(),
            1,
            "expected exactly one Definition binding, got {}: {:?}",
            def_bindings.len(),
            def_bindings.iter().map(|b| &b.name).collect::<Vec<_>>()
        );
        assert_eq!(
            def_bindings[0].name, "foo",
            "the sole Definition binding must be 'foo', not the module stem"
        );
    }

    // ── qualifier capture tests (unit 8a) ────────────────────────────────────

    #[test]
    fn qualified_call_single_segment_captures_qualifier() {
        // `mod_a::process()` → leaf "process", qualifier Some("mod_a")
        let src = "pub fn caller() { mod_a::process(); }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let r = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Call && r.name == "process")
            .expect("expected a Call ref for 'process'");
        assert_eq!(
            r.qualifier,
            Some("mod_a".to_owned()),
            "qualifier should be 'mod_a', got {:?}",
            r.qualifier
        );
    }

    #[test]
    fn qualified_call_nested_segments_captures_full_qualifier() {
        // `a::b::process()` → leaf "process", qualifier Some("a::b")
        let src = "pub fn caller() { a::b::process(); }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let r = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Call && r.name == "process")
            .expect("expected a Call ref for 'process'");
        assert_eq!(
            r.qualifier,
            Some("a::b".to_owned()),
            "qualifier should be 'a::b', got {:?}",
            r.qualifier
        );
    }

    #[test]
    fn unqualified_call_has_no_qualifier() {
        // `helper()` → qualifier None
        let src = "pub fn caller() { helper(); }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let r = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Call && r.name == "helper")
            .expect("expected a Call ref for 'helper'");
        assert_eq!(
            r.qualifier, None,
            "unqualified call should have qualifier == None, got {:?}",
            r.qualifier
        );
    }

    #[test]
    fn method_call_via_field_expression_has_no_qualifier() {
        // `obj.method()` — field_expression arm → leaf "method", qualifier None
        // (obj is the receiver, not a qualifier)
        let src = "pub fn caller(obj: Foo) { obj.method(); }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let r = facts
            .references
            .iter()
            .find(|r| r.role == RefRole::Call && r.name == "method")
            .expect("expected a Call ref for 'method'");
        assert_eq!(
            r.qualifier, None,
            "method call via field_expression should have qualifier == None, got {:?}",
            r.qualifier
        );
    }

    #[test]
    fn combined_def_and_use_emit_both_kinds_and_locals_still_work() {
        // A file with a top-level def + a `use` + a local let:
        // → a Definition binding for `foo`
        // → an Import binding for `Result`
        // → a Param binding (from prior unit) for the function param
        // → a Local binding for the let variable
        let src = "use std::io::Result;\npub fn foo(x: u32) { let y = 1; }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();

        // Definition binding present.
        assert!(
            facts
                .bindings
                .iter()
                .any(|b| b.kind == BindingKind::Definition && b.name == "foo"),
            "expected a Definition binding for 'foo'"
        );
        // Import binding present.
        assert!(
            facts
                .bindings
                .iter()
                .any(|b| b.kind == BindingKind::Import && b.name == "Result"),
            "expected an Import binding for 'Result'"
        );
        // Param binding from prior unit still works.
        assert!(
            facts
                .bindings
                .iter()
                .any(|b| b.kind == BindingKind::Param && b.name == "x"),
            "expected a Param binding for 'x' (regression check)"
        );
        // Local binding from prior unit still works.
        assert!(
            facts
                .bindings
                .iter()
                .any(|b| b.kind == BindingKind::Local && b.name == "y"),
            "expected a Local binding for 'y' (regression check)"
        );
    }

    // ── TypeRef tests ─────────────────────────────────────────────────────────

    fn type_refs(facts: &crate::graph::FileFacts) -> Vec<&Reference> {
        facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::TypeRef)
            .collect()
    }

    #[test]
    fn typeref_param_and_return_types_captured() {
        // `fn validate(cfg: Config) -> Outcome {}` → TypeRef refs for `Config` (param)
        // and `Outcome` (return type).
        let src = "fn validate(cfg: Config) -> Outcome {}";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let names: Vec<&str> = type_refs(&facts).iter().map(|r| r.name.as_str()).collect();
        assert!(
            names.contains(&"Config"),
            "expected TypeRef for 'Config' in {names:?}"
        );
        assert!(
            names.contains(&"Outcome"),
            "expected TypeRef for 'Outcome' in {names:?}"
        );
        for r in type_refs(&facts) {
            assert_eq!(
                r.role,
                RefRole::TypeRef,
                "role should be TypeRef, got {:?}",
                r.role
            );
        }
    }

    #[test]
    fn typeref_struct_field_type_captured() {
        // `struct Holder { item: Widget }` → TypeRef ref named `Widget`.
        let src = "struct Holder { item: Widget }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let names: Vec<&str> = type_refs(&facts).iter().map(|r| r.name.as_str()).collect();
        assert!(
            names.contains(&"Widget"),
            "expected TypeRef for 'Widget' in {names:?}"
        );
    }

    #[test]
    fn typeref_generic_base_type_captured_inner_deferred() {
        // `fn f(v: Vec<Config>) {}` → TypeRef ref for `Vec` (the base generic type).
        // `Config` inside the type_arguments is NOT captured (v1 boundary).
        let src = "fn f(v: Vec<Config>) {}";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let names: Vec<&str> = type_refs(&facts).iter().map(|r| r.name.as_str()).collect();
        assert!(
            names.contains(&"Vec"),
            "expected TypeRef for 'Vec' (base generic) in {names:?}"
        );
        assert!(
            !names.contains(&"Config"),
            "Config inside generic args should NOT be captured in v1 (got {names:?})"
        );
    }

    #[test]
    fn typeref_scoped_type_emits_leaf_and_qualifier() {
        // `fn f(r: std::io::Result) {}` → TypeRef ref `name == "Result"`,
        // `qualifier == Some("std::io")`.
        let src = "fn f(r: std::io::Result) {}";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let r = type_refs(&facts)
            .into_iter()
            .find(|r| r.name == "Result")
            .expect("expected a TypeRef ref named 'Result'");
        assert_eq!(
            r.qualifier,
            Some("std::io".to_owned()),
            "qualifier should be 'std::io', got {:?}",
            r.qualifier
        );
    }

    #[test]
    fn typeref_reference_type_descends_through_borrow() {
        // `fn f(c: &Config) {}` → TypeRef ref named `Config` (descended through `&`).
        let src = "fn f(c: &Config) {}";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let names: Vec<&str> = type_refs(&facts).iter().map(|r| r.name.as_str()).collect();
        assert!(
            names.contains(&"Config"),
            "expected TypeRef for 'Config' through '&' in {names:?}"
        );
    }

    #[test]
    fn typeref_primitive_type_not_captured() {
        // Primitives (u32, bool, i64, …) are skipped — they never resolve to a
        // user-defined Symbol, so capturing them only adds noise.
        let src = "fn f(n: u32, b: bool) -> i64 { 0 }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let names: Vec<&str> = type_refs(&facts).iter().map(|r| r.name.as_str()).collect();
        assert!(
            !names.contains(&"u32"),
            "primitive 'u32' should NOT be captured as TypeRef (got {names:?})"
        );
        assert!(
            !names.contains(&"bool"),
            "primitive 'bool' should NOT be captured as TypeRef (got {names:?})"
        );
        assert!(
            !names.contains(&"i64"),
            "primitive 'i64' should NOT be captured as TypeRef (got {names:?})"
        );
    }

    #[test]
    fn typeref_empty_fn_no_types_emits_no_typeref() {
        // `fn f() {}` with no type annotations → zero TypeRef refs.
        let src = "fn f() {}";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let trefs = type_refs(&facts);
        assert!(
            trefs.is_empty(),
            "fn with no types should produce no TypeRef refs, got {:?}",
            trefs.iter().map(|r| &r.name).collect::<Vec<_>>()
        );
    }

    // ── Read / Write reference tests ──────────────────────────────────────────

    #[test]
    fn read_ref_emitted_for_tail_use_not_declaration() {
        // `fn f() -> i32 { let base = 1; base }` →
        //   - a Read ref for the tail `base` expression
        //   - the `let base` binding name is NOT a Read
        let src = "fn f() -> i32 { let base = 1; base }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let read_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Read && r.name == "base")
            .collect();
        // There must be at least one Read ref (the tail `base` expression).
        assert!(
            !read_refs.is_empty(),
            "expected at least one Read ref for 'base', got none"
        );
        // The `let base` token is at the first `base` in source ("let base = 1").
        // The tail use `base` appears after the `=` and `;`.
        let decl_offset = src.find("let base").unwrap() + "let ".len();
        // All Read refs must be AFTER the declaration offset (not the let binding itself).
        for r in &read_refs {
            assert!(
                r.occ.byte > decl_offset,
                "Read ref for 'base' at byte {} should be after declaration offset {}",
                r.occ.byte,
                decl_offset
            );
        }
    }

    #[test]
    fn write_ref_emitted_for_assignment_not_let() {
        // `fn f() { let mut cnt = 0; cnt = 5; }` →
        //   - a Write ref for the `cnt = 5` assignment LHS
        //   - the `let mut cnt` declaration name is NOT a Write
        let src = "fn f() { let mut cnt = 0; cnt = 5; }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let write_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Write && r.name == "cnt")
            .collect();
        assert!(
            !write_refs.is_empty(),
            "expected at least one Write ref for 'cnt', got none — all refs: {:?}",
            facts
                .references
                .iter()
                .map(|r| (&r.name, r.role))
                .collect::<Vec<_>>()
        );
        // `cnt = 5` starts after the declaration — byte offset > the `let` start.
        let assign_offset = src.find("cnt = 5").unwrap();
        for r in &write_refs {
            assert!(
                r.occ.byte >= assign_offset,
                "Write ref for 'cnt' at byte {} should be at/after the assignment at {}",
                r.occ.byte,
                assign_offset
            );
        }
    }

    #[test]
    fn compound_assignment_emits_write_ref() {
        // `fn f() { let mut num = 0; num += 1; }` → a Write ref "num" for `num += 1`.
        let src = "fn f() { let mut num = 0; num += 1; }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let write_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Write && r.name == "num")
            .collect();
        assert!(
            !write_refs.is_empty(),
            "expected a Write ref for 'num' from compound assignment, got none — all refs: {:?}",
            facts
                .references
                .iter()
                .map(|r| (&r.name, r.role))
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn call_not_also_read() {
        // `fn f() { helper(); }` → a Call ref "helper", NOT also a Read for "helper".
        let src = "fn f() { helper(); }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let call_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Call && r.name == "helper")
            .collect();
        assert!(!call_refs.is_empty(), "expected a Call ref for 'helper'");
        let read_refs: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Read && r.name == "helper")
            .collect();
        assert!(
            read_refs.is_empty(),
            "helper() must NOT produce a Read ref; got: {read_refs:?}"
        );
    }

    #[test]
    fn field_access_not_a_read_of_field() {
        // `fn f(c: C) -> i32 { c.field }` →
        //   - a Read ref "c" (the receiver) is acceptable
        //   - NO Read ref "field" (field_identifier is a different node kind)
        let src = "fn f(c: C) -> i32 { c.field }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let field_reads: Vec<_> = facts
            .references
            .iter()
            .filter(|r| r.role == RefRole::Read && r.name == "field")
            .collect();
        assert!(
            field_reads.is_empty(),
            "field 'field' in field_expression must NOT be a Read ref; got: {field_reads:?}"
        );
    }

    // ── assoc fn / assoc const extraction (unit C3) ───────────────────────────

    #[test]
    fn assoc_fn_symbol_emitted_for_pub_new() {
        // `pub fn new()` in an inherent impl → SymbolKind::Method, SCIP ends `Foo#new().`
        let src = "pub struct Foo; impl Foo { pub fn new() -> Self { Foo } }";
        let facts = RustExtractor.extract(src, "src/foo.rs").unwrap();
        let sym = facts
            .symbols
            .iter()
            .find(|s| s.name == "new" && s.kind == SymbolKind::Method)
            .expect("expected a Method symbol named 'new'");
        assert!(
            sym.id.to_scip_string().ends_with("Foo#new()."),
            "SCIP string should end with 'Foo#new().', got: {}",
            sym.id.to_scip_string()
        );
    }

    #[test]
    fn assoc_const_symbol_emitted_for_pub_const() {
        // `pub const MAX: u32 = 3;` in an inherent impl → SymbolKind::Const, SCIP ends `Foo#MAX.`
        let src = "pub struct Foo; impl Foo { pub const MAX: u32 = 3; }";
        let facts = RustExtractor.extract(src, "src/foo.rs").unwrap();
        let sym = facts
            .symbols
            .iter()
            .find(|s| s.name == "MAX" && s.kind == SymbolKind::Const)
            .expect("expected a Const symbol named 'MAX'");
        assert!(
            sym.id.to_scip_string().ends_with("Foo#MAX."),
            "SCIP string should end with 'Foo#MAX.', got: {}",
            sym.id.to_scip_string()
        );
    }

    #[test]
    fn method_with_self_is_emitted() {
        // `pub fn run(&self)` in an inherent impl → SymbolKind::Method, SCIP ends `Foo#run().`
        let src = "pub struct Foo; impl Foo { pub fn run(&self) {} }";
        let facts = RustExtractor.extract(src, "src/foo.rs").unwrap();
        let sym = facts
            .symbols
            .iter()
            .find(|s| s.name == "run" && s.kind == SymbolKind::Method)
            .expect("expected a Method symbol named 'run'");
        assert!(
            sym.id.to_scip_string().ends_with("Foo#run()."),
            "SCIP string should end with 'Foo#run().', got: {}",
            sym.id.to_scip_string()
        );
    }

    #[test]
    fn non_pub_member_emitted_with_private_visibility() {
        // `fn secret(&self) {}` (no `pub`) → symbol IS emitted, tagged Private.
        let src = "pub struct Foo; impl Foo { fn secret(&self) {} }";
        let facts = RustExtractor.extract(src, "src/foo.rs").unwrap();
        let secret = facts
            .symbols
            .iter()
            .find(|s| s.name == "secret")
            .expect("private method 'secret' must now be emitted as a symbol");
        assert_eq!(
            secret.visibility,
            Visibility::Private,
            "private method 'secret' must have Visibility::Private, got {:?}",
            secret.visibility
        );
        assert_eq!(secret.kind, SymbolKind::Method);
    }

    #[test]
    fn trait_impl_members_excluded() {
        // `impl std::fmt::Display for Point { fn fmt(...) }` →
        // NO symbol named "fmt" under `Point#`; the `Impl` block symbol for
        // `Point` is still emitted.
        let src = r#"pub struct Point;
impl std::fmt::Display for Point {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { Ok(()) }
}"#;
        let facts = RustExtractor.extract(src, "src/foo.rs").unwrap();

        // The Impl block symbol for Point is still emitted.
        assert!(
            facts
                .symbols
                .iter()
                .any(|s| s.name == "Point" && s.kind == SymbolKind::Impl),
            "Impl block symbol for 'Point' should still be emitted"
        );
        // No symbol named "fmt" under Point# should be emitted.
        let fmt_under_point: Vec<_> = facts
            .symbols
            .iter()
            .filter(|s| s.name == "fmt" && s.id.to_scip_string().contains("Point#"))
            .collect();
        assert!(
            fmt_under_point.is_empty(),
            "trait-impl method 'fmt' must NOT be emitted under Point#, got: {:?}",
            fmt_under_point
                .iter()
                .map(|s| s.id.to_scip_string())
                .collect::<Vec<_>>()
        );
    }

    // ── Visibility tests (unit F2) ────────────────────────────────────────────

    #[test]
    fn pub_fn_has_public_visibility() {
        // `pub fn f() {}` → symbol with Visibility::Public.
        let src = "pub fn f() {}";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let sym = facts
            .symbols
            .iter()
            .find(|s| s.name == "f" && s.kind == SymbolKind::Function)
            .expect("expected a Function symbol named 'f'");
        assert_eq!(
            sym.visibility,
            Visibility::Public,
            "pub fn should have Visibility::Public, got {:?}",
            sym.visibility
        );
    }

    #[test]
    fn private_fn_has_private_visibility() {
        // `fn g() {}` (no modifier) → symbol IS emitted with Visibility::Private.
        let src = "fn g() {}";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let sym = facts
            .symbols
            .iter()
            .find(|s| s.name == "g" && s.kind == SymbolKind::Function)
            .expect("expected a Function symbol named 'g'");
        assert_eq!(
            sym.visibility,
            Visibility::Private,
            "fn with no modifier should have Visibility::Private, got {:?}",
            sym.visibility
        );
    }

    #[test]
    fn pub_crate_fn_has_internal_visibility() {
        // `pub(crate) fn h() {}` → symbol with Visibility::Internal.
        let src = "pub(crate) fn h() {}";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let sym = facts
            .symbols
            .iter()
            .find(|s| s.name == "h" && s.kind == SymbolKind::Function)
            .expect("expected a Function symbol named 'h'");
        assert_eq!(
            sym.visibility,
            Visibility::Internal,
            "pub(crate) fn should have Visibility::Internal, got {:?}",
            sym.visibility
        );
    }

    #[test]
    fn private_impl_method_emitted_with_private_visibility() {
        // `fn inner(&self) {}` in an inherent impl (no `pub`) →
        // symbol IS emitted with Visibility::Private.
        let src = "pub struct Bar; impl Bar { fn inner(&self) {} }";
        let facts = RustExtractor.extract(src, "src/lib.rs").unwrap();
        let sym = facts
            .symbols
            .iter()
            .find(|s| s.name == "inner" && s.kind == SymbolKind::Method)
            .expect("expected a Method symbol named 'inner'");
        assert_eq!(
            sym.visibility,
            Visibility::Private,
            "private impl method should have Visibility::Private, got {:?}",
            sym.visibility
        );
    }

    // ── Entry-point detection (E2) ────────────────────────────────────────────

    /// Find a symbol by bare name in the extracted facts (panics if absent).
    fn sym_by_name(facts: &crate::graph::types::FileFacts, name: &str) -> Symbol {
        facts
            .symbols
            .iter()
            .find(|s| s.name == name)
            .unwrap_or_else(|| {
                panic!(
                    "symbol '{name}' not found; symbols: {:?}",
                    facts
                        .symbols
                        .iter()
                        .map(|s| s.name.as_str())
                        .collect::<Vec<_>>()
                )
            })
            .clone()
    }

    /// Render entry_points as a compact string for assertion messages.
    fn ep_str(eps: &[EntryPoint]) -> String {
        eps.iter()
            .map(|ep| match ep {
                EntryPoint::Main => "Main".to_owned(),
                EntryPoint::HttpRoute(m) => format!("HttpRoute({m})"),
            })
            .collect::<Vec<_>>()
            .join(", ")
    }

    #[test]
    fn rust_entry_point_get_route() {
        // `#[get("/")]` is an Actix-web/Rocket route attribute; terminal = "get".
        let src = "#[get(\"/\")]\npub fn index() -> String { String::new() }";
        let facts = RustExtractor.extract(src, "src/routes.rs").unwrap();
        let sym = sym_by_name(&facts, "index");
        assert_eq!(
            sym.entry_points.len(),
            1,
            "expected exactly 1 entry point, got [{}]",
            ep_str(&sym.entry_points)
        );
        assert!(
            matches!(&sym.entry_points[0], EntryPoint::HttpRoute(m) if m == "get"),
            "expected HttpRoute(\"get\"), got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn rust_entry_point_post_route() {
        // `#[post("/users")]` → HttpRoute("post").
        let src = "#[post(\"/users\")]\npub fn create() {}";
        let facts = RustExtractor.extract(src, "src/routes.rs").unwrap();
        let sym = sym_by_name(&facts, "create");
        assert_eq!(
            sym.entry_points.len(),
            1,
            "expected exactly 1 entry point, got [{}]",
            ep_str(&sym.entry_points)
        );
        assert!(
            matches!(&sym.entry_points[0], EntryPoint::HttpRoute(m) if m == "post"),
            "expected HttpRoute(\"post\"), got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn rust_entry_point_non_route_attr_ignored() {
        // `#[derive(Debug)]` and `#[inline]` are not route attrs — entry_points must be empty.
        let src = "#[derive(Debug)]\n#[inline]\npub fn helper() {}";
        let facts = RustExtractor.extract(src, "src/util.rs").unwrap();
        let sym = sym_by_name(&facts, "helper");
        assert!(
            sym.entry_points.is_empty(),
            "non-route attributes must not produce entry points; got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn rust_entry_point_main_fn_name() {
        // A function literally named `main` → EntryPoint::Main.
        let src = "pub fn main() {}";
        let facts = RustExtractor.extract(src, "src/main.rs").unwrap();
        let sym = sym_by_name(&facts, "main");
        assert_eq!(
            sym.entry_points.len(),
            1,
            "expected exactly 1 entry point, got [{}]",
            ep_str(&sym.entry_points)
        );
        assert!(
            matches!(&sym.entry_points[0], EntryPoint::Main),
            "expected Main, got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn rust_entry_point_plain_fn_empty() {
        // A plain function with no special attribute or name → empty entry_points.
        let src = "pub fn process() {}";
        let facts = RustExtractor.extract(src, "src/util.rs").unwrap();
        let sym = sym_by_name(&facts, "process");
        assert!(
            sym.entry_points.is_empty(),
            "plain function must have no entry points; got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn rust_entry_point_qualified_path_terminal() {
        // `#[actix_web::get("/")]` — qualified path; terminal identifier = "get".
        let src = "#[actix_web::get(\"/\")]\npub fn scoped() {}";
        let facts = RustExtractor.extract(src, "src/routes.rs").unwrap();
        let sym = sym_by_name(&facts, "scoped");
        assert_eq!(
            sym.entry_points.len(),
            1,
            "expected exactly 1 entry point, got [{}]",
            ep_str(&sym.entry_points)
        );
        assert!(
            matches!(&sym.entry_points[0], EntryPoint::HttpRoute(m) if m == "get"),
            "expected HttpRoute(\"get\"), got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn rust_entry_point_tokio_main_not_a_route() {
        // `#[tokio::main]` has terminal `main` which is NOT in RUST_ROUTE_ATTRS,
        // so it does NOT produce an HttpRoute. But `fn main` name → EntryPoint::Main.
        let src = "#[tokio::main]\nasync fn main() {}";
        let facts = RustExtractor.extract(src, "src/main.rs").unwrap();
        let sym = sym_by_name(&facts, "main");
        // Should have exactly Main, not an HttpRoute for "main".
        assert_eq!(
            sym.entry_points.len(),
            1,
            "expected exactly 1 entry point (Main), got [{}]",
            ep_str(&sym.entry_points)
        );
        assert!(
            matches!(&sym.entry_points[0], EntryPoint::Main),
            "expected Main, got [{}]",
            ep_str(&sym.entry_points)
        );
    }

    #[test]
    fn cross_file_assoc_fn_call_resolves_to_impl_member() {
        // The point of unit C3: `Point::new()` in main.rs must resolve to the
        // `new` symbol in point.rs via a Call edge whose `to` ends with `Point#new().`.
        use crate::resolve::{Resolver, SymbolTableResolver};

        let point = RustExtractor
            .extract(
                "pub struct Point; impl Point { pub fn new() -> Self { Point } }",
                "src/point.rs",
            )
            .unwrap();
        let main = RustExtractor
            .extract("pub fn run() { let _ = Point::new(); }", "src/main.rs")
            .unwrap();

        let graph = SymbolTableResolver.resolve(&[point, main]);

        let call_to_new: Vec<_> = graph
            .edges
            .iter()
            .filter(|e| e.role == RefRole::Call && e.to.to_scip_string().ends_with("Point#new()."))
            .collect();
        assert_eq!(
            call_to_new.len(),
            1,
            "expected exactly one Call edge to Point#new().(), got: {:?}",
            call_to_new
                .iter()
                .map(|e| format!("{} -> {}", e.from.to_scip_string(), e.to.to_scip_string()))
                .collect::<Vec<_>>()
        );
    }
}