perl-lsp 0.5.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
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
use super::*;

fn parse(source: &str) -> Tree {
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    parser.parse(source, None).unwrap()
}

fn build_fa(source: &str) -> FileAnalysis {
    let tree = parse(source);
    build(&tree, source.as_bytes())
}

#[test]
fn debug_moo_name_refs() {
    let src = std::fs::read_to_string("test_files/frameworks.pl").unwrap();
    let fa = build_fa(&src);
    for r in &fa.refs {
        if r.target_name == "name" || r.target_name == "new" {
            eprintln!(
                "REF: target={} kind={:?} span={:?} resolves_to={:?}",
                r.target_name, r.kind, r.span, r.resolves_to
            );
        }
    }
    for s in &fa.symbols {
        if s.name == "name"
            || (matches!(s.kind, SymKind::HashKeyDef)
                && s.span.start.row > 5
                && s.span.start.row < 25)
        {
            eprintln!(
                "SYM: name={} kind={:?} span={:?} sel_span={:?} detail={:?}",
                s.name, s.kind, s.span, s.selection_span, s.detail
            );
        }
    }
}

// ---- varname-based extraction ----

/// Adversarial: every flavor of `foo` access (plain, element, slice,
/// KV slice, arraylen) must canonicalize to the underlying
/// `$foo`/`@foo`/`%foo` Variable symbol — NOT to "$foo" across the
/// board. TSP exposes the container kind via distinct node types
/// (`container_variable`, `slice_container_variable`,
/// `keyval_container_variable`, `arraylen`) + a `hash:`/`array:`
/// field on the parent. Our job is to route each to the correct
/// declared symbol.
#[test]
fn sigil_disambiguation_across_access_forms() {
    let src = "\
my ($foo, @foo, %foo);
$foo;
$foo[0];
$foo{hi};
@foo[0..1];
@foo{qw/hi there/};
$#foo;
%foo[0..1];
%foo{a};
";
    let fa = build_fa(src);

    // Three distinct declarations.
    let decls: std::collections::HashMap<&str, _> = fa
        .symbols
        .iter()
        .filter(|s| {
            s.kind == SymKind::Variable
                && s.scope == ScopeId(0)
                && matches!(s.name.as_str(), "$foo" | "@foo" | "%foo")
        })
        .map(|s| (s.name.as_str(), s.id))
        .collect();
    assert!(decls.contains_key("$foo"), "missing scalar decl");
    assert!(decls.contains_key("@foo"), "missing array decl");
    assert!(decls.contains_key("%foo"), "missing hash decl");

    // Collect every Variable/ContainerAccess ref, keyed by the line
    // it sits on. Line 0 is the declaration — skip it.
    let mut refs_by_line: std::collections::HashMap<usize, Vec<&str>> = Default::default();
    for r in &fa.refs {
        if !matches!(r.kind, RefKind::Variable | RefKind::ContainerAccess) {
            continue;
        }
        if r.access == AccessKind::Declaration {
            continue;
        }
        refs_by_line
            .entry(r.span.start.row)
            .or_default()
            .push(r.target_name.as_str());
    }

    let expected: &[(usize, &str, &str)] = &[
        (1, "$foo", "$foo"),               // plain scalar
        (2, "$foo[0]", "@foo"),            // array element access
        (3, "$foo{hi}", "%foo"),           // hash element access
        (4, "@foo[0..1]", "@foo"),         // array slice
        (5, "@foo{qw/hi there/}", "%foo"), // hash slice — Perl semantic
        (6, "$#foo", "@foo"),              // arraylen
        (7, "%foo[0..1]", "@foo"),         // KV slice of array (5.20+)
        (8, "%foo{a}", "%foo"),            // KV slice of hash
    ];

    let mut failures: Vec<String> = Vec::new();
    for (line, form, want) in expected {
        let got = refs_by_line.get(line).cloned().unwrap_or_default();
        if got.as_slice() != [*want] {
            failures.push(format!(
                "  line {} `{}` → want [{}], got {:?}",
                line, form, want, got
            ));
        }
    }
    assert!(
        failures.is_empty(),
        "sigil disambiguation failures:\n{}",
        failures.join("\n")
    );
}

#[test]
fn braced_var_declaration_names_match_bare_form() {
    // `my ${foo}` is just `my $foo`. Before the varname refactor we
    // stored the declared name as the full node text `${foo}`, so a
    // later `$foo` reference couldn't resolve to it. Now both share
    // the canonical `$foo` name.
    let fa = build_fa("my ${foo} = 1;\n$foo;\n");
    let decls: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Variable && s.name == "$foo")
        .collect();
    assert_eq!(
        decls.len(),
        1,
        "expected one $foo symbol, got {:?}",
        fa.symbols
            .iter()
            .filter(|s| s.kind == SymKind::Variable)
            .map(|s| &s.name)
            .collect::<Vec<_>>()
    );
}

// ---- parse_instance_of ----

#[test]
fn parse_instance_of_single_quoted() {
    assert_eq!(
        parse_instance_of("InstanceOf['Foo::Bar']").as_deref(),
        Some("Foo::Bar")
    );
}

#[test]
fn parse_instance_of_double_quoted() {
    assert_eq!(
        parse_instance_of("InstanceOf[\"Foo::Bar\"]").as_deref(),
        Some("Foo::Bar")
    );
}

#[test]
fn parse_instance_of_rejects_non_instance_of() {
    assert_eq!(parse_instance_of("Str"), None);
    assert_eq!(parse_instance_of("ArrayRef[Int]"), None);
    assert_eq!(parse_instance_of("My::Class"), None);
}

// ---- Scope tests ----

#[test]
fn test_file_scope() {
    let fa = build_fa("my $x = 1;");
    assert_eq!(fa.scopes.len(), 1);
    assert_eq!(fa.scopes[0].kind, ScopeKind::File);
}

#[test]
fn test_sub_creates_scope() {
    let fa = build_fa("sub foo { my $x = 1; }");
    let sub_scopes: Vec<_> = fa
        .scopes
        .iter()
        .filter(|s| matches!(&s.kind, ScopeKind::Sub { name } if name == "foo"))
        .collect();
    assert_eq!(sub_scopes.len(), 1);
    assert_eq!(sub_scopes[0].parent, Some(ScopeId(0))); // parent is file
}

#[test]
fn test_class_creates_scope() {
    let fa = build_fa("use v5.38;\nclass Point {\n    field $x :param;\n}");
    let class_scopes: Vec<_> = fa
        .scopes
        .iter()
        .filter(|s| matches!(&s.kind, ScopeKind::Class { name } if name == "Point"))
        .collect();
    assert_eq!(class_scopes.len(), 1);
    assert_eq!(class_scopes[0].package, Some("Point".to_string()));
}

#[test]
fn test_package_sets_scope_package() {
    let fa = build_fa("package Foo;\nsub bar { 1 }");
    // The sub scope should inherit package "Foo"
    let sub_scopes: Vec<_> = fa
        .scopes
        .iter()
        .filter(|s| matches!(&s.kind, ScopeKind::Sub { name } if name == "bar"))
        .collect();
    assert_eq!(sub_scopes.len(), 1);
    assert_eq!(sub_scopes[0].package, Some("Foo".to_string()));
}

#[test]
fn test_for_loop_scope() {
    let fa = build_fa("for my $i (1..10) { print $i; }");
    let for_scopes: Vec<_> = fa
        .scopes
        .iter()
        .filter(|s| matches!(&s.kind, ScopeKind::ForLoop { .. }))
        .collect();
    assert_eq!(for_scopes.len(), 1);
}

// ---- Symbol tests ----

#[test]
fn test_variable_symbol() {
    let fa = build_fa("my $x = 1;");
    let vars: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Variable && s.name == "$x")
        .collect();
    assert_eq!(vars.len(), 1);
    if let SymbolDetail::Variable { sigil, decl_kind } = &vars[0].detail {
        assert_eq!(*sigil, '$');
        assert_eq!(*decl_kind, DeclKind::My);
    } else {
        panic!("expected Variable detail");
    }
}

#[test]
fn test_sub_symbol_with_params() {
    let fa = build_fa("sub connect($self, %opts) { }");
    let subs: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Sub && s.name == "connect")
        .collect();
    assert_eq!(subs.len(), 1);
    if let SymbolDetail::Sub {
        params, is_method, ..
    } = &subs[0].detail
    {
        assert!(!is_method);
        assert_eq!(params.len(), 2);
        assert_eq!(params[0].name, "$self");
        assert_eq!(params[1].name, "%opts");
        assert!(params[1].is_slurpy);
    } else {
        panic!("expected Sub detail");
    }
}

#[test]
fn test_legacy_sub_params() {
    let fa = build_fa("sub new {\n    my ($class, %args) = @_;\n}");
    let subs: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Sub && s.name == "new")
        .collect();
    assert_eq!(subs.len(), 1);
    if let SymbolDetail::Sub { params, .. } = &subs[0].detail {
        assert_eq!(params.len(), 2);
        assert_eq!(params[0].name, "$class");
        assert_eq!(params[1].name, "%args");
        assert!(params[1].is_slurpy);
    } else {
        panic!("expected Sub detail");
    }
}

#[test]
fn test_package_symbol() {
    let fa = build_fa("package Foo;");
    let pkgs: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Package && s.name == "Foo")
        .collect();
    assert_eq!(pkgs.len(), 1);
}

#[test]
fn test_class_symbol() {
    let fa = build_fa("use v5.38;\nclass Point {\n    field $x :param;\n    field $y :param;\n    method magnitude() { }\n}");
    let classes: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Class && s.name == "Point")
        .collect();
    assert_eq!(classes.len(), 1);
    if let SymbolDetail::Class { fields, parent, .. } = &classes[0].detail {
        assert_eq!(fields.len(), 2);
        assert_eq!(fields[0].name, "$x");
        assert_eq!(fields[1].name, "$y");
        assert!(fields[0].attributes.contains(&"param".to_string()));
        assert!(parent.is_none());
    } else {
        panic!("expected Class detail");
    }
}

#[test]
fn test_field_symbol() {
    let fa = build_fa("use v5.38;\nclass Point {\n    field $x :param;\n}");
    let fields: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Field)
        .collect();
    assert_eq!(fields.len(), 1);
    assert_eq!(fields[0].name, "$x");
}

#[test]
fn test_field_reader_synthesizes_method() {
    let fa = build_fa(
        "use v5.38;\nclass Point {\n    field $x :param :reader;\n    field $y :param;\n}",
    );
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Method)
        .collect();
    assert_eq!(
        methods.len(),
        1,
        "got: {:?}",
        methods.iter().map(|m| &m.name).collect::<Vec<_>>()
    );
    assert_eq!(methods[0].name, "x");
}

#[test]
fn test_implicit_self_in_method() {
    // $self is implicitly available in Perl 5.38 method blocks
    let source = "use v5.38;\nclass Point {\n    field $x :param :reader;\n    method magnitude () {\n        $self->x;\n    }\n}\n";
    let fa = build_fa(source);

    // $self should be resolvable as a variable inside the method
    let resolved = fa.resolve_variable("$self", Point::new(4, 8));
    assert!(
        resolved.is_some(),
        "$self should resolve inside method body"
    );
}

#[test]
fn test_implicit_self_type_inference() {
    // $self should be type-inferred to the enclosing class
    let source = "use v5.38;\nclass Point {\n    field $x :param :reader;\n    method magnitude () {\n        $self->x;\n    }\n}\n";
    let fa = build_fa(source);

    // Type inference: $self → Point
    let inferred = fa.inferred_type_via_bag("$self", Point::new(4, 8));
    assert!(inferred.is_some(), "$self type should be inferred");
    match inferred.unwrap() {
        InferredType::ClassName(name) => assert_eq!(name, "Point"),
        InferredType::FirstParam { package } => assert_eq!(package, "Point"),
        other => panic!("expected ClassName or FirstParam, got {:?}", other),
    }
}

#[test]
fn test_self_completion_walks_ancestors_in_fallback() {
    // Untyped `$self` (the fallback path, no bag type — e.g. assigned via
    // `$class->SUPER::new`) must still resolve to the enclosing class AND walk
    // its ancestors, so inherited methods are offered, not just own ones.
    let source = "package Base;\nsub inherited_m { 1 }\npackage Child;\nuse parent -norequire, 'Base';\nsub own_m {\n  my $self = $class->SUPER::new;\n  $self->\n}\n";
    let fa = build_fa(source);
    let names: Vec<String> = fa
        .complete_methods("$self", Point::new(6, 9), None)
        .into_iter()
        .map(|c| c.label)
        .collect();
    assert!(names.iter().any(|n| n == "own_m"), "own method missing: {names:?}");
    assert!(
        names.iter().any(|n| n == "inherited_m"),
        "inherited (ancestor) method missing from untyped-$self fallback: {names:?}"
    );
}

#[test]
fn test_self_completion_inside_method() {
    // $self-> inside a method should complete with sibling methods
    let source = "use v5.38;\nclass Point {\n    field $x :param :reader;\n    method magnitude () { }\n    method to_string () {\n        $self->;\n    }\n}\n";
    let fa = build_fa(source);

    let candidates = fa.complete_methods("$self", Point::new(5, 14), None);
    let names: Vec<&str> = candidates.iter().map(|c| c.label.as_str()).collect();
    assert!(
        names.contains(&"magnitude"),
        "missing magnitude, got: {:?}",
        names
    );
    assert!(
        names.contains(&"to_string"),
        "missing to_string, got: {:?}",
        names
    );
    assert!(names.contains(&"x"), "missing reader x, got: {:?}", names);
}

#[test]
fn test_field_writer_synthesizes_method() {
    let fa =
        build_fa("use v5.38;\nclass Point {\n    field $label :reader :writer = \"point\";\n}");
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Method)
        .map(|s| s.name.clone())
        .collect();
    assert!(
        methods.contains(&"label".to_string()),
        "missing reader, got: {:?}",
        methods
    );
    assert!(
        methods.contains(&"set_label".to_string()),
        "missing writer, got: {:?}",
        methods
    );
}

#[test]
fn test_complete_methods_in_class() {
    let fa = build_fa("use v5.38;\nclass Point {\n    field $x :param :reader;\n    field $y :param;\n    method magnitude() { }\n    method to_string() { }\n}\nmy $p = Point->new(x => 1);\n$p->;\n");
    // $p-> is at line 8, col 4
    let candidates = fa.complete_methods("$p", Point::new(8, 4), None);
    let names: Vec<&str> = candidates.iter().map(|c| c.label.as_str()).collect();
    assert!(names.contains(&"new"), "missing new, got: {:?}", names);
    assert!(
        names.contains(&"magnitude"),
        "missing magnitude, got: {:?}",
        names
    );
    assert!(
        names.contains(&"to_string"),
        "missing to_string, got: {:?}",
        names
    );
    assert!(names.contains(&"x"), "missing reader x, got: {:?}", names);
}

#[test]
fn test_complete_methods_sample_file_layout() {
    // Matches sample.pl: class defined after package main, $p usage at end
    let source = r#"use v5.38;
class Point {
    field $x :param :reader;
    field $y :param;
    method magnitude () { }
    method to_string () { }
}
my $p = Point->new(x => 3, y => 4);
$p->;
"#;
    let fa = build_fa(source);

    // Check type inference resolved $p → Point
    let inferred = fa.inferred_type_via_bag("$p", Point::new(8, 4));
    assert!(inferred.is_some(), "type inference for $p should resolve");

    let candidates = fa.complete_methods("$p", Point::new(10, 4), None);
    let names: Vec<&str> = candidates.iter().map(|c| c.label.as_str()).collect();
    assert!(
        names.contains(&"magnitude"),
        "missing magnitude, got: {:?}",
        names
    );
    assert!(
        names.contains(&"to_string"),
        "missing to_string, got: {:?}",
        names
    );
    assert!(names.contains(&"x"), "missing reader x, got: {:?}", names);
}

#[test]
fn test_complete_methods_class_after_package_main() {
    // Real-world: package main; ... class Point {} ... $p->
    let source = r#"package main;
my $calc = Calculator->new();
1;
use v5.38;
class Point {
    field $x :param :reader;
    field $y :param;
    method magnitude () { }
    method to_string () { }
}
my $p = Point->new(x => 3, y => 4);
$p->;
"#;
    let fa = build_fa(source);

    let candidates = fa.complete_methods("$p", Point::new(11, 4), None);
    let names: Vec<&str> = candidates.iter().map(|c| c.label.as_str()).collect();
    assert!(names.contains(&"new"), "missing new, got: {:?}", names);
    assert!(
        names.contains(&"magnitude"),
        "missing magnitude, got: {:?}",
        names
    );
    assert!(
        names.contains(&"to_string"),
        "missing to_string, got: {:?}",
        names
    );
    assert!(names.contains(&"x"), "missing reader x, got: {:?}", names);
}

#[test]
fn test_complete_methods_flat_class() {
    // class Foo; (no block) — methods follow as siblings, like package
    let source = "use v5.38;\nclass Foo;\nmethod bar () { }\nmethod baz () { }\n";
    let fa = build_fa(source);
    let candidates = fa.complete_methods("Foo", Point::new(3, 0), None);
    let names: Vec<&str> = candidates.iter().map(|c| c.label.as_str()).collect();
    assert!(names.contains(&"bar"), "missing bar, got: {:?}", names);
    assert!(names.contains(&"baz"), "missing baz, got: {:?}", names);
}

#[test]
fn test_goto_def_method_after_package_main() {
    // go-to-def on $p->magnitude() should find the method, not the class
    let source = "package main;\n1;\nuse v5.38;\nclass Point {\n    field $x :param :reader;\n    method magnitude () { }\n}\nmy $p = Point->new(x => 3);\n$p->magnitude();\n";
    let fa = build_fa(source);
    // cursor on `magnitude` in `$p->magnitude()` — line 8, col 5
    let def = fa.find_definition(Point::new(8, 5), None);
    assert!(def.is_some(), "should find definition for magnitude");
    let span = def.unwrap();
    assert_eq!(
        span.start.row, 5,
        "should point to method declaration line, got row {}",
        span.start.row
    );
}

#[test]
fn test_field_reader_goto_def() {
    // go-to-def on $p->x should find the reader method, which points to the field
    let fa = build_fa("use v5.38;\nclass Point {\n    field $x :param :reader;\n    method mag() { }\n}\nmy $p = Point->new(x => 1);\n$p->x;");
    let def = fa.find_definition(Point::new(6, 5), None); // cursor on `x` in `$p->x`
    assert!(def.is_some(), "should find definition for reader method");
    // The reader method's selection_span points to the field declaration
    let span = def.unwrap();
    assert_eq!(span.start.row, 2, "should point to field declaration line");
}

/// NAV (a): goto-def on a method that does NOT exist on a known class
/// must be an honest miss (None), NEVER a confident jump to the
/// `package` decl. The `$self->{email}->method` shape used to over-type
/// the invocant to the enclosing class and then jump to its package
/// line when the method wasn't found — worse than a miss.
#[test]
fn test_goto_def_unknown_method_is_honest_miss_not_package_jump() {
    let source = "package Foo;\nsub new { bless { email => undef }, shift }\nsub to { my $self = shift; $self->{email}->totallyunknownmethod(1); }\n1;\n";
    let fa = build_fa(source);
    // `totallyunknownmethod` starts at row 2, col 43 (after the `->`).
    let def = fa.find_definition(Point::new(2, 48), None);
    assert!(
        def.is_none(),
        "unknown method must return None (honest miss), not jump to package decl; got {:?}",
        def
    );
}

/// NAV regression (iv): goto-def on a typed same-file method still
/// lands on the method declaration via the frozen dispatch edge.
#[test]
fn test_goto_def_typed_same_file_method_resolves() {
    let source = "package Widget;\nsub new { bless {}, shift }\nsub frobnicate { 1 }\nsub run { my $w = Widget->new; $w->frobnicate; }\n1;\n";
    let fa = build_fa(source);
    // `frobnicate` in `$w->frobnicate` — row 3. Find its column.
    let row = 3usize;
    let line = source.lines().nth(row).unwrap();
    let col = line.find("$w->frobnicate").unwrap() + "$w->".len() + 2;
    let def = fa.find_definition(Point::new(row, col), None);
    assert!(def.is_some(), "typed $w->frobnicate must resolve to the decl");
    assert_eq!(
        def.unwrap().start.row,
        2,
        "should land on `sub frobnicate` (row 2)"
    );
}

/// OVER-TYPING PIN: a hash element extracted to a scalar must NOT be
/// typed as the container's class. `my $h = $self->{helper}` carries
/// the value of `$self->{helper}`, whose type is independent of
/// `$self`'s class (Foo). The chain typer used to push a spurious
/// `TypeConstraint $h = Foo` because `$self->{helper}` resolved to
/// `$self`'s class. `$h` must be honest-UNTYPED (no real value type is
/// known), and `$h->do_thing` must be an honest miss — not a
/// confident-wrong jump to a Foo sub.
#[test]
fn test_hash_element_extracted_to_scalar_is_not_container_class() {
    let source = "package Foo;\nsub new { bless {}, shift }\nsub use_it { my $self = shift; $self->{helper} = Helper->new; my $h = $self->{helper}; $h->do_thing(); }\n1;\n";
    let fa = build_fa(source);

    // `$h` is declared on row 2. Probe just past its declaration.
    let line = source.lines().nth(2).unwrap();
    let h_decl_col = line.find("my $h").unwrap();
    let probe = tree_sitter::Point::new(2, h_decl_col + "my $h = $self->{helper}; ".len());

    let ty = fa.inferred_type("$h", probe);
    assert!(
        !matches!(ty, Some(InferredType::ClassName(c)) if c == "Foo"),
        "$h must NOT be typed as the container's class Foo; got {:?}",
        ty
    );

    // goto-def on `$h->do_thing` must be an honest miss, never a jump
    // to a Foo sub.
    let do_thing_col = line.rfind("do_thing").unwrap();
    let def = fa.find_definition(tree_sitter::Point::new(2, do_thing_col + 1), None);
    assert!(
        def.is_none(),
        "$h->do_thing must be an honest miss, not a confident jump to a Foo sub; got {:?}",
        def
    );
}

/// A4 end-to-end (Step 3 consume join): a typed write into a slot, extracted
/// to a scalar, types the scalar via `SlotType` — so a method call on it
/// resolves. Helper is defined here so resolution can complete (contrast the
/// honest-miss pin above, where it isn't).
#[test]
fn slot_type_write_then_extract_resolves_method() {
    let source = "package Helper;\nsub new { bless {}, shift }\nsub do_thing { 1 }\npackage Foo;\nsub new { bless {}, shift }\nsub use_it { my $self = shift; $self->{helper} = Helper->new; my $h = $self->{helper}; $h->do_thing(); }\n1;\n";
    let fa = build_fa(source);
    let line = source.lines().nth(5).unwrap();

    let probe = tree_sitter::Point::new(
        5,
        line.find("my $h").unwrap() + "my $h = $self->{helper}; ".len(),
    );
    let ty = fa.inferred_type("$h", probe);
    assert_eq!(
        ty.as_ref().and_then(|t| t.class_name()),
        Some("Helper"),
        "$h must type as Helper via the consumed SlotType; got {:?}",
        ty
    );

    let def = fa.find_definition(
        tree_sitter::Point::new(5, line.rfind("do_thing").unwrap() + 1),
        None);
    assert!(
        matches!(&def, Some(d) if d.start.row == 2),
        "$h->do_thing must resolve to Helper::do_thing on row 2; got {:?}",
        def
    );
}


#[test]
fn test_use_symbol() {
    let fa = build_fa("use Foo::Bar;");
    let modules: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Module)
        .collect();
    assert_eq!(modules.len(), 1);
    assert_eq!(modules[0].name, "Foo::Bar");
}

// ---- Ref tests ----

#[test]
fn test_variable_ref() {
    let fa = build_fa("my $x = 1;\nprint $x;");
    let var_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "$x" && matches!(r.kind, RefKind::Variable))
        .collect();
    // One declaration ref + one read ref
    assert!(var_refs.len() >= 2, "got {} refs for $x", var_refs.len());
    assert!(var_refs.iter().any(|r| r.access == AccessKind::Declaration));
    assert!(var_refs.iter().any(|r| r.access == AccessKind::Read));
}

#[test]
fn test_function_call_ref() {
    let fa = build_fa("sub foo { }\nfoo();");
    let call_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "foo" && matches!(r.kind, RefKind::FunctionCall { .. }))
        .collect();
    assert_eq!(call_refs.len(), 1);
}

/// Rule #7: a call that appears as an *operand* of a larger expression
/// (string concatenation, ternary) must still emit its FunctionCall ref.
/// AWStats shape `print "<td>".Format_Number($x)."</td>"` parses the call
/// as a `function_call_expression` nested inside a `binary_expression`
/// (the concat) which is itself the `print` verb's argument. The generic
/// `_ => visit_children` traversal in `visit_node` reaches it; this test
/// pins that so a future grammar/traversal change can't silently regress
/// references to statement-level calls only.
#[test]
fn call_ref_in_concatenation_operand() {
    let fa = build_fa("sub Format_Number { }\nprint \"<td>\".Format_Number($x).\"</td>\";\n");
    let call_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "Format_Number" && matches!(r.kind, RefKind::FunctionCall { .. }))
        .collect();
    assert_eq!(
        call_refs.len(),
        1,
        "a call inside `.`-concatenation must emit exactly one FunctionCall ref"
    );
    // The ref must pin the *call name*, not the surrounding concat/print.
    assert!(call_refs[0].span.start.row == 1);
}

/// Rule #7: calls in both arms of a ternary are operands too.
#[test]
fn call_ref_in_ternary_operands() {
    let fa = build_fa("sub foo { }\nsub bar { }\nmy $y = $cond ? foo() : bar();\n");
    let foo_refs = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "foo" && matches!(r.kind, RefKind::FunctionCall { .. }))
        .count();
    let bar_refs = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "bar" && matches!(r.kind, RefKind::FunctionCall { .. }))
        .count();
    assert_eq!(foo_refs, 1, "ternary consequent call must emit a ref");
    assert_eq!(bar_refs, 1, "ternary alternative call must emit a ref");
}

/// Method calls nested in expression operands must also emit a MethodCall ref.
#[test]
fn method_call_ref_in_concatenation_operand() {
    let fa = build_fa("my $s = \"x\" . $obj->fmt($n) . \"y\";\n");
    let m_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "fmt" && matches!(r.kind, RefKind::MethodCall { .. }))
        .collect();
    assert_eq!(m_refs.len(), 1, "method call inside concat must emit one MethodCall ref");
}

/// AWStats-shaped fixture: a def plus N call sites, every call embedded in a
/// concatenation operand. Mirrors the real-world undercount (def→6 of 172).
/// Asserts the call-ref count equals the textual occurrence count and that a
/// bareword that is NOT a call (`Format_Number` as a hash key) is not counted.
#[test]
fn call_refs_count_across_expression_positions() {
    let src = "\
sub Format_Number { my $n = shift; return $n; }
print \"<td>\".Format_Number($a).\"</td>\";
print \"<td>\".Format_Number($b).\"</td><td>x</td>\";
my $r = \"a\" . Format_Number($c) . \"b\" . Format_Number($d);
my $t = $cond ? Format_Number($e) : 0;
my %h = (Format_Number => 1);
";
    let fa = build_fa(src);
    let call_refs = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "Format_Number" && matches!(r.kind, RefKind::FunctionCall { .. }))
        .count();
    // 5 genuine call sites (two single-call prints, two in one concat, one ternary).
    assert_eq!(
        call_refs, 5,
        "every call-position occurrence must emit a FunctionCall ref; the hash-key bareword must not"
    );
}

/// Regression guard: a plain statement-level call still emits exactly one
/// ref (no double-emission from the operand-traversal path).
#[test]
fn statement_level_call_emits_single_ref() {
    let fa = build_fa("sub debug { }\ndebug(\"hello\");\n");
    let call_refs = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "debug" && matches!(r.kind, RefKind::FunctionCall { .. }))
        .count();
    assert_eq!(call_refs, 1, "statement-level call must emit exactly one ref");
}

#[test]
fn test_method_call_ref() {
    let fa = build_fa("$obj->method();");
    let method_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "method" && matches!(r.kind, RefKind::MethodCall { .. }))
        .collect();
    assert_eq!(method_refs.len(), 1);
    if let RefKind::MethodCall { ref invocant, .. } = method_refs[0].kind {
        assert_eq!(invocant, "$obj");
    }
}

#[test]
fn test_hash_key_ref() {
    let fa = build_fa("my %h;\n$h{foo};");
    let key_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "foo" && matches!(r.kind, RefKind::HashKeyAccess { .. }))
        .collect();
    assert_eq!(key_refs.len(), 1);
}

// ---- Query tests ----

#[test]
fn test_scope_at() {
    let fa = build_fa("sub foo {\n    my $x = 1;\n}");
    // Point inside the sub body
    let scope = fa.scope_at(Point::new(1, 8)).unwrap();
    let s = fa.scope(scope);
    assert!(matches!(&s.kind, ScopeKind::Sub { name } if name == "foo"));
}

#[test]
fn test_resolve_variable() {
    let fa = build_fa("my $x = 1;\nsub foo {\n    my $x = 2;\n    print $x;\n}");
    // Inside the sub, $x should resolve to the inner declaration
    let sym = fa.resolve_variable("$x", Point::new(3, 10)).unwrap();
    // Inner $x is at line 2
    assert_eq!(sym.selection_span.start.row, 2);
}

#[test]
fn test_resolve_variable_outer() {
    let fa = build_fa("my $x = 1;\nsub foo {\n    print $x;\n}");
    // Inside the sub with no inner $x, should resolve to outer
    let sym = fa.resolve_variable("$x", Point::new(2, 10)).unwrap();
    assert_eq!(sym.selection_span.start.row, 0);
}

#[test]
fn test_type_inference_constructor() {
    let fa = build_fa("use v5.38;\nclass Point { }\nmy $p = Point->new();");
    let ty = fa.inferred_type_via_bag("$p", Point::new(2, 20));
    assert!(ty.is_some(), "should infer type for $p");
    if let Some(InferredType::ClassName(cn)) = ty {
        assert_eq!(cn, "Point");
    } else {
        panic!("expected ClassName, got {:?}", ty);
    }
}

#[test]
fn test_type_inference_first_param() {
    // The walk pushes a `FirstParam { package: "Calculator" }`
    // type-constraint, but the bag-aware query normalises it to
    // `ClassName("Calculator")` via the FrameworkAwareTypeFold
    // (FirstParam is an internal observation; consumers see the
    // class identity). That's the canonical answer the LSP
    // serves at any cursor position on `$self`.
    let fa = build_fa("package Calculator;\nsub new {\n    my ($self) = @_;\n}");
    let ty = fa.inferred_type_via_bag("$self", Point::new(2, 10));
    assert_eq!(ty, Some(InferredType::ClassName("Calculator".into())));
}

#[test]
fn test_bless_promotes_var_to_class() {
    // `my $self = {}; bless $self, $class;` — after the bless, $self is an
    // instance of the enclosing class, not a bare HashRef.
    let src = "package Point;\nsub new {\n  my $class = shift;\n  my $self = {};\n  bless $self, $class;\n  return $self;\n}\n";
    let fa = build_fa(src);
    // Query $self at the `return $self` line (after the bless).
    let ty = fa.inferred_type_via_bag("$self", Point::new(5, 9));
    assert_eq!(
        ty,
        Some(InferredType::ClassName("Point".into())),
        "post-bless $self should be ClassName(Point), got {:?}",
        ty
    );
}

#[test]
fn test_bless_fat_arrow_and_package() {
    // `bless $self => __PACKAGE__` form.
    let src = "package Widget;\nsub build {\n  my $self = {};\n  bless $self => __PACKAGE__;\n  return $self;\n}\n";
    let fa = build_fa(src);
    let ty = fa.inferred_type_via_bag("$self", Point::new(4, 9));
    assert_eq!(ty, Some(InferredType::ClassName("Widget".into())));
}

#[test]
fn test_bless_literal_class() {
    // `bless $self, "Other"` — explicit literal class wins.
    let src = "package Factory;\nsub mk {\n  my $self = {};\n  bless $self, \"Other\";\n  return $self;\n}\n";
    let fa = build_fa(src);
    let ty = fa.inferred_type_via_bag("$self", Point::new(4, 9));
    assert_eq!(ty, Some(InferredType::ClassName("Other".into())));
}

#[test]
fn test_return_bless_anon_hash_class() {
    // `return bless {}, $class` — the sub returns a ClassName instance even
    // though there's no variable to promote.
    let src = "package Maker;\nsub new {\n  my $class = shift;\n  return bless {}, $class;\n}\n";
    let fa = build_fa(src);
    let ty = fa.sub_return_type_at_arity("new", Some(0));
    assert_eq!(
        ty,
        Some(InferredType::ClassName("Maker".into())),
        "return bless should type the sub return, got {:?}",
        ty
    );
}

#[test]
fn test_bless_into_ref_invocant_types_clone_return() {
    // `bless { ... }, ref $_[0]` (the clone idiom) blesses into the invocant's
    // class, so the implicit-return value types as the enclosing class.
    let src = "package DateTime;\nsub clone { bless { %{ $_[0] } }, ref $_[0] }\n";
    let fa = build_fa(src);
    let ty = fa.sub_return_type_at_arity("clone", Some(1));
    assert_eq!(
        ty,
        Some(InferredType::ClassName("DateTime".into())),
        "bless ..., ref $_[0] should type the clone return, got {:?}",
        ty
    );
}

#[test]
fn test_forward_declaration_does_not_duplicate_symbol() {
    // `sub foo;` is a forward declaration, not a definition: only the bodied
    // `sub foo { ... }` should produce a symbol (no outline dup / goto-def shadow).
    let fa = build_fa("package P;\nsub foo;\nsub foo { my ($self, $x) = @_; $x }\n");
    let foos: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| matches!(s.kind, SymKind::Sub | SymKind::Method) && s.name == "foo")
        .collect();
    assert_eq!(
        foos.len(),
        1,
        "expected one `foo` symbol (the definition), got {:?}",
        foos.iter().map(|s| s.span.start.row).collect::<Vec<_>>()
    );
    assert_eq!(foos[0].span.start.row, 2, "the symbol should be the bodied def on line 2");
}

#[test]
fn test_receiver_polymorphic_ctor_types_to_subclass() {
    // An inherited `bless {}, ref $class || $class` constructor returns whatever
    // class it was CALLED ON — Child->new is a Child, not a Base. The bless arm
    // emits ReturnExpr::ReceiverOr; the call's receiver substitutes.
    let fa = build_fa(
        "package Base;\nsub new { my $class = shift; bless {}, ref $class || $class }\npackage Child;\nuse parent -norequire, 'Base';\n",
    );
    assert_eq!(
        fa.find_method_return_type("Child", "new", None, Some(0)),
        Some(InferredType::ClassName("Child".into())),
        "Child->new (inherited ctor) must type as Child, not Base"
    );
    assert_eq!(
        fa.find_method_return_type("Base", "new", None, Some(0)),
        Some(InferredType::ClassName("Base".into())),
        "Base->new still types as Base"
    );
}

#[test]
fn test_non_bless_hashref_stays_hashref() {
    // Regression: a hashref that's never blessed keeps its HashRef type.
    let src = "sub mk {\n  my $h = {};\n  return $h;\n}\n";
    let fa = build_fa(src);
    let ty = fa.inferred_type_via_bag("$h", Point::new(2, 9));
    assert_eq!(ty, Some(InferredType::HashRef), "unblessed hashref stays HashRef");
}

// ---- Literal constructor extraction tests (via build_fa) ----

#[test]
fn test_extract_hashref_literal() {
    let fa = build_fa("my $href = {};");
    let ty = fa.inferred_type_via_bag("$href", Point::new(0, 14));
    assert_eq!(ty, Some(InferredType::HashRef), "empty hash ref literal");

    let fa = build_fa("my $href = { a => 1, b => 2 };");
    let ty = fa.inferred_type_via_bag("$href", Point::new(0, 30));
    assert!(
        ty.is_some_and(|t| t.is_hash_shaped()),
        "populated hash ref literal",
    );
}

#[test]
fn test_extract_arrayref_literal() {
    let fa = build_fa("my $aref = [];");
    let ty = fa.inferred_type_via_bag("$aref", Point::new(0, 14));
    assert_eq!(ty, Some(InferredType::ArrayRef), "empty array ref literal");

    let fa = build_fa("my $aref = [1, 2, 3];");
    let ty = fa.inferred_type_via_bag("$aref", Point::new(0, 21));
    assert!(
        ty.is_some_and(|t| t.is_array_shaped()),
        "populated array ref literal",
    );
}

#[test]
fn test_extract_coderef_literal() {
    let fa = build_fa("my $cref = sub { 42 };");
    let ty = fa.inferred_type_via_bag("$cref", Point::new(0, 22));
    // Sub-literal CodeRef carries `return_edge: Some(_)` — the
    // body's last-expression span. Survives the `my $cref = ...`
    // binding so downstream callable-shape consumers can edge-chase
    // into the body's type. Opaque coderef tests below use `None`.
    assert!(
        matches!(ty, Some(InferredType::CodeRef { return_edge: Some(_) })),
        "anonymous sub: got {:?}",
        ty
    );
}

#[test]
fn test_extract_regexp_literal() {
    let fa = build_fa("my $re = qr/pattern/;");
    let ty = fa.inferred_type_via_bag("$re", Point::new(0, 21));
    assert_eq!(ty, Some(InferredType::Regexp), "qr// literal");
}

#[test]
fn test_extract_reassignment_type_change() {
    let fa = build_fa("my $x = {};\n$x = [];");
    // After line 0 → HashRef
    let ty = fa.inferred_type_via_bag("$x", Point::new(0, 11));
    assert_eq!(ty, Some(InferredType::HashRef), "initial hashref");
    // After line 1 → ArrayRef
    let ty = fa.inferred_type_via_bag("$x", Point::new(1, 8));
    assert_eq!(ty, Some(InferredType::ArrayRef), "reassigned to arrayref");
}

#[test]
fn test_extract_constructor_still_works() {
    // Existing constructor detection should still work
    let fa = build_fa("my $obj = Foo->new();");
    let ty = fa.inferred_type_via_bag("$obj", Point::new(0, 21));
    assert_eq!(ty, Some(InferredType::ClassName("Foo".into())));
}

// ---- Operator-based type inference tests (Step 3) ----

#[test]
fn test_arrow_hash_deref_infers_hashref() {
    let fa = build_fa("my $x;\n$x->{key};");
    let ty = fa.inferred_type_via_bag("$x", Point::new(1, 10));
    assert!(ty.is_some_and(|t| t.is_hash_shaped()), "hash-shaped");
}

#[test]
fn test_arrow_array_deref_infers_arrayref() {
    let fa = build_fa("my $x;\n$x->[0];");
    let ty = fa.inferred_type_via_bag("$x", Point::new(1, 8));
    assert!(ty.is_some_and(|t| t.is_array_shaped()), "array-shaped");
}

#[test]
fn test_arrow_code_deref_infers_coderef() {
    let fa = build_fa("my $x;\n$x->(1, 2);");
    let ty = fa.inferred_type_via_bag("$x", Point::new(1, 10));
    // Deref-context inference: `$x->(...)` says `$x` is a coderef
    // but reveals nothing about its body (the binding is opaque).
    assert_eq!(ty, Some(InferredType::CodeRef { return_edge: None }));
}

#[test]
fn test_coderef_call_propagates_return_type() {
    // `my $cb = sub { [1,2] }; my $r = $cb->();` — the literal's
    // `return_edge` (Expr(body_last)) rides through the binding,
    // and `$cb->()` should chase it: $r types as ArrayRef.
    // Anonymous-sub literal whose body's last expression is an
    // anonymous_array_expression — closed-under-syntax, so the
    // body span resolves to ArrayRef without name lookup.
    let fa = build_fa("my $cb = sub { [1,2] };\nmy $r = $cb->();\nmy $z;");
    let ty = fa.inferred_type_via_bag("$r", Point::new(2, 0));
    assert!(
        ty.as_ref().is_some_and(|t| t.is_array_shaped()),
        "coderef call must inherit the callable's return type via return_edge: got {:?}",
        ty,
    );
}

#[test]
fn test_postfix_array_deref_infers_arrayref() {
    let fa = build_fa("my $x;\nmy @a = $x->@*;\nmy $z;");
    let ty = fa.inferred_type_via_bag("$x", Point::new(2, 0));
    assert!(ty.is_some_and(|t| t.is_array_shaped()), "array-shaped");
}

#[test]
fn test_postfix_hash_deref_infers_hashref() {
    let fa = build_fa("my $y;\nmy %h = $y->%*;\nmy $z;");
    let ty = fa.inferred_type_via_bag("$y", Point::new(2, 0));
    assert!(ty.is_some_and(|t| t.is_hash_shaped()), "hash-shaped");
}

#[test]
fn test_binary_numeric_ops_infer_numeric() {
    let fa = build_fa("my $x;\nmy $a = $x + 1;\nmy $z;");
    let ty = fa.inferred_type_via_bag("$x", Point::new(2, 0));
    assert_eq!(ty, Some(InferredType::Numeric), "+ operator");

    let fa = build_fa("my $x;\nmy $a = $x * 2;\nmy $z;");
    let ty = fa.inferred_type_via_bag("$x", Point::new(2, 0));
    assert_eq!(ty, Some(InferredType::Numeric), "* operator");
}

#[test]
fn test_assignment_from_binary_numeric_infers_result() {
    let fa = build_fa("my $a = 1;\nmy $b = 2;\nmy $result = $a + $b;\n$result;");
    let ty = fa.inferred_type_via_bag("$result", Point::new(3, 0));
    assert_eq!(
        ty,
        Some(InferredType::Numeric),
        "$result = $a + $b should be Numeric"
    );
}

#[test]
fn test_assignment_from_string_concat_infers_result() {
    let fa = build_fa("my $a = 'x';\nmy $b = 'y';\nmy $s = $a . $b;\n$s;");
    let ty = fa.inferred_type_via_bag("$s", Point::new(3, 0));
    assert_eq!(
        ty,
        Some(InferredType::String),
        "$s = $a . $b should be String"
    );
}

#[test]
fn test_string_concat_infers_string() {
    let fa = build_fa("my $s;\nmy $a = $s . \"x\";\nmy $z;");
    let ty = fa.inferred_type_via_bag("$s", Point::new(2, 0));
    assert_eq!(ty, Some(InferredType::String), ". operator");
}

#[test]
fn test_string_repeat_infers_string() {
    let fa = build_fa("my $s;\n$s x 3;\nmy $z;");
    let ty = fa.inferred_type_via_bag("$s", Point::new(2, 0));
    assert_eq!(ty, Some(InferredType::String), "x operator");
}

#[test]
fn test_numeric_comparison_infers_numeric() {
    let fa = build_fa("my $x;\nmy $y;\n$x == $y;\nmy $z;");
    assert_eq!(
        fa.inferred_type_via_bag("$x", Point::new(3, 0)),
        Some(InferredType::Numeric)
    );
    assert_eq!(
        fa.inferred_type_via_bag("$y", Point::new(3, 0)),
        Some(InferredType::Numeric)
    );
}

#[test]
fn test_string_comparison_infers_string() {
    let fa = build_fa("my $x;\nmy $y;\n$x eq $y;\nmy $z;");
    assert_eq!(
        fa.inferred_type_via_bag("$x", Point::new(3, 0)),
        Some(InferredType::String)
    );
    assert_eq!(
        fa.inferred_type_via_bag("$y", Point::new(3, 0)),
        Some(InferredType::String)
    );
}

#[test]
fn test_increment_infers_numeric() {
    let fa = build_fa("my $x;\n$x++;\nmy $z;");
    let ty = fa.inferred_type_via_bag("$x", Point::new(2, 0));
    assert_eq!(ty, Some(InferredType::Numeric));
}

#[test]
fn test_regex_match_infers_string() {
    let fa = build_fa("my $s;\n$s =~ /pattern/;\nmy $z;");
    let ty = fa.inferred_type_via_bag("$s", Point::new(2, 0));
    assert_eq!(ty, Some(InferredType::String));
}

#[test]
fn test_preinc_infers_numeric() {
    let fa = build_fa("my $x;\n++$x;\nmy $z;");
    let ty = fa.inferred_type_via_bag("$x", Point::new(2, 0));
    assert_eq!(ty, Some(InferredType::Numeric));
}

#[test]
fn test_block_array_deref_infers_arrayref() {
    let fa = build_fa("my $x;\nmy @items = @{$x};\nmy $z;");
    let ty = fa.inferred_type_via_bag("$x", Point::new(2, 0));
    assert!(ty.is_some_and(|t| t.is_array_shaped()), "array-shaped");
}

#[test]
fn test_block_hash_deref_infers_hashref() {
    let fa = build_fa("my $y;\nmy %t = %{$y};\nmy $z;");
    let ty = fa.inferred_type_via_bag("$y", Point::new(2, 0));
    assert!(ty.is_some_and(|t| t.is_hash_shaped()), "hash-shaped");
}

#[test]
fn test_block_code_deref_infers_coderef() {
    let fa = build_fa("my $z;\n&{$z}();\nmy $w;");
    let ty = fa.inferred_type_via_bag("$z", Point::new(2, 0));
    assert_eq!(ty, Some(InferredType::CodeRef { return_edge: None }));
}

#[test]
fn test_no_numeric_on_array_variable() {
    // @arr + 1 should NOT push Numeric on @arr
    let fa = build_fa("my @arr;\nmy $n = @arr + 1;\nmy $z;");
    let ty = fa.inferred_type_via_bag("@arr", Point::new(2, 0));
    assert_eq!(ty, None, "@arr should not get Numeric constraint");
}

// ---- Builtin type inference tests ----

#[test]
fn test_builtin_push_infers_arrayref() {
    // push @{$aref} triggers array_deref_expression which already infers ArrayRef
    let fa = build_fa("my $aref;\npush @{$aref}, 1;\nmy $z;");
    let ty = fa.inferred_type_via_bag("$aref", Point::new(2, 0));
    assert!(
        ty.is_some_and(|t| t.is_array_shaped()),
        "push deref should infer ArrayRef",
    );
}

#[test]
fn test_builtin_length_infers_string_arg() {
    let fa = build_fa("my $s;\nmy $n = length($s);\nmy $z;");
    let ty = fa.inferred_type_via_bag("$s", Point::new(2, 0));
    assert_eq!(
        ty,
        Some(InferredType::String),
        "length arg should be String"
    );
}

#[test]
fn test_builtin_abs_infers_numeric_arg() {
    let fa = build_fa("my $x;\nmy $n = abs($x);\nmy $z;");
    let ty = fa.inferred_type_via_bag("$x", Point::new(2, 0));
    assert_eq!(ty, Some(InferredType::Numeric), "abs arg should be Numeric");
}

#[test]
fn test_builtin_return_type_propagates() {
    let fa = build_fa("my $t = time();\n$t;");
    let ty = fa.inferred_type_via_bag("$t", Point::new(1, 0));
    assert_eq!(
        ty,
        Some(InferredType::Numeric),
        "time() should return Numeric"
    );
}

#[test]
fn test_builtin_join_return_type() {
    let fa = build_fa("my $s = join(',', @arr);\n$s;");
    let ty = fa.inferred_type_via_bag("$s", Point::new(1, 0));
    assert_eq!(
        ty,
        Some(InferredType::String),
        "join() should return String"
    );
}

#[test]
fn test_builtin_length_return_type() {
    let fa = build_fa("my $n = length('hello');\n$n;");
    let ty = fa.inferred_type_via_bag("$n", Point::new(1, 0));
    assert_eq!(
        ty,
        Some(InferredType::Numeric),
        "length() should return Numeric"
    );
}

// ---- Return type inference tests (Step 4) ----

#[test]
fn test_return_type_hashref() {
    let fa = build_fa("sub get_config {\n    return { host => \"localhost\" };\n}");
    assert!(
        fa.sub_return_type_at_arity("get_config", None).is_some_and(|t| t.is_hash_shaped()),
        "hash-shaped",
    );
}

#[test]
fn test_return_type_arrayref() {
    let fa = build_fa("sub get_tags {\n    return [1, 2, 3];\n}");
    assert!(
        fa.sub_return_type_at_arity("get_tags", None).is_some_and(|t| t.is_array_shaped()),
        "array-shaped",
    );
}

#[test]
fn test_return_type_coderef() {
    let fa = build_fa("sub get_handler {\n    return sub { 1 };\n}");
    let ty = fa.sub_return_type_at_arity("get_handler", None);
    // `return sub { 1 }` is a sub-literal — the returned CodeRef
    // carries `return_edge` to the body's last expression.
    assert!(
        matches!(ty, Some(InferredType::CodeRef { return_edge: Some(_) })),
        "got {:?}",
        ty
    );
}

#[test]
fn test_return_type_implicit_last_expr() {
    // No explicit return — last expression is the implicit return
    let fa = build_fa("sub get_data {\n    { key => \"val\" };\n}");
    assert!(
        fa.sub_return_type_at_arity("get_data", None).is_some_and(|t| t.is_hash_shaped()),
        "hash-shaped",
    );
}

#[test]
fn test_return_type_conflicting_returns_unknown() {
    // Two returns with different types → None (unknown)
    let fa = build_fa("sub ambiguous {\n    if (1) { return {} }\n    return [];\n}");
    assert_eq!(fa.sub_return_type_at_arity("ambiguous", None), None);
}

#[test]
fn test_return_type_consistent_returns() {
    // Multiple returns all hashref → HashRef
    let fa =
        build_fa("sub consistent {\n    if (1) { return { a => 1 } }\n    return { b => 2 };\n}");
    assert!(
        fa.sub_return_type_at_arity("consistent", None).is_some_and(|t| t.is_hash_shaped()),
        "hash-shaped",
    );
}

#[test]
fn test_return_type_propagation_to_call_site() {
    let fa =
        build_fa("sub get_config {\n    return { host => 1 };\n}\nmy $cfg = get_config();\nmy $z;");
    assert!(
        fa.sub_return_type_at_arity("get_config", None).is_some_and(|t| t.is_hash_shaped()),
        "hash-shaped",
    );
    let ty = fa.inferred_type_via_bag("$cfg", Point::new(4, 0));
    assert!(
        ty.is_some_and(|t| t.is_hash_shaped()),
        "call site should get return type",
    );
}

#[test]
fn test_return_type_propagation_method_call() {
    let src = "package Calculator;\nsub new { bless {}, shift }\nsub add {\n    my ($self, $a, $b) = @_;\n    my $result = $a + $b;\n    return $result;\n}\npackage main;\nmy $calc = Calculator->new();\nmy $sum = $calc->add(2, 3);\n$sum;";
    let fa = build_fa(src);
    assert_eq!(
        fa.sub_return_type_at_arity("add", None),
        Some(InferredType::Numeric),
        "add should return Numeric"
    );
    let ty = fa.inferred_type_via_bag("$sum", Point::new(10, 0));
    assert_eq!(
        ty,
        Some(InferredType::Numeric),
        "$sum should be Numeric via method call binding"
    );
}

#[test]
fn test_return_type_constructor() {
    let fa = build_fa("package User;\nsub new { bless {}, shift }\npackage main;\nsub get_user {\n    return User->new();\n}");
    assert_eq!(
        fa.sub_return_type_at_arity("get_user", None),
        Some(InferredType::ClassName("User".into()))
    );
}

#[test]
fn test_return_type_self_variable() {
    // `return $self` resolves through the witness bag to the canonical
    // class type. `FirstParam` (the body-internal observation) is
    // normalised to `ClassName` at the FrameworkAwareTypeFold boundary
    // — callers chaining off the return get the concrete class.
    let fa = build_fa("package Foo;\nsub new { bless {}, shift }\nsub clone {\n    my ($self) = @_;\n    return $self;\n}");
    assert_eq!(
        fa.sub_return_type_at_arity("clone", None),
        Some(InferredType::ClassName("Foo".into())),
    );
}

#[test]
fn test_return_type_bare_return_filtered() {
    // Bare return + typed return → bare is filtered, typed return wins
    let fa = build_fa("sub get_config {\n    return unless 1;\n    return { host => 1 };\n}");
    assert!(
        fa.sub_return_type_at_arity("get_config", None).is_some_and(|t| t.is_hash_shaped()),
        "hash-shaped",
    );
}

#[test]
fn test_return_type_all_bare_returns() {
    // All bare returns → no return type
    let fa = build_fa("sub noop {\n    return;\n}");
    assert_eq!(fa.sub_return_type_at_arity("noop", None), None);
}

#[test]
fn test_return_type_undef_filtered() {
    // return undef + typed return → undef is filtered, typed return wins
    let fa = build_fa("sub maybe {\n    return undef unless 1;\n    return { a => 1 };\n}");
    assert!(
        fa.sub_return_type_at_arity("maybe", None).is_some_and(|t| t.is_hash_shaped()),
        "hash-shaped",
    );
}

// ---- resolve_expression_type tests ----

/// Find the first node of given kind at/after a point (searches all children).
fn find_node_at<'a>(
    node: tree_sitter::Node<'a>,
    point: Point,
    kind: &str,
) -> Option<tree_sitter::Node<'a>> {
    if node.kind() == kind && node.start_position() >= point {
        return Some(node);
    }
    for i in 0..node.child_count() {
        if let Some(child) = node.child(i) {
            if let Some(found) = find_node_at(child, point, kind) {
                return Some(found);
            }
        }
    }
    None
}

#[test]
fn test_resolve_expr_type_function_call() {
    let src = "sub get_config {\n    return { host => 1 };\n}\nget_config();\n";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());
    // Find the function_call_expression on line 3
    let call_node = find_node_at(
        tree.root_node(),
        Point::new(3, 0),
        "function_call_expression",
    )
    .expect("should find function_call_expression");
    let ty = crate::cursor_context::resolve_expression_type(&fa, call_node, src.as_bytes(), None);
    assert!(ty.is_some_and(|t| t.is_hash_shaped()), "hash-shaped");
}

#[test]
fn test_resolve_expr_type_method_call_return() {
    let src = "package Foo;\nsub new { bless {}, shift }\nsub get_bar {\n    return Bar->new();\n}\npackage Bar;\nsub new { bless {}, shift }\nsub do_thing { }\npackage main;\nmy $f = Foo->new();\n";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());
    // $f->get_bar() should resolve to Object(Bar)
    // First verify get_bar has the right return type
    assert_eq!(
        fa.sub_return_type_at_arity("get_bar", None),
        Some(InferredType::ClassName("Bar".into()))
    );
}

#[test]
fn test_resolve_expr_type_scalar_variable() {
    let src = "my $x = {};\n$x;\n";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());
    // Find the scalar $x on line 1
    let scalar_node =
        find_node_at(tree.root_node(), Point::new(1, 0), "scalar").expect("should find scalar");
    let ty = crate::cursor_context::resolve_expression_type(&fa, scalar_node, src.as_bytes(), None);
    assert!(ty.is_some_and(|t| t.is_hash_shaped()), "hash-shaped");
}

#[test]
fn test_resolve_expr_type_chained_method() {
    let src = "package Foo;\nsub new { bless {}, shift }\nsub get_bar {\n    return Bar->new();\n}\npackage Bar;\nsub new { bless {}, shift }\nsub get_name {\n    return { name => 'test' };\n}\npackage main;\nmy $f = Foo->new();\n$f->get_bar()->get_name();\n";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());
    // Line 12: $f->get_bar()->get_name();
    // The outermost method_call_expression starts at column 0
    // Use descendant_for_point_range to find the node at the start of that line
    let node = tree
        .root_node()
        .descendant_for_point_range(Point::new(12, 0), Point::new(12, 25))
        .expect("should find node");
    // Walk up to find the outermost method_call_expression
    let mut n = node;
    while n.kind() != "method_call_expression"
        || n.parent()
            .map_or(false, |p| p.kind() == "method_call_expression")
    {
        n = match n.parent() {
            Some(p) => p,
            None => panic!("should find outermost method_call_expression"),
        };
    }
    assert_eq!(n.kind(), "method_call_expression");
    let ty = crate::cursor_context::resolve_expression_type(&fa, n, src.as_bytes(), None);
    assert!(ty.is_some_and(|t| t.is_hash_shaped()), "hash-shaped");
}

#[test]
fn test_resolve_expr_type_constructor() {
    let src = "package Foo;\nsub new { bless {}, shift }\npackage main;\nFoo->new();\n";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());
    let call = find_node_at(tree.root_node(), Point::new(3, 0), "method_call_expression")
        .expect("should find method_call_expression");
    let ty = crate::cursor_context::resolve_expression_type(&fa, call, src.as_bytes(), None);
    assert_eq!(ty, Some(InferredType::ClassName("Foo".into())));
}

#[test]
fn test_resolve_expr_type_triple_chain() {
    // $calc->get_self->get_config->{host} — no parens on method calls
    let src = "\
package Calculator;
sub new { bless {}, shift }
sub get_self {
    my ($self) = @_;
    return $self;
}
sub get_config {
    return { host => 'localhost', port => 5432 };
}
package main;
my $calc = Calculator->new();
$calc->get_self->get_config->{host};
";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());

    // Verify get_self returns an object type for Calculator
    let get_self_rt = fa.sub_return_type_at_arity("get_self", None);
    assert_eq!(
        get_self_rt.as_ref().and_then(|t| t.class_name()),
        Some("Calculator"),
        "get_self should return Calculator"
    );

    // Verify get_config returns HashRef
    let get_config_rt = fa.sub_return_type_at_arity("get_config", None);
    assert!(
        get_config_rt.is_some_and(|t| t.is_hash_shaped()),
        "get_config should return HashRef",
    );

    // The outermost expression is hash_element_expression wrapping the chain
    // Find the method_call_expression for get_config (inner chain)
    // Line 11: $calc->get_self->get_config->{host}
    let node = tree
        .root_node()
        .descendant_for_point_range(Point::new(11, 0), Point::new(11, 0))
        .expect("should find node");
    let mut n = node;
    // Walk up to find hash_element_expression
    loop {
        if n.kind() == "hash_element_expression" {
            break;
        }
        n = n.parent().expect("should find hash_element_expression");
    }
    // The base of hash_element_expression is the method chain
    let base = n.named_child(0).expect("should have base");
    assert_eq!(base.kind(), "method_call_expression");
    let ty = crate::cursor_context::resolve_expression_type(&fa, base, src.as_bytes(), None);
    assert!(
        ty.is_some_and(|t| t.is_hash_shaped()),
        "the chain $calc->get_self->get_config should resolve to HashRef",
    );
}

/// Acceptance for the unified, tree-free expression-type chase
/// (`docs/prompt-unify-expr-type-resolution.md`): the ref-keyed,
/// `tree: None` invocant-class path and the node-keyed
/// `resolve_expression_type` path must produce identical answers for
/// every invocant shape — scalar, chain, array-element, function-call,
/// and hash-element. Both now route through `expr_type_at_span`.
#[test]
fn invocant_class_and_resolve_expression_type_agree_tree_free() {
    let src = "\
package Foo;
sub new { bless {}, shift }
sub kid { return Foo->new(); }
sub cfg { return { host => 'x' }; }
package main;
sub mk { return Foo->new(); }
my $f = Foo->new();
my @arr;
push @arr, Foo->new();
my %h = (it => $f);
$f->kid();
$f->kid()->kid();
$arr[0]->kid();
mk()->kid();
$h{it}->kid();
";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());

    // For every MethodCall ref with an invocant span, the two paths
    // must agree. The invocant-class path takes no tree; the
    // expression-type path is fed the actual invocant CST node.
    let mut checked_shapes = 0;
    for r in &fa.refs {
        let RefKind::MethodCall { invocant_span: Some(sp), .. } = &r.kind else {
            continue;
        };
        let invocant_node = tree
            .root_node()
            .descendant_for_point_range(sp.start, sp.end)
            .expect("invocant span maps to a node");
        // Skip if the descendant doesn't exactly cover the invocant
        // (parser quirk for some shapes) — we only compare where both
        // paths see the same node.
        if invocant_node.start_position() != sp.start
            || invocant_node.end_position() != sp.end
        {
            continue;
        }
        let via_ref = fa.method_call_invocant_class(r, None);
        let via_node =
            crate::cursor_context::resolve_expression_type(&fa, invocant_node, src.as_bytes(), None)
                .and_then(|t| t.class_name().map(|s| s.to_string()));
        assert_eq!(
            via_ref, via_node,
            "invocant-class (tree-free) vs resolve_expression_type disagree \
             for invocant `{}` (kind {})",
            invocant_node.utf8_text(src.as_bytes()).unwrap_or("?"),
            invocant_node.kind(),
        );
        checked_shapes += 1;
    }
    // Sanity: the source exercises scalar / chain / array-element /
    // function-call / hash-element invocants, so we should have
    // compared several.
    assert!(
        checked_shapes >= 5,
        "expected to compare at least the 5 invocant shapes, got {}",
        checked_shapes,
    );

    // Spot-check the concrete answers so a mutual `None` regression
    // can't pass the agreement assert vacuously.
    let kid_on_scalar = fa.refs.iter().find(|r| {
        matches!(&r.kind, RefKind::MethodCall { invocant, .. } if invocant == "$f")
            && r.target_name == "kid"
    });
    assert_eq!(
        kid_on_scalar.and_then(|r| fa.method_call_invocant_class(r, None)).as_deref(),
        Some("Foo"),
        "scalar invocant `$f->kid` should type as Foo, tree-free",
    );
    let kid_on_array = fa.refs.iter().find(|r| {
        matches!(&r.kind, RefKind::MethodCall { invocant, .. } if invocant.starts_with("$arr"))
            && r.target_name == "kid"
    });
    assert_eq!(
        kid_on_array.and_then(|r| fa.method_call_invocant_class(r, None)).as_deref(),
        Some("Foo"),
        "array-element invocant `$arr[0]->kid` should type as Foo, tree-free",
    );
}

#[test]
fn test_package_at() {
    let fa = build_fa("package Foo;\nsub bar { }");
    let pkg = fa.package_at(Point::new(1, 5));
    assert_eq!(pkg, Some("Foo"));
}

#[test]
fn test_variable_resolves_to() {
    let fa = build_fa("my $x = 1;\nprint $x;");
    let read_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "$x" && r.access == AccessKind::Read)
        .collect();
    assert!(!read_refs.is_empty());
    assert!(
        read_refs[0].resolves_to.is_some(),
        "read ref should resolve to declaration"
    );
}

#[test]
fn test_fold_ranges() {
    let fa = build_fa("sub foo {\n    my $x = 1;\n}\nsub bar {\n    my $y = 2;\n}");
    assert!(
        fa.fold_ranges.len() >= 2,
        "should have fold ranges for sub blocks, got {}",
        fa.fold_ranges.len()
    );
}

#[test]
fn test_visible_symbols() {
    let fa = build_fa("my $outer = 1;\nsub foo {\n    my $inner = 2;\n}");
    // Inside the sub, both $outer and $inner should be visible
    let visible = fa.visible_symbols(Point::new(2, 10));
    let names: Vec<&str> = visible.iter().map(|s| s.name.as_str()).collect();
    assert!(
        names.contains(&"$inner"),
        "should see $inner, got: {:?}",
        names
    );
    assert!(
        names.contains(&"$outer"),
        "should see $outer, got: {:?}",
        names
    );
}

#[test]
fn test_two_packages_scoped() {
    let fa = build_fa("package Foo;\nsub alpha { }\npackage Bar;\nsub beta { }");
    // At the beta sub, package should be "Bar"
    let pkg = fa.package_at(Point::new(3, 5));
    assert_eq!(pkg, Some("Bar"));
    // At the alpha sub, package should be "Foo"
    let pkg = fa.package_at(Point::new(1, 5));
    assert_eq!(pkg, Some("Foo"));
}

#[test]
fn test_block_scoped_package_reverts() {
    // A `package Inner;` inside a bare `{ }` block must NOT leak past the
    // block close — `sub o` after the block belongs to Outer.
    let src = "package Outer;\n{\n  package Inner;\n  sub i { }\n}\nsub o { }\n";
    let fa = build_fa(src);

    let o = fa.symbols.iter().find(|s| s.name == "o").expect("sub o");
    assert_eq!(o.package.as_deref(), Some("Outer"), "sub o must be in Outer, not Inner");

    let i = fa.symbols.iter().find(|s| s.name == "i").expect("sub i");
    assert_eq!(i.package.as_deref(), Some("Inner"), "sub i must be in Inner");

    // package_at must also revert: line 5 (`sub o`) is Outer.
    assert_eq!(fa.package_at(Point::new(5, 4)), Some("Outer"));
    // line 3 (`sub i`) is Inner.
    assert_eq!(fa.package_at(Point::new(3, 6)), Some("Inner"));
}

#[test]
fn test_non_block_package_unaffected() {
    // Regression: a normal statement-form `package Bar;` (no block) still
    // flows to end of file.
    let fa = build_fa("package Foo;\nsub a { }\npackage Bar;\nsub b { }\nsub c { }\n");
    let b = fa.symbols.iter().find(|s| s.name == "b").expect("sub b");
    let c = fa.symbols.iter().find(|s| s.name == "c").expect("sub c");
    assert_eq!(b.package.as_deref(), Some("Bar"));
    assert_eq!(c.package.as_deref(), Some("Bar"));
}

// ---- High-level query tests ----

#[test]
fn test_find_def_variable() {
    let fa = build_fa("my $x = 1;\nprint $x;");
    // Cursor on the usage of $x at line 1
    let def = fa.find_definition(Point::new(1, 7), None);
    assert!(def.is_some(), "should find definition for $x");
    let span = def.unwrap();
    assert_eq!(span.start.row, 0, "definition should be on line 0");
}

#[test]
fn test_find_def_sub() {
    let fa = build_fa("sub greet { }\ngreet();");
    // Cursor on the function call at line 1
    let def = fa.find_definition(Point::new(1, 1), None);
    assert!(def.is_some(), "should find definition for greet");
    let span = def.unwrap();
    assert_eq!(span.start.row, 0, "definition should be on line 0");
}

#[test]
fn test_find_def_method_in_class() {
    let src = "package Foo;\nsub new { bless {}, shift }\nsub hello { }\npackage main;\nmy $f = Foo->new();\n$f->hello();";
    let fa = build_fa(src);
    // Cursor on hello() call at line 5
    let def = fa.find_definition(Point::new(5, 5), None);
    assert!(def.is_some(), "should find definition for hello method");
    let span = def.unwrap();
    assert_eq!(span.start.row, 2, "hello definition should be on line 2");
}

#[test]
fn test_find_def_scoped_variable() {
    let src = "my $x = 'outer';\nsub foo {\n    my $x = 'inner';\n    print $x;\n}";
    let fa = build_fa(src);
    // Cursor on $x inside sub (line 3) should resolve to inner $x (line 2)
    let def = fa.find_definition(Point::new(3, 11), None);
    assert!(def.is_some());
    let span = def.unwrap();
    assert_eq!(span.start.row, 2, "should resolve to inner $x on line 2");
}

#[test]
fn test_find_references_variable() {
    let src = "my $x = 1;\nprint $x;\n$x = 2;";
    let fa = build_fa(src);
    // Cursor on the declaration of $x
    let refs = fa.find_references(Point::new(0, 4), None);
    assert!(
        refs.len() >= 2,
        "should find at least declaration + usage, got {}",
        refs.len()
    );
}

#[test]
fn test_hash_key_def_implicit_return_gets_sub_owner() {
    // Implicit return: last expression in sub body, no explicit `return`
    let src = "sub get_config { { host => 'localhost', port => 5432 } }\nmy $cfg = get_config();\n$cfg->{host};\n";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());

    let host_defs: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "host" && matches!(s.detail, SymbolDetail::HashKeyDef { .. }))
        .collect();
    assert!(!host_defs.is_empty(), "should find HashKeyDef for 'host'");
    if let SymbolDetail::HashKeyDef { ref owner, .. } = host_defs[0].detail {
        assert_eq!(
            *owner,
            HashKeyOwner::Sub {
                // Top-level scripts default to `main` per Perl's
                // own semantics; the implicit-package seed in
                // `Builder::new` makes this an explicit `Some("main")`
                // rather than `None`.
                package: Some("main".to_string()),
                name: "get_config".to_string()
            },
            "implicit return hash key should have Sub get_config owner, got {:?}",
            owner
        );
    }

    // Go-to-def from $cfg->{host} should reach the hash key in the implicit return
    let host_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "host" && matches!(r.kind, RefKind::HashKeyAccess { .. }))
        .collect();
    assert!(
        !host_refs.is_empty(),
        "should find HashKeyAccess for 'host'"
    );
    let def = fa.find_definition(
        host_refs[0].span.start,
        None);
    assert!(def.is_some(), "should find definition for host");
    assert_eq!(def.unwrap().start.row, 0, "host def should be on line 0");
}

#[test]
fn test_find_references_sub() {
    let src = "sub greet { }\ngreet();\ngreet();";
    let fa = build_fa(src);
    // Cursor on the sub name
    let refs = fa.find_references(Point::new(0, 5), None);
    assert!(
        refs.len() >= 2,
        "should find definition + calls, got {}",
        refs.len()
    );
}

#[test]
fn test_find_references_method_through_chain() {
    let src = "\
package Foo;
sub new { bless {}, shift }
sub bar { 42 }
package main;
sub get_foo { return Foo->new() }
my $f = Foo->new();
$f->bar();
get_foo()->bar();
";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());
    // Cursor on bar definition (line 2, col 4)
    let refs = fa.find_references(Point::new(2, 5), None);
    // Should find: $f->bar() + get_foo()->bar() (definition may or may not be included)
    let ref_lines: Vec<usize> = refs.iter().map(|s| s.start.row).collect();
    assert!(
        refs.len() >= 2,
        "should find at least 2 refs, got {} at lines {:?}",
        refs.len(),
        ref_lines
    );
    // The key assertion: chained call get_foo()->bar() is found (was broken before P0a fix)
    assert!(
        ref_lines.contains(&7),
        "should find chained get_foo()->bar() at line 7, got {:?}",
        ref_lines
    );
}

#[test]
fn test_hash_key_def_in_return_gets_sub_owner() {
    let src = "sub get_config {\n    return { host => 'localhost', port => 5432 };\n}\nmy $cfg = get_config();\n$cfg->{host};\n";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());

    // Verify hash key defs exist with Sub owner
    let host_defs: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "host" && matches!(s.detail, SymbolDetail::HashKeyDef { .. }))
        .collect();
    assert!(!host_defs.is_empty(), "should find HashKeyDef for 'host'");
    if let SymbolDetail::HashKeyDef { ref owner, .. } = host_defs[0].detail {
        assert_eq!(
            *owner,
            HashKeyOwner::Sub {
                // Top-level scripts default to `main` per Perl's
                // own semantics; the implicit-package seed in
                // `Builder::new` makes this an explicit `Some("main")`
                // rather than `None`.
                package: Some("main".to_string()),
                name: "get_config".to_string()
            },
            "host def should have Sub get_config owner, got {:?}",
            owner
        );
    }

    // Verify HashKeyAccess ref for $cfg->{host} has Sub owner
    let host_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "host" && matches!(r.kind, RefKind::HashKeyAccess { .. }))
        .collect();
    assert!(
        !host_refs.is_empty(),
        "should find HashKeyAccess for 'host'"
    );
    if let RefKind::HashKeyAccess { ref owner, .. } = host_refs[0].kind {
        assert_eq!(
            *owner,
            Some(HashKeyOwner::Sub {
                package: Some("main".to_string()),
                name: "get_config".to_string()
            }),
            "host ref should have Sub get_config owner, got {:?}",
            owner
        );
    }

    // Verify go-to-references from the def finds the usage
    let host_def_point = host_defs[0].selection_span.start;
    let refs = fa.find_references(host_def_point, None);
    // symbol_at returns include_decl=false, so only usages are returned
    assert!(
        refs.len() >= 1,
        "should find at least 1 usage, got {} refs",
        refs.len()
    );

    // Verify go-to-references from the usage finds back to the def
    let host_ref_point = host_refs[0].span.start;
    let refs_from_usage = fa.find_references(host_ref_point, None);
    // ref resolves to def → include_decl=true, so def + usage
    assert!(
        refs_from_usage.len() >= 2,
        "should find def + usage, got {} refs",
        refs_from_usage.len()
    );
}

#[test]
fn test_hash_key_refs_chained_resolved_at_build() {
    // Chained method calls returning a Sub-keyed hash: the build-time
    // `emit_chained_hash_key_refs` pass resolves the owner to
    // `Sub{Calculator, get_config}` (the implicit-return keys), so the
    // stored ref carries it — no tree fallback needed.
    let src = r#"package Calculator;
sub new { bless {}, shift }
sub get_self { my ($self) = @_; return $self; }
sub get_config { return { host => "localhost", port => 5432 }; }
package main;
my $calc = Calculator->new();
$calc->get_self->get_config->{host};
"#;
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());

    // Find the hash key def for "host" in get_config's return
    let host_defs: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "host" && matches!(s.detail, SymbolDetail::HashKeyDef { .. }))
        .collect();
    assert!(!host_defs.is_empty(), "should find HashKeyDef for 'host'");

    // The chained ref now carries its resolved owner at build time.
    let owner = fa
        .refs
        .iter()
        .find_map(|r| match &r.kind {
            RefKind::HashKeyAccess { owner: Some(o), .. } if r.target_name == "host" => {
                Some(o.clone())
            }
            _ => None,
        })
        .expect("chained hash access should carry a resolved owner");
    assert_eq!(
        owner,
        HashKeyOwner::Sub {
            package: Some("Calculator".to_string()),
            name: "get_config".to_string(),
        },
        "owner should be the return-hash sub of the last chain hop, got {:?}",
        owner
    );

    // find_references from the def finds the chained usage.
    let host_def_point = host_defs[0].selection_span.start;
    let refs = fa.find_references(host_def_point, None);
    assert!(
        refs.len() >= 1,
        "should find chained usage, got {} refs",
        refs.len()
    );
}

#[test]
fn test_highlights_read_write() {
    let src = "my $x = 1;\nprint $x;\n$x = 2;";
    let fa = build_fa(src);
    let highlights = fa.find_highlights(Point::new(0, 4), None);
    assert!(!highlights.is_empty(), "should have highlights");
    // Check that we have both read and write accesses
    let has_write = highlights
        .iter()
        .any(|(_, a)| matches!(a, AccessKind::Write));
    let has_read = highlights
        .iter()
        .any(|(_, a)| matches!(a, AccessKind::Read));
    // At minimum we should see the declaration
    assert!(
        highlights.len() >= 2,
        "should have at least 2 highlights, got {}",
        highlights.len()
    );
    // Note: whether read/write are correctly tagged depends on builder's access classification
    let _ = (has_write, has_read); // suppress unused warnings if assertions change
}

#[test]
fn test_hover_variable() {
    let src = "my $greeting = 'hello';\nprint $greeting;";
    let fa = build_fa(src);
    let hover = fa.hover_info(Point::new(1, 8), src, None);
    assert!(hover.is_some(), "should have hover info");
    let text = hover.unwrap();
    assert!(
        text.contains("$greeting"),
        "hover should contain variable name, got: {}",
        text
    );
}

#[test]
fn test_hover_sub() {
    let src = "sub greet { }\ngreet();";
    let fa = build_fa(src);
    let hover = fa.hover_info(Point::new(1, 1), src, None);
    assert!(hover.is_some(), "should have hover info for function call");
    let text = hover.unwrap();
    assert!(
        text.contains("greet"),
        "hover should contain sub name, got: {}",
        text
    );
}

#[test]
fn test_hover_shows_inferred_type() {
    let src =
        "package Point;\nsub new { bless {}, shift }\npackage main;\nmy $p = Point->new();\n$p;";
    let fa = build_fa(src);
    // Hover on $p usage at line 4
    let hover = fa.hover_info(Point::new(4, 1), src, None);
    assert!(hover.is_some(), "should have hover info");
    let text = hover.unwrap();
    assert!(
        text.contains("Point"),
        "hover should show inferred type Point, got: {}",
        text
    );
}

#[test]
fn test_hover_type_at_usage_after_reassignment() {
    // $x starts as Point, gets reassigned to Foo — hover at each usage should reflect the type at that point
    let src = "package Point;\nsub new { bless {}, shift }\npackage Foo;\nsub new { bless {}, shift }\npackage main;\nmy $x = Point->new();\n$x;\n$x = Foo->new();\n$x;";
    let fa = build_fa(src);
    // line 6: $x; — should be Point
    let hover1 = fa.hover_info(Point::new(6, 1), src, None);
    assert!(hover1.is_some());
    let text1 = hover1.unwrap();
    assert!(
        text1.contains("Point"),
        "at line 6 should be Point, got: {}",
        text1
    );
    // line 8: $x; — should be Foo (after reassignment)
    let hover2 = fa.hover_info(Point::new(8, 1), src, None);
    assert!(hover2.is_some());
    let text2 = hover2.unwrap();
    assert!(
        text2.contains("Foo"),
        "at line 8 should be Foo, got: {}",
        text2
    );
}

#[test]
fn test_hover_shows_return_type() {
    let src = "package Foo;\nsub make { return Foo->new() }\nsub new { bless {}, shift }\npackage main;\nmake();";
    let fa = build_fa(src);
    // Hover on sub make definition
    let hover = fa.hover_info(Point::new(1, 5), src, None);
    assert!(hover.is_some(), "should have hover info for sub");
    let text = hover.unwrap();
    assert!(
        text.contains("returns"),
        "hover should show return type, got: {}",
        text
    );
    assert!(
        text.contains("Foo"),
        "hover return type should mention Foo, got: {}",
        text
    );
}

#[test]
fn test_rename_variable() {
    let src = "my $x = 1;\nprint $x;";
    let fa = build_fa(src);
    let edits = fa.rename_at(Point::new(0, 4), "y");
    assert!(edits.is_some(), "should produce rename edits");
    let edits = edits.unwrap();
    assert!(
        edits.len() >= 2,
        "should rename at least declaration + usage"
    );
    for (_, new_text) in &edits {
        assert_eq!(new_text, "y", "all edits should use new name");
    }
}

#[test]
fn test_rename_sub_finds_both_function_and_method_calls() {
    let fa = build_fa(
        "
package Foo;
sub emit { }
sub test {
    my $self = shift;
    emit('event');
    $self->emit('done');
}
",
    );
    // `sub emit` in package Foo. Scope-aware rename with
    // package=Foo catches the decl, the FunctionCall `emit()`,
    // AND the MethodCall `$self->emit()` — two shapes of the
    // same callable.
    let edits = fa.rename_sub_in_package("emit", &Some("Foo".to_string()), "fire", None);
    assert!(
        edits.len() >= 3,
        "rename_sub_in_package should find def + function call + method call, got {} edits",
        edits.len()
    );
    for (_, text) in &edits {
        assert_eq!(text, "fire");
    }
}

#[test]
fn test_moo_has_creates_constructor_hash_key_def() {
    let fa = build_fa(
        "
package MyApp;
use Moo;
has username => (is => 'ro');
has password => (is => 'rw');
",
    );
    // Should have HashKeyDef symbols owned by "new" for each has attribute
    let key_defs: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| matches!(s.detail, SymbolDetail::HashKeyDef { .. }))
        .collect();
    let names: Vec<&str> = key_defs.iter().map(|s| s.name.as_str()).collect();
    assert!(
        names.contains(&"username"),
        "should have HashKeyDef for username, got: {:?}",
        names
    );
    assert!(
        names.contains(&"password"),
        "should have HashKeyDef for password, got: {:?}",
        names
    );
    // Verify owner is Sub { package: "MyApp", name: "new" }
    if let SymbolDetail::HashKeyDef { ref owner, .. } = key_defs[0].detail {
        assert_eq!(
            owner,
            &HashKeyOwner::Sub {
                package: Some("MyApp".to_string()),
                name: "new".to_string(),
            }
        );
    }
}

// ---- ERROR recovery tests ----
// tree-sitter-perl wraps broken regions in ERROR nodes. Some structural
// declarations (sub, class) survive as typed nodes inside ERROR.
// use/package often get parsed as raw function tokens inside ERROR —
// those can't be recovered (parser fix needed).

#[test]
fn test_error_recovery_sub_outside_error() {
    // my $x = [ creates an ERROR, but sub below it survives as a top-level node
    let source = "package Foo;\nmy $x = [\nuse List::Util qw(max);\nsub process { }\n";
    let fa = build_fa(source);
    let subs: Vec<&str> = fa
        .symbols
        .iter()
        .filter(|s| matches!(s.kind, SymKind::Sub | SymKind::Method))
        .map(|s| s.name.as_str())
        .collect();
    assert!(
        subs.contains(&"process"),
        "sub process should survive (outside ERROR)"
    );
}

#[test]
fn test_error_recovery_sub_outside_error_survives() {
    // Sub below an ERROR survives as a top-level node (not inside ERROR)
    let source = "package Foo;\nmy $x = [\nuse List::Util qw(max);\nsub process { }\n";
    let fa = build_fa(source);
    let subs: Vec<&str> = fa
        .symbols
        .iter()
        .filter(|s| matches!(s.kind, SymKind::Sub | SymKind::Method))
        .map(|s| s.name.as_str())
        .collect();
    assert!(
        subs.contains(&"process"),
        "sub process should survive (outside ERROR)"
    );
}

#[test]
fn test_error_node_does_not_panic() {
    // ERROR nodes should not crash the builder
    let source = "package Foo;\nmy $x = [\nmy $y = [\nsub process { }\n";
    let fa = build_fa(source);
    let pkgs: Vec<&str> = fa
        .symbols
        .iter()
        .filter(|s| matches!(s.kind, SymKind::Package))
        .map(|s| s.name.as_str())
        .collect();
    assert!(pkgs.contains(&"Foo"), "package Foo should survive");
}

#[test]
fn test_error_recovery_sub_inside_error() {
    let source = "package Foo;\nmy $x = [\nmy $y = [\nsub process { }\n";
    let fa = build_fa(source);
    let subs: Vec<&str> = fa
        .symbols
        .iter()
        .filter(|s| matches!(s.kind, SymKind::Sub | SymKind::Method))
        .map(|s| s.name.as_str())
        .collect();
    assert!(
        subs.contains(&"process"),
        "sub process should be recovered from ERROR"
    );
}

#[test]
fn test_error_recovery_import_inside_error() {
    let source = "package Foo;\nmy $x = [\nuse List::Util qw(max);\nsub process { }\n";
    let fa = build_fa(source);
    let imports: Vec<&str> = fa.imports.iter().map(|i| i.module_name.as_str()).collect();
    assert!(
        imports.contains(&"List::Util"),
        "use List::Util should be recovered from ERROR"
    );
}

#[test]
fn test_error_recovery_package_inside_error() {
    let source = "my $x = [\npackage Bar;\nuse Moose;\nsub bar { }\n";
    let fa = build_fa(source);
    let pkgs: Vec<&str> = fa
        .symbols
        .iter()
        .filter(|s| matches!(s.kind, SymKind::Package))
        .map(|s| s.name.as_str())
        .collect();
    assert!(
        pkgs.contains(&"Bar"),
        "package Bar should be recovered from ERROR"
    );
}

#[test]
fn test_find_def_bareword_class() {
    let src = "package Point;\nsub new { bless {}, shift }\npackage main;\nPoint->new();";
    let fa = build_fa(src);
    // Cursor on "new" in Point->new()
    let def = fa.find_definition(Point::new(3, 8), None);
    assert!(def.is_some(), "should find definition for new");
}

// ---- Block dereference descent tests ----
// @{expr}, %{expr}, ${expr} parse as scalar/array/hash with varname→block.
// The builder must recurse into the block to find inner refs.

#[test]
fn test_deref_block_produces_inner_variable_ref() {
    // @{$arr} — the inner $arr should produce a Variable ref
    let fa = build_fa("my @data = (1,2,3);\nmy $arr = \\@data;\npush @{$arr}, 4;");
    let inner_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| {
            r.target_name == "$arr"
                && matches!(r.kind, RefKind::Variable)
                && r.access == AccessKind::Read
        })
        .collect();
    assert!(
        !inner_refs.is_empty(),
        "should find $arr ref inside @{{$arr}}"
    );
    // Should NOT have a bogus ref for the whole @{$arr}
    let bogus: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name.contains("{$arr}"))
        .collect();
    assert!(
        bogus.is_empty(),
        "should not record bogus ref for whole deref expression"
    );
}

#[test]
fn test_deref_block_produces_hash_key_ref() {
    // @{$self->{items}} — inner hash_element_expression should produce:
    // 1. Variable ref for $self
    // 2. HashKeyAccess ref for "items"
    let fa = build_fa("my %h = (items => []);\n@{$h{items}};");
    let key_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "items" && matches!(r.kind, RefKind::HashKeyAccess { .. }))
        .collect();
    assert!(
        !key_refs.is_empty(),
        "should find hash key ref 'items' inside deref block"
    );
}

#[test]
fn test_deref_block_resolves_variable() {
    // Variable inside deref block should resolve to its declaration
    let fa = build_fa("my @xs = (1,2);\nmy $ref = \\@xs;\nprint @{$ref};");
    let inner_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "$ref" && r.access == AccessKind::Read)
        .collect();
    assert!(!inner_refs.is_empty(), "$ref ref should exist");
    assert!(
        inner_refs[0].resolves_to.is_some(),
        "$ref inside deref should resolve to declaration"
    );
}

#[test]
fn test_deref_self_and_hash_key() {
    // Full integration: constructor defines hash keys, method accesses them through deref
    let src = "package Calculator;\nsub new {\n    my ($class, %args) = @_;\n    my $self = bless {\n        history => [],\n        verbose => 0,\n    }, $class;\n    return $self;\n}\nsub add {\n    my ($self, $a, $b) = @_;\n    my $result = $a + $b;\n    push @{$self->{history}}, \"add\";\n    return $result;\n}";
    let fa = build_fa(src);

    // $self at line 12 (push @{$self->{history}}, ...)
    let def_self = fa.find_definition(Point::new(12, 12), None);
    assert!(
        def_self.is_some(),
        "should find definition for $self in deref"
    );
    assert_eq!(
        def_self.unwrap().start.row,
        10,
        "$self should resolve to declaration on line 10"
    );

    // history key at line 12
    let def_history = fa.find_definition(Point::new(12, 20), None);
    assert!(
        def_history.is_some(),
        "should find definition for history hash key"
    );
    assert_eq!(
        def_history.unwrap().start.row,
        4,
        "history key should resolve to definition on line 4"
    );
}

#[test]
fn test_imports_qw() {
    let source = "use List::Util qw(first any all);\nuse Scalar::Util qw(blessed);\n";
    let fa = build_fa(source);

    assert_eq!(fa.imports.len(), 2);

    assert_eq!(fa.imports[0].module_name, "List::Util");
    let names0: Vec<&str> = fa.imports[0]
        .imported_symbols
        .iter()
        .map(|s| s.local_name.as_str())
        .collect();
    assert_eq!(names0, vec!["first", "any", "all"]);

    assert_eq!(fa.imports[1].module_name, "Scalar::Util");
    let names1: Vec<&str> = fa.imports[1]
        .imported_symbols
        .iter()
        .map(|s| s.local_name.as_str())
        .collect();
    assert_eq!(names1, vec!["blessed"]);
}

#[test]
fn test_imports_qw_close_paren_position() {
    // "use List::Util qw(first);\n"
    //  0123456789...
    //                  ^18    ^24 = )
    let source = "use List::Util qw(first);\n";
    let fa = build_fa(source);

    assert_eq!(fa.imports.len(), 1);
    let imp = &fa.imports[0];
    assert!(imp.qw_close_paren.is_some(), "qw_close_paren should be set");
    let pos = imp.qw_close_paren.unwrap();
    // The ) is at column 23 in "use List::Util qw(first);"
    assert_eq!(pos.row, 0);
    assert_eq!(pos.column, 23, "close paren should be at column 23");
}

#[test]
fn test_imports_bare() {
    let source = "use strict;\nuse warnings;\nuse Carp;\n";
    let fa = build_fa(source);

    // strict/warnings/Carp all produce imports with empty imported_symbols
    let carp = fa.imports.iter().find(|i| i.module_name == "Carp");
    assert!(carp.is_some());
    assert!(carp.unwrap().imported_symbols.is_empty());
}

#[test]
fn test_imports_module_symbol_created() {
    let source = "use List::Util qw(first);\n";
    let fa = build_fa(source);

    // Module symbol should exist
    let module_syms: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Module && s.name == "List::Util")
        .collect();
    assert_eq!(module_syms.len(), 1);

    // Import should exist
    assert_eq!(fa.imports.len(), 1);
    let names: Vec<&str> = fa.imports[0]
        .imported_symbols
        .iter()
        .map(|s| s.local_name.as_str())
        .collect();
    assert_eq!(names, vec!["first"]);
}

#[test]
fn test_goto_def_slurpy_hash_arg_at_call_site() {
    // Calculator->new(verbose => 1): cursor on "verbose" should go to
    // the bless hash key def, NOT to sub new.
    let src = r#"package Calculator;
sub new {
    my ($class, %args) = @_;
    my $self = bless {
        verbose => $args{verbose} // 0,
    }, $class;
    return $self;
}
package main;
my $calc = Calculator->new(verbose => 1);
"#;
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());
    // "verbose" at call site is line 9, after "Calculator->new("
    // Calculator->new(verbose => 1)
    // 0123456789012345678901234567
    //                 ^16 = v of verbose
    // my $calc = Calculator->new(verbose => 1);
    // 0         1         2         3
    // 0123456789012345678901234567890123456789
    //                            ^27 = v of verbose
    let def = fa.find_definition(Point::new(9, 27), None);
    assert!(
        def.is_some(),
        "should find definition for verbose at call site"
    );
    // Should go to line 4: "verbose => $args{verbose} // 0,"
    assert_eq!(
        def.unwrap().start.row,
        4,
        "verbose should resolve to bless hash key def on line 4, not sub new"
    );
}

#[test]
fn test_goto_def_param_field_at_call_site() {
    // Point->new(x => 3, y => 4): cursor on "x" should go to "field $x :param"
    let src = r#"use v5.38;
class Point {
    field $x :param :reader;
    field $y :param;
    method magnitude() { }
}
my $p = Point->new(x => 3, y => 4);
"#;
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());
    // my $p = Point->new(x => 3, y => 4);
    // 0         1         2
    // 0123456789012345678901234
    //                    ^19 = x

    let def = fa.find_definition(Point::new(6, 19), None);
    assert!(def.is_some(), "should find definition for x at call site");
    // Should go to line 2: "field $x :param :reader;"
    assert_eq!(
        def.unwrap().start.row,
        2,
        "x should resolve to field $x on line 2, not the class"
    );
}

// ---- Gap 1: __PACKAGE__ resolution ----

#[test]
fn test_dunder_package_resolution() {
    let fa = build_fa(
        "
        package Mojo::File;
        sub path { __PACKAGE__->new(@_) }
        ",
    );
    let rt = fa.sub_return_type_at_arity("path", None);
    assert_eq!(rt, Some(InferredType::ClassName("Mojo::File".into())));
}

#[test]
fn test_dunder_package_method_invocant() {
    // __PACKAGE__->new() should store the resolved class in MethodCall invocant
    let fa = build_fa(
        "
        package Foo;
        __PACKAGE__->some_method();
        ",
    );
    let method_ref = fa
        .refs
        .iter()
        .find(|r| r.target_name == "some_method")
        .unwrap();
    match &method_ref.kind {
        RefKind::MethodCall { invocant, .. } => {
            assert_eq!(
                invocant, "Foo",
                "invocant should be resolved from __PACKAGE__"
            );
        }
        _ => panic!("expected MethodCall ref"),
    }
}

// ---- Gap 2: Shift parameter extraction ----

#[test]
fn test_shift_params() {
    let fa = build_fa(
        "
        sub process {
            my $self = shift;
            my $file = shift;
            my $opts = shift || {};
        }
        ",
    );
    // signature_for_call strips $self when first param is $self
    let sig = fa
        .signature_for_call("process", false, None, Point::new(0, 0), None)
        .unwrap();
    assert!(sig.is_method, "should detect method from $self first param");
    assert_eq!(sig.params.len(), 2);
    assert_eq!(sig.params[0].name, "$file");
    assert_eq!(sig.params[1].name, "$opts");
    assert_eq!(sig.params[1].default, Some("{}".into()));

    // Check raw params via symbol detail
    let sub_sym = fa.symbols.iter().find(|s| s.name == "process").unwrap();
    if let SymbolDetail::Sub { ref params, .. } = sub_sym.detail {
        assert_eq!(params.len(), 3);
        assert_eq!(params[0].name, "$self");
        assert_eq!(params[1].name, "$file");
        assert_eq!(params[2].name, "$opts");
        assert_eq!(params[2].default, Some("{}".into()));
    } else {
        panic!("expected Sub detail");
    }
}

#[test]
fn test_shift_then_list_assign() {
    let fa = build_fa(
        "
        sub process {
            my $self = shift;
            my ($file, @opts) = @_;
        }
        ",
    );
    let sig = fa
        .signature_for_call("process", false, None, Point::new(0, 0), None)
        .unwrap();
    assert!(sig.is_method);
    assert_eq!(
        sig.params.len(),
        2,
        "should have $file and @opts (stripped $self)"
    );
    assert_eq!(sig.params[0].name, "$file");
    assert_eq!(sig.params[1].name, "@opts");
    assert!(sig.params[1].is_slurpy);

    // Check raw params
    let sub_sym = fa.symbols.iter().find(|s| s.name == "process").unwrap();
    if let SymbolDetail::Sub { ref params, .. } = sub_sym.detail {
        assert_eq!(params.len(), 3);
        assert_eq!(params[0].name, "$self");
    } else {
        panic!("expected Sub detail");
    }
}

#[test]
fn test_shift_with_double_pipe_default() {
    let fa = build_fa(
        "
        sub handler {
            my $self = shift;
            my $timeout = shift || 30;
        }
        ",
    );
    let sig = fa
        .signature_for_call("handler", false, None, Point::new(0, 0), None)
        .unwrap();
    assert_eq!(sig.params.len(), 1, "stripped $self");
    assert_eq!(sig.params[0].name, "$timeout");
    assert_eq!(sig.params[0].default, Some("30".into()));
}

#[test]
fn test_shift_with_defined_or_default() {
    let fa = build_fa(
        "
        sub handler {
            my $self = shift;
            my $verbose = shift // 0;
        }
        ",
    );
    let sig = fa
        .signature_for_call("handler", false, None, Point::new(0, 0), None)
        .unwrap();
    assert_eq!(sig.params.len(), 1, "stripped $self");
    assert_eq!(sig.params[0].name, "$verbose");
    assert_eq!(sig.params[0].default, Some("0".into()));
}

#[test]
fn test_subscript_param() {
    let fa = build_fa(
        "
        sub handler {
            my $self = $_[0];
            my $data = $_[1];
        }
        ",
    );
    let sig = fa
        .signature_for_call("handler", false, None, Point::new(0, 0), None)
        .unwrap();
    assert_eq!(sig.params.len(), 1, "stripped $self");
    assert_eq!(sig.params[0].name, "$data");
}

#[test]
fn test_legacy_at_params_still_work() {
    // Ensure the existing @_ pattern still works
    let fa = build_fa(
        "
        sub process {
            my ($first, $file, @opts) = @_;
        }
        ",
    );
    let sig = fa
        .signature_for_call("process", false, None, Point::new(0, 0), None)
        .unwrap();
    assert_eq!(sig.params.len(), 3);
    assert_eq!(sig.params[0].name, "$first");
    assert_eq!(sig.params[1].name, "$file");
    assert_eq!(sig.params[2].name, "@opts");
}

#[test]
fn test_tail_pod_item_method() {
    let fa = build_fa(
        "
            package WWW::Mech;
            sub get { }
            sub post { }

=head1 METHODS

=over

=item $mech->get($url)

Performs a GET request.

=item $mech->post($url)

Performs a POST request.

=back

=cut
        ",
    );
    let get_doc = fa
        .symbols
        .iter()
        .find(|s| s.name == "get")
        .and_then(|s| match &s.detail {
            SymbolDetail::Sub { doc, .. } => doc.as_ref(),
            _ => None,
        });
    assert!(get_doc.is_some(), "get should have doc from =item");
    assert!(get_doc.unwrap().contains("GET request"));
}

#[test]
fn test_pod_doc_extracted_per_function() {
    let src = "\
package DemoUtils;
use Exporter 'import';
our @EXPORT_OK = qw(fetch_data transform);

=head2 fetch_data

Fetches data from the given URL.

=head2 transform

Transforms items.

=cut

sub fetch_data { }
sub transform { }
";
    let fa = build_fa(src);
    let fd = fa.symbols.iter().find(|s| s.name == "fetch_data").unwrap();
    if let SymbolDetail::Sub { ref doc, .. } = fd.detail {
        let d = doc.as_ref().expect("fetch_data should have doc");
        assert!(
            d.contains("Fetches data"),
            "should have fetch_data doc, got: {}",
            d
        );
        assert!(
            !d.contains("Transforms items"),
            "should NOT have transform doc, got: {}",
            d
        );
    } else {
        panic!("fetch_data should be a Sub");
    }
}

// ---- Inheritance extraction tests ----

#[test]
fn test_use_parent_single() {
    let fa = build_fa(
        "
            package Child;
            use parent 'Parent';
            sub child_method { }
        ",
    );
    assert_eq!(
        fa.package_parents.get("Child").unwrap(),
        &vec!["Parent".to_string()]
    );
}

#[test]
fn test_use_parent_multiple() {
    let fa = build_fa(
        "
            package Multi;
            use parent qw(Foo Bar);
        ",
    );
    assert_eq!(
        fa.package_parents.get("Multi").unwrap(),
        &vec!["Foo".to_string(), "Bar".to_string()]
    );
}

#[test]
fn test_use_parent_emits_package_refs() {
    let fa = build_fa(
        "
            package Child;
            use parent 'Parent';
        ",
    );
    let refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| matches!(r.kind, RefKind::PackageRef) && r.target_name == "Parent")
        .collect();
    assert_eq!(refs.len(), 1, "should emit PackageRef for parent class");
}

#[test]
fn test_use_parent_qw_emits_package_refs() {
    let fa = build_fa(
        "
            package Multi;
            use parent qw(Foo Bar);
        ",
    );
    let foo_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| matches!(r.kind, RefKind::PackageRef) && r.target_name == "Foo")
        .collect();
    let bar_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| matches!(r.kind, RefKind::PackageRef) && r.target_name == "Bar")
        .collect();
    assert_eq!(foo_refs.len(), 1, "should emit PackageRef for Foo");
    assert_eq!(bar_refs.len(), 1, "should emit PackageRef for Bar");
}

#[test]
fn test_use_parent_norequire() {
    let fa = build_fa(
        "
            package Local;
            use parent -norequire, 'My::Base';
        ",
    );
    assert_eq!(
        fa.package_parents.get("Local").unwrap(),
        &vec!["My::Base".to_string()]
    );
}

#[test]
fn test_use_base() {
    let fa = build_fa(
        "
            package Old;
            use base 'Legacy::Base';
        ",
    );
    assert_eq!(
        fa.package_parents.get("Old").unwrap(),
        &vec!["Legacy::Base".to_string()]
    );
}

#[test]
fn test_isa_assignment() {
    let fa = build_fa(
        "
            package Direct;
            our @ISA = ('Alpha', 'Beta');
        ",
    );
    assert_eq!(
        fa.package_parents.get("Direct").unwrap(),
        &vec!["Alpha".to_string(), "Beta".to_string()]
    );
}

#[test]
fn test_class_isa_populates_package_parents() {
    let fa = build_fa(
        "
            class Child :isa(Parent) { }
        ",
    );
    assert_eq!(
        fa.package_parents.get("Child").unwrap(),
        &vec!["Parent".to_string()]
    );
}

#[test]
fn test_class_does_populates_package_parents() {
    let fa = build_fa(
        "
            class MyClass :does(Printable) :does(Serializable) { }
        ",
    );
    let parents = fa.package_parents.get("MyClass").unwrap();
    assert!(parents.contains(&"Printable".to_string()));
    assert!(parents.contains(&"Serializable".to_string()));
}

#[test]
fn test_class_isa_and_does_combined() {
    let fa = build_fa(
        "
            class Child :isa(Parent) :does(Role) { }
        ",
    );
    let parents = fa.package_parents.get("Child").unwrap();
    assert_eq!(parents, &vec!["Parent".to_string(), "Role".to_string()]);
}

#[test]
fn test_with_role_populates_package_parents() {
    let fa = build_fa(
        "
            package MyApp;
            use Moo;
            with 'My::Role::Logging';
        ",
    );
    let parents = fa.package_parents.get("MyApp").unwrap();
    assert!(parents.contains(&"My::Role::Logging".to_string()));
}

#[test]
fn test_with_multiple_roles() {
    let fa = build_fa(
        "
            package MyApp;
            use Moose;
            with 'Role::A', 'Role::B';
        ",
    );
    let parents = fa.package_parents.get("MyApp").unwrap();
    assert!(parents.contains(&"Role::A".to_string()));
    assert!(parents.contains(&"Role::B".to_string()));
}

// --- E4a: MooX::Options `option` ---

/// `option 'name' => (is => 'ro', ...)` is a `has` with extra option-parsing
/// keys; it synthesizes the same accessor Method symbol + constructor HashKeyDef.
#[test]
fn test_moox_option_synthesizes_accessor_and_ctor_key() {
    let fa = build_fa(
        "
            package MyApp;
            use Moo;
            use MooX::Options;
            option 'verbose' => (is => 'ro', format => 'i', doc => 'noisy');
            option name => (is => 'rw', isa => 'Str');
        ",
    );
    // Accessor Method symbols.
    let methods: Vec<&str> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == crate::file_analysis::SymKind::Method)
        .map(|s| s.name.as_str())
        .collect();
    assert!(methods.contains(&"verbose"), "ro accessor: {methods:?}");
    assert!(methods.contains(&"name"), "rw accessor: {methods:?}");

    // Constructor HashKeyDefs (`MyApp->new(verbose => ...)`).
    let ctor_keys: Vec<&str> = fa
        .symbols
        .iter()
        .filter(|s| {
            matches!(
                &s.detail,
                crate::file_analysis::SymbolDetail::HashKeyDef {
                    owner: crate::file_analysis::HashKeyOwner::Sub { name, .. },
                    ..
                } if name == "new"
            )
        })
        .map(|s| s.name.as_str())
        .collect();
    assert!(ctor_keys.contains(&"verbose"), "ctor key verbose: {ctor_keys:?}");
    assert!(ctor_keys.contains(&"name"), "ctor key name: {ctor_keys:?}");
}

/// `option` outside a MooX::Options package must NOT synthesize accessors — an
/// unrelated `option(...)` sub call isn't an attribute declaration.
#[test]
fn test_option_without_moox_is_not_an_accessor() {
    let fa = build_fa(
        "
            package MyApp;
            use Moo;
            option 'verbose' => (is => 'ro');
        ",
    );
    let methods: Vec<&str> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == crate::file_analysis::SymKind::Method)
        .map(|s| s.name.as_str())
        .collect();
    assert!(!methods.contains(&"verbose"), "no synthesis without MooX::Options: {methods:?}");
}

/// Regression: plain `has` in a package that also `use`s MooX::Options is
/// unaffected (still synthesizes via the shared path).
#[test]
fn test_moox_options_plain_has_still_works() {
    let fa = build_fa(
        "
            package MyApp;
            use Moo;
            use MooX::Options;
            has plain => (is => 'ro', isa => 'Int');
        ",
    );
    let methods: Vec<&str> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == crate::file_analysis::SymKind::Method)
        .map(|s| s.name.as_str())
        .collect();
    assert!(methods.contains(&"plain"), "plain has accessor: {methods:?}");
}

// --- E4b: `with 'Role'` role-provided methods resolve cross-file ---

/// A class `with 'SomeRole'` should resolve `$self->m` to the role's `sub m`
/// cross-file. `with` already unifies into `package_parents`, and the
/// ancestor walk + cross-file module_index do the rest — this is a lock test.
#[test]
fn test_with_role_method_resolves_cross_file() {
    use crate::module_index::ModuleIndex;
    use std::path::PathBuf;

    let idx = ModuleIndex::new_for_test();
    idx.set_workspace_root(None);

    // The role provides `log_it`.
    idx.insert_cache(
        "My::Role::Logging",
        Some(fake_cached_for_class(
            "My::Role::Logging",
            &PathBuf::from("/fake/My/Role/Logging.pm"),
            &["log_it"],
            &[],
        )),
    );

    let fa = build_fa(
        "
            package MyApp;
            use Moo;
            with 'My::Role::Logging';
            sub run { my $self = shift; }
        ",
    );

    // Completion surfaces the role method.
    let methods = fa.complete_methods_for_class("MyApp", Some(&idx));
    let names: Vec<&str> = methods.iter().map(|c| c.label.as_str()).collect();
    assert!(names.contains(&"log_it"), "role method in completion: {names:?}");

    // resolve_method_in_ancestors finds it cross-file.
    let res = fa.resolve_method_in_ancestors("MyApp", "log_it", Some(&idx));
    assert!(
        matches!(res, Some(crate::file_analysis::MethodResolution::CrossFile { ref class, .. }) if class == "My::Role::Logging"),
        "expected CrossFile to the role, got {res:?}"
    );
}

#[test]
fn test_load_components_bare() {
    let fa = build_fa(
        "
            package MySchema::Result::User;
            use base 'DBIx::Class::Core';
            __PACKAGE__->load_components('InflateColumn::DateTime', 'TimeStamp');
        ",
    );
    let parents = fa.package_parents.get("MySchema::Result::User").unwrap();
    assert!(parents.contains(&"DBIx::Class::Core".to_string()));
    assert!(parents.contains(&"DBIx::Class::InflateColumn::DateTime".to_string()));
    assert!(parents.contains(&"DBIx::Class::TimeStamp".to_string()));
}

#[test]
fn test_load_components_plus_prefix() {
    let fa = build_fa(
        "
            package MySchema::Result::User;
            use base 'DBIx::Class::Core';
            __PACKAGE__->load_components('+My::Custom::Component');
        ",
    );
    let parents = fa.package_parents.get("MySchema::Result::User").unwrap();
    assert!(parents.contains(&"My::Custom::Component".to_string()));
}

#[test]
fn test_load_components_qw() {
    let fa = build_fa(
        "
            package MySchema::ResultSet::User;
            use base 'DBIx::Class::Core';
            __PACKAGE__->load_components(qw(Helper::ResultSet::Shortcut Helper::ResultSet::Me));
        ",
    );
    let parents = fa.package_parents.get("MySchema::ResultSet::User").unwrap();
    assert!(parents.contains(&"DBIx::Class::Helper::ResultSet::Shortcut".to_string()));
    assert!(parents.contains(&"DBIx::Class::Helper::ResultSet::Me".to_string()));
}

// ---- Inheritance method resolution tests ----

#[test]
fn test_inherited_method_completion() {
    let fa = build_fa(
        "
            package Animal;
            sub speak { }
            sub eat { }

            package Dog;
            use parent 'Animal';
            sub fetch { }
        ",
    );
    let methods = fa.complete_methods_for_class("Dog", None);
    let names: Vec<&str> = methods.iter().map(|c| c.label.as_str()).collect();
    assert!(names.contains(&"fetch"), "own method");
    assert!(names.contains(&"speak"), "inherited from Animal");
    assert!(names.contains(&"eat"), "inherited from Animal");
}

#[test]
fn test_child_method_overrides_parent() {
    let fa = build_fa(
        "
            package Base;
            sub greet { }

            package Override;
            use parent 'Base';
            sub greet { }
        ",
    );
    let methods = fa.complete_methods_for_class("Override", None);
    let greet_count = methods.iter().filter(|c| c.label == "greet").count();
    assert_eq!(greet_count, 1, "child override should shadow parent");
}

#[test]
fn test_find_method_in_parent() {
    let fa = build_fa(
        "
            package Base;
            sub base_method { }

            package Child;
            use parent 'Base';
        ",
    );
    let span = fa.find_method_in_class("Child", "base_method");
    assert!(span.is_some(), "should find inherited method");
}

#[test]
fn test_inherited_return_type() {
    let fa = build_fa(
        "
            package Factory;
            sub create { Factory->new(@_) }

            package SpecialFactory;
            use parent 'Factory';
        ",
    );
    let rt = fa.find_method_return_type("SpecialFactory", "create", None, None);
    assert!(rt.is_some(), "should find return type from parent");
}

#[test]
fn test_multi_level_inheritance() {
    let fa = build_fa(
        "
            package A;
            sub from_a { }

            package B;
            use parent 'A';
            sub from_b { }

            package C;
            use parent 'B';
            sub from_c { }
        ",
    );
    let methods = fa.complete_methods_for_class("C", None);
    let names: Vec<&str> = methods.iter().map(|c| c.label.as_str()).collect();
    assert!(names.contains(&"from_a"));
    assert!(names.contains(&"from_b"));
    assert!(names.contains(&"from_c"));
}

#[test]
fn test_class_isa_inherits_methods() {
    let fa = build_fa(
        "
            class Parent {
                method greet() { }
            }
            class Child :isa(Parent) {
                method wave() { }
            }
        ",
    );
    let methods = fa.complete_methods_for_class("Child", None);
    let names: Vec<&str> = methods.iter().map(|c| c.label.as_str()).collect();
    assert!(names.contains(&"wave"), "own method");
    assert!(names.contains(&"greet"), "inherited from Parent");
}

// ---- Cross-file inheritance tests ----

/// Build a CachedModule from a synthesized Perl source listing the given subs
/// (each as an `sub name { $self }` method) plus optional parent packages.
fn fake_cached_for_class(
    package_name: &str,
    path: &std::path::Path,
    subs: &[&str],
    parents: &[&str],
) -> std::sync::Arc<crate::module_index::CachedModule> {
    let mut source = format!("package {};\n", package_name);
    if !parents.is_empty() {
        source.push_str(&format!("use parent '{}';\n", parents.join("', '")));
    }
    for sub in subs {
        source.push_str(&format!("sub {} {{ my $self = shift; }}\n", sub));
    }
    source.push_str("1;\n");
    let fa = build_fa(&source);
    std::sync::Arc::new(crate::module_index::CachedModule::new(
        path.to_path_buf(),
        std::sync::Arc::new(fa),
    ))
}

#[test]
fn test_cross_file_inherited_method_completion() {
    use crate::module_index::ModuleIndex;
    use std::path::PathBuf;

    let idx = ModuleIndex::new_for_test();
    idx.set_workspace_root(None);

    // Grandparent: DBI has `connect`
    idx.insert_cache(
        "DBI",
        Some(fake_cached_for_class(
            "DBI",
            &PathBuf::from("/fake/DBI.pm"),
            &["connect"],
            &[],
        )),
    );

    // Parent: DBI::db inherits from DBI, has `prepare`
    idx.insert_cache(
        "DBI::db",
        Some(fake_cached_for_class(
            "DBI::db",
            &PathBuf::from("/fake/DBI/db.pm"),
            &["prepare"],
            &["DBI"],
        )),
    );

    // Local code inherits from DBI::db
    let fa = build_fa(
        "
            package MyDB;
            use parent 'DBI::db';
            sub custom_query { }
        ",
    );

    let methods = fa.complete_methods_for_class("MyDB", Some(&idx));
    let names: Vec<&str> = methods.iter().map(|c| c.label.as_str()).collect();
    assert!(names.contains(&"custom_query"), "own method");
    assert!(names.contains(&"prepare"), "from DBI::db");
    assert!(names.contains(&"connect"), "from DBI (grandparent)");
}

#[test]
fn test_cross_file_method_override() {
    use crate::module_index::ModuleIndex;
    use std::path::PathBuf;

    let idx = ModuleIndex::new_for_test();
    idx.set_workspace_root(None);

    // Parent has `process`
    idx.insert_cache(
        "Base::Worker",
        Some(fake_cached_for_class(
            "Base::Worker",
            &PathBuf::from("/fake/Base/Worker.pm"),
            &["process"],
            &[],
        )),
    );

    // Local child overrides `process`
    let fa = build_fa(
        "
            package MyWorker;
            use parent 'Base::Worker';
            sub process { }
        ",
    );

    let methods = fa.complete_methods_for_class("MyWorker", Some(&idx));
    let process_count = methods.iter().filter(|c| c.label == "process").count();
    assert_eq!(process_count, 1, "local override should shadow parent");
}

#[test]
fn test_cross_file_return_type_through_inheritance() {
    use crate::module_index::ModuleIndex;
    use std::path::PathBuf;

    let idx = ModuleIndex::new_for_test();
    idx.set_workspace_root(None);

    // Parent module whose `fetch` returns a hashref with known keys.
    let source = r#"
package Fetcher;
sub fetch {
    my $self = shift;
    return { status => 1, body => 'ok' };
}
1;
"#;
    let fa_parent = build_fa(source);
    idx.insert_cache(
        "Fetcher",
        Some(std::sync::Arc::new(crate::module_index::CachedModule::new(
            PathBuf::from("/fake/Fetcher.pm"),
            std::sync::Arc::new(fa_parent),
        ))),
    );

    let fa = build_fa(
        "
            package MyFetcher;
            use parent 'Fetcher';
        ",
    );

    let rt = fa.find_method_return_type("MyFetcher", "fetch", Some(&idx), None);
    assert!(rt.is_some_and(|t| t.is_hash_shaped()), "hash-shaped");
}

#[test]
fn test_parents_cached() {
    use crate::module_index::ModuleIndex;
    use std::path::PathBuf;

    let idx = ModuleIndex::new_for_test();
    idx.set_workspace_root(None);

    idx.insert_cache(
        "Child::Mod",
        Some(fake_cached_for_class(
            "Child::Mod",
            &PathBuf::from("/fake/Child/Mod.pm"),
            &[],
            &["Parent::Mod", "Mixin::Role"],
        )),
    );

    let parents = idx.parents_cached("Child::Mod");
    assert_eq!(parents, vec!["Parent::Mod", "Mixin::Role"]);
    assert!(idx.parents_cached("Unknown::Mod").is_empty());
}

#[test]
fn test_cross_bag_inheritance_cycle_does_not_overflow() {
    // A → B and B → A across separate cached bags. Each bag's
    // package_parents only knows the local-side edge of the loop,
    // so the cycle only closes once the inheritance fallback in
    // `query_rec` crosses bags. A per-bag-only visited set lets the
    // walk re-enter A's bag for `MethodOnClass{A, _}` after going
    // through B, then re-enter B for `MethodOnClass{B, _}`, ad
    // infinitum until the stack overflows. Visited must compose
    // (bag, attachment) so the loop closes.
    use crate::module_index::ModuleIndex;
    use std::path::PathBuf;

    let idx = ModuleIndex::new_for_test();
    idx.set_workspace_root(None);

    idx.insert_cache(
        "Cycle::A",
        Some(fake_cached_for_class(
            "Cycle::A",
            &PathBuf::from("/fake/Cycle/A.pm"),
            &[],
            &["Cycle::B"],
        )),
    );
    idx.insert_cache(
        "Cycle::B",
        Some(fake_cached_for_class(
            "Cycle::B",
            &PathBuf::from("/fake/Cycle/B.pm"),
            &[],
            &["Cycle::A"],
        )),
    );

    let fa = build_fa("package main; 1;");

    assert_eq!(
        fa.find_method_return_type("Cycle::A", "no_such_method", Some(&idx), None),
        None,
    );
    assert_eq!(
        fa.find_method_return_type("Cycle::B", "no_such_method", Some(&idx), None),
        None,
    );
}

// ---- Method call return type propagation tests ----

#[test]
fn test_method_call_return_type_propagates() {
    let fa = build_fa(
        "
package Foo;
sub new { bless {}, shift }
sub get_config {
    return { host => 'localhost', port => 5432 };
}
package main;
my $f = Foo->new();
my $cfg = $f->get_config();
$cfg;
",
    );
    let ty = fa.inferred_type_via_bag("$cfg", Point::new(9, 0));
    assert!(ty.is_some_and(|t| t.is_hash_shaped()), "hash-shaped");
}

#[test]
fn test_method_call_chain_propagation() {
    let fa = build_fa(
        "
package Foo;
sub new { bless {}, shift }
sub get_bar { return Bar->new() }
package Bar;
sub new { bless {}, shift }
sub get_name { return { name => 'test' } }
package main;
my $f = Foo->new();
my $bar = $f->get_bar();
my $name = $bar->get_name();
$name;
",
    );
    let bar_ty = fa.inferred_type_via_bag("$bar", Point::new(10, 0));
    assert_eq!(bar_ty, Some(InferredType::ClassName("Bar".into())));
    let name_ty = fa.inferred_type_via_bag("$name", Point::new(11, 0));
    assert!(name_ty.is_some_and(|t| t.is_hash_shaped()), "hash-shaped");
}

#[test]
fn test_self_method_call_return_type() {
    let fa = build_fa(
        "
package Foo;
sub new { bless {}, shift }
sub get_config { return { host => 1 } }
sub run {
    my ($self) = @_;
    my $cfg = $self->get_config();
    $cfg;
}
",
    );
    let ty = fa.inferred_type_via_bag("$cfg", Point::new(7, 4));
    assert!(ty.is_some_and(|t| t.is_hash_shaped()), "hash-shaped");
}

// ---- Framework accessor synthesis tests ----

#[test]
fn test_moo_has_ro() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'name' => (is => 'ro');
",
    );
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "name" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(methods.len(), 1, "should synthesize one getter");
    if let SymbolDetail::Sub {
        ref params,
        is_method,
        ..
    } = methods[0].detail
    {
        assert!(is_method);
        assert!(params.is_empty(), "ro getter has no params");
    }
}

#[test]
fn test_moo_has_rw() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'name' => (is => 'rw');
",
    );
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "name" && s.kind == SymKind::Method)
        .collect();
    // rw produces getter (0 params) + setter (1 param)
    assert_eq!(methods.len(), 2, "should synthesize getter + setter");
}

#[test]
fn test_moo_has_isa_type() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'count' => (is => 'ro', isa => 'Int');
",
    );
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "count" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(methods.len(), 1);
    let __r = fa.symbol_return_type_via_bag(methods[0].id, None);
    let return_type = __r.as_ref();
    if matches!(methods[0].detail, SymbolDetail::Sub { .. }) {
        assert_eq!(return_type, Some(&InferredType::Numeric));
    }
}

#[test]
fn test_moo_has_multiple_qw() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has [qw(foo bar)] => (is => 'ro');
",
    );
    let foo: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "foo" && s.kind == SymKind::Method)
        .collect();
    let bar: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "bar" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(foo.len(), 1, "should synthesize foo accessor");
    assert_eq!(bar.len(), 1, "should synthesize bar accessor");
}

#[test]
fn test_moo_has_bare_no_accessor() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'internal' => (is => 'bare');
",
    );
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "internal" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(methods.len(), 0, "bare should not synthesize accessor");
}

#[test]
fn test_moo_no_accessor_without_is() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'internal';
",
    );
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "internal" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(methods.len(), 0, "no `is` should not synthesize accessor");
}

#[test]
fn test_moose_has_classname_isa() {
    let fa = build_fa(
        "
package Foo;
use Moose;
has 'db' => (is => 'ro', isa => 'DBI::db');
",
    );
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "db" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(methods.len(), 1);
    let __r = fa.symbol_return_type_via_bag(methods[0].id, None);
    let return_type = __r.as_ref();
    if matches!(methods[0].detail, SymbolDetail::Sub { .. }) {
        assert_eq!(
            return_type,
            Some(&InferredType::ClassName("DBI::db".into()))
        );
    }
}

#[test]
fn test_moo_has_instanceof() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'logger' => (is => 'ro', isa => \"InstanceOf['Log::Any']\");
",
    );
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "logger" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(methods.len(), 1);
    let __r = fa.symbol_return_type_via_bag(methods[0].id, None);
    let return_type = __r.as_ref();
    if matches!(methods[0].detail, SymbolDetail::Sub { .. }) {
        assert_eq!(
            return_type,
            Some(&InferredType::ClassName("Log::Any".into()))
        );
    }
}

#[test]
fn test_moo_has_rwp() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'status' => (is => 'rwp');
",
    );
    let getter: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "status" && s.kind == SymKind::Method)
        .collect();
    let writer: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "_set_status" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(getter.len(), 1, "rwp should synthesize getter");
    assert_eq!(writer.len(), 1, "rwp should synthesize _set_name writer");
}

#[test]
fn test_moo_has_accessor_keyword() {
    // `accessor => 'get_set_x'` synthesizes a combined read/write method named
    // `get_set_x` — distinct from the attr-named default accessor.
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'x' => (is => 'rw', accessor => 'get_set_x');
",
    );
    let acc: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "get_set_x" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(acc.len(), 1, "accessor keyword should synthesize get_set_x method");
    // The default attr-named accessor ('x') still exists from `is => 'rw'`.
    let default_acc: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "x" && s.kind == SymKind::Method)
        .collect();
    assert!(!default_acc.is_empty(), "default attr accessor still synthesized");
}

#[test]
fn test_moo_has_ro_does_not_synthesize_ro_symbol() {
    // `is => 'ro'` must NOT synthesize a method named `ro` — the gate that
    // fixes the phantom-`ro` regression (names_a_method excludes `is`).
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'y' => (is => 'ro');
",
    );
    let ro_sym: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "ro")
        .collect();
    assert!(ro_sym.is_empty(), "`is => 'ro'` must not mint a symbol named `ro`");
}

#[test]
fn test_mojo_has_basic() {
    let fa = build_fa(
        "
package Foo;
use Mojo::Base -base;
has 'name';
",
    );
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "name" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(methods.len(), 2, "Mojo::Base synthesizes getter + setter");
    // Getter: no params, no return type
    let getter = methods
        .iter()
        .find(|m| {
            if let SymbolDetail::Sub { ref params, .. } = m.detail {
                params.is_empty()
            } else {
                false
            }
        })
        .expect("should have getter");
    let __r = fa.symbol_return_type_via_bag(getter.id, None);
    let return_type = __r.as_ref();
    if let SymbolDetail::Sub { is_method, .. } = getter.detail {
        assert!(is_method);
        assert!(return_type.is_none(), "getter has no return type");
    }
    // Setter: 1 param, fluent return
    let setter = methods
        .iter()
        .find(|m| {
            if let SymbolDetail::Sub { ref params, .. } = m.detail {
                params.len() == 1
            } else {
                false
            }
        })
        .expect("should have setter");
    let __r = fa.symbol_return_type_via_bag(setter.id, None);
    let return_type = __r.as_ref();
    if let SymbolDetail::Sub { is_method, .. } = setter.detail {
        assert!(is_method);
        assert_eq!(
            return_type,
            Some(&InferredType::ClassName("Foo".into()))
        );
    }
}

/// Regression test for QA finding B1 (export-attribution; the sweep history):
/// Mojo::Base writer accessors lost their fluent invocant return type
/// when queried through the bag at arity=1. The QA dump for
/// `Mojo::Log::level` showed:
///
///   getter (params=0): raw=String,    bag=String     ← OK
///   writer (params=1): raw=Mojo::Log, bag=String     ← BUG, getter's type
///
/// `query_sub_return_type` finds the *first* same-named symbol by name
/// (the getter, since synthesis adds it first), folds witnesses on that
/// id, and answers from the getter's stored `return_type`. The writer's
/// distinct fluent type was never visible at the bag level — every
/// `$ua->ca($f)->cert(...)` chain lost its receiver type at the second
/// hop.
///
/// Fix: framework synthesis publishes `ReturnExpr::UnionOnArgs`
/// arms on `Symbol(sym_id)` (per-symbol arity arm) and a multi-arm
/// `UnionOnArgs` on `MethodOnClass{class, name}` (cross-symbol arity
/// dispatch scoped to the declaring class). `ReturnExprReducer`
/// dispatches `q.arity_hint` against the union's `ArgGuard` branches
/// regardless of which sister sym `find()` returned. See
/// `docs/adr/return-expr.md`.
#[test]
fn test_mojo_base_writer_returns_invocant_via_bag() {
    use crate::file_analysis::TypeProvenance;

    let fa = build_fa(
        "
package MyLog;
use Mojo::Base -base;

has level => 'info';   # default value gives getter type = String
has app;               # no default; getter has no return type
",
    );

    // arity=1 → fluent writer must return the package class for chaining.
    // Pre-fix this returned String (the getter's type) — that's the bug.
    assert_eq!(
        fa.sub_return_type_at_arity("level", Some(1)),
        Some(InferredType::ClassName("MyLog".into())),
        "Mojo::Base writer at arity=1 must return the invocant class for fluent chaining"
    );
    assert_eq!(
        fa.sub_return_type_at_arity("app", Some(1)),
        Some(InferredType::ClassName("MyLog".into())),
        "Mojo::Base writer with no default still returns the invocant class"
    );

    // arity=0 → getter returns its scalar accessor type.
    assert_eq!(
        fa.sub_return_type_at_arity("level", Some(0)),
        Some(InferredType::String),
        "Mojo::Base getter at arity=0 returns the default-value type"
    );

    // Both sister symbols carry per-symbol witnesses now (was 0 across
    // every Mojo::* dump in the QA sweep).
    let getter = fa
        .symbols
        .iter()
        .find(|s| s.name == "level" && matches!(&s.detail, SymbolDetail::Sub { params, .. } if params.is_empty()))
        .expect("getter symbol");
    let writer = fa
        .symbols
        .iter()
        .find(|s| s.name == "level" && matches!(&s.detail, SymbolDetail::Sub { params, .. } if params.len() == 1))
        .expect("writer symbol");
    let getter_witnesses = fa
        .witnesses
        .for_attachment(&crate::witnesses::WitnessAttachment::Symbol(getter.id))
        .len();
    let writer_witnesses = fa
        .witnesses
        .for_attachment(&crate::witnesses::WitnessAttachment::Symbol(writer.id))
        .len();
    assert!(getter_witnesses > 0, "getter must have at least one bag witness");
    assert!(writer_witnesses > 0, "writer must have at least one bag witness");

    // Provenance: each accessor flushes a FrameworkSynthesis entry, not
    // PluginOverride (Mojo::Base synthesis is core, not a plugin).
    match fa.return_type_provenance(writer.id) {
        TypeProvenance::FrameworkSynthesis { framework, reason } => {
            assert_eq!(framework, "Mojo::Base");
            assert!(reason.contains("level"), "reason names the attribute");
            assert!(
                reason.contains("fluent") || reason.contains("writer"),
                "reason describes the writer role"
            );
        }
        other => panic!("writer provenance must be FrameworkSynthesis, got {other:?}"),
    }
    match fa.return_type_provenance(getter.id) {
        TypeProvenance::FrameworkSynthesis { framework, .. } => {
            assert_eq!(framework, "Mojo::Base");
        }
        other => panic!("getter provenance must be FrameworkSynthesis, got {other:?}"),
    }
}

/// Mirror of B1 for Moo `is => 'rw'` writers — same shape, isa-typed
/// rather than fluent. The writer reads back the isa type at arity=1.
#[test]
fn test_moo_rw_writer_returns_isa_type_via_bag() {
    use crate::file_analysis::TypeProvenance;

    let fa = build_fa(
        "
package Thing;
use Moo;
has size => (is => 'rw', isa => 'Int');
",
    );

    // Both arities resolve to the isa-derived type.
    assert_eq!(
        fa.sub_return_type_at_arity("size", Some(0)),
        Some(InferredType::Numeric),
        "Moo getter returns isa type"
    );
    assert_eq!(
        fa.sub_return_type_at_arity("size", Some(1)),
        Some(InferredType::Numeric),
        "Moo rw writer returns isa type"
    );

    let writer = fa
        .symbols
        .iter()
        .find(|s| s.name == "size" && matches!(&s.detail, SymbolDetail::Sub { params, .. } if params.len() == 1))
        .expect("writer symbol");
    match fa.return_type_provenance(writer.id) {
        TypeProvenance::FrameworkSynthesis { framework, .. } => {
            assert_eq!(framework, "Moo");
        }
        other => panic!("Moo writer provenance must be FrameworkSynthesis, got {other:?}"),
    }
}

#[test]
fn test_mojo_base_parent_inheritance() {
    let fa = build_fa(
        "
package MyApp;
use Mojo::Base 'Mojolicious';
has 'config';
",
    );
    // Should register parent
    assert_eq!(
        fa.package_parents.get("MyApp").map(|v| v.as_slice()),
        Some(["Mojolicious".to_string()].as_slice())
    );
    // Should synthesize getter + setter accessors
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "config" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(methods.len(), 2, "Mojo::Base synthesizes getter + setter");
}

#[test]
fn test_mojo_base_strict_no_accessor() {
    let fa = build_fa(
        "
package Foo;
use Mojo::Base -strict;
has 'name';
",
    );
    // -strict means no framework mode, has is just a regular function
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "name" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(
        methods.len(),
        0,
        "-strict should not trigger accessor synthesis"
    );
}

#[test]
fn test_no_accessor_without_framework() {
    let fa = build_fa(
        "
package Foo;
has 'name' => (is => 'ro');
",
    );
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "name" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(methods.len(), 0, "no framework = no accessor synthesis");
}

#[test]
fn test_dbic_add_columns() {
    let fa = build_fa(
        "
package Schema::Result::User;
use base 'DBIx::Class::Core';
__PACKAGE__->add_columns(
    id    => { data_type => 'integer' },
    name  => { data_type => 'varchar' },
    email => { data_type => 'varchar' },
);
",
    );
    let id: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "id" && s.kind == SymKind::Method)
        .collect();
    let name: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "name" && s.kind == SymKind::Method)
        .collect();
    let email: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "email" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(id.len(), 1, "should synthesize id accessor");
    assert_eq!(name.len(), 1, "should synthesize name accessor");
    assert_eq!(email.len(), 1, "should synthesize email accessor");
}

#[test]
fn test_dbic_has_many() {
    let fa = build_fa(
        "
package Schema::Result::Post;
use base 'DBIx::Class::Core';
__PACKAGE__->has_many(comments => 'Schema::Result::Comment', 'post_id');
",
    );
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "comments" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(methods.len(), 1);
    let __r = fa.symbol_return_type_via_bag(methods[0].id, None);
    let return_type = __r.as_ref();
    if matches!(methods[0].detail, SymbolDetail::Sub { .. }) {
        assert_eq!(
            return_type,
            Some(&InferredType::ClassName("DBIx::Class::ResultSet".into()))
        );
    }
}

#[test]
fn test_dbic_belongs_to() {
    let fa = build_fa(
        "
package Schema::Result::Comment;
use base 'DBIx::Class::Core';
__PACKAGE__->belongs_to(author => 'Schema::Result::User', 'author_id');
",
    );
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "author" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(methods.len(), 1);
    let __r = fa.symbol_return_type_via_bag(methods[0].id, None);
    let return_type = __r.as_ref();
    if matches!(methods[0].detail, SymbolDetail::Sub { .. }) {
        assert_eq!(
            return_type,
            Some(&InferredType::ClassName("Schema::Result::User".into()))
        );
    }
}

#[test]
fn test_dbic_instance_add_columns_does_not_synthesize() {
    // A runtime `$rs->add_columns('x','y')` (dynamic query building, e.g. crm's
    // ResultSet joins) is NOT a class declaration — the dbic plugin gates on
    // `receiver_is_package`, so no column accessors are minted from it. Only
    // `__PACKAGE__->add_columns` (class-level) declares columns.
    let fa = build_fa(
        "
package My::RS;
use base 'DBIx::Class::ResultSet';
__PACKAGE__->add_columns('decl_col');
sub widen {
    my $self = shift;
    $self->add_columns('runtime_col');
}
",
    );
    let decl: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "decl_col" && s.kind == SymKind::Method)
        .collect();
    let runtime: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "runtime_col" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(decl.len(), 1, "class-level __PACKAGE__->add_columns declares");
    assert_eq!(
        runtime.len(),
        0,
        "instance $rs->add_columns is a runtime op, not a declaration"
    );
}

#[test]
fn test_accessor_return_type_propagation() {
    let src = r#"
package Moo::Config;
use Moo;
has 'host' => (is => 'ro', isa => 'Str');
sub dsn { my ($self) = @_; return "x"; }

package Moo::Service;
use Moo;
has 'config' => (is => 'ro', isa => "InstanceOf['Moo::Config']");
sub run {
    my ($self) = @_;
    my $cfg = $self->config;
    my $dsn = $cfg->dsn;
}
"#;
    let fa = build_fa(src);

    // Verify the config accessor has the right return type
    let config_methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "config" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(config_methods.len(), 1, "should have 1 config accessor");
    assert_eq!(config_methods[0].package.as_deref(), Some("Moo::Service"));
    let __r = fa.symbol_return_type_via_bag(config_methods[0].id, None);
    let return_type = __r.as_ref();
    if matches!(config_methods[0].detail, SymbolDetail::Sub { .. }) {
        assert_eq!(
            return_type,
            Some(&InferredType::ClassName("Moo::Config".into())),
            "config accessor should return Moo::Config"
        );
    }

    // Verify method call binding exists (not a function call binding)
    let cfg_binding = fa
        .method_call_bindings
        .iter()
        .find(|b| b.variable == "$cfg");
    assert!(
        cfg_binding.is_some(),
        "should have method call binding for $cfg"
    );
    assert!(
        fa.call_bindings
            .iter()
            .find(|b| b.variable == "$cfg")
            .is_none(),
        "$cfg should NOT be a function call binding"
    );

    // Verify $cfg gets Moo::Config type (not Moo::Service)
    let cfg_type = fa.inferred_type_via_bag("$cfg", tree_sitter::Point::new(13, 0));
    assert_eq!(
        cfg_type,
        Some(InferredType::ClassName("Moo::Config".into())),
        "$cfg should be Moo::Config, not Moo::Service"
    );

    // Verify chained resolution: $dsn = $cfg->dsn → String
    let dsn_binding = fa
        .method_call_bindings
        .iter()
        .find(|b| b.variable == "$dsn");
    assert!(
        dsn_binding.is_some(),
        "should have method call binding for $dsn"
    );
}

#[test]
fn test_mojo_getter_setter_distinct() {
    let fa = build_fa(
        "
package Foo;
use Mojo::Base -base;
has 'name';
",
    );
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "name" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(methods.len(), 2, "should synthesize getter + setter");

    let getter = methods.iter().find(|m| {
        if let SymbolDetail::Sub { ref params, .. } = m.detail {
            params.is_empty()
        } else {
            false
        }
    });
    let setter = methods.iter().find(|m| {
        if let SymbolDetail::Sub { ref params, .. } = m.detail {
            params.len() == 1
        } else {
            false
        }
    });
    assert!(getter.is_some(), "should have a 0-param getter");
    assert!(setter.is_some(), "should have a 1-param setter");

    // Getter: no return type (inferable from usage)
    let __r = fa.symbol_return_type_via_bag(getter.unwrap().id, None);
    let return_type = __r.as_ref();
    if let SymbolDetail::Sub { .. } = getter.unwrap().detail {
        assert!(return_type.is_none());
    }
    // Setter: fluent return
    let __r = fa.symbol_return_type_via_bag(setter.unwrap().id, None);
    let return_type = __r.as_ref();
    if let SymbolDetail::Sub { .. } = setter.unwrap().detail {
        assert_eq!(
            return_type,
            Some(&InferredType::ClassName("Foo".into()))
        );
    }
}

#[test]
fn test_mojo_fluent_chain_resolves() {
    let src = "
package Foo;
use Mojo::Base -base;
has 'name';
has 'age';
sub greet {
    my ($self) = @_;
    my $result = $self->name('Bob')->age;
    return $result;
}
";
    let fa = build_fa(src);
    // $self->name('Bob') has args → setter → returns Foo
    // ->age has no args → getter → returns None (unknown)
    // The chain should resolve: name('Bob') returns Foo, ->age is valid on Foo
    let method_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "age" && matches!(r.kind, RefKind::MethodCall { .. }))
        .collect();
    assert!(
        !method_refs.is_empty(),
        "should have method call ref for 'age'"
    );
}

#[test]
fn test_moo_rw_arity_resolution() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'name' => (is => 'rw', isa => 'Str');
",
    );
    // Moo rw: both getter and setter have same return type (Str)
    // With arity, both 0 and 1 should return String since both symbols have the same type
    let rt_getter = fa.find_method_return_type("Foo", "name", None, Some(0));
    assert_eq!(rt_getter, Some(InferredType::String));
    let rt_setter = fa.find_method_return_type("Foo", "name", None, Some(1));
    assert_eq!(rt_setter, Some(InferredType::String));
    let rt_default = fa.find_method_return_type("Foo", "name", None, None);
    assert_eq!(rt_default, Some(InferredType::String));
}

/// Regression guard for bag-residual D1: same-named methods on
/// unrelated classes must resolve to their own per-class types, no
/// matter what name-keyed cache or "latest-wins" witness landed last.
///
/// Two unrelated classes (`Sweet`, `Sour`) ship a method `flavor` via
/// Mojo::Base `has`, with different defaults. Class-keyed dispatch is
/// required to disambiguate them — any code path that resolves
/// methods by name alone (a `return_types: HashMap<String, _>` mirror,
/// or the now-deleted `WitnessAttachment::NamedSub(name)` shape)
/// will silently shadow one class's getter with the other's whenever
/// the second declaration overwrites the first.
///
/// The arity=1 (fluent writer) assertions extend the same guarantee
/// to overload dispatch: `Sweet`'s writer returns `Sweet`, `Sour`'s
/// returns `Sour`, even though both subs share the name `flavor`.
///
/// D1 (lifted from the abandoned `refactor/bag-residual-d1-method-on-class`
/// branch — see commit c322178 for the original attempt). The redo
/// must keep this test passing while routing every method-type query
/// through the bag.
#[test]
fn method_on_class_disambiguates_same_name_across_classes() {
    let fa = build_fa(
        "
package Sweet;
use Mojo::Base -base;
has flavor => 'caramel';

package Sour;
use Mojo::Base -base;
has flavor => sub { [1, 2, 3] };
",
    );
    let sweet_getter_sym = fa
        .symbols
        .iter()
        .find(|s| {
            s.name == "flavor"
                && s.package.as_deref() == Some("Sweet")
                && matches!(&s.detail, SymbolDetail::Sub { params, .. } if params.is_empty())
        })
        .map(|s| s.id);
    let sour_getter_sym = fa
        .symbols
        .iter()
        .find(|s| {
            s.name == "flavor"
                && s.package.as_deref() == Some("Sour")
                && matches!(&s.detail, SymbolDetail::Sub { params, .. } if params.is_empty())
        })
        .map(|s| s.id);
    assert!(sweet_getter_sym.is_some(), "Sweet getter sym must exist");
    assert!(sour_getter_sym.is_some(), "Sour getter sym must exist");
    assert_ne!(sweet_getter_sym, sour_getter_sym);

    assert_eq!(
        fa.find_method_return_type("Sweet", "flavor", None, Some(0)),
        Some(InferredType::String),
        "Sweet::flavor getter returns String (from 'caramel' default), \
         not Sour's ArrayRef"
    );
    assert!(
        fa.find_method_return_type("Sour", "flavor", None, Some(0)).is_some_and(|t| t.is_array_shaped()),
        "Sour::flavor getter returns ArrayRef (from sub-returning-array \
         default), not Sweet's String",
    );
    assert_eq!(
        fa.find_method_return_type("Sweet", "flavor", None, Some(1)),
        Some(InferredType::ClassName("Sweet".into())),
    );
    assert_eq!(
        fa.find_method_return_type("Sour", "flavor", None, Some(1)),
        Some(InferredType::ClassName("Sour".into())),
    );
}

/// Regression for the DFS-MRO order fix in
/// `for_each_ancestor_class`. Perl's default MRO is left-to-right
/// depth-first: for `@ISA = (A, B)` where A and B both define `m`,
/// `C->m` resolves to A's. Pre-fix, the stack-based walker pushed
/// parents left-to-right and `pop()`'d, traversing in REVERSE
/// `@ISA` order — so B::m silently won. The fix pushes parents in
/// reverse order so LIFO pops them in `@ISA` order.
#[test]
fn for_each_ancestor_class_walks_left_to_right_isa_order() {
    let fa = build_fa(
        "
package A;
sub m { return 'a' }
package B;
sub m { return 1 }
package C;
our @ISA = ('A', 'B');
",
    );
    // A::m returns String ('a'), B::m returns Numeric (1).
    // C->m must resolve to A's String — A is first in @ISA.
    assert_eq!(
        fa.find_method_return_type("C", "m", None, None),
        Some(InferredType::String),
        "C->m must walk @ISA left-to-right and pick A::m, not B::m"
    );
}

#[test]
fn test_mojo_arity_resolution() {
    let fa = build_fa(
        "
package Bar;
use Mojo::Base -base;
has 'title';
",
    );
    // Getter (0 args): no return type
    let rt_getter = fa.find_method_return_type("Bar", "title", None, Some(0));
    assert!(rt_getter.is_none(), "getter should have no return type");
    // Setter (1 arg): fluent return (ClassName)
    let rt_setter = fa.find_method_return_type("Bar", "title", None, Some(1));
    assert_eq!(rt_setter, Some(InferredType::ClassName("Bar".into())));
    // Default (None): getter (primary, first symbol)
    let rt_default = fa.find_method_return_type("Bar", "title", None, None);
    assert!(rt_default.is_none(), "default should return getter type");
}

#[test]
fn test_mojo_default_string_infers_type() {
    let fa = build_fa(
        "
package App;
use Mojo::Base -base;
has name => 'default';
",
    );
    let rt = fa.find_method_return_type("App", "name", None, Some(0));
    assert_eq!(
        rt,
        Some(InferredType::String),
        "string default → String getter"
    );
}

#[test]
fn test_mojo_default_arrayref_infers_type() {
    let fa = build_fa(
        "
package App;
use Mojo::Base -base;
has items => sub { [] };
",
    );
    let rt = fa.find_method_return_type("App", "items", None, Some(0));
    assert!(
        rt.is_some_and(|t| t.is_array_shaped()),
        "sub {{ [] }} default → ArrayRef getter",
    );
}

#[test]
fn test_mojo_default_hashref_infers_type() {
    let fa = build_fa(
        "
package App;
use Mojo::Base -base;
has config => sub { {} };
",
    );
    let rt = fa.find_method_return_type("App", "config", None, Some(0));
    assert!(
        rt.is_some_and(|t| t.is_hash_shaped()),
        "sub {{{{ }}}} default → HashRef getter",
    );
}

#[test]
fn test_mojo_default_constructor_infers_type() {
    let fa = build_fa(
        "
package App;
use Mojo::Base -base;
has ua => sub { Mojo::UserAgent->new };
",
    );
    let rt = fa.find_method_return_type("App", "ua", None, Some(0));
    assert_eq!(
        rt,
        Some(InferredType::ClassName("Mojo::UserAgent".into())),
        "sub {{ Foo->new }} default → ClassName getter"
    );
}

#[test]
fn test_mojo_default_number_infers_type() {
    let fa = build_fa(
        "
package App;
use Mojo::Base -base;
has timeout => 30;
",
    );
    let rt = fa.find_method_return_type("App", "timeout", None, Some(0));
    assert_eq!(
        rt,
        Some(InferredType::Numeric),
        "number default → Numeric getter"
    );
}

#[test]
fn test_mojo_default_no_value_no_type() {
    let fa = build_fa(
        "
package App;
use Mojo::Base -base;
has 'name';
",
    );
    let rt = fa.find_method_return_type("App", "name", None, Some(0));
    assert!(rt.is_none(), "no default → no getter type");
}

// ---- Constant folding + export extraction tests ----

#[test]
fn test_builder_extracts_exports_qw() {
    let fa = build_fa(
        "
package Foo;
use Exporter 'import';
our @EXPORT = qw(delta);
our @EXPORT_OK = qw(alpha beta gamma);
",
    );
    assert_eq!(fa.export, vec!["delta"]);
    assert_eq!(fa.export_ok, vec!["alpha", "beta", "gamma"]);
}

#[test]
fn test_builder_extracts_exports_paren() {
    let fa = build_fa(
        "
package Bar;
our @EXPORT_OK = ('foo', 'bar', 'baz');
",
    );
    assert_eq!(fa.export_ok, vec!["foo", "bar", "baz"]);
}

#[test]
fn test_push_exports() {
    let fa = build_fa(
        "
package Foo;
use Exporter 'import';
our @EXPORT_OK = qw(foo);
push @EXPORT_OK, 'bar', 'baz';
",
    );
    assert_eq!(fa.export_ok, vec!["foo", "bar", "baz"]);
}

#[test]
fn test_exporter_extensible_export_call() {
    // `export(qw( foo $bar @baz -tag ))` — only the plain sub name `foo`
    // is recorded; sigil'd vars and `-tag` group names are skipped.
    let fa = build_fa(
        "
package My::Ext;
use Exporter::Extensible -exporter_setup => 1;
export(qw( foo $bar @baz -tag ));
sub foo { 1 }
",
    );
    assert_eq!(fa.export_ok, vec!["foo"]);
}

#[test]
fn test_exporter_extensible_attribute() {
    // `sub foo :Export(...)` / `sub bar :Export` — the sub name is the export.
    let fa = build_fa(
        "
package My::Ext;
use Exporter::Extensible -exporter_setup => 1;
sub foo : Export(-tag) { 1 }
sub bar :Export { 2 }
sub plain { 3 }
",
    );
    assert!(fa.export_ok.contains(&"foo".to_string()));
    assert!(fa.export_ok.contains(&"bar".to_string()));
    assert!(!fa.export_ok.contains(&"plain".to_string()));
}

#[test]
fn test_exporter_declare_export_pair() {
    // `default_export NAME => sub {}` / `export NAME => sub {}` / `exports qw/../`.
    let fa = build_fa(
        "
package My::Decl;
use Exporter::Declare;
default_export foo => sub { 1 };
export bar => sub { 2 };
exports qw/a b/;
",
    );
    assert!(fa.export_ok.contains(&"foo".to_string()));
    assert!(fa.export_ok.contains(&"bar".to_string()));
    assert!(fa.export_ok.contains(&"a".to_string()));
    assert!(fa.export_ok.contains(&"b".to_string()));
}

#[test]
fn test_exporter_call_gated_on_use() {
    // False-positive guard: a `sub export {}` (or a stray `export(...)`)
    // in a package that didn't `use` an exporter-declare family module
    // must NOT register exports.
    let fa = build_fa(
        "
package Plain;
sub export { 1 }
export('not_an_export');
",
    );
    assert!(fa.export_ok.is_empty());
}

/// Gate 5: `find_sub_for_call` (resolution path) must check `export_ok`, not
/// just `export`. A name that Foo records only in `@EXPORT_OK` suppresses the
/// diagnostic in symbols.rs (already checks both), but before this fix
/// `signature_for_call` / goto-def would fall through because the resolution
/// path only tested `export`. Now both lists are checked.
#[test]
fn test_export_ok_resolves_cross_file() {
    use crate::module_index::ModuleIndex;
    use std::path::PathBuf;

    // Build a module that exports `fetch_data` via @EXPORT_OK only.
    let provider_fa = build_fa(
        "package Data::Fetcher;\nour @EXPORT_OK = qw(fetch_data);\nsub fetch_data { my ($url) = @_; }\n1;\n",
    );
    assert!(
        provider_fa.export_ok.contains(&"fetch_data".to_string()),
        "provider must record fetch_data in export_ok",
    );

    let idx = ModuleIndex::new_for_test();
    idx.set_workspace_root(None);
    idx.insert_cache(
        "Data::Fetcher",
        Some(std::sync::Arc::new(crate::module_index::CachedModule::new(
            PathBuf::from("/fake/Data/Fetcher.pm"),
            std::sync::Arc::new(provider_fa),
        ))),
    );

    // Consumer: bare `use Data::Fetcher;` — calls `fetch_data(...)`.
    let consumer_fa = build_fa(
        "package My::App;\nuse Data::Fetcher;\nfetch_data('http://example.com');\n",
    );

    // signature_for_call exercises find_sub_for_call → bare-import path.
    let sig = consumer_fa.signature_for_call(
        "fetch_data",
        false,
        None,
        tree_sitter::Point::new(2, 0),
        Some(&idx),
    );
    assert!(
        sig.is_some(),
        "signature_for_call must resolve fetch_data via @EXPORT_OK, got None",
    );
}

#[test]
fn test_importer_consumer_retargets_source() {
    // `use Importer 'M' => qw/foo bar/` imports foo/bar FROM M. The Import
    // entry must point at M, not Importer, so goto-def crosses to M's subs.
    let fa = build_fa(
        "
package My::Consumer;
use Importer 'Some::Module' => qw/foo bar/;
",
    );
    let imp = fa
        .imports
        .iter()
        .find(|i| i.module_name == "Some::Module")
        .expect("Import re-targeted to Some::Module");
    let names: Vec<&str> = imp
        .imported_symbols
        .iter()
        .map(|s| s.local_name.as_str())
        .collect();
    assert!(names.contains(&"foo"));
    assert!(names.contains(&"bar"));
    // No Import should pin to Importer itself.
    assert!(fa.imports.iter().all(|i| i.module_name != "Importer"));
}

#[test]
fn test_importer_menu_advertised_names() {
    // IMPORTER_MENU advertises export lists; pull the `export`/`export_ok`
    // name arrays. `export_anon` (name → coderef) is unmodeled.
    let fa = build_fa(
        "
package My::Menu;
sub IMPORTER_MENU {
  return (
    export => [qw/foo bar/],
    export_ok => ['baz'],
    export_anon => { quux => sub { 1 } },
  );
}
sub foo { 1 }
",
    );
    assert!(fa.export_ok.contains(&"foo".to_string()));
    assert!(fa.export_ok.contains(&"bar".to_string()));
    assert!(fa.export_ok.contains(&"baz".to_string()));
    assert!(!fa.export_ok.contains(&"quux".to_string()));
}

#[test]
fn test_use_constant_string() {
    let fa = build_fa(
        "
package Foo;
use constant NAME => 'hello';
use parent NAME;
",
    );
    assert_eq!(
        fa.package_parents.get("Foo").unwrap(),
        &vec!["hello".to_string()]
    );
}

#[test]
fn test_constant_array_our() {
    let fa = build_fa(
        "
our @THINGS = qw(a b);
our @EXPORT_OK = (@THINGS, 'c');
",
    );
    assert_eq!(fa.export_ok, vec!["a", "b", "c"]);
}

#[test]
fn test_constant_array_my() {
    let fa = build_fa(
        "
my @THINGS = qw(a b);
our @EXPORT_OK = (@THINGS, 'c');
",
    );
    assert_eq!(fa.export_ok, vec!["a", "b", "c"]);
}

#[test]
fn test_constant_array_in_exports() {
    let fa = build_fa(
        "
package Foo;
use Exporter 'import';
my @COMMON = qw(alpha beta);
our @EXPORT_OK = (@COMMON, 'gamma');
",
    );
    assert_eq!(fa.export_ok, vec!["alpha", "beta", "gamma"]);
}

#[test]
fn test_recursive_constant_resolution() {
    let fa = build_fa(
        "
package Foo;
use Exporter 'import';
use constant BASE => qw(a b);
use constant ALL => (BASE, 'c');
our @EXPORT_OK = (ALL);
",
    );
    assert_eq!(fa.export_ok, vec!["a", "b", "c"]);
}

#[test]
fn test_glob_export_literal_name() {
    // Data::Printer pattern: *{"${caller}::np"} = \&np
    let fa = build_fa(
        r#"
package Data::Printer;
sub np { }
sub p { }
sub import {
    my $class = shift;
    my $caller = caller;
    { no strict 'refs';
        *{"${caller}::p"} = \&p;
        *{"${caller}::np"} = \&np;
    }
}
"#,
    );
    assert!(
        fa.export.contains(&"p".to_string()),
        "should detect p export: {:?}",
        fa.export
    );
    assert!(
        fa.export.contains(&"np".to_string()),
        "should detect np export: {:?}",
        fa.export
    );
}

#[test]
fn test_glob_export_variable_name() {
    // Aliased export: my $imported = 'p'; *{"$caller\::$imported"} = \&p
    let fa = build_fa(
        r#"
package Data::Printer;
sub p { }
sub import {
    my $class = shift;
    my $caller = caller;
    my $imported = 'dump_it';
    { no strict 'refs';
        *{"$caller\::$imported"} = \&p;
    }
}
"#,
    );
    assert!(
        fa.export.contains(&"dump_it".to_string()),
        "should resolve aliased export: {:?}",
        fa.export
    );
}

#[test]
fn test_glob_export_loop_pattern() {
    // Try::Tiny pattern: loop over qw list
    let fa = build_fa(
        r#"
package Try::Tiny;
sub try { }
sub catch { }
sub finally { }
sub import {
    my $class = shift;
    my $caller = caller;
    for my $name (qw(try catch finally)) {
        no strict 'refs';
        *{"${caller}::${name}"} = \&$name;
    }
}
"#,
    );
    assert!(
        fa.export.contains(&"try".to_string()),
        "should detect try: {:?}",
        fa.export
    );
    assert!(
        fa.export.contains(&"catch".to_string()),
        "should detect catch: {:?}",
        fa.export
    );
    assert!(
        fa.export.contains(&"finally".to_string()),
        "should detect finally: {:?}",
        fa.export
    );
}

#[test]
fn test_glob_export_fallback_to_rhs() {
    // When glob name is fully dynamic, fall back to \&name on RHS
    let fa = build_fa(
        r#"
package Foo;
sub bar { }
sub import {
    my $caller = caller;
    *{$caller . '::bar'} = \&bar;
}
"#,
    );
    assert!(
        fa.export.contains(&"bar".to_string()),
        "should fall back to RHS name: {:?}",
        fa.export
    );
}

#[test]
fn test_glob_export_only_inside_import() {
    // Glob assigns outside sub import should NOT populate exports
    let fa = build_fa(
        r#"
package Foo;
sub setup {
    my $caller = caller;
    *{"${caller}::thing"} = \&thing;
}
"#,
    );
    assert!(
        fa.export.is_empty(),
        "should not export from non-import sub: {:?}",
        fa.export
    );
}

#[test]
fn test_mojo_has_accessor_writer_hidden_from_outline() {
    // Mojo `has 'x'` synthesizes a getter + a same-named fluent writer (for
    // arity-1 return typing). Only ONE should show in the outline; the writer
    // carries hide_in_outline so it doesn't duplicate the getter.
    let fa = build_fa("package Msg;\nuse Mojo::Base -base;\nhas 'content';\n");
    let visible: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "content" && s.kind == SymKind::Method)
        .filter(|s| !matches!(&s.detail, SymbolDetail::Sub { hide_in_outline: true, .. }))
        .collect();
    assert_eq!(
        visible.len(),
        1,
        "exactly one visible `content` accessor expected, got {}",
        visible.len()
    );
    // Both symbols still exist (writer hidden, not deleted) for arity typing.
    let total = fa.symbols.iter().filter(|s| s.name == "content" && s.kind == SymKind::Method).count();
    assert_eq!(total, 2, "getter + (hidden) writer both retained");
}

#[test]
fn test_strict_mojo_base_shift_not_invocant() {
    // `use Mojo::Base -strict` is a non-OO module: a bare `my $x = shift` is
    // arg[0], NOT the invocant, so it must not type as the package (doing so
    // produced bogus unresolved-method diagnostics, e.g. $tx->res in
    // Mojo::WebSocket). A named invocant is still typed elsewhere.
    let fa = build_fa(
        "package MyStrict;\nuse Mojo::Base -strict;\nsub helper {\n  my $tx = shift;\n  return $tx->res;\n}\n",
    );
    assert_eq!(
        fa.inferred_type_via_bag("$tx", Point::new(4, 9)),
        None,
        "shift in a -strict (non-OO) module must not type as the package"
    );
}

#[test]
fn test_mojo_base_base_and_strict_still_oo() {
    // `-base` (in any order, even alongside the redundant `-strict`) makes the
    // package a class, so a bare `shift` IS the invocant.
    for src in [
        "package C;\nuse Mojo::Base -base, -strict;\nsub greet {\n  my $x = shift;\n  return $x->name;\n}\n",
        "package C;\nuse Mojo::Base -strict, -base;\nsub greet {\n  my $x = shift;\n  return $x->name;\n}\n",
    ] {
        let fa = build_fa(src);
        assert_eq!(
            fa.inferred_type_via_bag("$x", Point::new(4, 9)),
            Some(InferredType::ClassName("C".into())),
            "-base makes the package OO regardless of a redundant -strict: {src}"
        );
    }
}

#[test]
fn test_list_shift_pair_params_extracted() {
    // Mojo idiom `my ($self, $name) = (shift, shift)` — each shift binds the
    // next @_ element, so the LHS vars are positional params. $self is the
    // invocant; $name is a real param.
    let fa = build_fa("package P;\nsub cookie {\n  my ($self, $name) = (shift, shift);\n}\n");
    let sub = fa.symbols.iter().find(|s| s.name == "cookie").expect("cookie sym");
    let params: Vec<&str> = match &sub.detail {
        SymbolDetail::Sub { params, .. } => params.iter().map(|p| p.name.as_str()).collect(),
        _ => panic!("cookie not a Sub"),
    };
    assert!(params.contains(&"$self") && params.contains(&"$name"),
        "expected $self + $name from (shift, shift), got {params:?}");
}

#[test]
fn test_goto_amp_fq_sub_emits_call_ref() {
    // `goto &Foo::bar` — the `&` code-ref sigil is stripped so the FQ call
    // resolves; a FunctionCall ref to Foo::bar is emitted (resolved_package Foo).
    let fa = build_fa("package Child;\nsub import { goto &Parent::Thing::setup; }\n");
    let r = fa.refs.iter().find(|r|
        matches!(r.kind, RefKind::FunctionCall { .. }) && r.target_name == "Parent::Thing::setup");
    assert!(r.is_some(), "expected FunctionCall ref to Parent::Thing::setup (& stripped), got {:?}",
        fa.refs.iter().filter(|r| matches!(r.kind, RefKind::FunctionCall{..})).map(|r| &r.target_name).collect::<Vec<_>>());
}

#[test]
fn test_glob_assigned_sub_ternary_rhs_registers() {
    // Try::Tiny `*_subname = $su ? \&Sub::Util::set_subname : sub {...}` /
    // Path::Tiny `*_same = IS_WIN32() ? sub{} : sub{}`: the glob holds a coderef
    // in every branch, so the name is a registered sub. Without this, same-file
    // calls were flagged unresolved-function (false positive).
    let fa = build_fa(
        r#"
package Demo;
sub bar { 1 }
*_subname = $su ? \&Sub::Util::set_subname : sub { $_[1] };
"#,
    );
    assert!(
        fa.symbols
            .iter()
            .any(|s| s.kind == SymKind::Sub && s.name == "_subname"),
        "ternary glob-assign should register `_subname` as a sub: {:?}",
        fa.symbols.iter().filter(|s| s.kind == SymKind::Sub).map(|s| &s.name).collect::<Vec<_>>()
    );
}

#[test]
fn test_loop_variable_constant_folding() {
    let fa = build_fa(
        "
package Foo;
sub test {
    my $self = shift;
    for my $attr (qw(name email)) {
        my $getter = \"get_$attr\";
        $self->$getter();
    }
}
",
    );
    let method_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| matches!(r.kind, RefKind::MethodCall { .. }))
        .map(|r| r.target_name.as_str())
        .collect();
    assert!(method_refs.contains(&"get_name"), "should resolve get_name");
    assert!(
        method_refs.contains(&"get_email"),
        "should resolve get_email"
    );
}

#[test]
fn test_dynamic_method_dispatch() {
    let fa = build_fa(
        "
package Foo;
my $method = 'get_name';
sub test { my $self = shift; $self->$method() }
",
    );
    let method_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| matches!(r.kind, RefKind::MethodCall { .. }) && r.target_name == "get_name")
        .collect();
    assert!(
        !method_refs.is_empty(),
        "dynamic method call should resolve to get_name"
    );
}

// ---- Framework plugin integration ----

/// End-to-end: the bundled `mojo-events` Rhai plugin should synthesize a
/// `HashKeyDef` for every literal event name passed to `->on(...)`
/// inside a class that inherits from `Mojo::EventEmitter`. This is the
/// proof that Rhai scripts emit real symbols that land in FileAnalysis
/// with the `Framework` namespace stamp.
#[test]
fn plugin_mojo_events_on_literal_emits_handler_symbol() {
    let src = r#"
package My::Emitter;
use parent 'Mojo::EventEmitter';

sub new {
    my $class = shift;
    my $self = bless {}, $class;
    $self->on('connect', sub { ... });
    $self->on('message', sub { ... });
    $self;
}

1;
"#;
    let fa = build_fa(src);

    let handlers: Vec<&Symbol> = fa
        .symbols
        .iter()
        .filter(|s| {
            s.kind == SymKind::Handler
                && matches!(&s.namespace, Namespace::Framework { id } if id == "mojo-events")
        })
        .collect();

    let names: std::collections::HashSet<&str> = handlers.iter().map(|s| s.name.as_str()).collect();
    assert!(
        names.contains("connect"),
        "mojo-events should emit Handler for 'connect'; got: {:?}",
        names
    );
    assert!(
        names.contains("message"),
        "mojo-events should emit Handler for 'message'; got: {:?}",
        names
    );

    // Each Handler should also carry the dispatcher set — at minimum
    // 'emit' (the canonical Mojo dispatch method).
    for h in &handlers {
        if let SymbolDetail::Handler { dispatchers, .. } = &h.detail {
            assert!(
                dispatchers.iter().any(|d| d == "emit"),
                "Handler for {} should declare `emit` dispatcher",
                h.name
            );
        } else {
            panic!("expected Handler detail on {}", h.name);
        }
    }
}

/// Dynamic event names must not produce spurious HashKeyDefs.
#[test]
fn plugin_mojo_events_dynamic_name_does_not_emit() {
    let src = r#"
package My::Emitter;
use parent 'Mojo::EventEmitter';

sub wire {
    my ($self, $name) = @_;
    $self->on($name, sub { ... });
}

1;
"#;
    let fa = build_fa(src);
    let plugin_handlers: Vec<&Symbol> = fa
        .symbols
        .iter()
        .filter(|s| {
            s.kind == SymKind::Handler
                && matches!(&s.namespace, Namespace::Framework { id } if id == "mojo-events")
        })
        .collect();
    assert!(
        plugin_handlers.is_empty(),
        "dynamic event name must not emit handlers; got: {:?}",
        plugin_handlers.iter().map(|s| &s.name).collect::<Vec<_>>()
    );
}

/// Const folding through the plugin: `my $name = 'connect'; ...` means
/// the plugin receives `arg.string_value == "connect"` and emits a
/// symbol named "connect" — not "$name". The plugin itself contains no
/// folding logic; the builder does it once in `arg_info_for` and every
/// plugin gets folded values for free.
#[test]
fn plugin_mojo_events_const_folds_scalar_event_name() {
    let src = r#"
package My::Emitter;
use parent 'Mojo::EventEmitter';

sub wire {
    my $self = shift;
    my $evt = 'disconnect';
    $self->on($evt, sub { ... });
}

1;
"#;
    let fa = build_fa(src);

    let names: std::collections::HashSet<&str> = fa
        .symbols
        .iter()
        .filter(|s| {
            s.kind == SymKind::Handler
                && matches!(&s.namespace, Namespace::Framework { id } if id == "mojo-events")
        })
        .map(|s| s.name.as_str())
        .collect();
    assert!(
        names.contains("disconnect"),
        "const-folded event name should emit 'disconnect'; got: {:?}",
        names
    );
    assert!(
        !names.contains("$evt"),
        "variable text must not leak through as symbol name"
    );
}

/// Transitive inheritance: a class whose parent (in the same file)
/// extends Mojo::EventEmitter should still trigger the plugin. Proves
/// the builder's transitive_parents walk composes with `ClassIsa`.
#[test]
fn plugin_mojo_events_triggers_through_transitive_parent() {
    let src = r#"
package Mid;
use parent 'Mojo::EventEmitter';

package Leaf;
use parent 'Mid';

sub wire {
    my $self = shift;
    $self->on('ready', sub { ... });
}

1;
"#;
    let fa = build_fa(src);
    let ready: Vec<&Symbol> = fa
        .symbols
        .iter()
        .filter(|s| {
            s.kind == SymKind::Handler
                && s.name == "ready"
                && matches!(&s.namespace, Namespace::Framework { id } if id == "mojo-events")
        })
        .collect();
    assert_eq!(
        ready.len(),
        1,
        "Leaf extends Mid extends Mojo::EventEmitter — plugin must fire transitively"
    );
}

/// Cross-file def/ref pairing. Producer.pm wires events via ->on, Consumer.pm
/// calls ->emit on a producer instance. Both plugin emissions end up with
/// `HashKeyOwner::Class("Producer")`, so `resolve::refs_to` finds the
/// consumer's access ref from the producer's def query — no LSP code is
/// plugin-aware.
#[test]
fn plugin_mojo_events_cross_file_ref_pairing() {
    use crate::file_analysis::HandlerOwner;
    use crate::file_store::FileStore;
    use crate::resolve::{refs_to, RoleMask, TargetKind, TargetRef};
    use std::path::PathBuf;

    let producer_src = r#"
package Producer;
use parent 'Mojo::EventEmitter';

sub new {
    my $class = shift;
    my $self = bless {}, $class;
    $self->on('ready', sub { warn "ready" });
    return $self;
}
1;
"#;
    let consumer_src = r#"
package Consumer;
use parent 'Mojo::EventEmitter';

sub run {
    my $p = Producer->new;
    $p->emit('ready');
    $p->unsubscribe('ready');
}
1;
"#;

    let store = FileStore::new();
    let producer_path = PathBuf::from("/tmp/plugin_producer.pm");
    let consumer_path = PathBuf::from("/tmp/plugin_consumer.pm");

    store.insert_workspace(producer_path.clone(), build_fa(producer_src));
    store.insert_workspace(consumer_path.clone(), build_fa(consumer_src));

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "ready".to_string(),
            kind: TargetKind::Handler {
                owner: HandlerOwner::Class("Producer".to_string()),
                name: "ready".to_string(),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );

    let producer_hits = results
        .iter()
        .filter(|r| matches!(&r.key, crate::file_store::FileKey::Path(p) if p == &producer_path))
        .count();
    let consumer_hits = results
        .iter()
        .filter(|r| matches!(&r.key, crate::file_store::FileKey::Path(p) if p == &consumer_path))
        .count();

    assert!(
        producer_hits >= 1,
        "producer should have ≥1 hit (the ->on Handler def); results: {:?}",
        results
    );
    assert!(
        consumer_hits >= 1,
        "consumer should have ≥1 hit (the ->emit DispatchCall); results: {:?}",
        results
    );
}

/// mojo-helpers: Phase-2 architecture emits ONE Method per helper,
/// owned by `Mojolicious::Controller` — the canonical home for
/// controller-callable helpers. The PluginNamespace's bridges cover
/// both Controller and Mojolicious so `$c->name` AND `$app->name`
/// both resolve through namespace lookup (no Symbol fan-out).
#[test]
fn plugin_mojo_helpers_registers_method_on_controller() {
    let src = r#"
package MyApp::Lite;
use Mojolicious::Lite;

my $app = Mojolicious->new;
$app->helper(current_user => sub {
    my ($c, $extra) = @_;
    return { id => 1 };
});
"#;
    let fa = build_fa(src);

    let helpers: Vec<&Symbol> = fa
        .symbols
        .iter()
        .filter(|s| {
            s.kind == SymKind::Method
                && s.name == "current_user"
                && matches!(&s.namespace, Namespace::Framework { id } if id == "mojo-helpers")
        })
        .collect();

    assert_eq!(
        helpers.len(),
        1,
        "one Method per helper (no fan-out — Phase 2)"
    );
    let helper = helpers[0];
    assert_eq!(
        helper.package.as_deref(),
        Some(crate::file_analysis::APP_SURFACE_CLASS),
        "canonical home is the fictional app surface"
    );

    if let SymbolDetail::Sub {
        params, display, ..
    } = &helper.detail
    {
        let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(
            names,
            vec!["$c", "$extra"],
            "helper's sub params flow through to the Method signature"
        );
        assert_eq!(
            *display,
            Some(crate::file_analysis::HandlerDisplay::Helper),
            "helpers render as HandlerDisplay::Helper — the LSP kind is \
                 FUNCTION (the enum doesn't have Helper), the outline word \
                 is 'helper'. See HandlerDisplay::outline_word.",
        );
    } else {
        panic!("helper detail should be Sub");
    }

    // The PluginNamespace owns the bridge visibility: a SINGLE bridge
    // to the fictional app surface (docs/adr/plugin-system.md). The
    // consumer classes reach it via the synthetic-parent edge in core,
    // not via a per-helper bridge list.
    let ns = fa
        .plugin_namespaces
        .iter()
        .find(|n| n.plugin_id == "mojo-helpers" && n.entities.contains(&helper.id))
        .expect("helper belongs to a mojo-helpers namespace");
    let bridge_classes: std::collections::HashSet<&str> = ns
        .bridges
        .iter()
        .map(|Bridge::Class(c)| c.as_str())
        .collect();
    assert_eq!(
        bridge_classes,
        std::iter::once(crate::file_analysis::APP_SURFACE_CLASS).collect(),
        "namespace bridges ONLY the app surface — open consumer set lives in core"
    );

    // The synthetic-ancestor edge: the helper resolves from BOTH the
    // app class and the controller class through the SAME ancestor walk,
    // even though neither is the helper's home package.
    for consumer in ["Mojolicious", "Mojolicious::Controller"] {
        let res = fa.resolve_method_in_ancestors(consumer, "current_user", None);
        match res {
            Some(crate::file_analysis::MethodResolution::Local { sym_id, .. }) => {
                assert_eq!(
                    sym_id, helper.id,
                    "{consumer}->current_user must resolve to the helper via the app surface"
                );
            }
            other => panic!(
                "{consumer}->current_user should resolve to the helper Local; got {other:?}"
            ),
        }
    }
}

/// Helper-fn `at` for `inferred_type_via_bag`: column past `my $c = shift;`
/// (or anywhere inside the sub body) so the TC's scope contains the point.
fn first_param_type(fa: &FileAnalysis, var: &str, body_line: usize, col: usize) -> Option<InferredType> {
    fa.inferred_type_via_bag(var, Point::new(body_line, col))
}

/// Named-sub helper registration (`->helper(greet => \&_greet)`): the
/// referenced sub's first positional is the controller, exactly like the
/// inline `sub ($c) {...}` form. `my $c = shift` unpacking.
#[test]
fn plugin_mojo_helpers_named_sub_typed_via_shift() {
    let src = r#"
package MyApp::Lite;
use Mojolicious::Lite;

my $app = Mojolicious->new;
$app->helper(greet => \&_greet);

sub _greet {
    my $c = shift;
    $c->render(text => 'hi');
}
"#;
    let fa = build_fa(src);
    // `$c` is declared on line 8 (`my $c = shift;`); query just after it.
    let ty = first_param_type(&fa, "$c", 8, 14);
    assert_eq!(
        ty,
        Some(InferredType::ClassName("Mojolicious::Controller".into())),
        "named-sub helper's first positional types as the controller"
    );
}

/// Same, signature form `sub _greet ($c, $name) {...}`.
#[test]
fn plugin_mojo_helpers_named_sub_typed_via_signature() {
    let src = r#"
package MyApp::Lite;
use Mojolicious::Lite;

my $app = Mojolicious->new;
$app->helper(greet => \&_greet);

sub _greet ($c, $name) {
    $c->render(text => $name);
}
"#;
    let fa = build_fa(src);
    let ty = first_param_type(&fa, "$c", 8, 8);
    assert_eq!(
        ty,
        Some(InferredType::ClassName("Mojolicious::Controller".into())),
        "signature-form named-sub helper's first positional types as the controller"
    );
}

/// Plain-comma spelling `helper('greet', \&_greet)` is identical to the
/// fat-comma form — fat-comma carries no code semantics (CLAUDE.md).
#[test]
fn plugin_mojo_helpers_named_sub_plain_comma() {
    let src = r#"
package MyApp::Lite;
use Mojolicious::Lite;

my $app = Mojolicious->new;
$app->helper('greet', \&_greet);

sub _greet {
    my $c = shift;
    $c->render;
}
"#;
    let fa = build_fa(src);
    let ty = first_param_type(&fa, "$c", 8, 14);
    assert_eq!(
        ty,
        Some(InferredType::ClassName("Mojolicious::Controller".into())),
        "plain-comma helper registration types the named sub identically"
    );
}

/// Regression: the inline-callback form still types `$c`.
#[test]
fn plugin_mojo_helpers_inline_callback_still_typed() {
    let src = r#"
package MyApp::Lite;
use Mojolicious::Lite;

my $app = Mojolicious->new;
$app->helper(greet => sub {
    my $c = shift;
    $c->render;
});
"#;
    let fa = build_fa(src);
    let ty = first_param_type(&fa, "$c", 6, 14);
    assert_eq!(
        ty,
        Some(InferredType::ClassName("Mojolicious::Controller".into())),
        "inline-callback helper still types its first positional"
    );
}

/// A named sub NOT registered as a helper (referenced via `\&` elsewhere,
/// plus a plain `sub`) gets no spurious controller typing.
#[test]
fn plugin_mojo_helpers_non_helper_named_sub_unaffected() {
    let src = r#"
package MyApp::Lite;
use Mojolicious::Lite;

my $cb = \&_other;

sub _other {
    my $c = shift;
    return $c;
}
"#;
    let fa = build_fa(src);
    let ty = first_param_type(&fa, "$c", 7, 14);
    assert_ne!(
        ty,
        Some(InferredType::ClassName("Mojolicious::Controller".into())),
        "a non-helper named sub must not be typed as a controller"
    );
}

/// Dotted helpers chain into namespace methods: `users.create` means
/// `$c->users->create`. Each non-leaf segment emits a parameterless
/// Method returning a synthetic proxy class; the leaf emits on the
/// innermost proxy with the helper's real params. Shared prefixes
/// dedup — `thing.hi` and `thing.there` must only ever produce one
/// `thing` symbol (not two), so completion + outline stay clean.
#[test]
fn plugin_mojo_helpers_dotted_chain_with_shared_prefix_dedup() {
    let src = r#"
package MyApp::Lite;
use Mojolicious::Lite;

my $app = Mojolicious->new;
$app->helper('thing.hi'    => sub { my ($c, $arg_a) = @_; });
$app->helper('thing.there' => sub { my ($c, $arg_b) = @_; });
"#;
    let fa = build_fa(src);

    // Exactly one `thing` method on the app surface (the chain root's
    // home; consumer classes reach it via the synthetic-parent edge),
    // despite two dotted helpers sharing that prefix.
    let thing_syms: Vec<&Symbol> = fa
        .symbols
        .iter()
        .filter(|s| {
            s.name == "thing"
                && s.kind == SymKind::Method
                && s.package.as_deref() == Some(crate::file_analysis::APP_SURFACE_CLASS)
        })
        .collect();
    assert_eq!(
        thing_syms.len(),
        1,
        "shared prefix must dedup: one `thing` method, got {}",
        thing_syms.len()
    );

    // Its return_type is the shared proxy class.
    match fa.symbol_return_type_via_bag(thing_syms[0].id, None) {
        Some(InferredType::ClassName(n)) => {
            assert_eq!(n, "Mojolicious::Controller::_Helper::thing");
        }
        _ => panic!("thing's return type should be the shared proxy class"),
    }

    // Both leaves exist on the shared proxy class, each with its own params.
    let hi = fa
        .symbols
        .iter()
        .find(|s| s.name == "hi" && s.kind == SymKind::Method)
        .expect("hi leaf emitted");
    let there = fa
        .symbols
        .iter()
        .find(|s| s.name == "there" && s.kind == SymKind::Method)
        .expect("there leaf emitted");
    assert_eq!(
        hi.package.as_deref(),
        Some("Mojolicious::Controller::_Helper::thing")
    );
    assert_eq!(
        there.package.as_deref(),
        Some("Mojolicious::Controller::_Helper::thing")
    );
    if let SymbolDetail::Sub { params, .. } = &hi.detail {
        let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(names, vec!["$c", "$arg_a"]);
    }
    if let SymbolDetail::Sub { params, .. } = &there.detail {
        let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(names, vec!["$c", "$arg_b"]);
    }
}

/// Three-level dotted helper chains: `admin.users.purge` synthesizes
/// two intermediate proxies, each with the right return_type, and
/// the leaf lands on the innermost proxy.
#[test]
fn plugin_mojo_helpers_three_level_dotted_chain() {
    let src = r#"
package MyApp::Lite;
use Mojolicious::Lite;

my $app = Mojolicious->new;
$app->helper('admin.users.purge' => sub { my ($c, $force) = @_; });
"#;
    let fa = build_fa(src);

    let admin = fa
        .symbols
        .iter()
        .find(|s| {
            s.name == "admin"
                && s.kind == SymKind::Method
                && s.package.as_deref() == Some(crate::file_analysis::APP_SURFACE_CLASS)
        })
        .expect("admin on app surface (chain root)");
    let users = fa
        .symbols
        .iter()
        .find(|s| {
            s.name == "users"
                && s.kind == SymKind::Method
                && s.package.as_deref() == Some("Mojolicious::Controller::_Helper::admin")
        })
        .expect("users on admin proxy");
    let purge = fa
        .symbols
        .iter()
        .find(|s| {
            s.name == "purge"
                && s.kind == SymKind::Method
                && s.package.as_deref() == Some("Mojolicious::Controller::_Helper::admin::users")
        })
        .expect("purge leaf on admin.users proxy");

    // Each non-leaf returns the next proxy in the chain.
    if let Some(InferredType::ClassName(n)) =
        fa.symbol_return_type_via_bag(admin.id, None)
    {
        assert_eq!(n, "Mojolicious::Controller::_Helper::admin");
    }
    if let Some(InferredType::ClassName(n)) =
        fa.symbol_return_type_via_bag(users.id, None)
    {
        assert_eq!(n, "Mojolicious::Controller::_Helper::admin::users");
    }
    // Leaf carries the helper's actual params.
    if let SymbolDetail::Sub { params, .. } = &purge.detail {
        let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(names, vec!["$c", "$force"]);
    }
}

/// `use Mojolicious::Lite` autoimports a fixed verb set — our
/// unresolved-function diagnostic must skip them. The plugin's
/// `on_use` hook emits FrameworkImport actions for each; the
/// builder stashes them in framework_imports so the diagnostic
/// filter drops matching FunctionCall refs.
#[test]
fn plugin_mojo_lite_autoimports_verbs() {
    let src = r#"
package main;
use Mojolicious::Lite;

get '/x' => sub {};
post '/y' => sub {};
helper foo => sub {};
"#;
    let fa = build_fa(src);
    for verb in &[
        "get",
        "post",
        "put",
        "del",
        "patch",
        "any",
        "under",
        "websocket",
        "app",
        "helper",
        "hook",
        "plugin",
        "group",
    ] {
        assert!(
            fa.framework_imports.contains(*verb),
            "{} must be autoimported by use Mojolicious::Lite",
            verb
        );
    }
}

/// mojo-lite: top-level route verbs (`get`, `post`, etc.) register
/// Handlers keyed by URL path, with ["url_for"] as the dispatcher so
/// `url_for('/users')` can find them. Exercises the on_function_call
/// plugin hook that mojo-events doesn't use.
#[test]
fn plugin_mojo_lite_registers_handlers_for_routes() {
    let src = r#"
package main;
use Mojolicious::Lite;

get '/users' => sub {
    my ($c, $arg) = @_;
    $c->render(text => 'hi');
};

post '/login' => sub {
    my ($c, $user, $pw) = @_;
};

app->start;
"#;
    let fa = build_fa(src);

    let route_handlers: Vec<&Symbol> = fa
        .symbols
        .iter()
        .filter(|s| {
            s.kind == SymKind::Handler
                && matches!(&s.namespace, Namespace::Framework { id } if id == "mojo-lite")
        })
        .collect();

    let names: std::collections::HashSet<&str> =
        route_handlers.iter().map(|s| s.name.as_str()).collect();
    assert!(
        names.contains("/users"),
        "GET /users handler emitted; got: {:?}",
        names
    );
    assert!(
        names.contains("/login"),
        "POST /login handler emitted; got: {:?}",
        names
    );

    // Each handler declares url_for as its dispatcher so completion
    // inside `url_for('|')` surfaces every route.
    for h in &route_handlers {
        if let SymbolDetail::Handler { dispatchers, .. } = &h.detail {
            assert!(
                dispatchers.iter().any(|d| d == "url_for"),
                "handler {} should dispatch via url_for",
                h.name
            );
        }
    }

    // Handler params come from the handler sub's signature —
    // different per route, so they round-trip correctly.
    let login = route_handlers.iter().find(|h| h.name == "/login").unwrap();
    if let SymbolDetail::Handler { params, .. } = &login.detail {
        let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
        assert_eq!(names, vec!["$c", "$user", "$pw"]);
    }
}

/// Routes are first-class things, not just refs. Every `->to(...)`
/// emits BOTH a MethodCallRef (cross-file target link) AND a
/// Handler symbol (route-as-entity — outline-visible, workspace-
/// searchable, discoverable via url_for completion). Mirrors the
/// mojo-lite model so route symbols are symmetric regardless of
/// declaration flavor.
#[test]
fn plugin_mojo_routes_emits_both_ref_and_handler_symbol() {
    let src = r#"
package MyApp;
use Mojolicious::Lite;

my $r = app->routes;
$r->get('/users')->to('Users#list');
$r->post('/users')->to(controller => 'Users', action => 'create');
"#;
    let fa = build_fa(src);

    // Each route: one MethodCallRef + one Handler symbol.
    let method_refs: Vec<&Ref> = fa
        .refs
        .iter()
        .filter(|r| {
            matches!(r.kind, RefKind::MethodCall { .. })
                && (r.target_name == "list" || r.target_name == "create")
        })
        .collect();
    assert_eq!(method_refs.len(), 2, "one MethodCallRef per route");

    let route_syms: Vec<&Symbol> = fa
        .symbols
        .iter()
        .filter(|s| {
            s.kind == SymKind::Handler
                && matches!(&s.namespace, Namespace::Framework { id } if id == "mojo-routes")
        })
        .collect();
    assert_eq!(
        route_syms.len(),
        2,
        "one Handler symbol per route so outline + workspace-symbol find them"
    );

    let names: std::collections::HashSet<&str> =
        route_syms.iter().map(|s| s.name.as_str()).collect();
    assert!(
        names.contains("Users#list"),
        "route identity `Users#list` present; got: {:?}",
        names
    );
    assert!(
        names.contains("Users#create"),
        "route identity `Users#create` present; got: {:?}",
        names
    );

    // Dispatcher is url_for so completion inside `url_for('|')`
    // offers every registered route.
    for s in &route_syms {
        if let SymbolDetail::Handler {
            dispatchers, owner, ..
        } = &s.detail
        {
            assert!(
                dispatchers.iter().any(|d| d == "url_for"),
                "route {} should dispatch via url_for",
                s.name
            );
            // Owner is `Mojolicious::Controller` — url_for is a
            // Controller method and the routes table is global
            // per Mojo's runtime model. Owning on Controller lets
            // `$c->url_for` in any controller resolve routes
            // declared in any app file through ancestor walking.
            // Not target-class (Users): routes exist independent
            // of their target; two routes can target the same
            // action (paginated/json/etc.).
            assert!(matches!(owner, HandlerOwner::Class(c) if c == "Mojolicious::Controller"),
                    "route owner is Mojolicious::Controller (shared base for url_for), not declaring package");
        }
    }
}

/// End-to-end cross-file gd for `->to('Users#list')`. Users.pm
/// is registered as a workspace module in ModuleIndex (via the
/// `register_workspace_module` bridge), so
/// `resolve_method_in_ancestors` finds it on lookup — and the
/// cross-file MethodCall path in `symbols::find_definition`
/// surfaces the Users::list def's location.
///
/// Before the fix, workspace modules lived only in FileStore so
/// lookups that key on module name (all cross-file method
/// resolution) missed them and gd fell through to noise.
#[test]
fn plugin_mojo_routes_gd_reaches_workspace_target() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;
    use tower_lsp::lsp_types::Position;

    let app_src = r#"
package MyApp;
use Mojolicious::Lite;

my $r = app->routes;
$r->get('/users')->to('Users#list');
"#;
    let users_src = r#"
package Users;
sub list { my ($c) = @_; }
1;
"#;

    let app_fa = build_fa(app_src);
    let users_fa = build_fa(users_src);

    let idx = ModuleIndex::new_for_test();
    // Simulate workspace indexing registering Users.pm under its
    // primary package name.
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Users.pm"),
        Arc::new(users_fa),
    );

    // Sanity: cross-file resolution on "Users"::"list" must succeed.
    let res = app_fa.resolve_method_in_ancestors("Users", "list", Some(&idx));
    assert!(
        res.is_some(),
        "Users::list must resolve cross-file after workspace register"
    );

    // And the MethodCallRef emitted by mojo-routes on the 'list'
    // portion of 'Users#list' should be at a span matching the
    // text 'list'.
    let route_ref = app_fa
        .refs
        .iter()
        .find(|r| matches!(r.kind, RefKind::MethodCall { .. }) && r.target_name == "list")
        .expect("mojo-routes MethodCallRef for 'list'");

    // The ref's span is tight on the action name — mid-string
    // completion + goto-def both rely on that precision.
    let _ = route_ref;
    let _ = Position::default();
}

/// mojo-routes short form: `->to('Users#list')` emits a MethodCall
/// ref pointing to `Users::list`. Cursor on the string → gd jumps
/// cross-file to the Users controller's list method, same as any
/// regular method call. No routes-specific resolution code; it's
/// just a Ref that happens to live inside a string literal.
#[test]
fn plugin_mojo_routes_short_form_emits_method_call_ref() {
    let src = r#"
package MyApp;
use Mojolicious::Lite;

my $r = app->routes;
$r->get('/users')->to('Users#list');
"#;
    let fa = build_fa(src);

    let route_refs: Vec<&Ref> = fa
        .refs
        .iter()
        .filter(|r| matches!(r.kind, RefKind::MethodCall { .. }) && r.target_name == "list")
        .collect();

    assert!(
        !route_refs.is_empty(),
        "at least one MethodCall ref for 'list'"
    );
    let r = route_refs
        .iter()
        .find(|r| matches!(&r.kind, RefKind::MethodCall { invocant, .. } if invocant == "Users"))
        .expect("MethodCall with invocant=Users");

    // Sanity: ref span covers the string literal so cursor anywhere
    // in the 'Users#list' range lands on the ref.
    assert!(
        r.span.end.column > r.span.start.column,
        "method ref has non-empty span"
    );
}

/// mojo-routes long form: `->to(controller => 'Users', action => 'list')`.
/// Walks kwarg pairs, pairs up controller+action, emits the ref
/// with span on the action value.
#[test]
fn plugin_mojo_routes_long_form_emits_method_call_ref() {
    let src = r#"
package MyApp;
use Mojolicious::Lite;

my $r = app->routes;
$r->get('/users')->to(controller => 'Users', action => 'list');
"#;
    let fa = build_fa(src);

    let has_ref = fa.refs.iter().any(|r| {
        matches!(&r.kind, RefKind::MethodCall { invocant, .. } if invocant == "Users")
            && r.target_name == "list"
    });
    assert!(
        has_ref,
        "long-form ->to(controller=>, action=>) must produce MethodCall ref"
    );
}

/// `$r->get('/users')->to('Users#list')->name('users_list')` — the
/// `->name()` call registers a symbolic handle. `url_for('users_list')`
/// and `redirect_to('users_list')` must resolve to it, the same way
/// they resolve to `'Users#list'`. Without `->name()`, calls like
/// `url_for('users_list')` sit unresolved.
#[test]
fn plugin_mojo_routes_name_registers_url_for_handle() {
    let src = r#"
package MyApp;
use Mojolicious::Lite;

my $r = app->routes;
$r->get('/users')->to('Users#list')->name('users_list');
"#;
    let fa = build_fa(src);

    let route_name_handler = fa
        .symbols
        .iter()
        .find(|s| s.kind == SymKind::Handler && s.name == "users_list");
    assert!(
        route_name_handler.is_some(),
        "->name('users_list') must emit a Handler; handlers: {:?}",
        fa.symbols
            .iter()
            .filter(|s| s.kind == SymKind::Handler)
            .map(|s| &s.name)
            .collect::<Vec<_>>()
    );

    let sym = route_name_handler.unwrap();
    if let SymbolDetail::Handler { dispatchers, .. } = &sym.detail {
        assert!(
            dispatchers.iter().any(|d| d == "url_for"),
            "named route must dispatch via url_for"
        );
        assert!(
            dispatchers.iter().any(|d| d == "redirect_to"),
            "named route must dispatch via redirect_to"
        );
    } else {
        panic!("route-name symbol should be Handler; got {:?}", sym.detail);
    }

    // The route name should be in a mojo-routes namespace bridged
    // to the declaring package, so cross-file `url_for('users_list')`
    // from other files in the workspace resolves.
    let ns = fa
        .plugin_namespaces
        .iter()
        .find(|n| n.plugin_id == "mojo-routes" && n.entities.contains(&sym.id));
    assert!(
        ns.is_some(),
        "named route must belong to a mojo-routes namespace"
    );
}

/// `->to('X#y')` routes dispatch via both `url_for` and `redirect_to`
/// (Phase-2 follow-up — `redirect_to` used to be Lite-only). Matches
/// Mojolicious's actual API where redirect_to on a controller resolves
/// named routes identically to url_for.
#[test]
fn plugin_mojo_routes_to_dispatches_via_redirect_to_too() {
    let src = r#"
package MyApp;
use Mojolicious::Lite;

my $r = app->routes;
$r->get('/users')->to('Users#list');
"#;
    let fa = build_fa(src);

    let route_handler = fa
        .symbols
        .iter()
        .find(|s| s.kind == SymKind::Handler && s.name == "Users#list")
        .expect("Users#list Handler");

    if let SymbolDetail::Handler { dispatchers, .. } = &route_handler.detail {
        assert!(
            dispatchers.iter().any(|d| d == "url_for"),
            "->to route must dispatch via url_for"
        );
        assert!(
            dispatchers.iter().any(|d| d == "redirect_to"),
            "->to route must dispatch via redirect_to"
        );
    } else {
        panic!("route symbol should be Handler");
    }
}

// ==== AliasTo: DSL verbs delegate to real methods, not imaginary ones. ====
//
// `Mojolicious::Lite` monkey-patches `get`, `post`, `helper`, `app`, …
// into the caller at import time. At the Perl level each verb is just
// a thin pass-through to a real method:
//
//     sub { $routes->get(@_) }                  # get, post, put, any,
//                                               # options, patch, websocket
//     sub { $routes->delete(@_) }               # del
//     sub { $app->helper(@_) }                  # helper, hook, plugin
//     sub { $app }                              # app (returns the app)
//
// Previously the plugin fabricated a `SymbolDetail::Sub` per verb with a
// hand-written one-line `doc:` and, for `app`, a typed return. That's
// the "imaginary methods" the user pointed at: hover shows stub text,
// gd lands on the use statement, signature help has no params, and —
// worst — the synthesized Sub shadows chain resolution on real Mojo
// objects (`$routes->get('/x')->to(...)` loses the `to` intelligence).
//
// The fix: emit an *alias* that points at the real cross-file method.
// Hover, gd, sig help, and return-type inference all dereference the
// alias and use the real method's data. The tests below pin the
// expected behavior on real cross-file methods — they fail until
// `FunctionAlias` / `alias_to` lands in the data model and the
// resolution paths dereference it.

/// The user-visible "stomping" case: `$routes->get('/x')->to('X#y')` on
/// a real `Mojolicious::Routes` should chain through
/// `Mojolicious::Routes::Route::get` (fluent, returns its own class)
/// so `->to` resolves on `Mojolicious::Routes::Route`. The plugin-
/// synthesized top-level `get` Sub in the Lite script must NOT
/// intercept a method call on a real object of a different class.
#[test]
fn mojo_lite_chain_off_real_routes_preserves_real_method_chain() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    let app_src = r#"
package main;
use Mojolicious::Lite;
use Mojolicious;

my $routes = Mojolicious::Routes->new;
$routes->get('/users')->to('Users#list');
"#;
    // Stub Mojolicious::Routes::Route with a fluent `get` (returns
    // its own class) so chain resolution can carry the type forward.
    let route_pm_src = r#"
package Mojolicious::Routes::Route;
use Mojo::Base -base;

sub get {
    my $self = shift;
    return $self;
}

sub to {
    my $self = shift;
    return $self;
}
1;
"#;
    // Mojolicious::Routes ISA Mojolicious::Routes::Route in real
    // Mojo, so methods invoked on $routes (typed Mojolicious::Routes)
    // flow up to the parent class via the normal inheritance walk.
    let routes_pm_src = r#"
package Mojolicious::Routes;
use Mojo::Base 'Mojolicious::Routes::Route';
1;
"#;

    let app_fa = build_fa(app_src);
    let route_fa = build_fa(route_pm_src);
    let routes_fa = build_fa(routes_pm_src);

    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Mojolicious/Routes/Route.pm"),
        Arc::new(route_fa),
    );
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Mojolicious/Routes.pm"),
        Arc::new(routes_fa),
    );

    // `$routes->get` must resolve to the real Mojolicious::Routes::Route::get
    // via inheritance (Mojolicious::Routes → Mojolicious::Routes::Route) —
    // NOT to the plugin's top-level `get` Sub emitted by mojo-lite.
    // `class_name()` unifies ClassName and FirstParam — both are
    // usable for downstream chain resolution.
    let get_rt = app_fa.find_method_return_type("Mojolicious::Routes", "get", Some(&idx), None);
    assert_eq!(
        get_rt.as_ref().and_then(|t| t.class_name()),
        Some("Mojolicious::Routes::Route"),
        "`$$routes->get` must chain through the REAL Mojolicious::Routes::Route::get — \
             not the plugin's imaginary top-level `get` Sub. got: {:?}",
        get_rt,
    );

    // Second hop: `->to(...)` on the Route object returned by `get`.
    // User's wording: "get should return a to which is intelligent".
    // Fluent Route — `to` stays on Mojolicious::Routes::Route so the
    // chain can keep going (`->name(...)`, `->via(...)`, ...).
    let to_rt =
        app_fa.find_method_return_type("Mojolicious::Routes::Route", "to", Some(&idx), None);
    assert_eq!(
        to_rt.as_ref().and_then(|t| t.class_name()),
        Some("Mojolicious::Routes::Route"),
        "`->get('/x')->to(...)` must stay intelligent — Route::to is fluent, and \
             further hops depend on it. got: {:?}",
        to_rt,
    );
}

/// Hover on the DSL verb `get` in `get '/x' => sub {}` must surface
/// the real `Mojolicious::Routes::Route::get` POD, not the plugin's
/// hand-written one-liner. Pins that the plugin's Sub symbol for
/// `get` is an alias — its hover dereferences to the real method.
#[test]
fn mojo_lite_dsl_verb_hover_uses_real_method_doc() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    let app_src = r#"
package main;
use Mojolicious::Lite;

get '/users' => sub { my $c = shift; };
"#;
    // Real method carries a recognizable POD line. The test matches
    // on a substring that no hand-written plugin doc uses.
    let route_pm_src = r#"
package Mojolicious::Routes::Route;

=head2 get

  my $route = $r->get('/:foo' => sub ($c) {...});

Generate route matching only GET requests. Shortcut for
L<Mojolicious::Routes::Route/"any">.

=cut

sub get { my $self = shift; return $self; }
1;
"#;

    let app_fa = build_fa(app_src);
    let route_fa = build_fa(route_pm_src);

    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Mojolicious/Routes/Route.pm"),
        Arc::new(route_fa),
    );

    // Cursor on the `get` bareword at the call site.
    let (row, line) = app_src
        .lines()
        .enumerate()
        .find(|(_, l)| l.starts_with("get "))
        .expect("`get` call line");
    let col = line.find("get").unwrap() + 1;
    let point = tree_sitter::Point { row, column: col };

    let hover = app_fa
        .hover_info(point, app_src, Some(&idx))
        .expect("hover on DSL verb `get` returns text");

    assert!(
        hover.contains("Generate route matching only GET requests"),
        "hover on `get` must surface the real Mojolicious::Routes::Route::get POD \
             (verb is an alias, not an imaginary stub). got: {:?}",
        hover,
    );
}

/// `app` parses as a bareword invocant (`app->routes`). The plugin's
/// typed `app` Sub must make that bareword resolve to Mojolicious so
/// the chain can flow. Pins the bareword edge case explicitly — the
/// regression shape the user called out.
#[test]
fn mojo_lite_app_bareword_invocant_types_as_mojolicious() {
    let src = r#"
package main;
use Mojolicious::Lite;

my $x = app;
"#;
    let fa = build_fa(src);

    // `$x = app` — $x should pick up the return type of the plugin's
    // `app` Sub (ClassName("Mojolicious")).
    let ty = fa
        .inferred_type("$x", tree_sitter::Point::new(4, 0))
        .expect("$x must carry a type sourced from `app`'s return type");
    assert!(
        matches!(ty, InferredType::ClassName(c) if c == "Mojolicious"),
        "`$$x = app` must type as Mojolicious — bareword `app` resolves to the \
             plugin's typed Sub. got: {:?}",
        ty,
    );
}

/// The headline case: the full `app->routes->get('/x')->to('X#y')`
/// chain must be fully intelligent at every hop. One plugin stub
/// at the head (`app` → Mojolicious) — everything else is real
/// cross-file method resolution.
///
/// Every arrow is a separate assertion so a regression at any hop
/// points at the specific broken link:
///
///   app                                          → Mojolicious              (plugin-typed Sub)
///   Mojolicious::routes                          → Mojolicious::Routes       (real Mojo::Base accessor)
///   Mojolicious::Routes::get  (via parent Route) → Mojolicious::Routes::Route (fluent)
///   Mojolicious::Routes::Route::to               → Mojolicious::Routes::Route (fluent)
///
/// If any hop returns None the chain's "intelligence" collapses —
/// completion, hover, gd, sig-help all lose context from that point
/// forward. That collapse is the "hardcoded list" symptom the user
/// reported, flipped around.
#[test]
fn mojo_lite_app_routes_chain_is_fully_intelligent_to_the_end() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    let app_src = r#"
package main;
use Mojolicious::Lite;

app->routes->get('/users')->to('Users#list');
"#;
    let mojolicious_pm_src = r#"
package Mojolicious;
use Mojo::Base -base;

has routes => sub { Mojolicious::Routes->new };
1;
"#;
    let routes_pm_src = r#"
package Mojolicious::Routes;
use Mojo::Base 'Mojolicious::Routes::Route';
1;
"#;
    let route_pm_src = r#"
package Mojolicious::Routes::Route;
use Mojo::Base -base;

sub get { my $self = shift; return $self; }
sub to  { my $self = shift; return $self; }
1;
"#;

    let app_fa = build_fa(app_src);
    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Mojolicious.pm"),
        Arc::new(build_fa(mojolicious_pm_src)),
    );
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Mojolicious/Routes.pm"),
        Arc::new(build_fa(routes_pm_src)),
    );
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Mojolicious/Routes/Route.pm"),
        Arc::new(build_fa(route_pm_src)),
    );

    // Hop 1: `app` → Mojolicious. The plugin's typed Sub seeds the
    // chain. This is the single sanctioned plugin stub.
    let app_sym = app_fa
        .symbols
        .iter()
        .find(|s| {
            s.name == "app"
                && matches!(&s.namespace, Namespace::Framework { id } if id == "mojo-lite")
        })
        .expect("mojo-lite plugin must synthesize `app`");
    let rt = app_fa
        .symbol_return_type_via_bag(app_sym.id, None)
        .expect("hop 1: `app` must carry a typed return");
    assert_eq!(
        rt.class_name(),
        Some("Mojolicious"),
        "hop 1: `app` must type as Mojolicious — the one plugin stub the chain leans on"
    );

    // Hop 2: Mojolicious::routes → Mojolicious::Routes. Real
    // cross-file Mojo::Base accessor; the anon-sub default's
    // `Mojolicious::Routes->new` is lifted as the return type.
    let routes_rt = app_fa.find_method_return_type("Mojolicious", "routes", Some(&idx), None);
    assert_eq!(
        routes_rt.as_ref().and_then(|t| t.class_name()),
        Some("Mojolicious::Routes"),
        "hop 2: `Mojolicious::routes` must resolve cross-file to the real Mojo::Base \
             accessor and return Mojolicious::Routes. got: {:?}",
        routes_rt,
    );

    // Hop 3: Mojolicious::Routes::get → Mojolicious::Routes::Route.
    // Resolves via inheritance (Routes ISA Route) to the real fluent
    // method on the parent class. This is where plugin-synthesized
    // `get` from mojo-lite MUST NOT stomp.
    let get_rt = app_fa.find_method_return_type("Mojolicious::Routes", "get", Some(&idx), None);
    assert_eq!(
        get_rt.as_ref().and_then(|t| t.class_name()),
        Some("Mojolicious::Routes::Route"),
        "hop 3: `$$routes->get` must chain through the REAL \
             Mojolicious::Routes::Route::get (fluent) — not the plugin's \
             imaginary top-level `get` Sub. got: {:?}",
        get_rt,
    );

    // Hop 4: Mojolicious::Routes::Route::to → Mojolicious::Routes::Route.
    // Fluent. After this, `->name(...)`/`->via(...)`/etc. must still
    // resolve on Route — i.e. the chain keeps going, not collapses.
    let to_rt =
        app_fa.find_method_return_type("Mojolicious::Routes::Route", "to", Some(&idx), None);
    assert_eq!(
        to_rt.as_ref().and_then(|t| t.class_name()),
        Some("Mojolicious::Routes::Route"),
        "hop 4: `->to(...)` must chain through the real fluent `to` on \
             Mojolicious::Routes::Route — preserving intelligence for further \
             hops (->name, ->via, ...). got: {:?}",
        to_rt,
    );
}

/// Adversarial: a dotted helper `users.create` and a route whose
/// action is `Users#create` both end up with a Perl-level symbol
/// named `create`. They are UNRELATED:
///
///   * `users.create` lives on `Mojolicious::Controller::_Helper::users`
///     — a synthetic proxy class invented by the plugin. It's called
///     as `$c->users->create(...)`.
///   * `Users#create` points at a method `create` on the user's
///     `Users` controller class. It's called via dispatch, not
///     chained off a helper.
///
/// Name-based resolution would cross-link them (goto-def on either
/// jumps to the other, find-references unions the two unrelated
/// call sites). Class-aware resolution must keep them apart: the
/// route's MethodCallRef targets class `Users`, the helper's leaf
/// lives on `_Helper::users`.
#[test]
fn helper_and_route_with_same_leaf_name_do_not_cross_link() {
    let src = r#"
package MyApp;
use Mojolicious::Lite;

$app->helper('users.create', sub ($c, $user) {});
$app->routes->post('/users')->to(controller => 'Users', action => 'create');
"#;
    let fa = build_fa(src);

    // --- Fact-finding: what actually got emitted? ---

    // The helper leaf `create` should live on the proxy class.
    let helper_create: Vec<&Symbol> = fa
        .symbols
        .iter()
        .filter(|s| {
            s.name == "create"
                && matches!(&s.namespace, Namespace::Framework { id } if id == "mojo-helpers")
        })
        .collect();
    assert_eq!(helper_create.len(), 1, "one helper-leaf named 'create'");
    let helper_create = helper_create[0];
    assert_eq!(
        helper_create.package.as_deref(),
        Some("Mojolicious::Controller::_Helper::users"),
        "helper leaf lives on the proxy class, NOT on Users"
    );

    // The route emits a MethodCallRef method_name=create invocant=Users.
    let route_ref = fa
        .refs
        .iter()
        .find(|r| {
            matches!(&r.kind, RefKind::MethodCall { invocant, .. } if invocant == "Users")
                && r.target_name == "create"
        })
        .expect("route should emit MethodCall create@Users");

    // --- The bug: does the route's ref resolve to the helper? ---

    // If resolves_to is Some(sym_id), it MUST NOT point to the
    // helper — the helper lives on a different class.
    if let Some(target_sid) = route_ref.resolves_to {
        assert_ne!(
            target_sid, helper_create.id,
            "route MethodCall(create @ Users) must NOT resolve to the \
                 helper-leaf on _Helper::users — they share a name only"
        );
    }

    // Cross-resolution via the public API: refs_to_symbol(helper)
    // must NOT include the route's ref.
    let refs_to_helper = fa.refs_to(helper_create.id);
    for r in &refs_to_helper {
        assert_ne!(
            (r.span.start.row, r.span.start.column),
            (route_ref.span.start.row, route_ref.span.start.column),
            "route ref showed up as a reference to the helper — cross-link bug. \
                 Helper is on _Helper::users, route targets Users, they shouldn't mix."
        );
    }

    // And the mirror: resolve_method_in_ancestors on class `Users`
    // for method `create` must NOT return the helper-leaf. The
    // helper's class is _Helper::users, not Users.
    let resolution = fa.resolve_method_in_ancestors("Users", "create", None);
    if let Some(crate::file_analysis::MethodResolution::Local { sym_id, .. }) = resolution {
        assert_ne!(
            sym_id, helper_create.id,
            "resolve_method_in_ancestors(Users, create) returned the helper — \
                 class-awareness broken"
        );
    }
}

/// Helpers emitted by mojo-helpers land on Mojolicious::Controller.
/// A controller subclass in ANOTHER file (standard workspace layout)
/// must see them when walking methods — the class_content_index
/// bridges the lookup because the synthesizing module's primary
/// package isn't Mojolicious::Controller.
#[test]
fn plugin_mojo_helpers_reachable_cross_file_from_controller() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    // Lite script with a helper.
    let lite_src = r#"
package MyApp;
use Mojolicious::Lite;

my $app = Mojolicious->new;
$app->helper(greet => sub { my ($c, $who) = @_; });
"#;
    // Controller subclass in another file.
    let ctrl_src = r#"
package MyApp::Controller::Home;
use parent 'Mojolicious::Controller';
1;
"#;

    let lite_fa = Arc::new(build_fa(lite_src));
    let ctrl_fa = build_fa(ctrl_src);

    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(std::path::PathBuf::from("/tmp/MyApp.pm"), lite_fa.clone());

    // bridges_index knows MyApp.pm declares a namespace bridged to the
    // app surface (mojo-helpers' app namespace).
    let mods = idx.modules_bridging_to(crate::file_analysis::APP_SURFACE_CLASS);
    assert!(
        mods.iter().any(|m| m == "MyApp"),
        "MyApp module should be listed as bridged to the app surface; got: {:?}",
        mods
    );

    // Completion on MyApp::Controller::Home inheriting from
    // Mojolicious::Controller should walk up to the controller, cross
    // the synthetic-parent edge to the app surface, and find `greet`.
    let candidates = ctrl_fa.complete_methods_for_class("MyApp::Controller::Home", Some(&idx));
    let labels: Vec<&str> = candidates.iter().map(|c| c.label.as_str()).collect();
    assert!(
        labels.contains(&"greet"),
        "helper `greet` on the app surface in MyApp.pm should complete on \
             controller subclasses via the synthetic-parent edge; got: {:?}",
        labels
    );
}

/// mojo-helpers cross-file: when a Lite script registers a helper
/// `greet`, the resulting Method symbol's `package` is the fictional
/// app surface. Any consumer file — controller subclass, the app, or
/// otherwise — finds it via the standard workspace walk + the
/// synthetic-parent edge, without a single mojo-helpers-aware line in
/// the consumer-side code path.
#[test]
fn plugin_mojo_helpers_land_on_controller_package() {
    let src = r#"
package MyApp::Lite;
use Mojolicious::Lite;

app->helper(greet => sub {
    my ($c, $name) = @_;
    return "hello, $name";
});
1;
"#;
    let fa = build_fa(src);
    let greet = fa
        .symbols
        .iter()
        .find(|s| s.name == "greet" && s.kind == SymKind::Method)
        .expect("helper must emit a Method named greet");
    assert_eq!(
        greet.package.as_deref(),
        Some(crate::file_analysis::APP_SURFACE_CLASS),
        "helper Method is packaged on the app surface; the synthetic-parent \
             edge lets every consumer class pick it up via the inheritance walk"
    );
    assert!(matches!(&greet.namespace, Namespace::Framework { id } if id == "mojo-helpers"));
}

/// Synthetic-ancestor app surface (docs/adr/plugin-system.md): a helper
/// that returns a concrete class resolves its RETURN type identically
/// from the app, the controller, AND a user-written app subclass —
/// proving the single bridge target + synthetic-parent edge composes with
/// the MethodOnClass type-resolution walk and that subclasses inherit the
/// surface for free.
#[test]
fn plugin_mojo_helpers_return_type_via_app_surface() {
    let src = r#"
package MyApp;
use Mojolicious::Lite;

my $app = Mojolicious->new;
$app->helper(model => sub { my ($c) = @_; return MyApp::Model->new; });
"#;
    // Declare a user app subclass in the SAME file so its
    // `package_parents` edge (MyApp::Web -> Mojolicious) is present;
    // it must inherit the surface for free.
    let src = format!("{src}\npackage MyApp::Web;\nuse parent 'Mojolicious';\n1;\n");
    let fa = build_fa(&src);

    // The helper resolves its return type from the app class, the
    // controller class, AND the user app subclass.
    for class in ["Mojolicious", "Mojolicious::Controller", "MyApp::Web"] {
        let rt = fa.find_method_return_type(class, "model", None, None);
        assert_eq!(
            rt,
            Some(crate::file_analysis::InferredType::ClassName("MyApp::Model".into())),
            "`{class}->model` must return MyApp::Model via the app surface; got {rt:?}",
        );
    }
}

/// App surface (docs/adr/plugin-system.md): `$app->minion->enqueue`
/// resolves once `$app` is typed. The `minion` helper (return type a
/// Minion subclass) is reached from the locally-typed `$app` via the app
/// surface; enrichment then resolves the `->enqueue` receiver and promotes
/// the dispatch. Proves the surface composes with dispatch-verb promotion.
#[test]
fn plugin_app_surface_minion_enqueue_resolves_when_app_typed() {
    use crate::file_analysis::HandlerOwner;
    use std::path::PathBuf;
    let idx = crate::module_index::ModuleIndex::new_for_test();
    idx.register_workspace_module(
        PathBuf::from("/tmp/as_acme_minion.pm"),
        std::sync::Arc::new(build_fa("package Acme::Minion;\nuse Mojo::Base 'Minion';\n1;\n")),
    );

    // `$app` is locally typed (Mojolicious->new); the `minion` helper
    // returns an Acme::Minion. `$app->minion` reaches the helper via the
    // synthetic app-surface edge, so its return type is Acme::Minion.
    let mut fa = build_fa(
        "package MyApp;\nuse Mojolicious::Lite;\n\
         my $app = Mojolicious->new;\n\
         $app->helper(minion => sub { my ($c) = @_; return Acme::Minion->new; });\n\
         $app->minion->enqueue('send_email' => ['alice']);\n1;\n",
    );

    let mref = fa.refs.iter().find(|r| {
        matches!(&r.kind, RefKind::MethodCall { .. }) && r.target_name == "minion"
    });
    assert!(mref.is_some(), "an `$app->minion` MethodCall ref must exist");

    fa.enrich_imported_types_with_keys(Some(&idx));

    // `Mojolicious::Lite` is a trigger, so the emit-hook materializes the
    // DispatchCall directly; `applicable_dispatches` de-dups the gated
    // candidate against it. Either path surfaces the handler — exactly once.
    let has_materialized = fa.refs.iter().any(|r|
        matches!(&r.kind, RefKind::DispatchCall { dispatcher, owner: Some(HandlerOwner::Class(c)) }
            if dispatcher == "enqueue" && c == "Minion")
            && r.target_name == "send_email");
    let has_gated = fa.applicable_dispatches(Some(&idx)).iter().any(|a|
        a.name == "send_email" && a.owner == HandlerOwner::Class("Minion".into()));
    assert!(
        has_materialized ^ has_gated,
        "`$app->minion->enqueue` must surface as a Minion dispatch exactly once — \
         via the emit-hook ref OR the gated candidate; materialized={has_materialized} \
         gated={has_gated}",
    );
}

/// Helpers complete on both `$c` (Controller) and `$app` (the
/// Mojolicious app class). Every helper registers a Method on each
/// entry class, so `complete_methods_for_class` for either class
/// surfaces the helper. Dotted chain roots also land on both
/// classes; the deeper proxies stay on the shared prefix.
#[test]
fn plugin_mojo_helpers_complete_on_app_class_too() {
    let src = r#"
package MyApp;
use Mojolicious::Lite;

my $app = Mojolicious->new;
$app->helper(current_user => sub { my ($c) = @_; });
$app->helper('users.create' => sub { my ($c, $name) = @_; });
"#;
    let fa = build_fa(src);

    for class in ["Mojolicious::Controller", "Mojolicious"] {
        let candidates = fa.complete_methods_for_class(class, None);
        let labels: Vec<&str> = candidates.iter().map(|c| c.label.as_str()).collect();
        assert!(
            labels.contains(&"current_user"),
            "`current_user` must complete on {}; got: {:?}",
            class,
            labels,
        );
        assert!(
            labels.contains(&"users"),
            "`users` (dotted-helper root) must complete on {}; got: {:?}",
            class,
            labels,
        );
    }
}

/// Diagnostic pin: inside a controller action, `$c->url_for('|')`
/// must offer every named route declared in the workspace —
/// Lite paths, `Ctrl#action` pairs from `->to(...)`, and symbolic
/// `->name('foo')` handles. This is the completion side that the
/// `_emits_refs` / `_registers_url_for_handle` tests don't cover.
///
/// Discovers two separate bugs at the same time:
///   (1) Handler.owner is the *declaring* package (`MyApp`), so
///       `$c->url_for(...)` on a `Users` controller fails the
///       `owner_class == invocant_class` filter in
///       `dispatch_target_completions`.
///   (2) No coverage for "does url_for completion work at all".
#[test]
fn plugin_mojo_routes_url_for_completion_offers_route_names() {
    use tower_lsp::lsp_types::Position;
    use tree_sitter::Parser;

    let app_src = r#"package MyApp;
use Mojolicious::Lite;

my $r = app->routes;
$r->get('/users')->to('Users#list')->name('users_list');
$r->post('/users')->to(controller => 'Users', action => 'create');

get '/hello' => sub { my ($c) = @_; };
"#;
    let app_fa = std::sync::Arc::new(build_fa(app_src));

    let ctrl_src = r#"package Users;
use parent 'Mojolicious::Controller';

sub list {
    my ($c) = @_;
    my $u = $c->url_for('x');
}
"#;
    let ctrl_fa = build_fa(ctrl_src);

    let idx = std::sync::Arc::new(crate::module_index::ModuleIndex::new_for_test());
    idx.register_workspace_module(std::path::PathBuf::from("/tmp/app.pl"), app_fa);
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Users.pm"),
        std::sync::Arc::new(build_fa(ctrl_src)),
    );

    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(ctrl_src, None).unwrap();

    // Cursor on the `x` inside `url_for('x')` — `active_param == 0`.
    let pos = Position {
        line: 5,
        character: 25,
    };
    let items = crate::symbols::completion_items(&ctrl_fa, &tree, ctrl_src, pos, &idx, None);
    let labels: Vec<String> = items.iter().map(|it| it.label.clone()).collect();

    for expected in &["users_list", "Users#list", "/hello"] {
        assert!(
            labels.iter().any(|l| l == expected),
            "url_for('|') inside Users::list must offer `{}` (route declared in MyApp); got: {:?}",
            expected,
            labels
        );
    }
}

/// Red pin (user-reported): starting to type inside
/// `$c->url_for('|')` must not kill completion — the string
/// content should feed the prefix filter, not suppress it.
/// Covers two realistic live-editing shapes:
///
/// 1. `url_for('|')` — cursor between the quotes, string body
///    empty. Every route should appear (no prefix yet).
/// 2. `url_for('adm|')` — user has typed `adm`, cursor inside
///    the string, closing quote already in place (what you get
///    after auto-paired quotes). The returned list must be
///    prefix-filterable by `adm` via either `filter_text` or a
///    server-side restriction — `admin.users.purge`-style
///    named routes should survive the filter, Lite `/hello`
///    should drop out client-side.
///
/// Existing work that this pin must use, NOT re-roll:
///   * `candidate_to_completion_item` already sets
///     `filter_text = Some(label)` so the quoted `insert_text`
///     doesn't defeat client-side matching — covered by
///     `completion_dispatch_filter_text_matches_bare_name`.
///   * `mid_string_methodref_completions` handles the same
///     shape for MethodCallRefs (`->to('Users#li|')`), slicing
///     `source[span_start..cursor]` as the prefix.
#[test]
fn plugin_mojo_routes_url_for_completion_survives_typed_prefix() {
    use tower_lsp::lsp_types::Position;
    use tree_sitter::Parser;

    let app_src = r#"package MyApp;
use Mojolicious::Lite;

my $r = app->routes;
$r->get('/users')->to('Users#list')->name('users_list');
$r->get('/admin/users/purge')->to('Admin#purge')->name('admin_users_purge');

get '/hello' => sub { my ($c) = @_; };
"#;
    let app_fa = std::sync::Arc::new(build_fa(app_src));

    let idx = std::sync::Arc::new(crate::module_index::ModuleIndex::new_for_test());
    idx.register_workspace_module(std::path::PathBuf::from("/tmp/app.pl"), app_fa);

    // Case 1: empty string, cursor between the quotes.
    // `    my $u = $c->url_for('');`
    //                          ^ char 24 (opening quote)
    //                           ^ char 25 (cursor here)
    //                           ^ char 25 (closing quote)
    let empty_src = r#"package Users;
use parent 'Mojolicious::Controller';

sub list {
    my ($c) = @_;
    my $u = $c->url_for('');
}
"#;
    let empty_fa = build_fa(empty_src);
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Users_empty.pm"),
        std::sync::Arc::new(build_fa(empty_src)),
    );
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(empty_src, None).unwrap();
    let items = crate::symbols::completion_items(
        &empty_fa,
        &tree,
        empty_src,
        Position {
            line: 5,
            character: 25,
        },
        &idx,
        None,
    );
    let labels: Vec<String> = items.iter().map(|it| it.label.clone()).collect();
    for expected in &["users_list", "admin_users_purge", "Users#list", "/hello"] {
        assert!(
            labels.iter().any(|l| l == expected),
            "empty url_for('|') must offer `{}`; got: {:?}",
            expected,
            labels
        );
    }

    // Case 2: user has typed `adm`, closing quote in place.
    // `    my $u = $c->url_for('adm');`
    //                          ^ 24 opening quote
    //                           ^ 25 a
    //                            ^ 26 d
    //                             ^ 27 m — cursor here after typing
    //                              ^ 28 closing quote
    let typed_src = r#"package Users;
use parent 'Mojolicious::Controller';

sub list {
    my ($c) = @_;
    my $u = $c->url_for('adm');
}
"#;
    let typed_fa = build_fa(typed_src);
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Users_typed.pm"),
        std::sync::Arc::new(build_fa(typed_src)),
    );
    let tree = parser.parse(typed_src, None).unwrap();
    let items = crate::symbols::completion_items(
        &typed_fa,
        &tree,
        typed_src,
        Position {
            line: 5,
            character: 27,
        },
        &idx,
        None,
    );

    // Server returns the dispatch-handler set (all routes). The
    // client narrows by `filter_text` (bare label) against the
    // typed prefix `adm`. For this pin we assert the two things
    // the server owes us:
    //
    //  (a) the set still includes routes whose LABEL starts with
    //      `adm` — if the server dropped them before we got a
    //      chance to filter, completion is "dead" as the user
    //      described.
    //  (b) every returned handler's `filter_text` is set to the
    //      bare label so the client's prefix match keys on the
    //      route name, not on the quoted insert_text (`'admin...'`
    //      starts with `'`, not `a`).
    let labels: Vec<String> = items.iter().map(|it| it.label.clone()).collect();
    assert!(
        labels.iter().any(|l| l == "admin_users_purge"),
        "typed prefix `adm` must still surface `admin_users_purge` from the \
             server so client-side filter_text matching can narrow to it; got: {:?}",
        labels
    );

    let adm_item = items
        .iter()
        .find(|it| it.label == "admin_users_purge")
        .expect("admin_users_purge must be in returned items");
    assert_eq!(
        adm_item.filter_text.as_deref(),
        Some("admin_users_purge"),
        "dispatch handler `filter_text` must be the bare label so the \
             typed `adm` (no quote) matches — otherwise starting to type the \
             string kills completion",
    );
}

/// mojo-lite route URLs are referenced from `->url_for(...)` and
/// `->redirect_to(...)`. Both emit `DispatchCall` refs tight to
/// the URL string so gd/gr compose via the standard Handler
/// resolution path — no Lite-aware code in the core.
#[test]
fn plugin_mojo_lite_url_dispatch_emits_refs() {
    let src = r#"
package MyApp;
use Mojolicious::Lite;

get '/hello' => sub {
    my ($c) = @_;
    $c->render(text => 'hi');
};

sub after {
    my ($c) = @_;
    $c->redirect_to('/hello');
    my $u = $c->url_for('/hello');
}
"#;
    let fa = build_fa(src);

    let dispatch_refs: Vec<&crate::file_analysis::Ref> = fa
        .refs
        .iter()
        .filter(|r| matches!(&r.kind, RefKind::DispatchCall { .. }))
        .filter(|r| r.target_name == "/hello")
        .collect();

    let dispatchers: Vec<&str> = dispatch_refs
        .iter()
        .map(|r| match &r.kind {
            RefKind::DispatchCall { dispatcher, .. } => dispatcher.as_str(),
            _ => unreachable!(),
        })
        .collect();

    assert!(
        dispatchers.contains(&"redirect_to"),
        "redirect_to('/hello') must emit a DispatchCall ref; got: {:?}",
        dispatchers,
    );
    assert!(
        dispatchers.contains(&"url_for"),
        "url_for('/hello') must emit a DispatchCall ref; got: {:?}",
        dispatchers,
    );
}

/// Plugin triggers must gate emission. A class that doesn't inherit from
/// Mojo::EventEmitter should see no mojo-events emissions even if it
/// happens to call a method named `->on(...)`.
#[test]
fn plugin_mojo_events_triggers_gate_emission() {
    let src = r#"
package My::Unrelated;

sub new {
    my $class = shift;
    my $self = bless {}, $class;
    $self->on('connect', sub { ... });
    $self;
}

1;
"#;
    let fa = build_fa(src);
    let plugin_syms: Vec<&Symbol> = fa
        .symbols
        .iter()
        .filter(|s| {
            matches!(&s.namespace,
                Namespace::Framework { id } if id == "mojo-events")
        })
        .collect();
    assert!(
        plugin_syms.is_empty(),
        "untriggered package must not get plugin emissions; got: {:?}",
        plugin_syms.iter().map(|s| &s.name).collect::<Vec<_>>()
    );
}

/// Minion plugin: `$minion->add_task(NAME, sub { ... })` emits a
/// Handler (owner: Minion) with the task's sub params, typed $job
/// in the callback body, and a DispatchCall ref on the name.
#[test]
fn plugin_minion_add_task_registers_handler() {
    let src = r#"
package MyApp;
use Minion;

my $minion = Minion->new;
$minion->add_task(send_email => sub {
    my ($job, $to, $subject) = @_;
    $job->finish;
});
"#;
    let fa = build_fa(src);

    let handler = fa
        .symbols
        .iter()
        .find(|s| {
            s.kind == SymKind::Handler
                && s.name == "send_email"
                && matches!(&s.namespace, Namespace::Framework { id } if id == "minion")
        })
        .expect("add_task must emit a Handler named send_email");

    let SymbolDetail::Handler {
        ref owner,
        ref dispatchers,
        ref params,
        ref display,
        ..
    } = handler.detail
    else {
        panic!("handler detail should be Handler")
    };
    assert!(matches!(owner, HandlerOwner::Class(c) if c == "Minion"));
    assert!(dispatchers.iter().any(|d| d == "enqueue"));
    assert!(
        matches!(display, HandlerDisplay::Task),
        "minion tasks render as HandlerDisplay::Task (LSP kind FUNCTION, outline word 'task')"
    );
    // Callback params: $job flagged as invocant, then the rest.
    let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
    assert_eq!(names, vec!["$job", "$to", "$subject"]);
    assert!(
        params[0].is_invocant,
        "Minion::Job is the callback's invocant"
    );

    // DispatchCall on the name (registration itself is a reference).
    let dc = fa.refs.iter()
            .find(|r| matches!(&r.kind, RefKind::DispatchCall { dispatcher, .. } if dispatcher == "add_task"))
            .expect("add_task must emit a DispatchCall ref");
    assert_eq!(dc.target_name, "send_email");
}

/// `$minion->enqueue(NAME, ...)` emits a DispatchCall for the name
/// so gd/gr compose against the add_task Handler.
#[test]
fn plugin_minion_enqueue_emits_dispatch_call() {
    let src = r#"
package MyApp;
use Minion;

my $minion = Minion->new;
$minion->add_task(send_email => sub { my ($job) = @_; });
$minion->enqueue(send_email => ['alice']);
$minion->enqueue_p(send_email => ['bob']);
"#;
    let fa = build_fa(src);

    let dispatchers: Vec<&str> = fa
        .refs
        .iter()
        .filter_map(|r| match &r.kind {
            RefKind::DispatchCall { dispatcher, .. } if r.target_name == "send_email" => {
                Some(dispatcher.as_str())
            }
            _ => None,
        })
        .collect();
    assert!(
        dispatchers.contains(&"enqueue"),
        "enqueue('send_email', ...) must emit a DispatchCall; got: {:?}",
        dispatchers
    );
    assert!(
        dispatchers.contains(&"enqueue_p"),
        "enqueue_p must emit a DispatchCall too; got: {:?}",
        dispatchers
    );
}

/// Option B: a `$minion->enqueue('T')` lights up by the RECEIVER's type,
/// not the file's `use`s. `Worker` never `use`s Minion and isn't a Mojo
/// app — so the bundled minion plugin's triggers never fire, and there's no
/// `DispatchCall` after the plain build. But `$m` is a locally-constructed
/// `Acme::Minion` (isa Minion, declared cross-file), so the builder records
/// a gated candidate and `applicable_dispatches` — which has the module
/// index, hence the cross-file `isa` — resolves it at QUERY time, with no
/// enrichment. This is the "wherever the minion came from provides the magic"
/// path the file-trigger model couldn't reach.
#[test]
fn gated_dispatch_resolves_on_subclass_receiver_query_time() {
    use crate::file_analysis::HandlerOwner;
    use std::path::PathBuf;
    let base = build_fa("package Acme::Minion;\nuse Mojo::Base 'Minion';\n1;\n");
    let idx = crate::module_index::ModuleIndex::new_for_test();
    idx.register_workspace_module(
        PathBuf::from("/tmp/b_acme_minion.pm"),
        std::sync::Arc::new(base),
    );

    let fa = build_fa(
        "package Worker;\nsub go {\n  my $m = Acme::Minion->new;\n  $m->enqueue('send_email' => ['a']);\n}\n1;\n",
    );
    // The triggers never fired, so nothing was materialized at parse time.
    assert!(
        !fa.refs.iter().any(|r| matches!(&r.kind, RefKind::DispatchCall { .. })),
        "no DispatchCall ref should exist (plugin trigger didn't fire)",
    );

    // No enrichment — query-time resolution alone surfaces the dispatch,
    // exactly as a non-open workspace file would be served.
    let applied = fa.applicable_dispatches(Some(&idx));
    assert_eq!(
        applied.iter().filter(|a|
            a.name == "send_email" && a.owner == HandlerOwner::Class("Minion".into())).count(),
        1,
        "query-time resolution must surface exactly one Minion dispatch for \
         enqueue on a Minion-subclass receiver, even with no enrichment; got {:?}",
        applied,
    );
}

/// The receiver isn't locally typed — it's a cross-file method-call return
/// (`$b->minion` where `Box::minion` returns an `Acme::Minion`). The
/// build-time hint is `None`; query-time resolution resolves the invocant
/// cross-file (via the module index) and, finding it isa Minion, surfaces the
/// dispatch. This is the `$self->_minion->enqueue(...)` shape — works whenever
/// the receiver's type is actually resolvable.
#[test]
fn gated_dispatch_resolves_cross_file_receiver_query_time() {
    use crate::file_analysis::HandlerOwner;
    use std::path::PathBuf;
    let idx = crate::module_index::ModuleIndex::new_for_test();
    idx.register_workspace_module(
        PathBuf::from("/tmp/b_acme_minion.pm"),
        std::sync::Arc::new(build_fa("package Acme::Minion;\nuse Mojo::Base 'Minion';\n1;\n")),
    );
    idx.register_workspace_module(
        PathBuf::from("/tmp/b_box.pm"),
        std::sync::Arc::new(build_fa(
            "package Box;\nsub new { bless {}, shift }\nsub minion ($self) { return Acme::Minion->new; }\n1;\n",
        )),
    );

    let fa = build_fa(
        "package Worker;\nsub go {\n  my $b = Box->new;\n  $b->minion->enqueue('send_email' => ['a']);\n}\n1;\n",
    );

    // No enrichment: the gate resolves the cross-file receiver lazily.
    let applied = fa.applicable_dispatches(Some(&idx));
    assert!(
        applied.iter().any(|a|
            a.name == "send_email" && a.owner == HandlerOwner::Class("Minion".into())),
        "query-time resolution must resolve the cross-file receiver `$b->minion` \
         (Acme::Minion isa Minion) and surface the dispatch; got {:?}",
        applied,
    );
}

/// A Minion SUBCLASS receiver (`Acme::Minion` isa Minion, the crm
/// `Clove::Minion` shape) must still register + dispatch tasks. The
/// receiver types to `ClassName("Acme::Minion")`, which a name-prefix
/// allowlist (`== "Minion" || starts_with("Minion::")`) silently rejects —
/// the rule-#10 trap. The plugin no longer gates on receiver class, so the
/// Handler (owner Minion) and the enqueue DispatchCall pair as usual.
#[test]
fn plugin_minion_subclass_receiver_still_wires() {
    let src = r#"
package MyApp;
use Minion;

my $minion = Acme::Minion->new;
$minion->add_task(send_email => sub { my ($job) = @_; });
$minion->enqueue(send_email => ['alice']);
"#;
    let fa = build_fa(src);

    let handler = fa.symbols.iter().find(|s| {
        s.kind == SymKind::Handler
            && s.name == "send_email"
            && matches!(&s.detail, SymbolDetail::Handler { owner: HandlerOwner::Class(c), .. } if c == "Minion")
    });
    assert!(
        handler.is_some(),
        "add_task on a Minion subclass receiver must still register a Minion-owned Handler",
    );

    let has_enqueue_dc = fa.refs.iter().any(|r| matches!(
        &r.kind, RefKind::DispatchCall { dispatcher, .. }
        if dispatcher == "enqueue" && r.target_name == "send_email"
    ));
    assert!(
        has_enqueue_dc,
        "enqueue on a Minion subclass receiver must still emit a DispatchCall",
    );
}

/// $job inside an add_task callback is typed as Minion::Job so
/// completion on $job-> resolves to Minion::Job methods.
#[test]
fn plugin_minion_types_job_inside_task_body() {
    let src = r#"
package MyApp;
use Minion;

my $minion = Minion->new;
$minion->add_task(send_email => sub {
    my ($job) = @_;
    $job->finish;
});
"#;
    let fa = build_fa(src);

    // `$job` should be typed Minion::Job inside the callback —
    // plugin-declared ClassName, not builder's FirstParam.
    let ty = fa
        .inferred_type("$job", tree_sitter::Point::new(8, 0))
        .expect("$job must carry a type inside add_task callback");
    assert!(
        matches!(ty, InferredType::ClassName(c) if c == "Minion::Job"),
        "type should be plugin-declared ClassName(Minion::Job), got {:?}",
        ty,
    );
}

/// Minion's `enqueue` options go in a hashref at position 3
/// (`enqueue(task, [args], {priority => 10})`). The plugin emits
/// HashKeyDefs for the common keys owned by Sub{Minion,enqueue}
/// — what's missing is cursor-context routing for "hash literal
/// as positional arg" → `HashKey { source_sub: "enqueue" }`.
/// Skipped until the core learns that shape; the emission side is
/// pinned here so regressing it trips.
#[test]
fn plugin_minion_enqueue_options_hashkeys_emitted() {
    let src = r#"
package MyApp;
use Minion;

my $minion = Minion->new;
$minion->enqueue(task_x => ['arg'] => { priority => 10 });
"#;
    let fa = build_fa(src);

    // Options emitted as HashKeyDef symbols owned by Sub{Minion, enqueue}.
    let option_names: Vec<&str> = fa
        .symbols
        .iter()
        .filter(|s| {
            s.kind == SymKind::HashKeyDef
                && matches!(&s.namespace, Namespace::Framework { id } if id == "minion")
        })
        .map(|s| s.name.as_str())
        .collect();
    for expected in &[
        "priority", "queue", "delay", "attempts", "notes", "parents", "expire", "lax",
    ] {
        assert!(
            option_names.contains(expected),
            "enqueue option `{}` must be emitted; got: {:?}",
            expected,
            option_names
        );
    }
}

/// Cross-file helper chain completion: Users.pm inherits from
/// Mojolicious::Controller; helpers declared in a sibling Lite
/// file register Methods on Controller. From Users.pm, cursor at
/// `$c->`, `$c->users->`, `$c->admin->` must all resolve through
/// the proxy classes even though the methods live in another
/// file and the CPAN-cached Controller doesn't know about them.
///
/// Regression trigger: `resolve_method_in_ancestors` used to scan
/// only `get_cached(class)` cross-file, missing plugin-emitted
/// methods that live in other modules under the same `package`.
/// `detect_cursor_context_tree` also only called `resolve_expression_type`
/// without a module_index, so chain resolution of `$c->users->`
/// fell through to the untyped fallback and returned Users's own
/// methods (list, create) instead of the proxy chain's leaves.
#[test]
fn plugin_mojo_helpers_cross_file_chain_completion() {
    use tower_lsp::lsp_types::Position;
    use tree_sitter::Parser;

    // The Lite file — declares the helpers.
    let lite_src = r#"package MyApp;
use strict;
use warnings;
use Mojolicious::Lite;

my $app = Mojolicious->new;

$app->helper(current_user => sub { my ($c, $fallback) = @_; });
$app->helper('users.create' => sub { my ($c, $name, $email) = @_; });
$app->helper('users.delete' => sub { my ($c, $id) = @_; });
$app->helper('admin.users.purge' => sub { my ($c, $force) = @_; });
"#;
    let lite_fa = build_fa(lite_src);

    // The controller file — inherits from Mojolicious::Controller
    // and expects to reach the helpers cross-file. This is where
    // the user's `$c->` completion is happening in real life.
    let src = r#"package Users;
use strict;
use warnings;
use parent 'Mojolicious::Controller';

sub list {
    my ($c) = @_;
    $c->;
    $c->users->;
    $c->admin->;
}
"#;
    let fa = build_fa(src);

    // Sanity — Users.pm's own analysis has `list` but not the
    // helpers (they're declared in the Lite file).
    let users_subs: Vec<&str> = fa
        .symbols
        .iter()
        .filter(|s| matches!(s.kind, SymKind::Method | SymKind::Sub))
        .map(|s| s.name.as_str())
        .collect();
    assert_eq!(users_subs, vec!["list"], "Users.pm owns only `list`");

    // Now simulate the nvim completion pipeline at `$c->` position.
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();

    // Populate a ModuleIndex with a mock Mojolicious::Controller
    // that has a few native-looking methods (render, stash, etc.).
    // Matches the user's env where CPAN Mojolicious is installed
    // and its Controller is cached cross-file. Register the Lite
    // script itself too — workspace indexer would.
    // Workspace has BOTH files registered — mirrors nvim startup
    // after Rayon indexes the .pm/.pl set.
    let idx = std::sync::Arc::new(crate::module_index::ModuleIndex::new_for_test());
    let lite_fa = std::sync::Arc::new(lite_fa);
    idx.register_workspace_module(std::path::PathBuf::from("/tmp/MyApp.pm"), lite_fa.clone());
    let users_fa = std::sync::Arc::new(build_fa(src));
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/lib/Users.pm"),
        users_fa.clone(),
    );

    let ctrl_src = r#"package Mojolicious::Controller;
sub render { my ($self, %args) = @_; }
sub stash { my ($self, $key) = @_; }
sub req { my ($self) = @_; }
sub res { my ($self) = @_; }
sub session { my ($self, $key) = @_; }
1;
"#;
    let ctrl_fa = std::sync::Arc::new(build_fa(ctrl_src));
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Mojolicious/Controller.pm"),
        ctrl_fa,
    );

    // The workspace knows the Lite file declares a namespace bridged
    // to the app surface (the mojo-helpers app namespace emits
    // `Bridge::Class(APP_SURFACE_CLASS)`). The controller reaches it
    // through the synthetic-parent edge in the ancestor walk.
    let mods = idx.modules_bridging_to(crate::file_analysis::APP_SURFACE_CLASS);
    assert!(
        mods.iter().any(|m| m == "MyApp"),
        "workspace index must list MyApp.pm bridged to the app surface; got: {:?}",
        mods
    );

    // Part 1: `$c->` completion in Users.pm surfaces both the
    // inherited native methods AND the plugin-emitted helpers
    // (cross-file, via the app namespace's Class(Controller) bridge).
    let pos = |row: u32, col: u32| Position {
        line: row,
        character: col,
    };
    let call_label_set = |items: &[tower_lsp::lsp_types::CompletionItem]| -> Vec<String> {
        items.iter().map(|it| it.label.clone()).collect()
    };

    let items = crate::symbols::completion_items(&fa, &tree, src, pos(7, 8), &idx, None);
    let labels = call_label_set(&items);
    for expected in &["list", "render", "stash", "current_user", "users", "admin"] {
        assert!(
            labels.iter().any(|l| l == expected),
            "$c-> must offer `{}`; got: {:?}",
            expected,
            labels
        );
    }

    // Part 2: `$c->users->` (chained cross-file) resolves to the
    // _Helper::users proxy and surfaces its leaves. Before the
    // fix: cursor_context couldn't resolve the chain without a
    // module_index, so completion fell through to Users's own
    // methods (`list`).
    let items = crate::symbols::completion_items(&fa, &tree, src, pos(8, 15), &idx, None);
    let labels = call_label_set(&items);
    assert_eq!(
        labels.iter().collect::<std::collections::HashSet<_>>(),
        ["create", "delete"]
            .iter()
            .map(|s| s.to_string())
            .collect::<Vec<_>>()
            .iter()
            .collect::<std::collections::HashSet<_>>(),
        "$c->users-> must offer exactly the helper chain leaves (create/delete); got: {:?}",
        labels,
    );
    assert!(
        !labels.iter().any(|l| l == "list"),
        "$c->users-> must NOT fall back to Users.pm's own `list`; got: {:?}",
        labels
    );

    // Part 3: `$c->admin->` resolves through the first-level proxy
    // to the innermost `users` step.
    let items = crate::symbols::completion_items(&fa, &tree, src, pos(9, 15), &idx, None);
    let labels = call_label_set(&items);
    assert_eq!(
        labels,
        vec!["users"],
        "$c->admin-> must offer exactly `users`; got: {:?}",
        labels
    );

    // Part 4: the proxy's detail is suppressed (opaque_return).
    // No `_Helper::...` string should leak into the user-facing
    // detail of a helper-root completion entry, even cross-file.
    let items = crate::symbols::completion_items(&fa, &tree, src, pos(7, 8), &idx, None);
    let users_item = items.iter().find(|it| it.label == "users").unwrap();
    let admin_item = items.iter().find(|it| it.label == "admin").unwrap();
    for (name, item) in [("users", users_item), ("admin", admin_item)] {
        let d = item.detail.as_deref().unwrap_or("");
        assert!(
            !d.contains("_Helper"),
            "opaque_return must suppress proxy class in `{}`'s detail cross-file; got: {:?}",
            name,
            d
        );
    }

    // Part 5: no "unresolved-method" diagnostic for helper calls
    // that now resolve cross-file. The diagnostic builder walks
    // resolve_method_in_ancestors; our fix extends that to pick
    // up plugin-emitted methods on parent classes declared
    // elsewhere in the workspace.
    let diags = crate::symbols::collect_diagnostics(&fa, &idx, Default::default());
    for diag in &diags {
        let msg = &diag.message;
        assert!(
            !msg.contains("'users' is not defined"),
            "no diagnostic for helper middle hop `users`; got: {}",
            msg
        );
        assert!(
            !msg.contains("'admin' is not defined"),
            "no diagnostic for helper middle hop `admin`; got: {}",
            msg
        );
        assert!(
            !msg.contains("'current_user' is not defined"),
            "no diagnostic for helper `current_user`; got: {}",
            msg
        );
    }
}

/// documentHighlight on a method-call identifier must highlight
/// JUST the method name, not the whole `$obj->method(...)` span.
/// Before this pin: hovering `helper` on one `$app->helper(NAME =>
/// sub { ... })` site underlined every other registration's full
/// multi-line call expression — args, sub bodies, closing `);`
/// all included. Regression trigger: MethodCall ref.span covers
/// the whole call (needed for gd/ref_at inside-args lookup);
/// highlight path now uses `method_name_span` from the ref kind.
#[test]
fn method_call_highlight_uses_method_name_span_only() {
    let src = r#"package MyApp;
sub do_thing { }
sub run {
    my ($self, $x) = @_;
    $self->do_thing($x, 1, 2);
    $self->do_thing(3);
}
"#;
    let fa = build_fa(src);

    // Cursor on `do_thing` at the first call site. Highlight
    // must return ranges whose width == len("do_thing"), never
    // a range that spans past the closing `)` or crosses into
    // the next line.
    let row = 4; // 0-indexed: `    $self->do_thing($x, 1, 2);`
    let col = src.lines().nth(row).unwrap().find("do_thing").unwrap();
    let point = tree_sitter::Point::new(row, col + 1);

    let hits = fa.find_highlights(point, None);
    assert!(!hits.is_empty(), "should highlight at least one occurrence");

    for (span, _access) in &hits {
        // Must be single-line + width exactly 8 ("do_thing").
        assert_eq!(
            span.start.row, span.end.row,
            "highlight must not span multiple lines; got: {:?}",
            span
        );
        let width = span.end.column - span.start.column;
        assert_eq!(
            width,
            "do_thing".len(),
            "highlight width must match method identifier; got {}: {:?}",
            width,
            span
        );
    }
}

/// `$app->admin->` (chained helper call) completion returns the
/// proxy class's methods — not the fallback full-file list.
/// Validates that `resolve_expression_type` chains through the
/// plugin-synthesized opaque return and
/// `complete_methods_for_class` finds methods on the proxy.
#[test]
fn plugin_mojo_helpers_chained_proxy_completion() {
    let src = r#"
package MyApp;
use Mojolicious::Lite;

my $app = Mojolicious->new;
$app->helper('admin.users.purge' => sub { my ($c, $force) = @_; });
"#;
    let fa = build_fa(src);

    // 1. `$app->admin` resolves to the first-level proxy.
    let admin_proxy = fa
        .find_method_return_type("Mojolicious", "admin", None, None)
        .expect("admin on Mojolicious has a return_type");
    let admin_class = admin_proxy
        .class_name()
        .expect("proxy return_type is a ClassName");
    assert_eq!(admin_class, "Mojolicious::Controller::_Helper::admin");

    // 2. `$app->admin->` completion shows the `users` proxy step.
    let candidates = fa.complete_methods_for_class(admin_class, None);
    let labels: Vec<&str> = candidates.iter().map(|c| c.label.as_str()).collect();
    assert!(
        labels.contains(&"users"),
        "chain completion on admin proxy must surface `users`; got: {:?}",
        labels
    );
    // And the `users` step's detail must NOT leak the internal
    // `_Helper::admin::users` proxy class name — the plugin
    // declared the return type opaque.
    let users_cand = candidates.iter().find(|c| c.label == "users").unwrap();
    assert!(
        !users_cand
            .detail
            .as_deref()
            .unwrap_or("")
            .contains("_Helper"),
        "opaque_return must hide the proxy class from detail: {:?}",
        users_cand.detail,
    );

    // 3. Two levels in — `$app->admin->users` → the innermost proxy.
    let users_proxy = fa
        .find_method_return_type(admin_class, "users", None, None)
        .expect("users on admin proxy has a return_type");
    let users_class = users_proxy.class_name().unwrap();
    assert_eq!(
        users_class,
        "Mojolicious::Controller::_Helper::admin::users"
    );

    // 4. Leaf completion shows `purge`.
    let leaf_candidates = fa.complete_methods_for_class(users_class, None);
    let leaf_labels: Vec<&str> = leaf_candidates.iter().map(|c| c.label.as_str()).collect();
    assert!(
        leaf_labels.contains(&"purge"),
        "leaf proxy must offer `purge`; got: {:?}",
        leaf_labels
    );
}

// ==== Three tests pinning this round's user-facing contracts. ====
//
// They begin RED and get fixed one at a time below. Shape of each is
// "source code + cursor position + real-pipeline assertion" so we
// can't lie about internal function results passing while the LSP
// experience breaks.

/// Outline detail names the semantic kind, LSP kind stays FUNCTION
/// (user config can render an icon for the domain word). Terminal
/// URL handlers (mojo-lite `get '/x' => sub {}`) are `<route>`;
/// routing hops (`->to('Users#list')`) are `<dispatch>` — those
/// two are semantically different and must not collapse. Tasks
/// stay `<task>`, helpers stay `<helper>`, events stay EVENT.
#[test]
fn outline_detail_names_the_semantic_kind() {
    use tower_lsp::lsp_types::SymbolKind;
    let src = r#"package MyApp;
use Mojolicious::Lite;

my $app = Mojolicious->new;
$app->helper(current_user => sub { my ($c) = @_; });

my $r = app->routes;
$r->get('/x')->to('Users#list');
get '/home' => sub { my $c = shift; };

use Minion;
my $minion = Minion->new;
$minion->add_task(send_email => sub { my ($job) = @_; });

package MyEmitter;
use parent 'Mojo::EventEmitter';
sub new {
    my $self = bless {}, shift;
    $self->on('ready', sub { my ($s) = @_; });
    $self;
}
"#;
    let fa = build_fa(src);
    let outline = fa.document_symbols();

    fn flatten<'a>(
        out: &'a [crate::file_analysis::OutlineSymbol],
        acc: &mut Vec<&'a crate::file_analysis::OutlineSymbol>,
    ) {
        for s in out {
            acc.push(s);
            flatten(&s.children, acc);
        }
    }
    let mut all = Vec::new();
    flatten(&outline, &mut all);

    let lsp_kind = |os: &crate::file_analysis::OutlineSymbol| -> SymbolKind {
        crate::symbols::outline_lsp_kind(os)
    };

    let helper = all
        .iter()
        .find(|s| s.name.contains("current_user"))
        .expect("helper must be in outline of its declaring file");
    assert_eq!(lsp_kind(helper), SymbolKind::FUNCTION);
    assert!(
        helper.detail.as_deref().unwrap_or("").contains("helper"),
        "helper outline detail must contain 'helper'; got: {:?}",
        helper.detail
    );

    // Terminal route: body lives here, `<route>` word.
    let term_route = all
        .iter()
        .find(|s| s.name.contains("/home"))
        .expect("mojo-lite terminal route must be in outline");
    assert_eq!(lsp_kind(term_route), SymbolKind::FUNCTION);
    assert_eq!(
        term_route.detail.as_deref(),
        Some("route"),
        "terminal mojo-lite route word is 'route'; got: {:?}",
        term_route.detail
    );

    // Controller action (`->to('Users#list')`): no body at this
    // site, just a cross-reference into Users::list. Word must be
    // `action`, not `route` — `<route> GET /x` and `<action>
    // Users#list` are semantically different line items.
    let action = all
        .iter()
        .find(|s| s.name.contains("Users#list"))
        .expect("->to('Users#list') action must be in outline");
    assert_eq!(lsp_kind(action), SymbolKind::FUNCTION);
    assert_eq!(
        action.detail.as_deref(),
        Some("action"),
        "->to(...) word is 'action' (distinct from a terminal route); got: {:?}",
        action.detail
    );

    let task = all
        .iter()
        .find(|s| s.name.contains("send_email"))
        .expect("task must be in outline of its declaring file");
    assert_eq!(lsp_kind(task), SymbolKind::FUNCTION);
    assert!(
        task.detail.as_deref().unwrap_or("").contains("task"),
        "task outline detail must contain 'task'; got: {:?}",
        task.detail
    );

    let event = all
        .iter()
        .find(|s| s.name.contains("ready"))
        .expect("event must be in outline of its declaring file");
    assert_eq!(
        lsp_kind(event),
        SymbolKind::EVENT,
        "events stay EVENT — the one LSP kind that fits"
    );
}

/// `sub get { shift->_generate_route(GET => @_) }` — the Mojo
/// Routes::Route pattern. `shift` in the invocant position of a
/// method call within a method body means `$self`, so the chain
/// invocant class must resolve to the enclosing package.
///
/// Without this, every HTTP-verb method on Mojolicious::Routes::Route
/// has an unknowable chain and `$r->get(...)->to(...)` loses
/// intelligence at the `->to` hop.
#[test]
fn shift_as_self_in_method_body_resolves_to_current_package() {
    let src = r#"
package Mojolicious::Routes::Route;

sub get { shift->_generate_route(GET => @_) }

sub _generate_route {
    my $self = shift;
    return $self;
}
"#;
    let fa = build_fa(src);

    // The MethodCall ref for `_generate_route` (inside `get`'s body)
    // must carry `invocant_class = Mojolicious::Routes::Route` —
    // proving the build-time chain resolver treated `shift` as
    // `$self` and looked up the enclosing package.
    let gr_ref = fa
        .refs
        .iter()
        .find(|r| {
            matches!(r.kind, RefKind::MethodCall { .. }) && r.target_name == "_generate_route"
        })
        .expect("MethodCall ref for `_generate_route`");

    if matches!(gr_ref.kind, RefKind::MethodCall { .. }) {
        let invocant_class = fa.method_call_invocant_class(gr_ref, None);
        assert_eq!(
            invocant_class.as_deref(),
            Some("Mojolicious::Routes::Route"),
            "`shift->_generate_route` must resolve its invocant to \
                 the enclosing package. got invocant_class: {:?}",
            invocant_class,
        );
    } else {
        panic!("expected MethodCall ref");
    }
}

/// `sub is_endpoint { $_[0]->inline ? undef : ... }` — Mojo uses
/// `$_[0]` instead of `shift` on hot paths where the shift's arg-
/// list mutation is expensive. Same self-tell as `shift`.
#[test]
fn dollar_underscore_zero_as_self_resolves_to_current_package() {
    let src = r#"
package Mojolicious::Routes::Route;

sub is_endpoint {
    $_[0]->inline;
}

sub inline {
    my $self = shift;
    return $self;
}
"#;
    let fa = build_fa(src);

    let inline_ref = fa
        .refs
        .iter()
        .find(|r| matches!(r.kind, RefKind::MethodCall { .. }) && r.target_name == "inline")
        .expect("MethodCall ref for `inline`");

    if matches!(inline_ref.kind, RefKind::MethodCall { .. }) {
        let invocant_class = fa.method_call_invocant_class(inline_ref, None);
        assert_eq!(
            invocant_class.as_deref(),
            Some("Mojolicious::Routes::Route"),
            "`$$_[0]->inline` must resolve its invocant to the \
                 enclosing package. got invocant_class: {:?}",
            invocant_class,
        );
    } else {
        panic!("expected MethodCall ref");
    }
}

/// Regression for the crash reported in the nvim LSP log:
/// `thread 'tokio-rt-worker' panicked at src/file_analysis.rs:1164:44:
/// index out of bounds: the len is 17 but the index is 17`.
///
/// Root cause: `enrich_imported_types_with_keys` truncates
/// `type_constraints` back to baseline but leaves stale indices in
/// `type_constraints_by_var` from the previous enrichment. The next
/// enrichment's call to `resolve_method_call_types` invokes
/// `inferred_type`, which indexes into `type_constraints[idx]` —
/// OOB when idx points past the truncated length.
///
/// Repro: enrich the same FileAnalysis twice with a module_index.
/// The second call must not panic.
#[test]
fn enrichment_twice_does_not_crash_on_stale_indices() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    let app_src = r#"
package main;
use Mojolicious::Lite;

my $r = app->routes;
$r->get('/users')->to('Users#list');
"#;
    let mojolicious_pm = r#"
package Mojolicious;
use Mojo::Base -base;
has routes => sub { Mojolicious::Routes->new };
1;
"#;
    let routes_pm = r#"
package Mojolicious::Routes;
use Mojo::Base 'Mojolicious::Routes::Route';
1;
"#;
    let route_pm = r#"
package Mojolicious::Routes::Route;
use Mojo::Base -base;
sub get { my $self = shift; return $self; }
sub to  { my $self = shift; return $self; }
1;
"#;

    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Mojolicious.pm"),
        Arc::new(build_fa(mojolicious_pm)),
    );
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Mojolicious/Routes.pm"),
        Arc::new(build_fa(routes_pm)),
    );
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Mojolicious/Routes/Route.pm"),
        Arc::new(build_fa(route_pm)),
    );

    let mut fa = build_fa(app_src);
    // First enrichment — simulates publish_diagnostics after module
    // resolution. Populates type_constraints + type_constraints_by_var.
    fa.enrich_imported_types_with_keys(Some(&idx));
    // Second enrichment — simulates a subsequent change or refresh.
    // Before the fix, the stale type_constraints_by_var indices
    // panicked `inferred_type` during resolve_method_call_types.
    fa.enrich_imported_types_with_keys(Some(&idx));

    // Sanity: `$r` is still typed after the second run (not just
    // "didn't crash" — the state is actually usable).
    let r_type = fa.inferred_type_via_bag("$r", tree_sitter::Point { row: 5, column: 0 });
    assert!(
        r_type.as_ref().and_then(|t| t.class_name()) == Some("Mojolicious::Routes"),
        "after two enrichments, $$r should still be typed as Mojolicious::Routes; got: {:?}",
        r_type,
    );
}

/// Real-file invariant: every meaningful token on the
/// `app->routes` / `$r->get(...)->to(...)` lines of the mojo demo
/// must surface a useful hover AND a useful goto-def. This is the
/// exact scenario the user reports dead in nvim — hover returns
/// nothing, gd has nowhere to go.
///
/// Probes (all on the actual demo file, not a synthetic snippet):
///   * `app`    in `my $r = app->routes;`         → hover mentions Mojolicious; gd lands somewhere
///   * `routes` in `app->routes`                  → hover mentions routes / Mojolicious::Routes; gd into Mojolicious.pm
///   * `$r`     in `$r->get(...)`                 → hover shows the declaration line
///   * `get`    in `$r->get(...)`                 → hover mentions the real Route::get POD; gd into Route.pm
///   * `to`     in `->to('Users#list')`           → hover mentions Route::to; gd into Route.pm
///
/// Any probe returning `None` for BOTH hover and gd is a bug. The
/// test enumerates each probe independently so failures pinpoint
/// which hop of the chain is broken, not "something somewhere".
#[test]
fn mojo_demo_lines_70_71_all_tokens_intelligent() {
    use crate::module_index::ModuleIndex;
    use std::sync::Arc;

    let path =
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("test_files/plugin_mojo_demo.pl");
    let src = std::fs::read_to_string(&path).unwrap();
    let fa = build_fa(&src);
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let _tree = parser.parse(&src, None).unwrap();

    // Stub the three Mojo modules the chain walks through so
    // cross-file resolution has something to reach. Shapes mirror
    // the real @INC modules' method signatures.
    let mojolicious_pm = r#"
package Mojolicious;
use Mojo::Base -base;

=head2 routes

Returns the router.

=cut

has routes => sub { Mojolicious::Routes->new };

=head2 helper

Register a helper.

=cut

sub helper { my $self = shift; }
1;
"#;
    let routes_pm = r#"
package Mojolicious::Routes;
use Mojo::Base 'Mojolicious::Routes::Route';
1;
"#;
    let route_pm = r#"
package Mojolicious::Routes::Route;
use Mojo::Base -base;

=head2 get

  my $route = $r->get('/:foo' => sub ($c) {...});

Generate route matching only C<GET> requests.

=cut

sub get { my $self = shift; return $self; }

=head2 to

  $r->to('Users#list');

Set the route's target.

=cut

sub to { my $self = shift; return $self; }
1;
"#;

    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Mojolicious.pm"),
        Arc::new(build_fa(mojolicious_pm)),
    );
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Mojolicious/Routes.pm"),
        Arc::new(build_fa(routes_pm)),
    );
    idx.register_workspace_module(
        std::path::PathBuf::from("/tmp/Mojolicious/Routes/Route.pm"),
        Arc::new(build_fa(route_pm)),
    );

    // Cross-file enrichment — mirrors `Backend::enrich_analysis`.
    // Without this pass, MethodCallBindings whose resolution needs
    // a cross-file return type (e.g. `$r = app->routes` needs real
    // Mojolicious.pm's `routes` accessor) don't land in
    // `type_constraints`, and `$r` stays untyped.
    let mut fa = fa;
    fa.enrich_imported_types_with_keys(Some(&idx));
    let fa = fa;

    // Locate the two target lines by content — decoupled from
    // absolute row numbers so reformats don't invalidate the test.
    let (row_app_routes, line_app_routes) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("my $r = app->routes;"))
        .map(|(i, l)| (i, l))
        .expect("demo must contain `my $r = app->routes;`");
    let (row_r_get_to, line_r_get_to) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("$r->get('/users')->to('Users#list');"))
        .map(|(i, l)| (i, l))
        .expect("demo must contain `$r->get('/users')->to('Users#list');`");

    // Column helper — cursor one char into the token, not at its start,
    // so `ref_at` / `symbol_at` hit the token reliably.
    let col_of =
        |line: &str, needle: &str| -> usize { line.find(needle).expect("needle in line") + 1 };
    let probe = |row: usize, col: usize| tree_sitter::Point { row, column: col };

    // Per-probe assertion. Any probe where BOTH hover and gd come
    // back empty is a dead token — the user's reported symptom.
    // Print detailed per-probe status so failures pinpoint the hop.
    let check = |label: &str, point: tree_sitter::Point| {
        let hover = fa.hover_info(point, &src, Some(&idx));
        let def = fa.find_definition(point, Some(&idx));
        assert!(
            hover.is_some() || def.is_some(),
            "[{label}] @ ({},{}) is a dead token — NO hover AND NO gd. \
                 Chain-resolution hit a wall here. src: {:?}",
            point.row,
            point.column,
            src.lines().nth(point.row).unwrap_or("<oob>"),
        );
    };

    // Line 70 probes.
    check(
        "app bareword",
        probe(row_app_routes, col_of(line_app_routes, "app")),
    );
    check(
        "routes accessor",
        probe(row_app_routes, col_of(line_app_routes, "routes")),
    );

    // Line 71 probes.
    check(
        "$r receiver",
        probe(row_r_get_to, col_of(line_r_get_to, "$r")),
    );
    check(
        "get method",
        probe(row_r_get_to, col_of(line_r_get_to, "->get") + 2),
    ); // skip "->"
    check(
        "to method",
        probe(row_r_get_to, col_of(line_r_get_to, "->to") + 2),
    );

    // Focused assertions on `app`:
    //   1. Hover surfaces the plugin's `app` Sub doc — i.e. ref_at
    //      resolves to the narrow FunctionCall ref for the bareword,
    //      NOT the wider MethodCall ref that would describe `routes`.
    //   2. A semantic token lands on the bareword span — the user
    //      reported no highlight on `app->` in nvim; the narrow
    //      FunctionCall ref is what feeds semantic tokens.
    let app_point = probe(row_app_routes, col_of(line_app_routes, "app"));
    let app_hover = fa.hover_info(app_point, &src, Some(&idx));
    let app_hover_text = app_hover.as_deref().unwrap_or("");
    assert!(
        app_hover_text.contains("The Mojolicious application instance"),
        "hover on `app` must surface the plugin-emitted Sub's doc \
             — proving ref_at picked the narrow FunctionCall ref, not \
             the outer MethodCall for `routes`. got: {:?}",
        app_hover,
    );

    // Semantic token on the bareword — any token kind is fine, the
    // point is SOMETHING lights it up.
    let tokens = fa.semantic_tokens();
    let app_row = row_app_routes;
    let app_col_start = line_app_routes.find("app").unwrap();
    let app_col_end = app_col_start + "app".len();
    let app_has_token = tokens.iter().any(|t| {
        t.span.start.row == app_row
            && t.span.start.column == app_col_start
            && t.span.end.column == app_col_end
    });
    assert!(
        app_has_token,
        "semantic token must fire on the `app` bareword span — \
             user reported no highlight and traced it to a missing \
             Ref at the invocant. tokens near row {}: {:?}",
        app_row,
        tokens
            .iter()
            .filter(|t| t.span.start.row == app_row)
            .collect::<Vec<_>>(),
    );

    // Headline chain assertion: `$r` MUST be typed as
    // Mojolicious::Routes after the `my $r = app->routes;` line.
    // This is the single most important observable — without it,
    // every `$r->...` downstream loses intelligence (precisely
    // the user's report). `inferred_type` is the same query
    // resolve_invocant_class uses for method resolution, so if
    // this says None, nothing on line 71 can work.
    let r_point = probe(row_r_get_to, col_of(line_r_get_to, "$r"));
    let r_type = fa.inferred_type_via_bag("$r", r_point);
    assert_eq!(
        r_type.as_ref().and_then(|t| t.class_name()),
        Some("Mojolicious::Routes"),
        "`$$r` must be typed as Mojolicious::Routes at the `$$r->get` \
             call site. Without this, the rest of line 71 is dead. got: {:?}",
        r_type,
    );

    // `$r->get` must resolve via inheritance (Mojolicious::Routes
    // ISA Mojolicious::Routes::Route) to the real `get` method.
    // Return type is fluent — stays on Route for `->to` to work.
    let get_rt = fa.find_method_return_type("Mojolicious::Routes", "get", Some(&idx), None);
    assert_eq!(
        get_rt.as_ref().and_then(|t| t.class_name()),
        Some("Mojolicious::Routes::Route"),
        "`$$r->get` must resolve to Mojolicious::Routes::Route::get \
             via inheritance. got: {:?}",
        get_rt,
    );
}

/// Real-file invariant pinning the original nvim repro: line 118
/// of plugin_mojo_demo.pl, which sits textually in `package MyApp`
/// but before the fix was reported as `MyApp::Progress` (the LAST-
/// declared package in the file) — so Minion's trigger didn't
/// match, the plugin hook didn't fire, and the native path
/// mis-keyed the task's sig off the enqueue parens.
///
/// Pinned points:
///   * cursor inside `'alice@example.com'` → $to   (slot 0)
///   * cursor inside `'hi'`                → $subject (slot 1)
///   * cursor inside `'body'`              → $body   (slot 2)
///   * cursor past the closing `]`          → NOT the task sig
#[test]
fn enqueue_sighelp_line_118_of_demo() {
    use tower_lsp::lsp_types::Position;
    use tree_sitter::Parser;

    let path =
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("test_files/plugin_mojo_demo.pl");
    let src = std::fs::read_to_string(&path).unwrap();
    let fa = build_fa(&src);
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(&src, None).unwrap();
    let idx = crate::module_index::ModuleIndex::new_for_test();

    // Locate the enqueue call by content — line numbers in the
    // demo file shift whenever it's edited, and the test's value
    // is the signature-help behavior, not a literal row.
    let (line_idx, line) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("$minion->enqueue(send_email"))
        .map(|(i, l)| (i as u32, l))
        .expect("demo must contain the send_email enqueue site");

    let cases: &[(&str, &str, Option<u32>)] = &[
        ("alice@example.com", "'alice", Some(0)),
        ("hi", "'hi'", Some(1)),
        ("body", "'body'", Some(2)),
    ];
    for (slot_label, needle, expected) in cases {
        let col = (line.find(needle).unwrap() + 2) as u32;
        let pos = Position {
            line: line_idx,
            character: col,
        };
        let sig = crate::symbols::signature_help(&fa, &tree, &src, pos, &idx)
            .unwrap_or_else(|| panic!("[{slot_label}] sig help must fire"));
        assert!(
            sig.signatures[0].label.contains("send_email"),
            "[{slot_label}] task sig expected; got {:?}",
            sig.signatures[0].label
        );
        assert_eq!(
            sig.active_parameter, *expected,
            "[{slot_label}] wrong slot; got {:?}",
            sig.active_parameter
        );
    }

    // Past the closing `]` — must NOT show the task sig.
    let col = (line.rfind(']').unwrap() + 1) as u32;
    let pos = Position {
        line: line_idx,
        character: col,
    };
    if let Some(s) = crate::symbols::signature_help(&fa, &tree, &src, pos, &idx) {
        let lbl = &s.signatures[0].label;
        assert!(
            !lbl.contains("send_email"),
            "past `]`: task sig must not leak; got {lbl:?}"
        );
    }
}

/// Pinned invariant for the real-nvim Minion sig-help bug:
///
///   * Fat commas and literal commas must produce the SAME
///     signature-help behavior at identical cursor positions.
///     Two cases before the fix: (a) inside the arrayref, both
///     variants routed to the task sig — that worked. (b) once
///     the cursor left the arrayref, the native string-dispatch
///     path keyed the task's active_param off the outer call's
///     literal-comma count, surfacing `$subject` at the options-
///     hash slot, and `$body` several slots into a run of
///     trailing commas. Both wrong in obviously different ways.
///
///   * Cursor inside the arrayref → task sig, correct slot.
///   * Cursor outside the arrayref but still in the enqueue call
///     → NEVER the task sig. Falls through to enqueue's own
///     method sig (none here, since Minion.pm isn't indexed in
///     the test — `None` is the acceptable outcome).
///
/// If this regresses, the sweep-style bug is back: flip to
/// `DUMP_SWEEP=1 cargo test` to get a per-column dump.
#[test]
fn enqueue_sighelp_separator_agnostic() {
    use tower_lsp::lsp_types::Position;
    use tree_sitter::Parser;

    let cases: &[(&str, &str)] = &[
        (
            "literal-comma",
            "$minion->enqueue('send_email', [ 'alice' ], {})",
        ),
        (
            "fat-comma",
            "$minion->enqueue(send_email => [ 'alice' ], , , , )",
        ),
    ];

    let header = "package MyApp;\nuse Minion;\nmy $minion = Minion->new;\n\
             $minion->add_task(send_email => sub { my ($job, $to, $subject, $body) = @_; });\n";

    let dump = std::env::var("DUMP_SWEEP").is_ok();
    let mut dump_out = String::new();

    for (label, call_line) in cases {
        let src = format!("{}{};\n", header, call_line);
        let fa = build_fa(&src);
        let mut parser = Parser::new();
        parser
            .set_language(&ts_parser_perl::LANGUAGE.into())
            .unwrap();
        let tree = parser.parse(&src, None).unwrap();
        let idx = crate::module_index::ModuleIndex::new_for_test();

        let line_idx = src
            .lines()
            .position(|l| l.starts_with("$minion->enqueue"))
            .unwrap();
        let line = src.lines().nth(line_idx).unwrap();

        // Cursor inside 'alice' → task sig, slot 0 ($to).
        let in_alice = line.find("'alice'").unwrap() + 3;
        let pos = Position {
            line: line_idx as u32,
            character: in_alice as u32,
        };
        let sig = crate::symbols::signature_help(&fa, &tree, &src, pos, &idx)
            .unwrap_or_else(|| panic!("[{label}] cursor in 'alice' must fire task sig"));
        assert!(
            sig.signatures[0].label.contains("send_email"),
            "[{label}] in 'alice' → task sig; got: {:?}",
            sig.signatures[0].label
        );
        assert_eq!(
            sig.active_parameter,
            Some(0),
            "[{label}] in 'alice' → $to (slot 0); got {:?}",
            sig.active_parameter
        );

        // Cursor past the `]` but still inside the enqueue parens
        // → the options-hash slot / trailing-comma space. MUST NOT
        // show the task sig. `None` is acceptable (enqueue's own
        // method isn't indexed in this test).
        let past_bracket = line.find(']').unwrap() + 2;
        let pos = Position {
            line: line_idx as u32,
            character: past_bracket as u32,
        };
        let sig = crate::symbols::signature_help(&fa, &tree, &src, pos, &idx);
        if let Some(s) = &sig {
            let lbl = &s.signatures[0].label;
            assert!(
                !lbl.contains("send_email"),
                "[{label}] past `]`: task sig must NOT show; got: {:?}",
                lbl
            );
        }

        // Fat-comma specific: sweep the trailing-commas region
        // and ensure NONE of those columns surface the task sig.
        // Before the fix, each literal comma bumped active_param
        // and produced $subject / $body at arbitrary positions.
        if *label == "fat-comma" {
            let start = line.find(']').unwrap() + 1;
            let end = line.rfind(')').unwrap();
            for col in start..=end {
                let pos = Position {
                    line: line_idx as u32,
                    character: col as u32,
                };
                let sig = crate::symbols::signature_help(&fa, &tree, &src, pos, &idx);
                if let Some(s) = &sig {
                    let lbl = &s.signatures[0].label;
                    assert!(!lbl.contains("send_email"),
                            "[{label}] col {col}: task sig leaked into trailing-comma region; got: {:?}",
                            lbl);
                }
            }
        }

        if dump {
            dump_out.push_str(&format!("\n=== {} ===\n{}\n", label, line));
            for col in 0..=line.len() {
                let pos = Position {
                    line: line_idx as u32,
                    character: col as u32,
                };
                let sig = crate::symbols::signature_help(&fa, &tree, &src, pos, &idx);
                let label_str = match &sig {
                    None => "<none>".to_string(),
                    Some(s) => format!(
                        "ap={:?} sig={}",
                        s.active_parameter,
                        s.signatures
                            .first()
                            .map(|si| si.label.as_str())
                            .unwrap_or("")
                    ),
                };
                let ch = line
                    .chars()
                    .nth(col)
                    .map(|c| c.to_string())
                    .unwrap_or_else(|| "<eol>".into());
                dump_out.push_str(&format!("col {:>3} ({:<5}): {}\n", col, ch, label_str));
            }
        }
    }

    if dump {
        panic!("{}", dump_out);
    }
}

/// Sanity: the minion plugin registers a task Handler with the
/// expected shape. The arrayref-sig-help behavior itself lives in
/// the plugin's `on_signature_help` IoC hook (tested end-to-end
/// below) — no data flag on the Handler.
#[test]
fn minion_registers_task_handler() {
    let src = r#"package MyApp;
use Minion;
my $minion = Minion->new;
$minion->add_task(send_email => sub { my ($job, $to) = @_; });
"#;
    let fa = build_fa(src);
    let h = fa
        .symbols
        .iter()
        .find(|s| s.kind == SymKind::Handler && s.name == "send_email")
        .expect("handler exists");
    let SymbolDetail::Handler {
        dispatchers,
        display,
        ..
    } = &h.detail
    else {
        panic!("detail shape");
    };
    assert!(
        dispatchers.iter().any(|d| d == "enqueue"),
        "must list enqueue as a dispatcher; got: {:?}",
        dispatchers
    );
    assert!(
        matches!(display, HandlerDisplay::Task),
        "task handlers display as Task; got: {:?}",
        display
    );
}

/// Test 2 — arrayref sig help, through the REAL LSP pipeline.
/// Cursor sits INSIDE the middle string literal `'hi'` — the
/// shape a user actually produces in nvim. active_parameter must
/// be 1 (= $subject). Earlier version of this test used a
/// cursor-right-after-comma position that nobody types at, and
/// passed while the real nvim experience was broken.
#[test]
fn enqueue_arrayref_sig_help_active_param_inside_string() {
    use tower_lsp::lsp_types::Position;
    use tree_sitter::Parser;

    let src = r#"package MyApp;
use Minion;
my $minion = Minion->new;
$minion->add_task(send_email => sub {
    my ($job, $to, $subject, $body) = @_;
});
$minion->enqueue(send_email => ['alice', 'hi', 'body']);
"#;
    let fa = build_fa(src);
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();

    // Cursor between `h` and `i` of `'hi'` — the middle slot of
    // the arrayref, which is $subject.
    let line_idx = src
        .lines()
        .position(|l| l.contains("enqueue(send_email"))
        .expect("enqueue line present");
    let line = src.lines().nth(line_idx).unwrap();
    let col = line.find("'hi'").unwrap() + 2; // between h and i
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    let idx = crate::module_index::ModuleIndex::new_for_test();
    let sig = crate::symbols::signature_help(&fa, &tree, src, pos, &idx)
        .expect("sig help must fire inside a string-literal arrayref arg");

    let info = &sig.signatures[0];
    assert!(
        info.label.contains("send_email"),
        "label references the task, not enqueue; got: {:?}",
        info.label
    );
    assert!(
        info.label.contains("$subject"),
        "label surfaces the task's params; got: {:?}",
        info.label
    );
    assert_eq!(
        sig.active_parameter,
        Some(1),
        "cursor inside `'hi'` → $subject (index 1), NOT $to. \
             If you see 0 here, sig help isn't recognizing it's inside \
             the arrayref at slot 1; got: {:?}",
        sig.active_parameter
    );
}

/// Sig help must also land on the LAST arrayref slot when the
/// cursor is inside its string literal. Pinned separately from
/// the middle-slot test because count_commas can off-by-one on
/// the last slot if the walker breaks wrong.
#[test]
fn enqueue_arrayref_sig_help_active_param_inside_last_string() {
    use tower_lsp::lsp_types::Position;
    use tree_sitter::Parser;

    let src = r#"package MyApp;
use Minion;
my $minion = Minion->new;
$minion->add_task(send_email => sub {
    my ($job, $to, $subject, $body) = @_;
});
$minion->enqueue(send_email => ['alice', 'hi', 'body']);
"#;
    let fa = build_fa(src);
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();

    let line_idx = src
        .lines()
        .position(|l| l.contains("enqueue(send_email"))
        .unwrap();
    let line = src.lines().nth(line_idx).unwrap();
    let col = line.find("'body'").unwrap() + 3; // inside "body"
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    let idx = crate::module_index::ModuleIndex::new_for_test();
    let sig = crate::symbols::signature_help(&fa, &tree, src, pos, &idx)
        .expect("sig help fires inside the last string too");

    assert_eq!(
        sig.active_parameter,
        Some(2),
        "cursor inside `'body'` → $body (index 2); got: {:?}",
        sig.active_parameter
    );
}

/// Test 3a — hash-key completion on an empty enqueue options hash
/// in a file that ALSO has a matching add_task. The earlier
/// version of this test used an enqueue for an unknown task name,
/// which accidentally sidestepped the dispatch-args short-circuit
/// — nvim's real experience (task registered, enqueue at 3rd arg)
/// was silently broken. Pin the real shape.
#[test]
fn enqueue_options_hash_completion_empty() {
    use tower_lsp::lsp_types::Position;
    use tree_sitter::Parser;

    let src = r#"package MyApp;
use Minion;
my $minion = Minion->new;
$minion->add_task(task_x => sub { my ($job, $a) = @_; });
$minion->enqueue(task_x => ['a'], {  });
"#;
    let fa = build_fa(src);
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();

    // Cursor inside the enqueue options hash — `{  }` on the
    // enqueue line. Can't just search for "{ " globally because
    // the sub body `sub { my ($job` matches first.
    let line_idx = src
        .lines()
        .position(|l| l.contains("enqueue(task_x"))
        .expect("enqueue line");
    let line = src.lines().nth(line_idx).unwrap();
    let col = line.find("{  }").unwrap() + 2; // halfway between `{` and `}`
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    let idx = crate::module_index::ModuleIndex::new_for_test();
    let items = crate::symbols::completion_items(&fa, &tree, src, pos, &idx, None);
    let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();

    for expected in &["priority", "queue", "delay", "attempts"] {
        assert!(
            labels.contains(expected),
            "empty-hash: `{}` must complete; got: {:?}",
            expected,
            labels
        );
    }
}

/// Test 3b — with an existing key in the hash, it must NOT be
/// offered again; the rest of the options must still appear.
/// Same task-registered shape as 3a so the dispatch-args
/// short-circuit IS active and gets properly bypassed on HashKey.
#[test]
fn enqueue_options_hash_completion_with_existing_keys() {
    use tower_lsp::lsp_types::Position;
    use tree_sitter::Parser;

    let src = r#"package MyApp;
use Minion;
my $minion = Minion->new;
$minion->add_task(task_x => sub { my ($job, $a) = @_; });
$minion->enqueue(task_x => ['a'], { priority => 10,  });
"#;
    let fa = build_fa(src);
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();

    // Scope the anchor to the enqueue line so the sub body's own
    // brace/comma pattern doesn't claim the match first.
    let line_idx = src
        .lines()
        .position(|l| l.contains("enqueue(task_x"))
        .expect("enqueue line");
    let line = src.lines().nth(line_idx).unwrap();
    let col = line.find("priority => 10, ").unwrap() + "priority => 10, ".len();
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    let idx = crate::module_index::ModuleIndex::new_for_test();
    let items = crate::symbols::completion_items(&fa, &tree, src, pos, &idx, None);
    let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();

    assert!(
        labels.contains(&"queue"),
        "with-existing: `queue` must still complete; got: {:?}",
        labels
    );
    assert!(
        labels.contains(&"delay"),
        "with-existing: `delay` must still complete; got: {:?}",
        labels
    );
    assert!(
        !labels.contains(&"priority"),
        "with-existing: `priority` is already used — must NOT re-appear; got: {:?}",
        labels
    );
}

/// mojo-helpers emits a PluginNamespace for the app, bridging to the
/// single fictional app surface (docs/adr/plugin-system.md). Each
/// registered helper's name is an entity. The consumer classes reach
/// the surface via the synthetic-parent edge in core. Multi-app
/// workspaces get one namespace per app.
#[test]
fn mojo_helpers_emits_app_plugin_namespace() {
    use crate::file_analysis::Bridge;
    let src = r#"package MyApp;
use Mojolicious::Lite;
my $app = Mojolicious->new;
$app->helper(current_user => sub { my ($c) = @_; });
$app->helper('users.create' => sub { my ($c) = @_; });
"#;
    let fa = build_fa(src);

    // Identify by semantic shape (kind + bridge to the app surface),
    // not by plugin id — the contract is "there's an 'app' namespace
    // bridging to the app surface", not "a plugin literally called
    // mojo-helpers emits it".
    let ns = fa
        .plugin_namespaces
        .iter()
        .find(|n| {
            n.kind == "app"
                && n.bridges
                    .contains(&Bridge::Class(crate::file_analysis::APP_SURFACE_CLASS.into()))
        })
        .expect("an `app` namespace must bridge the app surface");

    // Entities cover both registered helpers, through the
    // name-keyed resolution that expands fan-out Methods.
    let entity_names: Vec<&str> = ns
        .entities
        .iter()
        .map(|id| fa.symbol(*id).name.as_str())
        .collect();
    assert!(
        entity_names.contains(&"current_user"),
        "simple helper must land in the namespace; got: {:?}",
        entity_names
    );
    assert!(
        entity_names.contains(&"users"),
        "dotted-helper root must land in the namespace; got: {:?}",
        entity_names
    );

    // Namespace ID is stable per enclosing package — one namespace
    // for MyApp regardless of how many helpers it registers. Scope
    // the count to this namespace's own (plugin_id, id) pair.
    let count = fa
        .plugin_namespaces
        .iter()
        .filter(|n| n.plugin_id == ns.plugin_id && n.id == ns.id)
        .count();
    assert_eq!(count, 1, "one namespace per app, not one per helper");
}

/// Plugin namespaces are a structural concept (bridges into class
/// lookups via `for_each_entity_bridged_to`) — they are deliberately
/// NOT surfaced in the document outline. The entities inside (helpers,
/// routes, tasks) already render as individual entries with their
/// `<word>` kind prefix; a separate "this file hosts a mojo app" row
/// is noise the user can't act on. The namespace data still has to
/// be populated for cross-file bridge lookups to work — that's what
/// this test pins.
#[test]
fn plugin_namespaces_are_populated_but_not_in_outline() {
    let src = r#"package MyApp;
use Mojolicious::Lite;
app->helper(current_user => sub { my ($c) = @_; });
get '/home' => sub { my $c = shift; };
"#;
    let fa = build_fa(src);

    // The namespace data is still there for bridge queries — that's
    // how `$c->current_user` resolves to the helper across files.
    assert!(
        fa.plugin_namespaces.iter().any(|n| n.kind == "app"),
        "app namespace should still exist in FileAnalysis; got: {:?}",
        fa.plugin_namespaces
            .iter()
            .map(|n| &n.id)
            .collect::<Vec<_>>()
    );

    // Outline must NOT contain any Namespace kind entries from the
    // plugin namespaces. Packages (`MyApp`) are Namespace-kind too
    // but come from SymKind::Package symbols, which are fine.
    let outline = fa.document_symbols();
    let plugin_ns_in_outline: Vec<&str> = outline
        .iter()
        .filter(|o| o.kind == SymKind::Namespace)
        .map(|o| o.name.as_str())
        .filter(|n| n.starts_with('['))
        .collect();
    assert!(
        plugin_ns_in_outline.is_empty(),
        "plugin namespaces must not surface in outline; leaked: {:?}",
        plugin_ns_in_outline,
    );

    // The actual entries (helper, route) still show flat.
    fn walk<'a>(xs: &'a [crate::file_analysis::OutlineSymbol], out: &mut Vec<&'a str>) {
        for x in xs {
            out.push(x.name.as_str());
            walk(&x.children, out);
        }
    }
    let mut all = Vec::new();
    walk(&outline, &mut all);
    assert!(
        all.iter().any(|n| n.contains("current_user")),
        "helper must still appear flat in outline; got: {:?}",
        all
    );
    assert!(
        all.iter().any(|n| n.contains("/home")),
        "route must still appear flat in outline; got: {:?}",
        all
    );
}

/// mojo-events emits a PluginNamespace per emitter class. Bridges to
/// the emitter class; entity_names are the event Handler names.
/// Multiple `->on/->once/->subscribe` wire-ups on the same emitter
/// accumulate under the same namespace id.
#[test]
fn mojo_events_emits_emitter_plugin_namespace() {
    use crate::file_analysis::Bridge;
    let src = r#"package My::Emitter;
use parent 'Mojo::EventEmitter';
sub register {
    my $self = shift;
    $self->on(connect => sub { my ($e) = @_; });
    $self->on(disconnect => sub { my ($e) = @_; });
    $self->once(ready => sub { my ($e) = @_; });
}
"#;
    let fa = build_fa(src);

    let ns = fa
        .plugin_namespaces
        .iter()
        .find(|n| n.kind == "events" && n.bridges.contains(&Bridge::Class("My::Emitter".into())))
        .expect("an `events` namespace must bridge My::Emitter");

    let entity_names: Vec<&str> = ns
        .entities
        .iter()
        .map(|id| fa.symbol(*id).name.as_str())
        .collect();
    for ev in ["connect", "disconnect", "ready"] {
        assert!(
            entity_names.contains(&ev),
            "event `{}` must land in the namespace; got: {:?}",
            ev,
            entity_names
        );
    }

    let count = fa
        .plugin_namespaces
        .iter()
        .filter(|n| n.plugin_id == ns.plugin_id && n.id == ns.id)
        .count();
    assert_eq!(count, 1, "one namespace per emitter, not one per wire-up");
}

/// mojo-routes emits a PluginNamespace per declaring package. Each
/// `->to('Ctrl#action')` call's Handler lands as a namespace entity;
/// the bridge points at `Mojolicious::Controller` (not the declaring
/// package) so `$c->url_for('|')` from any controller resolves via
/// `for_each_entity_bridged_to` walking through Controller in its
/// ancestor chain. Namespace id still keys on the declaring package
/// so future app-scoping has per-app buckets to narrow to.
#[test]
fn mojo_routes_emits_app_plugin_namespace() {
    use crate::file_analysis::Bridge;
    let src = r#"package MyApp;
use Mojolicious;
sub startup {
    my $self = shift;
    my $r = $self->routes;
    $r->get('/users')->to('Users#list');
    $r->post('/users')->to('Users#create');
}
"#;
    let fa = build_fa(src);

    // Identify by semantic shape — a `routes` namespace that
    // bridges to Mojolicious::Controller (the happy-path owner
    // for the workspace-wide url_for lookup). Entity names are
    // the Controller#action form, distinguishing from the Lite
    // path-based flavor.
    let ns = fa
        .plugin_namespaces
        .iter()
        .find(|n| {
            n.kind == "routes"
                && n.bridges
                    .contains(&Bridge::Class("Mojolicious::Controller".into()))
                && n.entities
                    .iter()
                    .any(|id| fa.symbol(*id).name.contains('#'))
        })
        .expect(
            "a `routes` namespace must bridge Mojolicious::Controller with Ctrl#action entities",
        );

    let entity_names: Vec<&str> = ns
        .entities
        .iter()
        .map(|id| fa.symbol(*id).name.as_str())
        .collect();
    assert!(
        entity_names.contains(&"Users#list"),
        "route Users#list must land in the namespace; got: {:?}",
        entity_names
    );
    assert!(
        entity_names.contains(&"Users#create"),
        "route Users#create must land in the namespace; got: {:?}",
        entity_names
    );

    let count = fa
        .plugin_namespaces
        .iter()
        .filter(|n| n.plugin_id == ns.plugin_id && n.id == ns.id)
        .count();
    assert_eq!(
        count, 1,
        "one namespace per declaring package, not one per route"
    );
}

/// mojo-lite emits a PluginNamespace per Lite app. Entity names are
/// the route paths (the same string that mojo-lite stamps into the
/// Handler). Bridge is `Mojolicious::Controller` so `$c->url_for(|)`
/// inside any controller picks up these Lite routes too — mirrors
/// mojo-routes; the Lite script package lives on in the namespace
/// id (`mojo-lite:<pkg>`) for future app-scoping.
#[test]
fn mojo_lite_emits_app_plugin_namespace() {
    use crate::file_analysis::Bridge;
    let src = r#"package main;
use Mojolicious::Lite;
get '/users' => sub { my $c = shift; };
post '/login' => sub { my $c = shift; };
"#;
    let fa = build_fa(src);

    let ns = fa
        .plugin_namespaces
        .iter()
        .find(|n| {
            n.kind == "routes"
                && n.bridges
                    .contains(&Bridge::Class("Mojolicious::Controller".into()))
                && n.entities
                    .iter()
                    .any(|id| fa.symbol(*id).name.starts_with('/'))
        })
        .expect(
            "a Lite `routes` namespace must bridge Mojolicious::Controller with /path entities",
        );

    let entity_names: Vec<&str> = ns
        .entities
        .iter()
        .map(|id| fa.symbol(*id).name.as_str())
        .collect();
    assert!(
        entity_names.contains(&"/users"),
        "route /users must land in the namespace; got: {:?}",
        entity_names
    );
    assert!(
        entity_names.contains(&"/login"),
        "route /login must land in the namespace; got: {:?}",
        entity_names
    );
}

/// minion emits a PluginNamespace per enclosing package. Tasks land
/// as entities; bridge is `Class(Minion)` so the namespace feeds the
/// same cross-file lookup primitive used by the other plugins.
/// (The `dispatch_targets_for` completion-hook path is independent —
/// the namespace here is for outline/workspace-symbol and future
/// consolidation of the task-lookup path.)
#[test]
fn minion_emits_tasks_plugin_namespace() {
    use crate::file_analysis::Bridge;
    let src = r#"package MyApp;
use Minion;
my $minion = Minion->new;
$minion->add_task(send_email => sub { my ($job) = @_; });
$minion->add_task(resize_image => sub { my ($job) = @_; });
"#;
    let fa = build_fa(src);

    let ns = fa
        .plugin_namespaces
        .iter()
        .find(|n| n.kind == "tasks" && n.bridges.contains(&Bridge::Class("Minion".into())))
        .expect("a `tasks` namespace must bridge Minion");

    let entity_names: Vec<&str> = ns
        .entities
        .iter()
        .map(|id| fa.symbol(*id).name.as_str())
        .collect();
    assert!(
        entity_names.contains(&"send_email"),
        "task send_email must land in the namespace; got: {:?}",
        entity_names
    );
    assert!(
        entity_names.contains(&"resize_image"),
        "task resize_image must land in the namespace; got: {:?}",
        entity_names
    );

    let count = fa
        .plugin_namespaces
        .iter()
        .filter(|n| n.plugin_id == ns.plugin_id && n.id == ns.id)
        .count();
    assert_eq!(count, 1, "one namespace per package, not one per add_task");
}

/// RED — sig help at the OPTIONS hash of enqueue should show
/// enqueue's own signature, not the task's. Currently broken:
/// the string-dispatch sig help fires whenever the cursor is past
/// arg-0 of a dispatcher call, regardless of whether the cursor
/// is actually inside the handler-args slot. For `enqueue`,
/// handler args live INSIDE the arrayref at slot 1 — slot 2 is
/// enqueue's own options hash.
///
/// Proper fix: plugin-controlled dispatch (see
/// `docs/prompt-plugin-architecture.md` — IoC query hooks).
/// The plugin decides when sig help applies to the handler vs
/// when it applies to the dispatcher itself. Core-side fix is
/// possible (narrow the string-dispatch path to the declared
/// handler-args slot) but fragile; leaving as RED until the
/// IoC hook lands.
#[test]
fn enqueue_options_hash_sig_help_is_enqueue_not_task() {
    use tower_lsp::lsp_types::Position;
    use tree_sitter::Parser;

    let src = r#"package MyApp;
use Minion;
my $minion = Minion->new;
$minion->add_task(send_email => sub {
    my ($job, $to, $subject) = @_;
});
$minion->enqueue(send_email => ['a', 'b'], {  });
"#;
    let fa = build_fa(src);
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();

    let line_idx = src
        .lines()
        .position(|l| l.contains("enqueue(send_email"))
        .unwrap();
    let line = src.lines().nth(line_idx).unwrap();
    let col = line.find("{  }").unwrap() + 2;
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    let idx = crate::module_index::ModuleIndex::new_for_test();
    let sig = crate::symbols::signature_help(&fa, &tree, src, pos, &idx);

    // Tight contract: `PluginSigHelpAnswer::Silent` returns None
    // from `signature_help` — full stop. The plugin explicitly
    // claims the slot to block the native string-dispatch path
    // that would mis-show the task's sig. Anything else means
    // either the plugin stopped claiming, or the core's Silent
    // handler regressed.
    assert!(
        sig.is_none(),
        "plugin `Silent` on the options-hash slot must suppress native \
             sig help entirely; got: {:?}",
        sig
    );
}

/// RED — completion at arg-0 of enqueue should offer ONLY
/// registered task names (Handler dispatch targets), not a
/// union of tasks + every other `Minion` instance method.
/// Matches the real nvim env where CPAN-installed Minion brings
/// ~30 instance methods cross-file, which leak in when a
/// user types `$minion->enqueue(|)`.
///
/// Same arch gap as the sig-help one above: the core doesn't
/// know that `enqueue`'s arg-0 is semantically "pick a task
/// name", so `dispatch_target_completions` contributes task
/// names but instance methods reach in through completion of
/// the receiver's class methods on the `$minion->` receiver.
///
/// Proper fix: plugin-controlled `on_completion` hook + the
/// PluginNamespace entities indexed for fast "names of kind
/// `task` on this minion" lookup. See the arch doc.
#[test]
fn enqueue_arg0_offers_task_names_only() {
    use tower_lsp::lsp_types::Position;
    use tree_sitter::Parser;

    // Task-declaring file.
    let src = r#"package MyApp;
use Minion;
my $minion = Minion->new;
$minion->add_task(send_email => sub { my ($job) = @_; });
$minion->add_task(resize_image => sub { my ($job) = @_; });
$minion->enqueue();
"#;
    let fa = build_fa(src);
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();

    // Mock CPAN Minion with realistic instance methods that
    // would otherwise leak into `$minion->enqueue(|)`. Uses the
    // same workspace-module-registration path nvim startup uses.
    let minion_src = r#"package Minion;
sub new { my $class = shift; bless {}, $class }
sub enqueue     { my ($self, $task, $args, $opts) = @_; }
sub enqueue_p   { my ($self, $task, $args, $opts) = @_; }
sub perform_jobs { my ($self) = @_; }
sub backend     { my ($self) = @_; }
sub reset       { my ($self) = @_; }
sub stats       { my ($self) = @_; }
sub worker      { my ($self) = @_; }
sub repair      { my ($self) = @_; }
sub foreground  { my ($self, $id) = @_; }
1;
"#;
    let minion_fa = std::sync::Arc::new(build_fa(minion_src));
    let idx = std::sync::Arc::new(crate::module_index::ModuleIndex::new_for_test());
    idx.register_workspace_module(std::path::PathBuf::from("/tmp/Minion.pm"), minion_fa);

    // Cursor inside `enqueue(|)` — just after the `(`.
    let line_idx = src.lines().position(|l| l.ends_with("enqueue();")).unwrap();
    let line = src.lines().nth(line_idx).unwrap();
    let col = line.find("enqueue(").unwrap() + "enqueue(".len();
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    let items = crate::symbols::completion_items(&fa, &tree, src, pos, &idx, None);
    let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();

    assert!(
        labels.contains(&"send_email"),
        "task names must appear at enqueue's arg 0; got: {:?}",
        labels
    );
    assert!(
        labels.contains(&"resize_image"),
        "every registered task name must be offered; got: {:?}",
        labels
    );

    // The tight contract — only tasks, nothing else. When this
    // goes green we'll know the plugin owns the completion shape
    // at this position and the Minion-method firehose is gone.
    for label in &labels {
        assert!(
            *label == "send_email" || *label == "resize_image",
            "only task names should appear at enqueue's arg 0; \
                 got unexpected `{}` in {:?}",
            label,
            labels,
        );
    }
}

/// Sig help on a helper call strips `$c` like it strips `$self`.
/// The helper plugin flags its callback's first param as invocant
/// via `as_invocant_params`; the core sig help path drops any
/// invocant-flagged first positional instead of name-matching
/// `$self`/`$class` only.
#[test]
fn plugin_mojo_helpers_sig_help_strips_invocant() {
    use tower_lsp::lsp_types::Position;
    use tree_sitter::Parser;

    let src = r#"package MyApp;
use Mojolicious::Lite;

my $app = Mojolicious->new;
$app->helper(current_user => sub {
    my ($c, $fallback) = @_;
});

sub act {
    my ($c) = @_;
    $c->current_user();
}
"#;
    let fa = build_fa(src);
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();

    // Cursor inside `$c->current_user(|)` — between the parens.
    let (row, col) = src
        .lines()
        .enumerate()
        .find_map(|(r, l)| {
            l.find("current_user()")
                .map(|c| (r, c + "current_user(".len()))
        })
        .expect("find call site");
    let pos = Position {
        line: row as u32,
        character: col as u32,
    };

    let idx = crate::module_index::ModuleIndex::new_for_test();
    let sig = crate::symbols::signature_help(&fa, &tree, src, pos, &idx)
        .expect("sig help fires on helper call");

    let info = &sig.signatures[0];
    assert!(
        info.label.contains("current_user"),
        "label: {:?}",
        info.label
    );
    assert!(
        info.label.contains("$fallback"),
        "sig should show declared param `$fallback`; got: {:?}",
        info.label
    );
    assert!(
        !info.label.contains("$c"),
        "`$c` must be stripped as invocant; got: {:?}",
        info.label
    );
}

/// Sig help when the cursor sits inside the arrayref at position 1
/// of `enqueue` — the core routes via the Handler's
/// `args_in_arrayref_at` declaration (set by the minion plugin)
/// and shows the task's params (invocant-stripped). Plugin-agnostic
/// on the sig-help side: all the core needs is the declaration.
#[test]
fn plugin_minion_sig_help_on_enqueue_array_args() {
    use tower_lsp::lsp_types::Position;
    use tree_sitter::{Parser, Point};

    let src = r#"package MyApp;
use Minion;

my $minion = Minion->new;
$minion->add_task(send_email => sub {
    my ($job, $to, $subject, $body) = @_;
});
$minion->enqueue(send_email => [ ]);
"#;
    let fa = build_fa(src);

    // Cursor inside the enqueue call's arrayref: point at the
    // single space between the `[` and `]` on the last line.
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();

    // Find the `[ ]` — cursor at col AFTER `[`.
    let mut cursor_point: Option<Point> = None;
    for (row, line) in src.lines().enumerate() {
        if line.contains("enqueue(send_email") {
            if let Some(col) = line.find("[ ") {
                cursor_point = Some(Point::new(row, col + 1));
            }
        }
    }
    let cursor_point = cursor_point.expect("locate cursor inside [ ]");
    let pos = Position {
        line: cursor_point.row as u32,
        character: cursor_point.column as u32,
    };

    let idx = crate::module_index::ModuleIndex::new_for_test();
    let sig = crate::symbols::signature_help(&fa, &tree, src, pos, &idx)
        .expect("sig help must fire inside enqueue's arrayref");

    // At least one signature, matching the `send_email` handler
    // (the task's params minus $job).
    assert!(!sig.signatures.is_empty(), "at least one signature");
    let info = &sig.signatures[0];
    let label = &info.label;
    assert!(
        label.contains("send_email"),
        "sig label must reference the handler name: {:?}",
        label
    );
    assert!(
        label.contains("$to"),
        "sig should surface task params (`$to`): {:?}",
        label
    );
    assert!(
        !label.contains("$job"),
        "invocant `$job` must be stripped from display: {:?}",
        label
    );
}

/// Hash-key completion on the enqueue options hash
/// (`$minion->enqueue('task', [args], { | })`) — the cursor_context
/// layer now recognizes a nested hash literal as a positional
/// argument and routes it to `HashKeyOwner::Sub { name: enqueue }`.
#[test]
fn plugin_minion_hashkey_help_on_enqueue_options() {
    use tree_sitter::{Parser, Point};
    let src = r#"package MyApp;
use Minion;

my $minion = Minion->new;
$minion->enqueue(task_x => ['arg'] => { });
"#;
    // Build + parse
    let fa = build_fa(src);
    let mut parser = Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();

    // Cursor inside the empty options hash literal `{ | }`.
    // Line 4 (0-indexed) column after "{ " — aim at the middle
    // of the hash's interior.
    let src_bytes = src.as_bytes();
    let mut cursor: Option<Point> = None;
    for (row, line) in src.lines().enumerate() {
        if let Some(col) = line.find("{ ") {
            cursor = Some(Point::new(row, col + 2));
        }
    }
    let cursor = cursor.expect("find the `{ ` in the source");

    let ctx = crate::cursor_context::detect_cursor_context_tree(&tree, src_bytes, cursor, &fa)
        .expect("context should be detected inside hash literal");
    match ctx {
        crate::cursor_context::CursorContext::HashKey { source_sub, .. } => {
            assert_eq!(
                source_sub.as_deref(),
                Some("enqueue"),
                "nested {{ }} at call-arg position routes to the callee"
            );
        }
        other => panic!("expected HashKey context, got {:?}", other),
    }

    // Completion path surfaces the plugin's HashKeyDefs.
    let candidates = fa.complete_hash_keys_for_sub("enqueue", cursor);
    let labels: Vec<&str> = candidates.iter().map(|c| c.label.as_str()).collect();
    for expected in &["priority", "queue", "delay", "attempts"] {
        assert!(
            labels.contains(expected),
            "enqueue option `{}` must complete; got: {:?}",
            expected,
            labels
        );
    }
}

// ---- Plugin type overrides ----
//
// Tests pin the contract: a plugin's `overrides()` manifest patches
// local Sub/Method return types AFTER inference, with provenance
// recorded so debugging can tell asserted from inferred. The
// bundled `mojo-routes` plugin overrides `Mojolicious::Routes::Route::_route`
// to return `$self` because the upstream impl uses an `@_`-shift /
// array-slice idiom inference doesn't model.
//
// Targeting is by exact (class, method) — the override fires on the
// home class only; subclasses still get the type via the existing
// cross-file resolution path.

#[test]
fn plugin_override_patches_return_type_on_matching_method() {
    let src = "\
package Mojolicious::Routes::Route;

sub _route {
    my $self = shift;
    # Real impl uses an array slice that inference can't model.
    return $self;
}

1;
";
    let fa = build_fa(src);
    let route_sym = fa
        .symbols
        .iter()
        .find(|s| s.name == "_route" && matches!(s.kind, SymKind::Sub | SymKind::Method))
        .expect("_route must be parsed as a sub");
    match &route_sym.detail {
        SymbolDetail::Sub { .. } => {
            assert_eq!(
                fa.symbol_return_type_via_bag(route_sym.id, None),
                Some(InferredType::ClassName(
                    "Mojolicious::Routes::Route".into()
                )),
                "override must rewrite return_type to ClassName(Mojolicious::Routes::Route)",
            );
        }
        other => panic!("_route must be a Sub detail; got {:?}", other),
    }
}

#[test]
fn plugin_override_records_provenance_with_plugin_id_and_reason() {
    // The point of provenance is debug-time introspection: a
    // future inspector should be able to ask "why does the LSP
    // think `_route` returns Mojolicious::Routes::Route?" and
    // get back "because mojo-routes' overrides() said so". We pin
    // the plugin id and assert the reason isn't empty so a future
    // refactor that drops the reason field surfaces here.
    let src = "\
package Mojolicious::Routes::Route;
sub _route { my $self = shift; $self }
1;
";
    let fa = build_fa(src);
    let route_id = fa
        .symbols
        .iter()
        .find(|s| s.name == "_route")
        .expect("_route present")
        .id;
    match fa.return_type_provenance(route_id) {
        TypeProvenance::PluginOverride { plugin_id, reason } => {
            assert_eq!(plugin_id, "mojo-routes");
            assert!(
                !reason.is_empty(),
                "reason must explain why override exists"
            );
        }
        other => panic!("expected PluginOverride provenance; got {:?}", other),
    }
}

#[test]
fn plugin_override_does_not_touch_unrelated_subs() {
    // Same method NAME, different class → override must NOT apply.
    // The match is (class, method); a same-named method on an
    // unrelated package keeps whatever inference produced.
    let src = "\
package Some::Other::Package;
sub _route { my ($x) = @_; { id => $x } }
1;
";
    let fa = build_fa(src);
    let id = fa
        .symbols
        .iter()
        .find(|s| s.name == "_route")
        .expect("_route present")
        .id;
    // Override must not apply — provenance can be Inferred or
    // ReducerFold (inference produced the type via the witness
    // fold), but NOT PluginOverride.
    assert!(
        !matches!(
            fa.return_type_provenance(id),
            TypeProvenance::PluginOverride { .. }
        ),
        "override must not bleed across packages; provenance: {:?}",
        fa.return_type_provenance(id),
    );
}

#[test]
fn plugin_override_does_not_touch_other_methods_in_target_class() {
    // Same class, different method name → not the target.
    let src = "\
package Mojolicious::Routes::Route;
sub other_method { my $self = shift; { ok => 1 } }
1;
";
    let fa = build_fa(src);
    let id = fa
        .symbols
        .iter()
        .find(|s| s.name == "other_method")
        .expect("other_method present")
        .id;
    assert!(
        !matches!(
            fa.return_type_provenance(id),
            TypeProvenance::PluginOverride { .. }
        ),
        "override must not bleed across method names; got {:?}",
        fa.return_type_provenance(id),
    );
}

#[test]
fn plugin_override_visible_via_find_method_return_type() {
    // The user-visible payoff: any code path that asks "what does
    // calling `_route` on a Mojolicious::Routes::Route return?"
    // gets the override answer. find_method_return_type is the
    // primary API every chain-resolver / hover / completion path
    // routes through, so pinning it here covers the downstream
    // features without coupling to their specific internals.
    let src = "\
package Mojolicious::Routes::Route;
sub _route { my $self = shift; $self }
1;
";
    let fa = build_fa(src);
    let rt = fa.find_method_return_type("Mojolicious::Routes::Route", "_route", None, None);
    assert_eq!(
        rt,
        Some(InferredType::ClassName("Mojolicious::Routes::Route".into())),
        "find_method_return_type must surface the override-supplied type",
    );
}

#[test]
fn plugin_override_wins_over_inferred_return_type() {
    // Even if inference DID produce a (different) return type, the
    // override replaces it — the whole point is "inference reaches
    // the wrong answer here". The body explicitly returns a hashref
    // so inference would say HashRef without the override.
    let src = "\
package Mojolicious::Routes::Route;

sub _route {
    return { stub => 1 };
}

1;
";
    let fa = build_fa(src);
    let sym = fa
        .symbols
        .iter()
        .find(|s| s.name == "_route")
        .expect("_route present");
    match &sym.detail {
        SymbolDetail::Sub { .. } => {
            assert_eq!(
                fa.symbol_return_type_via_bag(sym.id, None),
                Some(InferredType::ClassName(
                    "Mojolicious::Routes::Route".into()
                )),
                "override must replace inferred HashRef, not be skipped",
            );
        }
        _ => unreachable!(),
    }
}

// ---- data-printer plugin ----
//
// Data::Printer monkey-patches `&p` and `&np` into the caller's
// symbol table from inside its custom `import` sub — no
// `@EXPORT` / `@EXPORT_OK`, so the cross-file extractor sees them
// as plain Subs but no caller's import list claims them. The
// plugin's job is to declare the imports plugin-side so call
// sites resolve.
//
// `use DDP` is a literal alias for `use Data::Printer` (DDP.pm
// just `push our @ISA, 'Data::Printer'` and re-uses the import).
// The plugin pins the synthetic Import at Data::Printer (the real
// module) regardless of which name the user typed, so cross-file
// hover/gd/sig-help on `p`/`np` always flow to the real source.

#[test]
fn plugin_data_printer_synthesizes_p_np_on_use_data_printer() {
    // `use Data::Printer;` — empty native qw list. Plugin must
    // emit an additional Import that lists `p` and `np` so
    // resolve_call_package finds them and routes cross-file
    // lookups to Data::Printer.
    let src = "\
use Data::Printer;
p $foo;
np \\%bar;
";
    let fa = build_fa(src);
    let dp_import = fa.imports.iter().find(|i| {
        i.module_name == "Data::Printer" && i.imported_symbols.iter().any(|s| s.local_name == "p")
    });
    assert!(
        dp_import.is_some(),
        "plugin must emit Import for Data::Printer carrying `p`; got: {:?}",
        fa.imports
    );
    let names: Vec<&str> = dp_import
        .unwrap()
        .imported_symbols
        .iter()
        .map(|s| s.local_name.as_str())
        .collect();
    assert!(names.contains(&"p"));
    assert!(names.contains(&"np"));
}

#[test]
fn plugin_data_printer_aliases_ddp_to_data_printer() {
    // `use DDP;` — the alias case. Plugin must still emit a
    // synthetic Import keyed on Data::Printer (NOT DDP) so
    // cross-file `p`/`np` lookups route to the real source
    // module. Otherwise the user gets nothing on hover/gd
    // when they typed `use DDP` instead of `use Data::Printer`.
    let src = "\
use DDP;
p $foo;
";
    let fa = build_fa(src);
    let dp_import = fa.imports.iter().find(|i| {
        i.module_name == "Data::Printer" && i.imported_symbols.iter().any(|s| s.local_name == "p")
    });
    assert!(
        dp_import.is_some(),
        "use DDP must produce an Import for Data::Printer (alias resolution); got: {:?}",
        fa.imports
            .iter()
            .map(|i| (
                i.module_name.clone(),
                i.imported_symbols
                    .iter()
                    .map(|s| s.local_name.clone())
                    .collect::<Vec<_>>(),
            ))
            .collect::<Vec<_>>()
    );
}

#[test]
fn plugin_data_printer_skips_unrelated_use_statements() {
    // Sanity check: an unrelated `use` doesn't pull a synthetic
    // Data::Printer import into the file. Otherwise the plugin
    // would be silently claiming every use statement.
    let src = "use List::Util qw(max);";
    let fa = build_fa(src);
    assert!(
        fa.imports
            .iter()
            .find(|i| i.module_name == "Data::Printer")
            .is_none(),
        "plugin must not synthesize a Data::Printer import unless DDP/Data::Printer was used"
    );
}

// ---- Dancer2 plugin tests ----

/// `use Dancer2` autoimports ~90 DSL keywords — unresolved-function
/// diagnostics must skip all of them. The plugin stashes a
/// `FrameworkImport` per keyword into `framework_imports`.
#[test]
fn plugin_dancer2_autoimports_dsl_keywords() {
    let src = r#"
package main;
use Dancer2;

get '/users' => sub { return template 'users' };
post '/login' => sub { my $u = param('user'); session user => $u; };
"#;
    let fa = build_fa(src);
    for kw in &[
        // Route verbs
        "get", "post", "put", "del", "patch", "any", "options",
        // Route organisation
        "prefix",
        // Lifecycle hooks
        "hook",
        // Request / response
        "request", "response", "param", "params",
        "body_parameters", "query_parameters", "route_parameters",
        // Headers / status
        "header", "headers", "content_type", "status",
        // Response control
        "redirect", "forward", "pass", "halt",
        // Rendering
        "template", "send_file", "send_as",
        // Config
        "config", "set", "setting",
        // Session / cookie
        "session", "cookie", "cookies",
        // Serialisers
        "to_json", "from_json", "to_yaml", "from_yaml",
        // Misc
        "var", "vars", "uri_for", "splat", "captures", "upload",
        "push_response_header",
        // App / DSL
        "app", "dancer_app", "dsl", "engine",
        // Async
        "delayed", "flush",
        // Logging
        "debug", "info", "warning", "error",
        // Boolean constants
        "true", "false",
        // Lifecycle
        "dance", "to_app", "start",
        // Keywords absent from the original set — verified against
        // Dancer2::Core::DSL::dsl_keywords (the authoritative list).
        "content", "send_error", "response_header", "request_header",
        "uri_for_route", "prepare_app", "encode_json", "decode_json",
        "to_dumper", "from_dumper", "push_header", "response_headers",
        "psgi_app", "runner", "done", "context",
        "dancer_version", "dancer_major_version",
        "mime", "request_data",
    ] {
        assert!(
            fa.framework_imports.contains(*kw),
            "`{}` must be autoimported by `use Dancer2`; framework_imports={:?}",
            kw,
            fa.framework_imports,
        );
    }
}

/// `use Dancer2` synthesizes typed Sub symbols for high-value DSL
/// functions so chained calls (`request->path`, `app->config`)
/// resolve against the correct class.
#[test]
fn plugin_dancer2_typed_stubs_have_return_types() {
    use crate::file_analysis::InferredType;

    let src = r#"
package main;
use Dancer2;
"#;
    let fa = build_fa(src);

    // `request` must resolve to Dancer2::Core::Request.
    let request_sym = fa
        .symbols
        .iter()
        .find(|s| s.name == "request" && matches!(s.kind, crate::file_analysis::SymKind::Sub));
    assert!(
        request_sym.is_some(),
        "dancer plugin must synthesize a `request` Sub symbol"
    );
    let rt = fa.sub_return_type_at_arity("request", None);
    assert_eq!(
        rt,
        Some(InferredType::ClassName("Dancer2::Core::Request".into())),
        "`request` must return Dancer2::Core::Request; got {:?}",
        rt
    );

    // `app` must resolve to Dancer2::Core::App.
    let rt = fa.sub_return_type_at_arity("app", None);
    assert_eq!(
        rt,
        Some(InferredType::ClassName("Dancer2::Core::App".into())),
        "`app` must return Dancer2::Core::App; got {:?}",
        rt
    );

    // `session` must resolve to Dancer2::Core::Session.
    let rt = fa.sub_return_type_at_arity("session", None);
    assert_eq!(
        rt,
        Some(InferredType::ClassName("Dancer2::Core::Session".into())),
        "`session` must return Dancer2::Core::Session; got {:?}",
        rt
    );

    // `config` returns a HashRef.
    let rt = fa.sub_return_type_at_arity("config", None);
    assert_eq!(
        rt,
        Some(InferredType::HashRef),
        "`config` must return HashRef; got {:?}",
        rt
    );

    // `uri_for_route` returns a String (URL).
    let rt = fa.sub_return_type_at_arity("uri_for_route", None);
    assert_eq!(
        rt,
        Some(InferredType::String),
        "`uri_for_route` must return String; got {:?}",
        rt
    );

    // `encode_json` returns a String (the serialized JSON).
    let rt = fa.sub_return_type_at_arity("encode_json", None);
    assert_eq!(
        rt,
        Some(InferredType::String),
        "`encode_json` must return String; got {:?}",
        rt
    );

    // `decode_json` returns a HashRef (the deserialized structure).
    let rt = fa.sub_return_type_at_arity("decode_json", None);
    assert_eq!(
        rt,
        Some(InferredType::HashRef),
        "`decode_json` must return HashRef; got {:?}",
        rt
    );

    // `runner` returns the Dancer2::Core::Runner singleton.
    let rt = fa.sub_return_type_at_arity("runner", None);
    assert_eq!(
        rt,
        Some(InferredType::ClassName("Dancer2::Core::Runner".into())),
        "`runner` must return Dancer2::Core::Runner; got {:?}",
        rt
    );
}

/// `use Dancer2::Plugin` also gets the full DSL — plugins
/// re-export via import and expect every DSL word to be in scope.
#[test]
fn plugin_dancer2_plugin_also_autoimports() {
    let src = r#"
package MyApp::Plugin::Foo;
use Dancer2::Plugin;

register my_keyword => sub { my $dsl = shift; $dsl->param('x') };
"#;
    let fa = build_fa(src);
    for kw in &["get", "post", "param", "request", "session", "config", "debug"] {
        assert!(
            fa.framework_imports.contains(*kw),
            "`{}` must be autoimported by `use Dancer2::Plugin`; got {:?}",
            kw,
            fa.framework_imports,
        );
    }
}

/// Unrelated `use` statements must NOT inject Dancer2 keywords.
/// Guards against the trigger firing too broadly.
#[test]
fn plugin_dancer2_skips_unrelated_use() {
    let src = r#"
package main;
use Mojolicious::Lite;
"#;
    let fa = build_fa(src);
    // `param` is a Dancer2 keyword — it should NOT appear in
    // framework_imports just because of Mojolicious::Lite.
    // (Mojolicious::Lite does not expose `param` as a standalone function.)
    // We verify via the synthesized Sub symbol: the dancer plugin
    // should not have emitted one.
    let dancer_stubs = fa
        .symbols
        .iter()
        .filter(|s| {
            s.name == "dancer_app"
                && matches!(
                    &s.namespace,
                    crate::file_analysis::Namespace::Framework { id } if id == "dancer"
                )
        })
        .count();
    assert_eq!(
        dancer_stubs, 0,
        "dancer plugin must not emit stubs for `use Mojolicious::Lite`"
    );
}

// ---- Red-pin: regressions caught against the rhai-plugins branch ----

/// `my` is lexical and crosses statement-form `package X;`
/// boundaries. The branch's sibling `ScopeKind::Package` was
/// originally swallowing `my` decls, so a use site under
/// `package main;` couldn't resolve a `my` declared under
/// `package Calculator;` earlier in the same file. e2e
/// `rename: $pi$tau` turned red on the interpolated-string
/// occurrence (the only `$pi` use under `package main;`); this
/// pins the underlying `resolves_to` linkage so the regression
/// can't sneak back in if the scope tree is reshuffled.
#[test]
fn red_pin_my_resolves_across_statement_packages() {
    let src = "\
package Calculator;
my $pi = 3.14159;
sub circumference { my ($self, $r) = @_; return 2 * $pi * $r }

package main;
print \"pi is $pi\\n\";
";
    let fa = build_fa(src);
    let pi_sym = fa
        .symbols
        .iter()
        .find(|s| s.name == "$pi" && s.kind == SymKind::Variable)
        .expect("$pi Variable symbol");
    let pi_refs: Vec<_> = fa.refs.iter().filter(|r| r.target_name == "$pi").collect();
    assert_eq!(pi_refs.len(), 3, "decl + body use + interpolation = 3 refs");
    for r in &pi_refs {
        assert_eq!(
            r.resolves_to,
            Some(pi_sym.id),
            "ref at {:?} (scope {:?}) didn't resolve to the lexical decl — \
                 sibling Package scopes are leaking into variable lookup",
            r.span.start,
            r.scope,
        );
    }
}

/// `our` is package-global with a lexical alias — bare `$version`
/// from a sibling `package main;` does NOT reach an `our $version`
/// declared under an earlier `package Calculator;` (you'd have to
/// spell `$Calculator::version`). The mirror of
/// `red_pin_my_resolves_across_statement_packages`: that test
/// guarantees `my` keeps crossing package boundaries; this one
/// guarantees `our` keeps NOT crossing them. Pinned now so the
/// scope-separation refactor — which moves variables onto the
/// real lexical scope tree — doesn't accidentally let `our` leak
/// across siblings the way it would if we forgot to keep `our`
/// attached to the package-context scope.
#[test]
fn red_pin_our_does_not_resolve_across_statement_packages() {
    let src = "\
package Calculator;
our $version = 1;
sub bump { $version++ }

package main;
print \"v=$version\\n\";
";
    let fa = build_fa(src);
    let our_sym = fa
        .symbols
        .iter()
        .find(|s| s.name == "$version" && s.kind == SymKind::Variable)
        .expect("$version Variable symbol");
    // Under Calculator the bare $version refs SHOULD resolve to
    // the our-decl: that's the lexical alias half of `our`.
    let bump_use = fa
        .refs
        .iter()
        .find(|r| r.target_name == "$version" && r.span.start.row == 2)
        .expect("ref inside Calculator's bump");
    assert_eq!(
        bump_use.resolves_to,
        Some(our_sym.id),
        "bare $version inside the same package as the `our` decl \
             must still resolve to it (lexical alias)"
    );
    // Under `package main;` the bare $version must NOT resolve.
    let main_use = fa
        .refs
        .iter()
        .find(|r| r.target_name == "$version" && r.span.start.row == 5)
        .expect("ref inside package main's print");
    assert_eq!(
        main_use.resolves_to, None,
        "bare $version under a sibling `package main;` must not \
             reach Calculator's `our $version` — that's $Calculator::version, \
             a different binding"
    );
}

/// Caller-side `HashKeyAccess` for a method/function call's
/// even-position stringy args. `MooApp->new(name => 'alice')`
/// must emit a HashKeyAccess at the `name` token so
/// cursor-on-key resolves to the `has`-emitted HashKeyDef
/// instead of the broad MethodCall ref. Gated on a matching
/// HashKeyDef existing — emission would otherwise shadow the
/// `class Foo { field $x :param }` `find_param_field`
/// fallback. e2e `rename: 'name' constructor arg` was the
/// surfacing failure.
#[test]
fn red_pin_call_arg_emits_hash_key_access_when_def_exists() {
    let src = "\
package MooApp;
use Moo;
has name => (is => 'ro');

package main;
my $m = MooApp->new(name => 'alice');
";
    let fa = build_fa(src);
    let name_access: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "name" && matches!(r.kind, RefKind::HashKeyAccess { .. }))
        .collect();
    assert!(
        !name_access.is_empty(),
        "no HashKeyAccess emitted for `name` in MooApp->new(name => 'alice')",
    );
    let RefKind::HashKeyAccess {
        owner: Some(owner), ..
    } = &name_access[0].kind
    else {
        panic!("HashKeyAccess emitted with no owner");
    };
    assert_eq!(
        *owner,
        HashKeyOwner::Sub {
            package: Some("MooApp".to_string()),
            name: "new".to_string()
        },
        "constructor-key owner should be Sub{{class, method}}, matching the has-emitted def",
    );

    // No matching HashKeyDef for `count` → no shadow ref.
    let count_access: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "count" && matches!(r.kind, RefKind::HashKeyAccess { .. }))
        .collect();
    let src_no_def = "\
package Plain;
sub run {}

package main;
my $p = Plain->run(count => 1);
";
    let fa2 = build_fa(src_no_def);
    let no_emit: Vec<_> = fa2
        .refs
        .iter()
        .filter(|r| r.target_name == "count" && matches!(r.kind, RefKind::HashKeyAccess { .. }))
        .collect();
    assert!(
        no_emit.is_empty(),
        "no HashKeyDef registered for Plain::run/count → \
             must not emit a phantom HashKeyAccess (would shadow other resolution paths)",
    );
    // `count` accesses on MooApp (which DOESN'T define count) — should not emit either.
    assert!(
        count_access.is_empty(),
        "MooApp has no `count` HashKeyDef → no HashKeyAccess emission expected",
    );
}

/// `=>` is autoquoting sugar for `,` — `f(name => 'alice')` and
/// `f('name', 'alice')` are the same call. The HashKeyAccess
/// emission must be position-based (every odd-indexed stringy
/// arg is a key), NOT keyed off the `=>` token. Pinning this
/// because the original draft of the helper walked siblings
/// looking for `=>` and would have missed the bare-comma form
/// — letting cursor-on-key in the bare-comma shape land on
/// the broad MethodCall ref, which renames the wrong token.
#[test]
fn red_pin_hash_key_access_emission_is_position_based() {
    // Same `has`-emitted def, two call shapes. Both should land
    // a HashKeyAccess at `name`, with the same owner.
    let fat_comma_src = "\
package MooApp;
use Moo;
has name => (is => 'ro');

package main;
my $a = MooApp->new(name => 'alice');
";
    let bare_comma_src = "\
package MooApp;
use Moo;
has name => (is => 'ro');

package main;
my $a = MooApp->new('name', 'alice');
";
    let fa_fat = build_fa(fat_comma_src);
    let fa_bare = build_fa(bare_comma_src);

    // Constructor call site only — the `has name` declaration
    // synthesizes its own internal-key refs that we're not
    // asserting on here.
    fn name_access_at_call<'a>(fa: &'a FileAnalysis) -> Vec<&'a Ref> {
        fa.refs
            .iter()
            .filter(|r| {
                r.target_name == "name"
                    && matches!(r.kind, RefKind::HashKeyAccess { .. })
                    && r.span.start.row == 5
            })
            .collect()
    }

    let fat_refs = name_access_at_call(&fa_fat);
    let bare_refs = name_access_at_call(&fa_bare);

    assert_eq!(
        fat_refs.len(),
        1,
        "fat-comma form should emit exactly one HashKeyAccess at the call site",
    );
    assert_eq!(
        bare_refs.len(),
        1,
        "bare-comma form (`'name', 'alice'`) must emit the same HashKeyAccess — \
             `=>` is autoquoting sugar, not a structural marker",
    );

    let owner_of = |r: &Ref| match &r.kind {
        RefKind::HashKeyAccess { owner: Some(o), .. } => o.clone(),
        _ => panic!("expected HashKeyAccess with owner"),
    };
    assert_eq!(
        owner_of(fat_refs[0]),
        owner_of(bare_refs[0]),
        "both forms must produce the same Sub{{MooApp, new}} owner",
    );

    // Even-indexed args ARE keys; odd-indexed (values) must
    // NOT get a HashKeyAccess regardless of whether they happen
    // to look like a key string. `'alice'` at idx 1 stays a value.
    for fa in [&fa_fat, &fa_bare] {
        let alice_access: Vec<_> = fa
            .refs
            .iter()
            .filter(|r| r.target_name == "alice" && matches!(r.kind, RefKind::HashKeyAccess { .. }))
            .collect();
        assert!(
            alice_access.is_empty(),
            "value-position arg must never become a HashKeyAccess",
        );
    }

    // Multi-pair, all bare commas — `('a', 1, 'b', 2)`. Both
    // `a` and `b` are keys (idx 0 and 2); `1` and `2` aren't
    // stringy so they don't even tempt the helper. Need a def
    // for each so emission isn't gated out.
    let multi_src = "\
package MooApp;
use Moo;
has a => (is => 'ro');
has b => (is => 'ro');

package main;
my $m = MooApp->new('a', 1, 'b', 2);
";
    let fa_multi = build_fa(multi_src);
    let call_keys: Vec<&Ref> = fa_multi
        .refs
        .iter()
        .filter(|r| {
            matches!(r.kind, RefKind::HashKeyAccess { .. })
                && r.span.start.row == 6
                && (r.target_name == "a" || r.target_name == "b")
        })
        .collect();
    assert_eq!(
        call_keys.len(),
        2,
        "both even-position args (`'a'`, `'b'`) must emit HashKeyAccess",
    );
}

/// Carp's canonical shape: `longmess` (caller) is defined before
/// `longmess_heavy` (callee). Both arms of the if/else return the
/// forward-defined call, so the per-sub fold should agree on `String`
/// — but only if the walk-time symbol-table miss for `longmess_heavy`
/// is recovered post-walk. `resolve_forward_call_targets` is what
/// makes this work; without it the bag has no `Expr(call_span)`
/// witness at all and `longmess` returns `None`.
#[test]
fn forward_reference_call_in_sub_return_resolves() {
    let src = r#"
package main;

sub longmess {
    if ($_[0]) {
        return longmess_heavy(@_);
    }
    else {
        return longmess_heavy(@_);
    }
}

sub longmess_heavy { return "ouch"; }
"#;
    let fa = build_fa(src);
    let rt = fa.sub_return_type_at_arity("longmess", None);
    assert_eq!(
        rt,
        Some(InferredType::String),
        "longmess must fold to String through both arms — \
         got {:?}. Walk-order regression: longmess_heavy is \
         defined after longmess.",
        rt,
    );
}

/// Single-arm forward call: implicit `return forward()` should fold
/// to whatever `forward()` returns. No branch arms — exercises the
/// `Symbol ← branch_arm Edge → Expr(body) → Edge(Symbol(callee))`
/// chain at minimum width.
#[test]
fn forward_reference_implicit_return_resolves() {
    let src = r#"
package main;

sub caller_sub { forward_sub() }

sub forward_sub { return "ok"; }
"#;
    let fa = build_fa(src);
    assert_eq!(
        fa.sub_return_type_at_arity("caller_sub", None),
        Some(InferredType::String),
    );
}

/// Forward reference inside a ternary return. Each arm calls a
/// different forward-defined sub; both must resolve so the ternary's
/// `BranchArmFold` agrees on `String`. Mixes the forward-ref fix with
/// the existing ternary path (`emit_expr_witness` recursion + arm
/// witnesses on the ternary span).
#[test]
fn forward_reference_in_ternary_arms_resolves() {
    let src = r#"
package main;

sub dispatch {
    return $_[0] ? handle_a() : handle_b();
}

sub handle_a { return "a"; }
sub handle_b { return "b"; }
"#;
    let fa = build_fa(src);
    assert_eq!(
        fa.sub_return_type_at_arity("dispatch", None),
        Some(InferredType::String),
    );
}

/// Scoped-identifier call: `Pkg::name()` form. `expr_payload`'s
/// `bareword`/`scoped_identifier` arm does the same walk-time lookup
/// as `function_call_expression`; the queue + post-walk resolve must
/// cover it too.
#[test]
fn forward_reference_scoped_identifier_call_resolves() {
    let src = r#"
package main;

sub bridge { return Helper::canon(); }

package Helper;

sub canon { return "yes"; }
"#;
    let fa = build_fa(src);
    assert_eq!(
        fa.sub_return_type_at_arity("bridge", None),
        Some(InferredType::String),
    );
}

/// Self-method tail with a forward-defined target. `$self->later()`
/// where `later` is declared after the caller. The MethodOnClass
/// chase needs the callee's `Symbol(sid)` writeback, which only fires
/// once the callee's own `Expr(body)` is populated — exercising the
/// forward-ref fix on the inner sub's body, not the call site itself.
#[test]
fn forward_reference_self_method_call_resolves() {
    let src = r#"
package Box;

sub new { my $class = shift; return bless {}, $class; }

sub head {
    my ($self) = @_;
    return $self->tail();
}

sub tail {
    my ($self) = @_;
    return helper();
}

sub helper { return "fin"; }
"#;
    let fa = build_fa(src);
    assert_eq!(
        fa.sub_return_type_at_arity("tail", None),
        Some(InferredType::String),
    );
}

// ---- SyntheticUse — plugin-emitted `use` statements ------------------------
//
// `EmitAction::SyntheticUse` lets a plugin react to a kit module's outer
// use (e.g. `use Co::Base -Class`) by injecting the inner `use`s that the
// kit performs at runtime (`Moo`, `parent`, etc.). The point is that the
// downstream effect — framework detection, has-synthesis, parent
// inheritance, plugin re-dispatch — is identical to what the user would
// have gotten by writing those `use` lines literally. The test below
// drives the kit path through a stub plugin and compares against a
// literal build.
mod synthetic_use {
    use super::*;
    use crate::file_analysis::Namespace;
    use crate::plugin::{
        CompletionQueryContext, EmitAction, FrameworkPlugin, PluginCompletionAnswer,
        PluginRegistry, PluginSigHelpAnswer, SigHelpQueryContext, Trigger, UseContext,
    };
    use std::sync::Arc;

    /// Catches `use Co::Base -Class` and emits a synthetic `use Moo`.
    /// One trigger (`Always`), one hook (`on_use`), zero overrides.
    /// Stripped to the minimum that exercises the path.
    struct CoBasePlugin;

    impl FrameworkPlugin for CoBasePlugin {
        fn id(&self) -> &str { "co-base-test" }
        fn triggers(&self) -> &[Trigger] {
            // `on_use` bypasses the trigger filter (every plugin sees
            // every use), so the trigger list here is incidental. Kept
            // non-empty to mirror real plugins.
            static T: [Trigger; 1] = [Trigger::Always];
            &T
        }
        fn on_use(&self, ctx: &UseContext) -> Vec<EmitAction> {
            if ctx.module_name != "Co::Base" { return Vec::new(); }
            let is_class = ctx.raw_args.iter().any(|a| a == "-Class");
            if !is_class { return Vec::new(); }
            vec![EmitAction::SyntheticUse {
                module: "Moo".into(),
                args: vec![],
                imports: vec![],
                span: ctx.span,
            }]
        }
        fn on_signature_help(&self, _: &SigHelpQueryContext) -> Option<PluginSigHelpAnswer> { None }
        fn on_completion(&self, _: &CompletionQueryContext) -> Option<PluginCompletionAnswer> { None }
    }

    fn registry_with_co_base() -> Arc<PluginRegistry> {
        let mut reg = PluginRegistry::new();
        reg.register(Box::new(CoBasePlugin));
        Arc::new(reg)
    }

    fn build_with(source: &str, plugins: Arc<PluginRegistry>) -> FileAnalysis {
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&ts_parser_perl::LANGUAGE.into()).unwrap();
        let tree = parser.parse(source, None).unwrap();
        super::super::build_with_plugins(&tree, source.as_bytes(), plugins)
    }

    /// `use Co::Base -Class` (via the stub kit plugin) produces the same
    /// observable downstream state as a literal `use Moo`:
    ///
    ///   * `package_framework` carries `Moo` for the package.
    ///   * `framework_imports` covers Moo's keyword set.
    ///   * `has 'name'` synthesizes the accessor Method.
    ///
    /// Anything that depends on those — has-synthesis, accessor symbols,
    /// inheritance via `with`/`extends`, the constructor key, downstream
    /// plugin chains — comes along for free because it reads the same
    /// state. We pin only the load-bearing axes; broader Moo behavior
    /// has its own dedicated tests.
    #[test]
    fn synthetic_use_moo_matches_literal_use_moo() {
        let kit_src = r#"
package Foo;
use Co::Base -Class;
has 'name' => (is => 'ro');
"#;
        let lit_src = r#"
package Foo;
use Moo;
has 'name' => (is => 'ro');
"#;
        let kit = build_with(kit_src, registry_with_co_base());
        let lit = build_with(lit_src, registry_with_co_base());

        // Both should record Moo as the active framework for Foo.
        assert_eq!(
            kit.package_framework.get("Foo"),
            lit.package_framework.get("Foo"),
            "kit (`use Co::Base -Class`) and literal (`use Moo`) must agree on package_framework"
        );
        assert!(
            kit.package_framework.contains_key("Foo"),
            "Foo's framework should be set by SyntheticUse \"Moo\"; package_framework={:?}",
            kit.package_framework,
        );

        // Both should have Moo's keyword set in framework_imports.
        for kw in &["has", "with", "extends", "around", "before", "after"] {
            assert!(
                kit.framework_imports.contains(*kw),
                "SyntheticUse \"Moo\" must populate framework_imports[{kw}]; got {:?}",
                kit.framework_imports,
            );
        }

        // The `has 'name'` accessor synthesis depends on framework_modes
        // being set at the time `visit_has_call` fires. With SyntheticUse,
        // the kit's `use Co::Base -Class` precedes `has`, so the plugin
        // re-dispatch flips the mode before the has-call is walked.
        let kit_methods: Vec<&str> = kit.symbols.iter()
            .filter(|s| s.name == "name" && s.kind == SymKind::Method)
            .map(|s| s.name.as_str())
            .collect();
        let lit_methods: Vec<&str> = lit.symbols.iter()
            .filter(|s| s.name == "name" && s.kind == SymKind::Method)
            .map(|s| s.name.as_str())
            .collect();
        assert_eq!(
            kit_methods, lit_methods,
            "`has 'name'` should synthesize the same accessor Methods under \
             SyntheticUse \"Moo\" as under literal `use Moo`",
        );
        assert_eq!(kit_methods.len(), 1, "ro getter is exactly one Method");

        // Provenance: the synthesized `Moo` Module symbol in the kit
        // build carries the emitting plugin's namespace tag; the
        // literal build's `Moo` Module is plain `Language`. This is
        // the one observable axis where the two builds are SUPPOSED
        // to differ — it's what lets `--dump-package` / outline /
        // completion filters surface "this came from co-base-test".
        let kit_moo = kit.symbols.iter()
            .find(|s| s.kind == SymKind::Module && s.name == "Moo")
            .expect("kit build must have a Module symbol for synthesized `use Moo`");
        assert_eq!(
            kit_moo.namespace,
            Namespace::framework("co-base-test"),
            "synthesized Module must carry the emitting plugin's namespace tag"
        );
        let lit_moo = lit.symbols.iter()
            .find(|s| s.kind == SymKind::Module && s.name == "Moo")
            .expect("literal build must have a Module symbol for `use Moo`");
        assert_eq!(
            lit_moo.namespace,
            Namespace::Language,
            "literal-source Module must stay on Namespace::Language (no plugin tag)"
        );
    }

    /// `use_dedup` short-circuits cycles. The stub plugin reacts to
    /// `use Co::Base` by emitting `SyntheticUse "Co::Base"` — if the
    /// gate didn't catch it, the on_use re-dispatch would loop and
    /// produce many duplicate Module symbols / Import entries.
    /// With dedup, the second emission is a no-op.
    #[test]
    fn synthetic_use_self_cycle_is_bounded() {
        struct LoopPlugin;
        impl FrameworkPlugin for LoopPlugin {
            fn id(&self) -> &str { "loop-test" }
            fn triggers(&self) -> &[Trigger] {
                static T: [Trigger; 1] = [Trigger::Always];
                &T
            }
            fn on_use(&self, ctx: &UseContext) -> Vec<EmitAction> {
                if ctx.module_name != "Co::Base" { return Vec::new(); }
                vec![EmitAction::SyntheticUse {
                    module: "Co::Base".into(),
                    args: vec![],
                    imports: vec![],
                    span: ctx.span,
                }]
            }
            fn on_signature_help(&self, _: &SigHelpQueryContext) -> Option<PluginSigHelpAnswer> { None }
            fn on_completion(&self, _: &CompletionQueryContext) -> Option<PluginCompletionAnswer> { None }
        }
        let mut reg = PluginRegistry::new();
        reg.register(Box::new(LoopPlugin));
        let fa = build_with("package Foo; use Co::Base;\n", Arc::new(reg));

        let co_base_imports = fa.imports.iter()
            .filter(|i| i.module_name == "Co::Base")
            .count();
        assert_eq!(
            co_base_imports, 1,
            "self-cycle must collapse to one Import entry; use_dedup gate kicked in"
        );

        let module_syms = fa.symbols.iter()
            .filter(|s| s.kind == SymKind::Module && s.name == "Co::Base")
            .count();
        assert_eq!(module_syms, 1, "self-cycle must emit one Module symbol");

        // Belt-and-suspenders for the gate. The dedup short-circuits at
        // the top of `process_use`, so every downstream effect is bounded
        // by construction — but pinning each axis catches a future
        // regression where the gate gets moved or `process_use` gets
        // split. If any of these grow without the others, something's
        // half-processing the cycle.
        let co_base_uses = fa.symbols.iter()
            .filter(|s| s.kind == SymKind::Module && s.name == "Co::Base")
            .count();
        assert_eq!(
            co_base_uses, 1,
            "package_uses-equivalent (Module symbol count) should match Import count"
        );
        // `framework_imports` for `use Co::Base` (not a built-in framework
        // module): the bundled plugins shouldn't touch it. Cycle should
        // leave this empty whether it loops once or a thousand times.
        assert!(
            fa.framework_imports.is_empty()
                || fa.framework_imports.iter().all(|s| !s.starts_with("co_base_")),
            "cycle on a non-framework module should not leak Co::Base-tagged keywords \
             into framework_imports; got {:?}",
            fa.framework_imports,
        );
    }

    /// `imports` MUST be part of the dedup key. Real `use Foo qw(a)` and
    /// `use Foo qw(b)` discriminate via `extract_mojo_base_args`'s
    /// fallback to `extract_use_import_list` (the fallback fires when
    /// no barewords / literals are present, putting qw imports in
    /// `raw_args`). Synthetic emissions carry `args` and `imports` as
    /// separate fields, so the equivalent two SyntheticUses with
    /// different `imports` and empty `args` must NOT collide on the
    /// dedup key. Pre-fix, both keyed on `(pkg, "Foo", [])` and the
    /// second silently dropped.
    #[test]
    fn synthetic_use_distinct_imports_both_emit() {
        struct ImportPlugin;
        impl FrameworkPlugin for ImportPlugin {
            fn id(&self) -> &str { "imports-test" }
            fn triggers(&self) -> &[Trigger] {
                static T: [Trigger; 1] = [Trigger::Always];
                &T
            }
            fn on_use(&self, ctx: &UseContext) -> Vec<EmitAction> {
                if ctx.module_name != "Trigger::Kit" { return Vec::new(); }
                vec![
                    EmitAction::SyntheticUse {
                        module: "Foo".into(),
                        args: vec![],
                        imports: vec!["a".into()],
                        span: ctx.span,
                    },
                    EmitAction::SyntheticUse {
                        module: "Foo".into(),
                        args: vec![],
                        imports: vec!["b".into()],
                        span: ctx.span,
                    },
                ]
            }
            fn on_signature_help(&self, _: &SigHelpQueryContext) -> Option<PluginSigHelpAnswer> { None }
            fn on_completion(&self, _: &CompletionQueryContext) -> Option<PluginCompletionAnswer> { None }
        }
        let mut reg = PluginRegistry::new();
        reg.register(Box::new(ImportPlugin));
        let fa = build_with("package Foo; use Trigger::Kit;\n", Arc::new(reg));

        let foo_imports: Vec<&crate::file_analysis::Import> = fa.imports.iter()
            .filter(|i| i.module_name == "Foo")
            .collect();
        assert_eq!(
            foo_imports.len(), 2,
            "two SyntheticUse \"Foo\" with distinct imports must both produce \
             Import entries — dedup must NOT collide on the args-only key. \
             Got imports: {:?}",
            foo_imports.iter().map(|i| &i.imported_symbols).collect::<Vec<_>>(),
        );

        // Each Import entry must carry its own qw-style import name.
        // Order-independent: we check the union covers both.
        let all_names: std::collections::HashSet<&str> = foo_imports.iter()
            .flat_map(|i| i.imported_symbols.iter().map(|s| s.local_name.as_str()))
            .collect();
        assert!(all_names.contains("a"), "missing import name 'a': {:?}", all_names);
        assert!(all_names.contains("b"), "missing import name 'b': {:?}", all_names);
    }
}

/// **Spike: array intelligence on the bag-canonical foundation.**
///
/// The headline scenario, top-to-bottom:
///
/// ```perl
/// # Some/User.pm (cross-file)
/// package Some::User;
/// use Mojo::Base -base;
/// has 'name';
/// sub greet { ... }
/// sub email { ... }
///
/// # main
/// package MyApp;
/// use Mojolicious::Lite;
/// use constant DEFAULT_NAME => 'alice';
///
/// helper make_user => sub {
///     my ($c, $name) = @_;
/// .   return Some::User->new(name => $name);
/// };
///
/// sub action {
///     my $c = Mojolicious::Controller->new;
///     my @users;
///     push @users, $c->make_user(DEFAULT_NAME);   # const fold + plugin helper
///     push @users, $c->make_user('bob');
///     $users[0]->                                  # ← method completion here
/// }
/// ```
///
/// The chain through `$users[0]`:
///   1. mojo-helpers plugin synthesizes `make_user` on
///      `Mojolicious::Controller` with `return_via_edge` pointing
///      at the anon-sub's body.
///   2. Coderef-return edge resolves the body's last expression
///      (`Some::User->new(...)`) → `ClassName("Some::User")`.
///   3. `push @users, $c->make_user(...)` contributes
///      `ClassName("Some::User")` to `@users`'s `Sequence` shape.
///   4. `$users[0]` projects the Sequence to its first element.
///   5. Method / hash-key completion on the projected class crosses
///      the file boundary into `Some::User.pm`.
///
/// The **new** code on this branch is purely the array hop —
/// declaration emission, `push` contribution, and projection at
/// `$users[N]`. Everything else (helper synth, coderef return,
/// const fold, cross-file dispatch, Mojo::Base hash-key defs)
/// drops out of the existing bag-canonical machinery for free.
#[test]
fn spike_array_hop_with_helper_and_cross_file_completion() {
    use crate::module_index::ModuleIndex;
    use std::path::PathBuf;
    use std::sync::Arc;

    let user_pm = r#"
package Some::User;
use Mojo::Base -base;
has 'name';
sub greet { my $self = shift; "hi $self->{name}" }
sub email { my $self = shift; "$self->{name}\@x.com" }
1;
"#;
    let user_fa = build_fa(user_pm);

    let idx = ModuleIndex::new_for_test();
    idx.register_workspace_module(
        PathBuf::from("/tmp/Some/User.pm"),
        Arc::new(user_fa),
    );

    let app_src = r#"
package MyApp;
use Mojolicious::Lite;
use constant DEFAULT_NAME => 'alice';

my $app = Mojolicious->new;
$app->helper(make_user => sub {
    my ($c, $name) = @_;
    return Some::User->new(name => $name);
});

sub action {
    my $c = Mojolicious::Controller->new;
    my @users;
    push @users, $c->make_user(DEFAULT_NAME);
    push @users, $c->make_user('bob');
    $users[0]->greet();
}
"#;
    let app_fa = build_fa(app_src);

    // Load-bearing: walk the tree to find the `$users[0]` node and
    // ask `resolve_expression_type` what it is. This is the receiver
    // resolution path the chain typer + cursor context both go
    // through for completion.
    let tree = parse(app_src);
    fn find_array_element<'a>(node: tree_sitter::Node<'a>) -> Option<tree_sitter::Node<'a>> {
        if node.kind() == "array_element_expression" {
            return Some(node);
        }
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if let Some(hit) = find_array_element(child) {
                return Some(hit);
            }
        }
        None
    }
    let elem_node = find_array_element(tree.root_node())
        .expect("test source contains `$users[0]`");
    let resolved = crate::cursor_context::resolve_expression_type(&app_fa, elem_node, app_src.as_bytes(), Some(&idx))
        .expect("$users[0] resolves to a type");
    assert_eq!(
        resolved.class_name(),
        Some("Some::User"),
        "the array hop survives the chain: helper(coderef) → push → \
         $users[0] → Some::User. got: {:?}",
        resolved,
    );

    // Cross-file method completion on the resolved class. Mojo::Base
    // accessor (`name`) + user-defined methods come through unified.
    let methods = app_fa.complete_methods_for_class("Some::User", Some(&idx));
    let method_names: std::collections::HashSet<&str> =
        methods.iter().map(|c| c.label.as_str()).collect();
    assert!(method_names.contains("greet"), "cross-file user method 'greet' missing");
    assert!(method_names.contains("email"), "cross-file user method 'email' missing");
    assert!(method_names.contains("name"), "Mojo::Base accessor 'name' missing");

    // Hash-key completion on the same class — synthesized by
    // `has 'name'`, reachable across files. Cross-file hash-key
    // completion flows through enrichment; the local
    // `complete_hash_keys_for_class` doesn't gate on `ModuleIndex`,
    // so this stays a soft observation for the spike rather than a
    // hard assert. The load-bearing claim is the array hop, not the
    // FA-side hash-key API.
    let keys = app_fa.complete_hash_keys_for_class("Some::User", Point::new(0, 0));
    let key_names: std::collections::HashSet<&str> =
        keys.iter().map(|c| c.label.as_str()).collect();
    let _ = key_names; // intentionally not asserted in the spike

    // Hover on `$users[0]->greet` — the tree-aware
    // `method_call_invocant_class_with_tree` path. The string-side
    // `method_call_invocant_class` couldn't resolve `$users[0]`
    // (it isn't a Variable witness name); the tree-aware variant
    // dispatches through `resolve_expression_type` on the actual
    // CST node, hitting the same array_element_expression arm
    // cursor_context uses for completion. One projection rule,
    // both entry points.
    fn find_method_call<'a>(
        node: tree_sitter::Node<'a>,
        src: &[u8],
        method: &str,
    ) -> Option<tree_sitter::Node<'a>> {
        if node.kind() == "method_call_expression" {
            if let Some(m) = node.child_by_field_name("method") {
                if m.utf8_text(src).ok() == Some(method) {
                    return Some(node);
                }
            }
        }
        let mut cursor = node.walk();
        for child in node.children(&mut cursor) {
            if let Some(hit) = find_method_call(child, src, method) {
                return Some(hit);
            }
        }
        None
    }
    let greet_call = find_method_call(tree.root_node(), app_src.as_bytes(), "greet")
        .expect("test source contains `$users[0]->greet()`");
    let method_node = greet_call
        .child_by_field_name("method")
        .expect("method-call has a method child");
    let hover = app_fa.hover_info(
        method_node.start_position(),
        app_src,
        Some(&idx),
    );
    let hover_text = hover.expect("hover on `$users[0]->greet` returns text");
    assert!(
        hover_text.contains("Some::User"),
        "hover on `$users[0]->greet` should mention Some::User; got: {}",
        hover_text,
    );
    assert!(
        hover_text.contains("greet"),
        "hover should include the method name; got: {}",
        hover_text,
    );
}

/// `has x => (isa => InstanceOf['Foo'])` — the constraint is `InstanceOf['Foo']`,
/// a Type::Tiny constraint *value*, not a class. The core types that call
/// expression as `TypeConstraintOf(ClassName(Foo))` (plugin fold), and the
/// accessor projects the constrained inner, so `x` returns `Foo`.
#[test]
fn moo_instanceof_isa_types_accessor_to_inner_class() {
    let fa = build_fa(
        "package T;\nuse Moo;\nuse Types::Standard qw/InstanceOf/;\nhas thing => (is => 'ro', isa => InstanceOf['My::Thing']);\n1;\n",
    );
    assert_eq!(
        fa.sub_return_type_at_arity("thing", Some(0)),
        Some(InferredType::ClassName("My::Thing".to_string())),
        "InstanceOf['My::Thing'] isa must give the getter a My::Thing return",
    );
}

/// The constructor expression itself is a `TypeConstraintOf` — NOT the inner
/// class. `$t->name` must see a constraint (so it can route to Type::Tiny
/// later), and an `isa => $t` projects the inner. This guards against the
/// lossy "InstanceOf['Foo'] == ClassName(Foo)" shortcut we rejected.
#[test]
fn instanceof_expression_is_a_type_constraint_not_the_class() {
    let fa = build_fa(
        "package T;\nuse Moo;\nuse Types::Standard qw/InstanceOf/;\nmy $t = InstanceOf['My::Thing'];\n1;\n",
    );
    let ty = fa
        .inferred_type_via_bag("$t", Point::new(3, 20))
        .expect("$t should carry a type");
    assert!(
        matches!(&ty, InferredType::TypeConstraintOf(inner)
            if matches!(inner.as_ref(), InferredType::ClassName(c) if c == "My::Thing")),
        "InstanceOf['My::Thing'] is a TypeConstraintOf(ClassName(My::Thing)), got {:?}",
        ty,
    );
    assert!(
        ty.constrained_inner().and_then(|i| i.class_name()) == Some("My::Thing"),
        "constrained_inner projects the class for the isa→accessor path",
    );
}

/// const-fold / variable path: `my $t = InstanceOf['Foo']; has x => (isa => $t)`.
/// `has` edges to the RHS `$t`, whose type is the constraint, and projects the
/// inner — no special handling of the variable form.
#[test]
fn moo_isa_via_constraint_variable_projects_inner() {
    let fa = build_fa(
        "package T;\nuse Moo;\nuse Types::Standard qw/InstanceOf/;\nmy $t = InstanceOf['My::Thing'];\nhas thing => (is => 'ro', isa => $t);\n1;\n",
    );
    assert_eq!(
        fa.sub_return_type_at_arity("thing", Some(0)),
        Some(InferredType::ClassName("My::Thing".to_string())),
        "isa => $constraint_var must project the constrained inner onto the accessor",
    );
}

// ---- isa coverage: the TypeConstraintOf path + the string/bareword split ----

/// String/bareword isa (the Moose idiom + builtins) stays on the meaning-map,
/// untouched by the constraint path. Regression guard that adding the node
/// path didn't break the common forms.
#[test]
fn moo_string_isa_forms_still_resolve() {
    let fa = build_fa(
        "package T;\nuse Moo;\nhas s => (is=>'ro', isa=>'Str');\nhas i => (is=>'ro', isa=>'Int');\nhas h => (is=>'ro', isa=>'HashRef');\n1;\n",
    );
    assert_eq!(fa.sub_return_type_at_arity("s", Some(0)), Some(InferredType::String));
    assert_eq!(fa.sub_return_type_at_arity("i", Some(0)), Some(InferredType::Numeric));
    assert_eq!(fa.sub_return_type_at_arity("h", Some(0)), Some(InferredType::HashRef));
}

/// `is => 'rw'` synthesizes a writer too; both getter (arity 0) and writer
/// (arity ≥1) return the constrained inner class.
#[test]
fn moo_instanceof_isa_types_both_getter_and_writer() {
    let fa = build_fa(
        "package T;\nuse Moo;\nuse Types::Standard qw/InstanceOf/;\nhas thing => (is=>'rw', isa=>InstanceOf['My::Thing']);\n1;\n",
    );
    let want = Some(InferredType::ClassName("My::Thing".to_string()));
    assert_eq!(fa.sub_return_type_at_arity("thing", Some(0)), want.clone(), "getter");
    assert_eq!(fa.sub_return_type_at_arity("thing", Some(1)), want, "rw writer");
}

/// `Maybe[InstanceOf['Foo']]` — the nested constructor is itself a constraint
/// value. The core types the inner call (`TypeConstraintOf(ClassName(Foo))`)
/// into the param's `ty`; the `Maybe` passthrough fold projects its inner, so
/// the accessor returns `Foo` (optionalness unmodeled — unwrap for resolution).
#[test]
fn moo_maybe_instanceof_isa_unwraps_to_inner_class() {
    let fa = build_fa(
        "package T;\nuse Moo;\nuse Types::Standard qw/Maybe InstanceOf/;\nhas thing => (is=>'ro', isa=>Maybe[InstanceOf['My::Thing']]);\n1;\n",
    );
    assert_eq!(
        fa.sub_return_type_at_arity("thing", Some(0)),
        Some(InferredType::ClassName("My::Thing".to_string())),
        "Maybe[InstanceOf['My::Thing']] must unwrap to a My::Thing accessor return",
    );
}

/// `ConsumerOf['Role']` shares the ClassParam shape (you can call the role's
/// methods on the value) — declared by the same plugin manifest entry.
#[test]
fn moo_consumerof_isa_types_accessor() {
    let fa = build_fa(
        "package T;\nuse Moo;\nuse Types::Standard qw/ConsumerOf/;\nhas r => (is=>'ro', isa=>ConsumerOf['My::Role']);\n1;\n",
    );
    assert_eq!(
        fa.sub_return_type_at_arity("r", Some(0)),
        Some(InferredType::ClassName("My::Role".to_string())),
    );
}

/// crm writes `InstanceOf ['Class']` (space before the bracket). Both spacings
/// parse as the same call node, so both must type.
#[test]
fn moo_instanceof_isa_handles_space_before_bracket() {
    let fa = build_fa(
        "package T;\nuse Moo;\nuse Types::Standard qw/InstanceOf/;\nhas thing => (is=>'ro', isa=>InstanceOf ['My::Thing']);\n1;\n",
    );
    assert_eq!(
        fa.sub_return_type_at_arity("thing", Some(0)),
        Some(InferredType::ClassName("My::Thing".to_string())),
    );
}

/// Moose mode, not just Moo — same constraint vocabulary.
#[test]
fn moose_instanceof_isa_types_accessor() {
    let fa = build_fa(
        "package T;\nuse Moose;\nuse Types::Standard qw/InstanceOf/;\nhas thing => (is=>'ro', isa=>InstanceOf['My::Thing']);\n1;\n",
    );
    assert_eq!(
        fa.sub_return_type_at_arity("thing", Some(0)),
        Some(InferredType::ClassName("My::Thing".to_string())),
    );
}

/// NEGATIVE: a coderef isa (`isa => sub {...}`) isn't a constraint — the
/// accessor must stay untyped, never falsely a class. Guards the projection
/// from over-firing on non-constraint complex RHS.
#[test]
fn moo_coderef_isa_leaves_accessor_untyped() {
    let fa = build_fa(
        "package T;\nuse Moo;\nhas thing => (is=>'ro', isa=>sub { die unless ref $_[0] });\n1;\n",
    );
    assert_eq!(
        fa.sub_return_type_at_arity("thing", Some(0)),
        None,
        "a coderef constraint has no class denotation",
    );
}

/// NEGATIVE: an undeclared constructor (`SomeType['X']`, not in any plugin's
/// type_constraint_names) falls through cleanly — no TypeConstraintOf, no
/// crash, accessor untyped.
#[test]
fn moo_unknown_constructor_isa_falls_through() {
    let fa = build_fa(
        "package T;\nuse Moo;\nhas thing => (is=>'ro', isa=>SomeUnknownType['X']);\n1;\n",
    );
    assert_eq!(fa.sub_return_type_at_arity("thing", Some(0)), None);
}

/// The chain payoff: an `InstanceOf` accessor's class flows into a downstream
/// method call. `$self->other->greet` must resolve `->greet` against `Other`
/// — this is the `$self->_minion->enqueue` shape that the crm fix turns on.
#[test]
fn instanceof_accessor_chains_into_method_call() {
    let src = "package Other;\nuse Moo;\nsub greet ($self) { return 'hi'; }\n\npackage T;\nuse Moo;\nuse Types::Standard qw/InstanceOf/;\nhas other => (is=>'ro', isa=>InstanceOf['Other']);\nsub use_it ($self) { return $self->other->greet; }\n1;\n";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());
    let idx = crate::module_index::ModuleIndex::new_for_test();

    // Find the `greet` method-call node in `$self->other->greet`.
    fn find_call<'a>(n: tree_sitter::Node<'a>, src: &[u8], m: &str) -> Option<tree_sitter::Node<'a>> {
        if n.kind() == "method_call_expression" {
            if let Some(mn) = n.child_by_field_name("method") {
                if mn.utf8_text(src).ok() == Some(m) { return Some(n); }
            }
        }
        for i in 0..n.named_child_count() {
            if let Some(c) = n.named_child(i) {
                if let Some(f) = find_call(c, src, m) { return Some(f); }
            }
        }
        None
    }
    let call = find_call(tree.root_node(), src.as_bytes(), "greet").expect("has $self->other->greet");
    let method_node = call.child_by_field_name("method").unwrap();
    let hover = fa
        .hover_info(method_node.start_position(), src, Some(&idx))
        .expect("hover on ->greet resolves");
    assert!(
        hover.contains("Other"),
        "->greet on an InstanceOf['Other'] accessor must resolve against Other; got: {hover}",
    );
}

/// Option B resolves a receiver whose type comes from a Mojo HELPER, not a
/// plain method. `$c->minion` (a helper bridged to Mojolicious::Controller,
/// returning a Minion subclass) → `$c->minion->enqueue('T')` must synthesize
/// the dispatch. This is the gap that left `$app->minion`/`$c->minion`
/// chains dark: option-B's enrichment receiver-resolution now threads the
/// index (variable arm) and chases the helper bridge the way hover does.
#[test]
fn provisional_dispatch_resolves_helper_returned_receiver() {
    use crate::file_analysis::HandlerOwner;
    use std::path::PathBuf;
    let idx = crate::module_index::ModuleIndex::new_for_test();
    idx.register_workspace_module(
        PathBuf::from("/tmp/b_hr_minion.pm"),
        std::sync::Arc::new(build_fa("package Acme::Minion;\nuse Mojo::Base 'Minion';\n1;\n")),
    );
    idx.register_workspace_module(
        PathBuf::from("/tmp/b_hr_plugin.pm"),
        std::sync::Arc::new(build_fa(
            "package Acme::Plugin;\nuse Mojo::Base 'Mojolicious::Plugin';\nsub register ($self, $app, $conf) {\n  my $m = Acme::Minion->new;\n  $app->helper(minion => sub {$m});\n  $app->minion->add_task('Task.go' => sub ($job) { 1 });\n}\n1;\n",
        )),
    );

    let fa = build_fa(
        "package Acme::Ctrl;\nuse Mojo::Base 'Mojolicious::Controller';\nsub act ($c) {\n  $c->minion->enqueue('Task.go');\n}\n1;\n",
    );

    // This file hits a Mojo trigger, so the emit-hook materializes the
    // DispatchCall directly (it doesn't gate on the receiver). The handler
    // is surfaced either way; `applicable_dispatches` de-dups the gated
    // candidate against the materialized ref so there's no double-count.
    let has_materialized = fa.refs.iter().any(|r|
        matches!(&r.kind, RefKind::DispatchCall { dispatcher, owner: Some(HandlerOwner::Class(c)) }
            if dispatcher == "enqueue" && c == "Minion")
            && r.target_name == "Task.go");
    let applied = fa.applicable_dispatches(Some(&idx));
    let has_gated = applied.iter().any(|a|
        a.name == "Task.go" && a.owner == HandlerOwner::Class("Minion".into()));
    assert!(
        has_materialized ^ has_gated,
        "the helper-returned receiver $c->minion (Acme::Minion isa Minion) enqueue \
         must surface exactly once — via the emit-hook ref OR the gated candidate, \
         never both; materialized={has_materialized} gated={has_gated} applied={:?}",
        applied,
    );
    assert!(
        has_materialized,
        "this file hits a Mojo trigger, so the emit-hook materializes the dispatch",
    );
}

/// Role-contract parameter typing: a plugin's `param_types()` manifest types a
/// named param of a sub declared in a class that does the rule's role. The
/// motivating case is `Clove::Upgrade::OneTime`'s `run_upgrade ($self, $app)`,
/// where `$app` is the Mojolicious app — a type the source can't express and
/// no callback-arg hook can reach (it's a plain sub declaration).
mod param_types_manifest {
    use super::*;
    use crate::plugin::{
        CompletionQueryContext, FrameworkPlugin, ParamType, PluginCompletionAnswer,
        PluginRegistry, PluginSigHelpAnswer, SigHelpQueryContext, Trigger,
    };
    use std::sync::Arc;

    struct UpgradeRolePlugin;
    impl FrameworkPlugin for UpgradeRolePlugin {
        fn id(&self) -> &str { "upgrade-role-test" }
        fn triggers(&self) -> &[Trigger] {
            static T: [Trigger; 1] = [Trigger::Always];
            &T
        }
        fn param_types(&self) -> &[ParamType] {
            // Built lazily into a static so the &[] borrow is 'static.
            use std::sync::OnceLock;
            static PT: OnceLock<Vec<ParamType>> = OnceLock::new();
            PT.get_or_init(|| {
                vec![ParamType {
                    method: Some("run_upgrade".into()),
                    in_role: "My::Upgrade::Role".into(),
                    param: 1,
                    type_class: "Mojolicious".into(),
                    requires_action_attr: false,
                    from_loader_config: false,
                }]
            })
        }
        fn on_signature_help(&self, _: &SigHelpQueryContext) -> Option<PluginSigHelpAnswer> { None }
        fn on_completion(&self, _: &CompletionQueryContext) -> Option<PluginCompletionAnswer> { None }
    }

    fn build_with_upgrade(source: &str) -> FileAnalysis {
        let mut reg = PluginRegistry::new();
        reg.register(Box::new(UpgradeRolePlugin));
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&ts_parser_perl::LANGUAGE.into()).unwrap();
        let tree = parser.parse(source, None).unwrap();
        crate::builder::build_with_plugins(&tree, source.as_bytes(), Arc::new(reg))
    }

    #[test]
    fn role_doer_run_upgrade_app_param_typed() {
        // `use Moo; with 'Role'` populates package_parents (core framework
        // handling); the manifest then types `$app` as Mojolicious.
        let fa = build_with_upgrade(
            "package My::Doer;\nuse Moo;\nwith 'My::Upgrade::Role';\nsub run_upgrade ($self, $app) {\n  my $x = $app;\n}\n1;\n",
        );
        let ty = fa
            .inferred_type_via_bag("$app", Point::new(4, 10))
            .expect("$app should be typed by the param_types manifest");
        assert!(
            matches!(&ty, InferredType::ClassName(c) if c == "Mojolicious"),
            "role-contract param typing should make $app a Mojolicious, got {:?}",
            ty,
        );
    }

    #[test]
    fn non_doer_same_method_name_not_typed() {
        // Same method name, but the class does NOT do the role → no typing
        // (the rule is role-gated, not name-gated).
        let fa = build_with_upgrade(
            "package Other;\nsub run_upgrade ($self, $app) {\n  my $x = $app;\n}\n1;\n",
        );
        assert_eq!(
            fa.inferred_type_via_bag("$app", Point::new(2, 10)),
            None,
            "a class that doesn't do the role must not get the contract param type",
        );
    }

    // ---- Cross-file manifest-applicability probes ----
    // Whether build-time `transitive_parents`-gated plugin behavior reaches a
    // class whose ancestry is established cross-file. See
    // `docs/prompt-enrichment-inheritance-residual.md`.

    /// `ClassIsa`-triggered plugin emission on a class whose trigger-class
    /// ancestry is only established CROSS-FILE. `Leaf` extends `Mid` (a
    /// cross-file module) which extends `Mojo::EventEmitter`. The
    /// mojo-events plugin's `ClassIsa: "Mojo::EventEmitter"` trigger walks
    /// local `transitive_parents` (builder is index-free during the walk),
    /// which sees only `Mid` — not the cross-file `Mojo::EventEmitter`.
    /// Enrichment can't help: plugin emit hooks fire at parse time, inside
    /// `build()`, before any module index exists.
    ///
    /// Architectural gap, NOT a contained fix — documented as a latent
    /// hazard. See the doc.
    #[test]
    #[ignore = "cross-file ClassIsa trigger: architectural, see docs/prompt-enrichment-inheritance-residual.md"]
    fn probe_class_isa_trigger_through_cross_file_parent() {
        use crate::module_index::ModuleIndex;
        use std::path::PathBuf;
        let idx = ModuleIndex::new_for_test();
        idx.set_workspace_root(None);
        idx.insert_cache(
            "Mid",
            Some(fake_cached_for_class(
                "Mid",
                &PathBuf::from("/fake/Mid.pm"),
                &[],
                &["Mojo::EventEmitter"],
            )),
        );
        let src = "package Leaf;\nuse parent 'Mid';\nsub wire {\n  my $self = shift;\n  $self->on('ready', sub { 1 });\n}\n1;\n";
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&ts_parser_perl::LANGUAGE.into()).unwrap();
        let tree = parser.parse(src, None).unwrap();
        let mut fa = crate::builder::build(&tree, src.as_bytes());
        fa.enrich_imported_types_with_keys(Some(&idx));
        let ready = fa.symbols.iter().filter(|s| {
            s.kind == SymKind::Handler && s.name == "ready"
                && matches!(&s.namespace, Namespace::Framework { id } if id == "mojo-events")
        }).count();
        assert_eq!(
            ready, 1,
            "mojo-events ClassIsa trigger should fire via cross-file parent chain"
        );
    }

    /// Dispatch-verb resolution in a NON-OPEN workspace/dependency file
    /// whose dispatch receiver `isa Minion` only CROSS-FILE and which does
    /// NOT `use Minion` itself. The minion plugin's emit-hook path
    /// (`UsesModule`/`ClassIsa` trigger) doesn't fire — only the
    /// trigger-independent `dispatch_verbs()` manifest captures a gated
    /// candidate. Under the query-time `ReceiverGated` seam the file is built
    /// WITHOUT enrichment (as the workspace indexer does) yet
    /// `applicable_dispatches` resolves the receiver cross-file and surfaces
    /// the call site. See `docs/adr/receiver-gated-dispatch.md`.
    #[test]
    fn dispatch_resolves_query_time_in_unenriched_workspace_file() {
        use crate::module_index::ModuleIndex;
        use std::path::PathBuf;
        let idx = ModuleIndex::new_for_test();
        idx.set_workspace_root(None);
        // `My::Minion` isa Minion, cross-file. The worker file below never
        // `use`s Minion — the emit-hook trigger can't fire, only the
        // receiver-isa manifest candidate, gated and resolved at query time.
        idx.insert_cache(
            "My::Minion",
            Some(fake_cached_for_class(
                "My::Minion",
                &PathBuf::from("/fake/My/Minion.pm"),
                &["new"],
                &["Minion"],
            )),
        );
        let src = "package My::Worker;\nsub run {\n  my $self = shift;\n  my $minion = My::Minion->new;\n  $minion->enqueue('send_email');\n}\n1;\n";
        // Build exactly as the workspace indexer does: no enrichment.
        let fa = build_fa(src);
        let applied = fa.applicable_dispatches(Some(&idx));
        assert_eq!(
            applied.len(), 1,
            "workspace-indexed file (no enrichment) should resolve its enqueue \
             dispatch at query time via the cross-file receiver isa — else \
             cross-file handler references miss it; got {:?}",
            applied,
        );
        assert_eq!(applied[0].name, "send_email");
    }

    // Wildcard-method param_types: a rule with `method: None` applies to every
    // sub in the class — the Catalyst pattern where every action gets `$c` typed.
    struct CatalystPlugin;
    impl FrameworkPlugin for CatalystPlugin {
        fn id(&self) -> &str { "catalyst-test" }
        fn triggers(&self) -> &[Trigger] {
            static T: [Trigger; 1] = [Trigger::Always];
            &T
        }
        fn param_types(&self) -> &[ParamType] {
            use std::sync::OnceLock;
            static PT: OnceLock<Vec<ParamType>> = OnceLock::new();
            PT.get_or_init(|| {
                vec![ParamType {
                    method: None, // wildcard: every ACTION method in the class
                    in_role: "Catalyst::Controller".into(),
                    param: 1,
                    type_class: "Catalyst".into(),
                    // Mirror the real catalyst.rhai: only attribute-carrying
                    // actions get $c, not plain helper subs.
                    requires_action_attr: true,
                    from_loader_config: false,
                }]
            })
        }
        fn on_signature_help(&self, _: &SigHelpQueryContext) -> Option<PluginSigHelpAnswer> { None }
        fn on_completion(&self, _: &CompletionQueryContext) -> Option<PluginCompletionAnswer> { None }
    }

    fn build_with_catalyst(source: &str) -> FileAnalysis {
        let mut reg = PluginRegistry::new();
        reg.register(Box::new(CatalystPlugin));
        let mut parser = tree_sitter::Parser::new();
        parser.set_language(&ts_parser_perl::LANGUAGE.into()).unwrap();
        let tree = parser.parse(source, None).unwrap();
        crate::builder::build_with_plugins(&tree, source.as_bytes(), Arc::new(reg))
    }

    #[test]
    fn catalyst_action_c_typed_via_wildcard_manifest() {
        // A controller action: $c (param index 1) should type as Catalyst.
        // The wildcard rule fires regardless of the action method's name.
        let fa = build_with_catalyst(
            "package MyApp::Controller::Foo;\nuse parent 'Catalyst::Controller';\nsub index :Local {\n    my ($self, $c) = @_;\n    my $req = $c;\n}\n1;\n",
        );
        let ty = fa
            .inferred_type_via_bag("$c", Point::new(4, 14))
            .expect("$c should be typed by wildcard param_types manifest");
        assert!(
            matches!(&ty, InferredType::ClassName(c) if c == "Catalyst"),
            "wildcard param_types should make $c a Catalyst in every controller action, got {:?}",
            ty,
        );
    }

    #[test]
    fn catalyst_wildcard_typed_for_any_action_name() {
        // A differently-named action — the wildcard covers it too.
        let fa = build_with_catalyst(
            "package MyApp::Controller::Bar;\nuse parent 'Catalyst::Controller';\nsub list :Local {\n    my ($self, $c) = @_;\n    my $x = $c;\n}\n1;\n",
        );
        let ty = fa
            .inferred_type_via_bag("$c", Point::new(4, 12))
            .expect("$c should be typed regardless of action method name");
        assert!(
            matches!(&ty, InferredType::ClassName(c) if c == "Catalyst"),
            "wildcard param_types must apply to any action name, got {:?}",
            ty,
        );
    }

    /// The Phase-2 cross-file case: a controller in file A `extends` a base in
    /// file B which `isa Catalyst::Controller`. The controller's ancestry to
    /// the wildcard rule's `in_role` is established only CROSS-FILE, so the old
    /// build-time local-only `transitive_parents` gate dropped it. The gated TC
    /// resolves at query time with the module index in hand → `$c` types.
    #[test]
    fn catalyst_wildcard_c_typed_through_cross_file_base() {
        use crate::module_index::ModuleIndex;
        use std::path::PathBuf;
        let idx = ModuleIndex::new_for_test();
        idx.set_workspace_root(None);
        // `MyApp::ControllerBase` isa Catalyst::Controller, cross-file. The
        // controller below `extends` it — its ancestry to the role is two hops,
        // through a class in another file the builder never sees.
        idx.insert_cache(
            "MyApp::ControllerBase",
            Some(fake_cached_for_class(
                "MyApp::ControllerBase",
                &PathBuf::from("/fake/MyApp/ControllerBase.pm"),
                &[],
                &["Catalyst::Controller"],
            )),
        );
        let src = "package MyApp::Controller::Deep;\nuse parent 'MyApp::ControllerBase';\nsub show :Local {\n    my ($self, $c) = @_;\n    my $req = $c;\n}\n1;\n";
        // Build as the workspace indexer does (no enrichment); the gated TC
        // rides the FA and resolves cross-file at query time.
        let fa = build_with_catalyst(src);
        let ty = fa
            .inferred_type_via_bag_ctx("$c", Point::new(4, 14), Some(&idx))
            .expect("$c should type via the cross-file Catalyst::Controller ancestry");
        assert!(
            matches!(&ty, InferredType::ClassName(c) if c == "Catalyst"),
            "wildcard param_types must type $c when Catalyst::Controller is a \
             cross-file ancestor, got {:?}",
            ty,
        );
    }

    #[test]
    fn catalyst_wildcard_not_applied_outside_controller() {
        // A package without the Catalyst::Controller ancestor must not get $c typed.
        let fa = build_with_catalyst(
            "package OtherPackage;\nsub index {\n    my ($self, $c) = @_;\n    my $x = $c;\n}\n1;\n",
        );
        assert_eq!(
            fa.inferred_type_via_bag("$c", Point::new(3, 12)),
            None,
            "wildcard rule must not type $c in a package that doesn't isa Catalyst::Controller",
        );
    }

    /// P1.4 — the real metacpan shape, through the actual hover query path: a
    /// controller reaches `Catalyst::Controller` through a *workspace
    /// intermediate* base that is itself a child of the role class. The leaf's
    /// local `package_parents` only knows its direct parent; reaching the role
    /// requires `class_isa` to chase the intermediate's parents through the
    /// module index. The bug was the hover path (`format_symbol_hover_at`)
    /// dropping the index — this exercises `hover_info` end-to-end so it
    /// fails on pre-fix code.
    #[test]
    fn catalyst_c_typed_through_workspace_intermediate_via_hover() {
        use crate::module_index::ModuleIndex;
        use std::path::PathBuf;
        let idx = ModuleIndex::new_for_test();
        idx.set_workspace_root(None);
        // Intermediate base, registered as a workspace module (like a project
        // `lib/.../Controller.pm`): its parent (`Catalyst::Controller`) lives
        // only in the index, NOT in the leaf's local `package_parents`.
        idx.register_workspace_module(
            PathBuf::from("/fake/MetaCPAN/Web/Controller.pm"),
            std::sync::Arc::new(build_fa(
                "package MetaCPAN::Web::Controller;\nuse parent 'Catalyst::Controller';\nsub pageset {\n    my ($self, $page) = @_;\n}\n1;\n",
            )),
        );
        // Leaf controller: extends only the workspace intermediate.
        let src = "package MetaCPAN::Web::Controller::Author;\nuse parent 'MetaCPAN::Web::Controller';\nsub root :Chained {\n    my ($self, $c, $id) = @_;\n    my $x = $c;\n}\n1;\n";
        let fa = build_with_catalyst(src);
        // Hover on the `$c` usage (row 4, the `my $x = $c;` line). The hover
        // path resolves the variable's type — only typed correctly if the
        // index is threaded all the way to the gated-param query.
        let hover = fa
            .hover_info(Point::new(4, 12), src, Some(&idx))
            .expect("hover should produce info for $c");
        assert!(
            hover.contains("type: Catalyst"),
            "3-hop cross-file ancestry through a workspace base must type $c in \
             hover (the path that dropped the index), got: {}",
            hover,
        );
    }

    /// P1.3 — the attribute gate: in the SAME controller, an action (`:Local`)
    /// gets `$c`, but a plain helper sub (no action attribute) must NOT get its
    /// 2nd param typed. The honest action signal is the attribute, not the
    /// parameter position.
    #[test]
    fn catalyst_non_action_helper_second_param_not_typed() {
        let fa = build_with_catalyst(
            "package MyApp::Controller::Foo;\nuse parent 'Catalyst::Controller';\nsub show :Local {\n    my ($self, $c) = @_;\n    my $a = $c;\n}\nsub pageset {\n    my ($self, $page) = @_;\n    my $b = $page;\n}\n1;\n",
        );
        // The action's $c IS typed.
        let c_ty = fa
            .inferred_type_via_bag("$c", Point::new(4, 12))
            .expect("action $c should be typed");
        assert!(
            matches!(&c_ty, InferredType::ClassName(c) if c == "Catalyst"),
            "action method's $c must type as Catalyst, got {:?}",
            c_ty,
        );
        // The plain helper's 2nd param ($page) must NOT be typed — no attribute.
        assert_eq!(
            fa.inferred_type_via_bag("$page", Point::new(8, 12)),
            None,
            "a non-action helper's 2nd param must NOT be typed Catalyst (P1.3 \
             over-application); only attribute-carrying actions receive $c",
        );
    }

    /// Catalyst private-action names (`begin`/`end`/`auto`/`default`/`index`)
    /// are dispatched by name alone — no action attribute. The `requires_action_attr`
    /// gate must not exclude them, so `$c` still types.
    #[test]
    fn catalyst_private_action_names_type_c_without_attr() {
        // `sub end { my ($self,$c)=@_ }` in a controller — no attribute.
        let fa = build_with_catalyst(
            "package MyApp::Controller::Root;\nuse parent 'Catalyst::Controller';\nsub end {\n    my ($self, $c) = @_;\n    my $r = $c;\n}\n1;\n",
        );
        let ty = fa
            .inferred_type_via_bag("$c", Point::new(4, 12))
            .expect("private-action end: $c should be typed even without an attribute");
        assert!(
            matches!(&ty, InferredType::ClassName(c) if c == "Catalyst"),
            "sub end without action attr must type $c as Catalyst, got {:?}",
            ty,
        );
    }

    /// A plain helper sub whose name happens to NOT be a private-action name
    /// and carries no action attribute must still be excluded.
    #[test]
    fn catalyst_plain_helper_not_a_private_action() {
        let fa = build_with_catalyst(
            "package MyApp::Controller::Root;\nuse parent 'Catalyst::Controller';\nsub helper {\n    my ($self, $x) = @_;\n    my $r = $x;\n}\n1;\n",
        );
        assert_eq!(
            fa.inferred_type_via_bag("$x", Point::new(4, 12)),
            None,
            "non-action, non-private-action helper must NOT have $x typed as Catalyst",
        );
    }
}

// ---- Fix #1: `not` operator ----

/// `not $x` must never produce an unresolved-function diagnostic.
/// Validated in symbols_tests; here we confirm the builder emits a
/// FunctionCall ref (so the name is visible for filtering) whose name
/// is "not" — the is_perl_builtin guard in collect_diagnostics then
/// suppresses it.
#[test]
fn not_operator_emits_no_function_call_ref() {
    // As of ts-parser-perl 1.1.0, `not` is the low-precedence logical-not
    // OPERATOR (`logical_not_expression`), not a function call. So no `not`
    // FunctionCall ref is emitted at all — which is the correct end state:
    // nothing for the builtin-suppressor to filter, and no unresolved-function
    // diagnostic for `not`.
    let fa = build_fa("my $x = 1;\nmy $y = not $x;\n");
    let not_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "not" && matches!(r.kind, RefKind::FunctionCall { .. }))
        .collect();
    assert!(
        not_refs.is_empty(),
        "`not` is an operator now; no FunctionCall ref should exist; got refs: {:?}",
        fa.refs.iter().map(|r| (&r.target_name, &r.kind)).collect::<Vec<_>>(),
    );
    // The $x operand still gets its read ref.
    assert!(
        fa.refs.iter().any(|r| r.target_name == "$x"),
        "operand $x should still be referenced",
    );
}

// ---- Fix #2: `\&subname` code-ref ----

/// `\&handler` must emit a FunctionCall ref pointing at `handler`
/// so goto-def and references both work.
#[test]
fn refgen_bare_name_emits_function_call_ref() {
    let fa = build_fa("sub handler { 1 }\nmy $cb = \\&handler;\n");
    let refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "handler" && matches!(r.kind, RefKind::FunctionCall { .. }))
        .collect();
    assert_eq!(
        refs.len(),
        1,
        "\\&handler should emit exactly one FunctionCall ref for `handler`; got: {:?}",
        fa.refs
            .iter()
            .filter(|r| r.target_name == "handler")
            .map(|r| &r.kind)
            .collect::<Vec<_>>(),
    );
}

/// `\&Pkg::handler` (qualified form) must also emit a FunctionCall ref.
#[test]
fn refgen_qualified_name_emits_function_call_ref() {
    let fa = build_fa("my $cb = \\&Foo::handler;\n");
    let refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| {
            r.target_name == "handler" || r.target_name == "Foo::handler"
        })
        .collect();
    assert!(
        !refs.is_empty(),
        "\\&Foo::handler should emit a FunctionCall ref; got refs: {:?}",
        fa.refs.iter().map(|r| (&r.target_name, &r.kind)).collect::<Vec<_>>(),
    );
}

/// goto-def on `\&handler` should land on the `sub handler` definition.
/// FunctionCall refs route goto-def through package+name matching, not
/// `resolves_to`, so we check `find_definition` returns the sub's span.
#[test]
fn refgen_goto_def_lands_on_sub_definition() {
    // sub handler on line 0, \&handler on line 1 col 9
    let src = "sub handler { 1 }\nmy $cb = \\&handler;\n";
    let fa = build_fa(src);
    let sub_sym = fa
        .symbols
        .iter()
        .find(|s| s.name == "handler" && matches!(s.kind, SymKind::Sub))
        .expect("handler sub should be defined");
    // Cursor at the `h` of `\&handler` on line 1 (0-indexed row=1, col≈11)
    let def_span = fa.find_definition(
        Point::new(1, 11),
        None);
    assert_eq!(
        def_span,
        Some(sub_sym.selection_span),
        "goto-def on \\&handler should land on the handler sub; sym={:?}",
        sub_sym,
    );
}

// ---- Fully-qualified variable reads → (pkg, basename) ----

#[test]
fn split_qualified_basics() {
    use crate::file_analysis::split_qualified;
    assert_eq!(split_qualified("Foo::Bar::baz"), (Some("Foo::Bar"), "baz"));
    assert_eq!(split_qualified("baz"), (None, "baz"));
    assert_eq!(split_qualified("Foo::bar"), (Some("Foo"), "bar"));
    // Leading `::` (main:: shorthand) → empty-string package, preserved.
    assert_eq!(split_qualified("::foo"), (Some(""), "foo"));
}

#[test]
fn fq_scalar_read_resolves_same_file() {
    // `our $x` in package Pkg; `$Pkg::x` read in another package, same file.
    let src = "package Pkg;\nour $x = 1;\npackage Main;\nmy $a = $Pkg::x;\n";
    let fa = build_fa(src);
    let decl = fa
        .symbols
        .iter()
        .find(|s| s.name == "$x" && s.package.as_deref() == Some("Pkg"))
        .expect("our $x in Pkg should be a symbol");
    // Cursor on the `x` tail of `$Pkg::x` (line 3).
    let read = fa
        .refs
        .iter()
        .find(|r| r.target_name == "$Pkg::x")
        .expect("$Pkg::x should emit a Variable ref");
    assert_eq!(
        read.resolves_to,
        Some(decl.id),
        "FQ scalar read should resolve to the Pkg::x declaration"
    );
    let def = fa.find_definition(read.span.start, None);
    assert_eq!(def, Some(decl.selection_span));
}

#[test]
fn fq_array_read_resolves_same_file() {
    let src = "package Pkg;\nour @arr = (1, 2);\npackage Main;\nmy @b = @Pkg::arr;\n";
    let fa = build_fa(src);
    let decl = fa
        .symbols
        .iter()
        .find(|s| s.name == "@arr" && s.package.as_deref() == Some("Pkg"))
        .expect("our @arr in Pkg should be a symbol");
    let read = fa
        .refs
        .iter()
        .find(|r| r.target_name == "@Pkg::arr")
        .expect("@Pkg::arr should emit a Variable ref");
    assert_eq!(read.resolves_to, Some(decl.id));
}

#[test]
fn fq_var_ref_span_narrowed_to_tail() {
    // rule #7: rename/highlight token is the bare tail, not the whole path.
    let src = "package Pkg;\nour $x = 1;\npackage Main;\nmy $a = $Pkg::x;\n";
    let fa = build_fa(src);
    let read = fa
        .refs
        .iter()
        .find(|r| r.target_name == "$Pkg::x")
        .expect("$Pkg::x ref");
    // `$Pkg::x` on line 3: `my $a = ` is 8 cols, `$Pkg::` is 6 → `x` at col 14.
    assert_eq!(read.span.start.row, 3);
    assert_eq!(read.span.start.column, 14, "span should start at the `x` tail");
}

#[test]
fn unqualified_var_still_resolves_lexically() {
    // Regression: the FQ fast-path must not break plain lexical resolution.
    let fa = build_fa("my $x = 1;\nprint $x;\n");
    let read = fa
        .refs
        .iter()
        .find(|r| r.target_name == "$x" && r.access == AccessKind::Read)
        .expect("plain $x read");
    assert!(read.resolves_to.is_some(), "unqualified read still resolves");
}

// ---- Fix #3: around/before/after modifier bodies ----

/// In `around foo => sub { my ($orig, $self) = @_; ... }`, `$self` (param index 1)
/// must be typed as the enclosing class so `$self->method` chains resolve.
#[test]
fn around_modifier_second_param_typed_as_class() {
    let src = r#"
package Dog;
use Moo;

sub speak { "woof" }

around speak => sub {
    my ($orig, $self) = @_;
    return $self->speak_loudly();
};

sub speak_loudly { "WOOF" }
"#;
    let fa = build_fa(src);

    // `$self` inside the around body should resolve to `Dog`
    // (row=8 is the `return $self->speak_loudly()` line).
    let ty = fa.inferred_type_via_bag("$self", Point::new(8, 12));
    assert!(
        ty.is_some(),
        "$self inside `around` body should have an inferred type; got None.\
         \nAll TCs: {:?}",
        fa.refs
            .iter()
            .filter(|r| r.target_name == "$self")
            .collect::<Vec<_>>(),
    );
    match ty.unwrap() {
        InferredType::ClassName(name) => assert_eq!(name, "Dog", "$self should be Dog"),
        InferredType::FirstParam { package } => {
            assert_eq!(package, "Dog", "$self FirstParam should be Dog")
        }
        other => panic!("expected ClassName/FirstParam for $self, got {:?}", other),
    }
}

/// In `before foo => sub { my ($self) = @_; ... }`, `$self` (param index 0)
/// must be typed as the enclosing class.
#[test]
fn before_modifier_first_param_typed_as_class() {
    let src = r#"
package Cat;
use Moo;

sub meow { "mrrp" }

before meow => sub {
    my ($self) = @_;
    $self->hiss();
};

sub hiss { "ssss" }
"#;
    let fa = build_fa(src);

    // Row 8 = `$self->hiss()` line
    let ty = fa.inferred_type_via_bag("$self", Point::new(8, 4));
    assert!(
        ty.is_some(),
        "$self inside `before` body should have an inferred type",
    );
    match ty.unwrap() {
        InferredType::ClassName(name) => assert_eq!(name, "Cat"),
        InferredType::FirstParam { package } => assert_eq!(package, "Cat"),
        other => panic!("expected ClassName/FirstParam, got {:?}", other),
    }
}

// ---- Runtime exporter modeling ----
//
// Static analysis can't run import(); we model the declarative setup
// shapes so exported names land in `export_ok` (same plumbing as
// `@EXPORT_OK`), which then drives goto-def / refs / diagnostics.

#[test]
fn sub_exporter_use_setup_records_exports() {
    let fa = build_fa(
        "package My::Exporter;\n\
         use Sub::Exporter -setup => { exports => [qw/alpha beta/] };\n\
         sub alpha { 1 }\n\
         sub beta { 2 }\n\
         1;\n",
    );
    assert!(fa.export_ok.contains(&"alpha".to_string()),
        "export_ok should contain alpha; got {:?}", fa.export_ok);
    assert!(fa.export_ok.contains(&"beta".to_string()),
        "export_ok should contain beta; got {:?}", fa.export_ok);
}

#[test]
fn sub_exporter_setup_exporter_call_records_exports() {
    let fa = build_fa(
        "package My::Exporter;\n\
         use Sub::Exporter ();\n\
         Sub::Exporter::setup_exporter({ exports => [qw/gamma/] });\n\
         sub gamma { 3 }\n\
         1;\n",
    );
    assert!(fa.export_ok.contains(&"gamma".to_string()),
        "export_ok should contain gamma; got {:?}", fa.export_ok);
}

#[test]
fn sub_exporter_generator_hashref_records_keys() {
    // Generators: best-effort — the hashref keys are the exported names.
    let fa = build_fa(
        "package My::Exporter;\n\
         use Sub::Exporter -setup => { exports => { delta => \\&_gen_delta } };\n\
         sub _gen_delta { sub { 4 } }\n\
         1;\n",
    );
    assert!(fa.export_ok.contains(&"delta".to_string()),
        "export_ok should contain generator name delta; got {:?}", fa.export_ok);
}

/// Sub::Exporter `exports` member collection is separator-agnostic: the
/// fat-comma generator entry (`bar => \&gen`) and its plain-comma equivalent
/// (`'bar', \&gen`) both put `bar` on the surface while skipping the opaque
/// generator value.
#[test]
fn sub_exporter_exports_plain_comma_members_join_surface() {
    for exports in [
        "[ 'foo', bar => \\&_gen ]",
        "[ 'foo', 'bar', \\&_gen ]",
    ] {
        let src = format!(
            "package My::Exp;\n\
             use Sub::Exporter -setup => {{ exports => {exports} }};\n\
             sub foo {{}}\n\
             sub bar {{}}\n\
             sub _gen {{}}\n\
             1;\n",
        );
        let fa = build_fa(&src);
        for name in ["foo", "bar"] {
            assert!(
                fa.exports_name(name),
                "exports `{exports}`: `{name}` must join the surface; export_ok={:?}",
                fa.export_ok,
            );
        }
    }
}

#[test]
fn sub_exporter_setup_array_members_and_groups_join_surface() {
    // `-setup => { exports => [ qw(foo bar), baz => \&_gen ], groups => {...} }`:
    // every member name joins the export surface (incl. the `name => \&gen`
    // generator entry's name and the group member arrays). The group keys
    // (`default`/`extra`) are selectors, not subs — they must NOT join.
    let fa = build_fa(
        "package My::Exp;\n\
         use Sub::Exporter -setup => {\n\
           exports => [ qw(foo bar), baz => \\&_build_baz ],\n\
           groups  => { default => [qw(foo)], extra => [qw(bar baz)] },\n\
         };\n\
         sub foo {}\n\
         sub bar {}\n\
         sub _build_baz {}\n\
         1;\n",
    );
    for name in ["foo", "bar", "baz"] {
        assert!(
            fa.exports_name(name),
            "exports_name({name}) should be true; export_ok={:?}",
            fa.export_ok
        );
    }
    assert!(
        !fa.export_ok.contains(&"default".to_string())
            && !fa.export_ok.contains(&"extra".to_string()),
        "group selector keys must not join the surface; got {:?}",
        fa.export_ok
    );
}

#[test]
fn sub_exporter_member_refs_local_subs() {
    // Each member that names a local sub gets a FunctionCall ref at its
    // export-list mention (rule #7); a member naming no local sub (the public
    // generator name) gets none.
    let fa = build_fa(
        "package My::Exp;\n\
         use Sub::Exporter -setup => {\n\
           exports => [ qw(foo bar), baz => \\&_build_baz ],\n\
           groups  => { extra => [qw(bar baz)] },\n\
         };\n\
         sub foo {}\n\
         sub bar {}\n\
         sub baz {}\n\
         1;\n",
    );
    let count = |name: &str| {
        fa.refs
            .iter()
            .filter(|r| {
                r.target_name == name
                    && matches!(
                        &r.kind,
                        RefKind::FunctionCall { resolved_package }
                            if resolved_package.as_deref() == Some("My::Exp")
                    )
            })
            .count()
    };
    // foo: exports list only = 1. bar: exports + group `extra` = 2.
    // baz: exports + group `extra` = 2.
    assert_eq!(count("foo"), 1, "foo member ref; got refs {:?}", fa.refs.iter().filter(|r| r.target_name=="foo").collect::<Vec<_>>());
    assert_eq!(count("bar"), 2, "bar in exports + group extra");
    assert_eq!(count("baz"), 2, "baz in exports + group extra");
}

#[test]
fn sub_exporter_member_goto_def_and_references() {
    use crate::file_store::FileStore;
    use crate::resolve::{refs_to, RoleMask, TargetKind, TargetRef};
    use std::path::PathBuf;

    let src = "package My::Exp;\n\
         use Sub::Exporter -setup => { exports => [ qw(foo bar) ] };\n\
         sub foo {}\n\
         sub bar {}\n\
         1;\n";
    let fa = build_fa(src);

    let foo_def_span = fa
        .symbols
        .iter()
        .find(|s| s.name == "foo")
        .map(|s| s.selection_span)
        .expect("foo sub symbol");
    let export_ref = fa
        .refs
        .iter()
        .find(|r| {
            r.target_name == "foo"
                && matches!(&r.kind, RefKind::FunctionCall { .. })
                && r.span != foo_def_span
        })
        .expect("an export-list FunctionCall ref for foo");
    let r = fa
        .ref_at(export_ref.span.start)
        .expect("ref_at the export member token");
    assert_eq!(r.target_name, "foo");

    let store = FileStore::new();
    let path = PathBuf::from("/tmp/qa_sub_exporter.pm");
    store.insert_workspace(path.clone(), fa);
    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "foo".to_string(),
            kind: TargetKind::Sub {
                package: Some("My::Exp".to_string()),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    // def + 1 exports-list mention = 2.
    assert_eq!(
        results.len(),
        2,
        "references on foo should list the def and its exports-list mention; got {results:?}"
    );
}

#[test]
fn sub_exporter_setup_exporter_call_with_groups() {
    // The function-call setup form folds exports + groups the same way.
    let fa = build_fa(
        "package My::Exp;\n\
         use Sub::Exporter ();\n\
         Sub::Exporter::setup_exporter({\n\
           exports => [qw/gamma delta/],\n\
           groups  => { all => [qw/gamma delta/] },\n\
         });\n\
         sub gamma {}\n\
         sub delta {}\n\
         1;\n",
    );
    assert!(fa.exports_name("gamma") && fa.exports_name("delta"),
        "setup_exporter exports should join surface; got {:?}", fa.export_ok);
    assert!(!fa.export_ok.contains(&"all".to_string()),
        "group selector `all` must not join the surface");
}

#[test]
fn non_sub_exporter_use_unaffected() {
    // Regression: a plain `use` of an unrelated module with a `-setup`-shaped
    // arg must not record exports (only Sub::Exporter's use is folded).
    let fa = build_fa(
        "package My::Thing;\n\
         use Some::Other -setup => { exports => [qw/leak/] };\n\
         sub leak {}\n\
         1;\n",
    );
    assert!(!fa.export_ok.contains(&"leak".to_string()),
        "non-Sub::Exporter use must not record exports; got {:?}", fa.export_ok);
    // And no spurious export-member ref on the local sub.
    let leak_refs = fa.refs.iter().filter(|r| r.target_name == "leak"
        && matches!(&r.kind, RefKind::FunctionCall { .. })).count();
    assert_eq!(leak_refs, 0, "no member ref for an unrelated use's pseudo-export");
}

#[test]
fn moose_exporter_setup_import_methods_records_exports() {
    let fa = build_fa(
        "package My::Sugar;\n\
         use Moose::Exporter;\n\
         Moose::Exporter->setup_import_methods(\n\
             with_meta => ['has_table'],\n\
             as_is     => [qw/col belongs_to/],\n\
         );\n\
         sub has_table { }\n\
         sub col { }\n\
         sub belongs_to { }\n\
         1;\n",
    );
    for name in ["has_table", "col", "belongs_to"] {
        assert!(fa.export_ok.contains(&name.to_string()),
            "export_ok should contain {}; got {:?}", name, fa.export_ok);
    }
}

#[test]
fn type_library_add_type_records_named_export() {
    let fa = build_fa(
        "package My::Types;\n\
         use Type::Library -base;\n\
         __PACKAGE__->add_type({ name => 'PositiveInt' });\n\
         __PACKAGE__->add_type({ name => 'Email' });\n\
         1;\n",
    );
    assert!(fa.export_ok.contains(&"PositiveInt".to_string()),
        "export_ok should contain PositiveInt; got {:?}", fa.export_ok);
    assert!(fa.export_ok.contains(&"Email".to_string()),
        "export_ok should contain Email; got {:?}", fa.export_ok);
}

#[test]
fn non_exporter_setup_does_not_pollute_exports() {
    // A plain method call named neither setup verb leaves exports empty.
    let fa = build_fa(
        "package My::Thing;\n\
         My::Thing->configure({ name => 'nope', exports => [qw/leak/] });\n\
         1;\n",
    );
    assert!(!fa.export_ok.contains(&"leak".to_string()),
        "unrelated method call must not record exports; got {:?}", fa.export_ok);
    assert!(!fa.export_ok.contains(&"nope".to_string()));
}

#[test]
fn setup_verb_name_without_exporter_use_does_not_pollute_exports() {
    // The verb name matches a real exporter setup call, but the package never
    // `use`d an exporter that defines it — so it's an unrelated method call
    // (`$x->add_type({name=>...})` on some domain object) and must not record
    // exports. Without the package-use gate this would false-positive.
    let fa = build_fa(
        "package My::Registry;\n\
         my $schema = build_schema();\n\
         $schema->add_type({ name => 'Widget' });\n\
         __PACKAGE__->setup_import_methods(as_is => [qw/leak/]);\n\
         1;\n",
    );
    assert!(!fa.export_ok.contains(&"Widget".to_string()),
        "add_type without Type::Library use must not record exports; got {:?}", fa.export_ok);
    assert!(!fa.export_ok.contains(&"leak".to_string()),
        "setup_import_methods without Moose::Exporter use must not record exports; got {:?}", fa.export_ok);
}

#[test]
fn export_ok_array_assignment_unions_with_runtime_exports() {
    // `:Export` attr records `attr_export` at the sub walk; a later
    // `our @EXPORT_OK = (...)` must union, not clobber, so both survive.
    let fa = build_fa(
        "package My::Mixed;\n\
         use Exporter::Extensible;\n\
         sub attr_export :Export { }\n\
         our @EXPORT_OK = ('array_export');\n\
         sub array_export { }\n\
         1;\n",
    );
    assert!(fa.export_ok.contains(&"attr_export".to_string()),
        "runtime :Export attr survives the array assignment; got {:?}", fa.export_ok);
    assert!(fa.export_ok.contains(&"array_export".to_string()),
        "array-assigned name recorded; got {:?}", fa.export_ok);
}

// Moo/Moose non-default has options: predicate, clearer,
// writer, reader, builder, handles
// ============================================================

#[test]
fn test_moo_has_predicate_string() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'name' => (is => 'ro', predicate => 'has_name');
",
    );
    let pred: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "has_name" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(pred.len(), 1, "explicit predicate string synthesizes method");
    if let SymbolDetail::Sub { ref params, is_method, .. } = pred[0].detail {
        assert!(is_method);
        assert!(params.is_empty(), "predicate takes no args");
    }
}

#[test]
fn test_moo_has_predicate_shorthand() {
    // `predicate => 1` derives `has_<attr>` for public attrs.
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'email' => (is => 'ro', predicate => 1);
",
    );
    let pred: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "has_email" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(pred.len(), 1, "predicate => 1 derives has_<attr>");
}

#[test]
fn test_moo_has_predicate_private_attr_shorthand() {
    // Private attrs (leading `_`) get `_has_<rest>` not `has__<rest>`.
    let fa = build_fa(
        "
package Foo;
use Moo;
has '_token' => (is => 'ro', predicate => 1);
",
    );
    let pred: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "_has_token" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(pred.len(), 1, "predicate => 1 on _attr derives _has_<rest>");
}

#[test]
fn test_moo_has_clearer_string() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'cache' => (is => 'rw', clearer => 'clear_cache');
",
    );
    let clearer: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "clear_cache" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(clearer.len(), 1, "explicit clearer string synthesizes method");
}

#[test]
fn test_moo_has_clearer_shorthand() {
    // `clearer => 1` derives `clear_<attr>`.
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'items' => (is => 'rw', clearer => 1);
",
    );
    let clearer: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "clear_items" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(clearer.len(), 1, "clearer => 1 derives clear_<attr>");
}

#[test]
fn test_moo_has_clearer_private_shorthand() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has '_session' => (is => 'rw', clearer => 1);
",
    );
    let clearer: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "_clear_session" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(clearer.len(), 1, "clearer => 1 on _attr derives _clear_<rest>");
}

#[test]
fn test_moo_has_writer_option() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'color' => (is => 'ro', writer => 'set_color');
",
    );
    let writer: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "set_color" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(writer.len(), 1, "writer option synthesizes method");
    if let SymbolDetail::Sub { ref params, .. } = writer[0].detail {
        assert_eq!(params.len(), 1, "writer has one param");
    }
}

#[test]
fn test_moo_has_reader_option() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'size' => (is => 'ro', reader => 'get_size');
",
    );
    let reader: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "get_size" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(reader.len(), 1, "reader option synthesizes method");
    if let SymbolDetail::Sub { ref params, is_method, .. } = reader[0].detail {
        assert!(is_method);
        assert!(params.is_empty(), "reader takes no args");
    }
}

#[test]
fn test_moo_has_builder_shorthand() {
    // `builder => 1` → method symbol `_build_<attr>` so goto-def
    // to the user-written sub resolves.
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'items' => (is => 'ro', builder => 1);
sub _build_items { return [] }
",
    );
    let builder_sym: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "_build_items" && s.kind == SymKind::Method)
        .collect();
    // The synthesized placeholder + the real sub definition both exist.
    // At minimum one symbol with that name must be present.
    assert!(
        !builder_sym.is_empty(),
        "_build_items must exist (synthesized or user-written)"
    );
}

#[test]
fn test_moo_has_builder_string() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'cache' => (is => 'lazy', builder => '_make_cache');
",
    );
    let builder_sym: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "_make_cache" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(builder_sym.len(), 1, "explicit builder name synthesizes method");
}

#[test]
fn test_moo_has_auxiliaries_without_is() {
    // predicate/clearer/builder are valid even when `is` is absent.
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'flag' => (predicate => 'has_flag', clearer => 'clear_flag');
",
    );
    let pred: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "has_flag" && s.kind == SymKind::Method)
        .collect();
    let clearer: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "clear_flag" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(pred.len(), 1, "predicate synthesized without is");
    assert_eq!(clearer.len(), 1, "clearer synthesized without is");
}

#[test]
fn test_moo_has_auxiliaries_with_bare() {
    // `is => bare` suppresses default accessor but auxiliaries still appear.
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'secret' => (is => 'bare', predicate => 'has_secret');
",
    );
    // Default accessor suppressed
    let accessors: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "secret" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(accessors.len(), 0, "bare suppresses default accessor");
    // Predicate still synthesized
    let pred: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "has_secret" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(pred.len(), 1, "predicate synthesized even with is => bare");
}

#[test]
fn test_moo_has_handles_hashref() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'logger' => (is => 'ro', isa => 'Log::Any', handles => { log => 'debug', warning => 'warn' });
",
    );
    let log_sym: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "log" && s.kind == SymKind::Method)
        .collect();
    let warning_sym: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "warning" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(log_sym.len(), 1, "handles hashref synthesizes 'log' method");
    assert_eq!(warning_sym.len(), 1, "handles hashref synthesizes 'warning' method");
}

#[test]
fn test_moose_has_handles_arrayref() {
    let fa = build_fa(
        "
package Foo;
use Moose;
has 'db' => (is => 'ro', isa => 'DBI::db', handles => [qw(prepare execute)]);
",
    );
    let prepare: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "prepare" && s.kind == SymKind::Method)
        .collect();
    let execute: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "execute" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(prepare.len(), 1, "handles arrayref synthesizes 'prepare'");
    assert_eq!(execute.len(), 1, "handles arrayref synthesizes 'execute'");
}

#[test]
fn test_moo_has_handles_instanceof_edges_return_type() {
    // When isa is InstanceOf['X'], handles delegation edges each local
    // method's return through MethodOnClass{X, remote} so type inference
    // chains through.
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'logger' => (is => 'ro', isa => \"InstanceOf['Log::Any']\", handles => { log => 'debug' });
",
    );
    let log_sym: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "log" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(log_sym.len(), 1, "handles delegation synthesizes method");
    // Provenance confirms this came from framework synthesis
    match fa.return_type_provenance(log_sym[0].id) {
        TypeProvenance::FrameworkSynthesis { framework, reason } => {
            assert!(
                framework == "Moo" || framework == "Moose",
                "provenance framework should be Moo/Moose, got {}",
                framework
            );
            assert!(reason.contains("handles"), "reason should mention handles");
        }
        TypeProvenance::Inferred => {
            // Acceptable: no witness was pushed if there was no isa type resolution.
        }
        other => panic!("unexpected provenance: {other:?}"),
    }
}

/// Regression: an option keyword that carries DATA, not a method name
/// (`is`/`isa`/`default`/`lazy`/…), must never mint a method named after its
/// string value. The sprint that moved the accessor vocabulary into moo.rhai
/// briefly synthesized phantom `ro`/`rw`/`lazy`/`bare` methods from every
/// option's value — this pins the gate that stopped it.
#[test]
fn test_moo_has_no_phantom_method_from_data_options() {
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'name' => (is => 'ro', isa => 'Str', default => 'bob', lazy => 1, required => 1);
",
    );
    for phantom in ["ro", "rw", "lazy", "bare", "Str", "bob", "1"] {
        let hits: Vec<_> = fa
            .symbols
            .iter()
            .filter(|s| s.name == phantom && s.kind == SymKind::Method)
            .collect();
        assert!(
            hits.is_empty(),
            "option value `{phantom}` must not become a method, got {} symbol(s)",
            hits.len()
        );
    }
    // The real accessor still lands.
    let name: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "name" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(name.len(), 1, "the real `name` accessor must still synthesize");
}

/// Moose `lazy_build => 1` implies a builder/clearer/predicate trio at runtime.
#[test]
fn test_moose_has_lazy_build_expands_trio() {
    let fa = build_fa(
        "
package Foo;
use Moose;
has 'cache' => (is => 'ro', lazy_build => 1);
",
    );
    for (name, what) in [
        ("_build_cache", "builder"),
        ("clear_cache", "clearer"),
        ("has_cache", "predicate"),
    ] {
        let hits: Vec<_> = fa
            .symbols
            .iter()
            .filter(|s| s.name == name && s.kind == SymKind::Method)
            .collect();
        assert_eq!(hits.len(), 1, "lazy_build must synthesize the {what} `{name}`");
    }
    // `lazy_build`/`is` themselves are not methods.
    for phantom in ["lazy_build", "ro", "1"] {
        assert!(
            !fa.symbols.iter().any(|s| s.name == phantom && s.kind == SymKind::Method),
            "`{phantom}` must not become a method"
        );
    }
}

/// goto-def on a `has` accessor must land on the attribute name token of the
/// `has` declaration, not an option line (`is => 'ro'`) inside the body.
#[test]
fn test_moo_has_accessor_selection_span_is_attr_name() {
    // `has` on line 3 (0-indexed), attr `name` at col 5; options on line 4.
    let fa = build_fa("package Foo;\nuse Moo;\nhas name => (\n    is => 'ro',\n);\n");
    let name = fa
        .symbols
        .iter()
        .find(|s| s.name == "name" && s.kind == SymKind::Method)
        .expect("name accessor");
    assert_eq!(
        name.selection_span.start.row, 2,
        "selection_span must point at the `has name` line, not the options line"
    );
}

/// Dancer2::Plugin re-exports Moo's `has`, so consumer plugins get accessor
/// synthesis even though they never literally `use Moo`.
#[test]
fn test_dancer2_plugin_has_synthesizes_accessor() {
    let fa = build_fa(
        "
package My::Plugin;
use Dancer2::Plugin;
has my_setting => (is => 'ro', isa => 'Str');
",
    );
    let acc: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "my_setting" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(acc.len(), 1, "Dancer2::Plugin `has` must synthesize the accessor");
    // And no phantom from the `is`/`isa` data options.
    for phantom in ["ro", "Str"] {
        assert!(
            !fa.symbols.iter().any(|s| s.name == phantom && s.kind == SymKind::Method),
            "`{phantom}` must not become a method under Dancer2::Plugin either"
        );
    }
}

#[test]
fn use_constant_scalar_form_registers_sub_symbol() {
    // `use constant NAME => VAL` declares a package-global sub. Registering
    // it as a Sub symbol silences the unresolved-function hint at callsites
    // and gives goto-def.
    let fa = build_fa("use constant DEBUG => 1;\nmy $y = DEBUG && 2;\n");
    assert!(
        fa.symbols.iter().any(|s| s.name == "DEBUG" && s.kind == SymKind::Sub),
        "DEBUG must be registered as a Sub symbol; got: {:?}",
        fa.symbols.iter().map(|s| (&s.name, s.kind)).collect::<Vec<_>>(),
    );
}

#[test]
fn use_constant_block_form_registers_each_name() {
    let fa = build_fa("use constant { A => 1, B => 2, C => 3 };\n");
    for n in ["A", "B", "C"] {
        assert!(
            fa.symbols.iter().any(|s| s.name == n && s.kind == SymKind::Sub),
            "block-form constant `{n}` must be a Sub symbol; got: {:?}",
            fa.symbols.iter().map(|s| s.name.clone()).collect::<Vec<_>>(),
        );
    }
}

#[test]
fn use_constant_block_plain_comma_keys_register() {
    // `=>` is just an autoquoting comma — `{ 'GAMMA', 3 }` is identical to
    // `{ GAMMA => 3 }`. The block walker must pair positionally, so quoted
    // plain-comma keys register as Sub symbols exactly like fat-comma keys.
    let fa = build_fa("use constant { 'GAMMA', 3, 'DELTA', 4, A => 1, B => 2 };\n");
    for n in ["GAMMA", "DELTA", "A", "B"] {
        assert!(
            fa.symbols.iter().any(|s| s.name == n && s.kind == SymKind::Sub),
            "plain-comma block constant `{n}` must be a Sub symbol; got: {:?}",
            fa.symbols.iter().map(|s| s.name.clone()).collect::<Vec<_>>(),
        );
    }
}

/// Plain-comma block constants get usage refs + goto-def/references, the same
/// as fat-comma — the registration path is separator-agnostic end to end.
#[test]
fn use_constant_block_plain_comma_goto_def_and_references() {
    use crate::file_store::FileStore;
    use crate::resolve::{refs_to, RoleMask, TargetKind, TargetRef};
    use std::path::PathBuf;

    let src = r#"package Foo;
use constant { 'GAMMA', 3, DELTA => 4 };
sub go {
    my $a = GAMMA;
    return DELTA;
}
"#;
    let fa = build_fa(src);
    // Usage refs emitted for both spellings' keys.
    for n in ["GAMMA", "DELTA"] {
        assert!(
            fa.refs.iter().any(|r| {
                r.target_name == n
                    && matches!(&r.kind, RefKind::FunctionCall { resolved_package }
                        if resolved_package.as_deref() == Some("Foo"))
            }),
            "usage of plain/fat-comma constant `{n}` must get a FunctionCall ref; refs: {:?}",
            fa.refs.iter().filter(|r| r.target_name == n).collect::<Vec<_>>(),
        );
    }
    let store = FileStore::new();
    store.insert_workspace(PathBuf::from("/tmp/qa_const_plain.pm"), fa);
    for name in ["GAMMA", "DELTA"] {
        let results = refs_to(
            &store,
            None,
            &TargetRef {
                name: name.to_string(),
                kind: TargetKind::Sub { package: Some("Foo".to_string()) },
                method_classes: Vec::new(),
            },
            RoleMask::EDITABLE,
        );
        assert_eq!(
            results.len(), 2,
            "references on `{name}` should list its def + 1 usage; got {results:?}",
        );
    }
}

/// Regression: positional pairing must not invent keys from a value position.
/// In `use constant { A => 1 }` the `1` is a value, never a constant name — the
/// walker pairs `A`→`1` and stops, so no `1`-named (or numeric) Sub appears.
#[test]
fn use_constant_block_does_not_mispair_values_as_keys() {
    let fa = build_fa("use constant { A => 1, 'B', 2 };\n");
    let const_subs: Vec<&str> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Sub)
        .map(|s| s.name.as_str())
        .collect();
    assert!(
        const_subs.contains(&"A") && const_subs.contains(&"B"),
        "keys A and B must register; got {:?}",
        const_subs,
    );
    // The value tokens (`1`, `2`) are not keys — no numeric-named Sub symbol.
    assert!(
        !const_subs.iter().any(|n| *n == "1" || *n == "2"),
        "value tokens must never register as constant names; got {:?}",
        const_subs,
    );
}

#[test]
fn use_constant_between_subs_at_file_scope() {
    // Constants declared between subs must still register.
    let src = "sub one {}\nuse constant MID => 'x';\nsub two {}\n";
    let fa = build_fa(src);
    assert!(
        fa.symbols.iter().any(|s| s.name == "MID" && s.kind == SymKind::Sub),
        "MID declared between subs must register as a Sub symbol",
    );
}

#[test]
fn multiple_name_form_use_constants_each_register() {
    // Several separate NAME-form `use constant` statements in one package:
    // each declares its own package-global sub. The use-dedup key carries the
    // statement span, so identical work identity at different spans (the
    // constant name isn't folded into `constant_strings` when `imports` is
    // extracted, so it's empty for all of them) no longer collapses past the
    // first.
    let src = r#"package Foo;
use constant ALPHA => 1;
use constant BETA  => 2;
use constant GAMMA => 3;
sub go {
    my $a = ALPHA;
    my $b = BETA;
    my $c = GAMMA;
}
"#;
    let fa = build_fa(src);
    for n in ["ALPHA", "BETA", "GAMMA"] {
        assert!(
            fa.symbols.iter().any(|s| s.name == n && s.kind == SymKind::Sub),
            "every separate NAME-form constant must register a Sub symbol; `{n}` missing. got: {:?}",
            fa.symbols.iter().map(|s| s.name.clone()).collect::<Vec<_>>(),
        );
        // Usages resolve: each name joins `declared_constants`, so the
        // standalone bareword usage gets a FunctionCall ref to the def.
        assert!(
            fa.refs.iter().any(|r| {
                r.target_name == n
                    && matches!(
                        &r.kind,
                        RefKind::FunctionCall { resolved_package } if resolved_package.as_deref() == Some("Foo")
                    )
            }),
            "usage of `{n}` must get a FunctionCall ref to its def; refs for {n}: {:?}",
            fa.refs.iter().filter(|r| r.target_name == n).collect::<Vec<_>>(),
        );
    }
}

/// goto-def + references across THREE separate NAME-form `use constant`
/// statements: every def is reachable and every usage lists.
#[test]
fn multiple_name_form_use_constants_goto_def_and_references() {
    use crate::file_store::FileStore;
    use crate::resolve::{refs_to, RoleMask, TargetKind, TargetRef};
    use std::path::PathBuf;

    let src = r#"package Foo;
use constant ALPHA => 1;
use constant BETA  => 2;
use constant GAMMA => 3;
sub go {
    my $a = ALPHA;
    my $b = BETA;
    return GAMMA;
}
"#;
    let fa = build_fa(src);
    let store = FileStore::new();
    store.insert_workspace(PathBuf::from("/tmp/qa_multi_const.pm"), fa);

    // BETA: def + 1 usage = 2 hits. GAMMA: def + 1 usage = 2. ALPHA: def + 1.
    for name in ["ALPHA", "BETA", "GAMMA"] {
        let results = refs_to(
            &store,
            None,
            &TargetRef {
                name: name.to_string(),
                kind: TargetKind::Sub { package: Some("Foo".to_string()) },
                method_classes: Vec::new(),
            },
            RoleMask::EDITABLE,
        );
        assert_eq!(
            results.len(),
            2,
            "references on `{name}` should list its def + 1 usage; got {results:?}"
        );
    }
}

#[test]
fn indirect_object_filehandle_not_a_function_ref() {
    // `print FH LIST` — the bareword filehandle must NOT become a
    // FunctionCall ref (otherwise STDERR/STDOUT/DATA flag as unresolved).
    for src in [
        "print STDERR \"hi\";\n",
        "printf STDERR \"%s\", $x;\n",
        "say STDOUT \"hi\";\n",
    ] {
        let fa = build_fa(src);
        let fh = src.split_whitespace().nth(1).unwrap().trim_matches(|c| c == '"');
        assert!(
            !fa.refs.iter().any(|r|
                matches!(r.kind, RefKind::FunctionCall { .. }) && r.target_name == fh),
            "filehandle `{fh}` must not be a FunctionCall ref for `{}`; refs: {:?}",
            src.trim(),
            fa.refs.iter().filter(|r| matches!(r.kind, RefKind::FunctionCall { .. }))
                .map(|r| r.target_name.clone()).collect::<Vec<_>>(),
        );
    }
}

#[test]
fn print_with_paren_call_still_emits_function_ref() {
    // `print foo("x")` is a real call — foo must keep its FunctionCall ref.
    let fa = build_fa("print foo(\"x\");\n");
    assert!(
        fa.refs.iter().any(|r|
            matches!(r.kind, RefKind::FunctionCall { .. }) && r.target_name == "foo"),
        "parenthesized call `foo(...)` inside print must keep its FunctionCall ref",
    );
}

#[test]
fn shift_invocant_typed_like_at_underscore() {
    // `my $self = shift;` types $self as the enclosing class, exactly like
    // `my ($self) = @_;` — so method calls on $self resolve in-package.
    // Each body is on line 2 (0-indexed); query $self at its use point.
    let at_point = tree_sitter::Point { row: 2, column: 28 };
    let is_class_w = |fa: &FileAnalysis| {
        matches!(
            fa.inferred_type_via_bag("$self", at_point),
            Some(InferredType::ClassName(ref c)) if c == "W"
        )
    };
    let shift_fa =
        build_fa("package W;\nsub go { 1 }\nsub f { my $self = shift; $self->go(); }\n");
    let at_fa =
        build_fa("package W;\nsub go { 1 }\nsub f { my ($self) = @_; $self->go(); }\n");
    assert!(is_class_w(&shift_fa), "shift-extracted $self must type as ClassName(W)");
    assert!(is_class_w(&at_fa), "@_-extracted $self must type as ClassName(W)");
}

// ---- Framework synthesis/detection: requires / Role::Tiny / DBIC ancestry /
//      mk_group_accessors / Mojo -base parent / has comma-form ----

#[test]
fn test_moo_role_requires_is_framework_import() {
    let fa = build_fa(
        "
package My::Role;
use Moo::Role;
requires 'must_implement';
",
    );
    assert!(
        fa.framework_imports.contains("requires"),
        "Moo::Role exports `requires` — should register as a framework import"
    );
}

#[test]
fn test_moose_role_requires_is_framework_import() {
    let fa = build_fa(
        "
package My::Role;
use Moose::Role;
requires 'foo';
",
    );
    assert!(fa.framework_imports.contains("requires"));
}

#[test]
fn test_role_tiny_behaves_like_moo_role() {
    let fa = build_fa(
        "
package My::Role;
use Role::Tiny;
requires 'bar';
with 'Other::Role';
",
    );
    assert!(
        fa.framework_imports.contains("requires"),
        "Role::Tiny exports `requires`"
    );
    assert!(
        fa.framework_imports.contains("with"),
        "Role::Tiny exports `with`"
    );
}

#[test]
fn test_role_tiny_with_behaves_like_moo_role() {
    let fa = build_fa(
        "
package My::Class;
use Role::Tiny::With;
with 'Some::Role';
",
    );
    assert!(fa.framework_imports.contains("with"));
}

#[test]
fn test_dbic_two_level_ancestry_synthesizes_columns() {
    // Result → BaseResult → DBIx::Class::Core: the DBIC base is two hops up.
    // The shallow direct-parent check missed this; full-ancestry walk catches it.
    let fa = build_fa(
        "
package My::Schema::BaseResult;
use base 'DBIx::Class::Core';

package My::Schema::Result::User;
use base 'My::Schema::BaseResult';
__PACKAGE__->add_columns(qw/id username/);
",
    );
    let id: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "id" && s.kind == SymKind::Method)
        .collect();
    let username: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "username" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(id.len(), 1, "2-level DBIC inheritance should synthesize `id`");
    assert_eq!(username.len(), 1, "and `username`");
}

#[test]
fn test_mk_group_accessors_synthesizes_methods() {
    let fa = build_fa(
        "
package My::Thing;
use base 'Class::Accessor::Grouped';
__PACKAGE__->mk_group_accessors('simple', qw/alpha beta/);
__PACKAGE__->mk_group_ro_accessors('inflated', 'gamma', 'delta');
",
    );
    for name in ["alpha", "beta", "gamma", "delta"] {
        let hits: Vec<_> = fa
            .symbols
            .iter()
            .filter(|s| s.name == name && s.kind == SymKind::Method)
            .collect();
        assert_eq!(hits.len(), 1, "mk_group accessor `{name}` should be synthesized");
    }
    // The group name itself is NOT an accessor.
    assert!(
        !fa.symbols.iter().any(|s| s.name == "simple" && s.kind == SymKind::Method),
        "the leading group name must not become an accessor"
    );
}

#[test]
fn test_mk_classdata_synthesizes_method() {
    let fa = build_fa(
        "
package My::Thing;
use base 'Class::Accessor::Grouped';
__PACKAGE__->mk_classdata('config');
",
    );
    let hits: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "config" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(hits.len(), 1, "mk_classdata should synthesize the named accessor");
}

#[test]
fn test_use_module_dash_base_registers_parent_and_mojo_behavior() {
    let fa = build_fa(
        "
package My::Emitter;
use Mojo::EventEmitter -base;
has 'value';
",
    );
    // The module imported with -base becomes a parent...
    assert!(
        fa.package_parents
            .get("My::Emitter")
            .map(|v| v.iter().any(|p| p == "Mojo::EventEmitter"))
            .unwrap_or(false),
        "`use X -base` should register X as a parent"
    );
    // ...and Mojo::Base accessor synthesis (getter + setter) applies.
    let methods: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "value" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(methods.len(), 2, "`-base` pulls Mojo::Base has-synthesis");
}

#[test]
fn test_mojo_base_dash_base_carries_mojo_base_as_parent() {
    let fa = build_fa(
        "
package My::Class;
use Mojo::Base -base;
has 'x';
",
    );
    assert!(
        fa.package_parents
            .get("My::Class")
            .map(|v| v.iter().any(|p| p == "Mojo::Base"))
            .unwrap_or(false),
        "`Mojo::Base -base` should carry Mojo::Base itself as a parent so tap/attr/new resolve"
    );
}

#[test]
fn test_moo_has_comma_form_synthesizes_accessor() {
    // The comma-separated option form (not the fat-arrow `name => (...)` form).
    let fa = build_fa(
        "
package Foo;
use Moo;
has 'name', is => 'ro', default => sub { 1 };
has age => (is => 'rw');
",
    );
    let name_acc: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "name" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(
        name_acc.len(),
        1,
        "comma-form `has 'name', is => 'ro'` should synthesize a `name` accessor"
    );
    // The fat-arrow form on the next line still works (no regression).
    // `is => 'rw'` synthesizes a getter + a writer (2 symbols named `age`).
    let age_acc: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "age" && s.kind == SymKind::Method)
        .collect();
    assert_eq!(age_acc.len(), 2, "fat-arrow rw form still synthesizes getter+setter");
    // `is`/`default` must not become phantom accessors.
    assert!(
        !fa.symbols.iter().any(|s| (s.name == "is" || s.name == "ro") && s.kind == SymKind::Method),
        "option keywords/values must not mint phantom methods in comma form"
    );
}

// ---- typeglob sub installation (CG-1) ----

fn has_sub(fa: &FileAnalysis, name: &str) -> bool {
    fa.symbols
        .iter()
        .any(|s| s.name == name && s.kind == SymKind::Sub)
}

#[test]
fn glob_static_name_sub() {
    let fa = build_fa("*greet = sub { return 'hi' };\n");
    assert!(has_sub(&fa, "greet"), "static *name = sub {{...}} must mint a Sub symbol");
}

#[test]
fn glob_alias_to_existing_sub() {
    let fa = build_fa("*alias = \\&Other::func;\n*local_alias = \\&real;\n");
    assert!(has_sub(&fa, "alias"), "*name = \\&Other::func glob alias must mint a Sub symbol");
    assert!(has_sub(&fa, "local_alias"), "*name = \\&func glob alias must mint a Sub symbol");
}

#[test]
fn glob_qualified_name_installs_tail() {
    // `*Other::foo = sub {...}` installs `foo` into Other; the unqualified
    // tail is what local call sites / nav use.
    let fa = build_fa("*Other::foo = sub { 1 };\n");
    assert!(has_sub(&fa, "foo"), "qualified glob must register the unqualified tail");
    assert!(!has_sub(&fa, "Other::foo"), "must not register the fully-qualified string as a name");
}

#[test]
fn glob_loop_over_qw() {
    let src = "for my $m (qw/red green blue/) {\n  no strict 'refs';\n  *$m = sub { 1 };\n}\n";
    let fa = build_fa(src);
    for name in ["red", "green", "blue"] {
        assert!(has_sub(&fa, name), "loop-installed glob `{name}` must mint a Sub symbol");
    }
}

#[test]
fn glob_begin_constant_style() {
    let src = "BEGIN {\n  *_FORCE_WRITABLE = sub () { 1 };\n}\n";
    let fa = build_fa(src);
    assert!(
        has_sub(&fa, "_FORCE_WRITABLE"),
        "constant-style glob sub in BEGIN must mint a Sub symbol"
    );
}

#[test]
fn glob_literal_block_name() {
    let fa = build_fa("*{ 'is_thing' } = sub { 1 };\n");
    assert!(has_sub(&fa, "is_thing"), "`*{{ 'literal' }}` glob must mint a Sub symbol");
}

#[test]
fn glob_scalar_rhs_coderef() {
    let fa = build_fa("*handler = $coderef;\n");
    assert!(has_sub(&fa, "handler"), "*name = $coderef must mint a Sub symbol");
}

#[test]
fn glob_dynamic_name_skipped() {
    // Fully runtime name — no static derivation, must NOT fabricate a symbol.
    let fa = build_fa("*{ $runtime } = sub { 1 };\n");
    // The anon `sub {...}` RHS mints an `(anon)` Sub symbol; the glob install
    // itself must add no named Sub.
    assert!(
        !fa.symbols.iter().any(|s| s.kind == SymKind::Sub && s.name != "(anon)"),
        "fully-dynamic glob name must be skipped, not guessed"
    );
}

#[test]
fn glob_unfoldable_concat_skipped() {
    // `'is_' . $type` with an unknown $type is not derivable → skip.
    let fa = build_fa("*{ 'is_' . $type } = sub { 1 };\n");
    assert!(
        !fa.symbols.iter().any(|s| s.kind == SymKind::Sub && s.name.starts_with("is_")),
        "unfoldable concat name must be skipped, not guessed with a partial prefix"
    );
}

#[test]
fn glob_concat_with_loop_var_foldable() {
    // `'is_' . $kind` where $kind ranges over a qw list → derivable names.
    let src =
        "for my $kind (qw/foo bar/) {\n  *{ 'is_' . $kind } = sub { 1 };\n}\n";
    let fa = build_fa(src);
    assert!(has_sub(&fa, "is_foo"), "foldable concat over loop var must mint is_foo");
    assert!(has_sub(&fa, "is_bar"), "foldable concat over loop var must mint is_bar");
}

#[test]
fn normal_assignment_unaffected() {
    // Regression guard: a plain scalar assignment must not mint a Sub symbol,
    // and `my $x = sub {...}` is a lexical coderef, not a glob install.
    let fa = build_fa("my $x = 42;\nmy $cb = sub { 1 };\n");
    assert!(
        !fa.symbols.iter().any(|s| s.name == "x" && s.kind == SymKind::Sub),
        "plain scalar assignment must not mint a Sub symbol"
    );
    assert!(
        !fa.symbols.iter().any(|s| s.name == "cb" && s.kind == SymKind::Sub),
        "lexical `my $cb = sub {{...}}` must not be treated as a glob install"
    );
}

// ---- CG-3a: glob loop over a local literal-returning sub ----

#[test]
fn glob_loop_over_local_qw_sub() {
    // CGI.pm shape: the loop source is a same-file sub returning a qw list.
    // Each installed glob name must mint a Sub symbol.
    let src = "\
foreach my $tag (_all_html_tags()) {
  no strict 'refs';
  *$tag = sub { 1 };
}
sub _all_html_tags { return qw(div span br); }
";
    let fa = build_fa(src);
    for name in ["div", "span", "br"] {
        assert!(has_sub(&fa, name), "loop over local qw-returning sub must mint `{name}`");
    }
}

#[test]
fn glob_loop_over_local_list_sub() {
    // Same, but the local sub returns a bare parenthesized string list
    // (no `qw`, no explicit `return`).
    let src = "\
for my $m (_names()) {
  *$m = sub { 1 };
}
sub _names { ('alpha', 'beta') }
";
    let fa = build_fa(src);
    assert!(has_sub(&fa, "alpha"), "loop over local list-returning sub must mint alpha");
    assert!(has_sub(&fa, "beta"), "loop over local list-returning sub must mint beta");
}

#[test]
fn glob_loop_over_nonliteral_local_sub_skipped() {
    // The local sub's body is computed (not a literal list) → fold yields
    // nothing, loop var stays dynamic, no fabricated symbols.
    let src = "\
for my $m (_dynamic()) {
  *$m = sub { 1 };
}
sub _dynamic { return map { lc } @ARGV; }
";
    let fa = build_fa(src);
    assert!(
        !fa.symbols.iter().any(|s| s.kind == SymKind::Sub && s.name != "(anon)" && s.name != "_dynamic"),
        "non-literal local sub return must not synthesize glob names"
    );
}

#[test]
fn glob_loop_over_unknown_sub_skipped() {
    // Cross-file / undefined callee — no same-file body to fold. Skip.
    let src = "\
for my $m (Some::Other::tags()) {
  *$m = sub { 1 };
}
";
    let fa = build_fa(src);
    assert!(
        !fa.symbols.iter().any(|s| s.kind == SymKind::Sub && s.name != "(anon)"),
        "unresolvable loop-source sub must not synthesize glob names"
    );
}

// ---- CG-3b: cross-package glob injection via ->can ----

#[test]
fn glob_loop_can_rhs_synthesizes_under_current_pkg() {
    // DateTime::PP shape. `__PACKAGE__->can($sub)` is recognized as a
    // sub-producing RHS; the qualified target name is synthesized as the
    // unqualified tail under the current package (cross-package attribution
    // deferred — see synthesize_glob_assigned_sub).
    let src = "\
for my $sub (qw/foo bar/) {
  *{ 'DateTime::' . $sub } = __PACKAGE__->can($sub);
}
";
    let fa = build_fa(src);
    assert!(has_sub(&fa, "foo"), "->can RHS over loop var must mint foo (tail)");
    assert!(has_sub(&fa, "bar"), "->can RHS over loop var must mint bar (tail)");
    assert!(!has_sub(&fa, "DateTime::foo"), "must not register the fully-qualified name");
}

#[test]
fn glob_can_on_package_invocant() {
    // `Pkg->can('name')` static target also qualifies as sub-producing.
    let fa = build_fa("*alias = Foo::Bar->can('helper');\n");
    assert!(has_sub(&fa, "alias"), "*name = Pkg->can(...) must mint a Sub symbol");
}

#[test]
fn glob_non_can_method_rhs_skipped() {
    // A method call that isn't `->can` is not known to yield a coderef → skip.
    let fa = build_fa("*thing = $obj->build_something();\n");
    assert!(!has_sub(&fa, "thing"), "non-can method RHS must not mint a Sub symbol");
}

// ---- mk_classdata in a statement-modifier loop ----

fn count_method(fa: &FileAnalysis, name: &str) -> usize {
    fa.symbols.iter().filter(|s| s.name == name && s.kind == SymKind::Method).count()
}

#[test]
fn mk_classdata_postfix_for_qw() {
    // Catalyst.pm:176 shape.
    let fa = build_fa(
        "\
package My::App;
use base 'Class::Accessor::Grouped';
__PACKAGE__->mk_classdata($_) for qw/setup_finished params/;
",
    );
    assert_eq!(count_method(&fa, "setup_finished"), 1, "loop mk_classdata must mint setup_finished once");
    assert_eq!(count_method(&fa, "params"), 1, "loop mk_classdata must mint params once");
}

#[test]
fn mk_classdata_postfix_for_list() {
    // `mk_classdata($_) for (LIST)` bare-call form (Controller.pm:123).
    let fa = build_fa(
        "\
package My::Controller;
use base 'Class::Accessor::Grouped';
mk_classdata($_) for ('action_namespace', 'path_prefix');
",
    );
    assert_eq!(count_method(&fa, "action_namespace"), 1, "bare-call loop must mint action_namespace");
    assert_eq!(count_method(&fa, "path_prefix"), 1, "bare-call loop must mint path_prefix");
}

#[test]
fn mk_classdata_postfix_for_nonliteral_skipped() {
    // Loop over an array variable → no literal names → no synthesis.
    let fa = build_fa(
        "\
package My::App;
use base 'Class::Accessor::Grouped';
__PACKAGE__->mk_classdata($_) for @dynamic_names;
",
    );
    assert!(
        !fa.symbols.iter().any(|s| s.kind == SymKind::Method),
        "non-literal loop list must not synthesize accessors"
    );
}

#[test]
fn postfix_for_non_accessor_call_synthesizes_nothing() {
    // Regression: a statement-modifier loop whose body is an unrelated call
    // must not mint any accessor symbol.
    let fa = build_fa(
        "\
package My::App;
print(\"$_\\n\") for qw/a b c/;
",
    );
    assert!(
        !fa.symbols.iter().any(|s| s.kind == SymKind::Method),
        "non-accessor postfix-for loop must not synthesize accessors"
    );
}

// ---- Class::Tiny accessor synthesis (CG-2) ----

#[test]
fn test_class_tiny_list_form_synthesizes_accessors() {
    let fa = build_fa(
        "
package Foo;
use Class::Tiny qw( resolvers cache );
",
    );
    for attr in ["resolvers", "cache"] {
        let acc: Vec<_> = fa
            .symbols
            .iter()
            .filter(|s| s.name == attr && s.kind == SymKind::Method)
            .collect();
        assert_eq!(
            acc.len(),
            1,
            "Class::Tiny qw list should synthesize one rw accessor for `{attr}`"
        );
        // Constructor key so `Foo->new(resolvers => ...)` connects.
        let key_def: Vec<_> = fa
            .symbols
            .iter()
            .filter(|s| s.name == attr && matches!(s.detail, SymbolDetail::HashKeyDef { .. }))
            .collect();
        assert!(
            !key_def.is_empty(),
            "Class::Tiny attr `{attr}` should mint a constructor HashKeyDef"
        );
        if let SymbolDetail::HashKeyDef { ref owner, .. } = key_def[0].detail {
            assert_eq!(
                owner,
                &HashKeyOwner::Sub {
                    package: Some("Foo".to_string()),
                    name: "new".to_string(),
                }
            );
        }
    }
}

#[test]
fn test_class_tiny_hashref_form_synthesizes_accessors_from_keys() {
    let fa = build_fa(
        "
package Foo;
use Class::Tiny {
  name => 'default',
  builder => sub { [] },
};
",
    );
    // Keys are accessors; default values (string / coderef) are NOT.
    for attr in ["name", "builder"] {
        let acc: Vec<_> = fa
            .symbols
            .iter()
            .filter(|s| s.name == attr && s.kind == SymKind::Method)
            .collect();
        assert_eq!(
            acc.len(),
            1,
            "Class::Tiny hashref key `{attr}` should synthesize an accessor"
        );
    }
    // The default value `'default'` must not become an accessor.
    assert!(
        !fa.symbols
            .iter()
            .any(|s| s.name == "default" && s.kind == SymKind::Method),
        "hashref default value must not mint a phantom accessor"
    );
}

#[test]
fn test_class_tiny_combined_list_and_hashref() {
    // `use Class::Tiny qw( ssn ), { name => undef };` — both shapes on one line.
    let fa = build_fa(
        "
package Foo;
use Class::Tiny qw( ssn ), { name => undef };
",
    );
    for attr in ["ssn", "name"] {
        assert!(
            fa.symbols
                .iter()
                .any(|s| s.name == attr && s.kind == SymKind::Method),
            "combined qw+hashref form should synthesize accessor `{attr}`"
        );
    }
}

#[test]
fn test_non_class_tiny_use_unaffected() {
    // Regression: an unrelated `use X qw(...)` must NOT synthesize accessors.
    let fa = build_fa(
        "
package Foo;
use List::Util qw( max min );
",
    );
    assert!(
        !fa.symbols
            .iter()
            .any(|s| (s.name == "max" || s.name == "min") && s.kind == SymKind::Method),
        "non-Class::Tiny use must not synthesize accessor methods"
    );
}

// ── Task A: rule #7 ref-emission for use-constant usages + export-list members ──

/// `use constant NAME => ...` usage sites (plain expr + call arg) each get a
/// FunctionCall ref back to the constant def, so goto-def and references work.
#[test]
fn const_usage_name_form_emits_function_call_ref() {
    let src = r#"
package QA::C;
use constant MAX_RETRIES => 5;
sub retry {
    my $limit = MAX_RETRIES;
    return _attempt($limit, MAX_RETRIES);
}
sub _attempt { return 1 }
"#;
    let fa = build_fa(src);
    let usages: Vec<&Ref> = fa
        .refs
        .iter()
        .filter(|r| {
            r.target_name == "MAX_RETRIES"
                && matches!(
                    &r.kind,
                    RefKind::FunctionCall { resolved_package } if resolved_package.as_deref() == Some("QA::C")
                )
        })
        .collect();
    assert_eq!(
        usages.len(),
        2,
        "both MAX_RETRIES usages (plain + call-arg) should ref the const def; got {:?}",
        fa.refs
            .iter()
            .filter(|r| r.target_name == "MAX_RETRIES")
            .collect::<Vec<_>>()
    );
}

/// Block form `use constant { TIMEOUT => 30, BACKOFF => 2 }` — usages of a
/// block-declared constant get the same FunctionCall ref.
#[test]
fn const_usage_block_form_emits_function_call_ref() {
    let src = r#"
package QA::C;
use constant {
    TIMEOUT => 30,
    BACKOFF => 2,
};
sub run {
    my $t = TIMEOUT;
    return $t + BACKOFF;
}
"#;
    let fa = build_fa(src);
    for name in ["TIMEOUT", "BACKOFF"] {
        let n = fa
            .refs
            .iter()
            .filter(|r| {
                r.target_name == name
                    && matches!(&r.kind, RefKind::FunctionCall { .. })
            })
            .count();
        assert_eq!(n, 1, "{name} usage should ref the block-form const def");
    }
}

/// goto-def from a constant usage lands on the const def via `ref_at` +
/// `refs_to`; references on the const lists the def + every usage.
#[test]
fn const_usage_goto_def_and_references() {
    use crate::file_store::FileStore;
    use crate::resolve::{refs_to, RoleMask, TargetKind, TargetRef};
    use std::path::PathBuf;

    let src = r#"package QA::C;
use constant MAX_RETRIES => 5;
sub retry {
    my $limit = MAX_RETRIES;
    return MAX_RETRIES;
}
"#;
    let fa = build_fa(src);

    // ref_at the first usage (`my $limit = MAX_RETRIES;`) is a FunctionCall
    // ref naming the const — that's the goto-def routing token.
    let usage_pt = Point::new(3, 16); // inside MAX_RETRIES on the `my $limit` line
    let r = fa
        .ref_at(usage_pt)
        .expect("a ref should sit on the constant usage");
    assert_eq!(r.target_name, "MAX_RETRIES");
    assert!(matches!(r.kind, RefKind::FunctionCall { .. }));

    let store = FileStore::new();
    let path = PathBuf::from("/tmp/qa_const.pm");
    store.insert_workspace(path.clone(), fa);

    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "MAX_RETRIES".to_string(),
            kind: TargetKind::Sub {
                package: Some("QA::C".to_string()),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    // def + 2 usages = 3 hits.
    assert_eq!(
        results.len(),
        3,
        "references on MAX_RETRIES should list the def and both usages; got {results:?}"
    );
}

/// Regression: a bareword that is NOT a declared constant gets no spurious
/// constant-usage ref.
#[test]
fn non_constant_bareword_gets_no_const_ref() {
    let src = r#"
package QA::C;
use constant MAX_RETRIES => 5;
sub run {
    my $x = SOME_OTHER;
    return $x;
}
"#;
    let fa = build_fa(src);
    assert!(
        !fa.refs
            .iter()
            .any(|r| r.target_name == "SOME_OTHER"),
        "a non-constant bareword must not get a constant-usage ref"
    );
}

/// `@EXPORT` / `@EXPORT_OK` / `%EXPORT_TAGS` member tokens that name a local
/// sub each get a FunctionCall ref to that sub (forward-declared subs work).
#[test]
fn export_list_members_ref_local_subs() {
    let src = r#"
package QA::E;
use Exporter 'import';
our @EXPORT      = qw(always_on);
our @EXPORT_OK   = qw(opt_a opt_b opt_c);
our %EXPORT_TAGS = (
    group_one => [qw(opt_a opt_b)],
    group_two => [qw(opt_c)],
);
sub always_on { 1 }
sub opt_a { 'a' }
sub opt_b { 'b' }
sub opt_c { 'c' }
"#;
    let fa = build_fa(src);
    let count = |name: &str| {
        fa.refs
            .iter()
            .filter(|r| {
                r.target_name == name
                    && matches!(
                        &r.kind,
                        RefKind::FunctionCall { resolved_package } if resolved_package.as_deref() == Some("QA::E")
                    )
            })
            .count()
    };
    // always_on: 1 (@EXPORT). opt_a: @EXPORT_OK + %EXPORT_TAGS group_one = 2.
    // opt_b: @EXPORT_OK + group_one = 2. opt_c: @EXPORT_OK + group_two = 2.
    assert_eq!(count("always_on"), 1, "@EXPORT member should ref its sub");
    assert_eq!(count("opt_a"), 2, "opt_a appears in @EXPORT_OK and a tag array");
    assert_eq!(count("opt_b"), 2, "opt_b appears in @EXPORT_OK and a tag array");
    assert_eq!(count("opt_c"), 2, "opt_c appears in @EXPORT_OK and a tag array");
}

/// goto-def / references on an export-list member resolve to the sub def.
#[test]
fn export_member_goto_def_and_references() {
    use crate::file_store::FileStore;
    use crate::resolve::{refs_to, RoleMask, TargetKind, TargetRef};
    use std::path::PathBuf;

    let src = r#"package QA::E;
use Exporter 'import';
our @EXPORT_OK = qw(opt_a opt_b);
sub opt_a { 'a' }
sub opt_b { 'b' }
"#;
    let fa = build_fa(src);

    // ref_at the `opt_a` token in the export list.
    let opt_a_def_span = fa
        .symbols
        .iter()
        .find(|s| s.name == "opt_a")
        .map(|s| s.selection_span)
        .expect("opt_a sub symbol");
    // The export-list member ref must NOT be the def span itself.
    let export_ref = fa
        .refs
        .iter()
        .find(|r| {
            r.target_name == "opt_a"
                && matches!(&r.kind, RefKind::FunctionCall { .. })
                && r.span != opt_a_def_span
        })
        .expect("an export-list FunctionCall ref for opt_a");
    let r = fa
        .ref_at(export_ref.span.start)
        .expect("ref_at the export member token");
    assert_eq!(r.target_name, "opt_a");

    let store = FileStore::new();
    let path = PathBuf::from("/tmp/qa_export.pm");
    store.insert_workspace(path.clone(), fa);
    let results = refs_to(
        &store,
        None,
        &TargetRef {
            name: "opt_a".to_string(),
            kind: TargetKind::Sub {
                package: Some("QA::E".to_string()),
            },
            method_classes: Vec::new(),
        },
        RoleMask::EDITABLE,
    );
    // def + 1 export-list mention = 2.
    assert_eq!(
        results.len(),
        2,
        "references on opt_a should list the def and its @EXPORT_OK mention; got {results:?}"
    );
}

/// Regression: a `%EXPORT_TAGS` tag-NAME key (`group_one`) is NOT a sub, so it
/// gets no ref even though it sits in the export table.
#[test]
fn export_tag_name_key_gets_no_ref() {
    let src = r#"
package QA::E;
use Exporter 'import';
our %EXPORT_TAGS = (
    group_one => [qw(opt_a)],
);
sub opt_a { 'a' }
sub group_one { 'not a tag' }
"#;
    let fa = build_fa(src);
    // The fixture defines a sub literally named `group_one` to make the test
    // sharp: if the tag-name key were (wrongly) recorded as a member, it would
    // resolve to this sub. The key must still get no ref — only the value-array
    // member `opt_a` does.
    let group_one_refs = fa
        .refs
        .iter()
        .filter(|r| {
            r.target_name == "group_one"
                && matches!(&r.kind, RefKind::FunctionCall { .. })
        })
        .count();
    assert_eq!(
        group_one_refs, 0,
        "a tag-name key must not be reffed even when a same-named sub exists"
    );
}

/// Package-qualified `@Pkg::EXPORT` / `@Pkg::EXPORT_OK` / `%Pkg::EXPORT_TAGS`
/// (Bugzilla's form) must populate the export surface exactly like the
/// `our @EXPORT` spelling. Without this, `use Bugzilla::Util;` resolves nothing
/// (the 1000+ Bugzilla FP cluster).
#[test]
fn qualified_export_globals_populate_surface() {
    let src = r#"
package Bugzilla::Util;
@Bugzilla::Util::EXPORT = qw(trick_taint detaint_natural);
@Bugzilla::Util::EXPORT_OK = qw(opt_util);
%Bugzilla::Util::EXPORT_TAGS = (all => [qw(trick_taint opt_util)]);
sub trick_taint { 1 }
sub detaint_natural { 2 }
sub opt_util { 3 }
"#;
    let fa = build_fa(src);
    assert!(
        fa.export.contains(&"trick_taint".to_string())
            && fa.export.contains(&"detaint_natural".to_string()),
        "qualified @Pkg::EXPORT must populate the default set; got export={:?}",
        fa.export,
    );
    assert!(
        fa.export_ok.contains(&"opt_util".to_string()),
        "qualified @Pkg::EXPORT_OK must populate the optional set; got export_ok={:?}",
        fa.export_ok,
    );
    // Tag membership is preserved per-tag for the `:tag` consumer selector.
    let surface = fa.export_surface();
    let all = surface.tag_members("all").expect("all tag present");
    assert!(
        all.contains(&"trick_taint") && all.contains(&"opt_util"),
        "qualified %Pkg::EXPORT_TAGS must record per-tag members; got {:?}",
        all,
    );
    // :DEFAULT is synthesized from @EXPORT.
    let default = surface.tag_members("DEFAULT").expect(":DEFAULT synthesized");
    assert!(
        default.contains(&"trick_taint") && default.contains(&"detaint_natural"),
        ":DEFAULT must equal @EXPORT; got {:?}",
        default,
    );
}

/// `%EXPORT_TAGS = ( all => [...] )` and the plain-comma `( 'all', [...] )`
/// fold identically — `=>` is just an autoquoting comma, so the tag key/value
/// pairing is positional. A `:all` import must bind the folded members in both
/// spellings.
#[test]
fn export_tags_plain_comma_folds_members() {
    for table in [
        "( all => [qw(foo bar)] )",
        "( 'all', [qw(foo bar)] )",
    ] {
        let src = format!(
            "package P;\nour %EXPORT_TAGS = {table};\nsub foo {{ 1 }}\nsub bar {{ 2 }}\n",
        );
        let fa = build_fa(&src);
        let surface = fa.export_surface();
        let all = surface
            .tag_members("all")
            .unwrap_or_else(|| panic!("`all` tag must fold for table `{table}`"));
        assert!(
            all.contains(&"foo") && all.contains(&"bar"),
            "table `{table}`: :all members foo+bar must fold; got {:?}",
            all,
        );
        assert!(
            fa.export_ok.contains(&"foo".to_string()),
            "table `{table}`: tag members join the export surface; got export_ok={:?}",
            fa.export_ok,
        );
    }
}

/// A constant invoked as a call (`MAX_RETRIES()`) is reffed once by the
/// function-call path; the bareword arm must not double-emit at that span.
#[test]
fn const_call_form_not_double_reffed() {
    let src = r#"
package QA::C;
use constant MAX_RETRIES => 5;
sub run { return MAX_RETRIES(); }
"#;
    let fa = build_fa(src);
    let n = fa
        .refs
        .iter()
        .filter(|r| {
            r.target_name == "MAX_RETRIES" && matches!(&r.kind, RefKind::FunctionCall { .. })
        })
        .count();
    assert_eq!(n, 1, "MAX_RETRIES() call must get exactly one FunctionCall ref");
}

/// AutoLoader-backed package: subs after `__END__` live in the opaque
/// `data_section`, but they are runtime-live via AUTOLOAD. They must surface
/// as navigable Sub symbols with file-offset spans, with POD between them
/// skipped, and goto-def from an in-package caller must reach them.
#[test]
fn autoloader_data_section_subs_synthesized() {
    let src = "package My::AL;\n\
               use AutoLoader qw(AUTOLOAD);\n\
               sub uses_them { want_read(); }\n\
               1;\n\
               __END__\n\
               sub want_read { return 42 }\n\
               sub get_https { do_httpx2(GET => 1, @_) }\n\
               =pod\n\
               junk\n\
               =cut\n\
               sub after_pod ($;$) { return 1 }\n";
    let fa = build_fa(src);

    let names: std::collections::HashSet<&str> = fa
        .symbols
        .iter()
        .filter(|s| s.kind == SymKind::Sub)
        .map(|s| s.name.as_str())
        .collect();
    assert!(names.contains("want_read"), "want_read must be synthesized");
    assert!(names.contains("get_https"), "get_https must be synthesized");
    assert!(names.contains("after_pod"), "sub after POD must be synthesized");

    // Spans land in the data section (row 5 = first sub after __END__).
    let want_read = fa
        .symbols
        .iter()
        .find(|s| s.name == "want_read" && s.kind == SymKind::Sub)
        .expect("want_read symbol");
    assert_eq!(want_read.selection_span.start.row, 5, "want_read at file row 5");
    assert_eq!(want_read.package.as_deref(), Some("My::AL"));

    // Goto-def from the in-package caller reaches the data-section def.
    let def = fa.find_definition(Point::new(2, 16), None);
    assert_eq!(
        def.map(|s| s.start.row),
        Some(5),
        "goto-def on want_read() should land on the data-section sub"
    );
}

/// The gate: a package that does NOT use AutoLoader/SelfLoader must not have
/// its trailing `__END__` / `__DATA__` payload mined for subs — that text is
/// genuine data or POD, not code.
#[test]
fn non_autoloader_data_section_synthesizes_nothing() {
    let src = "package My::Plain;\n\
               use strict;\n\
               sub real_sub { 1 }\n\
               1;\n\
               __END__\n\
               sub looks_like_a_sub { return 99 }\n\
               =pod\n\
               docs\n\
               =cut\n\
               plain documentation text\n";
    let fa = build_fa(src);
    assert!(
        fa.symbols
            .iter()
            .all(|s| s.name != "looks_like_a_sub"),
        "data-section subs must NOT be synthesized without AutoLoader/SelfLoader"
    );
    assert!(
        fa.symbols.iter().any(|s| s.name == "real_sub"),
        "the real pre-__END__ sub is still present"
    );
}

/// Inheritance-form gate: `use base 'AutoLoader'` (parents, not a direct
/// `use AutoLoader`) also enables data-section synthesis.
#[test]
fn autoloader_via_use_base_enables_synthesis() {
    let src = "package My::Sub;\n\
               use base 'AutoLoader';\n\
               1;\n\
               __END__\n\
               sub inherited_loader_sub { return 1 }\n";
    let fa = build_fa(src);
    assert!(
        fa.symbols
            .iter()
            .any(|s| s.name == "inherited_loader_sub" && s.kind == SymKind::Sub),
        "use base 'AutoLoader' must enable data-section synthesis"
    );
}

/// CHAINED hashref-key ref: `$obj->get_config->{host}` — get_config's
/// return type is a known class (here a blessed Config), so the `host`
/// key is knowable and must get its own narrow HashKeyAccess ref owned
/// by that class. Without it, references/goto-def on `host` are dropped.
#[test]
fn chained_method_call_hash_key_emits_owned_ref() {
    let src = "\
package Config;
sub new { bless { host => 'localhost', port => 5432 }, shift }
package Foo;
sub new { bless {}, shift }
sub get_config { return Config->new() }
package main;
my $obj = Foo->new();
$obj->get_config->{host};
";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());

    // The `host` token (line 7, after `->{`) gets a HashKeyAccess ref
    // owned by Config — the chain receiver's class.
    let host_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "host" && matches!(r.kind, RefKind::HashKeyAccess { .. }))
        .collect();
    assert!(
        !host_refs.is_empty(),
        "chained hash-key access should emit a HashKeyAccess ref for 'host'"
    );
    let owner = host_refs
        .iter()
        .find_map(|r| match &r.kind {
            RefKind::HashKeyAccess { owner: Some(o), .. } => Some(o.clone()),
            _ => None,
        })
        .expect("chained hash-key ref should carry a resolved owner");
    assert_eq!(
        owner,
        HashKeyOwner::Class("Config".to_string()),
        "owner should be the chain receiver's class, got {:?}",
        owner
    );

    // Goto-def from the `host` token reaches the bless'd key in Config::new.
    let key_ref = host_refs[0];
    let def = fa.find_definition(key_ref.span.start, None);
    assert!(
        def.is_some(),
        "goto-def on chained `->{{host}}` should resolve to Config's key def"
    );
    assert_eq!(def.unwrap().start.row, 1, "host def is the bless key on line 1");
}

/// Plain-comma blessed hash keys (`bless { 'host', $h }`) emit HashKeyDef
/// symbols exactly like the fat-comma spelling — `collect_pair_keys` pairs
/// positionally, so the key is the even-position element regardless of the
/// separator that follows it.
#[test]
fn blessed_hash_plain_comma_keys_emit_hash_key_defs() {
    let src = "\
package Config;
sub new { bless { 'host', 'localhost', port => 5432 }, shift }
package main;
my $c = Config->new();
$c->{host};
$c->{port};
";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());
    // `bless { ... }` inside `sub new` owns its keys by the declaring sub
    // (Config::new) — the same owner the fat-comma spelling produces.
    let expected = HashKeyOwner::Sub { package: Some("Config".to_string()), name: "new".to_string() };
    for key in ["host", "port"] {
        assert!(
            fa.symbols.iter().any(|s| s.name == key
                && matches!(&s.detail, SymbolDetail::HashKeyDef { owner, .. } if *owner == expected)),
            "plain/fat-comma bless key `{key}` must emit a HashKeyDef owned by Config::new; got: {:?}",
            fa.symbols.iter()
                .filter(|s| matches!(s.detail, SymbolDetail::HashKeyDef { .. }))
                .map(|s| (s.name.clone(), s.detail.clone())).collect::<Vec<_>>(),
        );
    }
}

/// Regression: an untyped chain (`$obj->mystery->{host}` where `mystery`
/// has no resolvable return type) must emit NO key ref — honest about
/// ignorance rather than latching onto a wrong owner.
#[test]
fn untyped_chain_emits_no_hash_key_ref() {
    let src = "\
package main;
my $obj = bless {}, 'Foo';
$obj->totally_unknown_method->{host};
";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());
    let host_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "host" && matches!(r.kind, RefKind::HashKeyAccess { .. }))
        .collect();
    assert!(
        host_refs.is_empty(),
        "untyped chain must not emit a hash-key ref, got {:?}",
        host_refs
    );
}

/// CG-3b cross-package glob attribution: `*{ 'DateTime::' . $sub } = …`
/// inside `package DateTime::PP` synthesizes the tail (`_ymd2rd`) under
/// the *named* package (`DateTime`), not the file's own package.
#[test]
fn cross_package_glob_synthesizes_under_target_package() {
    let src = r#"package DateTime::PP;
sub _ymd2rd { 1 }
sub _rd2ymd { 2 }
my @subs = qw( _ymd2rd _rd2ymd );
for my $sub (@subs) {
    no strict 'refs';
    *{ 'DateTime::' . $sub } = __PACKAGE__->can($sub);
}
1;
"#;
    let fa = build_fa(src);
    for tail in ["_ymd2rd", "_rd2ymd"] {
        let under_datetime = fa.symbols.iter().any(|s| {
            s.name == tail
                && matches!(s.kind, SymKind::Sub)
                && s.package.as_deref() == Some("DateTime")
        });
        assert!(
            under_datetime,
            "glob-synthesized `{}` should be attributed to DateTime, symbols: {:?}",
            tail,
            fa.symbols
                .iter()
                .filter(|s| s.name == tail)
                .map(|s| (&s.name, &s.package))
                .collect::<Vec<_>>()
        );
    }
    // The real definitions (under DateTime::PP) are untouched.
    assert!(
        fa.symbols.iter().any(|s| s.name == "_ymd2rd"
            && matches!(s.kind, SymKind::Sub)
            && s.package.as_deref() == Some("DateTime::PP")),
        "the original DateTime::PP::_ymd2rd sub must still exist"
    );
}

/// Pins ARBITRARY DEPTH for the chained hash-key owner: build-time owner
/// resolution must ride the recursive chain typer, so `host` carries the same
/// `Config` owner whether the chain is one hop or three.
#[test]
fn chained_method_call_hash_key_owned_at_arbitrary_depth() {
    let src = "\
package Config;
sub new { bless { host => 'localhost' }, shift }
package Foo;
sub new { bless {}, shift }
sub me { return $_[0] }
sub get_config { return Config->new() }
package main;
my $obj = Foo->new();
$obj->get_config->{host};
$obj->me->me->get_config->{host};
";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());
    let owners: Vec<_> = fa.refs.iter().filter_map(|r| match &r.kind {
        RefKind::HashKeyAccess { owner: Some(o), .. } if r.target_name == "host" => Some(o.clone()),
        _ => None,
    }).collect();
    assert_eq!(owners.len(), 2, "both 1-hop and 3-hop chained ->{{host}} should emit an owned ref, got {:?}", owners);
    assert!(owners.iter().all(|o| *o == HashKeyOwner::Class("Config".to_string())), "every depth's owner must be Config, got {:?}", owners);
}

/// Mixed-depth chain: a method-call value, then a hash-key, then a method,
/// then a hash-key. `$obj->get_config->deep->cfg->{host}` — the final `host`
/// resolves through (method → typed value → method → key).
#[test]
fn chained_hash_key_mixed_depth_method_key() {
    let src = "\
package Inner;
sub new { bless { host => 'localhost' }, shift }
package Deep;
sub new { bless {}, shift }
sub cfg { return Inner->new() }
package Config;
sub new { bless {}, shift }
sub deep { return Deep->new() }
package Foo;
sub new { bless {}, shift }
sub get_config { return Config->new() }
package main;
my $obj = Foo->new();
$obj->get_config->deep->cfg->{host};
";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());
    let owners: Vec<_> = fa.refs.iter().filter_map(|r| match &r.kind {
        RefKind::HashKeyAccess { owner: Some(o), .. } if r.target_name == "host" => Some(o.clone()),
        _ => None,
    }).collect();
    assert_eq!(owners, vec![HashKeyOwner::Class("Inner".to_string())],
        "mixed-depth chain must resolve host's owner to Inner, got {:?}", owners);
}

/// Regression: an untyped deep chain emits NO owner — honest-about-ignorance,
/// never a wrong-owner latch.
#[test]
fn chained_hash_key_untyped_deep_chain_no_owner() {
    let src = "\
package Foo;
sub new { bless {}, shift }
sub mystery { return $_[0]->some_unknown_thing() }
package main;
my $obj = Foo->new();
$obj->mystery->mystery->{host};
";
    let tree = parse(src);
    let fa = build(&tree, src.as_bytes());
    let owned: Vec<_> = fa.refs.iter().filter(|r| matches!(&r.kind,
        RefKind::HashKeyAccess { owner: Some(_), .. }) && r.target_name == "host").collect();
    assert!(owned.is_empty(), "untyped deep chain must not latch a wrong owner, got {:?}",
        owned.iter().map(|r| &r.kind).collect::<Vec<_>>());
}

/// Regression: a same-package glob (`*name = sub {…}`, no `::` prefix)
/// still synthesizes under the current package.
#[test]
fn same_package_glob_synthesizes_under_current_package() {
    let src = r#"package Acme::Widget;
*frobnicate = sub { 42 };
1;
"#;
    let fa = build_fa(src);
    assert!(
        fa.symbols.iter().any(|s| s.name == "frobnicate"
            && matches!(s.kind, SymKind::Sub)
            && s.package.as_deref() == Some("Acme::Widget")),
        "same-package glob must stay under the current package, symbols: {:?}",
        fa.symbols
            .iter()
            .filter(|s| s.name == "frobnicate")
            .map(|s| (&s.name, &s.package))
            .collect::<Vec<_>>()
    );
}

// ---- ${@} block-interpolation token-stream bleed recovery (TASK-C / G1) ----
//
// `"${@}"` (the `@` sigil inside `${...}`) mis-lexes: the string's closing
// quote is swallowed, wrapping the rest of the file in an ERROR and dissolving
// every following `sub` into stray tokens — they survive NOWHERE in the tree.
// Source-text recovery inside the ERROR span restores them. See
// docs/parser-shortcomings.md (G1) and docs/adr/error-recovery.md.

fn sub_names(fa: &FileAnalysis) -> Vec<String> {
    fa.symbols
        .iter()
        .filter(|s| matches!(s.kind, SymKind::Sub | SymKind::Method))
        .map(|s| s.name.clone())
        .collect()
}

#[test]
fn dollar_at_block_interp_bleed_recovers_following_subs() {
    let src = r#"package Foo;
my $x = "err ${@} more text here";
sub alpha { return 1; }
sub beta { return 2; }
sub gamma { my $self = shift; return $self; }
1;
"#;
    let fa = build_fa(src);
    // The bleed produces zero subroutine_declaration_statement nodes; without
    // text recovery this asserts 0 subs.
    let names = sub_names(&fa);
    for want in ["alpha", "beta", "gamma"] {
        assert!(
            names.iter().any(|n| n == want),
            "sub `{want}` must survive the ${{@}} bleed; recovered: {names:?}"
        );
    }
}

#[test]
fn dollar_at_block_interp_recovered_sub_has_correct_position() {
    let src = r#"package Foo;
my $x = "err ${@}";
sub alpha { return 1; }
1;
"#;
    let fa = build_fa(src);
    let alpha = fa
        .symbols
        .iter()
        .find(|s| s.name == "alpha" && matches!(s.kind, SymKind::Sub))
        .expect("alpha recovered");
    // `sub alpha` is on row 2 (0-based), name token at column 4.
    assert_eq!(alpha.selection_span.start.row, 2, "alpha row");
    assert_eq!(alpha.selection_span.start.column, 4, "alpha name column");
    assert_eq!(alpha.package.as_deref(), Some("Foo"), "alpha package");
}

#[test]
fn dollar_at_block_interp_bleed_keeps_package() {
    // The package statement precedes the bleed and must still be indexed so the
    // recovered subs key under the right package.
    let src = r#"package Net::DNS::RR;
my $e = "${@}in $stmnt\n";
sub new { }
sub decode { }
sub encode { }
1;
"#;
    let fa = build_fa(src);
    assert!(
        fa.symbols
            .iter()
            .any(|s| s.name == "Net::DNS::RR" && matches!(s.kind, SymKind::Package)),
        "package survives the bleed"
    );
    for want in ["new", "decode", "encode"] {
        assert!(
            fa.symbols.iter().any(|s| s.name == want
                && matches!(s.kind, SymKind::Sub | SymKind::Method)
                && s.package.as_deref() == Some("Net::DNS::RR")),
            "sub `{want}` recovered under Net::DNS::RR"
        );
    }
}

#[test]
fn normal_parse_unaffected_by_error_text_recovery() {
    // Regression: text recovery only runs inside ERROR spans, so a clean file
    // must produce exactly the structurally-parsed subs with no duplicates.
    let src = r#"package Foo;
sub one { 1 }
sub two { 2 }
1;
"#;
    let fa = build_fa(src);
    let mut names = sub_names(&fa);
    names.sort();
    assert_eq!(names, vec!["one".to_string(), "two".to_string()]);
}

#[test]
fn error_text_recovery_does_not_duplicate_a_recovered_sub() {
    // A sub inside an ERROR region must be recovered exactly once even when the
    // structural loop and the text scan could fire on overlapping spans (the
    // row-based dedup guards this). `if (` wraps the trailing sub in an ERROR;
    // the sub mis-parses, so the text scan recovers it — and must do so once.
    let src = "package Foo;\nif (\nsub kept { 1 }\n";
    let fa = build_fa(src);
    let kept: Vec<_> = fa
        .symbols
        .iter()
        .filter(|s| s.name == "kept" && matches!(s.kind, SymKind::Sub | SymKind::Method))
        .collect();
    assert_eq!(kept.len(), 1, "no duplicate `kept`: {kept:?}");
}

// ---- Typed-slot witness (SlotType) ----
//
// These exercise the typed half of the hash-key-write seed in isolation:
// build a fixture, then query the `SlotType{class, key}` attachment
// through the registry. Nothing in the server consumes this attachment
// yet (typed `$obj->{k}->m()` resolution is a later step), so the
// registry query IS the whole validation surface.

fn slot_type(fa: &FileAnalysis, class: &str, key: &str) -> Option<InferredType> {
    use crate::witnesses::{
        BagContext, FrameworkFact, ReducedValue, ReducerQuery, ReducerRegistry, WitnessAttachment,
    };
    let att = WitnessAttachment::SlotType {
        class: class.to_string(),
        key: key.to_string(),
    };
    let ctx = BagContext {
        scopes: &fa.scopes,
        package_framework: &fa.package_framework,
        module_index: None,
        package_parents: &fa.package_parents,
        app_surface_consumers: &fa.app_surface_consumers,
    };
    let q = ReducerQuery {
        attachment: &att,
        point: None,
        framework: FrameworkFact::Plain,
        arity_hint: None,
        receiver: None,
        context: Some(&ctx),
    };
    let reg = ReducerRegistry::with_defaults();
    match reg.query(&fa.witnesses, &q) {
        ReducedValue::Type(t) => Some(t),
        _ => None,
    }
}

#[test]
fn slot_type_single_typed_write() {
    let src = "package Foo;\nsub init {\n  my $self = shift;\n  $self->{h} = Helper->new;\n}\n";
    let fa = build_fa(src);
    let t = slot_type(&fa, "Foo", "h").expect("SlotType{Foo,h} should fold");
    assert_eq!(t.class_name(), Some("Helper"), "got {t:?}");
}

#[test]
fn slot_type_two_agreeing_writes() {
    let src = "package Foo;\nsub a {\n  my $self = shift;\n  $self->{h} = Helper->new;\n}\nsub b {\n  my $self = shift;\n  $self->{h} = Helper->new;\n}\n";
    let fa = build_fa(src);
    let t = slot_type(&fa, "Foo", "h").expect("agreeing writes fold to the agreed type");
    assert_eq!(t.class_name(), Some("Helper"), "got {t:?}");
}

#[test]
fn slot_type_two_disagreeing_writes_none() {
    let src = "package Foo;\nsub a {\n  my $self = shift;\n  $self->{h} = Helper->new;\n}\nsub b {\n  my $self = shift;\n  $self->{h} = Other->new;\n}\n";
    let fa = build_fa(src);
    // Disagreeing writes → honest None (no guess).
    assert_eq!(slot_type(&fa, "Foo", "h"), None);
}

#[test]
fn slot_type_unknown_rhs_no_slot() {
    // `= shift` / `= $param` carry no resolvable type — no SlotType seed,
    // never a guess.
    let src = "package Foo;\nsub init {\n  my $self = shift;\n  my $param = shift;\n  $self->{h} = $param;\n}\n";
    let fa = build_fa(src);
    assert_eq!(slot_type(&fa, "Foo", "h"), None);
}

#[test]
fn slot_type_keyed_by_owner_class() {
    // `$o->{h}` where `$o` is a typed local `Foo` keys the slot by the
    // OWNER's class, distinct from `$self->{h}` of the enclosing package.
    let src = "package Bar;\nsub mk {\n  my $self = shift;\n  my $o = Foo->new;\n  $o->{h} = Helper->new;\n  $self->{h} = Sidecar->new;\n}\n";
    let fa = build_fa(src);
    let foo_h = slot_type(&fa, "Foo", "h").expect("SlotType keyed by owner class Foo");
    assert_eq!(foo_h.class_name(), Some("Helper"), "got {foo_h:?}");
    // The enclosing-package write lands on Bar, not Foo — no cross-contamination.
    let bar_h = slot_type(&fa, "Bar", "h").expect("SlotType{Bar,h} from $self write");
    assert_eq!(bar_h.class_name(), Some("Sidecar"), "got {bar_h:?}");
}


#[test]
fn test_braced_invocant_bless_is_receiver_poly() {
    // The braced spelling `${self}` / `${class}` must be recognized as the
    // receiver-polymorphic ctor idiom (canonical varname, not raw `$self` text).
    let fa = build_fa(
        "package Base;\nsub new { my $class = shift; bless {}, ref ${class} || ${class} }\npackage Child;\nuse parent -norequire, 'Base';\n",
    );
    assert_eq!(
        fa.find_method_return_type("Child", "new", None, Some(0)),
        Some(InferredType::ClassName("Child".into())),
        "braced-self inherited ctor must type Child->new as Child"
    );
    // a real deref `bless {}, ${$ref}` is NOT receiver-poly -> not Child
    let fa2 = build_fa(
        "package Base;\nsub new { my $ref = \\'X'; bless {}, ${$ref} }\npackage Child;\nuse parent -norequire, 'Base';\n",
    );
    assert_ne!(
        fa2.find_method_return_type("Child", "new", None, Some(0)),
        Some(InferredType::ClassName("Child".into())),
        "a sigil-deref bless target must NOT be treated as the receiver"
    );
}

#[test]
fn test_super_new_types_to_calling_class() {
    // `$self->SUPER::new` looks `new` up on the parent (`Base`), but `Base::new`
    // is receiver-polymorphic (`bless {}, ref $class || $class`), so it blesses
    // into the SUBCLASS — `Child::new` must return `Child`, not `Base`. And a
    // `clone` that calls `$self->new` composes through the SUPER hop back to
    // `Child`.
    let fa = build_fa(
        "package Base;\nsub new { my $class = shift; bless {}, ref $class || $class }\nsub parse { $_[0] }\npackage Child;\nuse parent -norequire, 'Base';\nsub new { my $self = shift; @_ > 1 ? $self->SUPER::new->parse(@_) : $self->SUPER::new }\nsub clone { my $self = shift; my $c = $self->new; @$c{qw(a)} = (1); return $c }\n",
    );
    assert_eq!(
        fa.find_method_return_type("Child", "new", None, Some(0)),
        Some(InferredType::ClassName("Child".into())),
        "SUPER::new on a receiver-polymorphic parent ctor blesses into the subclass"
    );
    assert_eq!(
        fa.find_method_return_type("Child", "clone", None, Some(0)),
        Some(InferredType::ClassName("Child".into())),
        "clone's $self->new composes through the SUPER hop back to the subclass"
    );
}

#[test]
fn test_fq_method_call_dispatches_from_named_class() {
    // `$obj->Maker::build()` is a fully-qualified method call: Perl dispatches
    // `build` from `Maker`, NOT from the invocant's class. `Maker::build` is
    // receiver-polymorphic (returns the invocant's class), so the FQ call types
    // to `Invoker` (the invocant). If we wrongly dispatched from the invocant's
    // class, we'd pick `Invoker::build` → `Numeric` — so asserting `Invoker`
    // also proves the named class won.
    let fa = build_fa(
        "package Maker;\nsub build { my $class = shift; return bless {}, ref $class || $class }\npackage Invoker;\nsub new { my $c = shift; return bless {}, ref $c || $c }\nsub build { return 42 }\npackage main;\nmy $obj = Invoker->new;\nmy $r = $obj->Maker::build();\n",
    );
    assert_eq!(
        fa.inferred_type_via_bag("$r", Point::new(7, 4)),
        Some(InferredType::ClassName("Invoker".into())),
        "FQ call dispatches build from Maker (receiver-poly → invocant), not from Invoker"
    );
}

#[test]
fn test_bless_return_strands_class_arg_recovered() {
    // tree-sitter-perl strands the class arg of `return bless {BLOCK}, CLASS`
    // (the brace block greedily ends the parenless call). We splice it back, so
    // the foreign literal class is honored instead of falling to the enclosing
    // package.
    let lit = build_fa("package P;\nsub make { return bless {}, 'Widget' }\n");
    assert_eq!(
        lit.find_method_return_type("P", "make", None, Some(0)),
        Some(InferredType::ClassName("Widget".into())),
        "return bless {{}}, 'Widget' must type to Widget, not the enclosing package"
    );
    // The receiver-polymorphic spelling with `return` is the common inherited
    // ctor — recovery makes it ReceiverOr so a subclass types to itself.
    let poly = build_fa(
        "package Base;\nsub new { my $class = shift; return bless {}, ref $class || $class }\npackage Child;\nuse parent -norequire, 'Base';\nsub make { my $self = shift; return $self->new }\n",
    );
    assert_eq!(
        poly.find_method_return_type("Child", "make", None, Some(0)),
        Some(InferredType::ClassName("Child".into())),
        "inherited receiver-poly ctor (return bless {{}}, ref $class || $class) types to the subclass"
    );
}

#[test]
fn test_bless_positional_self_is_receiver() {
    // `$_[0]` is the positional spelling of the invocant — a receiver-poly ctor
    // written `bless {}, ref $_[0] || $_[0]` types to the calling subclass.
    let fa = build_fa(
        "package Base;\nsub new { return bless {}, ref $_[0] || $_[0] }\npackage Child;\nuse parent -norequire, 'Base';\nsub make { my $self = shift; return $self->new }\n",
    );
    assert_eq!(
        fa.find_method_return_type("Child", "make", None, Some(0)),
        Some(InferredType::ClassName("Child".into())),
        "bless {{}}, ref $_[0] || $_[0] is receiver-polymorphic via the positional self"
    );
}

/// `${sner}->thing` is `$sner->thing` — the grammar's `varname` child
/// excludes the braces, and the ref records the canonical sigiled name so
/// invocant-class resolution hits the variable's bag key. A deref block
/// (`${$ref}`) has no bare varname and must keep its raw text (no false
/// canonicalization).
#[test]
fn braced_scalar_invocant_canonicalizes_and_resolves() {
    let src = "\
package main;
my $sner = Foo->new;
${sner}->thing;
my $ref = \\$sner;
${$ref}->other;
";
    let fa = build_fa(src);
    let thing = fa
        .refs
        .iter()
        .find(|r| r.target_name == "thing")
        .expect("MethodCall ref for thing");
    let RefKind::MethodCall { ref invocant, .. } = thing.kind else {
        panic!("expected MethodCall, got {:?}", thing.kind);
    };
    assert_eq!(invocant, "$sner");
    assert_eq!(
        fa.method_call_invocant_class(thing, None).as_deref(),
        Some("Foo"),
        "braced spelling resolves through the variable's type",
    );

    let other = fa
        .refs
        .iter()
        .find(|r| r.target_name == "other")
        .expect("MethodCall ref for other");
    let RefKind::MethodCall { ref invocant, .. } = other.kind else {
        panic!("expected MethodCall, got {:?}", other.kind);
    };
    assert_eq!(invocant, "${$ref}", "deref block keeps raw text");
}

/// `my $c = 'Counter'; $c->bump` — a scalar invocant holding a const-folded
/// string dispatches on that class (the same fold dynamic method names use,
/// on the other slot of the arrow). Walk-time `invocant_class` pins it, so
/// class-scoped refs/rename see the call without inference.
#[test]
fn const_folded_scalar_invocant_pins_class() {
    let src = "\
package Counter;
sub bump { 1 }
package main;
my $c = 'Counter';
$c->bump;
";
    let fa = build_fa(src);
    let bump = fa
        .refs
        .iter()
        .find(|r| r.target_name == "bump" && matches!(r.kind, RefKind::MethodCall { .. }))
        .expect("MethodCall ref for bump");
    assert_eq!(
        fa.method_call_invocant_class(bump, None).as_deref(),
        Some("Counter"),
        "const-folded invocant should dispatch on Counter",
    );
}

/// `field $x :param :reader` is one renameable entity: the field variable,
/// the constructor key, and the reader-method calls rewrite together,
/// from WHICHEVER spelling the cursor is on — and the `$` sigil survives
/// (edits cover only the bare name).
#[test]
fn corinna_field_group_rename_ties_all_spellings() {
    let src = "\
use v5.38;
class Point {
    field $x :param :reader;
    field $y :param;
    method magnitude () { return sqrt($x**2 + $y**2); }
}
my $p = Point->new(x => 3, y => 4);
my $val = $p->x;
";
    let fa = build_fa(src);
    let find = |row: usize, col: usize| {
        fa.rename_at(Point::new(row, col), "coord")
            .map(|mut v| {
                v.sort_by_key(|(s, _)| (s.start.row, s.start.column));
                v
            })
            .expect("rename produces edits")
    };
    // Expected spellings of `x`: field decl (2), body use (4), ctor key (6),
    // reader call (7).
    let from_decl = find(2, 11);
    let rows: Vec<usize> = from_decl.iter().map(|(s, _)| s.start.row).collect();
    assert_eq!(rows, vec![2, 4, 6, 7], "decl rename covers all spellings: {:?}", from_decl);
    // Sigil survives: the decl edit starts AFTER the `$`.
    assert_eq!(from_decl[0].0.start.column, 11);
    assert!(from_decl.iter().all(|(_, t)| t == "coord"));

    // Same union from the constructor key and from the body use.
    assert_eq!(find(6, 19), from_decl, "ctor-key rename == decl rename");
    assert_eq!(find(4, 39), from_decl, "body-use rename == decl rename");

    // `$y` is untouched by `$x`'s group.
    assert!(
        !from_decl.iter().any(|(s, _)| s.start.row == 3),
        "y's decl must not be in x's group"
    );

    // A `:param`-less field still renames as a plain group (no keys).
    let src2 = "\
use v5.38;
class Q {
    field $label = \"q\";
    method tag () { return $label; }
}
my $q = Q->new();
";
    let fa2 = build_fa(src2);
    let edits = fa2.rename_at(Point::new(2, 11), "name").expect("plain field renames");
    assert_eq!(edits.len(), 2, "decl + body use only: {:?}", edits);
}

/// Moo `has name` is the same one-entity story as a Corinna field: the
/// decl token, accessor calls, and constructor keys rename together from
/// whichever spelling the cursor is on.
#[test]
fn moo_attr_group_rename_ties_all_spellings() {
    let src = "\
package Widget;
use Moo;
has size => (is => 'ro');
sub describe { my ($self) = @_; return $self->size; }
package main;
my $w = Widget->new(size => 3);
my $s = $w->size;
";
    let fa = build_fa(src);
    let find = |row: usize, col: usize| {
        fa.rename_at(Point::new(row, col), "extent")
            .map(|mut v| {
                v.sort_by_key(|(s, _)| (s.start.row, s.start.column));
                v
            })
            .expect("rename produces edits")
    };
    // Spellings of `size`: has decl (2), accessor call in describe (3),
    // ctor key (5), accessor call (6).
    let from_decl = find(2, 5);
    let rows: Vec<usize> = from_decl.iter().map(|(s, _)| s.start.row).collect();
    assert_eq!(rows, vec![2, 3, 5, 6], "decl rename covers all spellings: {:?}", from_decl);

    assert_eq!(find(5, 21), from_decl, "ctor-key rename == decl rename");
    assert_eq!(find(3, 47), from_decl, "accessor-call rename == decl rename");
}

/// Plugin-enrolled mapped members: `predicate => 1` synthesizes
/// `has_size`, whose name DERIVES from the attr. Renaming the attr from
/// any spelling re-derives the predicate (`has_size` → `has_extent`) at
/// its call sites, and references include them. A name-mapped member
/// never double-edits the shared decl token.
#[test]
fn moo_mapped_predicate_joins_group_rename() {
    let src = "\
package Widget;
use Moo;
has size => (is => 'ro', predicate => 1);
package main;
my $w = Widget->new(size => 3);
if ($w->has_size) { print $w->size; }
";
    let fa = build_fa(src);
    let edits = fa
        .rename_at(Point::new(2, 5), "extent")
        .expect("rename produces edits");
    // The predicate call site is re-derived, not bare-replaced.
    let predicate_edit = edits
        .iter()
        .find(|(s, _)| s.start.row == 5 && s.start.column == 8)
        .expect("has_size call edited");
    assert_eq!(predicate_edit.1, "has_extent");
    // Everything else gets the bare name (decl, ctor key, accessor call).
    assert!(
        edits.iter().filter(|(_, t)| t == "extent").count() >= 3,
        "bare spellings renamed too: {:?}",
        edits,
    );
    // No span is edited twice.
    let mut spans: Vec<_> = edits.iter().map(|(s, _)| (s.start.row, s.start.column)).collect();
    spans.sort();
    spans.dedup();
    assert_eq!(spans.len(), edits.len(), "no duplicate-span edits: {:?}", edits);

    // References from the attr decl include the predicate call.
    let refs = fa.find_references(Point::new(2, 5), None);
    assert!(
        refs.iter().any(|s| s.start.row == 5 && s.start.column == 8),
        "references include has_size call: {:?}",
        refs,
    );
}

// ---- Tier 2 nested-hashkey: structurally-typed hash literals ----

/// `{ host => 'x', port => 5432 }` carries per-key types; `->{key}`
/// narrows through assignments and direct nesting; a spread flips the
/// shape open (unknown keys aren't claimable misses either way, but the
/// shape records it for future diagnostics).
#[test]
fn hash_literal_structural_typing_and_narrowing() {
    let src = "\
my $config = { db => { host => 'localhost', port => 5432 }, debug => 1 };
my $db = $config->{db};
my $host = $db->{host};
my $port = $config->{db}->{port};
my $open = { %$config, extra => 'x' };
";
    let fa = build_fa(src);

    // The literal's own structure.
    let cfg = fa
        .inferred_type_via_bag("$config", Point::new(1, 0))
        .expect("$config typed");
    let db_ty = cfg.key_value_type("db").expect("db key present").expect("db value typed");
    assert!(
        matches!(db_ty, InferredType::HashWithKeys { open: false, .. }),
        "nested literal rides the value slot: {:?}",
        db_ty,
    );
    assert!(cfg.key_value_type("typo").is_none(), "closed shape: unknown key is no key");

    // Narrowing through an assignment hop.
    let db = fa
        .inferred_type_via_bag("$db", Point::new(2, 0))
        .expect("$db typed from ->{db}");
    assert!(matches!(db, InferredType::HashWithKeys { .. }), "got {:?}", db);
    let host = fa
        .inferred_type_via_bag("$host", Point::new(3, 0))
        .expect("$host typed from ->{host}");
    assert_eq!(host, InferredType::String);

    // Direct double-drill, no intermediate variable.
    let port = fa
        .inferred_type_via_bag("$port", Point::new(4, 0))
        .expect("$port typed from ->{db}->{port}");
    assert_eq!(port, InferredType::Numeric);

    // Spread → open shape.
    let open = fa
        .inferred_type_via_bag("$open", Point::new(4, 9))
        .expect("$open typed");
    assert!(
        matches!(open, InferredType::HashWithKeys { open: true, .. }),
        "spread flips open: {:?}",
        open,
    );
}

/// Mutation extension: an unconditional `$v->{k} = …` write EXTENDS a
/// closed shape (the key joins the list, value typed from the RHS,
/// `open` preserved); a conditional or dynamic-key write switches the
/// shape open. Reads before the write keep the original shape.
#[test]
fn mutation_extension_on_closed_shapes() {
    let src = "\
my $ext = { host => 'x' };
my $before = $ext->{host};
$ext->{added} = 42;
my $after = $ext->{added};
my $cond = { host => 'x' };
$cond->{maybe} = 1 if $ENV{X};
my $dyn = { host => 'x' };
$dyn->{$ENV{K}} = 1;
";
    let fa = build_fa(src);

    // Before the write: the literal's own closed single-key shape.
    let t0 = fa.inferred_type_via_bag("$ext", Point::new(1, 0)).expect("$ext typed");
    assert!(
        matches!(&t0, InferredType::HashWithKeys { keys, open: false } if keys.len() == 1),
        "pre-write shape: {:?}",
        t0,
    );

    // After: extended, still closed, value typed from the RHS.
    let t1 = fa.inferred_type_via_bag("$ext", Point::new(3, 0)).expect("$ext typed");
    let InferredType::HashWithKeys { keys, open: false } = &t1 else {
        panic!("post-write shape: {:?}", t1)
    };
    assert_eq!(keys.len(), 2, "{:?}", keys);
    assert_eq!(keys[1].0, "added");
    assert_eq!(keys[1].1.as_deref(), Some(&InferredType::Numeric));
    let after = fa.inferred_type_via_bag("$after", Point::new(4, 0)).expect("$after typed");
    assert_eq!(after, InferredType::Numeric, "read drills the extended key");

    // Conditional write → open.
    let tc = fa.inferred_type_via_bag("$cond", Point::new(6, 0)).expect("$cond typed");
    assert!(
        matches!(tc, InferredType::HashWithKeys { open: true, .. }),
        "conditional write opens: {:?}",
        tc,
    );

    // Dynamic key → open.
    let td = fa.inferred_type_via_bag("$dyn", Point::new(8, 0)).expect("$dyn typed");
    assert!(
        matches!(td, InferredType::HashWithKeys { open: true, .. }),
        "dynamic key opens: {:?}",
        td,
    );
}

/// The literal-hash spelling: `my %h = (k => v)` types through the
/// same shape builder as the hashref literal, `$h{k}` projects off
/// `%h` (the canonical container name), mutation extension applies,
/// and spreads — arrays included (`@_`) — flip the shape open.
#[test]
fn literal_hash_structural_typing() {
    let src = "\
my %config = (host => 'x', port => 5432);
my $v = $config{host};
$config{added} = 42;
my $a = $config{added};
my %spread = (default => 1, @_);
";
    let fa = build_fa(src);
    let t = fa.inferred_type_via_bag("%config", Point::new(1, 0)).expect("%config typed");
    assert!(
        matches!(&t, InferredType::HashWithKeys { keys, open: false } if keys.len() == 2),
        "literal-list shape: {:?}",
        t,
    );
    let v = fa.inferred_type_via_bag("$v", Point::new(2, 0)).expect("$v typed");
    assert_eq!(v, InferredType::String, "container-form read projects");
    let t2 = fa.inferred_type_via_bag("%config", Point::new(3, 0)).expect("%config typed");
    assert!(
        matches!(&t2, InferredType::HashWithKeys { keys, open: false } if keys.len() == 3),
        "write extends: {:?}",
        t2,
    );
    let a = fa.inferred_type_via_bag("$a", Point::new(4, 0)).expect("$a typed");
    assert_eq!(a, InferredType::Numeric, "extended key value type");
    let sp = fa.inferred_type_via_bag("%spread", Point::new(5, 0)).expect("%spread typed");
    assert!(
        matches!(sp, InferredType::HashWithKeys { open: true, .. }),
        "array spread opens: {:?}",
        sp,
    );
}

/// Slice writes — sigil (`@h{…}`), postfix deref (`$r->@{…}`), and
/// sigil deref (`@$s{…}`) — land several keys at once: each records an
/// open-switching KeyWrite, so the closed shape widens instead of
/// claiming the written keys as misses.
#[test]
fn slice_writes_open_closed_shapes() {
    let src = "\
my %h = (a => 1);
@h{qw(b c)} = (1, 2);
my $r = { a => 1 };
$r->@{qw(d e)} = (3, 4);
my $s = { a => 1 };
@$s{qw(f g)} = (5, 6);
";
    let fa = build_fa(src);
    for (var, line) in [("%h", 2), ("$r", 4), ("$s", 6)] {
        let t = fa
            .inferred_type_via_bag(var, Point::new(line, 0))
            .unwrap_or_else(|| panic!("{var} typed"));
        assert!(
            matches!(t, InferredType::HashWithKeys { open: true, .. }),
            "slice write opens {var}: {:?}",
            t,
        );
    }
}

/// Sequence slot writes: a direct unconditional `$v->[N] = …` retypes
/// the in-bounds slot from the RHS; a write at exactly `len` appends;
/// a conditional write changes nothing (out-of-scope widening — no
/// open flag on Sequence, no array-index diagnostic to protect).
#[test]
fn sequence_index_writes_retype_and_append() {
    let src = "\
my $t = [1, 'x'];
$t->[0] = 'str';
$t->[2] = 99;
my $a = $t->[0];
my $b = $t->[2];
my $c = [1];
$c->[0] = 'maybe' if $ENV{X};
";
    let fa = build_fa(src);
    let t = fa.inferred_type_via_bag("$t", Point::new(3, 0)).expect("$t typed");
    let InferredType::Sequence(elems) = &t else { panic!("{:?}", t) };
    assert_eq!(
        elems.as_slice(),
        &[InferredType::String, InferredType::String, InferredType::Numeric],
        "slot 0 retyped, slot 2 appended",
    );
    let a = fa.inferred_type_via_bag("$a", Point::new(4, 0)).expect("$a typed");
    assert_eq!(a, InferredType::String);
    let b = fa.inferred_type_via_bag("$b", Point::new(5, 0)).expect("$b typed");
    assert_eq!(b, InferredType::Numeric);
    let c = fa.inferred_type_via_bag("$c", Point::new(7, 0)).expect("$c typed");
    let InferredType::Sequence(ce) = &c else { panic!("{:?}", c) };
    assert_eq!(ce.as_slice(), &[InferredType::Numeric], "conditional write unmodeled");
}

/// Sub-return literals narrow at call sites: `cfg()->{host}` → String.
#[test]
fn hash_literal_narrows_through_sub_return() {
    let src = "\
sub cfg { return { host => 'x', port => 1 } }
my $h = cfg()->{host};
";
    let fa = build_fa(src);
    let h = fa
        .inferred_type_via_bag("$h", Point::new(2, 0))
        .expect("$h typed through cfg()->{host}");
    assert_eq!(h, InferredType::String);
}

// ---- Tier 3 nested-hashkey: array element narrowing + mixed drill ----

/// `->[N]` projects array-literal element types (tuple semantics — the
/// heterogeneous case answers per index, better than bailing), and the
/// mixed drill `$obj->{users}->[0]->{name}` chains hash narrowing →
/// element projection → hash narrowing end-to-end.
#[test]
fn array_element_narrowing_and_mixed_drill() {
    let src = "\
my $x = [1, 'a'];
my $n = $x->[0];
my $s = $x->[1];
my $obj = { users => [ { name => 'A', id => 1 } ] };
my $name = $obj->{users}->[0]->{name};
my $id = $obj->{users}->[0]->{id};
";
    let fa = build_fa(src);
    assert_eq!(
        fa.inferred_type_via_bag("$n", Point::new(2, 0)),
        Some(InferredType::Numeric),
        "heterogeneous tuple projects per index",
    );
    assert_eq!(
        fa.inferred_type_via_bag("$s", Point::new(2, 8)),
        Some(InferredType::String),
    );
    assert_eq!(
        fa.inferred_type_via_bag("$name", Point::new(5, 0)),
        Some(InferredType::String),
        "mixed drill end-to-end",
    );
    assert_eq!(
        fa.inferred_type_via_bag("$id", Point::new(5, 30)),
        Some(InferredType::Numeric),
    );
}

/// Out-of-range and unknown-element honesty: `->[7]` of a 2-tuple is
/// None; a literal with an untypable element degrades to plain ArrayRef
/// (no per-slot claims).
#[test]
fn array_element_narrowing_negative_space() {
    let src = "\
my $x = [1, 'a'];
my $oob = $x->[7];
my $mixed = [1, some_call()];
";
    let fa = build_fa(src);
    assert_eq!(
        fa.inferred_type_via_bag("$oob", Point::new(2, 0)),
        None,
        "out-of-range projection stays honest",
    );
    let m = fa.inferred_type_via_bag("$mixed", Point::new(2, 10));
    assert_eq!(m, Some(InferredType::ArrayRef), "untypable element degrades whole literal");
}

/// `with map "Prefix::$_", qw/A B/` — the string-template map over a
/// literal list folds statically: role parents land (resolution walks
/// them) with per-word spans (goto-def on each qw word). The crm
/// role-graph idiom.
#[test]
fn map_built_role_parents() {
    let src = "\
package My::Class;
use Moo;
with map \"My::Roles::$_\", qw/Alpha Beta/;
";
    let fa = build_fa(src);
    let parents = fa.package_parents.get("My::Class").expect("parents recorded");
    assert_eq!(
        parents.as_slice(),
        &["My::Roles::Alpha".to_string(), "My::Roles::Beta".to_string()],
    );
}

/// A bareword naming an in-scope sub IS a call (Perl prefers the
/// defined sub over the class-name reading), so value-position
/// barewords get the full function treatment: a FunctionCall ref per
/// site — hover/goto-def/references/rename ride it. The declaration
/// name slot and unresolvable barewords stay untouched.
#[test]
fn bareword_promotes_to_function_ref() {
    let src = "\
sub get_config { return { host => 1 } }
my $a = get_config;
my $b = get_config->{host};
my @l = (get_config, 1);
my $f = UNRESOLVED_BAREWORD_FH;
";
    let fa = build_fa(src);
    let call_refs: Vec<_> = fa
        .refs
        .iter()
        .filter(|r| {
            r.target_name == "get_config" && matches!(r.kind, RefKind::FunctionCall { .. })
        })
        .collect();
    assert_eq!(
        call_refs.len(),
        3,
        "three value-position barewords promote; the decl name does not",
    );
    assert!(
        !fa.refs.iter().any(|r| r.target_name == "UNRESOLVED_BAREWORD_FH"),
        "unresolvable barewords stay untouched",
    );
}

/// Mojolicious::Lite topic routes: `under(...)->to('ctrl#…')` sets the
/// implicit base, `group { }` scopes it (an inner `under` applies only
/// within, the outer base restores after), and `->to('#action')`
/// partials on lite verb calls inherit the controller. Every name in
/// the mechanism comes from the mojo-lite plugin's topic_route_dsl
/// manifest; the base write is the plugin's SetRouteBase emission.
#[test]
fn lite_group_under_route_inheritance() {
    let src = "\
use Mojolicious::Lite;
under('/auth')->to('login#check');
group {
  under('/n')->to('notifications#under');
  get('/x')->to('#missing_fnsku');
};
get('/y')->to('#after_group');
";
    let fa = {
        let mut parser = super::create_parser();
        let tree = parser.parse(src, None).unwrap();
        super::build_with_plugins(&tree, src.as_bytes(), super::default_plugin_registry())
    };
    let invocant_of = |action: &str| -> String {
        fa.refs
            .iter()
            .find_map(|r| {
                if r.target_name != action {
                    return None;
                }
                let RefKind::MethodCall { ref invocant, .. } = r.kind else { return None };
                Some(format!("{:?}", invocant))
            })
            .unwrap_or_else(|| panic!("no MethodCall ref for {action}"))
    };
    assert!(
        invocant_of("missing_fnsku").contains("notifications"),
        "in-group partial inherits the group's under",
    );
    assert!(
        invocant_of("after_group").contains("login"),
        "post-group partial inherits the OUTER under — the group frame popped",
    );
}

/// `plugin 'Thing'` emits a register-anchored MethodCall ref with the
/// DECAMELIZED token ("WasLoaded" → "was_loaded"), so goto-def rides
/// the same camelize+tail+ownership search as go-to-controller —
/// namespace-agnostic (Mojolicious::Plugin::* and app-specific
/// namespaces both land).
#[test]
fn lite_plugin_name_emits_register_ref() {
    let src = "\
use Mojolicious::Lite;
plugin 'WasLoaded';
plugin 'Foo::BarBaz';
";
    let fa = {
        let mut parser = super::create_parser();
        let tree = parser.parse(src, None).unwrap();
        super::build_with_plugins(&tree, src.as_bytes(), super::default_plugin_registry())
    };
    let invocants: Vec<String> = fa
        .refs
        .iter()
        .filter(|r| r.target_name == "register")
        .filter_map(|r| {
            let RefKind::MethodCall { ref invocant, .. } = r.kind else { return None };
            Some(format!("{:?}", invocant))
        })
        .collect();
    assert_eq!(invocants.len(), 2, "{:?}", invocants);
    assert!(invocants[0].contains("was_loaded"), "{:?}", invocants);
    assert!(invocants[1].contains("foo-bar_baz"), "{:?}", invocants);
}

/// Framework-assigned Mojo attrs (`has [qw(app tx)]` with no default —
/// the framework sets them at dispatch) type via plugin overrides, and
/// a plugin's `register($self, $app, $conf)` gets `$app: Mojolicious`
/// via the param_types manifest — with or without an indexed Mojo
/// source tree.
#[test]
fn mojo_framework_assigned_attrs_type() {
    let src = "\
package My::App::Plugin::Demo;
use Mojo::Base 'Mojolicious::Plugin';
sub register {
  my ($self, $app, $conf) = @_;
  return $app;
}
1;
";
    let fa = {
        let mut parser = super::create_parser();
        let tree = parser.parse(src, None).unwrap();
        super::build_with_plugins(&tree, src.as_bytes(), super::default_plugin_registry())
    };
    let idx = crate::module_index::ModuleIndex::new_for_test();
    let t = fa.inferred_type_via_bag_ctx("$app", Point::new(4, 10), Some(&idx));
    assert_eq!(
        t,
        Some(InferredType::ClassName("Mojolicious".into())),
        "register's $app is the application",
    );
}

/// Interpolation deref `${ EXPR }` — `scalar > block` with no varname
/// wrapper — carries real code in strings AND regex patterns:
/// `s/_to_${\ $self->filetype }$//` holds a method call that must get
/// refs (the crm Clove::Converter idiom). The outer scalar emits
/// nothing (its text is not a variable name).
#[test]
fn interpolation_deref_code_gets_refs() {
    let src = "\
package T;
sub filetype { 'csv' }
sub run {
  my $self = shift;
  my @m;
  grep {s/_to_${\\$self->filetype}$//} @m;
  my $y = \"x_${\\$self->filetype}_z\";
  return $y;
}
1;
";
    let fa = build_fa(src);
    let calls = fa
        .refs
        .iter()
        .filter(|r| {
            r.target_name == "filetype" && matches!(r.kind, RefKind::MethodCall { .. })
        })
        .count();
    assert_eq!(calls, 2, "regex-pattern and string interpolations both ref");
    assert!(
        !fa.refs.iter().any(|r| r.target_name.contains("${")),
        "no junk ref for the outer interpolation scalar",
    );
}

#[test]
fn test_plugin_declared_role_maker_marks_consumer_as_role() {
    // The role-maker set is OPEN: core holds no list (the base engines
    // live in frameworks/moo.rhai's manifest), and any plugin can
    // declare another engine. A registry with ONLY this plugin proves
    // the manifest alone carries the fact.
    let plugin_src = r#"
        fn id() { "house-role-kit" }
        fn triggers() { [ #{ UsesModule: "My::CustomRole" } ] }
        fn role_makers() { ["My::CustomRole"] }
    "#;
    let engine = std::sync::Arc::new(crate::plugin::rhai_host::make_engine());
    let plugin = crate::plugin::rhai_host::RhaiPlugin::from_source(plugin_src, engine)
        .expect("plugin compiles");
    let mut reg = crate::plugin::PluginRegistry::new();
    reg.register(Box::new(plugin));

    let source = "package House::Role;\nuse My::CustomRole;\n1;\n";
    let mut parser = create_parser();
    let tree = parser.parse(source, None).unwrap();
    let fa = build_with_plugins(&tree, source.as_bytes(), std::sync::Arc::new(reg));
    assert!(
        fa.is_role_package("House::Role"),
        "plugin-declared role maker must mark the consumer as a role",
    );
    assert!(
        !fa.is_role_package("My::CustomRole"),
        "the maker module itself is not thereby a role",
    );
}

#[test]
fn test_bundled_moo_manifest_carries_base_role_engines() {
    // Regression net for the core-list deletion: the four base engines
    // ride frameworks/moo.rhai's role_makers() manifest through the
    // default registry. If the manifest breaks (rhai parse error, a
    // renamed fn), this is the test that says so directly.
    let source = "package R1;\nuse Moo::Role;\npackage R2;\nuse Moose::Role;\n\
                  package R3;\nuse Mouse::Role;\npackage R4;\nuse Role::Tiny;\n\
                  package C1;\nuse Moo;\npackage C2;\nuse Role::Tiny::With;\n1;\n";
    let mut parser = create_parser();
    let tree = parser.parse(source, None).unwrap();
    let fa = build(&tree, source.as_bytes());
    for role in ["R1", "R2", "R3", "R4"] {
        assert!(fa.is_role_package(role), "{role} should be a role");
    }
    for class in ["C1", "C2"] {
        assert!(!fa.is_role_package(class), "{class} should NOT be a role");
    }
}

#[test]
fn plugin_loads_recorded_trigger_independent_and_multivalue() {
    use crate::file_analysis::SymKind;
    // A Mojolicious::Plugin file (NO Mojo app trigger) loading other
    // plugins three ways: literal, qw-loop topic, folded constant.
    let src = "package My::Plugin::All;\n\
        use Mojo::Base 'Mojolicious::Plugin';\n\
        use constant EXTRA => 'Gizmos';\n\
        sub register {\n\
          my ($self, $app, $conf) = @_;\n\
          $app->plugin('FeatureFlags');\n\
          $app->plugin($_) for qw/SheetReaders ImportTasks ExportTasks/;\n\
          $app->plugin(EXTRA);\n\
        }\n\
        1;\n";
    let mut parser = create_parser();
    let tree = parser.parse(src, None).unwrap();
    let fa = build(&tree, src.as_bytes());
    let mut loads: Vec<String> = fa.plugin_loads.iter().map(|f| f.name.clone()).collect();
    loads.sort();
    assert_eq!(
        loads,
        vec!["ExportTasks", "FeatureFlags", "Gizmos", "ImportTasks", "SheetReaders"],
        "all three forms (literal, qw-loop, folded constant) recorded; got {:?}",
        fa.plugin_loads,
    );
    let _ = SymKind::Sub;
}