symforge 8.13.3

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
use std::collections::{HashMap, HashSet};
use std::sync::OnceLock;

use streaming_iterator::StreamingIterator;
use tree_sitter::{Language, Node, Query, QueryCursor};

use crate::domain::{LanguageId, ReferenceKind, ReferenceRecord};

// ---------------------------------------------------------------------------
// Per-language query strings
// ---------------------------------------------------------------------------

const RUST_XREF_QUERY: &str = r#"
; Simple function calls: foo()
(call_expression function: (identifier) @ref.call)

; Qualified calls: Vec::new()  — capture the scoped_identifier for qualified_name too
(call_expression function: (scoped_identifier name: (identifier) @ref.call) @ref.qualified_call)

; Method calls: self.push()
(call_expression function: (field_expression field: (field_identifier) @ref.method_call))

; Macro invocations: println!()
(macro_invocation macro: (identifier) @ref.macro)

; Use declarations: use std::collections::HashMap
(use_declaration argument: (identifier) @ref.import)
(use_declaration argument: (scoped_identifier) @ref.import)
(use_declaration argument: (use_list) @ref.import)
(use_declaration argument: (scoped_use_list) @ref.import)

; Import with alias: use HashMap as Map
(use_as_clause path: (_) @import.original alias: (identifier) @import.alias)

; Type references (in function params, return types, struct fields, etc.)
(type_identifier) @ref.type

; Trait implementations: impl Trait for Struct
(impl_item trait: (type_identifier) @ref.implements type: (type_identifier) @ref.implements_target)
(impl_item trait: (scoped_type_identifier) @ref.implements type: (type_identifier) @ref.implements_target)
(impl_item trait: (generic_type) @ref.implements type: (type_identifier) @ref.implements_target)
"#;

// Focused query that collects the *definition* names of top-level / nested
// `const` and `static` items in a Rust file, e.g. `const FOO: u8 = 1;` →
// captures `FOO`.  Used to build the same-file const/static name set that
// gates value-position reference resolution (see `extract_rust_value_refs`).
const RUST_CONST_DEF_QUERY: &str = r#"
(const_item name: (identifier) @const.def)
(static_item name: (identifier) @const.def)
"#;

// Focused query that captures every bare value-position `(identifier)`.  On its
// own this is extremely noisy (it matches call targets, pattern bindings,
// parameters, etc.), so callers MUST gate each hit against the same-file
// const/static definition-name set and dedupe against ranges already captured
// by the main query (see `extract_rust_value_refs`).
const RUST_VALUE_IDENT_QUERY: &str = r#"
(identifier) @ref.value
"#;

// Captures every `scoped_identifier` (a `::`-qualified path).  On its own this
// is very noisy (it matches call targets, path prefixes of longer paths, `use`
// segments, and match-pattern paths), so `extract_rust_qualified_value_refs`
// gates each hit by parent node kind: it keeps ONLY value-position paths whose
// function was not already captured as a qualified call, are not the prefix of
// a longer path, and are not inside a `use` declaration or a match pattern.
const RUST_QUALIFIED_VALUE_QUERY: &str = r#"
(scoped_identifier) @ref.qualified_value
"#;

const PYTHON_XREF_QUERY: &str = r#"
; Function calls: foo(x)
(call function: (identifier) @ref.call)

; Method calls: obj.method()
(call function: (attribute attribute: (identifier) @ref.method_call))

; Import statements: import os
(import_statement name: (dotted_name (identifier) @ref.import))

; From imports: from os import path
(import_from_statement module_name: (dotted_name (identifier) @ref.import))
(import_from_statement name: (dotted_name (identifier) @ref.import))

; Import alias: import numpy as np
(aliased_import name: (dotted_name (identifier) @import.original) alias: (identifier) @import.alias)

; Bare type identifiers in annotation positions
(type (identifier) @ref.type)

; Subscript type annotations: QuerySet[Model]
(type (subscript value: (identifier) @ref.type))
(type (subscript subscript: (identifier) @ref.type))
(subscript value: (identifier) @ref.type)
(subscript subscript: (identifier) @ref.type)
(type (generic_type (identifier) @ref.type))
(generic_type (identifier) @ref.type)
(type (generic_type (type_parameter (type (identifier) @ref.type))))
(generic_type (type_parameter (type (identifier) @ref.type)))

; Attribute types in annotations: models.QuerySet
(type (attribute attribute: (identifier) @ref.type))

; Attribute chains: models.Model.__hash__
(attribute object: (attribute attribute: (identifier) @ref.type))

; Subscript with attribute base (legacy grammar)
(type (subscript value: (attribute attribute: (identifier) @ref.type)))
(subscript value: (attribute attribute: (identifier) @ref.type))

; Class inheritance — attribute base: class Foo(models.Model)
(class_definition
  superclasses: (argument_list
    (attribute attribute: (identifier) @ref.implements)))

; Class inheritance — bare base with implementor: class Foo(Bar)
(class_definition
  name: (identifier) @ref.implements_target
  superclasses: (argument_list (identifier) @ref.implements))
"#;

// Captures identifier/type-like tokens in call argument lists for a second pass
// (isinstance(x, Model), ForeignKey(Model), etc.). Gated in Rust by uppercase
// PEP-8 class-name heuristic and dedupe against the main query.
const PYTHON_VALUE_TYPE_IDENT_QUERY: &str = r#"
(argument_list (identifier) @ref.value)
(argument_list (attribute attribute: (identifier) @ref.value_attr))
"#;

const PYTHON_STRING_TYPE_QUERY: &str = r#"
(argument_list (string) @ref.string)
"#;

const JS_XREF_QUERY: &str = r#"
; Function calls: foo()
(call_expression function: (identifier) @ref.call)

; Method calls: obj.method()
(call_expression function: (member_expression property: (property_identifier) @ref.method_call))

; Constructor: new Foo()
(new_expression constructor: (identifier) @ref.call)

; Import statements: import React from 'react'
(import_statement source: (string) @ref.import)

; Import specifiers: import { Component } from 'react'
(import_specifier name: (identifier) @ref.import)
"#;

const TS_XREF_QUERY: &str = r#"
; Function calls: foo()
(call_expression function: (identifier) @ref.call)

; Method calls: obj.method()
(call_expression function: (member_expression property: (property_identifier) @ref.method_call))

; Constructor: new Foo()
(new_expression constructor: (identifier) @ref.call)

; Import statements: import React from 'react'
(import_statement source: (string) @ref.import)

; Import specifiers: import { Component } from 'react'
(import_specifier name: (identifier) @ref.import)

; TypeScript type references: param: MyType
(type_identifier) @ref.type

; Class implements: class Foo implements Bar
(class_declaration
  name: (type_identifier) @ref.implements_target
  (class_heritage
    (implements_clause
      (type_identifier) @ref.implements)))

; Class extends: class Foo extends Bar
(class_declaration
  name: (type_identifier) @ref.implements_target
  (class_heritage
    (extends_clause
      value: (identifier) @ref.implements)))
"#;

const GO_XREF_QUERY: &str = r#"
; Simple function calls: foo()
(call_expression function: (identifier) @ref.call)

; Selector calls: fmt.Println()
(call_expression function: (selector_expression field: (field_identifier) @ref.method_call))

; Import specs: import "fmt"
(import_spec path: (interpreted_string_literal) @ref.import)

; Type references
(type_identifier) @ref.type
"#;

const JAVA_XREF_QUERY: &str = r#"
; Method invocations: obj.println()
(method_invocation name: (identifier) @ref.call)

; Object creation: new ArrayList()
(object_creation_expression type: (type_identifier) @ref.call)

; Import declarations: import java.util.ArrayList
(import_declaration (scoped_identifier) @ref.import)

; Type references
(type_identifier) @ref.type

; Class implements: class Foo implements Bar
(class_declaration
  name: (identifier) @ref.implements_target
  interfaces: (super_interfaces
    (type_list (type_identifier) @ref.implements)))

; Class extends: class Foo extends Bar
(class_declaration
  name: (identifier) @ref.implements_target
  superclass: (superclass (type_identifier) @ref.implements))
"#;

const C_XREF_QUERY: &str = r#"
; Function calls: foo()
(call_expression function: (identifier) @ref.call)

; Method/field calls: obj->method() or obj.field()
(call_expression function: (field_expression field: (field_identifier) @ref.method_call))

; #include imports: "header.h" or <stdio.h>
(preproc_include path: (string_literal) @ref.import)
(preproc_include path: (system_lib_string) @ref.import)

; Type identifiers: MyStruct, typedef'd names
(type_identifier) @ref.type
"#;

const CPP_XREF_QUERY: &str = r#"
; Function calls: foo()
(call_expression function: (identifier) @ref.call)

; Method calls: obj.method() or obj->method()
(call_expression function: (field_expression field: (field_identifier) @ref.method_call))

; Qualified calls: std::sort(), Foo::bar() — capture the qualified_identifier as
; @ref.qualified_call so the type/namespace head (`Foo`) is recoverable for D13
; head-match recall (find_references("Foo") must see `Foo::bar()`/`Foo::create()`
; static-call & construction sites, which are keyed under the leaf `bar`).
; Scoped to call position to mirror the Rust rule and avoid double-capturing the
; leaf for non-call qualified identifiers.
(call_expression function: (qualified_identifier name: (identifier) @ref.call) @ref.qualified_call)

; #include imports
(preproc_include path: (string_literal) @ref.import)
(preproc_include path: (system_lib_string) @ref.import)

; Type identifiers
(type_identifier) @ref.type

; Template instantiation: vector<int>
(template_type name: (type_identifier) @ref.type)

; Using declarations: using std::string
(using_declaration (qualified_identifier) @import.original)

; Class inheritance: class Foo : public Bar
(class_specifier
  name: (type_identifier) @ref.implements_target
  (base_class_clause
    (type_identifier) @ref.implements))
"#;

const CSHARP_XREF_QUERY: &str = r#"
; Method invocations: obj.Method() — capture the method name
(invocation_expression
  (member_access_expression name: (identifier) @ref.method_call))

; Simple function calls: foo()
(invocation_expression
  function: (identifier) @ref.call)

; Object creation: new Foo()
(object_creation_expression type: (identifier) @ref.call)

; Using directives: keep the full namespace/type text when present.
(using_directive (qualified_name) @ref.import)
(using_directive (alias_qualified_name) @ref.import)
(using_directive (generic_name) @ref.import)
(using_directive (identifier) @ref.import)

; Type references in DI-style constructor params, fields, properties, and return types.
(parameter type: (type) @ref.type)
(variable_declaration type: (type) @ref.type)
(property_declaration type: (type) @ref.type)

; Class implements/extends: class Foo : IBar, Base
(class_declaration
  name: (identifier) @ref.implements_target
  (base_list (identifier) @ref.implements))
(class_declaration
  name: (identifier) @ref.implements_target
  (base_list (qualified_name) @ref.implements))
(class_declaration
  name: (identifier) @ref.implements_target
  (base_list (generic_name) @ref.implements))
"#;

const RUBY_XREF_QUERY: &str = r#"
; Method calls: foo() or object.method()
(call receiver: (_) method: (identifier) @ref.method_call)
(call method: (identifier) @ref.call)

