perl-lsp 0.3.0

A Perl LSP server built on tree-sitter-perl and tower-lsp
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
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
//! FileAnalysis: single-pass scope graph for Perl source files.
//!
//! Built once per parse/reparse via `builder::build()`. Every LSP query
//! becomes a lookup against these tables instead of a tree walk.
//!
//! Designed to compose into a project index: `HashMap<PathBuf, FileAnalysis>`.

use std::collections::{HashMap, HashSet};
use serde::{Deserialize, Serialize};
use tree_sitter::Point;

use crate::module_index::ModuleIndex;

// ---- Serde proxy for tree_sitter::Point ----

/// Remote-derive proxy for `tree_sitter::Point`, which doesn't implement serde.
/// Fields mirror `Point` exactly — use `#[serde(with = "PointDef")]` on Point fields.
#[derive(Serialize, Deserialize)]
#[serde(remote = "Point")]
pub(crate) struct PointDef {
    pub row: usize,
    pub column: usize,
}

/// Helper module for `Option<Point>` serialization via the remote-derived proxy.
pub(crate) mod point_opt_serde {
    use super::PointDef;
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use tree_sitter::Point;

    pub fn serialize<S: Serializer>(val: &Option<Point>, s: S) -> Result<S::Ok, S::Error> {
        #[derive(Serialize)]
        struct W<'a>(#[serde(with = "PointDef")] &'a Point);
        val.as_ref().map(W).serialize(s)
    }

    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Point>, D::Error> {
        #[derive(Deserialize)]
        struct W(#[serde(with = "PointDef")] Point);
        Option::<W>::deserialize(d).map(|o| o.map(|W(p)| p))
    }
}

// ---- Shared types (formerly in analysis.rs) ----

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Span {
    #[serde(with = "PointDef")]
    pub start: Point,
    #[serde(with = "PointDef")]
    pub end: Point,
}

/// Extract the function/method name from a call expression node.
pub(crate) fn extract_call_name(node: tree_sitter::Node, source: &[u8]) -> Option<String> {
    match node.kind() {
        "method_call_expression" => node
            .child_by_field_name("method")
            .and_then(|n| n.utf8_text(source).ok())
            .map(|s| s.to_string()),
        "function_call_expression" | "ambiguous_function_call_expression" => node
            .child_by_field_name("function")
            .and_then(|n| n.utf8_text(source).ok())
            .map(|s| s.to_string()),
        _ => None,
    }
}

pub(crate) fn node_to_span(node: tree_sitter::Node) -> Span {
    Span {
        start: node.start_position(),
        end: node.end_position(),
    }
}


#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FoldRange {
    pub start_line: usize,
    pub end_line: usize,
    pub kind: FoldKind,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[allow(dead_code)]
pub enum FoldKind {
    Region,
    Comment,
}

// ---- IDs ----

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct ScopeId(pub u32);

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SymbolId(pub u32);

// ---- Scope ----

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Scope {
    pub id: ScopeId,
    pub parent: Option<ScopeId>,
    pub kind: ScopeKind,
    pub span: Span,
    /// The enclosing package/class name at this scope level.
    /// For `package Foo;` regions, this is "Foo".
    /// Inherited from parent when not overridden.
    pub package: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[allow(dead_code)]
pub enum ScopeKind {
    File,
    /// `class Foo { ... }` block.
    Class { name: String },
    /// `sub foo { ... }` block.
    Sub { name: String },
    /// `method foo { ... }` block.
    Method { name: String },
    /// Bare `{ ... }`, if/while/for bodies, etc.
    Block,
    /// `for my $x (...) { }` — loop variable scoped to block.
    ForLoop { var: String },
}

// ---- Package context ----

/// Flat per-file record of which `package`/`class` declaration governs a
/// byte range. Independent of the lexical scope tree — `package Foo;` is
/// not a lexical boundary in Perl, so collapsing the two concepts would
/// force shims (lift `my` past the package "scope", merge buckets in the
/// outline) we'd rather not have.
///
/// Query via `FileAnalysis::package_at(point)` — innermost (latest-starting)
/// containing range wins for nested `package Foo { … package Bar; … }`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PackageRange {
    pub package: String,
    pub span: Span,
    pub kind: PackageKind,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum PackageKind {
    /// `package Foo;` / `class Foo;` — flows until the next sibling
    /// declaration or end of file/block.
    Statement,
    /// `package Foo { … }` / `class Foo { … }` — span equals the block.
    Block,
}

// ---- Namespace ----

/// Origin tag for symbols and refs. Phase 1 of the namespace-widening work:
/// every entity gets a `Namespace` that records whether it's native Perl or
/// was produced by a framework rule (built-in or plugin). Downstream features
/// (completion bucketing, diagnostic suppression, plugin-aware rename) read
/// this tag instead of reconstructing provenance from names and positions.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum Namespace {
    /// Native Perl: subs, variables, packages, classes, hash keys extracted
    /// directly from the CST by the builder.
    Language,
    /// Produced by a framework plugin. `id` is the plugin identifier
    /// (e.g. `"mojo-base"`, `"moo"`, `"dbic-columns"`), allowing per-plugin
    /// filtering, rename coordination, and diagnostic attribution.
    Framework { id: String },
}

impl Default for Namespace {
    fn default() -> Self { Self::Language }
}

impl Namespace {
    pub fn framework(id: impl Into<String>) -> Self {
        Self::Framework { id: id.into() }
    }

    pub fn is_framework(&self) -> bool {
        matches!(self, Self::Framework { .. })
    }
}

// ---- Symbol ----

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Symbol {
    pub id: SymbolId,
    pub name: String,
    pub kind: SymKind,
    pub span: Span,
    pub selection_span: Span,
    /// Scope this symbol is declared in.
    pub scope: ScopeId,
    /// The package this symbol belongs to (captured at creation time).
    pub package: Option<String>,
    /// Kind-specific extra data.
    pub detail: SymbolDetail,
    /// Provenance tag. Defaults to `Language` for builder-native symbols;
    /// framework plugins stamp their plugin id.
    #[serde(default)]
    pub namespace: Namespace,
    /// Optional outline-only display name override. When set, the document
    /// outline uses this verbatim instead of `name` (and drops any
    /// kind-specific prefix like "helper"/"method"). Plugin-controlled:
    /// a chained Mojo helper leaf has `name: "create"` (so method
    /// resolution works on `$c->users->create`) but needs
    /// `outline_label: "users.create"` so the outline reflects the
    /// declared helper path. A mojo-lite route uses it to prepend the
    /// HTTP verb to the path. Doesn't affect resolution, rename, or
    /// workspace-symbol.
    #[serde(default)]
    pub outline_label: Option<String>,
}

impl Symbol {
    /// Bare variable/field name without the sigil. Uses the sigil stored
    /// in `detail` so we never re-derive it by text-stripping (which would
    /// mis-handle forms like `$$ref` if the name ever carried that shape).
    /// For non-variable symbols, returns `name` unchanged.
    pub fn bare_name(&self) -> &str {
        match &self.detail {
            SymbolDetail::Variable { sigil, .. } | SymbolDetail::Field { sigil, .. } => {
                let off = sigil.len_utf8();
                self.name.get(off..).unwrap_or(&self.name)
            }
            _ => &self.name,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SymKind {
    Variable,
    Sub,
    Method,
    Package,
    Class,
    Module,
    Field,
    HashKeyDef,
    /// Named handler registered on a class via string-dispatch (e.g. Mojo
    /// events, Dancer routes, Catalyst actions). Not a Perl method — it
    /// can't be called as `$self->name()`. It's dispatched through named
    /// methods (`->emit`, `->get`, `->forward`) whose first string arg
    /// selects which Handler to run. Multiple Handlers with the same
    /// `(owner, name)` stack, they don't override.
    Handler,
    /// Plugin-controlled scope (mojo app, Minion instance, mojo-events
    /// emitter). Surfaces in the document outline and workspace symbol
    /// search as a navigable entry. Outline entity — not backed by a
    /// Perl symbol, so most queries (gd/gr/rename) don't hit it.
    Namespace,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub enum SymbolDetail {
    Variable {
        sigil: char,
        decl_kind: DeclKind,
    },
    Sub {
        params: Vec<ParamInfo>,
        is_method: bool,
        /// Pre-rendered markdown from POD or comments preceding this sub.
        doc: Option<String>,
        /// Optional plugin-provided display override. Framework-synthesized
        /// methods (Mojo helpers, Dancer routes, DBIC relationships, etc.)
        /// resolve/complete/goto-def the same as a regular Method, but the
        /// plugin gets the final word on which LSP kind they render as.
        /// `None` leaves the default (Method → METHOD, Sub → FUNCTION).
        #[serde(default)]
        display: Option<HandlerDisplay>,
        /// Suppress this symbol in the document outline / workspace
        /// symbol list. Plugins synthesizing DSL imports (Mojolicious::Lite's
        /// `get`/`post`/`app`/...) set it so hover/gd/completion still work
        /// on the name, but the outline stays focused on user-visible
        /// structure. Whoever constructs the detail decides — the core
        /// never infers.
        #[serde(default)]
        hide_in_outline: bool,
        /// The return type is plugin-internal plumbing — use it for
        /// chain resolution but don't render it in completion details,
        /// hover return-type lines, or inlay hints. Lets framework
        /// plugins thread proxy classes (Mojo helper namespaces, DBIC
        /// result wrappers, etc.) without leaking "returns:
        /// _Helper::users::create" at every call site. Plugin-declared,
        /// no core heuristic on the type name.
        #[serde(default)]
        opaque_return: bool,
    },
    Class {
        parent: Option<String>,
        roles: Vec<String>,
        fields: Vec<FieldDetail>,
    },
    Field {
        sigil: char,
        attributes: Vec<String>,
    },
    HashKeyDef {
        owner: HashKeyOwner,
        is_dynamic: bool,
    },
    /// String-dispatched handler detail. `owner` ties the handler to a
    /// class (so two classes can each register a handler named "ready"
    /// without collision). `dispatchers` is the set of method names that
    /// select this handler by string — e.g. `["emit", "subscribe"]` for
    /// Mojo events, `["forward"]` for Catalyst actions. `params` is the
    /// handler's sub signature, consumed by signature help at call
    /// sites and by hover to describe the handler shape.
    ///
    /// `display` is the plugin's choice of LSP kind for outline,
    /// completion icon, and workspace-symbol presentation. Handlers
    /// share internal machinery (refs_by_target, stacking semantics,
    /// cross-file resolution) but aren't all "events" — Mojo events
    /// are, but routes are methods, config keys are fields, etc.
    /// The plugin says what the user sees; the abstraction stays one
    /// thing internally.
    Handler {
        owner: HandlerOwner,
        dispatchers: Vec<String>,
        params: Vec<ParamInfo>,
        #[serde(default)]
        display: HandlerDisplay,
        /// Suppress this handler in the document outline. Plugins set
        /// it for framework-synthesized entries that shouldn't clutter
        /// the user's navigation view — hover/gd/completion still find
        /// them via the symbol table.
        #[serde(default)]
        hide_in_outline: bool,
    },
    /// Package, Module, or other kinds needing no extra data.
    None,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DeclKind {
    My,
    Our,
    State,
    Field,
    Param,
    ForVar,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParamInfo {
    pub name: String,
    pub default: Option<String>,
    pub is_slurpy: bool,
    /// True when this param is the implicit receiver of the call,
    /// supplied by the caller via `$obj->method(...)` rather than
    /// written in the argument list. Sig help, hover, and outline
    /// drop invocant params so users see what they actually type.
    /// Whoever constructs the ParamInfo is responsible for setting
    /// this — the core never infers it from the name.
    #[serde(default)]
    pub is_invocant: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct FieldDetail {
    pub name: String,
    pub sigil: char,
    pub attributes: Vec<String>,
}

// ---- Ref ----

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Ref {
    pub kind: RefKind,
    pub span: Span,
    pub scope: ScopeId,
    pub target_name: String,
    pub access: AccessKind,
    /// For variable refs: which Symbol this resolves to (filled in post-pass).
    pub resolves_to: Option<SymbolId>,
}

/// What kind of entity is being renamed — determines single-file vs cross-file scope.
#[derive(Debug)]
pub enum RenameKind {
    Variable,
    /// A sub defined in (or imported from) a specific package.
    /// `package == None` means a top-level/script sub with no
    /// package context; otherwise package-scoped so cross-file
    /// walks don't rename same-named subs in unrelated packages.
    Function { name: String, package: Option<String> },
    Package(String),
    /// A method with its owning class. Cross-file walks use `class`
    /// to avoid unioning unrelated classes that share a method name
    /// (e.g. `Foo::run` vs `Bar::run`, mojo-helper leaves vs route
    /// targets).
    Method { name: String, class: String },
    HashKey(String),
    /// Rename a `Handler` by (owner, name) — touches the handler symbol's
    /// name + every `DispatchCall` ref targeting it.
    Handler { owner: HandlerOwner, name: String },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[allow(dead_code)]
pub enum RefKind {
    Variable,
    /// Bare `foo()` or `Pkg::foo()` call. `resolved_package` is the
    /// package whose `sub` this call actually targets — computed at
    /// build time by walking the enclosing-package-then-imports graph
    /// (see `Builder::resolve_call_package`). `None` means no pin (the
    /// call site has no package context and no import covers it);
    /// class/package-scoped queries treat unpinned refs as no-match
    /// rather than cross-linking same-named subs across packages.
    FunctionCall {
        #[serde(default)]
        resolved_package: Option<String>,
    },
    /// Method call site `$obj->m(...)` / `Class->m(...)` /
    /// `chain()->m(...)`. **Invocant class is NOT cached on the
    /// variant** — it's resolved on demand via
    /// `FileAnalysis::method_call_invocant_class(ref, module_index)`,
    /// which dispatches by invocant shape (variable / chain receiver /
    /// function-call receiver / bareword / `__PACKAGE__` / `shift` /
    /// `$_[0]`) and queries the witness bag. This is intentional:
    /// a cached field would silently miss invocants that get typed
    /// only by post-build cross-file enrichment, and chain hops
    /// can't be cached without invalidation. The bag-routed helper
    /// composes through cross-file enrichment automatically.
    ///
    /// Build-time chain typing still runs in the builder — it
    /// publishes Variable witnesses + chain-receiver `Expression`
    /// edge witnesses; the helper reads those at query time.
    MethodCall {
        invocant: String,
        /// Span of the invocant node. Used by
        /// `method_call_invocant_class` to find an inner-receiver
        /// ref via `call_ref_by_start` (chain dispatch).
        invocant_span: Option<Span>,
        /// Span of just the method name (for rename — r.span covers the whole expression).
        method_name_span: Span,
    },
    PackageRef,
    HashKeyAccess {
        var_text: String,
        owner: Option<HashKeyOwner>,
    },
    /// The container variable in `$hash{key}`, `@arr[0]`, etc.
    ContainerAccess,
    /// Call site that dispatches to a `Handler` symbol by string name,
    /// e.g. `$emitter->emit('ready', ...)`. `dispatcher` is the method
    /// name chosen on the receiver (`"emit"`, `"subscribe"`, etc.).
    /// `owner` is resolved at build time when the receiver type is
    /// known; otherwise left `None` and re-linked by enrichment later.
    /// `target_name` on the enclosing `Ref` is the handler name
    /// (the string literal first-arg).
    DispatchCall {
        dispatcher: String,
        owner: Option<HandlerOwner>,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum AccessKind {
    Read,
    Write,
    Declaration,
}

// ---- Type constraints ----

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TypeConstraint {
    pub variable: String,
    pub scope: ScopeId,
    pub constraint_span: Span,
    pub inferred_type: InferredType,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum InferredType {
    /// `$p = Point->new(...)` — variable is an instance of ClassName.
    ClassName(String),
    /// `my ($self) = @_` in `package Foo` — first param is the class.
    FirstParam { package: String },
    /// `$x = {}` or `$x = { ... }` — unblessed hash reference.
    HashRef,
    /// `$x = []` or `$x = [ ... ]` — unblessed array reference.
    ArrayRef,
    /// `$x = sub { ... }` — code reference. `return_edge` is a
    /// witness-bag attachment whose type IS the callable's return
    /// when invoked. Two shapes populate it:
    ///
    ///   - Anonymous-sub literals (`sub { ... }`) →
    ///     `Expr(body_last_expr_span)`. The bag walks that span's
    ///     own witnesses at query time, after the body is built.
    ///   - Named-sub references (`\&foo`, `\&Foo::bar`) →
    ///     `MethodOnClass { class, name }`. Same attachment the
    ///     bag's existing edge-chase uses for method dispatch —
    ///     resolves in-file via the named-sub's Symbol witnesses
    ///     AND cross-file via `module_index` (the bag transparently
    ///     recurses into the cached module's bag).
    ///
    /// Survives variable rebinding because chain typing propagates
    /// the whole `InferredType` through `my $sub = ...` via the
    /// bag's TC machinery — so `helper(name => sub {...})` and
    /// `my $cb = \&foo; helper(name => $cb)` both reach the same
    /// attachment-driven resolution.
    ///
    /// `None` for opaque sources (params typed `CodeRef`, deref-
    /// shape narrowing, `Rep::Code` observations) where no body or
    /// named target is reachable from the syntax alone.
    CodeRef { return_edge: Option<crate::witnesses::WitnessAttachment> },
    /// `$x = qr/.../` — compiled regular expression.
    Regexp,
    /// Used in numeric context (`+`, `-`, `==`, etc.).
    Numeric,
    /// Used in string context (`.`, `eq`, `=~`, etc.).
    String,
    /// Parametric type — a sealed enum where each variant carries
    /// its own data shape (concrete flavors) or wraps an operand
    /// for type-level projections. Per-axis methods on
    /// `ParametricType` (`class_name`, `hash_key_class`,
    /// `method_arg_owner`) carry per-flavor policy. **Match
    /// invariant: never `_ => …`.** Compiler exhaustiveness is
    /// the safety net for the future `Plugin` escape hatch
    /// variant.
    ///
    /// Design history: Phase 1 of Part 5c shipped this as a flat
    /// `{ base: String, type_args: Vec<TypeArg> }` shape with
    /// dual-accessor helpers; the per-method allowlist and the
    /// data-layout-special-cased accessors are gone, lifted into
    /// per-flavor methods on `ParametricType`. The emitter still
    /// gates per-shape — `Strict` (constructor keys), `Open`
    /// (Parametric receiver claims the method), `Deferred`
    /// (chain receiver, type unresolvable until enrichment) — but
    /// the three flavors share one `emit_call_arg_key_accesses`
    /// body via a `Gate` discriminator. See
    /// `docs/adr/parametric-types.md`.
    Parametric(ParametricType),
    /// Positional container — `my @arr = (...)` or
    /// `push @arr, ...` contributions accumulated walk-side. The
    /// `Vec` stores per-index types; `element_at(i)` projects.
    /// Spike scope: tuple shape only, no Homogeneous / Cycle /
    /// Heterogeneous classification yet.
    ///
    /// Placed at the END of the enum so bincode-serialized cache
    /// blobs keep their existing variant indices stable. Inserting
    /// new variants in the middle would shift every subsequent
    /// variant's wire-format index and silently misread old blobs.
    Sequence(Vec<InferredType>),
}

/// Concrete parametric flavors + type-level operators. Each
/// concrete flavor carries the data its semantics need; operators
/// (`RowOf`) wrap a sub-`InferredType` and reduce via
/// `ParametricProjectionReducer` in the witness bag.
///
/// **Match invariant: never `_ => …` arms.** Every consumer
/// explicitly handles every variant. The compiler enforces this
/// when the (deferred) `Plugin` escape hatch lands.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum ParametricType {
    /// DBIC `$schema->resultset('Foo')` shape. `base` is the
    /// resolved resultset class (default
    /// `DBIx::Class::ResultSet`, or a discovered custom resultset
    /// class — see `goto_def_offers_custom_resultset_method` red-
    /// pin). `row` is the row class (where `add_columns`
    /// synthesizes its column accessors). Two distinct fields
    /// because the value carries dual identity:
    ///   - method dispatch goes through `base`
    ///   - hash-key arg owner / direct hash-key access go through `row`
    ///
    /// Pinned by internal-shape tests so a refactor to a single-
    /// class encoding silently breaks `RowOf` rather than
    /// silently returning the wrong dimension.
    ResultSet { base: String, row: String },

    /// `RowOf<T>` — type-level projection. Reduces:
    ///   - `RowOf<ResultSet { base, row }>` → `ClassName(row)`
    ///   - everything else → `None` (the operand has no row
    ///     dimension)
    ///
    /// Lazy: emitted as a witness, reduced by
    /// `ParametricProjectionReducer` in the bag. Composes —
    /// `RowOf<RowOf<X>>` evaluates by recursing into the operand.
    /// Plugin port (queued) emits `RowOf(receiver_type)` for
    /// methods like `find` / `first` / `single` / `next` /
    /// `create` that project a ResultSet to its row.
    RowOf(Box<InferredType>),
}

impl ParametricType {
    /// Class to consult for method dispatch on this value.
    /// `$rs->all` resolves against `class_name()`'s answer.
    pub fn class_name(&self) -> Option<&str> {
        match self {
            ParametricType::ResultSet { base, .. } => Some(base.as_str()),
            ParametricType::RowOf(inner) => {
                // Evaluate: row-class of inner (if inner is
                // ResultSet) is the dispatch class for the
                // projected value.
                match inner.as_ref() {
                    InferredType::Parametric(ParametricType::ResultSet { row, .. }) => {
                        Some(row.as_str())
                    }
                    _ => None,
                }
            }
        }
    }

    /// Class to consult for direct `recv->{key}` hash-key access
    /// on this value. ResultSet returns `row` (the column-keyed
    /// class — used today only by the cleanup-pass HashKeyAccess
    /// owner-resolution paths; HRI shape isn't supported but the
    /// field is the right one when it lands). Operators evaluate
    /// recursively.
    pub fn hash_key_class(&self) -> Option<&str> {
        match self {
            ParametricType::ResultSet { row, .. } => Some(row.as_str()),
            ParametricType::RowOf(inner) => match inner.as_ref() {
                InferredType::Parametric(p) => p.hash_key_class(),
                _ => None,
            },
        }
    }

    /// Owner for hash-key args of `recv->method({KEY => ...})`.
    /// `Some(owner)` means "this flavor claims this method's args
    /// — emit the HashKeyAccess unconditionally with this owner;
    /// the type IS the gate." `None` means "this flavor doesn't
    /// claim, fall through to the strict-eq local-symbol path."
    ///
    /// ResultSet claims the row-keyed methods (search, search_rs,
    /// find, find_or_new, find_or_create, update_or_create, create,
    /// update, populate). Methods that take filters or no args
    /// (count, exists, delete, all without args) return None.
    pub fn method_arg_owner(&self, method: &str) -> Option<HashKeyOwner> {
        match self {
            ParametricType::ResultSet { row, .. } => match method {
                "search" | "search_rs" | "find" | "find_or_new" | "find_or_create"
                | "update_or_create" | "create" | "update" | "populate" | "new_result" => {
                    Some(HashKeyOwner::Class(row.clone()))
                }
                _ => None,
            },
            ParametricType::RowOf(_) => None,
        }
    }


    /// Symbol-declarative projection table — list of `(method_name,
    /// ReturnExpr)` pairs the flavor publishes on
    /// `MethodOnClass{base, method}` so consumers chasing through
    /// inheritance / coderef-edge / dynamic-method routes hit the
    /// projection without the call-site `parametric_projection`
    /// emitter firing. Used by `emit_parametric_return_expr_decls`
    /// after every `extract_resultset_parametric` hit — the `base`
    /// discovered there pins the class slot for the witness.
    ///
    /// `ReturnExpr::Operator(RowOf(Receiver))` evaluates at the
    /// reducer with `q.receiver = the call's invocant type`. For
    /// `\&MyRS::find; $cb->($rs, ...)`, the chain typer's coderef
    /// arm sees the target is `MethodOnClass{MyRS, find}`,
    /// inheritance walks to `MethodOnClass{DBIx::Class::ResultSet,
    /// find}`, finds the `Operator(RowOf, Receiver)` declaration,
    /// substitutes `q.receiver = $rs`'s `Parametric(ResultSet)`,
    /// evaluates `RowOf(ResultSet { row, .. }) → ClassName(row)`.
    pub fn return_method_declarations(
        &self,
    ) -> Vec<(&'static str, crate::witnesses::ReturnExpr)> {
        match self {
            ParametricType::ResultSet { .. } => {
                let row_of_receiver = crate::witnesses::ReturnExpr::Operator(
                    crate::witnesses::ParametricOp::RowOf(Box::new(
                        crate::witnesses::ReturnExpr::Receiver,
                    )),
                );
                ["find", "first", "single", "next", "create",
                 "find_or_new", "find_or_create", "update_or_create",
                 "new_result"]
                    .iter()
                    .map(|m| (*m, row_of_receiver.clone()))
                    .collect()
            }
            ParametricType::RowOf(_) => Vec::new(),
        }
    }
}

impl InferredType {
    /// Extract the class name if this is an object type
    /// (ClassName, FirstParam, or Parametric — the latter
    /// delegates to the flavor's `class_name()`). For the row-
    /// class / hash-key-arg dimension on a Parametric, see
    /// `hash_key_class`.
    pub fn class_name(&self) -> Option<&str> {
        match self {
            InferredType::ClassName(name) => Some(name.as_str()),
            InferredType::FirstParam { package } => Some(package.as_str()),
            InferredType::Parametric(p) => p.class_name(),
            _ => None,
        }
    }

    /// Project a `Sequence(...)` to its element at index `i`. Negative
    /// indices wrap from the end (Perl `$arr[-1]`). `None` for any
    /// non-Sequence type or out-of-bounds index.
    pub fn element_at(&self, i: i32) -> Option<&InferredType> {
        let InferredType::Sequence(elems) = self else { return None };
        let n = elems.len() as i32;
        let idx = if i < 0 { n + i } else { i };
        if idx < 0 || idx >= n { return None; }
        elems.get(idx as usize)
    }

    /// True if this is any object-shaped variant (ClassName,
    /// FirstParam, or a Parametric flavor that has a class_name).
    pub fn is_object(&self) -> bool {
        self.class_name().is_some()
    }

    /// Class to consult for direct `recv->{key}` hash-key access
    /// on this value. For Parametric, delegates to the flavor; for
    /// other variants, falls back to `class_name()` (constructor
    /// keys etc. on `bless { } 'Foo'`-shaped values).
    pub fn hash_key_class(&self) -> Option<&str> {
        match self {
            InferredType::Parametric(p) => p.hash_key_class(),
            _ => self.class_name(),
        }
    }

    /// Direct accessor to the parametric flavor, when this type
    /// is `Parametric(_)`. Lets consumers route to flavor-specific
    /// methods (`method_arg_owner`, etc.) without re-matching.
    pub fn as_parametric(&self) -> Option<&ParametricType> {
        match self {
            InferredType::Parametric(p) => Some(p),
            _ => None,
        }
    }

    /// Witness-bag attachment whose type IS this callable's return
    /// when invoked. `Expr(span)` for anon-sub literals (resolves
    /// at query time via the body's last-expression witnesses);
    /// `MethodOnClass{class, name}` for named-sub references
    /// (`\&foo`, `\&Foo::bar` — resolves via the bag's existing
    /// MRO + cross-file machinery, same shape used by method
    /// dispatch). Returns `None` for opaque coderef sources.
    ///
    /// Survives variable rebinding: chain typing propagates the
    /// `InferredType` through `my $cb = ...` via the bag's TC
    /// machinery, so consumers see the same attachment whether
    /// the callable arrives as a literal or a rebound scalar.
    pub fn callable_return_edge(&self) -> Option<&crate::witnesses::WitnessAttachment> {
        match self {
            InferredType::CodeRef { return_edge } => return_edge.as_ref(),
            _ => None,
        }
    }

    /// True when `self` is at least as informative as `narrowing`
    /// — adding the narrowing's TC would not refine `self` further.
    /// "Informativeness" is defined per-variant: same discriminant
    /// AND, where the variant carries refinable payload, `self`'s
    /// payload is at least as specific as `narrowing`'s.
    ///
    /// Used by `infer_deref_type` to suppress the
    /// `$cb->()`-shaped narrowing TC when the operand was already
    /// typed with a richer attachment (e.g. an anon-sub literal's
    /// `CodeRef { return_edge: Some(_) }` should NOT be clobbered
    /// by the deref's `CodeRef { return_edge: None }` under
    /// latest-wins reduction).
    ///
    /// Conservative: returns false on different discriminants
    /// (let the reducer-stack decide the conflict). Variants
    /// without refinable payload (HashRef/ArrayRef/Regexp/Numeric/
    /// String) subsume themselves trivially.
    pub fn subsumes_narrowing(&self, narrowing: &InferredType) -> bool {
        match (self, narrowing) {
            // Refinable-payload variants — `self` subsumes only
            // if its payload is at least as specific.
            (
                InferredType::CodeRef { return_edge: have },
                InferredType::CodeRef { return_edge: want },
            ) => want.is_none() || have.is_some(),
            (InferredType::ClassName(a), InferredType::ClassName(b)) => a == b,
            (InferredType::FirstParam { package: a }, InferredType::FirstParam { package: b }) => {
                a == b
            }
            (InferredType::Parametric(a), InferredType::Parametric(b)) => a == b,
            // Unit-shape variants subsume themselves; mismatched
            // discriminants don't subsume.
            (a, b) => std::mem::discriminant(a) == std::mem::discriminant(b),
        }
    }
}

/// Where a type judgement came from. Lets debugging surface "the
/// analyzer worked this out from your code" vs "a plugin override
/// said so" without changing the shape of `InferredType` at every
/// callsite. Stored in a sidecar map keyed by SymbolId — entries
/// only exist for non-default provenances, so the common case (an
/// inferred type) costs nothing.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum TypeProvenance {
    /// Derived from the analyzed source — return statements,
    /// last-expression inference, framework synthesis, constructor
    /// patterns. The default; never stored explicitly.
    Inferred,
    /// Asserted by a plugin's `overrides()` manifest because
    /// inference can't (or shouldn't) reach the right answer here.
    /// Carries the asserting plugin's id and a free-form reason for
    /// the debugger.
    PluginOverride { plugin_id: String, reason: String },
    /// Produced by a witness-bag reducer at type-resolution time.
    /// `reducer` names the rule that fired (`framework_aware`,
    /// `branch_arm`, `arity_dispatch`, `named_sub_return`, …);
    /// `evidence` is a short list of human-readable facts the
    /// reducer leaned on ("framework=MojoBase", "arms=2 agree",
    /// "arity=Default"). Read-only debugging aid surfaced by
    /// `--dump-package`. Empty `evidence` is fine — the reducer
    /// name alone often answers "why".
    ReducerFold { reducer: String, evidence: Vec<String> },
    /// Tail-delegation: the sub's body ends in `shift->M(...)` /
    /// `$self->M(...)` / `return Y()` and inherits the tail's
    /// return type. `via` is the delegate's name; `kind` is
    /// "self_method_tail" or "sub_return". Lets `--dump-package`
    /// answer "get returns ClassName(Route) — because it tails on
    /// _generate_route which the framework-aware reducer typed as
    /// ClassName(Route)".
    Delegation { kind: String, via: String },
    /// Core framework synthesis — Mojo::Base / Moo / Moose `has`,
    /// DBIx::Class `add_columns` / `has_many` / etc. The accessor
    /// has no source body to fold; the type comes directly from the
    /// declaration shape (Mojo writers always return the invocant;
    /// Moo getters honour `isa`; DBIC relationships return the
    /// related class). `framework` names the rule set
    /// ("Mojo::Base" / "Moo" / "Moose" / "DBIx::Class") and
    /// `reason` describes the specific accessor ("`has 'level'`
    /// fluent writer", "DBIx::Class row relationship `book`").
    /// Distinct from `PluginOverride` because plugins are user-installed
    /// and configurable; framework synthesis is built into the analyzer.
    FrameworkSynthesis { framework: String, reason: String },
}

/// Resolve a return type from a list of inferred types (one per return statement).
///
/// Rules (from spec):
/// - All agree → that type
/// - Object subsumes HashRef (overloaded objects are common)
/// - Disagreement → None (Unknown)
///
/// The input should already have bare returns / undef filtered out.
pub fn resolve_return_type(return_types: &[InferredType]) -> Option<InferredType> {
    if return_types.is_empty() {
        return None;
    }
    let first = &return_types[0];
    if return_types.iter().all(|t| t == first) {
        return Some(first.clone());
    }
    // Object subsumes HashRef: if some returns are Object(X) and others are HashRef,
    // the Object wins (overloaded hash access is common in Perl).
    let mut object = None;
    for t in return_types {
        if t.is_object() {
            object = Some(t.clone());
        } else if *t != InferredType::HashRef {
            // Non-HashRef, non-Object disagreement → Unknown
            return None;
        }
    }
    object
}

// ---- Handler owner ----

/// Plugin-chosen LSP display kind for a `Handler`. Handlers all share
/// the same internal mechanism (string-dispatched, stacked, cross-file),
/// but they aren't all the same thing *semantically* — routes are
/// method-ish, events are event-ish, config keys are field-ish. The
/// plugin decides what icon the editor shows.
///
/// Expand this enum when a plugin has a concept that doesn't fit any
/// existing variant; every variant maps to a corresponding LSP
/// `SymbolKind` / `CompletionItemKind` via thin translation in
/// `symbols.rs`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HandlerDisplay {
    Event,
    Method,
    Function,
    Field,
    Property,
    Constant,
    /// Plugin-synthesized callable on the framework's app instance.
    /// Renders with LSP kind FUNCTION; outline detail prints "helper".
    Helper,
    /// Framework-declared URL pattern. Same LSP kind as Helper/Task;
    /// outline detail prints "route" so the client can disambiguate.
    Route,
    /// A controller action referenced from a routing declaration —
    /// e.g. the `Users#list` target of Mojolicious' `->to('Users#list')`
    /// (Mojo's own docs call this an "action") or Catalyst's
    /// `->forward('/users/list')`. Distinct from `Route` because no
    /// request-handling body lives at this source site: it's a
    /// cross-reference to a method that lives elsewhere. Outline word
    /// "action" so `<route> GET /users` and `<action> Users#list` read
    /// as two different kinds of line items.
    Action,
    /// Job-queue / worker task (Minion etc.). Helper-kin for the LSP
    /// kind, distinct "task" word in outline detail.
    Task,
}

impl Default for HandlerDisplay {
    fn default() -> Self { Self::Event }
}

impl HandlerDisplay {
    /// Short human-readable word the outline puts in `detail` so LSP
    /// clients can show `[Function] name — helper` even though the
    /// LSP kind enum doesn't have a Helper variant. Returns `None`
    /// for display kinds that don't carry a distinguishing word
    /// beyond the LSP kind itself.
    pub fn outline_word(&self) -> Option<&'static str> {
        match self {
            HandlerDisplay::Event => Some("event"),
            HandlerDisplay::Helper => Some("helper"),
            HandlerDisplay::Route => Some("route"),
            HandlerDisplay::Action => Some("action"),
            HandlerDisplay::Task => Some("task"),
            _ => None,
        }
    }
}

/// Owner of a `Handler` symbol. Distinct from `HashKeyOwner` because
/// hash keys and dispatch handlers are different concepts even though
/// both happen to be keyed by a name under a class. Keeping them split
/// prevents overload creep — each stays free to evolve on its own axis.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HandlerOwner {
    /// Handler is registered on a specific class (typical for Mojo
    /// events, Moose roles, DBIC relationships, etc.).
    Class(String),
}

// ---- Plugin namespace ----

/// A plugin-controlled scope. Replaces the bolt-on of "plugin entities
/// become Methods on a hijacked Perl class" with a first-class
/// registration: the plugin says "I own a namespace — here's its
/// bridges (how Perl-space expressions find it) and its entities".
///
/// Why this exists:
///   * Helpers aren't methods on `Mojolicious::Controller`. They're
///     callables on the app instance, reached THROUGH a controller.
///   * Two apps in one workspace become two `PluginNamespace`s with
///     the same `Class("Mojolicious::Controller")` bridge. Their
///     entities don't collide at the class level — they're owned by
///     the namespace, not the class.
///   * Cross-file lookup is one primitive
///     (`ModuleIndex::namespaces_bridged_to(class)`) instead of the
///     patchwork of `class_content_index` / `reverse_index` /
///     `modules_with_symbol`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginNamespace {
    /// Plugin-generated unique identifier. E.g.
    /// `"mojo-app:/abs/path/to/MyApp.pm"` or
    /// `"minion:$minion@MyApp.pm:5"`. Plugin decides how to
    /// disambiguate multiple instances in a single workspace.
    pub id: String,
    /// Which plugin registered this namespace — the Namespace::Framework
    /// `id` that gets stamped on emitted entities.
    pub plugin_id: String,
    /// Plugin-defined kind tag. `"app"`, `"minion"`, `"emitter"`, …
    /// Used by display/completion to tell users what sort of thing
    /// a namespace member is.
    pub kind: String,
    /// Symbols that belong to this namespace. Cross-references into
    /// the same FileAnalysis's `symbols` table — plugins still emit
    /// Methods / Handlers normally; the namespace indexes them.
    pub entities: Vec<SymbolId>,
    /// How Perl-space expressions reach this namespace's entities.
    pub bridges: Vec<Bridge>,
    /// Span where the plugin declared the namespace (typically the
    /// registration call — `$app->plugin('Minion', ...)` etc.).
    pub decl_span: Span,
}

/// A connection from a Perl-space type/shape into a plugin namespace.
/// When a lookup asks "what's reachable from class X?", the core
/// unions Perl-native methods with entities from every namespace
/// whose bridges match X.
///
/// Currently only `Class` is wired — `Bareword` / `Variable` would
/// require lookup machinery (`bareword_index`, per-variable bridge
/// table) that doesn't exist yet. Re-add them when a concrete plugin
/// needs the shape; speculative variants just rot.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum Bridge {
    /// Any expression typed as this class (or a subclass reached via
    /// inheritance walk) can see this namespace's entities. The
    /// canonical bridge for framework helpers on controllers.
    Class(String),
}

// ---- Hash key owner (for scope graph) ----

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HashKeyOwner {
    Class(String),
    Variable { name: String, def_scope: ScopeId },
    /// Hash keys from a sub's return value: `sub get_config { return { host => 1 } }`.
    /// `package` is the enclosing Perl package at the sub's declaration site
    /// (or `None` for top-level script subs where no `package` statement is
    /// in scope). Without this, two different packages each defining
    /// `sub get_config { ... host ... }` would collide at query time.
    Sub { package: Option<String>, name: String },
}

impl HashKeyOwner {
    /// Directional match: would a lookup with `lookup` owner reach a
    /// def with `self` owner? Strict equality, plus the broadening
    /// rule that a `Class(C)` lookup picks up `Sub{Some(C), _}` defs.
    ///
    /// Why: bless-inside-a-sub registers HashKeyDefs as `Sub{C,
    /// sub_name}` (the constructor sub). `has` does the same. But
    /// `$obj->{key}` deref refs and `complete_hash_keys_for_class`
    /// callers carry `Class(C)` — that's the "any key for objects of
    /// C" lookup. The asymmetry keeps strict `Sub{C, M}` lookups
    /// from accidentally finding keys registered to a *different*
    /// method on the same class.
    pub fn found_by(&self, lookup: &HashKeyOwner) -> bool {
        if self == lookup { return true; }
        match (self, lookup) {
            (HashKeyOwner::Sub { package: Some(c1), .. }, HashKeyOwner::Class(c2)) => c1 == c2,
            _ => false,
        }
    }
}


// ---- Call binding ----

/// A variable assigned from a function call: `my $cfg = get_config()`.
/// Stored in FileAnalysis so query-time resolution can follow the chain.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CallBinding {
    pub variable: String,
    pub func_name: String,
    pub scope: ScopeId,
    pub span: Span,
}

/// A method call binding: `$var = $invocant->method()`.
/// Recorded during build, resolved in post-pass via `find_method_return_type`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MethodCallBinding {
    pub variable: String,
    pub invocant_var: String,
    pub method_name: String,
    pub scope: ScopeId,
    pub span: Span,
}

// ---- Import ----

/// One name brought into scope by a `use` statement.
///
/// `local_name` is how the name appears at call sites in this file.
/// `remote_name` is the sub's real name in the source module — usually
/// identical to `local_name` (the common case, encoded as `None` to
/// keep the serialized form compact) and different only for renaming
/// imports: `del` in Mojolicious::Lite is really `delete` on
/// Mojolicious::Routes::Route, `use Exporter::Tiny ( foo => { -as => 'bar' } )`
/// gives a `bar` locally pointing at the real `foo`, etc.
///
/// Cross-file lookups always resolve via `remote()` so hover, gd, sig
/// help, and return-type inference use the real module's `sub_info`.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct ImportedSymbol {
    pub local_name: String,
    /// `None` means the local and remote names are the same.
    ///
    /// No `skip_serializing_if` — bincode is a non-self-describing
    /// format and needs the field present on the wire regardless.
    /// Self-describing formats (JSON, YAML) happily encode `null`
    /// for None too, so keeping it always-serialized is fine
    /// everywhere.
    #[serde(default)]
    pub remote_name: Option<String>,
}

impl ImportedSymbol {
    /// Same-name import — the overwhelmingly common case.
    pub fn same(name: impl Into<String>) -> Self {
        Self { local_name: name.into(), remote_name: None }
    }
    /// Renaming import — local name differs from the real sub's name.
    ///
    /// Currently constructed only from Rhai plugins via serde-deserialized
    /// maps (`#{ local_name: ..., remote_name: ... }`), so this Rust-side
    /// constructor has no direct caller yet. Keeping it as documented public
    /// API so future Rust callers (e.g. a hand-written parser for renaming
    /// import syntax, or core plugins) have the canonical way to build one.
    #[allow(dead_code)]
    pub fn renamed(local: impl Into<String>, remote: impl Into<String>) -> Self {
        let remote = remote.into();
        let local = local.into();
        // Collapse `remote == local` to the same-name shape so downstream
        // code doesn't need to handle both representations.
        if remote == local {
            Self { local_name: local, remote_name: None }
        } else {
            Self { local_name: local, remote_name: Some(remote) }
        }
    }
    /// Real name in the source module — used for cross-file sub_info lookup.
    pub fn remote(&self) -> &str {
        self.remote_name.as_deref().unwrap_or(&self.local_name)
    }
}

/// A `use Foo::Bar qw(func1 func2)` statement parsed from the source.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Import {
    /// Module name, e.g. "List::Util".
    pub module_name: String,
    /// Explicitly imported names from `qw(...)`. Empty = bare `use Foo;`.
    /// Each entry carries local + (optional) remote name for renaming imports.
    pub imported_symbols: Vec<ImportedSymbol>,
    /// Span of the entire `use` statement.
    pub span: Span,
    /// Position of the closing delimiter of the `qw()` list (the `)` character).
    /// Used to insert new imports into an existing qw list.
    #[serde(with = "point_opt_serde")]
    pub qw_close_paren: Option<Point>,
}