; Require/require_relative
(call method: (identifier) @ref.import
  (#match? @ref.import "^require"))

; Constant references: MyClass, MY_CONST
(constant) @ref.type

; Class inheritance: class Foo < Bar
(class
  name: (constant) @ref.implements_target
  (superclass (constant) @ref.implements))
(class
  name: (constant) @ref.implements_target
  (superclass (scope_resolution) @ref.implements))
"#;

const KOTLIN_XREF_QUERY: &str = r#"
; Function/method calls: foo() or obj.method()
(call_expression (simple_identifier) @ref.call)
(navigation_expression (simple_identifier) @ref.method_call)

; Import directives
(import_header (identifier) @ref.import)

; Type references
(user_type (type_identifier) @ref.type)
"#;

const DART_XREF_QUERY: &str = r#"
; nielsenko tree-sitter-dart (0.2.0) call shapes, mirroring upstream
; tags.scm reference queries.

; Plain function calls: print(x), Circle(2.0)
(call_expression
  function: (identifier) @ref.call)

; Method calls through a receiver: c.area(), obj?.method()
(call_expression
  function: (member_expression property: (identifier) @ref.method_call))
(call_expression
  function: (null_aware_member_expression property: (identifier) @ref.method_call))

; Import directives: import 'dart:core'
; import_specification -> configurable_uri -> uri -> string_literal
(import_specification (configurable_uri (uri (string_literal) @ref.import)))

; Type identifiers
(type_identifier) @ref.type
"#;

const ELIXIR_XREF_QUERY: &str = r#"
; Function calls: Module.function()
(call target: (dot left: (alias) right: (identifier) @ref.method_call))

; Local function calls: my_func()
(call target: (identifier) @ref.call)

; alias/import/use module references — capture the module alias
(call target: (identifier)
  (arguments (alias) @ref.import))
"#;

const PHP_XREF_QUERY: &str = r#"
; Function calls: foo() — function: can be qualified_name or variable_name
(function_call_expression
  function: (qualified_name (name) @ref.call))

; Method calls: $obj->method()
(member_call_expression
  name: (name) @ref.method_call)

; Static calls: Foo::bar()
(scoped_call_expression
  name: (name) @ref.method_call)

; Type references in class extends/implements
(named_type (name) @ref.type)

; Class implements: class Foo implements Bar
(class_declaration
  name: (name) @ref.implements_target
  (class_interface_clause (name) @ref.implements))

; Class extends: class Foo extends Bar
(class_declaration
  name: (name) @ref.implements_target
  (base_clause (name) @ref.implements))
"#;

const SWIFT_XREF_QUERY: &str = r#"
; Navigation expression method calls: obj.method()
(navigation_expression
  (simple_identifier) @ref.method_call)

; Import declarations: import Foundation
(import_declaration
  (identifier) @ref.import)

; Type references
(user_type
  (type_identifier) @ref.type)

; Protocol conformance: class Foo: Bar, Protocol
(class_declaration
  name: (type_identifier) @ref.implements_target
  (inheritance_specifier
    (user_type (type_identifier) @ref.implements)))
"#;

const PERL_XREF_QUERY: &str = r#"
; Method calls: $obj->method()
(method_call_expression method: (method) @ref.method_call)

; Plain function calls: foo(1, 2)
(function_call_expression function: (function) @ref.call)

; Ambiguous list-op calls: print foo
(ambiguous_function_call_expression function: (function) @ref.call)

; Coderef invocation: $coderef->()
(coderef_call_expression (scalar (varname) @ref.call))

; use Foo::Bar;
(use_statement module: (package) @ref.import)

; require Baz::Qux;
(require_expression (bareword) @ref.import)

; Qualified static calls: Foo::bar() — leaf split in extract_references for Perl
; (function) node text is the full :: path; same capture as plain calls.
"#;

// ---------------------------------------------------------------------------
// OnceLock-cached compiled queries
// ---------------------------------------------------------------------------

// Each cache holds `Option<Query>`: `Some` once a query compiles, `None` when
// `Query::new` rejects it (a grammar/query node-kind mismatch). Caching `None`
// means a mismatch degrades to empty refs ONCE-AND-FOR-ALL instead of
// re-attempting (and re-logging) on every file. See `compile_xref_query`.
static RUST_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static RUST_CONST_DEF_QUERY_C: OnceLock<Option<Query>> = OnceLock::new();
static RUST_VALUE_IDENT_QUERY_C: OnceLock<Option<Query>> = OnceLock::new();
static RUST_QUALIFIED_VALUE_QUERY_C: OnceLock<Option<Query>> = OnceLock::new();
static PYTHON_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static PYTHON_VALUE_TYPE_IDENT_QUERY_C: OnceLock<Option<Query>> = OnceLock::new();
static PYTHON_STRING_TYPE_QUERY_C: OnceLock<Option<Query>> = OnceLock::new();
static JS_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static TS_QUERY: OnceLock<Option<Query>> = OnceLock::new();
// A tree-sitter Query binds to a specific Language's node-kind IDs. The TSX
// grammar (`LANGUAGE_TSX`) is a distinct Language from `LANGUAGE_TYPESCRIPT`,
// so the same xref query source must be compiled and cached separately for it;
// reusing the TS-compiled query against a TSX tree yields wrong/empty matches.
static TSX_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static GO_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static JAVA_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static C_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static CPP_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static CSHARP_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static RUBY_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static KOTLIN_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static DART_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static ELIXIR_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static PHP_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static SWIFT_QUERY: OnceLock<Option<Query>> = OnceLock::new();
static PERL_QUERY: OnceLock<Option<Query>> = OnceLock::new();

/// Compile a tree-sitter xref query, caching the result in `cache`.
///
/// On a `Query::new` error (a grammar/query node-kind mismatch — e.g. a
/// grammar swap that renamed the nodes a query targets) this logs a
/// `tracing::warn!` and caches `None`, so cross-reference extraction degrades
/// to *empty refs* instead of panicking. The `None` is cached permanently:
/// a query that fails to compile against the linked grammar will never
/// compile, so there is no value in retrying (or re-logging) per file.
///
/// `label` names the query for the log line (e.g. `"perl"`, `"rust const-def"`).
fn compile_xref_query(
    cache: &'static OnceLock<Option<Query>>,
    lang: &Language,
    src: &str,
    label: &str,
) -> Option<&'static Query> {
    cache
        .get_or_init(|| match Query::new(lang, src) {
            Ok(query) => Some(query),
            Err(err) => {
                tracing::warn!(
                    query = label,
                    error = %err,
                    "xref query failed to compile against the linked grammar; \
                     cross-references for this language are disabled"
                );
                None
            }
        })
        .as_ref()
}

// ponytail: these ~17 per-language query getters look like collapsible
// boilerplate (audit 2026-06-17, Tier 4a). A `OnceLock<Query>`-table collapse was
// implemented and fully verified (all 21 langs byte-identical, 3016 tests green)
// and then REJECTED 2026-06-18: it saved ~0 production lines, the 17-arm dispatch
// match is irreducible regardless, and it traded "a language cannot be mis-bound"
// (robust by construction) for "a language is mis-bound if the slot/enum order
// ever drifts" (guarded only by a test). For load-bearing symbol resolution —
// where a wrong query silently corrupts xref and breaks LLM trust — the explicit,
// impossible-to-misalign form is the superior one. Do NOT collapse without a
// reason that outweighs that trade.
// Every getter returns `Option<&'static Query>`: `Some` on success, `None` if
// the query failed to compile against the linked grammar (logged once, cached).
// Callers degrade to empty refs on `None` rather than panicking.
fn rust_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&RUST_QUERY, lang, RUST_XREF_QUERY, "rust")
}

fn rust_const_def_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(
        &RUST_CONST_DEF_QUERY_C,
        lang,
        RUST_CONST_DEF_QUERY,
        "rust const-def",
    )
}

fn rust_value_ident_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(
        &RUST_VALUE_IDENT_QUERY_C,
        lang,
        RUST_VALUE_IDENT_QUERY,
        "rust value-ident",
    )
}

fn rust_qualified_value_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(
        &RUST_QUALIFIED_VALUE_QUERY_C,
        lang,
        RUST_QUALIFIED_VALUE_QUERY,
        "rust qualified-value",
    )
}

fn python_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&PYTHON_QUERY, lang, PYTHON_XREF_QUERY, "python")
}

fn python_value_type_ident_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(
        &PYTHON_VALUE_TYPE_IDENT_QUERY_C,
        lang,
        PYTHON_VALUE_TYPE_IDENT_QUERY,
        "python value-type ident",
    )
}

fn python_string_type_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(
        &PYTHON_STRING_TYPE_QUERY_C,
        lang,
        PYTHON_STRING_TYPE_QUERY,
        "python string-type",
    )
}

fn js_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&JS_QUERY, lang, JS_XREF_QUERY, "js")
}

fn ts_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&TS_QUERY, lang, TS_XREF_QUERY, "ts")
}

/// The TSX-grammar counterpart of [`ts_query`]. Compiled against `LANGUAGE_TSX`
/// and cached independently of the plain TypeScript query.
fn tsx_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&TSX_QUERY, lang, TS_XREF_QUERY, "tsx")
}

fn go_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&GO_QUERY, lang, GO_XREF_QUERY, "go")
}

fn java_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&JAVA_QUERY, lang, JAVA_XREF_QUERY, "java")
}

fn c_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&C_QUERY, lang, C_XREF_QUERY, "c")
}

fn cpp_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&CPP_QUERY, lang, CPP_XREF_QUERY, "cpp")
}

fn csharp_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&CSHARP_QUERY, lang, CSHARP_XREF_QUERY, "csharp")
}

fn ruby_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&RUBY_QUERY, lang, RUBY_XREF_QUERY, "ruby")
}

fn kotlin_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&KOTLIN_QUERY, lang, KOTLIN_XREF_QUERY, "kotlin")
}

fn dart_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&DART_QUERY, lang, DART_XREF_QUERY, "dart")
}

fn elixir_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&ELIXIR_QUERY, lang, ELIXIR_XREF_QUERY, "elixir")
}

fn php_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&PHP_QUERY, lang, PHP_XREF_QUERY, "php")
}

fn swift_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&SWIFT_QUERY, lang, SWIFT_XREF_QUERY, "swift")
}

fn perl_query(lang: &Language) -> Option<&'static Query> {
    compile_xref_query(&PERL_QUERY, lang, PERL_XREF_QUERY, "perl")
}

fn split_top_level_rust_items(input: &str) -> Vec<&str> {
    let mut parts = Vec::new();
    let mut depth = 0usize;
    let mut start = 0usize;

    for (idx, ch) in input.char_indices() {
        match ch {
            '{' => depth += 1,
            '}' => depth = depth.saturating_sub(1),
            ',' if depth == 0 => {
                parts.push(input[start..idx].trim());
                start = idx + ch.len_utf8();
            }
            _ => {}
        }
    }

    if start <= input.len() {
        parts.push(input[start..].trim());
    }

    parts.into_iter().filter(|part| !part.is_empty()).collect()
}

fn rust_grouped_import_parts(input: &str) -> Option<(&str, &str)> {
    let trimmed = input.trim();
    let brace_start = trimmed.find('{')?;
    let brace_end = trimmed.rfind('}')?;
    if brace_end <= brace_start {
        return None;
    }

    let prefix = trimmed[..brace_start].trim_end().trim_end_matches("::");
    let inner = &trimmed[brace_start + 1..brace_end];
    Some((prefix, inner))
}

/// Whether an Elixir `@ref.import` alias node belongs to a genuine module
/// directive (`alias`/`import`/`use`/`require`) rather than an arbitrary call
/// that happens to take a module alias as its first argument (e.g.
/// `raise ArgumentError`, `socket "...", UserSocket`).
///
/// The import query captures the `(alias)` inside `(call target: (identifier)
/// (arguments (alias)))`. We walk up to the enclosing `call` node, read its
/// `target` field text, and accept only the directive keywords. Returns `false`
/// when the enclosing call or its target cannot be resolved, so a non-directive
/// call never produces a spurious `Import` reference.
fn elixir_import_target_is_directive(alias_node: Node, source_bytes: &[u8]) -> bool {
    const DIRECTIVES: [&str; 4] = ["alias", "import", "use", "require"];

    // Walk up to the nearest `call` ancestor (alias -> arguments -> call).
    let mut node = alias_node;
    while node.kind() != "call" {
        match node.parent() {
            Some(parent) => node = parent,
            None => return false,
        }
    }

    node.child_by_field_name("target")
        .and_then(|target| target.utf8_text(source_bytes).ok())
        .map(|text| DIRECTIVES.contains(&text.trim()))
        .unwrap_or(false)
}

fn expand_rust_import_paths(input: &str) -> Vec<String> {
    let trimmed = input.trim();
    let alias_free = trimmed
        .split_once(" as ")
        .map(|(original, _)| original.trim())
        .unwrap_or(trimmed);

    if let Some((prefix, inner)) = rust_grouped_import_parts(alias_free) {
        return split_top_level_rust_items(inner)
            .into_iter()
            .flat_map(|item| {
                let combined = if prefix.is_empty() {
                    item.to_string()
                } else {
                    format!("{prefix}::{item}")
                };
                expand_rust_import_paths(&combined)
            })
            .collect();
    }

    vec![alias_free.to_string()]
}

/// `use parent qw(Foo)` / `use base qw(Bar)` — pragma name is on `(package)` but the
/// inherited module lives in `(quoted_word_list content: (string_content))`.
fn perl_use_import_paths(import_node: Node, name_text: &str, source_bytes: &[u8]) -> Vec<String> {
    let pragma = name_text.trim();
    if pragma != "parent" && pragma != "base" {
        return vec![pragma.to_string()];
    }

    let Some(use_stmt) = import_node.parent().filter(|n| n.kind() == "use_statement") else {
        return vec![pragma.to_string()];
    };

    let mut modules = Vec::new();
    let mut cursor = use_stmt.walk();
    for child in use_stmt.children(&mut cursor) {
        if child.kind() != "quoted_word_list" {
            continue;
        }
        let mut list_cursor = child.walk();
        for list_child in child.children(&mut list_cursor) {
            if list_child.kind() == "string_content"
                && let Ok(text) = list_child.utf8_text(source_bytes)
            {
                let module = text.trim();
                if !module.is_empty() {
                    modules.push(module.to_string());
                }
            }
        }
    }

    if modules.is_empty() {
        vec![pragma.to_string()]
    } else {
        modules
    }
}

fn push_import_reference(
    references: &mut Vec<ReferenceRecord>,
    import_text: &str,
    import_node: Node,
) {
    let full_text = import_text.trim();
    let name = if full_text.contains('/') && !full_text.contains("::") {
        // JS/TS path imports like '../utils/helpers' — take the last path segment
        full_text.split('/').next_back().unwrap_or(full_text)
    } else {
        // Reduce a qualified import to its final segment so name-based
        // find_references matches it: strip `::` then `.` (namespace.Class ->
        // Class, module path 'pkg.sub' -> sub), mirroring the `/` path-segment
        // handling above. `qualified_name` below retains the full dotted path.
        let after_colons = full_text.rsplit("::").next().unwrap_or(full_text);
        after_colons.rsplit('.').next().unwrap_or(after_colons)
    };
    let name = name.trim_matches('"').trim_matches('\'').to_string();

    if name.is_empty() {
        return;
    }

    let qualified_name = if full_text.contains("::") || full_text.contains('.') {
        Some(full_text.to_string())
    } else {
        None
    };
    let start = import_node.start_position();
    let end = import_node.end_position();
    references.push(ReferenceRecord {
        name,
        qualified_name,
        kind: ReferenceKind::Import,
        byte_range: (
            import_node.start_byte() as u32,
            import_node.end_byte() as u32,
        ),
        line_range: (start.row as u32, end.row as u32),
        enclosing_symbol_index: None,
    });
}

fn python_attribute_qualified_name(node: Node, source_bytes: &[u8]) -> Option<String> {
    if node.kind() == "attribute" {
        return node
            .utf8_text(source_bytes)
            .ok()
            .map(|text| text.trim().to_string());
    }
    node.parent()
        .filter(|parent| parent.kind() == "attribute")
        .and_then(|parent| parent.utf8_text(source_bytes).ok())
        .map(|text| text.trim().to_string())
}

fn python_name_looks_like_type(name: &str) -> bool {
    name.chars()
        .next()
        .is_some_and(|ch| ch.is_ascii_uppercase())
}