// ---- Outline ----

pub struct OutlineSymbol {
    pub name: String,
    pub detail: Option<String>,
    pub kind: SymKind,
    pub span: Span,
    pub selection_span: Span,
    pub children: Vec<OutlineSymbol>,
    /// For `Handler` symbols, the plugin-chosen LSP display kind.
    /// Carried here so the outline→DocumentSymbol conversion doesn't
    /// need to re-resolve the SymbolDetail. `None` for non-Handler
    /// kinds (they use the fixed SymKind → LSP mapping).
    pub handler_display: Option<HandlerDisplay>,
}

// ---- Semantic tokens ----

// Token type/modifier indices — must match the order in semantic_token_types/modifiers().
// Some are forward-declared for future phases.
pub const TOK_VARIABLE: u32 = 0;
pub const TOK_PARAMETER: u32 = 1;
pub const TOK_FUNCTION: u32 = 2;
pub const TOK_METHOD: u32 = 3;
pub const TOK_MACRO: u32 = 4;
pub const TOK_PROPERTY: u32 = 5;
pub const TOK_NAMESPACE: u32 = 6;
#[allow(dead_code)] pub const TOK_REGEXP: u32 = 7;
#[allow(dead_code)] pub const TOK_ENUM_MEMBER: u32 = 8;
pub const TOK_KEYWORD: u32 = 9;

pub const MOD_DECLARATION: u32 = 0;
pub const MOD_READONLY: u32 = 1;
pub const MOD_MODIFICATION: u32 = 2;
pub const MOD_DEFAULT_LIBRARY: u32 = 3;
#[allow(dead_code)] pub const MOD_DEPRECATED: u32 = 4;
#[allow(dead_code)] pub const MOD_STATIC: u32 = 5;
pub const MOD_SCALAR: u32 = 6;
pub const MOD_ARRAY: u32 = 7;
pub const MOD_HASH: u32 = 8;

#[derive(Debug, Clone)]
pub struct PerlSemanticToken {
    pub span: Span,
    pub token_type: u32,
    pub modifiers: u32,
}

/// Plugin-chosen LSP display for a Sub-detail symbol, if any. Null for
/// everything else — lets completion/outline carry plugin intent
/// without each site re-matching on detail shape.
fn sub_display_override(detail: &SymbolDetail) -> Option<HandlerDisplay> {
    if let SymbolDetail::Sub { display, .. } = detail {
        *display
    } else {
        None
    }
}

fn sigil_modifier(sigil: char) -> u32 {
    match sigil {
        '@' => 1 << MOD_ARRAY,
        '%' => 1 << MOD_HASH,
        _ => 1 << MOD_SCALAR,
    }
}

// ---- FileAnalysis ----

#[derive(Debug, Serialize, Deserialize)]
pub struct FileAnalysis {
    // Core tables
    pub scopes: Vec<Scope>,
    pub symbols: Vec<Symbol>,
    pub refs: Vec<Ref>,
    pub fold_ranges: Vec<FoldRange>,
    pub imports: Vec<Import>,
    pub call_bindings: Vec<CallBinding>,
    pub method_call_bindings: Vec<MethodCallBinding>,

    /// Flat list of `package`/`class` declarations and the byte ranges
    /// they govern. Replaces `Scope::package` walks for `package_at`.
    /// `#[serde(default)]` so older cache blobs deserialize as empty
    /// (`package_at` falls back to the legacy scope walk in that case).
    #[serde(default)]
    pub package_ranges: Vec<PackageRange>,

    /// Parent classes for each package in this file.
    /// Populated by the builder from use parent/base, @ISA, and class :isa.
    pub package_parents: HashMap<String, Vec<String>>,

    /// Modules `use`-d inside each package in this file. Parallel to
    /// `package_parents`: keyed by the enclosing package name, values are
    /// module names. Powers trigger-matching for plugin query hooks
    /// (emit-path builder state isn't visible at cursor time).
    pub package_uses: HashMap<String, Vec<String>>,

    /// Functions implicitly imported by OOP frameworks (e.g. `has`, `extends`, `with`).
    /// Used to suppress "not defined" diagnostics for these known framework keywords.
    pub framework_imports: HashSet<String>,

    /// Exported function names from `@EXPORT = ...` assignments.
    pub export: Vec<String>,
    /// Exported function names from `@EXPORT_OK = ...` assignments.
    pub export_ok: Vec<String>,

    /// Plugin-declared namespaces. Each is a scope managed by a plugin
    /// (a Mojolicious app, a Minion instance, an event-emitter subclass,
    /// …). Declares bridges into Perl-space and owns a set of entities.
    /// Lookups union these with native Perl resolution — see
    /// `ModuleIndex::namespaces_bridged_to` for the cross-file primitive.
    #[serde(default)]
    pub plugin_namespaces: Vec<PluginNamespace>,

    /// Per-symbol provenance for return types. Populated for plugin
    /// `overrides()` and (with this spike) for reducer-driven folds
    /// over the witness bag. Missing entry == `TypeProvenance::Inferred`.
    /// Read-only debugging aid: features like hover/completion don't
    /// branch on it; it exists so `--dump-package` and a future
    /// inspector can answer "why does the LSP think this returns X?"
    /// without re-running the build.
    #[serde(default)]
    pub type_provenance: HashMap<SymbolId, TypeProvenance>,

    /// Detected framework mode per package (for Part 6's resolver).
    /// Populated by the builder when `use Moo` / `use Mojo::Base` /
    /// `use Moose` etc. is observed. Additive: the existing framework
    /// accessor synthesis keeps running the same code paths.
    #[serde(default)]
    pub package_framework: HashMap<String, crate::witnesses::FrameworkFact>,

    /// Part 7 — the witness bag. Canonical store for type facts:
    /// every Variable type, Symbol/MethodOnClass return type, branch
    /// arm Edge, hash-key observation. `inferred_type_via_bag` reads
    /// here. The builder pushes directly via `push_type_constraint`
    /// (Variable witnesses with TC shape) and per-attachment emit
    /// helpers; cache blobs round-trip the bag in full.
    #[serde(default)]
    pub witnesses: crate::witnesses::WitnessBag,

    /// Witness-bag baseline — `enrich_imported_types_with_keys`
    /// truncates back to this length before re-deriving so repeat
    /// calls stay idempotent.
    #[serde(default)]
    base_symbol_count: usize,
    #[serde(default)]
    base_witness_count: usize,

    // Indices (built in post-pass — skipped by serde; call rebuild_all_indices() after deserialize)
    #[serde(skip, default)]
    scope_starts: Vec<(Point, ScopeId)>, // sorted by start point
    #[serde(skip, default)]
    symbols_by_name: HashMap<String, Vec<SymbolId>>,
    #[serde(skip, default)]
    symbols_by_scope: HashMap<ScopeId, Vec<SymbolId>>,
    #[serde(skip, default)]
    refs_by_name: HashMap<String, Vec<usize>>,
    /// Refs indexed by the SymbolId they resolve to (phase 5).
    /// Every query for "refs to symbol X" collapses to an O(1) lookup here.
    #[serde(skip, default)]
    refs_by_target: HashMap<SymbolId, Vec<usize>>,
    /// Start-point → call-shaped ref index. Used by
    /// `method_call_invocant_class` to chase a chain receiver:
    /// `Foo->new->m`'s outer `->m` `invocant_span` starts at the
    /// inner `Foo->new` call's start; `make_b()->touch()`'s outer
    /// `invocant_span` starts at `make_b`'s start. Only MethodCall
    /// and FunctionCall refs go in here — the receiver dispatch is
    /// keyed on those two kinds.
    #[serde(skip, default)]
    call_ref_by_start: HashMap<Point, usize>,
}

impl FileAnalysis {
    /// Create a new FileAnalysis with indices built from the raw tables.
    pub fn new(
        scopes: Vec<Scope>,
        symbols: Vec<Symbol>,
        refs: Vec<Ref>,
        fold_ranges: Vec<FoldRange>,
        imports: Vec<Import>,
        call_bindings: Vec<CallBinding>,
        package_parents: HashMap<String, Vec<String>>,
        method_call_bindings: Vec<MethodCallBinding>,
        framework_imports: HashSet<String>,
        export: Vec<String>,
        export_ok: Vec<String>,
        plugin_namespaces: Vec<PluginNamespace>,
        package_uses: HashMap<String, Vec<String>>,
        type_provenance: HashMap<SymbolId, TypeProvenance>,
        package_ranges: Vec<PackageRange>,
    ) -> Self {
        let mut fa = FileAnalysis {
            scopes,
            symbols,
            refs,
            fold_ranges,
            imports,
            call_bindings,
            method_call_bindings,
            package_ranges,
            package_parents,
            package_uses,
            framework_imports,
            export,
            export_ok,
            plugin_namespaces,
            type_provenance,
            witnesses: crate::witnesses::WitnessBag::new(),
            package_framework: HashMap::new(),
            base_symbol_count: 0,
            base_witness_count: 0,
            scope_starts: Vec::new(),
            symbols_by_name: HashMap::new(),
            symbols_by_scope: HashMap::new(),
            refs_by_name: HashMap::new(),
            refs_by_target: HashMap::new(),
            call_ref_by_start: HashMap::new(),
        };
        fa.build_indices();
        // The builder path overwrites `witnesses` with its already-populated
        // bag after construction. Hand-crafted FAs (tests) push witnesses
        // directly via `fa.witnesses.push(...)` or `push_type_constraint`.
        // `finalize_post_walk` runs on the builder path to seal baseline
        // counts and resolve text-based MCB; tests skip it.
        fa
    }

    /// Run the local-only method-call-binding resolution and seal
    /// baseline counts. Called by `builder::build` after the witness
    /// bag has been moved in.
    ///
    /// `Symbol(sym_id)` and `MethodOnClass{class, name}` return-type
    /// witnesses for every local Sub/Method are already in the bag —
    /// published by `Builder::write_back_sub_return_types` at the
    /// end of the worklist (single emission point for "this sub's
    /// return type is known"). Cross-file imports do not get a local
    /// mirror; they resolve lazily through `query_sub_return_type`.
    pub(crate) fn finalize_post_walk(&mut self) {
        self.resolve_method_call_types(None);
        // Fill HashKeyAccess owners that are resolvable in-file
        // via the chain-recursion dispatcher
        // (`method_call_invocant_type`'s `call_ref_by_start`
        // walk). Cross-file gaps stay None until
        // `enrich_imported_types_with_keys` re-runs the same
        // routine with `module_index`.
        self.fix_chain_receiver_hash_key_owners(None);
        self.base_symbol_count = self.symbols.len();
        self.base_witness_count = self.witnesses.len();
    }

    /// Set the `owner` on `HashKeyAccess { owner: None, .. }` refs
    /// whose enclosing `MethodCall`'s receiver types as a
    /// `Parametric` flavor that claims this method's args (DBIC's
    /// `search`/`find`/`update`/...). Build emits these refs
    /// eagerly with `owner: None` for chain receivers it can't
    /// resolve at walk time; this routine fills them once the
    /// receiver's type is resolvable.
    ///
    /// `module_index = None` resolves only in-file chains. The
    /// same routine runs from enrichment with `module_index =
    /// Some(_)` to fill cross-file gaps. Idempotent — only None-
    /// owner refs are touched, so a second run leaves them alone.
    fn fix_chain_receiver_hash_key_owners(&mut self, module_index: Option<&ModuleIndex>) {
        let mut owner_fixes: Vec<(usize, HashKeyOwner)> = Vec::new();
        for (i, r) in self.refs.iter().enumerate() {
            if !matches!(r.kind, RefKind::HashKeyAccess { owner: None, .. }) {
                continue;
            }
            // Find the enclosing MethodCall ref by span
            // containment — smallest-span containing MethodCall
            // wins (innermost call's args).
            let mut enclosing: Option<&Ref> = None;
            let mut enclosing_area: u64 = u64::MAX;
            for other in &self.refs {
                if !matches!(other.kind, RefKind::MethodCall { .. }) {
                    continue;
                }
                if !contains_point(&other.span, r.span.start) {
                    continue;
                }
                let area = (other.span.end.row.saturating_sub(other.span.start.row)) as u64
                    * 10_000
                    + other.span.end.column as u64;
                if area < enclosing_area {
                    enclosing = Some(other);
                    enclosing_area = area;
                }
            }
            let Some(call) = enclosing else { continue };
            let Some(ty) = self.method_call_invocant_type(call, module_index) else {
                continue;
            };
            let Some(p) = ty.as_parametric() else { continue };
            let Some(o) = p.method_arg_owner(&call.target_name) else { continue };
            owner_fixes.push((i, o));
        }
        for (i, o) in owner_fixes {
            if let RefKind::HashKeyAccess { ref mut owner, .. } = self.refs[i].kind {
                *owner = Some(o);
            }
        }
    }


    /// Rebuild all derived indices after deserialization.
    /// Idempotent: safe to call on a freshly deserialized `FileAnalysis` whose
    /// index fields were zeroed by `#[serde(skip, default)]`.
    pub fn after_deserialize(&mut self) {
        // Clear first in case this is called on a populated FileAnalysis.
        self.scope_starts.clear();
        self.symbols_by_name.clear();
        self.symbols_by_scope.clear();
        self.refs_by_name.clear();
        self.refs_by_target.clear();
        self.call_ref_by_start.clear();
        self.build_indices();
    }

    fn build_indices(&mut self) {
        // Scope starts — sorted for binary search
        self.scope_starts = self.scopes.iter()
            .map(|s| (s.span.start, s.id))
            .collect();
        self.scope_starts.sort_by_key(|(p, _)| (p.row, p.column));

        // Symbols by name
        for sym in &self.symbols {
            self.symbols_by_name
                .entry(sym.name.clone())
                .or_default()
                .push(sym.id);
        }

        // Symbols by scope
        for sym in &self.symbols {
            self.symbols_by_scope
                .entry(sym.scope)
                .or_default()
                .push(sym.id);
        }

        // Phase 5: link HashKeyAccess refs to their HashKeyDef symbols whenever
        // the owner is already resolved (the builder's pre-pass handled type
        // constraints + variable identity + call-binding fixups). With this
        // link, `refs_to_symbol(def_id)` returns all accesses in O(1), which
        // is what references, rename, and highlights consume.
        let hashkey_defs: HashMap<(&str, &HashKeyOwner), SymbolId> = self.symbols.iter()
            .filter_map(|sym| {
                if let SymbolDetail::HashKeyDef { owner, .. } = &sym.detail {
                    Some(((sym.name.as_str(), owner), sym.id))
                } else {
                    None
                }
            })
            .collect();
        let mut hashkey_resolutions: Vec<(usize, SymbolId)> = Vec::new();
        for (i, r) in self.refs.iter().enumerate() {
            if r.resolves_to.is_some() {
                continue;
            }
            if let RefKind::HashKeyAccess { owner: Some(owner), .. } = &r.kind {
                if let Some(&sid) = hashkey_defs.get(&(r.target_name.as_str(), owner)) {
                    hashkey_resolutions.push((i, sid));
                }
            }
        }
        for (idx, sid) in hashkey_resolutions {
            self.refs[idx].resolves_to = Some(sid);
        }

        // Link DispatchCall refs → Handler symbols by (owner, name). A
        // DispatchCall whose owner couldn't be resolved at build time (e.g.
        // `$obj->emit('x')` where `$obj` type isn't known yet) stays
        // unlinked here and may be re-resolved by enrichment when the
        // cross-file receiver type becomes known.
        //
        // Unlike hash keys, multiple Handlers with the same (owner, name)
        // legitimately coexist (stacked registrations) — we link the ref
        // to the *first* def found so `resolves_to` has a single target,
        // and rely on `refs_to_symbol` walking all stacked defs separately
        // for features like references/rename.
        let handler_defs: HashMap<(&str, &HandlerOwner), SymbolId> = self.symbols.iter()
            .filter_map(|sym| {
                if let SymbolDetail::Handler { owner, .. } = &sym.detail {
                    Some(((sym.name.as_str(), owner), sym.id))
                } else {
                    None
                }
            })
            .collect();
        let mut handler_resolutions: Vec<(usize, SymbolId)> = Vec::new();
        for (i, r) in self.refs.iter().enumerate() {
            if r.resolves_to.is_some() { continue; }
            if let RefKind::DispatchCall { owner: Some(owner), .. } = &r.kind {
                if let Some(&sid) = handler_defs.get(&(r.target_name.as_str(), owner)) {
                    handler_resolutions.push((i, sid));
                }
            }
        }
        for (idx, sid) in handler_resolutions {
            self.refs[idx].resolves_to = Some(sid);
        }

        // Refs by target name, and refs by resolved target SymbolId (phase 5).
        // Same loop populates the start-point → call-ref-idx index
        // used by `method_call_invocant_class` to chase chain
        // receivers. Only MethodCall (whose span covers the whole
        // call expression) and FunctionCall (whose span covers just
        // the function-name node, but whose start point still
        // matches the outer call's invocant_span.start) refs go in.
        for (i, r) in self.refs.iter().enumerate() {
            self.refs_by_name
                .entry(r.target_name.clone())
                .or_default()
                .push(i);
            if let Some(sym_id) = r.resolves_to {
                self.refs_by_target.entry(sym_id).or_default().push(i);
            }
            if matches!(r.kind, RefKind::MethodCall { .. } | RefKind::FunctionCall { .. }) {
                // First write wins. Method-call refs are visited
                // outer-first by the walker (the outer call site is
                // emitted before recursing into its receiver), so
                // for a chain like `Foo->new->m` the outer `m` ref
                // would land at start point of `Foo`. Insert with
                // `or_insert(i)` and rely on the inner receiver
                // being visited later — but for FunctionCall there
                // is no outer clash because chains-of-function-calls
                // don't have the same shape. To keep the inner
                // receiver as the lookup target, prefer overwriting
                // when the new ref has a *smaller* span (closer to
                // the actual receiver).
                let cur = self.call_ref_by_start.get(&r.span.start).copied();
                let take = match cur {
                    None => true,
                    Some(prev) => {
                        let prev_span = self.refs[prev].span;
                        // Smaller span (closer to the receiver) wins.
                        // Tie-breaker: prefer FunctionCall over MethodCall
                        // when at the same start, since FunctionCall is
                        // narrower (just the function-name span).
                        let new_smaller = (r.span.end.row, r.span.end.column)
                            < (prev_span.end.row, prev_span.end.column);
                        new_smaller
                    }
                };
                if take {
                    self.call_ref_by_start.insert(r.span.start, i);
                }
            }
        }
    }

    /// All refs that resolve to this symbol — O(1) lookup via the index.
    /// Callers typically combine this with a kind filter.
    pub fn refs_to_symbol(&self, sym_id: SymbolId) -> &[usize] {
        self.refs_by_target.get(&sym_id).map(|v| v.as_slice()).unwrap_or(&[])
    }

    // ---- Query methods ----

    /// Find the innermost scope containing a point.
    pub fn scope_at(&self, point: Point) -> Option<ScopeId> {
        let mut best: Option<(ScopeId, usize)> = None; // (id, span_size)
        for scope in &self.scopes {
            if contains_point(&scope.span, point) {
                let size = span_size(&scope.span);
                if best.is_none() || size <= best.unwrap().1 {
                    best = Some((scope.id, size));
                }
            }
        }
        best.map(|(id, _)| id)
    }

    /// Walk the scope chain from a scope upward to file root.
    pub fn scope_chain(&self, start: ScopeId) -> Vec<ScopeId> {
        let mut chain = Vec::new();
        let mut current = Some(start);
        while let Some(id) = current {
            chain.push(id);
            current = self.scopes[id.0 as usize].parent;
        }
        chain
    }

    /// Get the scope struct by ID.
    pub fn scope(&self, id: ScopeId) -> &Scope {
        &self.scopes[id.0 as usize]
    }

    /// Get the symbol struct by ID.
    pub fn symbol(&self, id: SymbolId) -> &Symbol {
        &self.symbols[id.0 as usize]
    }

    /// Find all symbols visible at a point (walks scope chain).
    pub fn visible_symbols(&self, point: Point) -> Vec<&Symbol> {
        let scope = match self.scope_at(point) {
            Some(s) => s,
            None => return Vec::new(),
        };
        let chain = self.scope_chain(scope);
        let mut result = Vec::new();
        for scope_id in &chain {
            if let Some(sym_ids) = self.symbols_by_scope.get(scope_id) {
                for sid in sym_ids {
                    let sym = &self.symbols[sid.0 as usize];
                    // Symbol must be declared before the point (or be a sub/package/class)
                    if sym.span.start <= point || matches!(sym.kind, SymKind::Sub | SymKind::Method | SymKind::Package | SymKind::Class) {
                        result.push(sym);
                    }
                }
            }
        }
        result
    }

    /// Resolve a variable name to its declaration at a given point.
    /// Returns the innermost-scope match (Perl lexical scoping).
    pub fn resolve_variable(&self, name: &str, point: Point) -> Option<&Symbol> {
        let scope = self.scope_at(point)?;
        let chain = self.scope_chain(scope);
        for scope_id in &chain {
            if let Some(sym_ids) = self.symbols_by_scope.get(scope_id) {
                for sid in sym_ids {
                    let sym = &self.symbols[sid.0 as usize];
                    if sym.name == name
                        && matches!(sym.kind, SymKind::Variable | SymKind::Field)
                        && sym.span.start <= point
                    {
                        return Some(sym);
                    }
                }
            }
        }
        None
    }

    /// Raw Variable+InferredType lookup — returns the latest in-scope
    /// witness for `var_name` before `point`, with no framework rules,
    /// no branch fold, no narrowing.
    ///
    /// **NOT the canonical type query.** Use `inferred_type_via_bag`
    /// for any consumer that wants the answer the rest of the LSP
    /// uses — this method exists for two narrow purposes:
    ///
    /// 1. Internal "did we explicitly assign a type to this variable
    ///    yet?" checks (e.g. `resolve_method_call_types` early-out)
    ///    that need the bare seed state, not the bag's reduced answer
    ///    (which can be non-`None` from rep observations alone).
    /// 2. Tests that assert on raw seed state.
    ///
    /// If you find a third use case, prefer `inferred_type_via_bag`
    /// and only fall back here if you have a concrete reason that
    /// would survive a code review.
    pub fn inferred_type(&self, var_name: &str, point: Point) -> Option<&InferredType> {
        use crate::witnesses::{WitnessAttachment, WitnessPayload};
        let mut best: Option<(&InferredType, Point)> = None;
        for w in self.witnesses.all() {
            let WitnessAttachment::Variable { name, scope } = &w.attachment else { continue };
            if name != var_name { continue; }
            let scope_obj = &self.scopes[scope.0 as usize];
            if !contains_point(&scope_obj.span, point) { continue; }
            if w.span.start > point { continue; }
            let WitnessPayload::InferredType(t) = &w.payload else { continue };
            if best.is_none() || w.span.start > best.unwrap().1 {
                best = Some((t, w.span.start));
            }
        }
        best.map(|(t, _)| t)
    }

    /// Part 6/7 — query the witness bag via the reducer registry for
    /// a variable at a point, falling back to the legacy
    /// `inferred_type()` when the bag has nothing. Returns owned
    /// `InferredType` because the reducer may synthesize a value not
    /// stored anywhere.
    ///
    /// The bag is the canonical store: `push_type_constraint` (TC
    /// shape), `call_bindings` propagation, framework accessor
    /// synthesis, and cross-file enrichment all push witnesses here.
    /// `inferred_type` reads the same Variable+InferredType slice
    /// without applying reducer rules.
    pub fn inferred_type_via_bag(&self, var_name: &str, point: Point) -> Option<InferredType> {
        let scope = self.scope_at(point)?;
        crate::witnesses::query_variable_type(
            &self.witnesses,
            &self.scopes,
            &self.package_framework,
            var_name,
            scope,
            point,
        )
    }

    /// Part 6/7 — resolve the inferred return type of a method call
    /// by its ref index (from `refs`). Uses the Expression-attached
    /// witnesses seeded by the builder; the `return_of` closure looks
    /// up `sub_return_type` by name, resolving a `FirstParam`
    /// invocant to the method's enclosing class.
    ///
    /// This is the piece that makes `$r->get('/x')->to(...)` fold
    /// across chain hops without needing an intermediate variable.
    /// Resolve the inferred return type of a method call by its
    /// ref index. Reads `Expression(refidx)` witnesses seeded by
    /// the builder; `module_index` lets cross-file MethodOnClass
    /// edges (e.g. `$r->get(...)` where `get` lives in
    /// `Mojolicious::Routes`) chase through the registry's
    /// recursive walker.
    #[allow(dead_code)] // documented type-query entry point; CLAUDE.md
    pub fn method_call_return_type_via_bag(
        &self,
        ref_idx: usize,
        module_index: Option<&ModuleIndex>,
    ) -> Option<InferredType> {
        use crate::witnesses::{
            BagContext, FrameworkFact, ReducedValue, ReducerQuery, ReducerRegistry,
            WitnessAttachment,
        };

        let att = WitnessAttachment::Expression(crate::witnesses::RefIdx(ref_idx as u32));
        let reg = ReducerRegistry::with_defaults();
        let ctx = BagContext {
            scopes: &self.scopes,
            package_framework: &self.package_framework,
            module_index,
            package_parents: &self.package_parents,
            };
        let q = ReducerQuery {
            attachment: &att,
            point: None,
            framework: FrameworkFact::Plain,
            arity_hint: None,
            receiver: None,
            context: Some(&ctx),
        };
        match reg.query(&self.witnesses, &q) {
            ReducedValue::Type(t) => {
                // If the return is FirstParam, surface it as the
                // ClassName of the enclosing package — callers chain
                // against a concrete class, not a role.
                if let InferredType::FirstParam { package } = t {
                    Some(InferredType::ClassName(package))
                } else {
                    Some(t)
                }
            }
            _ => None,
        }
    }

    /// Part 6b — resolve a sub's return type at a call site given
    /// the caller's arg count. Queries the arity-dispatch reducer; if
    /// no arity fact exists, falls back to the declared /
    /// inferred-from-returns `sub_return_type`.
    ///
    /// `arity` is the number of *additional* args passed after the
    /// invocant on methods (or simply the arg count for plain subs).
    pub fn sub_return_type_at_arity(
        &self,
        sub_name: &str,
        arity: Option<u32>,
    ) -> Option<InferredType> {
        let ctx = crate::witnesses::BagContext {
            scopes: &self.scopes,
            package_framework: &self.package_framework,
            module_index: None,
            package_parents: &self.package_parents,
            };
        crate::witnesses::query_sub_return_type(
            &self.witnesses,
            &self.symbols,
            sub_name,
            arity,
            None,
            Some(&ctx),
        )
    }

    /// Part 1 — list hash keys that have been written to on instances
    /// of `class`. Powers dynamic-key completion: `$self->{` completes
    /// with both `has`-declared keys and keys observed as write
    /// targets across the class's methods.
    #[allow(dead_code)] // documented type-query entry point; CLAUDE.md
    pub fn mutated_keys_on_class(&self, class: &str) -> Vec<String> {
        use crate::witnesses::{WitnessAttachment, WitnessPayload};
        let mut out: Vec<String> = Vec::new();
        for w in self.witnesses.all() {
            if let WitnessAttachment::HashKey { owner, name } = &w.attachment {
                let matches_class = match owner {
                    HashKeyOwner::Class(c) if c == class => true,
                    HashKeyOwner::Sub { package: Some(p), .. } if p == class => true,
                    _ => false,
                };
                if !matches_class {
                    continue;
                }
                if matches!(
                    &w.payload,
                    WitnessPayload::Fact { family, .. } if family == "mutation"
                ) && !out.contains(name)
                {
                    out.push(name.clone());
                }
            }
        }
        out
    }

    /// Get the return type of a named sub/method (local definitions
    /// only). Routes through the bag — `Symbol(sid)` writeback witness
    /// is the post-field-deletion authority. Returns owned because
    /// the value is synthesized by the reducer, not stored.
    pub fn sub_return_type_local(&self, name: &str) -> Option<InferredType> {
        for sym in &self.symbols {
            if sym.name == name && matches!(sym.kind, SymKind::Sub | SymKind::Method) {
                if let Some(t) = self.symbol_return_type_via_bag(sym.id, None) {
                    return Some(t);
                }
            }
        }
        None
    }

    /// Get the return type of a named sub/method. Local definitions
    /// first (via the bag's `Symbol(sym_id)` writeback), then imported
    /// sub returns (resolved lazily through `query_sub_return_type`'s
    /// walk of `module_index.find_exporters` into the cached module's
    /// own `Symbol(_)` witnesses).
    #[allow(dead_code)] // public type-query API; used by tooling/tests
    pub fn sub_return_type(&self, name: &str) -> Option<InferredType> {
        self.sub_return_type_at_arity(name, None)
    }

    /// Provenance of a symbol's return type — `Inferred` by default,
    /// `PluginOverride` for plugin-declared overrides. Always returns
    /// a value (never `None`) so debug tooling can ask "where did this
    /// come from?" without branching on missingness.
    #[allow(dead_code)] // debug-introspection accessor; consumed by tests
    pub fn return_type_provenance(&self, sym_id: SymbolId) -> TypeProvenance {
        self.type_provenance
            .get(&sym_id)
            .cloned()
            .unwrap_or(TypeProvenance::Inferred)
    }

    /// Resolve call bindings for imported functions and inject
    /// synthetic HashKeyDef symbols. Walks `self.imports` against
    /// `module_index` to derive each imported sub's return type and
    /// hash-key set inline — `build_imported_return_types` and the
    /// `imported_returns` / `imported_hash_keys` parameters were
    /// killed in D3 since the bag now reaches cross-file `Symbol(_)`
    /// witnesses through `BagContext.module_index` directly. Call
    /// after building, when the module index is available.
    pub fn enrich_imported_types_with_keys(
        &mut self,
        module_index: Option<&ModuleIndex>,
    ) {
        // Truncate back to baseline so repeated enrichment doesn't
        // accumulate duplicates. Enrichment pushes Variable witnesses
        // via `push_type_constraint` and synthetic symbols + witnesses
        // for imported-hash-key completion.
        self.symbols.truncate(self.base_symbol_count);
        self.witnesses.truncate(self.base_witness_count);

        // Build the import → exported-name map inline from
        // `self.imports` + `module_index`. `imported_hash_keys` is
        // the only piece still needed by enrichment; imported return
        // types are reached lazily by `query_sub_return_type` walking
        // `module_index.find_exporters(name)`.
        let mut imported_hash_keys: HashMap<String, Vec<String>> = HashMap::new();
        let mut imported_returns: HashMap<String, InferredType> = HashMap::new();
        if let Some(idx) = module_index {
            for import in &self.imports {
                let Some(cached) = idx.get_cached(&import.module_name) else { continue };
                for sym in &cached.analysis.symbols {
                    if !matches!(sym.kind, SymKind::Sub | SymKind::Method) {
                        continue;
                    }
                    if !cached.analysis.export.iter().any(|n| n == &sym.name)
                        && !cached.analysis.export_ok.iter().any(|n| n == &sym.name)
                    {
                        continue;
                    }
                    if matches!(sym.detail, SymbolDetail::Sub { .. }) {
                        if let Some(ty) = cached.analysis.symbol_return_type_via_bag(sym.id, None) {
                            imported_returns.insert(sym.name.clone(), ty);
                        }
                    }
                    if let Some(sub_info) = cached.sub_info(&sym.name) {
                        let hk = sub_info.hash_keys();
                        if !hk.is_empty() {
                            imported_hash_keys.insert(sym.name.clone(), hk.to_vec());
                        }
                    }
                }
            }
        }

        // Push call-binding TCs for imports whose return type the
        // cross-file scan resolved. Same shape the local-sub path
        // produces (`propagate_call_bindings_to_constraints`).
        let mut to_push: Vec<TypeConstraint> = Vec::new();
        for binding in &self.call_bindings {
            if self.sub_return_type_local(&binding.func_name).is_some()
                || builtin_return_type(&binding.func_name).is_some()
            {
                continue;
            }
            if let Some(rt) = imported_returns.get(&binding.func_name) {
                to_push.push(TypeConstraint {
                    variable: binding.variable.clone(),
                    scope: binding.scope,
                    constraint_span: binding.span,
                    inferred_type: rt.clone(),
                });
            }
        }
        for tc in to_push {
            self.push_type_constraint(tc);
        }

        // Inject synthetic HashKeyDef symbols for imported functions' hash keys.
        // Imported subs have no local package — package=None mirrors the
        // HashKeyAccess fixup's default for imported bindings.
        for (func_name, keys) in &imported_hash_keys {
            let owner = HashKeyOwner::Sub { package: None, name: func_name.clone() };
            for key_name in keys {
                let id = SymbolId(self.symbols.len() as u32);
                let zero_span = Span {
                    start: Point { row: 0, column: 0 },
                    end: Point { row: 0, column: 0 },
                };
                self.symbols.push(Symbol {
                    id,
                    name: key_name.clone(),
                    kind: SymKind::HashKeyDef,
                    span: zero_span,
                    selection_span: zero_span,
                    scope: ScopeId(0),
                    package: None,
                    detail: SymbolDetail::HashKeyDef {
                        owner: owner.clone(),
                        is_dynamic: false,
                    },
                    namespace: Namespace::Language,
                    outline_label: None,
                });
            }
        }

        // HashKeyAccess owner fixup for imports: the builder's pass
        // only ran for bindings where the func's return type was
        // known at build time. Cross-file return types come in here,
        // so the consumer-side `$cfg = Lib::get_config(); $cfg->{host}`
        // access gets its owner set to Sub{None, "get_config"},
        // matching the synthetic HashKeyDef we just injected.
        let imported_keyed_subs: std::collections::HashSet<String> = imported_hash_keys
            .keys()
            .cloned()
            .collect();
        let binding_by_var: std::collections::HashMap<String, String> = self.call_bindings.iter()
            .filter_map(|b| {
                let bare = b.func_name.rsplit("::").next().unwrap_or(&b.func_name).to_string();
                if imported_keyed_subs.contains(&bare) {
                    Some((b.variable.clone(), bare))
                } else {
                    None
                }
            })
            .collect();
        if !binding_by_var.is_empty() {
            for r in &mut self.refs {
                if let RefKind::HashKeyAccess { ref var_text, ref mut owner } = r.kind {
                    if owner.is_some() && !matches!(owner, Some(HashKeyOwner::Variable { .. })) {
                        continue;
                    }
                    if let Some(func_name) = binding_by_var.get(var_text.as_str()) {
                        if let Some(keys) = imported_hash_keys.get(func_name) {
                            if keys.iter().any(|k| k == &r.target_name) {
                                *owner = Some(HashKeyOwner::Sub {
                                    package: None,
                                    name: func_name.clone(),
                                });
                                r.resolves_to = None;
                            }
                        }
                    }
                }
            }
        }

        // Deferred HashKeyAccess owner fix for chain-receiver
        // method calls — see `fix_chain_receiver_hash_key_owners`.
        // Enrichment runs it with module_index so cross-file
        // receiver types resolve; the same routine runs from
        // `finalize_post_walk` with module_index=None for the
        // in-file-resolvable case (chain recursion via
        // `call_ref_by_start` doesn't need module_index).
        self.fix_chain_receiver_hash_key_owners(module_index);

        // Cross-file inheritance edges. Local writeback emits
        // `MethodOnClass(child, m) → Edge(MethodOnClass(parent, m))`
        // for every method `m` declared on a *local* parent. When
        // the parent class lives in another file (or its methods
        // do, via further parent chaining), we read the cached
        // analysis here and project the same edge shape into the
        // local bag. The registry's edge-chase then follows
        // `MethodOnClass(child, m) → MethodOnClass(parent_cross, m)`
        // and re-enters the cached parent's bag via the existing
        // cross-file primary lookup in `query_rec`.
        if let Some(idx) = module_index {
            use crate::witnesses::{Witness, WitnessAttachment, WitnessPayload, WitnessSource};
            let zero = Span {
                start: Point { row: 0, column: 0 },
                end: Point { row: 0, column: 0 },
            };
            // Snapshot to avoid double-mutable-borrow when pushing.
            let parents_snapshot: Vec<(String, Vec<String>)> = self
                .package_parents
                .iter()
                .map(|(c, ps)| (c.clone(), ps.clone()))
                .collect();
            for (child, parents) in &parents_snapshot {
                // First-parent-wins per method, mirroring Perl's
                // default DFS-MRO. Aligned with the local-parent
                // edge emission in `write_back_sub_return_types`.
                let mut emitted_for_child: std::collections::HashSet<String> =
                    std::collections::HashSet::new();
                for parent in parents {
                    if parent == child {
                        continue;
                    }
                    let Some(cached) = idx.get_cached(parent) else { continue };
                    for sym in &cached.analysis.symbols {
                        if sym.package.as_deref() != Some(parent.as_str()) {
                            continue;
                        }
                        if !matches!(sym.kind, SymKind::Sub | SymKind::Method) {
                            continue;
                        }
                        if !emitted_for_child.insert(sym.name.clone()) {
                            continue;
                        }
                        self.witnesses.push(Witness {
                            attachment: WitnessAttachment::MethodOnClass {
                                class: child.clone(),
                                name: sym.name.clone(),
                            },
                            source: WitnessSource::Enrichment("inheritance_cross".to_string()),
                            payload: WitnessPayload::Edge(WitnessAttachment::MethodOnClass {
                                class: parent.clone(),
                                name: sym.name.clone(),
                            }),
                            span: zero,
                        });
                    }
                }
            }
        }

        self.resolve_method_call_types(module_index);
        self.rebuild_enrichment_indices();
    }

    /// Resolve method call bindings to type constraints.
    /// Called in local post-pass (None) and cross-file enrichment (Some(module_index)).
    fn resolve_method_call_types(&mut self, module_index: Option<&ModuleIndex>) {
        let bindings = self.method_call_bindings.clone();
        for binding in &bindings {
            // Skip if this variable already has a type at this point
            if self.inferred_type(&binding.variable, binding.span.start).is_some() {
                continue;
            }

            // Resolve invocant to class name
            let class_name = self.resolve_invocant_class(
                &binding.invocant_var,
                binding.scope,
                binding.span.start,
            );

            if let Some(cn) = class_name {
                if let Some(rt) = self.find_method_return_type(&cn, &binding.method_name, module_index, None) {
                    self.push_type_constraint(TypeConstraint {
                        variable: binding.variable.clone(),
                        scope: binding.scope,
                        constraint_span: binding.span,
                        inferred_type: rt,
                    });
                }
            }
        }
    }

    /// Push a `TypeConstraint` shape into the witness bag — a Variable
    /// `InferredType` witness plus a class-assertion observation when
    /// the type is a class identity. The bag is the single store; this
    /// helper exists so callers can keep the legible "I'm seeding a
    /// type constraint on $X" call shape rather than open-coding the
    /// witness construction. Builder has a parallel helper that does
    /// the same thing during the walk.
    pub(crate) fn push_type_constraint(&mut self, tc: TypeConstraint) {
        use crate::witnesses::{
            TypeObservation, Witness, WitnessAttachment, WitnessPayload, WitnessSource,
        };
        let TypeConstraint { variable, scope, constraint_span: span, inferred_type: ty } = tc;
        self.witnesses.push(Witness {
            attachment: WitnessAttachment::Variable { name: variable.clone(), scope },
            source: WitnessSource::Builder("type_constraint".into()),
            payload: WitnessPayload::InferredType(ty.clone()),
            span: Span { start: span.start, end: span.start },
        });
        match ty {
            InferredType::ClassName(n) => {
                self.witnesses.push(Witness {
                    attachment: WitnessAttachment::Variable { name: variable, scope },
                    source: WitnessSource::Builder("type_constraint".into()),
                    payload: WitnessPayload::Observation(TypeObservation::ClassAssertion(n)),
                    span,
                });
            }
            InferredType::FirstParam { package } => {
                self.witnesses.push(Witness {
                    attachment: WitnessAttachment::Variable { name: variable, scope },
                    source: WitnessSource::Builder("type_constraint".into()),
                    payload: WitnessPayload::Observation(TypeObservation::FirstParamInMethod {
                        package,
                    }),
                    span,
                });
            }
            _ => {}
        }
    }

    /// Rebuild indices affected by enrichment (type constraints + symbols +
    /// the phase-5 refs_by_target + HashKeyAccess linkage).
    ///
    /// Enrichment injects synthetic HashKeyDef symbols for imported subs and
    /// clears `resolves_to` on HashKeyAccess refs that now have a matching
    /// owner. This method re-runs the same `(target_name, owner)` linker that
    /// `build_indices` uses, so `refs_by_target` stays accurate after a
    /// cross-file hash-key binding resolves.
    fn rebuild_enrichment_indices(&mut self) {
        self.symbols_by_name.clear();
        self.symbols_by_scope.clear();
        for sym in &self.symbols {
            self.symbols_by_name
                .entry(sym.name.clone())
                .or_default()
                .push(sym.id);
            self.symbols_by_scope
                .entry(sym.scope)
                .or_default()
                .push(sym.id);
        }

        // Re-link HashKeyAccess refs to (possibly newly-injected) HashKeyDef
        // symbols, mirroring build_indices's phase-5 logic.
        let hashkey_defs: HashMap<(String, HashKeyOwner), SymbolId> = self.symbols.iter()
            .filter_map(|sym| {
                if let SymbolDetail::HashKeyDef { owner, .. } = &sym.detail {
                    Some(((sym.name.clone(), owner.clone()), sym.id))
                } else {
                    None
                }
            })
            .collect();
        let mut hashkey_resolutions: Vec<(usize, SymbolId)> = Vec::new();
        for (i, r) in self.refs.iter().enumerate() {
            if r.resolves_to.is_some() {
                continue;
            }
            if let RefKind::HashKeyAccess { owner: Some(owner), .. } = &r.kind {
                if let Some(&sid) = hashkey_defs.get(&(r.target_name.clone(), owner.clone())) {
                    hashkey_resolutions.push((i, sid));
                }
            }
        }
        for (idx, sid) in hashkey_resolutions {
            self.refs[idx].resolves_to = Some(sid);
        }

        // Refresh refs_by_name + refs_by_target against the current refs.
        self.refs_by_name.clear();
        self.refs_by_target.clear();
        for (i, r) in self.refs.iter().enumerate() {
            self.refs_by_name
                .entry(r.target_name.clone())
                .or_default()
                .push(i);
            if let Some(sym_id) = r.resolves_to {
                self.refs_by_target.entry(sym_id).or_default().push(i);
            }
        }
    }