/// Resolve uppercase class-name tokens in call argument lists (e.g.
/// `isinstance(x, Model)`, `ForeignKey(Model)`).
fn extract_python_value_refs(
    root: &Node,
    source: &str,
    ts_language: &Language,
    existing: &[ReferenceRecord],
) -> Vec<ReferenceRecord> {
    let source_bytes = source.as_bytes();
    let existing_ranges: HashSet<(u32, u32)> = existing.iter().map(|r| r.byte_range).collect();
    let Some(value_query) = python_value_type_ident_query(ts_language) else {
        return Vec::new();
    };
    let value_capture_names = value_query.capture_names();
    let mut out: Vec<ReferenceRecord> = Vec::new();
    let mut emitted_ranges: HashSet<(u32, u32)> = HashSet::new();

    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(value_query, *root, source_bytes);
    while let Some(m) = {
        matches.advance();
        matches.get()
    } {
        let mut value_ident: Option<Node> = None;
        let mut value_attr: Option<Node> = None;

        for capture in m.captures {
            match value_capture_names[capture.index as usize] {
                "ref.value" => value_ident = Some(capture.node),
                "ref.value_attr" => value_attr = Some(capture.node),
                _ => {}
            }
        }

        let (node, qualified_name) = if let Some(attr_node) = value_attr {
            let Some(parent) = attr_node.parent().filter(|n| n.kind() == "attribute") else {
                continue;
            };
            (
                attr_node,
                parent
                    .utf8_text(source_bytes)
                    .ok()
                    .map(|text| text.trim().to_string()),
            )
        } else if let Some(ident_node) = value_ident {
            (ident_node, None)
        } else {
            continue;
        };

        let range = (node.start_byte() as u32, node.end_byte() as u32);
        if existing_ranges.contains(&range) || emitted_ranges.contains(&range) {
            continue;
        }

        let Ok(text) = node.utf8_text(source_bytes) else {
            continue;
        };
        let name = text.trim();
        if name.is_empty() || !python_name_looks_like_type(name) {
            continue;
        }

        let start = node.start_position();
        let end = node.end_position();
        out.push(ReferenceRecord {
            name: name.to_string(),
            qualified_name,
            kind: ReferenceKind::ValueUse,
            byte_range: range,
            line_range: (start.row as u32, end.row as u32),
            enclosing_symbol_index: None,
        });
        emitted_ranges.insert(range);
    }

    out
}

fn python_string_type_name(raw: &str) -> Option<(String, Option<String>)> {
    let trimmed = raw.trim();
    let unquoted = trimmed
        .strip_prefix('"')
        .and_then(|s| s.strip_suffix('"'))
        .or_else(|| {
            trimmed
                .strip_prefix('\'')
                .and_then(|s| s.strip_suffix('\''))
        })?;
    let unquoted = unquoted.trim();
    if unquoted.is_empty() {
        return None;
    }
    if python_name_looks_like_type(unquoted) {
        return Some((unquoted.to_string(), None));
    }
    if let Some((prefix, name)) = unquoted.rsplit_once('.')
        && python_name_looks_like_type(name)
    {
        return Some((name.to_string(), Some(format!("{prefix}.{name}"))));
    }
    None
}

/// Resolve class-name tokens in string call arguments (migration labels, mock.patch paths).
fn extract_python_string_type_refs(
    root: &Node,
    source: &str,
    ts_language: &Language,
    existing: &[ReferenceRecord],
) -> Vec<ReferenceRecord> {
    let source_bytes = source.as_bytes();
    let existing_ranges: HashSet<(u32, u32)> = existing.iter().map(|r| r.byte_range).collect();
    let Some(string_query) = python_string_type_query(ts_language) else {
        return Vec::new();
    };
    let string_capture_names = string_query.capture_names();
    let mut out: Vec<ReferenceRecord> = Vec::new();
    let mut emitted_ranges: HashSet<(u32, u32)> = HashSet::new();

    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(string_query, *root, source_bytes);
    while let Some(m) = {
        matches.advance();
        matches.get()
    } {
        for capture in m.captures {
            if string_capture_names[capture.index as usize] != "ref.string" {
                continue;
            }
            let node = capture.node;
            let range = (node.start_byte() as u32, node.end_byte() as u32);
            if existing_ranges.contains(&range) || emitted_ranges.contains(&range) {
                continue;
            }
            let Ok(text) = node.utf8_text(source_bytes) else {
                continue;
            };
            let Some((name, qualified_name)) = python_string_type_name(text) else {
                continue;
            };
            let start = node.start_position();
            let end = node.end_position();
            out.push(ReferenceRecord {
                name,
                qualified_name,
                kind: ReferenceKind::ValueUse,
                byte_range: range,
                line_range: (start.row as u32, end.row as u32),
                enclosing_symbol_index: None,
            });
            emitted_ranges.insert(range);
        }
    }

    out
}

/// Resolve bare value-position references to same-file `const`/`static` items.
///
/// The main Rust query only captures identifiers in *call*, *type*, *import*,
/// *macro*, or *qualified-path* positions. A `const`/`static` used as a plain
/// value — iterated in `for x in CONST`, passed as `CONST.contains(..)`, or
/// handed to a function as a bare argument — is just an `(identifier)` node and
/// is therefore invisible to the main query. This pass closes that gap with
/// strict, precision-first calibration:
///
/// 1. It builds the set of `const`/`static` definition names declared *in this
///    same file*. A bare identifier is emitted ONLY when its exact text is in
///    that set, so ordinary locals, parameters, struct fields, and function
///    names are never reported (a `let foo` is not a reference to `const FOO`,
///    and case is significant). If the file declares no consts/statics the pass
///    does nothing.
/// 2. It skips the definition sites themselves (the identifier in
///    `const FOO: .. = ..;` is not a self-reference).
/// 3. It dedupes against every range already captured by the main query, so a
///    name already recorded as a call/type/import/macro/qualified-path hit is
///    not double-counted, and it dedupes within this pass.
///
/// Precision over recall: a cross-file bare use whose target const is not
/// defined in the current file is intentionally *not* resolved here (we have no
/// whole-repo symbol table at extraction time). Missing such a use is
/// acceptable — `find_references` prints a `search_text` fallback hint on an
/// empty result — whereas a false positive would poison a high-traffic tool.
fn extract_rust_value_refs(
    root: &Node,
    source: &str,
    ts_language: &Language,
    existing: &[ReferenceRecord],
) -> Vec<ReferenceRecord> {
    let source_bytes = source.as_bytes();

    // Step 1: collect same-file const/static definition names and their
    // definition-site byte ranges (so we can skip the definition itself).
    let Some(def_query) = rust_const_def_query(ts_language) else {
        return Vec::new();
    };
    let def_capture_names = def_query.capture_names();
    let mut def_names: HashSet<String> = HashSet::new();
    let mut def_ranges: HashSet<(u32, u32)> = HashSet::new();
    {
        let mut cursor = QueryCursor::new();
        let mut matches = cursor.matches(def_query, *root, source_bytes);
        while let Some(m) = {
            matches.advance();
            matches.get()
        } {
            for capture in m.captures {
                if def_capture_names[capture.index as usize] != "const.def" {
                    continue;
                }
                let node = capture.node;
                if let Ok(text) = node.utf8_text(source_bytes) {
                    let trimmed = text.trim();
                    if !trimmed.is_empty() {
                        def_names.insert(trimmed.to_string());
                        def_ranges.insert((node.start_byte() as u32, node.end_byte() as u32));
                    }
                }
            }
        }
    }

    // No consts/statics defined here → nothing this pass can resolve.
    if def_names.is_empty() {
        return Vec::new();
    }

    // Ranges already captured by the main query (any kind), used for dedup so a
    // name already recorded as a call/type/import/macro/qualified hit is not
    // emitted again as a value use.
    let existing_ranges: HashSet<(u32, u32)> = existing.iter().map(|r| r.byte_range).collect();

    // Step 2: scan every bare value-position identifier and emit a reference
    // only for those resolving to a known same-file const/static.
    let Some(value_query) = rust_value_ident_query(ts_language) else {
        return Vec::new();
    };
    let value_capture_names = value_query.capture_names();
    let mut out: Vec<ReferenceRecord> = Vec::new();
    let mut emitted_ranges: HashSet<(u32, u32)> = HashSet::new();

    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(value_query, *root, source_bytes);
    while let Some(m) = {
        matches.advance();
        matches.get()
    } {
        for capture in m.captures {
            if value_capture_names[capture.index as usize] != "ref.value" {
                continue;
            }
            let node = capture.node;
            let range = (node.start_byte() as u32, node.end_byte() as u32);

            // Skip the definition site itself.
            if def_ranges.contains(&range) {
                continue;
            }
            // Skip anything already captured by the main query or this pass.
            if existing_ranges.contains(&range) || emitted_ranges.contains(&range) {
                continue;
            }

            let Ok(text) = node.utf8_text(source_bytes) else {
                continue;
            };
            let name = text.trim();
            // Exact, case-sensitive match against same-file const/static names.
            if name.is_empty() || !def_names.contains(name) {
                continue;
            }

            let start = node.start_position();
            let end = node.end_position();
            out.push(ReferenceRecord {
                name: name.to_string(),
                qualified_name: None,
                kind: ReferenceKind::ValueUse,
                byte_range: range,
                line_range: (start.row as u32, end.row as u32),
                enclosing_symbol_index: None,
            });
            emitted_ranges.insert(range);
        }
    }

    out
}

/// Resolve path-qualified references used in *value* position, e.g. a function
/// passed as an argument rather than called: `from_fn(handlers::caller_guard)`.
///
/// The main Rust query captures a `scoped_identifier` only when it is the
/// function of a `call_expression` (`Vec::new()`), and the macro-body text
/// fallback only recovers `a::b::name(` *call* shapes. A qualified path in a
/// value position (argument, `let` binding, struct field init, `Self::CONST`,
/// `Enum::Variant` as an expression) is therefore invisible to
/// `find_references`. This pass closes that gap.
///
/// Precision — a bare `(scoped_identifier)` match is enormous, so each hit is
/// gated by the parent node kind (cheaper and clearer than encoding these
/// exclusions in the tree-sitter query):
///  * parent `call_expression` / `generic_function` → the path IS the callee of
///    a (possibly turbofish) qualified call, already captured as `Call`; skip.
///  * parent `scoped_identifier` → this is the `path:` prefix of a longer path
///    (`axum::middleware` inside `axum::middleware::from_fn`); only the
///    outermost path is emitted, so skip the prefix.
///  * any ancestor `use_declaration` → import segment, handled by import capture.
///  * parent is a pattern node (`match_pattern`, `tuple_struct_pattern`,
///    `struct_pattern`, `or_pattern`) → a match/`let` pattern, not a value use.
///
/// `Type::CONST` / `Enum::Variant` in genuine value position are kept — they
/// are real value usages. `name` is the leaf identifier (for name-based
/// `find_references`); `qualified_name` retains the full `::` path.
fn extract_rust_qualified_value_refs(
    root: &Node,
    source: &str,
    ts_language: &Language,
    existing: &[ReferenceRecord],
) -> Vec<ReferenceRecord> {
    let source_bytes = source.as_bytes();
    let Some(query) = rust_qualified_value_query(ts_language) else {
        return Vec::new();
    };
    let capture_names = query.capture_names();
    // Dedup against ranges already captured by the main query (belt-and-braces;
    // the parent-kind gate below is the real call-site guard) and within pass.
    let existing_ranges: HashSet<(u32, u32)> = existing.iter().map(|r| r.byte_range).collect();
    let mut emitted_ranges: HashSet<(u32, u32)> = HashSet::new();
    let mut out: Vec<ReferenceRecord> = Vec::new();

    let mut cursor = QueryCursor::new();
    let mut matches = cursor.matches(query, *root, source_bytes);
    while let Some(m) = {
        matches.advance();
        matches.get()
    } {
        for capture in m.captures {
            if capture_names[capture.index as usize] != "ref.qualified_value" {
                continue;
            }
            let node = capture.node;

            // Parent-kind gate.
            let parent_kind = node.parent().map(|p| p.kind());
            // Callee of a qualified call (already a `Call` ref), the prefix
            // of a longer path, or a pattern position — all excluded.
            if let Some(
                "call_expression"
                | "generic_function"
                | "scoped_identifier"
                | "match_pattern"
                | "tuple_struct_pattern"
                | "struct_pattern"
                | "or_pattern",
            ) = parent_kind
            {
                continue;
            }

            // Skip anything inside a `use` declaration (imports are captured by
            // the main query's import rules).
            let mut ancestor = node.parent();
            let mut in_use = false;
            while let Some(a) = ancestor {
                if a.kind() == "use_declaration" {
                    in_use = true;
                    break;
                }
                ancestor = a.parent();
            }
            if in_use {
                continue;
            }

            let range = (node.start_byte() as u32, node.end_byte() as u32);
            if existing_ranges.contains(&range) || emitted_ranges.contains(&range) {
                continue;
            }

            // Leaf identifier for name-based lookup; full path for qualified_name.
            let Some(leaf) = node.child_by_field_name("name") else {
                continue;
            };
            let Ok(leaf_text) = leaf.utf8_text(source_bytes) else {
                continue;
            };
            let name = leaf_text.trim();
            if name.is_empty() {
                continue;
            }
            let qualified_name = node
                .utf8_text(source_bytes)
                .ok()
                .map(|t| t.trim().to_string());

            let start = node.start_position();
            let end = node.end_position();
            out.push(ReferenceRecord {
                name: name.to_string(),
                qualified_name,
                kind: ReferenceKind::ValueUse,
                byte_range: range,
                line_range: (start.row as u32, end.row as u32),
                enclosing_symbol_index: None,
            });
            emitted_ranges.insert(range);
        }
    }

    out
}