    /// Resolve the type of an arbitrary CST expression node.
    ///
    /// Recursive tree walk that composes existing atoms:
    /// - `scalar` → `inferred_type(var_text, point)`
    /// - bareword (class name) → `Object(ClassName)`
    /// - `method_call_expression` → resolve invocant → find method → return type
    /// - `function_call_expression` → `sub_return_type(name)`
    /// - `hash_element_expression` → resolve base (for chaining)
    ///
    /// Used at query time (completion, goto-def, hover) — not during the build walk.
    pub fn resolve_expression_type(
        &self,
        node: tree_sitter::Node,
        source: &[u8],
        module_index: Option<&ModuleIndex>,
    ) -> Option<InferredType> {
        let point = node.start_position();
        match node.kind() {
            "scalar" => {
                let text = node.utf8_text(source).ok()?;
                // Route scalar-type resolution through the witness
                // bag so framework / branch / arity rules refine the
                // answer. Legacy `inferred_type` is used as fallback.
                self.inferred_type_via_bag(text, point)
            }
            "package" | "bareword" => {
                // Bareword = class name
                let text = node.utf8_text(source).ok()?;
                Some(InferredType::ClassName(text.to_string()))
            }
            "array_element_expression" => {
                // `$arr[N]` — look up `@arr`'s Sequence shape via the
                // bag, project the index. The bag answer is whatever
                // the walker's last `push` / `my @arr = (...)`
                // contribution left on `Variable{"@arr", scope}`.
                let arr = node.child_by_field_name("array")?;
                let name = arr
                    .named_child(0)
                    .and_then(|n| n.utf8_text(source).ok())?;
                let idx_node = node.child_by_field_name("index")?;
                let idx: i32 = idx_node.utf8_text(source).ok()?.parse().ok()?;
                let arr_var = format!("@{}", name);
                self.inferred_type_via_bag(&arr_var, point)
                    .and_then(|t| t.element_at(idx).cloned())
            }
            "method_call_expression" => {
                let invocant_node = node.child_by_field_name("invocant")?;
                let invocant_type = self.resolve_expression_type(invocant_node, source, module_index)?;
                let class_name = invocant_type.class_name()?;
                let method_name = node.child_by_field_name("method")?;
                let method_text = method_name.utf8_text(source).ok()?;
                // Constructor call returns Object(ClassName)
                if method_text == "new" {
                    return Some(InferredType::ClassName(class_name.to_string()));
                }
                let arg_count = self.count_call_args(node);
                self.find_method_return_type(class_name, method_text, module_index, Some(arg_count))
            }
            "function_call_expression" | "ambiguous_function_call_expression" => {
                let func_node = node.child_by_field_name("function")?;
                let name = func_node.utf8_text(source).ok()?;
                // Route through the arity-aware helper so fluent
                // arity dispatch (`return X unless @_`) can pick the
                // right branch when the caller's arg count is known.
                let arg_count = self.count_call_args(node) as u32;
                self.sub_return_type_at_arity(name, Some(arg_count))
                    .or_else(|| builtin_return_type(name))
            }
            "func1op_call_expression" | "func0op_call_expression" => {
                let name = node.child(0)?.utf8_text(source).ok()?;
                builtin_return_type(name)
            }
            "hash_element_expression" => {
                // For chaining: resolve the base expression
                let base = node.named_child(0)?;
                self.resolve_expression_type(base, source, module_index)
            }
            _ => None,
        }
    }

    /// Resolve the hash key owner from a tree node at a given point.
    ///
    /// Finds the enclosing `hash_element_expression`, resolves its base expression
    /// type, and returns the appropriate `HashKeyOwner`. Used by goto-def,
    /// references, completion, and highlights for chained hash access like
    /// `$calc->get_self->get_config->{host}`.
    pub fn resolve_hash_owner_from_tree(
        &self,
        tree: &tree_sitter::Tree,
        source: &[u8],
        point: Point,
        module_index: Option<&ModuleIndex>,
    ) -> Option<HashKeyOwner> {
        let hash_elem = tree.root_node()
            .descendant_for_point_range(point, point)
            .and_then(|n| find_ancestor(n, "hash_element_expression"))?;
        let base = hash_elem.named_child(0)?;
        let ty = self.resolve_expression_type(base, source, module_index)?;

        // Extract the function/method name for Sub owner
        let sub_name = match base.kind() {
            "method_call_expression" => base.child_by_field_name("method")
                .and_then(|n| n.utf8_text(source).ok())
                .map(|s| s.to_string()),
            "function_call_expression" | "ambiguous_function_call_expression" =>
                base.child_by_field_name("function")
                    .and_then(|n| n.utf8_text(source).ok())
                    .map(|s| s.to_string()),
            _ => None,
        };

        if let Some(name) = sub_name {
            // Try each package the sub might belong to. In practice, the sub
            // is either defined locally (package comes from its Symbol) or
            // imported (package = None, matching the enrichment synthetic def).
            let mut candidate_owners: Vec<HashKeyOwner> = Vec::new();
            for sym in &self.symbols {
                if (sym.kind == SymKind::Sub || sym.kind == SymKind::Method) && sym.name == name {
                    candidate_owners.push(HashKeyOwner::Sub {
                        package: sym.package.clone(),
                        name: name.clone(),
                    });
                }
            }
            // Fallback: None-package owner (matches imported synthetic defs).
            candidate_owners.push(HashKeyOwner::Sub { package: None, name: name.clone() });
            for sub_owner in candidate_owners {
                if !self.hash_key_defs_for_owner(&sub_owner).is_empty() {
                    return Some(sub_owner);
                }
            }
        }

        // Hash-key context: read `hash_key_class()` (= row-class
        // for Parametric, dispatch class else) instead of bare
        // `class_name()`. CLAUDE.md invariant #10 — never special-
        // case for a particular shape; the type already carries
        // the per-axis answer. For non-Parametric this is
        // equivalent to `class_name()`; for Parametric it's the
        // crucial narrowing to the type's row-class arg.
        if let Some(cn) = ty.hash_key_class() {
            return Some(HashKeyOwner::Class(cn.to_string()));
        }

        None
    }

    /// Check if cursor is on a bareword or string inside call arguments.
    /// Returns the text if so (could be a named arg key).
    fn call_arg_key_at(&self, tree: &tree_sitter::Tree, source: &[u8], point: Point) -> Option<String> {
        let node = tree.root_node().descendant_for_point_range(point, point)?;
        let key_node = match node.kind() {
            "autoquoted_bareword" => node,
            "string_literal" | "interpolated_string_literal" => node,
            _ => {
                let parent = node.parent()?;
                if matches!(parent.kind(), "string_literal" | "interpolated_string_literal") {
                    parent
                } else {
                    return None;
                }
            }
        };
        let text = key_node.utf8_text(source).ok()?;
        if (text.starts_with('\'') || text.starts_with('"')) && text.len() >= 2 {
            Some(text[1..text.len()-1].to_string())
        } else if text.starts_with('\'') || text.starts_with('"') {
            None
        } else {
            Some(text.to_string())
        }
    }

    /// Bag-routed query: "what does `Symbol(sym_id)` return at this
    /// arity?" Runs through the full reducer registry — Plugin
    /// overrides dominate, then arity dispatch, then `SubReturnReducer`
    /// (which claims plain writeback-pushed `InferredType` witnesses).
    /// Returns `None` when nothing in the bag answers.
    pub(crate) fn symbol_return_type_via_bag(
        &self,
        sym_id: SymbolId,
        arg_count: Option<usize>,
    ) -> Option<InferredType> {
        use crate::witnesses::{
            BagContext, FrameworkFact, ReducedValue, ReducerQuery, ReducerRegistry,
            WitnessAttachment,
        };
        let att = WitnessAttachment::Symbol(sym_id);
        let reg = ReducerRegistry::with_defaults();
        let ctx = BagContext {
            scopes: &self.scopes,
            package_framework: &self.package_framework,
            module_index: None,
            package_parents: &self.package_parents,
            };
        // Default the arity hint from the sym's own param count
        // when the caller didn't supply one. Symbol introspection
        // is naturally "what does THIS sym return," and the sym's
        // params count IS its native arity — Mojo writer (params=1)
        // answers its `(AtLeast(1), Receiver)` arm, getter (params=0)
        // answers its `(Empty, Concrete(_))` arm. Without this, a
        // writer's per-Symbol UnionOnArgs would be unmatched at a
        // None hint (AtLeast(1) doesn't match None) and the query
        // would silently return None.
        //
        // Default receiver = `ClassName(class)` so the writer's
        // `Receiver` placeholder evaluates to the natural fluent
        // answer at sym-introspection time.
        let resolved_arity = arg_count.map(|n| n as u32).or_else(|| {
            self.symbols
                .get(sym_id.0 as usize)
                .and_then(|s| match &s.detail {
                    SymbolDetail::Sub { params, .. } => Some(params.len() as u32),
                    _ => None,
                })
        });
        let receiver = self
            .symbols
            .get(sym_id.0 as usize)
            .and_then(|s| s.package.clone())
            .map(InferredType::ClassName);
        let q = ReducerQuery {
            attachment: &att,
            point: None,
            framework: FrameworkFact::Plain,
            arity_hint: resolved_arity,
            receiver,
            context: Some(&ctx),
        };
        match reg.query(&self.witnesses, &q) {
            ReducedValue::Type(t) => Some(t),
            _ => None,
        }
    }

    /// Find a method's return type within a class/package, walking
    /// inheritance. Thin wrapper that queries the bag's class-keyed
    /// `MethodOnClass{class, method}` attachment with the caller's
    /// `arg_count` as arity hint. Inheritance composes through
    /// `package_parents` (carried in `BagContext`); cross-file
    /// classes resolve via `module_index`. No procedural ancestor
    /// walk; no procedural overload picking — the registry's
    /// `ReturnExprReducer` claims `MethodOnClass + ReturnExpr` and
    /// the structural-walk code in `query_rec` handles MRO.
    pub(crate) fn find_method_return_type(
        &self,
        class_name: &str,
        method_name: &str,
        module_index: Option<&ModuleIndex>,
        arg_count: Option<usize>,
    ) -> Option<InferredType> {
        use crate::witnesses::{
            BagContext, FrameworkFact, ReducedValue, ReducerQuery, ReducerRegistry,
            WitnessAttachment,
        };
        let framework = self
            .package_framework
            .get(class_name)
            .copied()
            .unwrap_or(FrameworkFact::Plain);
        let att = WitnessAttachment::MethodOnClass {
            class: class_name.to_string(),
            name: method_name.to_string(),
        };
        let ctx = BagContext {
            scopes: &self.scopes,
            package_framework: &self.package_framework,
            module_index,
            package_parents: &self.package_parents,
        };
        // Default receiver = `ClassName(class_name)` so that
        // `ReturnExpr::Receiver` evaluates correctly for class-keyed
        // method-return queries that don't have a specific
        // call-site invocant — Mojo `has 'title'` writer's
        // Receiver evaluates to ClassName(Bar), DBIC `find`'s
        // RowOf(Receiver) wraps the Parametric (when one is
        // supplied via the `arg_count` Some path elsewhere). Same
        // policy as `query_sub_return_type`'s class-fallback rule.
        let q = ReducerQuery {
            attachment: &att,
            point: None,
            framework,
            arity_hint: arg_count.map(|n| n as u32),
            receiver: Some(InferredType::ClassName(class_name.to_string())),
            context: Some(&ctx),
        };
        let reg = ReducerRegistry::with_defaults();
        if let ReducedValue::Type(t) = reg.query(&self.witnesses, &q) {
            return Some(t);
        }
        None
    }

    /// Count arguments in a method/function call expression (excluding invocant).
    pub(crate) fn count_call_args(&self, node: tree_sitter::Node) -> usize {
        let args = match node.child_by_field_name("arguments") {
            Some(a) => a,
            None => return 0,
        };
        match args.kind() {
            "parenthesized_expression" | "list_expression" => args.named_child_count(),
            _ => 1, // single argument
        }
    }

    /// Find a `:param` field in a class by its bare name (without sigil).
    fn find_param_field(&self, class_name: &str, key: &str) -> Option<Span> {
        for sym in &self.symbols {
            if matches!(sym.kind, SymKind::Field) {
                if let SymbolDetail::Field { ref attributes, .. } = sym.detail {
                    if attributes.contains(&"param".to_string())
                        && self.symbol_in_class(sym.id, class_name)
                    {
                        if sym.bare_name() == key {
                            return Some(sym.selection_span);
                        }
                    }
                }
            }
        }
        None
    }

    /// Format a method completion detail string, appending return type if known.
    fn method_detail(
        &self,
        class_name: &str,
        method_name: &str,
        defining_class: Option<&str>,
        module_index: Option<&ModuleIndex>,
    ) -> String {
        let base = if let Some(dc) = defining_class {
            if dc != class_name {
                format!("{} (from {})", class_name, dc)
            } else {
                class_name.to_string()
            }
        } else {
            class_name.to_string()
        };
        if let Some(ref rt) = self.find_method_return_type(class_name, method_name, module_index, None) {
            // `opaque_return` lets the declaring plugin say "this
            // whole chain link is internal plumbing — don't render
            // the class name OR the return type". The chain still
            // resolves (find_method_return_type returned the proxy),
            // but the user doesn't see the proxy-class path at every
            // completion detail line. Plugin-declared; the core
            // never inspects names.
            //
            // Check both the completion context class AND the
            // defining class (when the method is inherited from a
            // parent): the plugin declares opacity on the symbol
            // where the method LIVES, which is the defining class
            // during a cross-class walk (e.g. Users inheriting the
            // helper from Mojolicious::Controller).
            let opaque = self.method_opaque_return_cross_file(class_name, method_name, module_index)
                || defining_class.is_some_and(|dc| {
                    self.method_opaque_return_cross_file(dc, method_name, module_index)
                });
            if opaque {
                return String::new();
            }
            format!("{}{}", base, format_inferred_type(&rt))
        } else {
            base
        }
    }

    /// Does the Method/Sub `method_name` on `class_name` opt out of
    /// rendering its return type at call sites? Plugin-declared via
    /// `opaque_return` on the symbol's detail. Walks both local
    /// symbols and any cross-file modules that emit content on the
    /// class (plugin helpers land in the file where the registration
    /// runs, not in the target class's own module).
    fn method_opaque_return(&self, class_name: &str, method_name: &str) -> bool {
        let check = |sym: &Symbol| -> bool {
            if sym.name != method_name { return false; }
            if !matches!(sym.kind, SymKind::Sub | SymKind::Method) { return false; }
            if sym.package.as_deref() != Some(class_name) { return false; }
            matches!(&sym.detail, SymbolDetail::Sub { opaque_return: true, .. })
        };
        for sym in &self.symbols {
            if check(sym) { return true; }
        }
        false
    }

    /// Cross-file-aware variant: used by `method_detail` during
    /// completion to decide whether to suppress the proxy chain in
    /// the detail string, even when the declaring plugin emitted the
    /// method from another file. Same contract as
    /// `method_opaque_return` otherwise.
    fn method_opaque_return_cross_file(
        &self,
        class_name: &str,
        method_name: &str,
        module_index: Option<&ModuleIndex>,
    ) -> bool {
        if self.method_opaque_return(class_name, method_name) {
            return true;
        }
        let Some(idx) = module_index else { return false };
        let mut found = false;
        idx.for_each_entity_bridged_to(class_name, |_cached, sym| {
            if found { return; }
            if sym.name != method_name { return; }
            if !matches!(sym.kind, SymKind::Sub | SymKind::Method) { return; }
            if matches!(&sym.detail, SymbolDetail::Sub { opaque_return: true, .. }) {
                found = true;
            }
        });
        found
    }

    /// Complete methods for a known class name, walking the inheritance chain.
    pub fn complete_methods_for_class(
        &self,
        class_name: &str,
        module_index: Option<&ModuleIndex>,
    ) -> Vec<CompletionCandidate> {
        let mut candidates = Vec::new();
        let mut seen_names: HashSet<String> = HashSet::new();

        // Check for class definition → implicit new
        for sym in &self.symbols {
            if matches!(sym.kind, SymKind::Class) && sym.name == class_name {
                candidates.push(CompletionCandidate {
                    label: "new".to_string(),
                    kind: SymKind::Method,
                    detail: Some(self.method_detail(class_name, "new", None, module_index)),
                    insert_text: None,
                    sort_priority: PRIORITY_LOCAL,
                    additional_edits: vec![],
                display_override: None,
                });
                seen_names.insert("new".to_string());
                break;
            }
        }

        // Collect methods from this class and all ancestors
        self.collect_ancestor_methods(class_name, class_name, module_index, &mut candidates, &mut seen_names, 0);

        candidates
    }

    /// Recursively collect methods from a class and its ancestors, deduping by name.
    fn collect_ancestor_methods(
        &self,
        original_class: &str,
        class_name: &str,
        module_index: Option<&ModuleIndex>,
        candidates: &mut Vec<CompletionCandidate>,
        seen_names: &mut HashSet<String>,
        depth: usize,
    ) {
        if depth > 20 {
            return;
        }

        // Local methods in this class
        for sym in &self.symbols {
            if matches!(sym.kind, SymKind::Sub | SymKind::Method) {
                if self.symbol_in_class(sym.id, class_name) && !seen_names.contains(&sym.name) {
                    seen_names.insert(sym.name.clone());
                    let defining = if class_name != original_class { Some(class_name) } else { None };
                    let display_override = sub_display_override(&sym.detail);
                    candidates.push(CompletionCandidate {
                        label: sym.name.clone(),
                        kind: sym.kind,
                        detail: Some(self.method_detail(original_class, &sym.name, defining, module_index)),
                        insert_text: None,
                        sort_priority: PRIORITY_LOCAL,
                        additional_edits: vec![],
                        display_override,
                    });
                }
            }
        }

        // Local plugin-namespace entities bridged to this class. The
        // same-file equivalent of `for_each_entity_bridged_to` — plugin
        // namespaces in THIS FileAnalysis whose bridges include
        // `class_name`. Namespace membership is the sole filter (per
        // `for_each_entity_bridged_to` docs); entity packages can be
        // different from `class_name` (e.g. a helper Method whose
        // package is `Mojolicious::Controller` surfacing from a
        // `Mojolicious` query when the namespace bridges both).
        for ns in &self.plugin_namespaces {
            let bridges_class = ns.bridges.iter().any(|b|
                matches!(b, Bridge::Class(c) if c == class_name));
            if !bridges_class { continue; }
            for sym_id in &ns.entities {
                let Some(sym) = self.symbols.get(sym_id.0 as usize) else { continue };
                if !matches!(sym.kind, SymKind::Sub | SymKind::Method) { continue; }
                if seen_names.contains(&sym.name) { continue; }
                seen_names.insert(sym.name.clone());
                let defining = if class_name != original_class { Some(class_name) } else { None };
                let display_override = sub_display_override(&sym.detail);
                candidates.push(CompletionCandidate {
                    label: sym.name.clone(),
                    kind: sym.kind,
                    detail: Some(self.method_detail(original_class, &sym.name, defining, module_index)),
                    insert_text: None,
                    sort_priority: PRIORITY_LOCAL,
                    additional_edits: vec![],
                    display_override,
                });
            }
        }

        // Walk local parents
        if let Some(parents) = self.package_parents.get(class_name) {
            for parent in parents {
                self.collect_ancestor_methods(
                    original_class, parent, module_index, candidates, seen_names, depth + 1,
                );
            }
        }

        // Walk cross-file parents
        if let Some(idx) = module_index {
            // Two sources of candidates:
            //   (1) Plugin entities reached through bridges (helpers,
            //       routes, tasks, etc. — explicit `Bridge::Class(X)`
            //       declarations from PluginNamespaces across the
            //       workspace).
            //   (2) The cached module whose primary package IS
            //       class_name (real CPAN/user-defined methods on the
            //       class itself).
            // Collect into a temporary list to avoid borrow-checker
            // issues with the closure capturing &mut seen_names/candidates.
            let mut bridged: Vec<(String, SymKind, Option<SymbolDetail>, Option<InferredType>)> = Vec::new();
            idx.for_each_entity_bridged_to(class_name, |_cached, sym| {
                if !matches!(sym.kind, SymKind::Sub | SymKind::Method) { return; }
                bridged.push((
                    sym.name.clone(),
                    sym.kind,
                    Some(sym.detail.clone()),
                    None,
                ));
            });
            for (name, kind, detail, _rt) in bridged {
                if seen_names.contains(&name) { continue; }
                seen_names.insert(name.clone());
                let is_method = kind == SymKind::Method
                    || matches!(detail, Some(SymbolDetail::Sub { is_method: true, .. }));
                let kind = if is_method { SymKind::Method } else { SymKind::Sub };
                let defining = if class_name != original_class { Some(class_name) } else { None };
                let method_detail_str = self.method_detail(original_class, &name, defining, module_index);
                let display_override = detail.as_ref()
                    .map(|d| sub_display_override(d))
                    .unwrap_or(None);
                candidates.push(CompletionCandidate {
                    label: name,
                    kind,
                    detail: Some(method_detail_str),
                    insert_text: None,
                    sort_priority: PRIORITY_LOCAL,
                    additional_edits: vec![],
                    display_override,
                });
            }
            // (2) Real methods on class_name's own cached module.
            if let Some(cached) = idx.get_cached(class_name) {
                for sym in &cached.analysis.symbols {
                    if !matches!(sym.kind, SymKind::Sub | SymKind::Method) { continue; }
                    if sym.package.as_deref() != Some(class_name) { continue; }
                    if seen_names.contains(&sym.name) { continue; }
                    seen_names.insert(sym.name.clone());
                    let is_method = sym.kind == SymKind::Method
                        || matches!(sym.detail, SymbolDetail::Sub { is_method: true, .. });
                    let kind = if is_method { SymKind::Method } else { SymKind::Sub };
                    let defining = if class_name != original_class { Some(class_name) } else { None };
                    let detail = self.method_detail(original_class, &sym.name, defining, module_index);
                    let display_override = sub_display_override(&sym.detail);
                    candidates.push(CompletionCandidate {
                        label: sym.name.clone(),
                        kind,
                        detail: Some(detail),
                        insert_text: None,
                        sort_priority: PRIORITY_LOCAL,
                        additional_edits: vec![],
                        display_override,
                    });
                }
            }

            // Cross-file parents
            let cross_parents = idx.parents_cached(class_name);
            for parent in &cross_parents {
                // Don't re-collect if it's a local package (already handled above)
                if !self.package_parents.contains_key(parent.as_str()) {
                    self.collect_ancestor_methods(
                        original_class, parent, module_index, candidates, seen_names, depth + 1,
                    );
                }
            }
        }
    }

    /// Get the enclosing package name at a point.
    ///
    /// Resolves via `package_ranges` (innermost — latest-starting —
    /// containing range wins). Falls back to a scope walk for older
    /// cache blobs deserialised before `package_ranges` existed.
    #[allow(dead_code)]
    pub fn package_at(&self, point: Point) -> Option<&str> {
        if !self.package_ranges.is_empty() {
            let mut best: Option<&PackageRange> = None;
            for r in &self.package_ranges {
                if !contains_point(&r.span, point) {
                    continue;
                }
                let win = match best {
                    None => true,
                    Some(prev) => {
                        // Latest-starting wins; on a tie, narrower span wins.
                        let cur_start = (r.span.start.row, r.span.start.column);
                        let prev_start = (prev.span.start.row, prev.span.start.column);
                        cur_start > prev_start
                            || (cur_start == prev_start && span_size(&r.span) < span_size(&prev.span))
                    }
                };
                if win {
                    best = Some(r);
                }
            }
            return best.map(|r| r.package.as_str());
        }
        // Fallback: legacy cache blob with no package_ranges.
        let scope = self.scope_at(point)?;
        let chain = self.scope_chain(scope);
        for scope_id in &chain {
            let s = &self.scopes[scope_id.0 as usize];
            if let Some(ref pkg) = s.package {
                return Some(pkg.as_str());
            }
        }
        None
    }

    /// Iterate Handler symbols whose owner class is `owner_class` and
    /// that dispatch through any of `dispatchers`. When `dispatchers`
    /// is empty, all handlers for that class match. Powers plugin
    /// `dispatch_targets_for` (rule #5: this extraction lives on the
    /// data model, not duplicated in symbols.rs).
    pub fn handlers_for_owner<'a>(
        &'a self,
        owner_class: &'a str,
        dispatchers: &'a [String],
    ) -> impl Iterator<Item = &'a Symbol> + 'a {
        self.symbols.iter().filter(move |sym| {
            let SymbolDetail::Handler { owner, dispatchers: dd, .. } = &sym.detail else {
                return false;
            };
            let HandlerOwner::Class(c) = owner;
            if c != owner_class { return false; }
            if !dispatchers.is_empty()
                && !dd.iter().any(|d| dispatchers.iter().any(|n| n == d))
            {
                return false;
            }
            true
        })
    }

    /// Trigger-matching view for plugin query hooks at `point`: the
    /// modules `use`d inside the enclosing package plus the transitive
    /// parent chain. Mirrors what the builder assembles at emit time so
    /// query hooks can be gated by the same `PluginRegistry::applicable`
    /// filter instead of running against every bundled plugin.
    pub fn trigger_view_at(&self, point: Point) -> (Vec<String>, Vec<String>) {
        let pkg = match self.package_at(point) {
            Some(p) => p.to_string(),
            None => return (Vec::new(), Vec::new()),
        };
        let uses = self.package_uses.get(&pkg).cloned().unwrap_or_default();
        let mut parents = Vec::new();
        let mut seen = std::collections::HashSet::new();
        let mut stack = vec![pkg.clone()];
        while let Some(cur) = stack.pop() {
            if let Some(ps) = self.package_parents.get(&cur) {
                for p in ps {
                    if seen.insert(p.clone()) {
                        parents.push(p.clone());
                        stack.push(p.clone());
                    }
                }
            }
        }
        (uses, parents)
    }

    /// Resolve the class name for an invocant expression text (the token
    /// left of `->`). Handles the two Perl conventions `$self` and
    /// `__PACKAGE__` by falling back to the enclosing package; typed
    /// scalars go through `inferred_type`; barewords are treated as
    /// class names verbatim.
    ///
    /// This is Perl-semantic resolution, so it belongs on the data
    /// layer (rule #3). Callers in `symbols.rs` / `cursor_context.rs`
    /// compose this; they don't repeat the rules.
    pub fn invocant_text_to_class(&self, invocant: Option<&str>, point: Point) -> Option<String> {
        let text = invocant?;
        if text == "$self" || text == "__PACKAGE__" {
            return self.package_at(point).map(|s| s.to_string());
        }
        if text.starts_with('$') {
            // Use `InferredType::class_name()` so BOTH `ClassName` and
            // `FirstParam` resolve to their class — without this, a
            // `my ($c) = @_` invocant in a controller method (typed
            // `FirstParam { package: Users }`) falls back to None and
            // dispatch-target completion never fires for `$c->url_for(|)`.
            // Method completion on the same `$c` already uses this
            // accessor; routing through it here keeps the two paths in
            // sync. Rule #3.
            return self.inferred_type_via_bag(text, point)
                .and_then(|t| t.class_name().map(str::to_string));
        }
        if text.starts_with('@') || text.starts_with('%') {
            return None;
        }
        Some(text.to_string())
    }

    /// Find all symbols with a given name.
    pub fn symbols_named(&self, name: &str) -> &[SymbolId] {
        self.symbols_by_name.get(name).map(|v| v.as_slice()).unwrap_or(&[])
    }

    /// Find all symbols in a given scope.
    #[allow(dead_code)]
    pub fn symbols_in_scope(&self, scope: ScopeId) -> &[SymbolId] {
        self.symbols_by_scope.get(&scope).map(|v| v.as_slice()).unwrap_or(&[])
    }

    /// Find all refs with a given target name.
    #[allow(dead_code)]
    pub fn refs_named(&self, name: &str) -> Vec<&Ref> {
        self.refs_by_name.get(name)
            .map(|idxs| idxs.iter().map(|&i| &self.refs[i]).collect())
            .unwrap_or_default()
    }

    /// Find all refs that resolve to a specific symbol.
    #[allow(dead_code)]
    pub fn refs_to(&self, target: SymbolId) -> Vec<&Ref> {
        self.refs.iter()
            .filter(|r| r.resolves_to == Some(target))
            .collect()
    }

    /// Find all hash key accesses/definitions for a given owner.
    #[allow(dead_code)]
    pub fn hash_keys_for_owner(&self, owner: &HashKeyOwner) -> Vec<&Ref> {
        self.refs.iter()
            .filter(|r| {
                if let RefKind::HashKeyAccess { owner: Some(ref o), .. } = r.kind {
                    o == owner
                } else {
                    false
                }
            })
            .collect()
    }

    /// Find all hash key definition symbols for a given owner.
    pub fn hash_key_defs_for_owner(&self, owner: &HashKeyOwner) -> Vec<&Symbol> {
        self.symbols.iter()
            .filter(|s| {
                if let SymbolDetail::HashKeyDef { owner: ref o, .. } = s.detail {
                    o.found_by(owner)
                } else {
                    false
                }
            })
            .collect()
    }

    // ---- Cursor lookup methods ----

    /// Find the ref at a given point (cursor position).
    pub fn ref_at(&self, point: Point) -> Option<&Ref> {
        self.refs.iter()
            .filter(|r| contains_point(&r.span, point))
            .min_by_key(|r| span_size(&r.span))
    }

    /// Find the symbol whose selection_span contains the point.
    pub fn symbol_at(&self, point: Point) -> Option<&Symbol> {
        self.symbols.iter().find(|s| contains_point(&s.selection_span, point))
    }

    // ---- High-level queries ----

    /// Go-to-definition: resolve the symbol at cursor to its definition span.
    pub fn find_definition(&self, point: Point, tree: Option<&tree_sitter::Tree>, source_bytes: Option<&[u8]>, module_index: Option<&ModuleIndex>) -> Option<Span> {
        // 1. Check if cursor is on a ref
        if let Some(r) = self.ref_at(point) {
            match &r.kind {
                RefKind::Variable => {
                    if let Some(sym_id) = r.resolves_to {
                        return Some(self.symbol(sym_id).selection_span);
                    }
                }
                RefKind::FunctionCall { resolved_package } => {
                    // Package-scoped: pick the sub whose package
                    // matches the ref's resolved_package. When the
                    // call pinned a specific package (import or
                    // local-package match), we MUST NOT jump to a
                    // same-named sub in a different package — that's
                    // the cross-class collision we're specifically
                    // guarding against.
                    for &sid in self.symbols_named(&r.target_name) {
                        let sym = self.symbol(sid);
                        if sym.kind != SymKind::Sub { continue; }
                        if sym.package == *resolved_package {
                            return Some(sym.selection_span);
                        }
                    }
                    // Nothing local; leave cross-file resolution to
                    // the LSP adapter (symbols::find_definition).
                }
                RefKind::MethodCall { .. } => {
                    let class_name = self.method_call_invocant_class(r, module_index);

                    // Check if cursor is on a named arg key in the
                    // call args, not on the method name itself.
                    // Resolve to hash key def or :param field.
                    //
                    // The owner for hash-key args is per-flavor +
                    // method-aware: ask the receiver's
                    // ParametricType for `method_arg_owner(method)`
                    // — `Some(owner)` means the flavor claims this
                    // method's args (DBIC's ResultSet returns the
                    // row class for search/find/create/etc.;
                    // returns None for count/exists). When the
                    // flavor doesn't claim, fall back to the
                    // receiver's class (constructor keys etc. on
                    // `bless { } 'Foo'`-shaped non-Parametric
                    // values). Method dispatch on the same ref
                    // still uses `class_name()`, so `$rs->search`
                    // resolves against the ResultSet base.
                    if let (Some(t), Some(s)) = (tree, source_bytes) {
                        if let Some(key_name) = self.call_arg_key_at(t, s, point) {
                            let owner = self
                                .method_call_invocant_type(r, module_index)
                                .as_ref()
                                .and_then(|ty| ty.as_parametric())
                                .and_then(|p| p.method_arg_owner(&r.target_name))
                                .or_else(|| {
                                    class_name
                                        .as_ref()
                                        .map(|c| HashKeyOwner::Class(c.clone()))
                                });
                            if let Some(owner) = owner {
                                for def in self.hash_key_defs_for_owner(&owner) {
                                    if def.name == key_name {
                                        return Some(def.selection_span);
                                    }
                                }
                                if let HashKeyOwner::Class(cn) = &owner {
                                    if let Some(span) = self.find_param_field(cn, &key_name) {
                                        return Some(span);
                                    }
                                }
                            }
                        }
                    }

                    if let Some(ref cn) = class_name {
                        // Find method in the resolved class (walks inheritance)
                        match self.resolve_method_in_ancestors(cn, &r.target_name, module_index) {
                            Some(MethodResolution::Local { sym_id, .. }) => {
                                return Some(self.symbol(sym_id).selection_span);
                            }
                            Some(MethodResolution::CrossFile { .. }) => {
                                // Cross-file method — return None so the LSP adapter
                                // can resolve it via ModuleIndex with the correct URI.
                                return None;
                            }
                            None => {
                                // If the class has known parents, the method might be
                                // inherited but the module index hasn't resolved yet.
                                // Return None so the cross-file block in symbols.rs
                                // gets a chance, rather than jumping to the package decl.
                                if self.package_parents.contains_key(cn) {
                                    return None;
                                }
                            }
                        }
                        // Method not found and no parents — go to class def
                        if let Some(span) = self.find_package_or_class(cn) {
                            return Some(span);
                        }
                    }
                    // Last-resort "any sub/method with that name" fallback.
                    // Only fires when we couldn't resolve the invocant at
                    // all — if we knew the target class but couldn't find
                    // the method there, jumping to an unrelated sub is
                    // actively harmful (plugin-emitted MethodCallRefs
                    // targeting `'Users#create'` would otherwise latch
                    // onto a `create` helper synthesized on some unrelated
                    // class). Returning None is better — the LSP adapter
                    // can still try cross-file paths.
                    if class_name.is_none() {
                        for &sid in self.symbols_named(&r.target_name) {
                            let sym = self.symbol(sid);
                            if matches!(sym.kind, SymKind::Sub | SymKind::Method) {
                                return Some(sym.selection_span);
                            }
                        }
                    }
                }
                RefKind::PackageRef => {
                    return self.find_package_or_class(&r.target_name);
                }
                RefKind::HashKeyAccess { ref owner, .. } => {
                    // Try the pre-resolved owner first
                    let resolved_owner = owner.clone().or_else(|| {
                        let tree = tree?;
                        let source = source_bytes?;
                        self.resolve_hash_owner_from_tree(tree, source, r.span.start, module_index)
                    });
                    if let Some(ref owner) = resolved_owner {
                        for def in self.hash_key_defs_for_owner(owner) {
                            if def.name == r.target_name {
                                return Some(def.selection_span);
                            }
                        }
                    }
                }
                RefKind::ContainerAccess => {
                    return self.resolve_variable(&r.target_name, point)
                        .map(|sym| sym.selection_span);
                }
                RefKind::DispatchCall { owner: Some(owner), .. } => {
                    // Go-to-def on a dispatch call site lands at the
                    // first stacked Handler for this (owner, name).
                    // Features that want all registrations walk
                    // `refs_to_symbol` or use `refs_to` with
                    // `TargetKind::Handler`.
                    for sym in &self.symbols {
                        if sym.name != r.target_name { continue; }
                        if let SymbolDetail::Handler { owner: o, .. } = &sym.detail {
                            if o == owner {
                                return Some(sym.selection_span);
                            }
                        }
                    }
                }
                RefKind::DispatchCall { owner: None, .. } => {}
            }
        }

        // 2. Check if cursor is on a symbol declaration
        if let Some(sym) = self.symbol_at(point) {
            return Some(sym.selection_span);
        }

        None
    }

    /// Find all references to the symbol at cursor.
    pub fn find_references(
        &self,
        point: Point,
        tree: Option<&tree_sitter::Tree>,
        source_bytes: Option<&[u8]>,
        module_index: Option<&ModuleIndex>,
    ) -> Vec<Span> {
        if let Some((target_id, include_decl)) = self.resolve_target_at(point, tree, source_bytes, module_index) {
            let mut results = self.collect_refs_for_target(target_id, include_decl, tree, source_bytes, module_index);
            results.sort_by_key(|(s, _)| (s.start.row, s.start.column));
            results.dedup_by(|a, b| a.0.start == b.0.start && a.0.end == b.0.end);
            results.into_iter().map(|(span, _)| span).collect()
        } else {
            Vec::new()
        }
    }

    /// Document highlights: like references but with read/write annotation.
    pub fn find_highlights(
        &self,
        point: Point,
        tree: Option<&tree_sitter::Tree>,
        source_bytes: Option<&[u8]>,
        module_index: Option<&ModuleIndex>,
    ) -> Vec<(Span, AccessKind)> {
        if let Some((target_id, _)) = self.resolve_target_at(point, tree, source_bytes, module_index) {
            let mut results = self.collect_refs_for_target(target_id, true, tree, source_bytes, module_index);
            results.sort_by_key(|(s, _)| (s.start.row, s.start.column));
            results.dedup_by(|a, b| a.0.start == b.0.start && a.0.end == b.0.end);
            return results;
        }
        // Fallback — cursor is on a ref whose target isn't defined in
        // this file (cross-file method call, unresolved import). Match
        // other refs in the same file that share (target_name, scope).
        // Without this, documentHighlight on a cross-file method call
        // returns empty even when other call sites for the same class+method
        // exist in the file.
        if let Some(r) = self.ref_at(point) {
            let mut results: Vec<(Span, AccessKind)> = Vec::new();
            match &r.kind {
                RefKind::MethodCall { method_name_span, .. } => {
                    // Single bag-routed invocant resolver — same call
                    // for the cursor's ref and every candidate.
                    let Some(wanted_class) = self.method_call_invocant_class(r, module_index) else {
                        return Vec::new();
                    };
                    results.push((*method_name_span, r.access));
                    for other in &self.refs {
                        if std::ptr::eq(other, r) { continue; }
                        if other.target_name != r.target_name { continue; }
                        if !matches!(other.kind, RefKind::MethodCall { .. }) { continue; }
                        let Some(ocn) = self.method_call_invocant_class(other, module_index) else { continue };
                        if ocn != wanted_class { continue; }
                        if let RefKind::MethodCall { method_name_span: ms, .. } = &other.kind {
                            results.push((*ms, other.access));
                        }
                    }
                }
                RefKind::FunctionCall { resolved_package: Some(pkg) } => {
                    let wanted_pkg = pkg.clone();
                    results.push((r.span, r.access));
                    for other in &self.refs {
                        if std::ptr::eq(other, r) { continue; }
                        if other.target_name != r.target_name { continue; }
                        if let RefKind::FunctionCall { resolved_package: Some(op) } = &other.kind {
                            if op == &wanted_pkg {
                                results.push((other.span, other.access));
                            }
                        }
                    }
                }
                _ => {}
            }
            results.sort_by_key(|(s, _)| (s.start.row, s.start.column));
            results.dedup_by(|a, b| a.0.start == b.0.start && a.0.end == b.0.end);
            return results;
        }
        Vec::new()
    }

    /// Shared implementation for find_references and find_highlights.
    fn collect_refs_for_target(
        &self,
        target_id: SymbolId,
        include_decl: bool,
        tree: Option<&tree_sitter::Tree>,
        source_bytes: Option<&[u8]>,
        module_index: Option<&ModuleIndex>,
    ) -> Vec<(Span, AccessKind)> {
        let sym = self.symbol(target_id);
        let mut results: Vec<(Span, AccessKind)> = Vec::new();

        // Include the declaration itself
        if include_decl {
            results.push((sym.selection_span, AccessKind::Declaration));
        }

        // Phase 5: O(1) lookup for every ref resolved to this symbol.
        // This covers variables, HashKeyAccess refs whose owner was resolved at
        // build time, and any future kinds that set resolves_to.
        for &idx in self.refs_to_symbol(target_id) {
            let r = &self.refs[idx];
            results.push((r.span, r.access));
        }

        // For subs/methods/packages/classes, also find refs by name.
        // Scope-filter callable refs (Sub / Method) by the target
        // symbol's package — matches `resolve::refs_to` so
        // documentHighlight and references agree on "same callable".
        // Without this, cursor on one `create` highlights every other
        // same-named method/sub in the file regardless of class
        // (mojo-helper leaf on `_Helper::users` cross-highlighting
        // the route's `Users::create` ref, etc.).
        if matches!(sym.kind, SymKind::Sub | SymKind::Method | SymKind::Package | SymKind::Class | SymKind::Module) {
            let sym_package = sym.package.clone();
            for r in &self.refs {
                if r.target_name == sym.name && r.resolves_to.is_none() {
                    match (&r.kind, &sym.kind) {
                        (RefKind::FunctionCall { resolved_package }, SymKind::Sub) => {
                            if *resolved_package == sym_package {
                                results.push((r.span, r.access));
                            }
                        }
                        (RefKind::MethodCall { method_name_span, .. },
                         SymKind::Sub | SymKind::Method) => {
                            // Same-class match only; unresolved or
                            // different-class invocants are excluded.
                            // Method-call ref.span covers the whole
                            // `$obj->foo(...)` expression so we use
                            // `method_name_span` to highlight just
                            // the identifier.
                            match (self.method_call_invocant_class(r, module_index), &sym_package) {
                                (Some(cn), Some(pkg)) if cn == *pkg => {
                                    results.push((*method_name_span, r.access));
                                }
                                _ => {}
                            }
                        }
                        (RefKind::PackageRef, SymKind::Package | SymKind::Class | SymKind::Module) => results.push((r.span, r.access)),
                        _ => {}
                    }
                }
            }
        }

        // For hash key definitions, find all accesses with same owner + key name
        if let SymbolDetail::HashKeyDef { ref owner, .. } = sym.detail {
            for r in &self.refs {
                if let RefKind::HashKeyAccess { owner: ref ro, .. } = r.kind {
                    if r.target_name != sym.name {
                        continue;
                    }
                    let matches = match ro {
                        Some(ref ro) => owner.found_by(ro),
                        None => {
                            if let (Some(t), Some(s)) = (tree, source_bytes) {
                                self.resolve_hash_owner_from_tree(t, s, r.span.start, None)
                                    .as_ref()
                                    .map_or(false, |resolved| owner.found_by(resolved))
                            } else {
                                false
                            }
                        }
                    };
                    if matches {
                        results.push((r.span, r.access));
                    }
                }
            }
        }

        results
    }

    /// Hover info: return display text for the symbol at cursor.
    pub fn hover_info(&self, point: Point, source: &str, tree: Option<&tree_sitter::Tree>, module_index: Option<&ModuleIndex>) -> Option<String> {
        // Check refs first
        if let Some(r) = self.ref_at(point) {
            match &r.kind {
                RefKind::Variable | RefKind::ContainerAccess => {
                    // Check if this variable is also a dynamic method call target
                    // (e.g. $self->$method() where $method is a known constant)
                    let method_hover = self.refs.iter()
                        .find(|mr| matches!(mr.kind, RefKind::MethodCall { .. })
                            && contains_point(&mr.span, point)
                            && mr.target_name != r.target_name);
                    if let Some(mr) = method_hover {
                        if matches!(mr.kind, RefKind::MethodCall { .. }) {
                            let class_name = self.method_call_invocant_class_with_tree(
                                mr, tree, Some(source.as_bytes()), module_index,
                            );
                            if let Some(ref cn) = class_name {
                                match self.resolve_method_in_ancestors(cn, &mr.target_name, module_index) {
                                    Some(MethodResolution::Local { sym_id, class: ref defining_class, .. }) => {
                                        let sym = self.symbol(sym_id);
                                        let line = source_line_at(source, sym.selection_span.start.row);
                                        let class_label = if defining_class != cn {
                                            format!("{} (from {})", cn, defining_class)
                                        } else {
                                            cn.to_string()
                                        };
                                        let mut text = format!("```perl\n{}\n```\n\n*class {} — resolved from `{}`*", line.trim(), class_label, r.target_name);
                                        if let Some(ref rt) = self.find_method_return_type(cn, &mr.target_name, module_index, None) {
                                            text.push_str(&format!("\n\n*returns: {}*", format_inferred_type(&rt)));
                                        }
                                        if let SymbolDetail::Sub { ref doc, .. } = sym.detail {
                                            if let Some(ref d) = doc {
                                                text.push_str(&format!("\n\n{}", d));
                                            }
                                        }
                                        return Some(text);
                                    }
                                    Some(MethodResolution::CrossFile { ref class }) => {
                                        if let Some(idx) = module_index {
                                            if let Some(cached) = idx.get_cached(class) {
                                                if let Some(sub_info) = cached.sub_info(&mr.target_name) {
                                                    let sig = format_cross_file_signature(&mr.target_name, &sub_info);
                                                    let mut text = format!("```perl\n{}\n```\n\n*class {} — resolved from `{}`*", sig, class, r.target_name);
                                                    if let Some(rt) = sub_info.return_type() {
                                                        text.push_str(&format!("\n\n*returns: {}*", format_inferred_type(&rt)));
                                                    }
                                                    if let Some(doc) = sub_info.doc() {
                                                        text.push_str(&format!("\n\n{}", doc));
                                                    }
                                                    return Some(text);
                                                }
                                            }
                                        }
                                    }
                                    None => {}
                                }
                            }
                        }
                    }
                    if let Some(sym_id) = r.resolves_to {
                        let sym = self.symbol(sym_id);
                        return Some(self.format_symbol_hover_at(sym, source, point));
                    }
                    // Unresolved variable — try resolve ourselves
                    if let Some(sym) = self.resolve_variable(&r.target_name, point) {
                        return Some(self.format_symbol_hover_at(sym, source, point));
                    }
                }
                RefKind::FunctionCall { resolved_package } => {
                    // Package-scoped: hover shows the sub whose
                    // package matches what the ref resolved to.
                    for &sid in self.symbols_named(&r.target_name) {
                        let sym = self.symbol(sid);
                        if sym.kind != SymKind::Sub { continue; }
                        if sym.package == *resolved_package {
                            return Some(self.format_symbol_hover(sym, source));
                        }
                    }
                    // Fall-through: the name might be a function imported
                    // from another module (either hand-written `use` or a
                    // plugin-synthesized Import like Mojolicious::Lite's
                    // route verbs). Cross-file lookup pulls real POD,
                    // real signature, real return type from the source
                    // module's cached analysis.
                    if let Some(idx) = module_index {
                        for import in &self.imports {
                            let matched = import.imported_symbols.iter()
                                .find(|s| s.local_name == r.target_name);
                            let Some(is) = matched else { continue };
                            let Some(cached) = idx.get_cached(&import.module_name) else { continue };
                            let Some(sub_info) = cached.sub_info(is.remote()) else { continue };

                            let sig_params = sub_info.params().iter()
                                .map(|p| p.name.as_str())
                                .collect::<Vec<_>>()
                                .join(", ");
                            let mut sig = format!("sub {}({})", r.target_name, sig_params);
                            if let Some(rt) = sub_info.return_type() {
                                sig.push_str(&format!("{}", format_inferred_type(&rt)));
                            }
                            let mut text = format!("```perl\n{}\n```", sig);
                            if let Some(doc) = sub_info.doc() {
                                text.push_str(&format!("\n\n{}", doc));
                            }
                            if is.remote() != r.target_name {
                                text.push_str(&format!(
                                    "\n\n*imported from `{}` (as `{}`)*",
                                    import.module_name, is.remote()
                                ));
                            } else {
                                text.push_str(&format!(
                                    "\n\n*imported from `{}`*",
                                    import.module_name
                                ));
                            }
                            return Some(text);
                        }
                    }
                }
                RefKind::MethodCall { .. } => {
                    let class_name = self.method_call_invocant_class_with_tree(
                        r, tree, Some(source.as_bytes()), module_index,
                    );
                    if let Some(ref cn) = class_name {
                        match self.resolve_method_in_ancestors(cn, &r.target_name, module_index) {
                            Some(MethodResolution::Local { sym_id, class: ref defining_class, .. }) => {
                                let sym = self.symbol(sym_id);
                                let line = source_line_at(source, sym.selection_span.start.row);
                                let class_label = if defining_class != cn {
                                    format!("{} (from {})", cn, defining_class)
                                } else {
                                    cn.to_string()
                                };
                                let mut text = format!("```perl\n{}\n```\n\n*class {}*", line.trim(), class_label);
                                if let Some(ref rt) = self.find_method_return_type(cn, &r.target_name, module_index, None) {
                                    text.push_str(&format!("\n\n*returns: {}*", format_inferred_type(&rt)));
                                }
                                return Some(text);
                            }
                            Some(MethodResolution::CrossFile { ref class }) => {
                                if let Some(idx) = module_index {
                                    if let Some(cached) = idx.get_cached(class) {
                                        if let Some(sub_info) = cached.sub_info(&r.target_name) {
                                            let class_label = if class != cn {
                                                format!("{} (from {})", cn, class)
                                            } else {
                                                cn.to_string()
                                            };
                                            let sig = format_cross_file_signature(&r.target_name, &sub_info);
                                            let mut text = format!("```perl\n{}\n```\n\n*class {}*", sig, class_label);
                                            if let Some(rt) = sub_info.return_type() {
                                                text.push_str(&format!("\n\n*returns: {}*", format_inferred_type(&rt)));
                                            }
                                            if let Some(doc) = sub_info.doc() {
                                                text.push_str(&format!("\n\n{}", doc));
                                            }
                                            return Some(text);
                                        }
                                    }
                                }
                            }
                            None => {}
                        }
                    }
                    // Fallback
                    for &sid in self.symbols_named(&r.target_name) {
                        let sym = self.symbol(sid);
                        if matches!(sym.kind, SymKind::Sub | SymKind::Method) {
                            return Some(self.format_symbol_hover(sym, source));
                        }
                    }
                }
                RefKind::PackageRef => {
                    for &sid in self.symbols_named(&r.target_name) {
                        let sym = self.symbol(sid);
                        if matches!(sym.kind, SymKind::Package | SymKind::Class) {
                            return Some(self.format_symbol_hover(sym, source));
                        }
                    }
                }
                RefKind::HashKeyAccess { owner, .. } => {
                    if let Some(ref owner) = owner {
                        let defs = self.hash_key_defs_for_owner(owner);
                        let matching: Vec<_> = defs.iter()
                            .filter(|d| d.name == r.target_name)
                            .collect();
                        if !matching.is_empty() {
                            let lines: Vec<String> = matching.iter()
                                .map(|d| {
                                    let line = source_line_at(source, d.span.start.row);
                                    format!("- `{}`", line.trim())
                                })
                                .collect();
                            return Some(format!("**Hash key `{}`**\n\n{}", r.target_name, lines.join("\n")));
                        }
                    }
                }
                RefKind::DispatchCall { dispatcher, owner } => {
                    if let Some(ref owner) = owner {
                        return Some(self.format_handler_hover(
                            &r.target_name,
                            owner,
                            Some(dispatcher),
                            module_index,
                        ));
                    }
                }
            }
        }

        // Check symbols
        if let Some(sym) = self.symbol_at(point) {
            // Handler symbols get a specialized multi-registration hover
            // (stacked defs, dispatcher list, param shapes).
            if let SymbolDetail::Handler { owner, .. } = &sym.detail {
                return Some(self.format_handler_hover(&sym.name, owner, None, module_index));
            }
            return Some(self.format_symbol_hover(sym, source));
        }

        None
    }

    /// Rename: return all spans + new text for renaming the symbol at cursor.
    pub fn rename_at(&self, point: Point, new_name: &str, tree: Option<&tree_sitter::Tree>, source_bytes: Option<&[u8]>) -> Option<Vec<(Span, String)>> {
        let refs = self.find_references(point, tree, source_bytes, None);
        if refs.is_empty() {
            return None;
        }

        // Determine if this is a variable (sigil handling needed)
        let is_variable = self.ref_at(point)
            .map(|r| matches!(r.kind, RefKind::Variable | RefKind::ContainerAccess))
            .or_else(|| self.symbol_at(point).map(|s| matches!(s.kind, SymKind::Variable | SymKind::Field)))
            .unwrap_or(false);

        let edits: Vec<(Span, String)> = if is_variable {
            // Strip sigil from new_name if present
            let bare_name = if new_name.starts_with('$') || new_name.starts_with('@') || new_name.starts_with('%') {
                &new_name[1..]
            } else {
                new_name
            };
            refs.into_iter().map(|span| {
                // Each ref span includes the sigil; replace only the name part (after sigil)
                let name_span = Span {
                    start: Point::new(span.start.row, span.start.column + 1),
                    end: span.end,
                };
                (name_span, bare_name.to_string())
            }).collect()
        } else {
            refs.into_iter().map(|span| (span, new_name.to_string())).collect()
        };

        Some(edits)
    }

    /// Determine what kind of rename is appropriate for the cursor position.
    ///
    /// For `RenameKind::Method`, the class is mandatory (so cross-file
    /// walks don't cross-link unrelated classes that share a method
    /// name). When the invocant can't be resolved to a class, rename
    /// falls through to symbol-at resolution; if that also has no
    /// class context (orphan Sub), returns `None` — the cursor isn't
    /// on something we can safely rename.
    pub fn rename_kind_at(&self, point: Point, module_index: Option<&ModuleIndex>) -> Option<RenameKind> {
        if let Some(r) = self.ref_at(point) {
            match &r.kind {
                RefKind::Variable | RefKind::ContainerAccess => return Some(RenameKind::Variable),
                RefKind::FunctionCall { resolved_package } => {
                    return Some(RenameKind::Function {
                        name: r.target_name.clone(),
                        package: resolved_package.clone(),
                    });
                }
                RefKind::MethodCall { .. } => {
                    if let Some(class) = self.method_call_invocant_class(r, module_index) {
                        return Some(RenameKind::Method {
                            name: r.target_name.clone(),
                            class,
                        });
                    }
                    // Invocant unresolvable — try symbol-at fallback
                    // below; if that also has no class, bail rather
                    // than return a class-less Method rename.
                }
                RefKind::PackageRef => return Some(RenameKind::Package(r.target_name.clone())),
                RefKind::HashKeyAccess { .. } => return Some(RenameKind::HashKey(r.target_name.clone())),
                RefKind::DispatchCall { owner: Some(owner), .. } => {
                    return Some(RenameKind::Handler {
                        owner: owner.clone(),
                        name: r.target_name.clone(),
                    });
                }
                // Unresolved DispatchCall — owner couldn't be determined
                // at build time, so rename can't safely scope.
                RefKind::DispatchCall { owner: None, .. } => return None,
            }
        }
        if let Some(sym) = self.symbol_at(point) {
            return match sym.kind {
                SymKind::Variable | SymKind::Field => Some(RenameKind::Variable),
                SymKind::Sub => Some(RenameKind::Function {
                    name: sym.name.clone(),
                    package: sym.package.clone(),
                }),
                SymKind::Method => {
                    let class = sym.package.clone()?;
                    Some(RenameKind::Method {
                        name: sym.name.clone(),
                        class,
                    })
                }
                SymKind::Package | SymKind::Class => Some(RenameKind::Package(sym.name.clone())),
                SymKind::Handler => {
                    if let SymbolDetail::Handler { owner, .. } = &sym.detail {
                        Some(RenameKind::Handler { owner: owner.clone(), name: sym.name.clone() })
                    } else { None }
                }
                _ => None,
            };
        }
        None
    }

    /// Find all occurrences of a sub name (def + ALL call refs) for cross-file rename.
    /// Searches both FunctionCall and MethodCall refs because Perl subs can be called either way.
    /// Scope-aware rename for a sub/method: matches decls + both
    /// call shapes that resolve to this (scope, name) pair.
    ///
    ///   * decl walk — `Sub`/`Method` symbols whose `package == scope`
    ///   * FunctionCall refs whose `resolved_package == scope`
    ///   * MethodCall refs whose `invocant_class == scope`
    ///
    /// The two call shapes both resolve to the same underlying sub:
    /// `package Foo; sub run {}` is callable as `run()` OR
    /// `$self->run()` OR `Foo::run()`. A rename must rewrite every
    /// shape, and must NOT rewrite same-named subs/methods in other
    /// packages. When `scope == None`, matches top-level/script subs
    /// with no package; FunctionCall refs whose resolver didn't pin
    /// a package match those. MethodCall refs always need a class —
    /// `None` scope never matches them.
    fn rename_callable_in_scope(
        &self,
        old_name: &str,
        scope: &Option<String>,
        new_name: &str,
        module_index: Option<&ModuleIndex>,
    ) -> Vec<(Span, String)> {
        let mut edits = Vec::new();
        for sym in &self.symbols {
            if sym.name != old_name { continue; }
            if !matches!(sym.kind, SymKind::Sub | SymKind::Method) { continue; }
            if sym.package != *scope { continue; }
            edits.push((sym.selection_span, new_name.to_string()));
        }
        for r in &self.refs {
            if r.target_name != old_name { continue; }
            match &r.kind {
                RefKind::FunctionCall { resolved_package } => {
                    if resolved_package == scope {
                        edits.push((r.span, new_name.to_string()));
                    }
                }
                RefKind::MethodCall { method_name_span, .. } => {
                    // MethodCall refs target a class — `None` scope
                    // doesn't reach methods.
                    if let (Some(cls), Some(wanted)) =
                        (self.method_call_invocant_class(r, module_index), scope.as_ref())
                    {
                        if &cls == wanted {
                            edits.push((*method_name_span, new_name.to_string()));
                        }
                    }
                }
                _ => {}
            }
        }
        edits
    }

    /// Package-scoped sub rename — public-API name used by the
    /// Function rename path. Delegates to the unified
    /// `rename_callable_in_scope`; the distinction between "function"
    /// and "method" in Perl is just call shape, not identity.
    pub fn rename_sub_in_package(
        &self,
        old_name: &str,
        package: &Option<String>,
        new_name: &str,
        module_index: Option<&ModuleIndex>,
    ) -> Vec<(Span, String)> {
        self.rename_callable_in_scope(old_name, package, new_name, module_index)
    }

    /// Class-scoped method rename — public-API name used by the
    /// Method rename path. Same semantics as
    /// `rename_sub_in_package(old, &Some(class), new)`: function and
    /// method calls into the same package are two shapes of the same
    /// callable.
    pub fn rename_method_in_class(
        &self,
        old_name: &str,
        class: &str,
        new_name: &str,
        module_index: Option<&ModuleIndex>,
    ) -> Vec<(Span, String)> {
        self.rename_callable_in_scope(old_name, &Some(class.to_string()), new_name, module_index)
    }

    /// Find all occurrences of a package name (def + refs + use statements) for cross-file rename.
    pub fn rename_package(&self, old_name: &str, new_name: &str) -> Vec<(Span, String)> {
        let mut edits = Vec::new();
        for sym in &self.symbols {
            if sym.name == old_name && matches!(sym.kind, SymKind::Package | SymKind::Class | SymKind::Module) {
                edits.push((sym.selection_span, new_name.to_string()));
            }
        }
        for r in &self.refs {
            if r.target_name == old_name && matches!(r.kind, RefKind::PackageRef) {
                edits.push((r.span, new_name.to_string()));
            }
        }
        edits
    }

    // ---- Internal resolution helpers ----

    /// Find the target symbol for the thing at cursor. Returns (SymbolId, include_decl_in_refs).
    fn resolve_target_at(&self, point: Point, tree: Option<&tree_sitter::Tree>, source_bytes: Option<&[u8]>, module_index: Option<&ModuleIndex>) -> Option<(SymbolId, bool)> {
        // Check refs first
        if let Some(r) = self.ref_at(point) {
            match &r.kind {
                RefKind::Variable | RefKind::ContainerAccess => {
                    if let Some(sym_id) = r.resolves_to {
                        return Some((sym_id, true));
                    }
                    // Try resolving manually
                    if let Some(sym) = self.resolve_variable(&r.target_name, point) {
                        return Some((sym.id, true));
                    }
                }
                RefKind::FunctionCall { resolved_package } => {
                    for &sid in self.symbols_named(&r.target_name) {
                        let sym = self.symbol(sid);
                        if sym.kind != SymKind::Sub { continue; }
                        if sym.package == *resolved_package {
                            return Some((sid, true));
                        }
                    }
                }
                RefKind::MethodCall { .. } => {
                    let class_name = self.method_call_invocant_class(r, module_index);
                    // Try inheritance-aware resolution first
                    if let Some(ref cn) = class_name {
                        match self.resolve_method_in_ancestors(cn, &r.target_name, module_index) {
                            Some(MethodResolution::Local { sym_id, .. }) => {
                                return Some((sym_id, true));
                            }
                            Some(MethodResolution::CrossFile { .. }) => {
                                // Cross-file: no local SymbolId. Match
                                // a local symbol only when its package
                                // equals the resolved class — no
                                // same-name cross-class latching.
                                for &sid in self.symbols_named(&r.target_name) {
                                    let sym = self.symbol(sid);
                                    if !matches!(sym.kind, SymKind::Sub | SymKind::Method) { continue; }
                                    if sym.package.as_deref() == Some(cn.as_str()) {
                                        return Some((sid, true));
                                    }
                                }
                            }
                            None => {}
                        }
                        // No local match, and the class is known but
                        // has no local decl — return a synthetic
                        // target by name filtered to the class, so
                        // collect_refs_for_target still walks refs
                        // correctly. If there's NO matching symbol on
                        // the class locally, produce no target —
                        // better than cross-linking a same-named
                        // method on a different class.
                        for &sid in self.symbols_named(&r.target_name) {
                            let sym = self.symbol(sid);
                            if !matches!(sym.kind, SymKind::Sub | SymKind::Method) { continue; }
                            if sym.package.as_deref() == Some(cn.as_str()) {
                                return Some((sid, true));
                            }
                        }
                        // Class known but not defined locally — no
                        // local symbol to anchor on. Caller may still
                        // collect refs via `refs_to` at the LSP layer,
                        // but highlight/definition within this file
                        // have nothing to return.
                        return None;
                    }
                    // Invocant class couldn't be pinned at all —
                    // last-resort name match. Only reaches here for
                    // refs the builder AND the runtime resolver both
                    // failed on (rare: ERROR-recovered invocants).
                    for &sid in self.symbols_named(&r.target_name) {
                        if matches!(self.symbol(sid).kind, SymKind::Sub | SymKind::Method) {
                            return Some((sid, true));
                        }
                    }
                }
                RefKind::PackageRef => {
                    for &sid in self.symbols_named(&r.target_name) {
                        if matches!(self.symbol(sid).kind, SymKind::Package | SymKind::Class | SymKind::Module) {
                            return Some((sid, true));
                        }
                    }
                }
                RefKind::HashKeyAccess { ref owner, .. } => {
                    let resolved_owner = owner.clone().or_else(|| {
                        let tree = tree?;
                        let source = source_bytes?;
                        self.resolve_hash_owner_from_tree(tree, source, r.span.start, module_index)
                    });
                    if let Some(ref owner) = resolved_owner {
                        for def in self.hash_key_defs_for_owner(owner) {
                            if def.name == r.target_name {
                                return Some((def.id, true));
                            }
                        }
                    }
                }
                RefKind::DispatchCall { owner: Some(owner), .. } => {
                    for sym in &self.symbols {
                        if sym.name != r.target_name { continue; }
                        if let SymbolDetail::Handler { owner: o, .. } = &sym.detail {
                            if o == owner {
                                return Some((sym.id, true));
                            }
                        }
                    }
                }
                RefKind::DispatchCall { owner: None, .. } => {}
            }
        }

        // Check if cursor is directly on a symbol declaration
        if let Some(sym) = self.symbol_at(point) {
            return Some((sym.id, false));
        }

        None
    }

    /// Resolve a `MethodCall` ref's invocant class via the witness
    /// bag — **the** invocant resolver. No tree, no text fallback,
    /// no per-reader parallel paths. Every reader (refs_to,
    /// find_highlights, collect_refs_for_target, rename_callable_in_scope,
    /// hover, find-def, rename_kind_at, resolve_target_at, the
    /// completion path) routes through here.
    ///
    /// Dispatch by invocant shape:
    ///   * `$var` / `@var` / `%var` → `inferred_type_via_bag` (so
    ///     cross-file enrichment's variable types compose
    ///     automatically — the bug that prompted this rewrite).
    ///   * `$self` (untyped) → enclosing class fallback.
    ///   * `__PACKAGE__` → enclosing class.
    ///   * Chain or function-call receiver (invocant_span points at
    ///     another ref) → that ref's bag answer
    ///     (`method_call_return_type_via_bag` for MethodCall;
    ///     `sub_return_type_at_arity` for FunctionCall). Receiver
    ///     ref is found via `ref_idx_by_exact_span` (O(1)).
    ///   * Bareword → `Foo` if a zero-arg sub by that name returns
    ///     ClassName, else the bareword itself.
    ///
    /// Build-time chain typing still runs in the builder — its
    /// product lands in the bag (Variable witnesses, `Expression`
    /// edge witnesses on chain receivers). This helper just queries
    /// the bag, never re-derives.
    ///
    /// `module_index` lets chain receivers whose return type lives
    /// in another package resolve (e.g. `$r->get('/x')->to(...)`
    /// where `Routes::get` returns `Routes::Route`). Pass `None`
    /// only when no index is available (CLI debug, isolated tests);
    /// every LSP-facing reader has one.
    pub fn method_call_invocant_class(
        &self,
        r: &Ref,
        module_index: Option<&ModuleIndex>,
    ) -> Option<String> {
        self.method_call_invocant_class_with_tree(r, None, None, module_index)
    }

    /// Tree-aware variant. When a `tree` + `source` are available
    /// (every LSP-facing reader has them), this routes non-trivial
    /// invocants (`$arr[N]`, future shapes) through
    /// `resolve_expression_type` on the actual CST node — the same
    /// arm the cursor-context completion path uses. Without the
    /// tree, falls through to the string-based bag query.
    /// One resolution rule, two entry points, no shape drift.
    pub fn method_call_invocant_class_with_tree(
        &self,
        r: &Ref,
        tree: Option<&tree_sitter::Tree>,
        source: Option<&[u8]>,
        module_index: Option<&ModuleIndex>,
    ) -> Option<String> {
        let RefKind::MethodCall { invocant, invocant_span, .. } = &r.kind else {
            return None;
        };
        if invocant.is_empty() {
            return None;
        }
        let point = invocant_span.map(|s| s.start).unwrap_or(r.span.start);

        // Pseudo-invocants for "$self at the method's first arg":
        // `shift` (no args; `sub m { my $self = shift; ... }`),
        // `$_[0]` / `@_[0]` (positional). Tree-aware build-time
        // resolver treats these as enclosing-class identity. The
        // bag has no Variable witness for them — they aren't real
        // variables — so we resolve here directly.
        if invocant == "shift" || invocant == "$_[0]" || invocant == "@_[0]" {
            return self.enclosing_class_for_scope(r.scope);
        }

        // Tree-aware fast path: find the invocant's CST node and
        // dispatch through `resolve_expression_type`. That arm
        // already handles `array_element_expression` (and any
        // future non-trivial invocant shape) — keeping hover /
        // dispatch on the same projection logic completion uses.
        if let (Some(tree), Some(source), Some(span)) = (tree, source, invocant_span) {
            let node = tree.root_node().descendant_for_point_range(span.start, span.end);
            if let Some(node) = node {
                // Only take this path for shapes the string-based
                // bag query can't handle. `scalar` / `array` /
                // `hash` invocants are simple variables — the
                // existing string lookup is fine and consistent
                // with every other variable-typed call site.
                let needs_tree = !matches!(
                    node.kind(),
                    "scalar" | "array" | "hash" | "bareword" | "package" | "scoped_identifier"
                );
                if needs_tree {
                    if let Some(t) = self.resolve_expression_type(node, source, module_index) {
                        if let Some(cn) = t.class_name() {
                            return Some(cn.to_string());
                        }
                    }
                }
            }
        }

        // `__PACKAGE__` is rewritten to the enclosing package at
        // walk time, but synthesized refs may still carry it raw.
        if invocant == "__PACKAGE__" {
            return self.enclosing_class_for_scope(r.scope);
        }

        // Chain / function-call receiver — checked BEFORE the
        // simple-variable path because complex invocants like
        // `$r->get('/x')` lead with `$` but aren't a variable
        // lookup; they're a sub-expression whose type lives in
        // another ref's bag answer. Index `call_ref_by_start`
        // returns the *innermost* call-shaped ref starting at
        // `invocant_span.start` (smallest-span tie-break in
        // `build_indices`); we additionally require that ref's
        // span be contained in `invocant_span` so we don't loop
        // back on the outer ref itself for `Foo->m` where there's
        // no real inner receiver.
        if let Some(span) = invocant_span {
            if let Some(&recv_idx) = self.call_ref_by_start.get(&span.start) {
                let recv_span = self.refs[recv_idx].span;
                let contained = recv_span.start == span.start
                    && (recv_span.end.row, recv_span.end.column)
                        <= (span.end.row, span.end.column);
                // Guard against the lookup returning the outer ref
                // itself (no genuine inner receiver). Compare by
                // pointer to handle the equal-span case.
                let is_self = std::ptr::eq(&self.refs[recv_idx], r);
                if contained && !is_self {
                    match &self.refs[recv_idx].kind {
                    RefKind::MethodCall { .. } => {
                        // Recursive: resolve the receiver's own
                        // invocant class fresh (so cross-file
                        // enrichment-typed variables compose
                        // through chain hops without depending on
                        // a build-time-published Expression edge),
                        // then chase MethodOnClass{class, method}
                        // through `find_method_return_type` — the
                        // single class-keyed entry point that walks
                        // ancestors + cross-file bridges via the
                        // registry's `query_rec`.
                        let recv = &self.refs[recv_idx];
                        if let Some(recv_class) =
                            self.method_call_invocant_class(recv, module_index)
                        {
                            if recv.target_name == "new" {
                                return Some(recv_class);
                            }
                            if let Some(t) = self.find_method_return_type(
                                &recv_class,
                                &recv.target_name,
                                module_index,
                                None,
                            ) {
                                if let Some(cn) = t.class_name() {
                                    return Some(cn.to_string());
                                }
                            }
                        }
                        return None;
                    }
                    RefKind::FunctionCall { .. } => {
                        let recv = &self.refs[recv_idx];
                        if let Some(InferredType::ClassName(c)) =
                            self.sub_return_type_at_arity(&recv.target_name, Some(0))
                        {
                            return Some(c);
                        }
                        return None;
                    }
                    _ => {}
                    }
                }
            }
        }

        // Variable invocant — bag query handles every typed shape
        // (TC, FrameworkAware, BranchArm, ReturnExpr, cross-file
        // Variable witnesses pushed by enrichment).
        let first = invocant.as_bytes()[0];
        if first == b'$' || first == b'@' || first == b'%' {
            if let Some(t) = self.inferred_type_via_bag(invocant, point) {
                if let Some(cn) = t.class_name() {
                    return Some(cn.to_string());
                }
            }
            // `$self` enclosing-class fallback. Other untyped
            // variable invocants stay None — better than poisoning
            // them with the surrounding package and pretending
            // method calls land on it.
            if invocant == "$self" {
                return self.enclosing_class_for_scope(r.scope);
            }
            return None;
        }

        // Bareword invocant. Could be a zero-arg sub returning
        // ClassName (`app->routes` where `app` is plugin-emitted) —
        // promote that case. Otherwise the bareword *is* the class
        // name (`Foo->method`).
        let bare = invocant.rsplit("::").next().unwrap_or(invocant);
        if let Some(InferredType::ClassName(c)) = self.sub_return_type_at_arity(bare, Some(0)) {
            return Some(c);
        }
        Some(invocant.to_string())
    }

    /// Full `InferredType` of a `MethodCall` ref's invocant — same
    /// dispatch shape as `method_call_invocant_class` but returning
    /// the type, not just the class name. Lets readers that care
    /// about Parametric narrowing (hash-key lookup for DBIC search-
    /// family methods, etc.) inspect `parametric_type_args` without
    /// re-resolving the invocant from scratch.
    pub fn method_call_invocant_type(
        &self,
        r: &Ref,
        module_index: Option<&ModuleIndex>,
    ) -> Option<InferredType> {
        let RefKind::MethodCall { invocant, invocant_span, .. } = &r.kind else {
            return None;
        };
        if invocant.is_empty() {
            return None;
        }
        let point = invocant_span.map(|s| s.start).unwrap_or(r.span.start);

        // Pseudo-invocants (`shift`, `$_[0]`, `__PACKAGE__`) → enclosing class.
        if invocant == "shift" || invocant == "$_[0]" || invocant == "@_[0]" || invocant == "__PACKAGE__" {
            return self.enclosing_class_for_scope(r.scope).map(InferredType::ClassName);
        }

        // Chain / function-call receiver — same indexing path
        // `method_call_invocant_class` uses, but we surface the
        // full type instead of unwrapping to class_name.
        if let Some(span) = invocant_span {
            if let Some(&recv_idx) = self.call_ref_by_start.get(&span.start) {
                let recv_span = self.refs[recv_idx].span;
                let contained = recv_span.start == span.start
                    && (recv_span.end.row, recv_span.end.column)
                        <= (span.end.row, span.end.column);
                let is_self = std::ptr::eq(&self.refs[recv_idx], r);
                if contained && !is_self {
                    match &self.refs[recv_idx].kind {
                        RefKind::MethodCall { .. } => {
                            return self.method_call_return_type_via_bag(recv_idx, module_index);
                        }
                        RefKind::FunctionCall { .. } => {
                            return self.sub_return_type_at_arity(
                                &self.refs[recv_idx].target_name,
                                Some(0),
                            );
                        }
                        _ => {}
                    }
                }
            }
        }

        // Variable invocant.
        let first = invocant.as_bytes()[0];
        if first == b'$' || first == b'@' || first == b'%' {
            if let Some(t) = self.inferred_type_via_bag(invocant, point) {
                return Some(t);
            }
            if invocant == "$self" {
                return self.enclosing_class_for_scope(r.scope).map(InferredType::ClassName);
            }
            return None;
        }

        // Bareword: the bareword *is* the class (or a zero-arg
        // ClassName-returning sub — same rule as
        // `method_call_invocant_class`'s bareword branch).
        let bare = invocant.rsplit("::").next().unwrap_or(invocant);
        if let Some(InferredType::ClassName(c)) = self.sub_return_type_at_arity(bare, Some(0)) {
            return Some(InferredType::ClassName(c));
        }
        Some(InferredType::ClassName(invocant.clone()))
    }

    /// Walk the scope chain to find the enclosing class or package.
    fn enclosing_class_for_scope(&self, scope: ScopeId) -> Option<String> {
        for sid in self.scope_chain(scope).iter() {
            let s = self.scope(*sid);
            if let ScopeKind::Class { ref name } = s.kind {
                return Some(name.clone());
            }
            if let Some(ref pkg) = s.package {
                return Some(pkg.clone());
            }
        }
        None
    }

    /// Test-only wrapper over the private `resolve_invocant_class`.
    #[cfg(test)]
    pub(crate) fn resolve_invocant_class_test(
        &self,
        invocant: &str,
        scope: ScopeId,
        point: Point,
    ) -> Option<String> {
        self.resolve_invocant_class(invocant, scope, point)
    }

    /// Resolve an invocant string to a class name. Internal helper
    /// used by string-based completion / hover-context paths that
    /// don't have a `Ref` in hand. The ref-aware
    /// `method_call_invocant_class` is preferred everywhere a
    /// `&Ref` is available.
    fn resolve_invocant_class(&self, invocant: &str, scope: ScopeId, point: Point) -> Option<String> {
        if invocant.starts_with('$') || invocant.starts_with('@') || invocant.starts_with('%') {
            // Variable invocant → infer type via the witness bag so
            // framework/branch/arity rules refine the answer (falls
            // back to legacy `inferred_type` internally).
            self.inferred_type_via_bag(invocant, point)
                .and_then(|t| t.class_name().map(|s| s.to_string()))
                .or_else(|| {
                    // Enclosing-class fallback only applies to
                    // `$self` — other variable invocants whose type
                    // we don't know stay None, not poisoned with the
                    // surrounding package. Otherwise `$r->to(...)`
                    // with `$r` un-typed would pretend `to` is a
                    // method on the enclosing package (MyApp), and
                    // goto-def on the method name lands on
                    // `package MyApp;`. The comment here described
                    // this guard but the code didn't actually check.
                    if invocant != "$self" {
                        return None;
                    }
                    let chain = self.scope_chain(scope);
                    for scope_id in &chain {
                        let s = self.scope(*scope_id);
                        if let ScopeKind::Class { ref name } = s.kind {
                            return Some(name.clone());
                        }
                        if let Some(ref pkg) = s.package {
                            return Some(pkg.clone());
                        }
                    }
                    None
                })
        } else {
            // Bareword invocant: ambiguous between class-name and
            // zero-arg function call. If a sub by this name resolves
            // (locally or via a cross-file import) to a ClassName
            // return type when called with zero args, treat the
            // bareword as the call and use that class. Mirrors the
            // same rule in `receiver_type_for` and
            // `resolve_invocant_class_tree`.
            let bare = invocant.rsplit("::").next().unwrap_or(invocant);
            if let Some(InferredType::ClassName(c)) =
                self.sub_return_type_at_arity(bare, Some(0))
            {
                return Some(c);
            }
            Some(invocant.to_string())
        }
    }

    /// Find a method definition within a class/package.
    #[cfg(test)]
    pub(crate) fn find_method_in_class(&self, class_name: &str, method_name: &str) -> Option<Span> {
        self.find_method_in_class_with_index(class_name, method_name, None)
    }

    /// Find a method definition, walking the inheritance chain if needed.
    #[cfg(test)]
    fn find_method_in_class_with_index(
        &self,
        class_name: &str,
        method_name: &str,
        module_index: Option<&ModuleIndex>,
    ) -> Option<Span> {
        match self.resolve_method_in_ancestors(class_name, method_name, module_index) {
            Some(MethodResolution::Local { sym_id, .. }) => {
                Some(self.symbol(sym_id).selection_span)
            }
            Some(MethodResolution::CrossFile { .. }) => {
                // Cross-file method found but no local span to return
                // Caller should handle cross-file resolution via ModuleIndex
                None
            }
            None => None,
        }
    }

    /// Single-source-of-truth DFS ancestor walk for every per-class
    /// lookup on this file: walks `class_name` and every ancestor
    /// (local `package_parents` ∪ cross-file `parents_cached`),
    /// cycle-safe via `seen_classes`, depth-capped at 20 (matches
    /// Perl's default MRO and the historical `resolve_method_in_ancestors`
    /// bound). Visitor decides when to stop via `ControlFlow::Break`.
    ///
    /// Both `resolve_method_in_ancestors` (find-first) and
    /// `for_each_dispatch_handler_on_class` (collect-all) route
    /// through here so the two code paths can never drift on MRO
    /// rules. New ancestor-aware queries should reuse it too rather
    /// than reroll the walk.
    fn for_each_ancestor_class(
        &self,
        class_name: &str,
        module_index: Option<&ModuleIndex>,
        mut visit: impl FnMut(&str) -> std::ops::ControlFlow<()>,
    ) {
        // Perl's default MRO is left-to-right depth-first: for
        // `@ISA = (A, B)`, walk A and all A's ancestors before
        // visiting B. A stack-based DFS achieves this by pushing
        // parents in REVERSE order so LIFO pops them in `@ISA`
        // order. The previous implementation pushed left-to-right
        // and visited parents in reverse `@ISA` — wrong for
        // method-resolution semantics, surfaced as same-name
        // overrides on a later parent silently winning over an
        // earlier one. Local + cross-file parents concatenate in
        // `@ISA` order before the reverse-push.
        let mut seen: HashSet<String> = HashSet::new();
        let mut stack: Vec<String> = vec![class_name.to_string()];
        while let Some(cur) = stack.pop() {
            if !seen.insert(cur.clone()) { continue; }
            if seen.len() > 21 { break; } // matches the legacy depth guard
            if let std::ops::ControlFlow::Break(()) = visit(&cur) {
                return;
            }
            let mut parents: Vec<String> = Vec::new();
            if let Some(ps) = self.package_parents.get(&cur) {
                parents.extend(ps.iter().cloned());
            }
            if let Some(idx) = module_index {
                for p in idx.parents_cached(&cur) {
                    if !parents.contains(&p) {
                        parents.push(p);
                    }
                }
            }
            for p in parents.into_iter().rev() {
                stack.push(p);
            }
        }
    }

    /// Inheritance chain for a method rename: `[class, ..., defining_class]`.
    ///
    /// Cross-class method rename has to touch two distinct things:
    ///   * the `sub M` definition in whichever ancestor actually
    ///     defines the method, and
    ///   * every `$obj->M(...)` call site whose static `invocant_class`
    ///     is the rename target *or* an intermediate ancestor that
    ///     inherited (didn't override) the method.
    ///
    /// `rename_method_in_class` is per-class — so callers iterate this
    /// chain. Stops at the first ancestor that defines the method
    /// (inclusive); intermediate ancestors that *override* are
    /// skipped because they're a different method from the
    /// inheritance perspective.
    pub fn method_rename_chain(
        &self,
        class_name: &str,
        method_name: &str,
        module_index: Option<&ModuleIndex>,
    ) -> Vec<String> {
        let defining = match self.resolve_method_in_ancestors(class_name, method_name, module_index) {
            Some(MethodResolution::Local { class, .. })
            | Some(MethodResolution::CrossFile { class }) => class,
            None => return vec![class_name.to_string()],
        };
        let mut chain = Vec::new();
        self.for_each_ancestor_class(class_name, module_index, |cls| {
            chain.push(cls.to_string());
            if cls == defining {
                std::ops::ControlFlow::Break(())
            } else {
                std::ops::ControlFlow::Continue(())
            }
        });
        if chain.is_empty() { chain.push(class_name.to_string()); }
        chain
    }

    /// Walk the inheritance chain to find a method (DFS, matches Perl's default MRO).
    pub fn resolve_method_in_ancestors(
        &self,
        class_name: &str,
        method_name: &str,
        module_index: Option<&ModuleIndex>,
    ) -> Option<MethodResolution> {
        let mut result: Option<MethodResolution> = None;
        self.for_each_ancestor_class(class_name, module_index, |cls| {
            // (a) Local symbols in this file packaged under `cls`.
            for &sid in self.symbols_named(method_name) {
                let sym = self.symbol(sid);
                if matches!(sym.kind, SymKind::Sub | SymKind::Method)
                    && self.symbol_in_class(sid, cls)
                {
                    result = Some(MethodResolution::Local {
                        class: cls.to_string(),
                        sym_id: sid,
                    });
                    return std::ops::ControlFlow::Break(());
                }
            }
            // (b) Local plugin-namespace entities bridged to `cls`.
            for ns in &self.plugin_namespaces {
                if !ns.bridges.iter().any(|b| matches!(b, Bridge::Class(c) if c == cls)) { continue; }
                for sym_id in &ns.entities {
                    let Some(sym) = self.symbols.get(sym_id.0 as usize) else { continue };
                    if !matches!(sym.kind, SymKind::Sub | SymKind::Method) { continue; }
                    if sym.name == method_name {
                        result = Some(MethodResolution::Local {
                            class: cls.to_string(),
                            sym_id: *sym_id,
                        });
                        return std::ops::ControlFlow::Break(());
                    }
                }
            }
            // (c) Cross-file: the cached module for `cls` itself
            // (real CPAN/user-defined methods on the class) plus
            // plugin-emitted methods registered via bridges from
            // other workspace files. Per rule #8 the bridge index
            // is the lookup — see `for_each_entity_bridged_to`.
            if let Some(idx) = module_index {
                if let Some(cached) = idx.get_cached(cls) {
                    if cached.has_sub(method_name) {
                        result = Some(MethodResolution::CrossFile { class: cls.to_string() });
                        return std::ops::ControlFlow::Break(());
                    }
                }
                let mut bridged_hit = false;
                idx.for_each_entity_bridged_to(cls, |_cached, sym| {
                    if bridged_hit { return; }
                    if !matches!(sym.kind, SymKind::Sub | SymKind::Method) { return; }
                    if sym.name == method_name { bridged_hit = true; }
                });
                if bridged_hit {
                    result = Some(MethodResolution::CrossFile { class: cls.to_string() });
                    return std::ops::ControlFlow::Break(());
                }
            }
            std::ops::ControlFlow::Continue(())
        });
        result
    }

    /// Collect every Handler visible from `class_name` whose `dispatchers`
    /// list contains `dispatcher`. Walks the inheritance chain and at
    /// each level pulls Handlers from (1) this file's symbols with
    /// matching owner, (2) this file's `plugin_namespaces` bridged to
    /// the current class, and (3) cross-file via
    /// `module_index.for_each_entity_bridged_to` — rule #8.
    ///
    /// Shares `for_each_ancestor_class` with `resolve_method_in_ancestors`
    /// so the two dispatch paths can't drift on MRO rules. Both
    /// `dispatch_target_completions` and `class_has_dispatch_handlers`
    /// in `symbols.rs` funnel through here.
    ///
    /// `visit(symbol, provenance)` — provenance is `"this file"` for
    /// local hits and the cached module's filename for cross-file
    /// hits (matches the existing detail-string contract).
    pub fn for_each_dispatch_handler_on_class(
        &self,
        class_name: &str,
        dispatcher: &str,
        module_index: Option<&ModuleIndex>,
        mut visit: impl FnMut(&Symbol, &str),
    ) {
        let disp_matches = |dd: &[String]| dd.iter().any(|d| d == dispatcher);
        self.for_each_ancestor_class(class_name, module_index, |cls| {
            // (1) Local Handler symbols owned by this class.
            for sym in &self.symbols {
                if let SymbolDetail::Handler { owner, dispatchers, .. } = &sym.detail {
                    let HandlerOwner::Class(n) = owner;
                    if n == cls && disp_matches(dispatchers) {
                        visit(sym, "this file");
                    }
                }
            }
            // (2) Local plugin-namespace bridge to `cls`.
            for ns in &self.plugin_namespaces {
                if !ns.bridges.iter().any(|b| matches!(b, Bridge::Class(c) if c == cls)) { continue; }
                for sym_id in &ns.entities {
                    let Some(sym) = self.symbols.get(sym_id.0 as usize) else { continue };
                    if let SymbolDetail::Handler { dispatchers, .. } = &sym.detail {
                        if disp_matches(dispatchers) {
                            visit(sym, "this file");
                        }
                    }
                }
            }
            // (3) Cross-file plugin-namespace bridge.
            if let Some(idx) = module_index {
                idx.for_each_entity_bridged_to(cls, |cached, sym| {
                    if let SymbolDetail::Handler { dispatchers, .. } = &sym.detail {
                        if disp_matches(dispatchers) {
                            let prov = cached.path.file_name()
                                .and_then(|s| s.to_str())
                                .unwrap_or("cross-file");
                            visit(sym, prov);
                        }
                    }
                });
            }
            std::ops::ControlFlow::Continue(())
        });
    }

    /// Hover text for a `Handler` symbol or `DispatchCall` ref. Shows
    /// every stacked registration with its param shape, lists the
    /// dispatcher methods that route to it, and names the owning class.
    /// Walks the module index too so consumer-file hovers cross-file
    /// back to the producer's registrations — critical for the common
    /// case where events are defined in a lib and emitted from scripts.
    fn format_handler_hover(
        &self,
        name: &str,
        owner: &HandlerOwner,
        active_dispatcher: Option<&str>,
        module_index: Option<&ModuleIndex>,
    ) -> String {
        let class = match owner {
            HandlerOwner::Class(n) => n.as_str(),
        };

        // Gather stacked registrations from this file first, then any
        // additional ones in the workspace/dependency cache. Each entry
        // is `(line_number, display_params)` rather than a `&Symbol`
        // reference so cross-file handlers (owned by other
        // FileAnalyses) flow through the same formatting path.
        let mut registrations: Vec<(usize, Vec<String>)> = self.symbols.iter()
            .filter(|s| s.name == name)
            .filter_map(|s| match &s.detail {
                SymbolDetail::Handler { owner: o, params, .. } if o == owner => {
                    Some((s.selection_span.start.row + 1, display_handler_params(params)))
                }
                _ => None,
            })
            .collect();

        // Cross-file walk — now O(matches) instead of O(workspace)
        // via the name-based reverse index on ModuleIndex. Only modules
        // that have a symbol with this name are visited; most of the
        // workspace is skipped without any per-module inspection.
        if let Some(idx) = module_index {
            for module_name in idx.modules_with_symbol(name) {
                let Some(cached) = idx.get_cached(&module_name) else { continue };
                for sym in &cached.analysis.symbols {
                    if sym.name != name { continue; }
                    if let SymbolDetail::Handler { owner: o, params, .. } = &sym.detail {
                        if o == owner {
                            registrations.push((
                                sym.selection_span.start.row + 1,
                                display_handler_params(params),
                            ));
                        }
                    }
                }
            }
        }
        registrations.sort();
        registrations.dedup();

        // Dispatchers: union across stacked registrations, current-file only
        // (plugins declare them consistently, no need to walk deps).
        let registrations_ref: Vec<&Symbol> = self.symbols.iter()
            .filter(|s| s.name == name)
            .filter(|s| matches!(
                &s.detail,
                SymbolDetail::Handler { owner: o, .. } if o == owner
            ))
            .collect();

        // Union dispatcher lists across the current-file registrations.
        let mut dispatchers: Vec<String> = registrations_ref.iter()
            .filter_map(|s| match &s.detail {
                SymbolDetail::Handler { dispatchers, .. } => Some(dispatchers.clone()),
                _ => None,
            })
            .flatten()
            .collect();
        // If we have only cross-file registrations, pull dispatchers from
        // the module index cache too so the hover still shows the
        // dispatcher list to the consumer.
        if dispatchers.is_empty() {
            if let Some(idx) = module_index {
                for module_name in idx.modules_with_symbol(name) {
                    let Some(cached) = idx.get_cached(&module_name) else { continue };
                    for sym in &cached.analysis.symbols {
                        if sym.name != name { continue; }
                        if let SymbolDetail::Handler { owner: o, dispatchers: ds, .. } = &sym.detail {
                            if o == owner { dispatchers.extend(ds.clone()); }
                        }
                    }
                }
            }
        }
        dispatchers.sort();
        dispatchers.dedup();

        let mut text = String::new();
        text.push_str(&format!("**handler `{}`** on `{}`\n\n", name, class));

        if registrations.is_empty() {
            text.push_str("*no handler registered in this workspace — dispatch will be a no-op*");
            return text;
        }

        let plural = if registrations.len() == 1 { "" } else { "s" };
        text.push_str(&format!(
            "*{} registration{} stack{}:*\n\n",
            registrations.len(),
            plural,
            if registrations.len() == 1 { "s" } else { "" },
        ));

        for (line, display) in &registrations {
            text.push_str(&format!(
                "- **line {}:** `({})`\n",
                line,
                display.join(", "),
            ));
        }

        if !dispatchers.is_empty() {
            text.push_str(&format!(
                "\n*Dispatch via:* `{}`",
                dispatchers.iter()
                    .map(|d| {
                        if Some(d.as_str()) == active_dispatcher {
                            format!("**->{}(...)**", d)
                        } else {
                            format!("->{}(...)", d)
                        }
                    })
                    .collect::<Vec<_>>()
                    .join(", "),
            ));
        }

        text
    }

    // helpers defined at module scope below
    // (`resolve_cross_file_method` retired — `resolve_method_in_ancestors`
    // now routes through the unified `for_each_ancestor_class` traversal,
    // which already unions local and cross-file parents.)

    /// Check if a symbol is defined within a class/package.
    pub(crate) fn symbol_in_class(&self, sym_id: SymbolId, class_name: &str) -> bool {
        let sym = self.symbol(sym_id);
        // Fast path: check the package captured at symbol creation time.
        // This is authoritative for multi-package files where the scope's
        // mutable `package` field gets overwritten by later package statements.
        if let Some(ref pkg) = sym.package {
            return pkg == class_name;
        }
        // Fallback: walk the scope chain for symbols without a package field.
        let start_scope = self.scope_at(sym.span.start).unwrap_or(sym.scope);
        let chain = self.scope_chain(start_scope);
        for scope_id in &chain {
            let s = self.scope(*scope_id);
            if let ScopeKind::Class { ref name } = s.kind {
                return name == class_name;
            }
            if let Some(ref pkg) = s.package {
                return pkg == class_name;
            }
        }
        false
    }

    /// Find the definition span of a package or class by name.
    fn find_package_or_class(&self, name: &str) -> Option<Span> {
        for &sid in self.symbols_named(name) {
            let sym = self.symbol(sid);
            if matches!(sym.kind, SymKind::Package | SymKind::Class) {
                return Some(sym.selection_span);
            }
        }
        None
    }

    fn format_symbol_hover(&self, sym: &Symbol, source: &str) -> String {
        self.format_symbol_hover_at(sym, source, sym.selection_span.end)
    }

    fn format_symbol_hover_at(&self, sym: &Symbol, source: &str, at: Point) -> String {
        let line = source_line_at(source, sym.span.start.row);
        let mut text = format!("```perl\n{}\n```", line.trim());

        // Append inferred type for variables/fields (bag-routed so
        // framework / branch / arity rules refine the answer).
        if matches!(sym.kind, SymKind::Variable | SymKind::Field) {
            if let Some(it) = self.inferred_type_via_bag(&sym.name, at) {
                text.push_str(&format!("\n\n*type: {}*", format_inferred_type(&it)));
            }
        }

        // Append return type + preceding/POD doc for subs/methods.
        if matches!(sym.kind, SymKind::Sub | SymKind::Method) {
            // Disambiguate `Foo::run` vs `Bar::run` by showing the
            // owning package. Without this, two same-named subs in
            // different packages both render identical hover text
            // and the user can't tell which one the LSP resolved to.
            if let Some(pkg) = sym.package.as_deref() {
                text.push_str(&format!("\n\n*package {}*", pkg));
            }
            if let SymbolDetail::Sub { ref doc, .. } = sym.detail {
                if let Some(rt) = self.symbol_return_type_via_bag(sym.id, None) {
                    text.push_str(&format!("\n\n*returns: {}*", format_inferred_type(&rt)));
                }
                if let Some(d) = doc {
                    text.push_str(&format!("\n\n{}", d));
                }
            }
        }

        text
    }

    // ---- Document outline ----

    /// Build document outline as a nested symbol tree.
    /// Returns (name, detail, kind, span, selection_span, children) tuples.
    pub fn document_symbols(&self) -> Vec<OutlineSymbol> {
        // All top-level entities (subs/methods declared after
        // `package X;`, `my`/`our` decls, `use` imports, …) attach
        // to the file scope directly. Statement-form `package X;`
        // is package context, not a lexical boundary, so it doesn't
        // create an intermediate scope. The bucket-merge + post-sort
        // shim that used to live here is gone — children come out in
        // declaration order from the symbols vector.
        //
        // Plugin namespaces are NOT surfaced. They exist for
        // cross-file bridge lookups (`for_each_entity_bridged_to`),
        // not as navigation targets — users look for the
        // helpers/routes/tasks themselves, which already render flat
        // with their `<word>` kind prefix.
        self.outline_children_of(ScopeId(0))
    }

    fn outline_children_of(&self, parent_scope: ScopeId) -> Vec<OutlineSymbol> {
        let mut result = Vec::new();

        // Plugin fan-out (e.g. Mojo helpers register a Method on both
        // Mojolicious::Controller AND Mojolicious) produces multiple
        // Symbols with the same (name, kind, span). Completion and
        // resolution want them all; the outline wants one entry.
        // Keyed by (kind, name, span_start) — tight enough to dedup
        // true fan-out without collapsing user-written overloads.
        let mut outline_seen: HashSet<(SymKind, String, usize, usize)> = HashSet::new();

        for sym in &self.symbols {
            if sym.scope != parent_scope {
                continue;
            }
            // Per-symbol opt-out. Plugins mark DSL imports / internal
            // infrastructure so the outline stays focused on real
            // user-visible structure.
            let hidden = match &sym.detail {
                SymbolDetail::Sub { hide_in_outline, .. } => *hide_in_outline,
                SymbolDetail::Handler { hide_in_outline, .. } => *hide_in_outline,
                _ => false,
            };
            if hidden { continue; }
            if matches!(sym.kind, SymKind::Sub | SymKind::Method) && sym.namespace.is_framework() {
                let key = (
                    sym.kind,
                    sym.name.clone(),
                    sym.span.start.row,
                    sym.span.start.column,
                );
                if !outline_seen.insert(key) {
                    continue;
                }
            }

            let (name, detail, children) = match sym.kind {
                SymKind::Sub | SymKind::Method => {
                    let body_scope = self.find_body_scope(sym);
                    let children = body_scope
                        .map(|s| self.outline_children_of(s))
                        .unwrap_or_default();
                    // LSP `DocumentSymbol.name` should be the bare
                    // identifier; `kind` (Function/Method) is what
                    // tells the client to render the right icon.
                    //
                    // Plugin-tagged subs are the exception: when a
                    // plugin overrides the display word (helper,
                    // action, route, task, event …), SymbolKind has
                    // no enum value that conveys it, so we keep the
                    // `<word>` prefix in `name` for those — it's the
                    // only surviving kind cue once SymbolKind collapses
                    // Helper/Action/Route → FUNCTION. Native subs and
                    // methods get the spec-compliant bare name and
                    // route their kind word through `detail`.
                    let disp = sub_display_override(&sym.detail);
                    let default_word = if matches!(sym.kind, SymKind::Method) { "method" } else { "sub" };
                    let identifier = sym.outline_label.clone().unwrap_or_else(|| sym.name.clone());
                    let params_suffix = match &sym.detail {
                        SymbolDetail::Sub { params, .. } => {
                            let visible: Vec<&str> = params.iter()
                                .filter(|p| !p.is_invocant)
                                .map(|p| p.name.as_str())
                                .collect();
                            if visible.is_empty() { String::new() }
                            else { format!(" ({})", visible.join(", ")) }
                        }
                        _ => String::new(),
                    };
                    let (label, outline_detail) = match disp.and_then(|d| d.outline_word()) {
                        Some(plugin_word) => (
                            format!("<{}> {}{}", plugin_word, identifier, params_suffix),
                            Some(plugin_word.to_string()),
                        ),
                        None => (
                            identifier,
                            Some(format!("{}{}", default_word, params_suffix)),
                        ),
                    };
                    (label, outline_detail, children)
                }
                SymKind::Class => {
                    let body_scope = self.find_body_scope(sym);
                    let children = body_scope
                        .map(|s| self.outline_children_of(s))
                        .unwrap_or_default();
                    (sym.name.clone(), Some("class".to_string()), children)
                }
                SymKind::Package => {
                    (sym.name.clone(), Some("package".to_string()), Vec::new())
                }
                SymKind::Module => {
                    (format!("use {}", sym.name), None, Vec::new())
                }
                SymKind::Variable => {
                    let detail = match &sym.detail {
                        SymbolDetail::Variable { decl_kind, .. } => match decl_kind {
                            DeclKind::My => "my",
                            DeclKind::Our => "our",
                            DeclKind::State => "state",
                            DeclKind::Field => "field",
                            DeclKind::Param => "param",
                            DeclKind::ForVar => "for",
                        },
                        _ => "my",
                    };
                    (sym.name.clone(), Some(detail.to_string()), Vec::new())
                }
                SymKind::Field => {
                    (sym.name.clone(), Some("field".to_string()), Vec::new())
                }
                SymKind::HashKeyDef => continue, // Skip hash key defs from outline
                SymKind::Handler => {
                    // Show registered handlers in the outline. The
                    // semantic word (`event`/`route`/`task`/…) and
                    // params ride along in the NAME — most outline
                    // clients render only `name`, so baking it there
                    // gives stacked registrations (two handlers on
                    // the same name with different sigs, GET + POST
                    // on the same path) visually distinct entries.
                    // `outline_label` lets the plugin inject a
                    // disambiguator (e.g. HTTP verb) into the
                    // identifier slot without affecting dispatch
                    // lookups, which still key on `sym.name`.
                    let (word, params_suffix) = match &sym.detail {
                        SymbolDetail::Handler { params, display, .. } => {
                            let word = display.outline_word().unwrap_or("handler");
                            let visible: Vec<&str> = params
                                .iter()
                                .filter(|p| !p.is_invocant)
                                .map(|p| p.name.as_str())
                                .collect();
                            let suf = if visible.is_empty() { String::new() }
                                else { format!(" ({})", visible.join(", ")) };
                            (word, suf)
                        }
                        _ => ("handler", String::new()),
                    };
                    let identifier = sym.outline_label.clone().unwrap_or_else(|| sym.name.clone());
                    let label = format!("<{}> {}{}", word, identifier, params_suffix);
                    (label, Some(word.to_string()), Vec::new())
                }
                SymKind::Namespace => {
                    // Real Namespace entries are appended by
                    // `document_symbols` from `plugin_namespaces`,
                    // not from the symbol table. Nothing to do here.
                    continue;
                }
            };

            let handler_display = match &sym.detail {
                SymbolDetail::Handler { display, .. } => Some(*display),
                SymbolDetail::Sub { display: Some(d), .. } => Some(*d),
                _ => None,
            };
            result.push(OutlineSymbol {
                name,
                detail,
                kind: sym.kind,
                span: sym.span,
                selection_span: sym.selection_span,
                children,
                handler_display,
            });
        }

        result
    }

    /// Find the body scope for a sub/method/class symbol.
    fn find_body_scope(&self, sym: &Symbol) -> Option<ScopeId> {
        self.scopes.iter().find(|s| {
            let kind_matches = match (&s.kind, &sym.kind) {
                (ScopeKind::Sub { name: sn }, SymKind::Sub) => sn == &sym.name,
                (ScopeKind::Method { name: mn }, SymKind::Method) => mn == &sym.name,
                (ScopeKind::Class { name: cn }, SymKind::Class) => cn == &sym.name,
                _ => false,
            };
            kind_matches && s.span == sym.span
        }).map(|s| s.id)
    }

    // ---- Semantic tokens ----

    /// Collect semantic tokens for all variable references and declarations.
    pub fn semantic_tokens(&self) -> Vec<PerlSemanticToken> {
        let mut tokens: Vec<PerlSemanticToken> = Vec::new();

        // ---- Variable/parameter/self declarations from symbols ----
        for sym in &self.symbols {
            match sym.kind {
                SymKind::Variable | SymKind::Field => {
                    let is_self = sym.name == "$self" || sym.name == "$class";
                    let (sigil, is_readonly, is_param) = match &sym.detail {
                        SymbolDetail::Variable { sigil, decl_kind } => {
                            let readonly = matches!(decl_kind, DeclKind::Field);
                            let is_param = matches!(decl_kind, DeclKind::Param | DeclKind::ForVar);
                            (*sigil, readonly, is_param)
                        }
                        SymbolDetail::Field { sigil, attributes } => {
                            let readonly = !attributes.iter().any(|a| a == "writer" || a == "mutator" || a == "accessor");
                            (*sigil, readonly, true)
                        }
                        _ => continue,
                    };
                    let token_type = if is_self { TOK_KEYWORD } else if is_param { TOK_PARAMETER } else { TOK_VARIABLE };
                    // Don't add sigil modifier for $self/$class — it would override the keyword color
                    let mut mods = if is_self { 0 } else { sigil_modifier(sigil) };
                    mods |= 1 << MOD_DECLARATION;
                    if is_readonly { mods |= 1 << MOD_READONLY; }
                    tokens.push(PerlSemanticToken { span: sym.selection_span, token_type, modifiers: mods });
                }
                SymKind::Package | SymKind::Class => {
                    tokens.push(PerlSemanticToken {
                        span: sym.selection_span,
                        token_type: TOK_NAMESPACE,
                        modifiers: 1 << MOD_DECLARATION,
                    });
                }
                SymKind::Module => {
                    tokens.push(PerlSemanticToken {
                        span: sym.selection_span,
                        token_type: TOK_NAMESPACE,
                        modifiers: 0,
                    });
                }
                SymKind::Sub => {
                    tokens.push(PerlSemanticToken {
                        span: sym.selection_span,
                        token_type: TOK_FUNCTION,
                        modifiers: 1 << MOD_DECLARATION,
                    });
                }
                SymKind::Method => {
                    tokens.push(PerlSemanticToken {
                        span: sym.selection_span,
                        token_type: TOK_METHOD,
                        modifiers: 1 << MOD_DECLARATION,
                    });
                }
                _ => {}
            }
        }

        // ---- Refs: variables, functions, methods, properties, namespaces ----
        let imported_names: std::collections::HashSet<&str> = self.imports.iter()
            .flat_map(|imp| imp.imported_symbols.iter().map(|s| s.local_name.as_str()))
            .collect();

        for r in &self.refs {
            // Skip declaration refs — the symbol loop already emits tokens for declarations
            if matches!(r.access, AccessKind::Declaration) {
                continue;
            }
            match &r.kind {
                RefKind::Variable | RefKind::ContainerAccess => {
                    let sigil = r.target_name.chars().next().unwrap_or('$');
                    let is_self = r.target_name == "$self" || r.target_name == "$class";
                    let token_type = if is_self { TOK_KEYWORD } else { TOK_VARIABLE };
                    // Don't add sigil modifier for $self/$class — it would override the keyword color
                    let mut mods = if is_self { 0 } else { sigil_modifier(sigil) };
                    if matches!(r.access, AccessKind::Write) { mods |= 1 << MOD_MODIFICATION; }
                    tokens.push(PerlSemanticToken { span: r.span, token_type, modifiers: mods });
                }
                RefKind::FunctionCall { .. } => {
                    // Framework DSL keywords → macro, otherwise function
                    let token_type = if self.framework_imports.contains(r.target_name.as_str()) {
                        TOK_MACRO
                    } else {
                        TOK_FUNCTION
                    };
                    let mut mods = 0;
                    if imported_names.contains(r.target_name.as_str()) {
                        mods |= 1 << MOD_DEFAULT_LIBRARY;
                    }
                    tokens.push(PerlSemanticToken { span: r.span, token_type, modifiers: mods });
                }
                RefKind::MethodCall { method_name_span, .. } => {
                    // Use method_name_span for precise highlighting of just the method name
                    let mods = 0; // TODO: readonly for ro accessors, static for class methods
                    tokens.push(PerlSemanticToken { span: *method_name_span, token_type: TOK_METHOD, modifiers: mods });
                }
                RefKind::PackageRef => {
                    tokens.push(PerlSemanticToken { span: r.span, token_type: TOK_NAMESPACE, modifiers: 0 });
                }
                RefKind::HashKeyAccess { .. } => {
                    tokens.push(PerlSemanticToken { span: r.span, token_type: TOK_PROPERTY, modifiers: 0 });
                }
                RefKind::DispatchCall { .. } => {
                    // Colors dispatch-call event names like property keys —
                    // same visual weight as other named members of a class.
                    tokens.push(PerlSemanticToken { span: r.span, token_type: TOK_PROPERTY, modifiers: 0 });
                }
            }
        }

        // ---- HashKeyDef symbols → property tokens ----
        for sym in &self.symbols {
            if matches!(sym.kind, SymKind::HashKeyDef) {
                tokens.push(PerlSemanticToken {
                    span: sym.selection_span,
                    token_type: TOK_PROPERTY,
                    modifiers: 1 << MOD_DECLARATION,
                });
            }
        }

        tokens.sort_by_key(|t| (t.span.start.row, t.span.start.column));
        // Dedup by position — if two tokens start at the same (row, col), keep the first
        tokens.dedup_by(|b, a| a.span.start.row == b.span.start.row && a.span.start.column == b.span.start.column);
        tokens
    }
}