// ---------------------------------------------------------------------------
// Main extraction function
// ---------------------------------------------------------------------------

/// Collect the byte ranges of every `macro_invocation` node in a Rust tree.
///
/// tree-sitter parses macro arguments as an opaque `token_tree` (raw tokens),
/// so call/type/import queries never fire inside a macro body. Callers use
/// these ranges to scope a text-based recovery scan to macro interiors only,
/// where whole-file scanning would otherwise be too imprecise.
fn collect_rust_macro_ranges(root: &Node) -> Vec<(u32, u32)> {
    let mut ranges: Vec<(u32, u32)> = Vec::new();
    let mut cursor = root.walk();
    let mut stack: Vec<Node> = vec![*root];
    while let Some(node) = stack.pop() {
        if node.kind() == "macro_invocation" {
            ranges.push((node.start_byte() as u32, node.end_byte() as u32));
        }
        for child in node.children(&mut cursor) {
            stack.push(child);
        }
    }
    ranges
}

/// Extract cross-references from a parsed tree-sitter tree.
///
/// Returns `(Vec<ReferenceRecord>, HashMap<String, String>)` where the HashMap
/// is the alias map (alias → original) built from import-as patterns.
///
/// Note: `enclosing_symbol_index` is NOT set here — it is assigned later in
/// `IndexedFile::from_parse_result` where both symbols and references are available.
pub fn extract_references(
    root: &Node,
    source: &str,
    language: &LanguageId,
    is_tsx: bool,
) -> (Vec<ReferenceRecord>, HashMap<String, String>) {
    let source_bytes = source.as_bytes();

    let (query, ts_language) = match language {
        LanguageId::Rust => {
            let lang: Language = tree_sitter_rust::LANGUAGE.into();
            (rust_query(&lang), lang)
        }
        LanguageId::Python => {
            let lang: Language = tree_sitter_python::LANGUAGE.into();
            (python_query(&lang), lang)
        }
        LanguageId::JavaScript => {
            let lang: Language = tree_sitter_javascript::LANGUAGE.into();
            (js_query(&lang), lang)
        }
        LanguageId::TypeScript => {
            // `.tsx` uses the TSX grammar; the xref query MUST be compiled
            // against whichever grammar parsed the tree so node-kind IDs line up
            // (TS and TSX are distinct tree-sitter Languages with separate query
            // caches — see `tsx_query`).
            if is_tsx {
                let lang: Language = tree_sitter_typescript::LANGUAGE_TSX.into();
                (tsx_query(&lang), lang)
            } else {
                let lang: Language = tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into();
                (ts_query(&lang), lang)
            }
        }
        LanguageId::Go => {
            let lang: Language = tree_sitter_go::LANGUAGE.into();
            (go_query(&lang), lang)
        }
        LanguageId::Java => {
            let lang: Language = tree_sitter_java::LANGUAGE.into();
            (java_query(&lang), lang)
        }
        LanguageId::C => {
            let lang: Language = tree_sitter_c::LANGUAGE.into();
            (c_query(&lang), lang)
        }
        LanguageId::Cpp => {
            let lang: Language = tree_sitter_cpp::LANGUAGE.into();
            (cpp_query(&lang), lang)
        }
        LanguageId::CSharp => {
            let lang: Language = tree_sitter_c_sharp::LANGUAGE.into();
            (csharp_query(&lang), lang)
        }
        LanguageId::Ruby => {
            let lang: Language = tree_sitter_ruby::LANGUAGE.into();
            (ruby_query(&lang), lang)
        }
        LanguageId::Kotlin => {
            let lang: Language = tree_sitter_kotlin_sg::LANGUAGE.into();
            (kotlin_query(&lang), lang)
        }
        LanguageId::Dart => {
            let lang: Language = tree_sitter_dart::LANGUAGE.into();
            (dart_query(&lang), lang)
        }
        LanguageId::Elixir => {
            let lang: Language = tree_sitter_elixir::LANGUAGE.into();
            (elixir_query(&lang), lang)
        }
        LanguageId::Php => {
            let lang: Language = tree_sitter_php::LANGUAGE_PHP.into();
            (php_query(&lang), lang)
        }
        LanguageId::Swift => {
            let lang: Language = tree_sitter_swift::LANGUAGE.into();
            (swift_query(&lang), lang)
        }
        LanguageId::Perl => {
            let lang: Language = tree_sitter_perl::LANGUAGE.into();
            (perl_query(&lang), lang)
        }
        LanguageId::Json
        | LanguageId::Toml
        | LanguageId::Yaml
        | LanguageId::Markdown
        | LanguageId::Env => unreachable!("config types are handled before extract_references"),
        LanguageId::Html | LanguageId::Css | LanguageId::Scss => {
            return (vec![], HashMap::new());
        }
    };

    // The main query may be `None` if it failed to compile against the linked
    // grammar (e.g. a grammar swap renamed the nodes it targets). Degrade to
    // empty refs rather than panicking — `compile_xref_query` already logged it.
    let Some(query) = query else {
        return (Vec::new(), HashMap::new());
    };

    // Safety: the query and parse tree use the same grammar version because both are produced by
    // the same linked tree-sitter crate. The OnceLock ensures the query is compiled once and reused.
    // `ts_language` is reused below for the Rust const/static value-reference pass.
    let _ = &ts_language;

    let capture_names = query.capture_names();
    let mut cursor = QueryCursor::new();
    let mut references: Vec<ReferenceRecord> = Vec::new();
    let mut alias_map: HashMap<String, String> = HashMap::new();

    // StreamingIterator: use advance()/get() pattern instead of for..in
    let mut matches = cursor.matches(query, *root, source_bytes);
    while let Some(m) = {
        matches.advance();
        matches.get()
    } {
        let mut ref_call: Option<Node> = None;
        let mut ref_qualified_call: Option<Node> = None;
        let mut ref_method_call: Option<Node> = None;
        let mut ref_import: Option<Node> = None;
        let mut ref_type: Option<Node> = None;
        let mut ref_macro: Option<Node> = None;
        let mut import_original: Option<Node> = None;
        let mut import_alias: Option<Node> = None;
        let mut ref_implements: Option<Node> = None;
        let mut ref_implements_target: Option<Node> = None;

        for capture in m.captures {
            let name = capture_names[capture.index as usize];
            let node = capture.node;
            match name {
                "ref.call" => {
                    ref_call = Some(node);
                }
                "ref.qualified_call" => {
                    ref_qualified_call = Some(node);
                }
                "ref.method_call" => {
                    ref_method_call = Some(node);
                }
                "ref.import" => {
                    ref_import = Some(node);
                }
                "ref.type" => {
                    ref_type = Some(node);
                }
                "ref.macro" => {
                    ref_macro = Some(node);
                }
                "import.original" => {
                    import_original = Some(node);
                }
                "import.alias" => {
                    import_alias = Some(node);
                }
                "ref.implements" => {
                    ref_implements = Some(node);
                }
                "ref.implements_target" => {
                    ref_implements_target = Some(node);
                }
                _ => {}
            }
        }

        // Handle alias pair — build alias_map and skip generating a reference
        if let (Some(orig_node), Some(alias_node)) = (import_original, import_alias) {
            if let (Ok(orig_text), Ok(alias_text)) = (
                orig_node.utf8_text(source_bytes),
                alias_node.utf8_text(source_bytes),
            ) {
                // Extract the last segment of the original path (e.g. "HashMap" from "std::collections::HashMap")
                let orig_name = orig_text
                    .split("::")
                    .last()
                    .unwrap_or(orig_text)
                    .trim()
                    .to_string();
                let alias_str = alias_text.trim().to_string();
                alias_map.insert(alias_str, orig_name);
            }
            continue;
        }

        // Process ref.call (potentially with qualified_call overlay)
        if let Some(call_node) = ref_call
            && let Ok(name_text) = call_node.utf8_text(source_bytes)
        {
            let mut name = name_text.trim().to_string();
            let mut qualified_name = if let Some(qual_node) = ref_qualified_call {
                qual_node
                    .utf8_text(source_bytes)
                    .ok()
                    .map(|t| t.trim().to_string())
            } else {
                None
            };

            // ts-parser-perl: `Foo::bar()` captures the whole path on the `(function)`
            // node — split to leaf + qualified_name like import refs for recall.
            if *language == LanguageId::Perl && qualified_name.is_none() && name.contains("::") {
                let full = name.clone();
                name = full.rsplit("::").next().unwrap_or(&full).to_string();
                qualified_name = Some(full);
            }

            let start = call_node.start_position();
            let end = call_node.end_position();
            references.push(ReferenceRecord {
                name,
                qualified_name,
                kind: ReferenceKind::Call,
                byte_range: (call_node.start_byte() as u32, call_node.end_byte() as u32),
                line_range: (start.row as u32, end.row as u32),
                enclosing_symbol_index: None,
            });
        }

        // Method call
        if let Some(method_node) = ref_method_call
            && let Ok(name_text) = method_node.utf8_text(source_bytes)
        {
            let mut name = name_text.trim().to_string();
            let mut qualified_name = None;

            // ts-parser-perl: `$self->SUPER::method()` puts the full path on `(method)`.
            if *language == LanguageId::Perl && name.contains("::") {
                let full = name.clone();
                name = full.rsplit("::").next().unwrap_or(&full).to_string();
                qualified_name = Some(full);
            }

            let start = method_node.start_position();
            let end = method_node.end_position();
            references.push(ReferenceRecord {
                name,
                qualified_name,
                kind: ReferenceKind::Call,
                byte_range: (
                    method_node.start_byte() as u32,
                    method_node.end_byte() as u32,
                ),
                line_range: (start.row as u32, end.row as u32),
                enclosing_symbol_index: None,
            });
        }

        // Import
        if let Some(import_node) = ref_import
            && let Ok(name_text) = import_node.utf8_text(source_bytes)
            // Elixir guard: the import query `(call target: (identifier)
            // (arguments (alias) @ref.import))` cannot distinguish a real
            // directive (`alias`/`import`/`use`/`require`) from any other call
            // that takes a module as its first argument (`raise ArgumentError`,
            // `socket "...", UserSocket`). Tree-sitter text predicates are NOT
            // applied by `QueryCursor::matches`, so constrain it here: only keep
            // the import when the enclosing call's target is a directive keyword.
            && (*language != LanguageId::Elixir
                || elixir_import_target_is_directive(import_node, source_bytes))
        {
            let import_texts = match language {
                LanguageId::Rust => expand_rust_import_paths(name_text),
                LanguageId::Perl => perl_use_import_paths(import_node, name_text, source_bytes),
                _ => vec![name_text.trim().to_string()],
            };

            for import_text in import_texts {
                push_import_reference(&mut references, &import_text, import_node);
            }
        }

        // Type reference
        if let Some(type_node) = ref_type
            && let Ok(name_text) = type_node.utf8_text(source_bytes)
        {
            let name = name_text.trim().to_string();
            if !name.is_empty() {
                let qualified_name = python_attribute_qualified_name(type_node, source_bytes);
                let start = type_node.start_position();
                let end = type_node.end_position();
                references.push(ReferenceRecord {
                    name,
                    qualified_name,
                    kind: ReferenceKind::TypeUsage,
                    byte_range: (type_node.start_byte() as u32, type_node.end_byte() as u32),
                    line_range: (start.row as u32, end.row as u32),
                    enclosing_symbol_index: None,
                });
            }
        }

        // Macro use
        if let Some(macro_node) = ref_macro
            && let Ok(name_text) = macro_node.utf8_text(source_bytes)
        {
            let name = name_text.trim().to_string();
            if !name.is_empty() {
                let start = macro_node.start_position();
                let end = macro_node.end_position();
                references.push(ReferenceRecord {
                    name,
                    qualified_name: None,
                    kind: ReferenceKind::MacroUse,
                    byte_range: (macro_node.start_byte() as u32, macro_node.end_byte() as u32),
                    line_range: (start.row as u32, end.row as u32),
                    enclosing_symbol_index: None,
                });
            }
        }

        // Implements / inherits relationship
        if let Some(impl_node) = ref_implements
            && let Ok(impl_text) = impl_node.utf8_text(source_bytes)
        {
            let trait_name = impl_text.trim().to_string();
            if !trait_name.is_empty() {
                let qualified_name = if let Some(target_node) = ref_implements_target {
                    target_node
                        .utf8_text(source_bytes)
                        .ok()
                        .map(|text| text.trim().to_string())
                        .filter(|implementor| !implementor.is_empty())
                } else {
                    python_attribute_qualified_name(impl_node, source_bytes)
                };

                let start = impl_node.start_position();
                let end = impl_node.end_position();
                references.push(ReferenceRecord {
                    name: trait_name,
                    qualified_name,
                    kind: ReferenceKind::Implements,
                    byte_range: (impl_node.start_byte() as u32, impl_node.end_byte() as u32),
                    line_range: (start.row as u32, end.row as u32),
                    enclosing_symbol_index: None,
                });
            }
        }
    }

    // --- Rust macro-body fallback ---
    //
    // tree-sitter parses Rust macro bodies as `token_tree` (raw tokens), so
    // `call_expression` / `scoped_identifier` queries never fire inside macros
    // like `format!(... crate::hash::digest_hex(...))`.  Fall back to a text
    // scan that recovers two shapes whose byte positions are not already
    // covered by a tree-sitter capture:
    //   * qualified calls (`a::b::name(`) — recovered file-wide, since the `::`
    //     prefix makes a false positive vanishingly unlikely; and
    //   * plain calls (`name(`) — recovered ONLY inside a macro invocation's
    //     token tree, where whole-file scanning would be too imprecise
    //     (it would collide with definitions and ordinary already-captured calls).
    if *language == LanguageId::Rust {
        let captured_call_ranges: Vec<(u32, u32)> = references
            .iter()
            .filter(|r| r.kind == ReferenceKind::Call)
            .map(|r| r.byte_range)
            .collect();

        // Byte ranges of macro invocations, used to scope plain-call recovery.
        let macro_ranges = collect_rust_macro_ranges(root);

        // Scan for `ident(` patterns; classify each as qualified (file-wide) or
        // plain (macro-scoped) below.
        let bytes = source.as_bytes();
        let len = bytes.len();
        let mut i = 0;
        while i < len {
            // Quick check: find `(` which may terminate a qualified call.
            if bytes[i] != b'(' {
                i += 1;
                continue;
            }
            let paren_pos = i;

            // Walk backwards over optional whitespace before `(`.
            let mut j = paren_pos;
            while j > 0 && matches!(bytes[j - 1], b' ' | b'\t') {
                j -= 1;
            }
            let name_end = j;

            // Walk backwards over the trailing identifier (the function name).
            while j > 0 && (bytes[j - 1].is_ascii_alphanumeric() || bytes[j - 1] == b'_') {
                j -= 1;
            }
            let name_start = j;
            if name_start == name_end {
                i += 1;
                continue;
            }

            // Plain (unqualified) call: not preceded by `::`. Recover it ONLY
            // when the call sits inside a macro token tree — elsewhere the main
            // tree-sitter query already captured every real call, and a naked
            // `ident(` file-wide would also match definitions (`fn name(`).
            if j < 2 || bytes[j - 1] != b':' || bytes[j - 2] != b':' {
                let byte_start = name_start as u32;
                let byte_end = name_end as u32;

                // Only inside a macro invocation.
                let in_macro = macro_ranges
                    .iter()
                    .any(|&(ms, me)| ms <= byte_start && byte_end <= me);
                // Skip the macro name itself (`format` in `format!(`): the token
                // immediately before is `!`, and it is already a MacroUse ref.
                let is_macro_name = name_end < bytes.len() && bytes[name_end] == b'!';
                // Skip if already captured by a tree-sitter query match.
                let already = captured_call_ranges.iter().any(|&(cs, ce)| {
                    (cs <= byte_start && byte_end <= ce) || (byte_start <= cs && cs < byte_end)
                });
                // Rough string-literal guard: even count of `"` before the name.
                // ponytail: quote-parity heuristic, not a lexer — precision-favoring
                // (matches the qualified-call fallback above; a name after an odd
                // number of earlier quotes is skipped rather than risk a phantom
                // ref). Upgrade to a real tokenizer only if a macro-heavy fixture
                // shows a real miss. Known limitation logged in the verify-tools harness.
                let outside_string = source[..name_start].matches('"').count().is_multiple_of(2);

                if in_macro && !is_macro_name && !already && outside_string {
                    let name_text = &source[name_start..name_end];
                    if !name_text.is_empty() {
                        let line =
                            bytes[..name_start].iter().filter(|&&b| b == b'\n').count() as u32;
                        references.push(ReferenceRecord {
                            name: name_text.to_string(),
                            qualified_name: None,
                            kind: ReferenceKind::Call,
                            byte_range: (byte_start, byte_end),
                            line_range: (line, line),
                            enclosing_symbol_index: None,
                        });
                    }
                }

                i += 1;
                continue;
            }

            // Walk further back collecting `segment::` prefixes.
            let mut path_start = j - 2;
            loop {
                let seg_end = path_start;
                while path_start > 0
                    && (bytes[path_start - 1].is_ascii_alphanumeric()
                        || bytes[path_start - 1] == b'_')
                {
                    path_start -= 1;
                }
                if path_start == seg_end {
                    // No identifier before `::` — stop.
                    path_start = seg_end;
                    break;
                }
                // Another `::` before this segment?
                if path_start >= 2 && bytes[path_start - 1] == b':' && bytes[path_start - 2] == b':'
                {
                    path_start -= 2;
                } else {
                    break;
                }
            }

            let qualified_text = &source[path_start..name_end];
            let name_text = &source[name_start..name_end];

            // Must have at least one `::` (two segments).
            if !qualified_text.contains("::")
                || name_text.is_empty()
                // Skip if inside a string literal (very rough: odd number of `"` before).
                || !source[..path_start].matches('"').count().is_multiple_of(2)
            {
                i += 1;
                continue;
            }

            let byte_start = name_start as u32;
            let byte_end = name_end as u32;

            // Skip if already captured by a tree-sitter query match.
            let already = captured_call_ranges.iter().any(|&(cs, ce)| {
                (cs <= byte_start && byte_end <= ce) || (byte_start <= cs && cs < byte_end)
            });

            if !already {
                let line = bytes[..path_start].iter().filter(|&&b| b == b'\n').count() as u32;
                references.push(ReferenceRecord {
                    name: name_text.to_string(),
                    qualified_name: Some(qualified_text.to_string()),
                    kind: ReferenceKind::Call,
                    byte_range: (byte_start, byte_end),
                    line_range: (line, line),
                    enclosing_symbol_index: None,
                });
            }

            i += 1;
        }
    }

    // --- Rust const/static value-position references ---
    //
    // The main query never captures a `const`/`static` used as a bare value
    // (iterated in a `for` loop, passed to `.contains(..)`, handed as a plain
    // argument), so resolve those here against same-file const/static defs.
    // Strict precision gating lives in `extract_rust_value_refs`.
    if *language == LanguageId::Rust {
        let value_refs = extract_rust_value_refs(root, source, &ts_language, &references);
        references.extend(value_refs);
        // Path-qualified value-position uses (`from_fn(handlers::foo)`), which
        // the main query and macro fallback never see. Runs after the const
        // pass so it dedups against every reference captured so far.
        let qualified_value_refs =
            extract_rust_qualified_value_refs(root, source, &ts_language, &references);
        references.extend(qualified_value_refs);
    }

    if *language == LanguageId::Python {
        let value_refs = extract_python_value_refs(root, source, &ts_language, &references);
        references.extend(value_refs);
        let string_refs = extract_python_string_type_refs(root, source, &ts_language, &references);
        references.extend(string_refs);
    }

    (references, alias_map)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use tree_sitter::Parser;

    fn parse_and_extract(
        source: &str,
        language: LanguageId,
    ) -> (Vec<ReferenceRecord>, HashMap<String, String>) {
        parse_and_extract_flavored(source, language, false)
    }

    /// Like [`parse_and_extract`] but selects the TSX grammar when `is_tsx`.
    fn parse_and_extract_flavored(
        source: &str,
        language: LanguageId,
        is_tsx: bool,
    ) -> (Vec<ReferenceRecord>, HashMap<String, String>) {
        let mut parser = Parser::new();
        let ts_language: Language = match &language {
            LanguageId::Rust => tree_sitter_rust::LANGUAGE.into(),
            LanguageId::Python => tree_sitter_python::LANGUAGE.into(),
            LanguageId::JavaScript => tree_sitter_javascript::LANGUAGE.into(),
            LanguageId::TypeScript if is_tsx => tree_sitter_typescript::LANGUAGE_TSX.into(),
            LanguageId::TypeScript => tree_sitter_typescript::LANGUAGE_TYPESCRIPT.into(),
            LanguageId::Go => tree_sitter_go::LANGUAGE.into(),
            LanguageId::Java => tree_sitter_java::LANGUAGE.into(),
            LanguageId::C => tree_sitter_c::LANGUAGE.into(),
            LanguageId::Cpp => tree_sitter_cpp::LANGUAGE.into(),
            LanguageId::CSharp => tree_sitter_c_sharp::LANGUAGE.into(),
            LanguageId::Ruby => tree_sitter_ruby::LANGUAGE.into(),
            LanguageId::Kotlin => tree_sitter_kotlin_sg::LANGUAGE.into(),
            LanguageId::Dart => tree_sitter_dart::LANGUAGE.into(),
            LanguageId::Elixir => tree_sitter_elixir::LANGUAGE.into(),
            LanguageId::Php => tree_sitter_php::LANGUAGE_PHP.into(),
            LanguageId::Swift => tree_sitter_swift::LANGUAGE.into(),
            LanguageId::Perl => tree_sitter_perl::LANGUAGE.into(),
            LanguageId::Json
            | LanguageId::Toml
            | LanguageId::Yaml
            | LanguageId::Markdown
            | LanguageId::Env
            | LanguageId::Html
            | LanguageId::Css
            | LanguageId::Scss => {
                unreachable!("config/frontend languages don't use tree-sitter xref extraction")
            }
        };
        parser.set_language(&ts_language).expect("set language");
        let tree = parser.parse(source, None).expect("parse");
        let root = tree.root_node();
        extract_references(&root, source, &language, is_tsx)
    }

    fn find_ref<'a>(refs: &'a [ReferenceRecord], name: &str) -> Option<&'a ReferenceRecord> {
        refs.iter().find(|r| r.name == name)
    }

    fn has_ref(refs: &[ReferenceRecord], name: &str, kind: ReferenceKind) -> bool {
        refs.iter().any(|r| r.name == name && r.kind == kind)
    }

    // --- Rust ---

    #[test]
    fn test_rust_call_expression_simple() {
        let (refs, _) = parse_and_extract("fn main() { foo(); }", LanguageId::Rust);
        assert!(
            has_ref(&refs, "foo", ReferenceKind::Call),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_rust_scoped_identifier_qualified_call() {
        let (refs, _) = parse_and_extract("fn main() { Vec::new(); }", LanguageId::Rust);
        let r = find_ref(&refs, "new");
        assert!(r.is_some(), "should find 'new' call, refs: {:?}", refs);
        let r = r.unwrap();
        assert_eq!(r.kind, ReferenceKind::Call);
        assert!(r.qualified_name.is_some(), "should have qualified_name");
        let qname = r.qualified_name.as_deref().unwrap();
        assert!(
            qname.contains("Vec"),
            "qualified_name should contain Vec, got: {qname}"
        );
    }

    #[test]
    fn test_rust_method_call() {
        let (refs, _) = parse_and_extract("fn main() { self.items.push(x); }", LanguageId::Rust);
        assert!(
            has_ref(&refs, "push", ReferenceKind::Call),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_rust_macro_invocation() {
        let (refs, _) = parse_and_extract(r#"fn main() { println!("hi"); }"#, LanguageId::Rust);
        assert!(
            has_ref(&refs, "println", ReferenceKind::MacroUse),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_rust_qualified_call_inside_macro_body() {
        // tree-sitter parses macro bodies as token_tree (raw tokens), so the
        // call_expression query never fires.  The text-based fallback should
        // still capture the qualified call.
        let src = r#"fn project_key() -> String {
    format!("project-{}", crate::hash::digest_hex(b"abc"))
}"#;
        let (refs, _) = parse_and_extract(src, LanguageId::Rust);
        let call = refs
            .iter()
            .find(|r| r.name == "digest_hex" && r.kind == ReferenceKind::Call);
        assert!(
            call.is_some(),
            "should find digest_hex call inside macro body, refs: {:?}",
            refs
        );
        let call = call.unwrap();
        assert_eq!(
            call.qualified_name.as_deref(),
            Some("crate::hash::digest_hex"),
            "should have full qualified name"
        );
    }

    #[test]
    fn test_rust_qualified_call_outside_macro_not_duplicated() {
        // A normal qualified call should be captured by tree-sitter AND the
        // fallback should not add a duplicate.
        let src = "fn main() { crate::hash::digest_hex(b\"abc\"); }";
        let (refs, _) = parse_and_extract(src, LanguageId::Rust);
        let calls: Vec<_> = refs
            .iter()
            .filter(|r| r.name == "digest_hex" && r.kind == ReferenceKind::Call)
            .collect();
        assert_eq!(
            calls.len(),
            1,
            "should have exactly one Call ref (no duplicates), got: {:?}",
            calls
        );
    }

    #[test]
    fn test_rust_plain_call_inside_macro_body() {
        // tree-sitter parses macro bodies as token_tree (raw tokens), so a PLAIN
        // (unqualified) call inside a macro like `format!("{}", tally(xs))` never
        // fires the call_expression query.  The macro-body fallback must recover it
        // even without a `::` qualifier, or renames leave dangling call sites.
        let src = r#"fn describe(xs: &[i64]) -> String {
        format!("total={}", tally(xs))
    }"#;
        let (refs, _) = parse_and_extract(src, LanguageId::Rust);
        let call = refs
            .iter()
            .find(|r| r.name == "tally" && r.kind == ReferenceKind::Call);
        assert!(
            call.is_some(),
            "should find plain `tally` call inside macro body, refs: {:?}",
            refs
        );
        // A plain (unqualified) call carries no qualified name.
        assert_eq!(call.unwrap().qualified_name, None);
    }

    #[test]
    fn test_rust_plain_call_inside_macro_not_duplicated() {
        // A normal call captured by tree-sitter must NOT be duplicated by the
        // macro-body plain-call fallback.
        let src = "fn main() { tally(); }";
        let (refs, _) = parse_and_extract(src, LanguageId::Rust);
        let calls: Vec<_> = refs
            .iter()
            .filter(|r| r.name == "tally" && r.kind == ReferenceKind::Call)
            .collect();
        assert_eq!(
            calls.len(),
            1,
            "should have exactly one Call ref (no duplicates), got: {:?}",
            calls
        );
    }

    #[test]
    fn test_rust_use_declaration_import() {
        let (refs, _) = parse_and_extract("use std::collections::HashMap;", LanguageId::Rust);
        // The import captures scoped_identifier for the whole use path
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "should have at least one Import ref, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_rust_grouped_use_declaration_expands_imports() {
        let (refs, _) = parse_and_extract("use crate::{daemon, other};", LanguageId::Rust);
        assert!(
            refs.iter().any(|r| {
                r.kind == ReferenceKind::Import
                    && r.name == "daemon"
                    && r.qualified_name.as_deref() == Some("crate::daemon")
            }),
            "grouped Rust imports should include crate::daemon, refs: {:?}",
            refs
        );
        assert!(
            refs.iter().any(|r| {
                r.kind == ReferenceKind::Import
                    && r.name == "other"
                    && r.qualified_name.as_deref() == Some("crate::other")
            }),
            "grouped Rust imports should include crate::other, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_rust_use_as_clause_populates_alias_map() {
        let source = "use std::collections::HashMap as Map;";
        let (_, alias_map) = parse_and_extract(source, LanguageId::Rust);
        assert!(
            alias_map.contains_key("Map"),
            "alias_map should contain 'Map', got: {:?}",
            alias_map
        );
        assert_eq!(alias_map.get("Map").map(|s| s.as_str()), Some("HashMap"));
    }

    #[test]
    fn test_rust_type_identifier() {
        let (refs, _) = parse_and_extract("fn foo(param: MyStruct) {}", LanguageId::Rust);
        assert!(
            has_ref(&refs, "MyStruct", ReferenceKind::TypeUsage),
            "refs: {:?}",
            refs
        );
    }

    /// D13 recall: a qualified-call construction site `MinimalFilter::new()` is
    /// keyed in `reverse_index` under the leaf `new`, but retains the full
    /// `qualified_name` (`MinimalFilter::new`). This asserts the extraction shape
    /// the `find_references` head-match branch relies on. The struct-literal
    /// `MinimalFilter { .. }` is ALREADY captured here as a `TypeUsage` keyed
    /// under the head via the unscoped `(type_identifier)` rule -- so NO extra
    /// struct_expression capture is needed (it would only duplicate).
    #[test]
    fn test_rust_qualified_call_retains_head_and_struct_literal_keyed_under_head() {
        let src = r#"
struct MinimalFilter { a: u8 }
fn use_it(p: MinimalFilter) {
    let a: MinimalFilter = MinimalFilter::new();
    let b = MinimalFilter { a: 1 };
    let _ = (a, b, p);
}
"#;
        let (refs, _) = parse_and_extract(src, LanguageId::Rust);

        // The constructor call is keyed under the leaf, with the head retained.
        let ctor = refs
            .iter()
            .find(|r| r.name == "new" && r.kind == ReferenceKind::Call)
            .expect("MinimalFilter::new() should be captured as a Call");
        assert_eq!(
            ctor.qualified_name.as_deref(),
            Some("MinimalFilter::new"),
            "constructor call must retain the type head in qualified_name"
        );

        // The struct literal IS already a head-keyed TypeUsage (no extra capture).
        let literal_count = refs
            .iter()
            .filter(|r| {
                r.name == "MinimalFilter"
                    && r.kind == ReferenceKind::TypeUsage
                    && r.line_range.0 == 4
            })
            .count();
        assert_eq!(
            literal_count, 1,
            "struct literal MinimalFilter {{..}} on line 4 must be captured exactly once under the head, got refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_rust_impl_trait_for_struct() {
        let source = r#"
            struct MyStruct;
            trait Display {}
            impl Display for MyStruct {}
        "#;
        let (refs, _) = parse_and_extract(source, LanguageId::Rust);
        let impl_refs: Vec<_> = refs
            .iter()
            .filter(|r| r.kind == ReferenceKind::Implements)
            .collect();
        assert_eq!(
            impl_refs.len(),
            1,
            "should find 1 implements ref, got: {:?}",
            impl_refs
        );
        assert_eq!(impl_refs[0].name, "Display");
        assert_eq!(impl_refs[0].qualified_name.as_deref(), Some("MyStruct"));
    }

    #[test]
    fn test_rust_impl_scoped_trait_for_struct() {
        let source = r#"
            struct Foo;
            impl std::fmt::Display for Foo {
                fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { Ok(()) }
            }
        "#;
        let (refs, _) = parse_and_extract(source, LanguageId::Rust);
        let impl_refs: Vec<_> = refs
            .iter()
            .filter(|r| r.kind == ReferenceKind::Implements)
            .collect();
        assert_eq!(
            impl_refs.len(),
            1,
            "should find 1 implements ref, got: {:?}",
            impl_refs
        );
        assert!(
            impl_refs[0].name.contains("Display"),
            "trait name should contain Display, got: {}",
            impl_refs[0].name
        );
        assert_eq!(impl_refs[0].qualified_name.as_deref(), Some("Foo"));
    }

    // --- Rust const/static value-position references (issue #257) ---

    #[test]
    fn test_rust_const_used_in_for_loop_and_contains() {
        // SYMFORGE_TOOL_NAMES-style: a const iterated in `for ... in CONST` and
        // queried via `CONST.contains(..)` must both surface as ValueUse refs.
        let source = r#"
const TOOL_NAMES: &[&str] = &["a", "b"];

fn iterate() {
    for name in TOOL_NAMES {
        let _ = name;
    }
}

fn membership(candidate: &str) -> bool {
    TOOL_NAMES.contains(&candidate)
}
"#;
        let (refs, _) = parse_and_extract(source, LanguageId::Rust);
        let value_refs: Vec<_> = refs
            .iter()
            .filter(|r| r.name == "TOOL_NAMES" && r.kind == ReferenceKind::ValueUse)
            .collect();
        assert_eq!(
            value_refs.len(),
            2,
            "for-loop use and .contains() use should both surface as ValueUse, refs: {:?}",
            refs
        );
        // The definition site itself must NOT be reported as a reference.
        assert!(
            !refs
                .iter()
                .any(|r| r.name == "TOOL_NAMES" && r.line_range.0 == 1),
            "the const definition site must not be a reference, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_rust_static_used_as_bare_value_arg() {
        // A `static` handed to a function as a bare value argument must surface.
        let source = r#"
static MAX_RETRIES: u32 = 5;

fn configure(limit: u32) {
    let _ = limit;
}

fn run() {
    configure(MAX_RETRIES);
}
"#;
        let (refs, _) = parse_and_extract(source, LanguageId::Rust);
        assert!(
            has_ref(&refs, "MAX_RETRIES", ReferenceKind::ValueUse),
            "bare value-arg use of a static should surface as ValueUse, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_rust_value_ref_does_not_report_local_var_named_like_const() {
        // False-positive guard: a lowercase local `let foo`/parameter `foo`
        // must NOT be reported as a reference to an unrelated `const FOO`.
        // Case discipline + exact same-file def-name matching makes this safe.
        let source = r#"
const FOO: u32 = 1;

fn unrelated(foo: u32) -> u32 {
    let bar = foo + 1;
    bar
}
"#;
        let (refs, _) = parse_and_extract(source, LanguageId::Rust);
        // The lowercase `foo` (param + uses) must produce zero ValueUse refs.
        assert!(
            !refs
                .iter()
                .any(|r| r.name == "foo" && r.kind == ReferenceKind::ValueUse),
            "lowercase local `foo` must not be a reference to const FOO, refs: {:?}",
            refs
        );
        // And FOO is never used, so it should produce no ValueUse refs at all.
        assert!(
            !refs
                .iter()
                .any(|r| r.name == "FOO" && r.kind == ReferenceKind::ValueUse),
            "unused const FOO should have no value references, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_rust_value_ref_requires_same_file_definition() {
        // Precision guard: a SCREAMING_SNAKE_CASE identifier that is NOT defined
        // as a const/static in this file must not be reported (no whole-repo
        // symbol table at extraction time — we resolve same-file only).
        let source = r#"
fn run() {
    let _ = EXTERNAL_CONST;
}
"#;
        let (refs, _) = parse_and_extract(source, LanguageId::Rust);
        assert!(
            !refs.iter().any(|r| r.kind == ReferenceKind::ValueUse),
            "an identifier with no same-file const/static def must not surface as ValueUse, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_rust_value_ref_not_duplicated_with_call_capture() {
        // Dedup guard: if a const-named identifier is *also* captured by the
        // main query (here a function call shares the byte range of nothing,
        // but a same-named call must not collide), we must not double-count.
        // Use a const whose name is also referenced once as a bare value — it
        // should appear exactly once as ValueUse, never as Call.
        let source = r#"
const LIMIT: u32 = 10;

fn check(v: u32) -> bool {
    v < LIMIT
}
"#;
        let (refs, _) = parse_and_extract(source, LanguageId::Rust);
        let limit_refs: Vec<_> = refs.iter().filter(|r| r.name == "LIMIT").collect();
        assert_eq!(
            limit_refs.len(),
            1,
            "LIMIT should be referenced exactly once, refs: {:?}",
            refs
        );
        assert_eq!(
            limit_refs[0].kind,
            ReferenceKind::ValueUse,
            "the LIMIT value use should be kind ValueUse, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_rust_existing_call_and_type_refs_unchanged_with_value_pass() {
        // Regression: the value pass must not perturb call/type/import capture.
        let source = r#"
use std::collections::HashMap;

const SIZE: usize = 4;

fn build(map: HashMap<String, usize>) {
    let _ = map;
    helper(SIZE);
}

fn helper(n: usize) {
    let _ = n;
}
"#;
        let (refs, _) = parse_and_extract(source, LanguageId::Rust);
        assert!(
            has_ref(&refs, "helper", ReferenceKind::Call),
            "call ref to helper must remain, refs: {:?}",
            refs
        );
        assert!(
            has_ref(&refs, "HashMap", ReferenceKind::TypeUsage),
            "type ref to HashMap must remain, refs: {:?}",
            refs
        );
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "import ref must remain, refs: {:?}",
            refs
        );
        assert!(
            has_ref(&refs, "SIZE", ReferenceKind::ValueUse),
            "const SIZE used as a bare arg should surface as ValueUse, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_rust_qualified_value_arg_surfaces_as_value_use() {
        // A path-qualified function passed as an argument (not called) must
        // surface as a ValueUse named by its leaf, with the full path retained.
        let source = r#"
fn wire() {
    let _ = from_fn(handlers::foo);
}
"#;
        let (refs, _) = parse_and_extract(source, LanguageId::Rust);
        let value_ref = refs
            .iter()
            .find(|r| r.name == "foo" && r.kind == ReferenceKind::ValueUse)
            .unwrap_or_else(|| panic!("expected ValueUse for `foo`, refs: {refs:?}"));
        assert_eq!(
            value_ref.qualified_name.as_deref(),
            Some("handlers::foo"),
            "qualified_name should retain the full path, refs: {refs:?}"
        );
    }

    #[test]
    fn test_rust_qualified_call_not_duplicated_by_value_pass() {
        // A qualified CALL must remain exactly one reference: the value pass
        // must not add a second ValueUse for the same path.
        let source = r#"
fn run() {
    handlers::foo();
}
"#;
        let (refs, _) = parse_and_extract(source, LanguageId::Rust);
        let foo_refs: Vec<_> = refs.iter().filter(|r| r.name == "foo").collect();
        assert_eq!(
            foo_refs.len(),
            1,
            "qualified call `handlers::foo()` should yield exactly one ref, refs: {refs:?}"
        );
        assert_eq!(
            foo_refs[0].kind,
            ReferenceKind::Call,
            "the single ref should be a Call, not a ValueUse, refs: {refs:?}"
        );
    }

    #[test]
    fn test_rust_use_declaration_produces_no_qualified_value_use() {
        // `use handlers::foo;` must not emit a ValueUse from the new rule;
        // import handling is unchanged (it stays an Import ref).
        let source = r#"
use handlers::foo;

fn run() {
    let _ = foo;
}
"#;
        let (refs, _) = parse_and_extract(source, LanguageId::Rust);
        assert!(
            !refs
                .iter()
                .any(|r| r.qualified_name.as_deref() == Some("handlers::foo")
                    && r.kind == ReferenceKind::ValueUse),
            "a `use` path must not surface as a qualified ValueUse, refs: {refs:?}"
        );
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "the use declaration should still produce an Import ref, refs: {refs:?}"
        );
    }

    #[test]
    fn test_python_class_inheritance() {
        let source = "class Dog(Animal):\n    pass";
        let (refs, _) = parse_and_extract(source, LanguageId::Python);
        let impl_refs: Vec<_> = refs
            .iter()
            .filter(|r| r.kind == ReferenceKind::Implements)
            .collect();
        assert_eq!(
            impl_refs.len(),
            1,
            "should find 1 implements ref, got: {:?}",
            impl_refs
        );
        assert_eq!(impl_refs[0].name, "Animal");
        assert_eq!(impl_refs[0].qualified_name.as_deref(), Some("Dog"));
    }

    #[test]
    fn test_ts_class_implements() {
        let source = "class Foo implements Bar {}";
        let (refs, _) = parse_and_extract(source, LanguageId::TypeScript);
        let impl_refs: Vec<_> = refs
            .iter()
            .filter(|r| r.kind == ReferenceKind::Implements)
            .collect();
        assert!(
            impl_refs
                .iter()
                .any(|r| r.name == "Bar" && r.qualified_name.as_deref() == Some("Foo")),
            "should find Foo implements Bar, got: {:?}",
            impl_refs
        );
    }

    #[test]
    fn test_csharp_class_base_list() {
        let source = "class MyService : IService {}";
        let (refs, _) = parse_and_extract(source, LanguageId::CSharp);
        let impl_refs: Vec<_> = refs
            .iter()
            .filter(|r| r.kind == ReferenceKind::Implements)
            .collect();
        assert!(
            impl_refs
                .iter()
                .any(|r| r.name == "IService" && r.qualified_name.as_deref() == Some("MyService")),
            "should find MyService : IService, got: {:?}",
            impl_refs
        );
    }

    #[test]
    fn test_java_class_implements() {
        let source = "class Foo implements Runnable {}";
        let (refs, _) = parse_and_extract(source, LanguageId::Java);
        let impl_refs: Vec<_> = refs
            .iter()
            .filter(|r| r.kind == ReferenceKind::Implements)
            .collect();
        assert!(
            impl_refs
                .iter()
                .any(|r| r.name == "Runnable" && r.qualified_name.as_deref() == Some("Foo")),
            "should find Foo implements Runnable, got: {:?}",
            impl_refs
        );
    }

    // --- Python ---

    #[test]
    fn test_python_function_call() {
        let (refs, _) = parse_and_extract("process(data)", LanguageId::Python);
        assert!(
            has_ref(&refs, "process", ReferenceKind::Call),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_python_import_statement() {
        let (refs, _) = parse_and_extract("import os", LanguageId::Python);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "should have Import ref, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_python_from_import() {
        let (refs, _) = parse_and_extract("from os import path", LanguageId::Python);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "should have Import ref, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_python_type_annotation() {
        let (refs, _) = parse_and_extract("def foo(x: MyType): pass", LanguageId::Python);
        assert!(
            has_ref(&refs, "MyType", ReferenceKind::TypeUsage),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_python_models_model_class_inheritance() {
        let (refs, _) = parse_and_extract(
            "class Permission(models.Model):\n    pass",
            LanguageId::Python,
        );
        let model_ref = refs.iter().find(|r| r.name == "Model");
        assert!(
            model_ref.is_some(),
            "models.Model base should surface Model ref, refs: {:?}",
            refs
        );
        assert_eq!(
            model_ref.unwrap().qualified_name.as_deref(),
            Some("models.Model")
        );
        assert_eq!(model_ref.unwrap().kind, ReferenceKind::Implements);
    }

    #[test]
    fn test_python_subscript_type_annotation() {
        let (refs, _) = parse_and_extract(
            "def f(qs: QuerySet[Model]) -> None:\n    pass",
            LanguageId::Python,
        );
        assert!(
            has_ref(&refs, "QuerySet", ReferenceKind::TypeUsage),
            "refs: {:?}",
            refs
        );
        assert!(
            has_ref(&refs, "Model", ReferenceKind::TypeUsage),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_python_value_type_in_call_args() {
        let (refs, _) = parse_and_extract(
            "def g():\n    return isinstance(x, Model)",
            LanguageId::Python,
        );
        assert!(
            has_ref(&refs, "Model", ReferenceKind::ValueUse),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_python_foreign_key_model_arg() {
        let (refs, _) = parse_and_extract(
            "field = models.ForeignKey(Model, on_delete=CASCADE)",
            LanguageId::Python,
        );
        assert!(
            has_ref(&refs, "Model", ReferenceKind::ValueUse),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_python_model_attribute_chain() {
        let (refs, _) = parse_and_extract("__hash__ = models.Model.__hash__", LanguageId::Python);
        assert!(
            has_ref(&refs, "Model", ReferenceKind::TypeUsage),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_python_string_model_migration_arg() {
        let (refs, _) = parse_and_extract(
            "migrations.RenameField(\"Model\", \"old\", \"new\")",
            LanguageId::Python,
        );
        assert!(
            has_ref(&refs, "Model", ReferenceKind::ValueUse),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_python_mock_patch_dotted_model_string() {
        let (refs, _) =
            parse_and_extract("mock.patch(\"django.db.models.Model\")", LanguageId::Python);
        let model_ref = refs.iter().find(|r| r.name == "Model");
        assert!(
            model_ref.is_some(),
            "mock.patch dotted path should surface Model, refs: {:?}",
            refs
        );
        assert_eq!(
            model_ref.unwrap().qualified_name.as_deref(),
            Some("django.db.models.Model")
        );
    }

    // --- JavaScript ---

    #[test]
    fn test_js_call_expression() {
        let (refs, _) = parse_and_extract("fetch(url);", LanguageId::JavaScript);
        assert!(
            has_ref(&refs, "fetch", ReferenceKind::Call),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_js_import_statement() {
        let (refs, _) = parse_and_extract("import React from 'react';", LanguageId::JavaScript);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "should have Import ref, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_jsx_import_extracted_under_plain_js_grammar() {
        // Regression: `.jsx` resolves to LanguageId::JavaScript and is NOT a TSX
        // path, so it runs through the plain (non-flavored) JavaScript grammar.
        // tree-sitter-javascript 0.25 parses JSX natively — unlike `.ts`, the JSX
        // here is NOT a partial parse — so the import reference for the component
        // rendered in the fragment must still be captured.
        let source = "import { Row } from './Row';\n\
export const Table = ({ rows }) => (\n\
  <>{rows.map((r) => <Row key={r.id} value={r.value} />)}</>\n\
);\n";
        let (refs, _) = parse_and_extract(source, LanguageId::JavaScript);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "JSX under the plain JavaScript grammar must still capture the import; refs: {:?}",
            refs
        );
    }

    // --- TypeScript ---

    #[test]
    fn test_ts_type_references() {
        let source = "interface Foo { bar: MyInterface; }";
        let (refs, _) = parse_and_extract(source, LanguageId::TypeScript);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::TypeUsage),
            "should have TypeUsage ref, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_tsx_references_extracted_under_tsx_grammar() {
        // JSX only parses under the TSX grammar. With the plain TypeScript
        // grammar this source is a partial parse and the import reference is
        // lost; the TSX-flavored extraction recovers it.
        let source = "import { App } from './App';\nexport const root = () => <App />;\n";
        let (refs, _) = parse_and_extract_flavored(source, LanguageId::TypeScript, true);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "TSX import must be captured under the TSX grammar; refs: {:?}",
            refs
        );
    }

    // --- Go ---

    #[test]
    fn test_go_call_expression() {
        let source = "package main\nimport \"fmt\"\nfunc main() { fmt.Println(\"hi\") }";
        let (refs, _) = parse_and_extract(source, LanguageId::Go);
        assert!(
            has_ref(&refs, "Println", ReferenceKind::Call),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_go_import() {
        let source = "package main\nimport \"fmt\"";
        let (refs, _) = parse_and_extract(source, LanguageId::Go);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "should have Import ref, refs: {:?}",
            refs
        );
    }

    // --- Java ---

    #[test]
    fn test_java_method_invocation() {
        let source = "class A { void f() { System.out.println(\"hi\"); } }";
        let (refs, _) = parse_and_extract(source, LanguageId::Java);
        assert!(
            has_ref(&refs, "println", ReferenceKind::Call),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_java_import() {
        let source = "import java.util.ArrayList;";
        let (refs, _) = parse_and_extract(source, LanguageId::Java);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "should have Import ref, refs: {:?}",
            refs
        );
    }

    // --- C ---

    #[test]
    fn test_c_call_ref() {
        let source = "void foo() { bar(); }";
        let (refs, _) = parse_and_extract(source, LanguageId::C);
        assert!(
            has_ref(&refs, "bar", ReferenceKind::Call),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_c_include_ref() {
        let source = "#include <stdio.h>\nvoid foo() {}";
        let (refs, _) = parse_and_extract(source, LanguageId::C);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "should have Import ref for #include, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_c_type_ref() {
        let source = "void foo(MyStruct *s) {}";
        let (refs, _) = parse_and_extract(source, LanguageId::C);
        assert!(
            has_ref(&refs, "MyStruct", ReferenceKind::TypeUsage),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_c_field_method_call_ref() {
        let source = "void foo(MyObj *obj) { obj->method(); }";
        let (refs, _) = parse_and_extract(source, LanguageId::C);
        assert!(
            refs.iter()
                .any(|r| r.kind == ReferenceKind::Call && r.name == "method"),
            "should have method call ref, refs: {:?}",
            refs
        );
    }

    // --- C++ ---

    #[test]
    fn test_cpp_method_call_ref() {
        let source = "void foo(Foo *f) { f->bar(); }";
        let (refs, _) = parse_and_extract(source, LanguageId::Cpp);
        assert!(
            refs.iter()
                .any(|r| r.kind == ReferenceKind::Call && r.name == "bar"),
            "should have method call ref, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_cpp_qualified_ref() {
        let source = "void foo() { std::sort(v.begin(), v.end()); }";
        let (refs, _) = parse_and_extract(source, LanguageId::Cpp);
        // qualified_identifier captures: "sort" from std::sort
        assert!(
            refs.iter()
                .any(|r| r.kind == ReferenceKind::Call && r.name == "sort"),
            "should have qualified call ref for sort, refs: {:?}",
            refs
        );
    }

    /// D13: a C++ qualified call `Foo::create()` must retain the head (`Foo`) in
    /// `qualified_name` so the find_references head-match branch can recall it under
    /// the type. Before the `@ref.qualified_call` envelope was added to the C++
    /// query, this carried `qualified_name=None` and the static-call/construction
    /// site was invisible to find_references("Foo").
    #[test]
    fn test_cpp_qualified_call_retains_head() {
        let source = "void f() { Foo::create(); }";
        let (refs, _) = parse_and_extract(source, LanguageId::Cpp);
        let call = refs
            .iter()
            .find(|r| r.name == "create" && r.kind == ReferenceKind::Call)
            .expect("Foo::create() should be captured as a Call, refs: {refs:?}");
        assert_eq!(
            call.qualified_name.as_deref(),
            Some("Foo::create"),
            "C++ qualified call must retain the type/namespace head in qualified_name"
        );
    }

    #[test]
    fn test_cpp_template_type_ref() {
        let source = "void foo(std::vector<MyType> v) {}";
        let (refs, _) = parse_and_extract(source, LanguageId::Cpp);
        assert!(
            has_ref(&refs, "MyType", ReferenceKind::TypeUsage),
            "refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_cpp_using_declaration_import() {
        let source = "using std::string;";
        let (refs, _) = parse_and_extract(source, LanguageId::Cpp);
        // using_declaration with @import.original does NOT produce a separate ref.import
        // (there's no @import.alias to pair with), so the qualified_identifier is
        // processed as import.original but the alias pair is incomplete, so it's skipped.
        // The qualified_identifier capture also matches @ref.call via qualified_identifier pattern.
        // Just verify no panic and query parses correctly.
        let _ = refs; // query compiled and ran without panic
    }

    #[test]
    fn test_cpp_include_ref() {
        let source = "#include <vector>\nvoid foo() {}";
        let (refs, _) = parse_and_extract(source, LanguageId::Cpp);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "should have Import ref for #include, refs: {:?}",
            refs
        );
    }

    // --- Cross-language coverage ---

    #[test]
    fn test_all_languages_produce_at_least_one_ref_from_nontrivial_source() {
        let cases: &[(&str, LanguageId)] = &[
            ("fn main() { println!(\"hi\"); foo(); }", LanguageId::Rust),
            (
                "import os\ndef main():\n    os.path.join('a', 'b')",
                LanguageId::Python,
            ),
            (
                "import React from 'react';\nfetch('/api');",
                LanguageId::JavaScript,
            ),
            (
                "import { Component } from 'react';\nconst x: MyType = null;",
                LanguageId::TypeScript,
            ),
            (
                "package main\nimport \"fmt\"\nfunc main() { fmt.Println(\"hi\") }",
                LanguageId::Go,
            ),
            (
                "import java.util.ArrayList;\nclass A { void f() { new ArrayList(); } }",
                LanguageId::Java,
            ),
            ("#include <stdio.h>\nvoid foo() { bar(); }", LanguageId::C),
            (
                "#include <vector>\nvoid foo() { std::sort(v.begin(), v.end()); }",
                LanguageId::Cpp,
            ),
            // New languages (Phase 07-04)
            (
                "using System;\npublic class App { void Run() { Console.WriteLine(\"hi\"); } }",
                LanguageId::CSharp,
            ),
            (
                "require 'json'\nclass App\n  def run\n    puts 'hi'\n  end\nend",
                LanguageId::Ruby,
            ),
            (
                "import kotlin.io.*\nfun main() { println(\"hi\") }",
                LanguageId::Kotlin,
            ),
            (
                "import 'dart:io';\nvoid main() { print('hello'); }",
                LanguageId::Dart,
            ),
            (
                "defmodule App do\n  alias MyLib.Helper\n  def run, do: :ok\nend",
                LanguageId::Elixir,
            ),
        ];

        for (source, lang) in cases {
            let (refs, _) = parse_and_extract(source, lang.clone());
            assert!(
                !refs.is_empty(),
                "language {:?} should produce refs from non-trivial source, got none",
                lang
            );
        }
    }

    #[test]
    fn test_empty_source_produces_empty_refs_all_languages() {
        let languages = [
            LanguageId::Rust,
            LanguageId::Python,
            LanguageId::JavaScript,
            LanguageId::TypeScript,
            LanguageId::Go,
            LanguageId::Java,
            LanguageId::C,
            LanguageId::Cpp,
            LanguageId::CSharp,
            LanguageId::Ruby,
            LanguageId::Kotlin,
            LanguageId::Dart,
            LanguageId::Elixir,
        ];
        for lang in languages {
            let (refs, alias_map) = parse_and_extract("", lang.clone());
            assert!(
                refs.is_empty(),
                "language {:?} should produce no refs from empty source",
                lang
            );
            assert!(
                alias_map.is_empty(),
                "language {:?} should produce no aliases from empty source",
                lang
            );
        }
    }

    #[test]
    fn test_query_compilation_cached_onclock() {
        // Call extract_references twice for Rust — both calls should return consistent results
        // The query is compiled once (OnceLock) and reused.
        let source = "fn main() { foo(); }";
        let (refs1, _) = parse_and_extract(source, LanguageId::Rust);
        let (refs2, _) = parse_and_extract(source, LanguageId::Rust);
        assert_eq!(
            refs1.len(),
            refs2.len(),
            "same source should produce same number of refs regardless of cache state"
        );
    }

    // --- C# ---

    #[test]
    fn test_csharp_call_ref() {
        let source = "public class App { void Run() { Console.WriteLine(\"hi\"); } }";
        let (refs, _) = parse_and_extract(source, LanguageId::CSharp);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Call),
            "should have at least one Call ref, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_csharp_import_ref() {
        let source = "using System.Collections.Generic;\npublic class App {}";
        let (refs, _) = parse_and_extract(source, LanguageId::CSharp);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "should have Import ref for using directive, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_csharp_import_ref_preserves_qualified_namespace() {
        let source = "using CeRegistry.Core.Services;\npublic class App {}";
        let (refs, _) = parse_and_extract(source, LanguageId::CSharp);
        let import_ref = refs
            .iter()
            .find(|r| r.kind == ReferenceKind::Import)
            .expect("should capture C# using directive");
        assert_eq!(
            import_ref.qualified_name.as_deref(),
            Some("CeRegistry.Core.Services")
        );
    }

    #[test]
    fn test_import_ref_reduces_dotted_name_to_final_segment() {
        // A dotted import reduces its simple `name` to the final segment so
        // name-based find_references matches it, while `qualified_name` retains the
        // full dotted path. Previously a dead `.or_else(split('.'))` branch left the
        // full dotted string as the simple name.
        let source = "using CeRegistry.Core.Services;\npublic class App {}";
        let (refs, _) = parse_and_extract(source, LanguageId::CSharp);
        let import_ref = refs
            .iter()
            .find(|r| r.kind == ReferenceKind::Import)
            .expect("should capture C# using directive");
        assert_eq!(import_ref.name, "Services");
        assert_eq!(
            import_ref.qualified_name.as_deref(),
            Some("CeRegistry.Core.Services")
        );
    }

    #[test]
    fn test_csharp_type_refs_include_constructor_params_and_fields() {
        let source = r#"
using CeRegistry.Core.Services;

public class PacketsController
{
    private readonly IMinioService _minio;

    public PacketsController(IMinioService minioService)
    {
        _minio = minioService;
    }
}
"#;
        let (refs, _) = parse_and_extract(source, LanguageId::CSharp);
        let type_refs: Vec<_> = refs
            .iter()
            .filter(|r| r.kind == ReferenceKind::TypeUsage && r.name == "IMinioService")
            .collect();
        assert_eq!(
            type_refs.len(),
            2,
            "field type and constructor parameter type should both be tracked, refs: {:?}",
            refs
        );
    }

    // --- Ruby ---

    #[test]
    fn test_ruby_call_ref() {
        let source = "def run\n  puts 'hello'\nend";
        let (refs, _) = parse_and_extract(source, LanguageId::Ruby);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Call),
            "should have at least one Call ref, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_ruby_import_ref() {
        let source = "require 'json'\ndef run; end";
        let (refs, _) = parse_and_extract(source, LanguageId::Ruby);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "should have Import ref for require, refs: {:?}",
            refs
        );
    }

    // --- Kotlin ---

    #[test]
    fn test_kotlin_call_ref() {
        let source = "fun main() { println(\"hello\") }";
        let (refs, _) = parse_and_extract(source, LanguageId::Kotlin);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Call),
            "should have at least one Call ref, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_kotlin_import_ref() {
        let source = "import kotlin.io.println\nfun main() {}";
        let (refs, _) = parse_and_extract(source, LanguageId::Kotlin);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "should have Import ref, refs: {:?}",
            refs
        );
    }

    // --- Dart ---

    /// Plain calls and receiver method calls must both produce Call refs
    /// with the callee name, mirroring the nielsenko grammar's
    /// `call_expression(function:)` / `member_expression(property:)` shapes.
    #[test]
    fn test_dart_call_refs() {
        let source = "void main() { print('x'); var s = 'y'.toUpperCase(); }";
        let (refs, _) = parse_and_extract(source, LanguageId::Dart);
        let calls: Vec<&str> = refs
            .iter()
            .filter(|r| r.kind == ReferenceKind::Call)
            .map(|r| r.name.as_str())
            .collect();
        assert!(
            calls.contains(&"print"),
            "plain function call must yield a Call ref named print, refs: {:?}",
            refs
        );
        assert!(
            calls.contains(&"toUpperCase"),
            "receiver method call must yield a Call ref named toUpperCase, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_dart_import_ref() {
        let source = "import 'dart:io';\nvoid main() {}";
        let (refs, _) = parse_and_extract(source, LanguageId::Dart);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "should have Import ref for dart import, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_dart_type_ref() {
        let source = "class Foo { MyType field; }";
        let (refs, _) = parse_and_extract(source, LanguageId::Dart);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::TypeUsage),
            "should have TypeUsage ref, refs: {:?}",
            refs
        );
    }

    // --- Elixir ---

    #[test]
    fn test_elixir_call_ref() {
        let source = "def run do\n  IO.puts(\"hello\")\nend";
        let (refs, _) = parse_and_extract(source, LanguageId::Elixir);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Call),
            "should have at least one Call ref, refs: {:?}",
            refs
        );
    }

    #[test]
    fn test_elixir_import_ref() {
        let source = "defmodule App do\n  alias MyLib.Helper\nend";
        let (refs, _) = parse_and_extract(source, LanguageId::Elixir);
        assert!(
            refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "should have Import ref for alias, refs: {:?}",
            refs
        );
    }

    /// SF-STRESS-021 regression: `raise ArgumentError` parses as the same
    /// `(call target: (identifier) (arguments (alias)))` shape as `alias Foo`,
    /// so the import query matched it and mislabeled `ArgumentError` as an
    /// Import (polluting conventions common-imports and find_references). The
    /// extraction-site directive guard must reject non-directive call targets.
    #[test]
    fn test_elixir_raise_is_not_an_import() {
        let source = "defmodule App do\n  def run do\n    raise ArgumentError\n  end\nend";
        let (refs, _) = parse_and_extract(source, LanguageId::Elixir);
        assert!(
            !refs.iter().any(|r| r.kind == ReferenceKind::Import),
            "`raise ArgumentError` must NOT produce an Import ref, refs: {:?}",
            refs
        );
    }

    /// The directive guard keeps `import`/`use`/`require` (not just `alias`)
    /// classified as imports.
    #[test]
    fn test_elixir_use_and_import_are_imports() {
        let source = "defmodule App do\n  use GenServer\n  import Enum\n  require Logger\nend";
        let (refs, _) = parse_and_extract(source, LanguageId::Elixir);
        let import_count = refs
            .iter()
            .filter(|r| r.kind == ReferenceKind::Import)
            .count();
        assert!(
            import_count >= 3,
            "use/import/require are all directives -> Import refs, refs: {:?}",
            refs
        );
    }

    // --- Perl (ts-parser-perl grammar) ---

    /// Mirrors `test_java_method_invocation`: a method call, a plain call, and
    /// two import forms (`use`/`require`) must all surface as the right refs.
    /// Imports store the LAST path segment as `name` and the full dotted/`::`
    /// path as `qualified_name` (see `push_import_reference`).
    #[test]
    fn test_perl_method_invocation_and_import() {
        let source = "$obj->greet();\nhelper();\nuse Foo::Bar;\nrequire Baz::Qux;";
        let (refs, _) = parse_and_extract(source, LanguageId::Perl);

        assert!(
            has_ref(&refs, "greet", ReferenceKind::Call),
            "should capture $obj->greet() method call, refs: {:?}",
            refs
        );
        assert!(
            has_ref(&refs, "helper", ReferenceKind::Call),
            "should capture helper() function call, refs: {:?}",
            refs
        );

        // `use Foo::Bar;` -> name "Bar", qualified_name "Foo::Bar".
        let use_ref = find_ref(&refs, "Bar")
            .filter(|r| r.kind == ReferenceKind::Import)
            .unwrap_or_else(|| panic!("should capture `use Foo::Bar` import, refs: {refs:?}"));
        assert_eq!(use_ref.qualified_name.as_deref(), Some("Foo::Bar"));

        // `require Baz::Qux;` -> name "Qux", qualified_name "Baz::Qux".
        let require_ref = find_ref(&refs, "Qux")
            .filter(|r| r.kind == ReferenceKind::Import)
            .unwrap_or_else(|| panic!("should capture `require Baz::Qux` import, refs: {refs:?}"));
        assert_eq!(require_ref.qualified_name.as_deref(), Some("Baz::Qux"));
    }

    /// Xref proof-of-value: a method call inside a `class { method ... }` body —
    /// the construct the old ganezdragon grammar ERROR-noded — is now recovered.
    #[test]
    fn test_perl_class_method_call_recovered() {
        let source = "class Point {\n    method render {\n        $self->draw();\n    }\n}";
        let (refs, _) = parse_and_extract(source, LanguageId::Perl);
        assert!(
            has_ref(&refs, "draw", ReferenceKind::Call),
            "should recover $self->draw() inside a class method, refs: {:?}",
            refs
        );
    }

    /// Qualified static call `Foo::bar()` — function node wraps package + bareword.
    #[test]
    fn test_perl_qualified_function_call() {
        let source = "Foo::bar(1, 2);";
        let (refs, _) = parse_and_extract(source, LanguageId::Perl);
        assert!(
            has_ref(&refs, "bar", ReferenceKind::Call),
            "should capture Foo::bar() call leaf, refs: {:?}",
            refs
        );
        let call = refs
            .iter()
            .find(|r| r.kind == ReferenceKind::Call && r.name == "bar")
            .expect("bar call ref");
        assert_eq!(
            call.qualified_name.as_deref(),
            Some("Foo::bar"),
            "qualified static call should retain full path"
        );
    }

    /// `$self->SUPER::method()` — method node carries the full :: path.
    #[test]
    fn test_perl_super_method_call() {
        let source = "$self->SUPER::method();";
        let (refs, _) = parse_and_extract(source, LanguageId::Perl);
        let call = refs
            .iter()
            .find(|r| r.kind == ReferenceKind::Call && r.name == "method")
            .unwrap_or_else(|| panic!("should capture SUPER::method leaf, refs: {refs:?}"));
        assert_eq!(call.qualified_name.as_deref(), Some("SUPER::method"));
    }

    /// `CORE::push()` — same leaf split as qualified static calls.
    #[test]
    fn test_perl_core_function_call() {
        let source = "CORE::push(@a, 1);";
        let (refs, _) = parse_and_extract(source, LanguageId::Perl);
        let call = refs
            .iter()
            .find(|r| r.kind == ReferenceKind::Call && r.name == "push")
            .unwrap_or_else(|| panic!("should capture CORE::push leaf, refs: {refs:?}"));
        assert_eq!(call.qualified_name.as_deref(), Some("CORE::push"));
    }

    /// `use parent qw(Foo)` — pragma is not the inherited module.
    #[test]
    fn test_perl_use_parent_import() {
        let source = "use parent qw(Foo);";
        let (refs, _) = parse_and_extract(source, LanguageId::Perl);
        assert!(
            has_ref(&refs, "Foo", ReferenceKind::Import),
            "should import parent module from qw list, refs: {refs:?}"
        );
        assert!(
            !has_ref(&refs, "parent", ReferenceKind::Import),
            "pragma name should not be the import ref, refs: {refs:?}"
        );
    }

    /// `$coderef->()` — coderef_call_expression invocant.
    #[test]
    fn test_perl_coderef_call() {
        let source = "$coderef->();";
        let (refs, _) = parse_and_extract(source, LanguageId::Perl);
        assert!(
            has_ref(&refs, "coderef", ReferenceKind::Call),
            "should capture coderef invocant as call, refs: {refs:?}"
        );
    }

    /// A deliberately-malformed query must degrade to `None` (logged + cached),
    /// never panic. This is the panic-hardening contract of `compile_xref_query`.
    #[test]
    fn test_compile_xref_query_degrades_on_mismatch() {
        // A fresh, test-local cache so we observe the first-init outcome.
        static BAD_QUERY_CACHE: OnceLock<Option<Query>> = OnceLock::new();
        let lang: Language = tree_sitter_perl::LANGUAGE.into();
        // `(no_such_node_kind_xyz)` is not a node in any grammar -> Query::new errs.
        let result = compile_xref_query(
            &BAD_QUERY_CACHE,
            &lang,
            "(no_such_node_kind_xyz) @ref.call",
            "deliberately-bad",
        );
        assert!(
            result.is_none(),
            "a query against a non-existent node kind must compile to None, not panic"
        );
    }

    /// Quick ref probe for constructs beyond the 22-fixture corpus.
    #[test]
    #[ignore]
    fn probe_deferred_perl_refs() {
        let cases = [
            ("super", "$self->SUPER::method();"),
            ("core", "CORE::push(@a, 1);"),
            ("parent", "use parent qw(Foo);"),
            ("coderef", "$c->();"),
        ];
        for (label, source) in cases {
            let (refs, _) = parse_and_extract(source, LanguageId::Perl);
            println!("{label}: {refs:?}");
        }
    }

    /// Empirical anchor (kept `#[ignore]`): prints the s-expr for the verified
    /// ts-parser-perl node shapes. Run with `--ignored` to re-confirm the node
    /// names this implementation depends on after a grammar bump.
    #[test]
    #[ignore = "diagnostic probe; run with --ignored to re-verify grammar node names"]
    fn probe_perl_grammar_sexp() {
        let samples = [
            "sub greet { 1 }",
            "package MyApp::Module;",
            "class Bar { method m { 1 } }",
            "$obj->method(1, 2);",
            "foo(1, 2);",
            "print foo;",
            "use Foo::Bar;",
            "require Baz::Qux;",
            "Foo::bar(1, 2);",
            "$self->SUPER::method();",
            "CORE::push(@arr, 1);",
            "use parent qw(Foo);",
            "use base qw(Bar);",
            "$coderef->();",
            "sub foo { shift->SUPER::bar(@_); }",
        ];
        let mut parser = Parser::new();
        let lang: Language = tree_sitter_perl::LANGUAGE.into();
        parser.set_language(&lang).expect("set perl language");
        for src in samples {
            let tree = parser.parse(src, None).expect("parse");
            println!("--- {src}\n{}", tree.root_node().to_sexp());
        }
    }
}