// ---- Completion priority constants ----
//
// Lower numbers sort first. Used by both file_analysis (local completions)
// and symbols.rs (cross-file completions).

/// Variables, local subs, methods — direct scope match.
pub const PRIORITY_LOCAL: u8 = 0;
/// General subs, hash keys, keyval args — file-wide match.
pub const PRIORITY_FILE_WIDE: u8 = 10;
/// Explicitly imported via `use Foo qw(bar)`.
pub const PRIORITY_EXPLICIT_IMPORT: u8 = 12;
/// Bare `use Foo;` @EXPORT symbol (no qw list to edit).
pub const PRIORITY_BARE_IMPORT: u8 = 15;
/// Auto-add to existing `qw()` list.
pub const PRIORITY_AUTO_ADD_QW: u8 = 18;
/// Sub already used as first param (less relevant).
pub const PRIORITY_LESS_RELEVANT: u8 = 20;
/// Unimported module — inserts full `use` statement.
pub const PRIORITY_UNIMPORTED: u8 = 25;
/// Dynamic hash keys (may not exist).
pub const PRIORITY_DYNAMIC: u8 = 50;

// ---- Method resolution types ----

/// Result of resolving a method through the inheritance chain.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub enum MethodResolution {
    /// Found in a local class within this file.
    Local { class: String, sym_id: SymbolId },
    /// Found in a cross-file module (use ModuleIndex to get details).
    CrossFile { class: String },
}

/// Result of resolving a sub/method call — local symbol or cross-file metadata.
pub enum ResolvedSub<'a> {
    /// Found locally in this file's symbols.
    Local(&'a Symbol),
    /// Found in a cross-file module via ModuleIndex.
    CrossFile {
        params: Vec<ParamInfo>,
        /// Inferred type per param (parallel to `params`); `None` if unknown.
        param_types: Vec<Option<InferredType>>,
        is_method: bool,
        hash_keys: Vec<String>,
    },
}

// ---- Completion types ----

/// A completion candidate from FileAnalysis resolution (pure table lookup).
#[derive(Debug, Clone)]
pub struct CompletionCandidate {
    pub label: String,
    pub kind: SymKind,
    pub detail: Option<String>,
    pub insert_text: Option<String>,
    pub sort_priority: u8,
    /// Additional text edits applied when this candidate is accepted (e.g. auto-import).
    pub additional_edits: Vec<(Span, String)>,
    /// Plugin-provided display override. When `Some`, the LSP adapter renders
    /// the candidate with this kind instead of `kind`'s default mapping. Lets
    /// helpers/routes/DSL verbs carry their plugin-chosen icon all the way
    /// through completion without leaking plugin specifics into the core.
    pub display_override: Option<HandlerDisplay>,
}

/// Signature info for a sub/method, resolved from the symbol table.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct SignatureInfo {
    pub name: String,
    pub params: Vec<ParamInfo>,
    pub is_method: bool,
    /// End of the sub body — used to query inferred types for params.
    pub body_end: Point,
    /// Pre-resolved param types (for cross-file subs where body_end is meaningless).
    pub param_types: Option<Vec<Option<String>>>,
}

// ---- Completion query methods ----

impl FileAnalysis {
    /// Complete variables at a point with cross-sigil forms.
    pub fn complete_variables(&self, point: Point, sigil: char) -> Vec<CompletionCandidate> {
        let visible = self.visible_symbols(point);
        let mut seen = HashSet::<(String, char)>::new();
        let mut candidates = Vec::new();

        // Sort by scope size (innermost first) — stable priority ordering
        let mut vars: Vec<(&Symbol, usize)> = visible
            .into_iter()
            .filter(|s| matches!(s.kind, SymKind::Variable | SymKind::Field))
            .filter_map(|s| {
                if let SymbolDetail::Variable { .. } = &s.detail {
                    let scope = &self.scopes[s.scope.0 as usize];
                    let scope_size = span_size(&scope.span);
                    Some((s, scope_size))
                } else if let SymbolDetail::Field { .. } = &s.detail {
                    let scope = &self.scopes[s.scope.0 as usize];
                    let scope_size = span_size(&scope.span);
                    Some((s, scope_size))
                } else {
                    None
                }
            })
            .collect();
        vars.sort_by_key(|(_, sz)| *sz);

        for (sym, scope_size) in vars {
            let (bare_name, decl_sigil) = match &sym.detail {
                SymbolDetail::Variable { sigil: ds, .. } => {
                    (sym.name[1..].to_string(), *ds)
                }
                SymbolDetail::Field { sigil: ds, .. } => {
                    (sym.name[1..].to_string(), *ds)
                }
                _ => continue,
            };
            let key = (bare_name.clone(), decl_sigil);
            if seen.contains(&key) {
                continue;
            }
            seen.insert(key);

            let priority = std::cmp::min(scope_size, 255) as u8;
            let detail = match &sym.detail {
                SymbolDetail::Variable { decl_kind, .. } => {
                    Some(match decl_kind {
                        DeclKind::My => "my".to_string(),
                        DeclKind::Our => "our".to_string(),
                        DeclKind::State => "state".to_string(),
                        DeclKind::Field => "field".to_string(),
                        DeclKind::Param => "param".to_string(),
                        DeclKind::ForVar => "for".to_string(),
                    })
                }
                SymbolDetail::Field { .. } => Some("field".to_string()),
                _ => None,
            };

            generate_cross_sigil_candidates(
                &bare_name,
                decl_sigil,
                sigil,
                detail,
                priority,
                &mut candidates,
            );
        }

        candidates
    }

    /// Complete methods for an invocant (variable or class name) at a point.
    pub fn complete_methods(&self, invocant: &str, point: Point) -> Vec<CompletionCandidate> {
        let class_name = if !invocant.starts_with('$')
            && !invocant.starts_with('@')
            && !invocant.starts_with('%')
        {
            Some(invocant.to_string())
        } else {
            self.resolve_invocant_class(
                invocant,
                self.scope_at(point).unwrap_or(ScopeId(0)),
                point,
            )
        };

        if let Some(ref cn) = class_name {
            let candidates = self.complete_methods_for_class(cn, None);
            if !candidates.is_empty() {
                return candidates;
            }
        }

        // Fallback: native subs/methods in file, deduped by label.
        //
        // Plugin-synthesized entries are skipped on purpose. A plugin
        // emits Methods on specific classes (Mojo helpers on
        // Controller, DBIC accessors on the schema, etc.); without a
        // known receiver type we can't say which ones apply here.
        // Surfacing them blindly dumps framework noise onto every
        // untyped `$x->` call site. Native entries stay — those are
        // always valid candidates regardless of receiver.
        let mut seen = HashSet::<String>::new();
        self.symbols
            .iter()
            .filter(|s| matches!(s.kind, SymKind::Sub | SymKind::Method))
            .filter(|s| !s.namespace.is_framework())
            .filter(|s| seen.insert(s.name.clone()))
            .map(|s| CompletionCandidate {
                label: s.name.clone(),
                kind: s.kind,
                detail: Some(
                    if matches!(s.kind, SymKind::Method) {
                        "method"
                    } else {
                        "sub"
                    }
                    .to_string(),
                ),
                insert_text: None,
                sort_priority: PRIORITY_FILE_WIDE,
                additional_edits: vec![],
                display_override: sub_display_override(&s.detail),
            })
            .collect()
    }

    /// Complete hash keys for a resolved owner.
    fn complete_hash_keys_for_owner(&self, owner: &HashKeyOwner) -> Vec<CompletionCandidate> {
        let defs = self.hash_key_defs_for_owner(owner);
        let mut seen = HashSet::new();
        let mut candidates = Vec::new();

        for def in defs {
            if !seen.insert(def.name.clone()) {
                continue;
            }

            let is_dynamic = matches!(
                &def.detail,
                SymbolDetail::HashKeyDef { is_dynamic: true, .. }
            );

            let detail = match owner {
                HashKeyOwner::Class(name) => format!("{}->{{{}}}", name, def.name),
                HashKeyOwner::Variable { name, .. } => format!("{}{{{}}}", name, def.name),
                HashKeyOwner::Sub { name, .. } => format!("{}()->{{{}}}", name, def.name),
            };

            candidates.push(CompletionCandidate {
                label: def.name.clone(),
                kind: SymKind::Variable,
                detail: Some(detail),
                insert_text: None,
                sort_priority: if is_dynamic { PRIORITY_DYNAMIC } else { PRIORITY_FILE_WIDE },
                additional_edits: vec![],
                display_override: None,
            });
        }

        candidates
    }

    /// Complete hash keys for a variable at a point.
    pub fn complete_hash_keys(&self, var_text: &str, point: Point) -> Vec<CompletionCandidate> {
        match self.resolve_hash_key_owner(var_text, point) {
            Some(owner) => self.complete_hash_keys_for_owner(&owner),
            None => Vec::new(),
        }
    }

    /// Complete hash keys for a known class name (from expression type resolution).
    pub fn complete_hash_keys_for_class(&self, class_name: &str, _point: Point) -> Vec<CompletionCandidate> {
        self.complete_hash_keys_for_owner(&HashKeyOwner::Class(class_name.to_string()))
    }

    /// Complete hash keys for a sub's return value (from expression type resolution).
    ///
    /// Tries the caller's enclosing package first (local subs), then falls
    /// back to an unpackaged owner (imported subs whose synthetic HashKeyDef
    /// was added during enrichment with `package: None`).
    pub fn complete_hash_keys_for_sub(&self, sub_name: &str, _point: Point) -> Vec<CompletionCandidate> {
        // Try each candidate owner variant until one has defs.
        let mut out = Vec::new();
        let mut seen = HashSet::new();
        let push_unique = |cands: Vec<CompletionCandidate>, out: &mut Vec<CompletionCandidate>, seen: &mut HashSet<String>| {
            for c in cands {
                if seen.insert(c.label.clone()) {
                    out.push(c);
                }
            }
        };
        for sym in &self.symbols {
            if (sym.kind == SymKind::Sub || sym.kind == SymKind::Method) && sym.name == sub_name {
                let owner = HashKeyOwner::Sub { package: sym.package.clone(), name: sub_name.to_string() };
                push_unique(self.complete_hash_keys_for_owner(&owner), &mut out, &mut seen);
            }
        }
        let imported_owner = HashKeyOwner::Sub { package: None, name: sub_name.to_string() };
        push_unique(self.complete_hash_keys_for_owner(&imported_owner), &mut out, &mut seen);

        // Final sweep: match any HashKeyDef whose owner is Sub{name: sub_name}
        // regardless of package. Covers plugin-synthesized options (e.g.
        // `Sub { package: Minion, name: enqueue }` from the minion plugin)
        // where the sub itself isn't in the local symbol table.
        let pseudo_syms: Vec<_> = self.symbols.iter()
            .filter(|s| {
                if !matches!(s.kind, SymKind::HashKeyDef) { return false; }
                matches!(&s.detail, SymbolDetail::HashKeyDef {
                    owner: HashKeyOwner::Sub { name, .. }, ..
                } if name == sub_name)
            })
            .collect();
        for def in pseudo_syms {
            if seen.insert(def.name.clone()) {
                let detail = format!("{}() option", sub_name);
                out.push(CompletionCandidate {
                    label: def.name.clone(),
                    kind: SymKind::Variable,
                    detail: Some(detail),
                    insert_text: None,
                    sort_priority: PRIORITY_FILE_WIDE,
                    additional_edits: vec![],
                    display_override: None,
                });
            }
        }

        // Body-derived keys: if the sub has a final hashref-ish param
        // (`sub foo { my ($x, $opts) = @_; $opts->{priority} }`), the
        // key accesses in the body reveal the expected option names.
        // Mirror of `complete_keyval_args` but for the nested-hash-literal
        // call shape (`foo($x, { | })`) routed through HashKey context.
        for sym in &self.symbols {
            if sym.name != sub_name { continue; }
            if !matches!(sym.kind, SymKind::Sub | SymKind::Method) { continue; }
            let params = match &sym.detail {
                SymbolDetail::Sub { params, .. } => params,
                _ => continue,
            };
            let hashish = params
                .iter()
                .find(|p| p.is_slurpy && p.name.starts_with('%'))
                .or_else(|| params
                    .last()
                    .filter(|p| !p.is_invocant && p.name.starts_with('$')));
            let bare_name = match hashish {
                Some(p) if p.name.len() > 1 => &p.name[1..],
                _ => continue,
            };
            let Some(body_scope) = self.find_body_scope(sym) else { continue };
            for k in self.hash_keys_in_scope(bare_name, body_scope) {
                if seen.insert(k.clone()) {
                    out.push(CompletionCandidate {
                        label: k,
                        kind: SymKind::Variable,
                        detail: Some(format!("{}() option", sub_name)),
                        insert_text: None,
                        sort_priority: PRIORITY_FILE_WIDE,
                        additional_edits: vec![],
                        display_override: None,
                    });
                }
            }
        }

        out
    }

    /// General completion: all variables (all sigils) + subs + packages.
    pub fn complete_general(&self, point: Point) -> Vec<CompletionCandidate> {
        let mut candidates = Vec::new();

        // Variables (all sigils)
        for sigil in ['$', '@', '%'] {
            candidates.extend(self.complete_variables(point, sigil));
        }

        // Subs
        for sym in &self.symbols {
            if matches!(sym.kind, SymKind::Sub | SymKind::Method) {
                candidates.push(CompletionCandidate {
                    label: sym.name.clone(),
                    kind: sym.kind,
                    detail: Some(
                        if matches!(sym.kind, SymKind::Method) {
                            "method"
                        } else {
                            "sub"
                        }
                        .to_string(),
                    ),
                    insert_text: None,
                    sort_priority: PRIORITY_FILE_WIDE,
                    additional_edits: vec![],
                display_override: None,
                });
            }
        }

        // Packages/classes
        for sym in &self.symbols {
            if matches!(sym.kind, SymKind::Package | SymKind::Class) {
                candidates.push(CompletionCandidate {
                    label: sym.name.clone(),
                    kind: sym.kind,
                    detail: Some(
                        if matches!(sym.kind, SymKind::Class) {
                            "class"
                        } else {
                            "package"
                        }
                        .to_string(),
                    ),
                    insert_text: None,
                    sort_priority: PRIORITY_LESS_RELEVANT,
                    additional_edits: vec![],
                display_override: None,
                });
            }
        }

        candidates
    }

    /// Complete keyval args at a call site.
    /// Returns `key =>` completions for unused keys.
    pub fn complete_keyval_args(
        &self,
        call_name: &str,
        is_method: bool,
        invocant: Option<&str>,
        point: Point,
        used_keys: &HashSet<String>,
        module_index: Option<&ModuleIndex>,
    ) -> Vec<CompletionCandidate> {
        // For `new` calls on a class, check for :param fields
        if call_name == "new" {
            if let Some(inv) = invocant {
                let class_name = if !inv.starts_with('$') {
                    Some(inv.to_string())
                } else {
                    self.resolve_invocant_class(
                        inv,
                        self.scope_at(point).unwrap_or(ScopeId(0)),
                        point,
                    )
                };
                if let Some(ref cn) = class_name {
                    let param_candidates = self.class_param_completions(cn, used_keys);
                    if !param_candidates.is_empty() {
                        return param_candidates;
                    }
                }
            }
        }

        // Find the sub definition (local or cross-file)
        let resolved = match self.find_sub_for_call(call_name, is_method, invocant, point, module_index) {
            Some(r) => r,
            None => return Vec::new(),
        };

        match resolved {
            ResolvedSub::Local(sub_sym) => {
                let params = match &sub_sym.detail {
                    SymbolDetail::Sub { params, .. } => params,
                    _ => return Vec::new(),
                };

                // Pick the param that carries key=>value pairs:
                //   * slurpy `%opts` is the classic shape
                //   * final `$opts` scalar deref'd as a hashref in the
                //     body (`$opts->{…}`) is the same pattern — we
                //     collect the same way, just strip the `$` sigil
                //     when scanning the body. Previously only slurpy
                //     worked; every "options-hashref" sub missed out.
                let hashish = params
                    .iter()
                    .find(|p| p.is_slurpy && p.name.starts_with('%'))
                    .or_else(|| params
                        .last()
                        .filter(|p| !p.is_invocant && p.name.starts_with('$')));
                let slurpy_name = match hashish {
                    Some(p) => {
                        if p.name.starts_with('%') || p.name.starts_with('$') || p.name.starts_with('@') {
                            &p.name[1..]
                        } else {
                            &p.name
                        }
                    }
                    None => return Vec::new(),
                };

                // Find hash key accesses for this param name within the sub's body scope
                let body_scope = self.find_body_scope(sub_sym);
                let keys = match body_scope {
                    Some(scope_id) => self.hash_keys_in_scope(slurpy_name, scope_id),
                    None => Vec::new(),
                };
                // Bail silently when the chosen scalar doesn't actually
                // get deref'd as a hash — the last-param heuristic is
                // loose; no accesses means "not an options param".
                if keys.is_empty() { return Vec::new(); }

                keys.into_iter()
                    .filter(|k| !used_keys.contains(k))
                    .map(|k| CompletionCandidate {
                        label: format!("{} =>", k),
                        kind: SymKind::Variable,
                        detail: Some(format!("{}(%{})", call_name, slurpy_name)),
                        insert_text: Some(format!("{} => ", k)),
                        sort_priority: PRIORITY_LOCAL,
                        additional_edits: vec![],
                display_override: None,
                    })
                    .collect()
            }
            ResolvedSub::CrossFile { hash_keys, params, .. } => {
                // Check if any param is slurpy %hash
                let has_slurpy = params.iter().any(|p| p.is_slurpy && p.name.starts_with('%'));
                if !has_slurpy || hash_keys.is_empty() {
                    return Vec::new();
                }

                hash_keys.into_iter()
                    .filter(|k| !used_keys.contains(k))
                    .map(|k| CompletionCandidate {
                        label: format!("{} =>", k),
                        kind: SymKind::Variable,
                        detail: Some(format!("{}()", call_name)),
                        insert_text: Some(format!("{} => ", k)),
                        sort_priority: PRIORITY_LOCAL,
                        additional_edits: vec![],
                display_override: None,
                    })
                    .collect()
            }
        }
    }

    /// Resolve signature info for a call (sub/method name).
    pub fn signature_for_call(
        &self,
        name: &str,
        is_method: bool,
        invocant: Option<&str>,
        point: Point,
        module_index: Option<&ModuleIndex>,
    ) -> Option<SignatureInfo> {
        let resolved = self.find_sub_for_call(name, is_method, invocant, point, module_index)?;

        match resolved {
            ResolvedSub::Local(sub_sym) => {
                let (params, sym_is_method) = match &sub_sym.detail {
                    SymbolDetail::Sub { params, is_method, .. } => (params.clone(), *is_method),
                    _ => return None,
                };

                let mut params = params;
                let is_method = is_method
                    || sym_is_method
                    || params
                        .first()
                        .map_or(false, |p| p.name == "$self" || p.name == "$class");

                // Strip the implicit invocant from the display list.
                // `is_invocant` covers both Perl-native `$self`/`$class`
                // (flagged by the builder at extract time) and plugin-
                // marked framework invocants (`$c` for helpers, etc.).
                if !params.is_empty() && params[0].is_invocant {
                    params.remove(0);
                }

                Some(SignatureInfo {
                    name: name.to_string(),
                    params,
                    is_method,
                    body_end: sub_sym.span.end,
                    param_types: None, // local — use inferred_type() with body_end
                })
            }
            ResolvedSub::CrossFile {
                params: cross_params,
                param_types: cross_param_types,
                is_method: cf_is_method,
                ..
            } => {
                let mut params: Vec<ParamInfo> = cross_params;
                let mut param_types: Vec<Option<String>> = cross_param_types
                    .into_iter()
                    .map(|t| t.as_ref().map(inferred_type_to_tag))
                    .collect();

                let is_method = is_method || cf_is_method
                    || params.first().map_or(false, |p| p.name == "$self" || p.name == "$class");

                // Same invocant-strip as the local branch — by flag,
                // not by name. Cross-file ParamInfo carries the flag
                // through the cache (set by the plugin or builder at
                // build time), so `$c` on a helper is dropped the
                // same way `$self` on a Perl method is.
                if !params.is_empty() && params[0].is_invocant {
                    params.remove(0);
                    if !param_types.is_empty() {
                        param_types.remove(0);
                    }
                }

                Some(SignatureInfo {
                    name: name.to_string(),
                    params,
                    is_method,
                    body_end: Point::new(0, 0),
                    param_types: Some(param_types),
                })
            }
        }
    }

    // ---- Internal completion helpers ----

    /// Find a sub/method by name, optionally scoped to a class.
    /// Returns `ResolvedSub::Local` for same-file symbols, or `ResolvedSub::CrossFile`
    /// for inherited methods and imported functions found via `ModuleIndex`.
    fn find_sub_for_call<'s>(
        &'s self,
        name: &str,
        is_method: bool,
        invocant: Option<&str>,
        point: Point,
        module_index: Option<&ModuleIndex>,
    ) -> Option<ResolvedSub<'s>> {
        // Resolve class name for scoped lookup
        let class_name = if is_method {
            invocant.and_then(|inv| {
                if !inv.starts_with('$') && !inv.starts_with('@') && !inv.starts_with('%') {
                    Some(inv.to_string())
                } else {
                    self.resolve_invocant_class(
                        inv,
                        self.scope_at(point).unwrap_or(ScopeId(0)),
                        point,
                    )
                }
            })
        } else {
            None
        };

        // Try inheritance-aware class-scoped lookup first
        if let Some(ref cn) = class_name {
            match self.resolve_method_in_ancestors(cn, name, module_index) {
                Some(MethodResolution::Local { sym_id, .. }) => {
                    return Some(ResolvedSub::Local(self.symbol(sym_id)));
                }
                Some(MethodResolution::CrossFile { ref class }) => {
                    if let Some(idx) = module_index {
                        if let Some(cached) = idx.get_cached(class) {
                            if let Some(sub_info) = cached.sub_info(name) {
                                return Some(cross_file_resolved(&sub_info));
                            }
                        }
                    }
                }
                None => {}
            }
        }

        // Fallback: any local sub/method with that name
        for &sid in self.symbols_named(name) {
            let sym = self.symbol(sid);
            if matches!(sym.kind, SymKind::Sub | SymKind::Method) {
                return Some(ResolvedSub::Local(sym));
            }
        }

        // Fallback: imported function via ModuleIndex
        if !is_method {
            if let Some(idx) = module_index {
                for import in &self.imports {
                    if let Some(is) = import.imported_symbols.iter().find(|s| s.local_name == *name) {
                        if let Some(cached) = idx.get_cached(&import.module_name) {
                            if let Some(sub_info) = cached.sub_info(is.remote()) {
                                return Some(cross_file_resolved(&sub_info));
                            }
                        }
                    }
                }
                // Also check @EXPORT (bare imports)
                for import in &self.imports {
                    if let Some(cached) = idx.get_cached(&import.module_name) {
                        if cached.analysis.export.iter().any(|s| s == name) {
                            if let Some(sub_info) = cached.sub_info(name) {
                                return Some(cross_file_resolved(&sub_info));
                            }
                        }
                    }
                }
            }
        }

        None
    }

    /// Resolve a variable text to a HashKeyOwner for hash key completion.
    fn resolve_hash_key_owner(&self, var_text: &str, point: Point) -> Option<HashKeyOwner> {
        let bare_name = if var_text.starts_with('$') || var_text.starts_with('@') || var_text.starts_with('%') {
            &var_text[1..]
        } else {
            var_text
        };

        // Try type inference → class owner (bag-routed). Hash-
        // key context: read `hash_key_class()` so Parametric
        // values narrow to their row-class arg (DBIC `$row->{name}`
        // after `find` etc.). For non-Parametric this is
        // equivalent to `class_name()`. CLAUDE.md invariant #10.
        if let Some(it) = self.inferred_type_via_bag(var_text, point) {
            if let Some(cn) = it.hash_key_class() {
                return Some(HashKeyOwner::Class(cn.to_string()));
            }
        }

        // Check call bindings → follow to sub's return hash keys
        for cb in &self.call_bindings {
            if cb.variable == var_text
                && cb.span.start <= point
                && contains_point(&self.scopes[cb.scope.0 as usize].span, point)
            {
                let package = self.sub_defining_package(&cb.func_name);
                return Some(HashKeyOwner::Sub { package, name: cb.func_name.clone() });
            }
        }

        // Check method call bindings → follow to method's return hash keys
        for mcb in &self.method_call_bindings {
            if mcb.variable == var_text
                && mcb.span.start <= point
                && contains_point(&self.scopes[mcb.scope.0 as usize].span, point)
            {
                let package = self.sub_defining_package(&mcb.method_name);
                return Some(HashKeyOwner::Sub { package, name: mcb.method_name.clone() });
            }
        }

        // Try resolving the variable declaration → Variable owner
        // For $hash{}, try %hash first
        let try_names: Vec<String> = if var_text.starts_with('$') {
            vec![format!("%{}", bare_name), var_text.to_string()]
        } else {
            vec![var_text.to_string()]
        };

        for name in &try_names {
            if let Some(sym) = self.resolve_variable(name, point) {
                return Some(HashKeyOwner::Variable {
                    name: name.clone(),
                    def_scope: sym.scope,
                });
            }
        }

        // Check if any existing hash key refs/defs use this bare_name
        for sym in &self.symbols {
            if let SymbolDetail::HashKeyDef { ref owner, .. } = sym.detail {
                match owner {
                    HashKeyOwner::Variable { name, .. } => {
                        let owner_bare = if name.starts_with('$') || name.starts_with('@') || name.starts_with('%') {
                            &name[1..]
                        } else {
                            name
                        };
                        if owner_bare == bare_name {
                            return Some(owner.clone());
                        }
                    }
                    HashKeyOwner::Class(_) | HashKeyOwner::Sub { .. } => {}
                }
            }
        }

        None
    }

    /// Look up the defining package of a sub/method by name. Returns None when
    /// the sub is not found locally (imported, or absent). Used to package-
    /// qualify `HashKeyOwner::Sub` so distinct same-name subs in different
    /// packages don't collide at query time.
    fn sub_defining_package(&self, name: &str) -> Option<String> {
        for sym in &self.symbols {
            if (sym.kind == SymKind::Sub || sym.kind == SymKind::Method) && sym.name == name {
                return sym.package.clone();
            }
        }
        None
    }

    /// Collect :param field names from a core class as keyval completions.
    fn class_param_completions(
        &self,
        class_name: &str,
        used_keys: &HashSet<String>,
    ) -> Vec<CompletionCandidate> {
        let mut candidates = Vec::new();
        for sym in &self.symbols {
            if matches!(sym.kind, SymKind::Field) {
                if let SymbolDetail::Field { ref attributes, .. } = sym.detail {
                    if attributes.contains(&"param".to_string()) {
                        // Check this field belongs to the class
                        if self.symbol_in_class(sym.id, class_name) {
                            let key = sym.bare_name().to_string();
                            if !used_keys.contains(&key) {
                                candidates.push(CompletionCandidate {
                                    label: format!("{} =>", key),
                                    kind: SymKind::Variable,
                                    detail: Some(format!("{}->new(:param)", class_name)),
                                    insert_text: Some(format!("{} => ", key)),
                                    sort_priority: PRIORITY_LOCAL,
                    additional_edits: vec![],
                display_override: None,
                                });
                            }
                        }
                    }
                }
            }
        }
        candidates
    }

    /// Find hash key names accessed via a variable in a specific scope.
    fn hash_keys_in_scope(&self, var_bare_name: &str, scope_id: ScopeId) -> Vec<String> {
        let scope_span = &self.scopes[scope_id.0 as usize].span;
        let mut keys = Vec::new();
        let mut seen = HashSet::new();

        for r in &self.refs {
            if let RefKind::HashKeyAccess { ref var_text, .. } = r.kind {
                // Check the var_text's bare name matches
                let ref_bare = if var_text.starts_with('$')
                    || var_text.starts_with('@')
                    || var_text.starts_with('%')
                {
                    &var_text[1..]
                } else {
                    var_text.as_str()
                };
                if ref_bare == var_bare_name && contains_point(scope_span, r.span.start) {
                    if !seen.contains(&r.target_name) {
                        seen.insert(r.target_name.clone());
                        keys.push(r.target_name.clone());
                    }
                }
            }
        }

        keys
    }
}

/// Generate cross-sigil completion candidates for a variable.
fn generate_cross_sigil_candidates(
    bare_name: &str,
    decl_sigil: char,
    requested_sigil: char,
    detail: Option<String>,
    priority: u8,
    out: &mut Vec<CompletionCandidate>,
) {
    match requested_sigil {
        '$' => {
            if decl_sigil == '$' {
                out.push(CompletionCandidate {
                    label: format!("${}", bare_name),
                    kind: SymKind::Variable,
                    detail: detail.clone(),
                    insert_text: Some(bare_name.to_string()),
                    sort_priority: priority,
                    additional_edits: vec![],
                display_override: None,
                });
            }
            if decl_sigil == '@' {
                out.push(CompletionCandidate {
                    label: format!("${}[]", bare_name),
                    kind: SymKind::Variable,
                    detail: detail.clone().or(Some(format!("@{}", bare_name))),
                    insert_text: Some(format!("{}[", bare_name)),
                    sort_priority: priority,
                    additional_edits: vec![],
                display_override: None,
                });
                out.push(CompletionCandidate {
                    label: format!("$#{}", bare_name),
                    kind: SymKind::Variable,
                    detail: detail
                        .clone()
                        .or(Some(format!("last index of @{}", bare_name))),
                    insert_text: Some(format!("#{}", bare_name)),
                    sort_priority: priority.saturating_add(1),
                    additional_edits: vec![],
                display_override: None,
                });
            }
            if decl_sigil == '%' {
                out.push(CompletionCandidate {
                    label: format!("${}{{}}", bare_name),
                    kind: SymKind::Variable,
                    detail: detail.clone().or(Some(format!("%{}", bare_name))),
                    insert_text: Some(format!("{}{{", bare_name)),
                    sort_priority: priority,
                    additional_edits: vec![],
                display_override: None,
                });
            }
        }
        '@' => {
            if decl_sigil == '@' {
                out.push(CompletionCandidate {
                    label: format!("@{}", bare_name),
                    kind: SymKind::Variable,
                    detail: detail.clone(),
                    insert_text: Some(bare_name.to_string()),
                    sort_priority: priority,
                    additional_edits: vec![],
                display_override: None,
                });
                out.push(CompletionCandidate {
                    label: format!("@{}[]", bare_name),
                    kind: SymKind::Variable,
                    detail: Some("array slice".to_string()),
                    insert_text: Some(format!("{}[", bare_name)),
                    sort_priority: priority.saturating_add(1),
                    additional_edits: vec![],
                display_override: None,
                });
            }
            if decl_sigil == '%' {
                out.push(CompletionCandidate {
                    label: format!("@{}{{}}", bare_name),
                    kind: SymKind::Variable,
                    detail: detail.clone().or(Some("hash slice".to_string())),
                    insert_text: Some(format!("{}{{", bare_name)),
                    sort_priority: priority,
                    additional_edits: vec![],
                display_override: None,
                });
            }
        }
        '%' => {
            if decl_sigil == '%' {
                out.push(CompletionCandidate {
                    label: format!("%{}", bare_name),
                    kind: SymKind::Variable,
                    detail: detail.clone(),
                    insert_text: Some(bare_name.to_string()),
                    sort_priority: priority,
                    additional_edits: vec![],
                display_override: None,
                });
                out.push(CompletionCandidate {
                    label: format!("%{}{{}}", bare_name),
                    kind: SymKind::Variable,
                    detail: Some("hash kv slice".to_string()),
                    insert_text: Some(format!("{}{{", bare_name)),
                    sort_priority: priority.saturating_add(1),
                    additional_edits: vec![],
                display_override: None,
                });
            }
            if decl_sigil == '@' {
                out.push(CompletionCandidate {
                    label: format!("%{}[]", bare_name),
                    kind: SymKind::Variable,
                    detail: Some("array kv slice".to_string()),
                    insert_text: Some(format!("{}[", bare_name)),
                    sort_priority: priority,
                    additional_edits: vec![],
                display_override: None,
                });
            }
        }
        _ => {}
    }
}

// ---- Helpers ----

pub(crate) fn contains_point(span: &Span, point: Point) -> bool {
    (span.start.row < point.row || (span.start.row == point.row && span.start.column <= point.column))
        && (point.row < span.end.row || (point.row == span.end.row && point.column <= span.end.column))
}

/// Walk up from a node to find an ancestor of the given kind.
fn find_ancestor<'a>(node: tree_sitter::Node<'a>, kind: &str) -> Option<tree_sitter::Node<'a>> {
    let mut current = node;
    for _ in 0..20 {
        if current.kind() == kind {
            return Some(current);
        }
        current = current.parent()?;
    }
    None
}

fn span_size(span: &Span) -> usize {
    // Use row difference as primary size metric; column as tiebreaker
    let rows = span.end.row.saturating_sub(span.start.row);
    let cols = if rows == 0 {
        span.end.column.saturating_sub(span.start.column)
    } else {
        0
    };
    rows * 10000 + cols
}

/// Strip the implicit invocant param from a handler signature so hover
/// and sig help don't include the `$self` the user never types.
fn display_handler_params(params: &[ParamInfo]) -> Vec<String> {
    params
        .iter()
        .filter(|p| !p.is_invocant)
        .map(|p| p.name.clone())
        .collect()
}

fn source_line_at(source: &str, row: usize) -> &str {
    source.lines().nth(row).unwrap_or("")
}

/// Return the known return type for a Perl builtin function, if any.
pub(crate) fn builtin_return_type(name: &str) -> Option<InferredType> {
    match name {
        // Numeric returns
        "time" | "length" | "index" | "rindex" | "abs" | "int" | "sqrt"
        | "hex" | "oct" | "ord" | "rand" | "pos" | "tell"
        | "fileno" => Some(InferredType::Numeric),

        // String returns
        "join" | "uc" | "lc" | "ucfirst" | "lcfirst" | "substr" | "sprintf"
        | "ref" | "chr" | "crypt" | "quotemeta" | "pack" | "readline"
        | "readlink" => Some(InferredType::String),

        _ => None,
    }
}

/// Type constraint to push on the first argument of a Perl builtin.
pub(crate) fn builtin_first_arg_type(name: &str) -> Option<InferredType> {
    match name {
        // Numeric arg builtins
        "abs" | "int" | "sqrt" | "chr"
        | "sin" | "cos" | "atan2" | "log" | "exp" => Some(InferredType::Numeric),

        // String arg builtins
        "uc" | "lc" | "ucfirst" | "lcfirst" | "length" | "chomp" | "chop"
        | "substr" | "index" | "rindex" | "quotemeta"
        | "hex" | "oct" | "ord" => Some(InferredType::String),

        _ => None,
    }
}

/// Serialize an InferredType to a simple string tag.
/// Used by signature help's `param_types` field, which piggy-backs on the
/// pre-unification string representation for backwards-compatible JSON output.
pub fn inferred_type_to_tag(ty: &InferredType) -> String {
    match ty {
        InferredType::ClassName(name) => format!("Object:{}", name),
        InferredType::FirstParam { package } => format!("Object:{}", package),
        InferredType::HashRef => "HashRef".to_string(),
        InferredType::ArrayRef => "ArrayRef".to_string(),
        InferredType::CodeRef { .. } => "CodeRef".to_string(),
        InferredType::Regexp => "Regexp".to_string(),
        InferredType::Numeric => "Numeric".to_string(),
        InferredType::String => "String".to_string(),
        // Method dispatch on a Parametric uses its `class_name()`
        // (= the flavor's dispatch class), so the tag follows.
        // Type-arg detail lives in the richer
        // `format_inferred_type` rendering.
        InferredType::Parametric(p) => match p.class_name() {
            Some(c) => format!("Object:{}", c),
            None => "Parametric".to_string(),
        },
        InferredType::Sequence(_) => "Sequence".to_string(),
    }
}

/// Format a cross-file method signature from a SubInfo view.
fn format_cross_file_signature(method_name: &str, sub_info: &crate::module_index::SubInfo<'_>) -> String {
    let params = sub_info.params();
    if params.is_empty() {
        format!("sub {}()", method_name)
    } else {
        let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
        format!("sub {}({})", method_name, names.join(", "))
    }
}

/// Build a `ResolvedSub::CrossFile` from a SubInfo view, snapshotting owned data.
fn cross_file_resolved(sub_info: &crate::module_index::SubInfo<'_>) -> ResolvedSub<'static> {
    let params: Vec<ParamInfo> = sub_info.params().to_vec();
    let param_types: Vec<Option<InferredType>> = params
        .iter()
        .map(|p| sub_info.param_inferred_type(&p.name))
        .collect();
    ResolvedSub::CrossFile {
        params,
        param_types,
        is_method: sub_info.is_method(),
        hash_keys: sub_info.hash_keys().to_vec(),
    }
}

pub(crate) fn format_inferred_type(ty: &InferredType) -> String {
    match ty {
        InferredType::ClassName(name) => name.clone(),
        InferredType::FirstParam { package } => package.clone(),
        InferredType::HashRef => "HashRef".to_string(),
        InferredType::ArrayRef => "ArrayRef".to_string(),
        InferredType::CodeRef { .. } => "CodeRef".to_string(),
        InferredType::Regexp => "Regexp".to_string(),
        InferredType::Numeric => "Numeric".to_string(),
        InferredType::String => "String".to_string(),
        InferredType::Parametric(p) => format_parametric_type(p),
        InferredType::Sequence(elems) => {
            // Angle brackets, not `[...]` — markdown renderers treat
            // bracketed text as link syntax and either swallow it
            // or render it as a broken link. Matches the
            // `Parametric<T1, T2>` style.
            let parts: Vec<String> = elems.iter().map(format_inferred_type).collect();
            format!("Sequence<{}>", parts.join(", "))
        }
    }
}

fn format_parametric_type(p: &ParametricType) -> String {
    match p {
        ParametricType::ResultSet { base, row } => {
            format!("{}<{}>", base, row)
        }
        ParametricType::RowOf(inner) => {
            format!("RowOf<{}>", format_inferred_type(inner))
        }
    }
}

#[cfg(test)]
#[path = "file_analysis_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "call_ref_index_tests.rs"]
mod call_ref_index_tests;

#[cfg(test)]
#[path = "parametric_resultset_tests.rs"]
mod parametric_resultset_tests;

#[cfg(test)]
#[path = "return_expr_tests.rs"]
mod return_expr_tests;