perl-lsp 0.3.0

A Perl LSP server built on tree-sitter-perl and tower-lsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
use super::*;
use crate::builder;

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

/// Build a CachedModule by parsing a synthesized Perl source listing the given exports.
/// Used by tests to seed ModuleIndex with known export lists without real @INC files.
fn fake_cached(
    path: &str,
    exports: &[&str],
    exports_ok: &[&str],
) -> std::sync::Arc<crate::module_index::CachedModule> {
    let mut source = String::from("package Fake;\n");
    if !exports.is_empty() {
        source.push_str(&format!("our @EXPORT = qw({});\n", exports.join(" ")));
    }
    if !exports_ok.is_empty() {
        source.push_str(&format!("our @EXPORT_OK = qw({});\n", exports_ok.join(" ")));
    }
    for n in exports.iter().chain(exports_ok.iter()) {
        source.push_str(&format!("sub {} {{}}\n", n));
    }
    source.push_str("1;\n");
    std::sync::Arc::new(crate::module_index::CachedModule::new(
        std::path::PathBuf::from(path),
        std::sync::Arc::new(parse_analysis(&source)),
    ))
}

#[test]
fn test_builtins_sorted() {
    for window in PERL_BUILTINS.windows(2) {
        assert!(
            window[0] < window[1],
            "PERL_BUILTINS not sorted: '{}' >= '{}'",
            window[0],
            window[1],
        );
    }
}

#[test]
fn test_is_perl_builtin() {
    assert!(is_perl_builtin("print"));
    assert!(is_perl_builtin("chomp"));
    assert!(is_perl_builtin("die"));
    assert!(!is_perl_builtin("frobnicate"));
    assert!(!is_perl_builtin("my_custom_sub"));
}

#[test]
fn test_diagnostics_skips_builtins() {
    let source = "use Carp qw(croak);\nprint 'hello';\ndie 'oops';\n";
    let analysis = parse_analysis(source);
    let module_index = crate::module_index::ModuleIndex::new_for_test();
    let diags = collect_diagnostics(&analysis, &module_index);
    // print and die are builtins, croak is explicitly imported — no diagnostics
    assert!(
        diags.is_empty(),
        "Expected no diagnostics for builtins/imported, got: {:?}",
        diags.iter().map(|d| &d.message).collect::<Vec<_>>(),
    );
}

#[test]
fn test_diagnostics_unresolved_function() {
    let source = "frobnicate();\n";
    let analysis = parse_analysis(source);
    let module_index = crate::module_index::ModuleIndex::new_for_test();
    let diags = collect_diagnostics(&analysis, &module_index);
    assert_eq!(diags.len(), 1);
    assert_eq!(diags[0].severity, Some(DiagnosticSeverity::INFORMATION));
    assert!(diags[0].message.contains("frobnicate"));
}

#[test]
fn test_diagnostics_skips_local_sub() {
    let source = "sub helper { 1 }\nhelper();\n";
    let analysis = parse_analysis(source);
    let module_index = crate::module_index::ModuleIndex::new_for_test();
    let diags = collect_diagnostics(&analysis, &module_index);
    assert!(
        diags.is_empty(),
        "Locally defined sub should not produce diagnostic, got: {:?}",
        diags.iter().map(|d| &d.message).collect::<Vec<_>>(),
    );
}

#[test]
fn test_diagnostics_skips_package_qualified() {
    let source = "Foo::Bar::baz();\n";
    let analysis = parse_analysis(source);
    let module_index = crate::module_index::ModuleIndex::new_for_test();
    let diags = collect_diagnostics(&analysis, &module_index);
    assert!(
        diags.is_empty(),
        "Package-qualified calls should not produce diagnostic",
    );
}

#[test]
fn test_code_action_from_diagnostic() {
    let source = "use Carp qw(croak);\ncarp('oops');\n";
    let analysis = parse_analysis(source);
    let uri = Url::parse("file:///test.pl").unwrap();

    // Simulate a HINT diagnostic with data (as collect_diagnostics would produce
    // if module_index had resolved Carp)
    let diag = Diagnostic {
        range: Range {
            start: Position {
                line: 1,
                character: 0,
            },
            end: Position {
                line: 1,
                character: 4,
            },
        },
        severity: Some(DiagnosticSeverity::HINT),
        code: Some(NumberOrString::String("unresolved-function".into())),
        source: Some("perl-lsp".into()),
        message: "'carp' is exported by Carp but not imported".into(),
        data: Some(serde_json::json!({"module": "Carp", "function": "carp"})),
        ..Default::default()
    };

    let actions = code_actions(&[diag], &analysis, &uri);
    assert_eq!(actions.len(), 1);
    if let CodeActionOrCommand::CodeAction(action) = &actions[0] {
        assert_eq!(action.title, "Import 'carp' from Carp");
        assert_eq!(action.kind, Some(CodeActionKind::QUICKFIX));
        assert_eq!(action.is_preferred, Some(true));

        // Verify the edit inserts " carp" at the qw close paren
        let edit = action.edit.as_ref().unwrap();
        let changes = edit.changes.as_ref().unwrap();
        let text_edits = changes.get(&uri).unwrap();
        assert_eq!(text_edits.len(), 1);
        assert_eq!(text_edits[0].new_text, " carp");
    } else {
        panic!("Expected CodeAction, got Command");
    }
}

#[test]
fn test_code_action_new_use_statement() {
    let source = "use strict;\nuse warnings;\nfrobnicate();\n";
    let analysis = parse_analysis(source);
    let uri = Url::parse("file:///test.pl").unwrap();

    let diag = Diagnostic {
        range: Range {
            start: Position {
                line: 2,
                character: 0,
            },
            end: Position {
                line: 2,
                character: 11,
            },
        },
        severity: Some(DiagnosticSeverity::HINT),
        code: Some(NumberOrString::String("unresolved-function".into())),
        source: Some("perl-lsp".into()),
        message: "'frobnicate' is exported by Some::Module (not yet imported)".into(),
        data: Some(serde_json::json!({
            "modules": ["Some::Module"],
            "function": "frobnicate",
        })),
        ..Default::default()
    };

    let actions = code_actions(&[diag], &analysis, &uri);
    assert_eq!(actions.len(), 1);
    if let CodeActionOrCommand::CodeAction(action) = &actions[0] {
        assert_eq!(action.title, "Add 'use Some::Module qw(frobnicate)'");
        assert_eq!(action.is_preferred, Some(true));
        let edit = action.edit.as_ref().unwrap();
        let changes = edit.changes.as_ref().unwrap();
        let text_edits = changes.get(&uri).unwrap();
        assert_eq!(text_edits[0].new_text, "use Some::Module qw(frobnicate);\n");
        // Inserted after last use statement (line 2)
        assert_eq!(text_edits[0].range.start.line, 2);
    } else {
        panic!("Expected CodeAction");
    }
}

#[test]
fn test_unimported_completion_with_auto_import() {
    let source = "use strict;\nuse warnings;\n\nfir\n";
    let analysis = parse_analysis(source);

    // Simulate a cached module that exports "first"
    let idx = ModuleIndex::new_for_test();
    idx.set_workspace_root(None);
    // Insert directly into cache for testing
    idx.insert_cache(
        "List::Util",
        Some(fake_cached(
            "/usr/lib/perl5/List/Util.pm",
            &[],
            &["first", "max", "min"],
        )),
    );

    let tree = crate::document::Document::new(source.to_string())
        .unwrap()
        .tree;
    let items = completion_items(
        &analysis,
        &tree,
        source,
        Position {
            line: 3,
            character: 3,
        },
        &idx,
        None,
    );

    // Should find "first" from List::Util
    let first_item = items.iter().find(|i| i.label == "first");
    assert!(
        first_item.is_some(),
        "Should offer 'first' from unimported List::Util"
    );

    let first_item = first_item.unwrap();
    assert!(
        first_item.detail.as_ref().unwrap().contains("List::Util"),
        "Detail should mention the module"
    );
    assert!(
        first_item.detail.as_ref().unwrap().contains("auto-import"),
        "Detail should indicate auto-import"
    );

    // Should have additional text edit inserting `use List::Util qw(first);`
    let edits = first_item.additional_text_edits.as_ref().unwrap();
    assert_eq!(edits.len(), 1);
    assert_eq!(edits[0].new_text, "use List::Util qw(first);\n");
    // Should insert after the last use statement (line 2)
    assert_eq!(edits[0].range.start.line, 2);
}

#[test]
fn test_unimported_completion_skips_imported_modules() {
    // List::Util is already imported — its exports should NOT appear as unimported completions
    let source = "use List::Util qw(max);\nfir\n";
    let analysis = parse_analysis(source);

    let idx = ModuleIndex::new_for_test();
    idx.set_workspace_root(None);
    idx.insert_cache(
        "List::Util",
        Some(fake_cached(
            "/usr/lib/perl5/List/Util.pm",
            &[],
            &["first", "max", "min"],
        )),
    );
    idx.insert_cache(
        "Scalar::Util",
        Some(fake_cached(
            "/usr/lib/perl5/Scalar/Util.pm",
            &[],
            &["blessed", "reftype"],
        )),
    );

    let tree = crate::document::Document::new(source.to_string())
        .unwrap()
        .tree;
    let items = completion_items(
        &analysis,
        &tree,
        source,
        Position {
            line: 1,
            character: 3,
        },
        &idx,
        None,
    );

    // "first" should appear via imported_function_completions (auto-add to qw),
    // NOT via unimported_function_completions
    let first_items: Vec<_> = items.iter().filter(|i| i.label == "first").collect();
    assert!(!first_items.is_empty(), "Should offer 'first'");
    // It should come from the imported path (adds to qw) not unimported
    for item in &first_items {
        if let Some(ref detail) = item.detail {
            assert!(
                !detail.contains("auto-import") || detail.contains("List::Util"),
                "first should come from List::Util context"
            );
        }
    }

    // "blessed" should appear as unimported (Scalar::Util not imported)
    let blessed_item = items.iter().find(|i| i.label == "blessed");
    assert!(
        blessed_item.is_some(),
        "Should offer 'blessed' from unimported Scalar::Util"
    );
    let blessed_item = blessed_item.unwrap();
    assert!(blessed_item
        .detail
        .as_ref()
        .unwrap()
        .contains("Scalar::Util"));
    let edits = blessed_item.additional_text_edits.as_ref().unwrap();
    assert!(edits[0].new_text.contains("use Scalar::Util qw(blessed)"));
}

/// Regression: typing `Package::` should NOT trigger the global
/// workspace-symbol firehose. Mirrors the EM gold corpus fixture
/// `completion_package_colon` (the pre-fix flood was 263 items); the
/// fix narrows to the package's own subs.
///
/// Multi-segment package name (`Math::Util`) on purpose — earlier
/// drafts narrowed only single-segment names, so this case is the
/// load-bearing assertion. Fixture also threads a `use constant` +
/// const-folded call site so the case is realistic Perl and the
/// constant doesn't get mistaken for a package qualifier.
#[test]
fn test_qualified_path_completion_narrows_to_package() {
    let source = "\
package Math::Util;
use constant PI => 3.14159;
sub square    { my ($n) = @_; $n * $n }
sub cube      { my ($n) = @_; $n * $n * $n }
sub circle_area {
    my ($r) = @_;
    return PI * $r * $r;           # const-folded arg flows through
}
package main;
use constant TAU => Math::Util::PI() * 2;
my $sq   = Math::Util::s
";
    let analysis = parse_analysis(source);
    let module_index = ModuleIndex::new_for_test();
    module_index.set_workspace_root(None);
    // Seed an unrelated cross-file module so the workspace flood
    // would include it if the firehose were still firing.
    module_index.insert_cache(
        "Scalar::Util",
        Some(fake_cached(
            "/usr/lib/perl5/Scalar/Util.pm",
            &[],
            &["blessed", "reftype"],
        )),
    );

    let tree = crate::document::Document::new(source.to_string())
        .unwrap()
        .tree;
    // Cursor at end of `Math::Util::s` on line 10 (0-indexed).
    // Line: `my $sq   = Math::Util::s` — cursor sits past the `s`.
    let line_text = source.lines().nth(10).unwrap();
    let cursor_col = line_text.len() as u32;
    let items = completion_items(
        &analysis,
        &tree,
        source,
        Position { line: 10, character: cursor_col },
        &module_index,
        None,
    );

    let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
    assert!(
        labels.contains(&"square"),
        "completion after `Math::Util::` should include `square`, got {:?}",
        labels,
    );
    assert!(
        labels.contains(&"cube"),
        "completion after `Math::Util::` should include `cube`, got {:?}",
        labels,
    );
    assert!(
        labels.contains(&"circle_area"),
        "completion after `Math::Util::` should include `circle_area` \
         (the const-folded sub), got {:?}",
        labels,
    );
    assert!(
        !labels.contains(&"blessed"),
        "completion after `Math::Util::` must NOT flood unrelated workspace \
         symbols (`blessed` is from Scalar::Util), got {:?}",
        labels,
    );
    // Tight bound — the 263-item flood is the bug we're regressing.
    // Allow some headroom for inherited / framework-synthesized
    // members but flag anything that grows past ~10× the package
    // size as a regression of the narrowing.
    assert!(
        items.len() <= 20,
        "completion after `Math::Util::` should narrow tightly to the package; \
         got {} items: {:?}",
        items.len(),
        labels,
    );
}

/// `Foo::<cursor>` should also offer the *sub-packages* nested
/// underneath, not just the methods on `Foo` itself. Typing `Mojo::`
/// expects to see `Util`, `Base`, `IOLoop` etc. alongside any methods
/// `Mojo` directly carries. Covers two sources of sub-packages —
/// in-file `package Foo::Bar` declarations AND cross-file modules
/// known to the resolver index — since either can be the right
/// answer in a real project.
#[test]
fn test_qualified_path_completion_offers_sub_packages() {
    let source = "\
package Math::Util;
sub square { my ($n) = @_; $n * $n }
package Math::Helpers;     # in-file sub-package, no module index entry
sub clamp { my ($x, $lo, $hi) = @_; $x }
package main;
my $x = Math::
";
    let analysis = parse_analysis(source);
    let module_index = ModuleIndex::new_for_test();
    module_index.set_workspace_root(None);
    // Cross-file sub-package: known via the workspace index, mirrors
    // the real "every package in its own .pm" project layout.
    module_index.insert_cache(
        "Math::Stats",
        Some(fake_cached("/usr/lib/perl5/Math/Stats.pm", &[], &["mean", "stddev"])),
    );
    // Unrelated module — must not bleed into Math:: results.
    module_index.insert_cache(
        "Scalar::Util",
        Some(fake_cached(
            "/usr/lib/perl5/Scalar/Util.pm",
            &[],
            &["blessed", "reftype"],
        )),
    );

    let tree = crate::document::Document::new(source.to_string())
        .unwrap()
        .tree;
    // Cursor at end of `Math::` on the last source line.
    let last_line_idx = source.lines().count() as u32 - 1;
    let line_text = source.lines().last().unwrap();
    let items = completion_items(
        &analysis,
        &tree,
        source,
        Position { line: last_line_idx, character: line_text.len() as u32 },
        &module_index,
        None,
    );

    let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
    assert!(
        labels.contains(&"Util"),
        "`Math::` should offer in-file sub-package `Util`, got {:?}",
        labels,
    );
    assert!(
        labels.contains(&"Helpers"),
        "`Math::` should offer in-file sub-package `Helpers`, got {:?}",
        labels,
    );
    assert!(
        labels.contains(&"Stats"),
        "`Math::` should offer cross-file sub-package `Stats`, got {:?}",
        labels,
    );
    assert!(
        !labels.contains(&"Scalar::Util") && !labels.contains(&"blessed"),
        "`Math::` must NOT bleed unrelated workspace symbols, got {:?}",
        labels,
    );
    // Sub-packages carry SymbolKind::MODULE, subs carry FUNCTION —
    // sanity-check the kind so clients pick the right icon.
    for item in &items {
        if matches!(item.label.as_str(), "Util" | "Helpers" | "Stats") {
            assert_eq!(
                item.kind,
                Some(tower_lsp::lsp_types::CompletionItemKind::MODULE),
                "sub-package `{}` should be SymbolKind::MODULE",
                item.label,
            );
        }
    }
}

/// Sibling case: the *package name itself* arrives via const-fold.
/// `my $pkg = 'Math::Util';` should let `$pkg->squ<cursor>` narrow
/// to `Math::Util`'s methods — but reaching that end-state needs the
/// witness bag to upgrade `$pkg` from `String` to `ClassName` when
/// it's used as a method invocant. That's a separate inference gap
/// (the QualifiedPath narrowing this PR ships handles the literal
/// `Foo::Bar::sub` syntactic form only). Marking ignored so the gap
/// is tracked rather than absorbed into this PR.
#[test]
#[ignore = "needs ClassName-from-string-invocant inference; tracked separately"]
fn test_const_folded_package_resolves_for_method_completion() {
    let source = "\
package Math::Util;
sub square    { my ($n) = @_; $n * $n }
sub cube      { my ($n) = @_; $n * $n * $n }
package main;
my $pkg = 'Math::Util';
$pkg->squ
";
    let analysis = parse_analysis(source);
    let module_index = ModuleIndex::new_for_test();
    module_index.set_workspace_root(None);

    let tree = crate::document::Document::new(source.to_string())
        .unwrap()
        .tree;
    // Cursor sits past the `q` in `$pkg->squ`.
    let line_text = source.lines().nth(5).unwrap();
    let cursor_col = line_text.len() as u32;
    let items = completion_items(
        &analysis,
        &tree,
        source,
        Position { line: 5, character: cursor_col },
        &module_index,
        None,
    );

    let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
    assert!(
        labels.contains(&"square"),
        "method completion on const-folded `$pkg` (= 'Math::Util') \
         should offer `square`, got {:?}",
        labels,
    );
    assert!(
        labels.contains(&"cube"),
        "method completion on const-folded `$pkg` (= 'Math::Util') \
         should offer `cube`, got {:?}",
        labels,
    );
}

/// Native subs emit `DocumentSymbol.name` as the bare identifier —
/// the LSP `kind` enum carries the Function/Method distinction.
/// Pre-fix we stuffed `<sub> ` into the name, which collided with
/// the EM gold corpus' protocol-correct assertions.
#[test]
fn test_document_symbol_name_is_bare_identifier() {
    let source = "\
package Demo::Symbols;
sub alpha { return 1 }
sub beta  { my ($x) = @_; $x * 2 }
1;
";
    let analysis = parse_analysis(source);
    let names: Vec<String> = analysis
        .document_symbols()
        .iter()
        .flat_map(|sym| {
            let mut acc = vec![sym.name.clone()];
            for c in &sym.children {
                acc.push(c.name.clone());
            }
            acc
        })
        .collect();
    assert!(
        names.iter().any(|n| n == "alpha"),
        "expected bare 'alpha' in document symbols, got {:?}",
        names,
    );
    assert!(
        names.iter().any(|n| n == "beta"),
        "expected bare 'beta' in document symbols, got {:?}",
        names,
    );
    for n in &names {
        assert!(
            !n.starts_with("<sub>") && !n.starts_with("<method>"),
            "DocumentSymbol.name should not carry `<sub>`/`<method>` prefix (got {:?})",
            n,
        );
    }
}

/// Hover on a Perl builtin returns the seeded perlfunc.pod entry.
/// The full POD parse pipeline is exercised separately in the
/// builtins_pod unit tests; here we just confirm the wiring from
/// hover_info → module_index.builtin_doc fires for builtin names.
#[test]
fn test_hover_on_builtin_uses_module_index() {
    let source = "push @items, 4;\n";
    let analysis = parse_analysis(source);
    let module_index = ModuleIndex::new_for_test();
    module_index.set_workspace_root(None);
    module_index.seed_builtin_for_test(
        "push",
        "```perl\npush ARRAY,LIST\n```\n\nAppends LIST to ARRAY.",
    );

    let tree = crate::document::Document::new(source.to_string())
        .unwrap()
        .tree;
    let hover = hover_info(
        &analysis,
        source,
        Position { line: 0, character: 0 },
        &module_index,
        &tree,
    )
    .expect("expected hover on `push`");
    let text = match hover.contents {
        HoverContents::Markup(m) => m.value,
        _ => panic!("expected markdown hover"),
    };
    assert!(text.contains("push ARRAY,LIST"), "hover body missing: {text}");
    assert!(text.contains("Appends LIST"), "hover body missing: {text}");
}

#[test]
fn test_code_action_multiple_exporters_not_preferred() {
    let source = "use strict;\nfirst();\n";
    let analysis = parse_analysis(source);
    let uri = Url::parse("file:///test.pl").unwrap();

    let diag = Diagnostic {
        range: Range {
            start: Position {
                line: 1,
                character: 0,
            },
            end: Position {
                line: 1,
                character: 5,
            },
        },
        severity: Some(DiagnosticSeverity::HINT),
        code: Some(NumberOrString::String("unresolved-function".into())),
        source: Some("perl-lsp".into()),
        message: "...".into(),
        data: Some(serde_json::json!({
            "modules": ["List::Util", "List::MoreUtils"],
            "function": "first",
        })),
        ..Default::default()
    };

    let actions = code_actions(&[diag], &analysis, &uri);
    assert_eq!(actions.len(), 2);
    // Neither should be preferred (ambiguous)
    for action in &actions {
        if let CodeActionOrCommand::CodeAction(a) = action {
            assert_eq!(a.is_preferred, Some(false));
        }
    }
}

// ---- String-dispatch signature help (mojo-events plugin path) ----

/// `$self->emit('ready', CURSOR)` should surface the `->on('ready', sub
/// ($self, $msg) {})` handler's params as sig help. The dispatch string
/// is arg 0; handler params are offset by 1 so active_parameter lines
/// up with the user's cursor.
#[test]
fn sig_help_returns_handler_params_for_emit() {
    let src = r#"package My::Emitter;
use parent 'Mojo::EventEmitter';

sub register {
    my $self = shift;
    $self->on('ready', sub {
        my ($self_in, $msg, $when) = @_;
        warn $msg;
    });
}

sub fire {
    my $self = shift;
    $self->emit('ready', 'hi', )
}
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let analysis = crate::builder::build(&tree, src.as_bytes());
    let idx = ModuleIndex::new_for_test();

    // Cursor just after `'hi', ` on the emit line — active_param=2 means
    // we're in the 2nd handler slot (after event name + first handler arg).
    let pos = {
        let (line_idx, line) = src
            .lines()
            .enumerate()
            .find(|(_, l)| l.contains("->emit('ready'"))
            .unwrap();
        let col = line.find(", )").unwrap() + 2;
        Position {
            line: line_idx as u32,
            character: col as u32,
        }
    };

    let sig = signature_help(&analysis, &tree, src, pos, &idx)
        .expect("sig help should surface handler sig");
    assert_eq!(sig.signatures.len(), 1, "one registered handler");

    let s = &sig.signatures[0];
    // Label mirrors the actual call the user is writing — `emit('ready',
    // $msg, $when)` — not a fake method-call shape.
    assert!(
        s.label.starts_with("emit('ready'"),
        "label should show the call shape starting with emit('ready'): {}",
        s.label
    );
    // Documentation carries the class + line provenance.
    if let Some(Documentation::String(ref d)) = s.documentation {
        assert!(
            d.contains("My::Emitter"),
            "doc should name the owning class: {}",
            d
        );
    } else {
        panic!("expected Documentation::String, got {:?}", s.documentation);
    }
    // $self_in stripped as implicit → remaining params $msg, $when.
    let params = s.parameters.as_ref().expect("has params");
    assert_eq!(params.len(), 2, "drops implicit $self_in");
    assert!(matches!(&params[0].label, ParameterLabel::Simple(s) if s == "$msg"));
    assert!(matches!(&params[1].label, ParameterLabel::Simple(s) if s == "$when"));
}

/// Multiple `->on('ready', sub {...})` wire-ups stack — each becomes a
/// separate SignatureInformation entry, so users see every handler
/// shape they might be dispatching to.
#[test]
fn sig_help_stacks_multiple_handler_defs() {
    let src = r#"package My::Emitter;
use parent 'Mojo::EventEmitter';

sub new {
    my $self = bless {}, shift;
    $self->on('tick', sub {
        my ($self_in, $count) = @_;
    });
    $self->on('tick', sub {
        my ($self_in, $count, $unit) = @_;
    });
    $self;
}

sub go {
    my $self = shift;
    $self->emit('tick', )
}
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let analysis = crate::builder::build(&tree, src.as_bytes());
    let idx = ModuleIndex::new_for_test();

    let pos = {
        let line_idx = src
            .lines()
            .enumerate()
            .find(|(_, l)| l.contains("->emit('tick'"))
            .map(|(i, _)| i)
            .unwrap();
        let line = src.lines().nth(line_idx).unwrap();
        let col = line.find(", )").unwrap() + 2;
        Position {
            line: line_idx as u32,
            character: col as u32,
        }
    };

    let sig = signature_help(&analysis, &tree, src, pos, &idx).expect("sig help should fire");
    assert_eq!(
        sig.signatures.len(),
        2,
        "stacked handlers: one signature per ->on call"
    );

    let labels: Vec<&str> = sig.signatures.iter().map(|s| s.label.as_str()).collect();
    assert!(
        labels.iter().all(|l| l.starts_with("emit('tick'")),
        "every signature uses emit('tick', ...) call shape: {:?}",
        labels
    );
}

/// Baseline before the user started typing: cursor in the empty
/// second-arg slot `$self->emit('connect', CURSOR );`. Sig help
/// should offer handler params from the moment the comma is typed.
#[test]
fn sig_help_fires_in_empty_second_slot() {
    let src = r#"package My::Emitter;
use parent 'Mojo::EventEmitter';

sub wire {
    my $self = shift;
    $self->on('connect', sub {
        my ($self_in, $sock, $remote_ip) = @_;
    });
}

sub fire {
    my $self = shift;
    $self->emit('connect', );
}
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let analysis = crate::builder::build(&tree, src.as_bytes());
    let idx = ModuleIndex::new_for_test();

    let (line_idx, line) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("->emit('connect'"))
        .unwrap();
    let col = line.find(", )").unwrap() + 2; // just after `, `
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    let sig = signature_help(&analysis, &tree, src, pos, &idx)
        .expect("empty arg slot after comma should offer handler sig");
    let s = &sig.signatures[0];
    assert!(
        s.label.starts_with("emit('connect'"),
        "baseline: label identifies emit handler call: {}",
        s.label
    );
}

/// Flow gap fix: `my $dynamic = 'connect'; $self->emit($dynamic, ...)`
/// — hover already worked (DispatchCall.target_name is const-folded
/// by the plugin) but sig help used to miss because it parsed the
/// first arg from text ($dynamic → not a literal). Now sig help
/// routes through the DispatchCall ref too, so const folding
/// composes uniformly and this class of gap can't reopen.
#[test]
fn sig_help_follows_const_folding_like_hover_does() {
    let src = r#"package My::Emitter;
use parent 'Mojo::EventEmitter';

sub wire {
    my $self = shift;
    $self->on('connect', sub {
        my ($self_in, $sock, $remote_ip) = @_;
    });
}

sub fire {
    my $self = shift;
    my $dynamic = 'connect';
    $self->emit($dynamic, 'hi', );
}
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let analysis = crate::builder::build(&tree, src.as_bytes());
    let idx = ModuleIndex::new_for_test();

    let (line_idx, line) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("->emit($dynamic"))
        .unwrap();
    let col = line.find(", )").unwrap() + 2;
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    let sig = signature_help(&analysis, &tree, src, pos, &idx)
        .expect("sig help must follow const folding like hover does");
    let s = &sig.signatures[0];
    assert!(
        s.label.starts_with("emit('connect'"),
        "const-folded: $dynamic → 'connect' → emit('connect', ...) label; got: {}",
        s.label
    );
    let params = s.parameters.as_ref().unwrap();
    assert_eq!(
        params.len(),
        2,
        "$sock, $remote_ip (implicit $self_in dropped)"
    );
}

/// Regression: cursor inside the SECOND literal-string arg of a
/// dispatch call — matches the user's screenshot where
/// `$self->emit('connect', 'soc' )` had the cursor mid-'soc'. The
/// string-dispatch sig should still fire (first arg is 'connect',
/// handler is registered, active_param is 1).
#[test]
fn sig_help_fires_from_inside_second_string_arg() {
    let src = r#"package My::Emitter;
use parent 'Mojo::EventEmitter';

sub wire {
    my $self = shift;
    $self->on('connect', sub {
        my ($self_in, $sock, $remote_ip) = @_;
    });
}

sub fire {
    my $self = shift;
    $self->emit('connect', 'soc' );
}
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let analysis = crate::builder::build(&tree, src.as_bytes());
    let idx = ModuleIndex::new_for_test();

    let (line_idx, line) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("->emit('connect', 'soc'"))
        .unwrap();
    // Cursor at column index pointing into the middle of `'soc'`.
    let col = line.find("'soc'").unwrap() + 2; // between 's' and 'o'
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    let sig = signature_help(&analysis, &tree, src, pos, &idx)
        .expect("cursor in 2nd string arg should still surface handler sig");
    let s = &sig.signatures[0];
    assert!(
        s.label.starts_with("emit('connect'"),
        "label should still be the emit(handler) form: {}",
        s.label
    );
    let params = s.parameters.as_ref().unwrap();
    assert_eq!(params.len(), 2, "handler params ($sock, $remote_ip)");
}

/// Completion at the first arg of a dispatch call should list every
/// registered Handler on the receiver's class — top priority, quoted
/// insert, handler params in detail. Same abstraction as hover +
/// sig help, so new plugins don't have to wire this up separately.
#[test]
fn completion_offers_handler_names_at_dispatch_arg0() {
    let src = r#"package My::Emitter;
use parent 'Mojo::EventEmitter';

sub wire {
    my $self = shift;
    $self->on('connect', sub { my ($s, $sock, $ip) = @_; });
    $self->on('disconnect', sub { my ($s) = @_; });
}

sub fire {
    my $self = shift;
    $self->emit();
}
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let analysis = crate::builder::build(&tree, src.as_bytes());
    let idx = ModuleIndex::new_for_test();

    // Cursor inside the empty `()` of `$self->emit()`.
    let (line_idx, line) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("->emit()"))
        .unwrap();
    let col = line.find("emit(").unwrap() + "emit(".len();
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    let items = completion_items(&analysis, &tree, src, pos, &idx, None);

    // Every registered handler shows up as a top-priority suggestion.
    let connect = items
        .iter()
        .find(|i| i.label == "connect")
        .expect("connect handler should be offered at emit arg-0");
    let disconnect = items
        .iter()
        .find(|i| i.label == "disconnect")
        .expect("disconnect handler should be offered at emit arg-0");

    assert_eq!(
        connect.kind,
        Some(CompletionItemKind::EVENT),
        "handler completion kind is EVENT (matches outline)"
    );
    assert_eq!(
        connect.insert_text.as_deref(),
        Some("'connect'"),
        "insert should include quotes so the user doesn't type them"
    );
    assert!(
        connect
            .detail
            .as_deref()
            .unwrap_or("")
            .contains("My::Emitter"),
        "detail should name the owning class: {:?}",
        connect.detail
    );
    assert!(
        connect.detail.as_deref().unwrap_or("").contains("$sock"),
        "detail should expose handler params: {:?}",
        connect.detail
    );

    // Sort text puts handlers ahead of other general completions.
    // Space prefix sorts lex-before any digit-prefixed sort_text,
    // guaranteeing handlers as a top block even when surrounding
    // items (local subs at PRIORITY_LOCAL=0) tie on numeric priority.
    assert!(
        connect
            .sort_text
            .as_deref()
            .unwrap_or("zzz")
            .starts_with(' '),
        "handler sort should lead with space to outrank digit-prefixed sort_text: {:?}",
        connect.sort_text
    );
    assert!(disconnect
        .sort_text
        .as_deref()
        .unwrap_or("zzz")
        .starts_with(' '));
}

/// Bug B: dispatch-target items set their `insert_text` to
/// `'name'` (quoted) but left `filter_text` unset — some LSP
/// clients fall back to `insert_text` for client-side prefix
/// matching, so typing `c` after `(` fails to match `'connect'`
/// (prefix starts with `'`, not `c`). `filter_text` now pins
/// client-side matching to the bare label regardless of insert
/// shape; typing a character keeps the handler visible.
#[test]
fn completion_dispatch_filter_text_matches_bare_name() {
    let src = r#"
package My::Emitter;
use parent 'Mojo::EventEmitter';
sub wire { my $self = shift; $self->on('connect', sub {}); }
sub fire { my $self = shift; $self->emit(); }
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let analysis = crate::builder::build(&tree, src.as_bytes());
    let idx = ModuleIndex::new_for_test();

    let (line_idx, line) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("->emit()"))
        .unwrap();
    let col = line.find("emit(").unwrap() + "emit(".len();
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    let items = completion_items(&analysis, &tree, src, pos, &idx, None);
    let connect = items
        .iter()
        .find(|i| i.label == "connect")
        .expect("connect handler offered");

    // filter_text is the bare name — the client can prefix-match on
    // `c`/`co`/`con`/... even though insert_text is `'connect'`.
    assert_eq!(
        connect.filter_text.as_deref(),
        Some("connect"),
        "filter_text must be the bare label, not the quoted insert_text"
    );
    assert_eq!(
        connect.insert_text.as_deref(),
        Some("'connect'"),
        "insert_text still quotes for the bare-parens case"
    );
}

/// Bug: dispatch-target completion always wrapped the label in
/// quotes — so if the cursor was already inside `''`, accepting
/// `connect` inserted `''connect''`. Now detects the string
/// context via the tree and emits bare text.
#[test]
fn completion_dispatch_inside_quotes_does_not_double_quote() {
    let src = r#"
package My::Emitter;
use parent 'Mojo::EventEmitter';

sub wire {
    my $self = shift;
    $self->on('connect', sub { my ($s) = @_; });
}

sub fire {
    my $self = shift;
    $self->emit('');
}
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let analysis = crate::builder::build(&tree, src.as_bytes());
    let idx = ModuleIndex::new_for_test();

    // Cursor BETWEEN the two quotes in `->emit('')`.
    let (line_idx, line) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("->emit('')"))
        .unwrap();
    let col = line.find("('").unwrap() + 2;
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    let items = completion_items(&analysis, &tree, src, pos, &idx, None);
    let connect = items
        .iter()
        .find(|i| i.label == "connect")
        .expect("connect handler offered inside '|'");
    // Cursor inside a string arg → item ships a textEdit pinned
    // to the string-content span so the client's word-at-cursor
    // heuristic can't drop it over non-identifier chars. The
    // newText is the BARE handler name (no wrapping quotes) and
    // insert_text is cleared — textEdit takes precedence in the
    // LSP spec, and leaving insert_text alongside confuses some
    // clients. The original "don't double-quote" invariant now
    // reads off textEdit.newText instead of insert_text.
    assert_eq!(
        connect.insert_text, None,
        "cursor is inside quotes; insert_text is cleared in favor of textEdit"
    );
    use tower_lsp::lsp_types::CompletionTextEdit;
    let Some(CompletionTextEdit::Edit(ref te)) = connect.text_edit else {
        panic!(
            "expected a TextEdit for mid-string dispatch item; got {:?}",
            connect.text_edit
        );
    };
    assert_eq!(
        te.new_text, "connect",
        "textEdit.newText is the bare label — not `'connect'` (would double-quote inside '|')"
    );
}

/// Red pin (user-reported): dispatch-target completions for labels
/// containing non-identifier chars (`/`, `#`) died client-side
/// because nvim's word-at-cursor heuristic uses `iskeyword`, which
/// excludes `/` and `#` by default. The server returned the item
/// with `filter_text = "/users/profile"` but the client extracted
/// `users` or `profile` (a word run starting/ending at the non-
/// keyword boundary) and dropped the item since neither is a
/// prefix of `/users/profile`. Same shape for `Users#list` — the
/// cursor parked past the `#` gave word `list`, which fails
/// `"Users#list".starts_with("list")`.
///
/// Fix: emit `textEdit` with `range = string_content_span_at(...)`
/// so the client filters by the whole in-range text against the
/// full label — regardless of keyword class. This pin locks that
/// textEdit emission for BOTH flavors; regressing either re-
/// surfaces the bug for any route with a URL path or `Ctrl#act`
/// handler name.
#[test]
fn completion_dispatch_textedit_handles_non_keyword_labels() {
    use crate::module_index::ModuleIndex;
    use tower_lsp::lsp_types::CompletionTextEdit;

    // Route declarations: one URL path (leading `/`), one
    // `Ctrl#act` (embedded `#`). Both must survive mid-string
    // completion inside `url_for('...')`.
    let app_src = r#"package MyApp;
use Mojolicious::Lite;

my $r = app->routes;
$r->get('/users')->to('Users#list');

get '/users/profile' => sub { my ($c) = @_; };
"#;
    let app_fa = std::sync::Arc::new(crate::builder::build(
        &{
            let mut p = tree_sitter::Parser::new();
            p.set_language(&ts_parser_perl::LANGUAGE.into()).unwrap();
            p.parse(app_src, None).unwrap()
        },
        app_src.as_bytes(),
    ));

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

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

sub list {
    my ($c) = @_;
    $c->url_for('/users/profile');
}
"#;
    let ctrl_fa = crate::builder::build(
        &{
            let mut p = tree_sitter::Parser::new();
            p.set_language(&ts_parser_perl::LANGUAGE.into()).unwrap();
            p.parse(ctrl_src, None).unwrap()
        },
        ctrl_src.as_bytes(),
    );

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

    // Cursor deep inside the path, past the first `/` —
    // `'/users/pr|ofile'`. Before the fix, nvim would extract
    // `users` or `profile` from the chars around the cursor;
    // neither is a prefix of the `/users/profile` label.
    let line_idx = 5u32; // `    $c->url_for('/users/profile');`
    let line = ctrl_src.lines().nth(line_idx as usize).unwrap();
    let quote_start = line.find("'/users/profile").unwrap();
    let pr_col = (quote_start + 1 + "/users/pr".len()) as u32;
    let pos = Position {
        line: line_idx,
        character: pr_col,
    };

    let items = completion_items(&ctrl_fa, &tree, ctrl_src, pos, &idx, None);

    let path_item = items
        .iter()
        .find(|i| i.label == "/users/profile")
        .expect("/users/profile must be offered (dispatch completion inside string)");

    // insert_text is cleared; textEdit carries the range spanning
    // the entire string content, so the client uses `/users/pr...`
    // as the filter input and matches against the full label.
    assert_eq!(
        path_item.insert_text, None,
        "insert_text cleared — textEdit takes precedence for non-keyword-char labels"
    );
    let Some(CompletionTextEdit::Edit(ref te)) = path_item.text_edit else {
        panic!(
            "expected textEdit for `/users/profile`; got {:?}",
            path_item.text_edit
        );
    };
    assert_eq!(
        te.new_text, "/users/profile",
        "textEdit.newText is the bare label, no surrounding quotes"
    );
    // Range must span the string CONTENT (between the quotes).
    // Start column = col of first `/` (just after opening quote),
    // end column = col of closing quote.
    assert_eq!(te.range.start.line, line_idx);
    assert_eq!(te.range.end.line, line_idx);
    assert_eq!(
        te.range.start.character,
        (quote_start + 1) as u32,
        "range start hugs the char just after the opening quote",
    );
    assert_eq!(
        te.range.end.character,
        (quote_start + 1 + "/users/profile".len()) as u32,
        "range end hugs the closing quote — replacement stays INSIDE the existing quotes",
    );

    // Same check for the `Ctrl#act` flavor — cursor past the `#`.
    let ctrl_src_hash = r#"package Users;
use parent 'Mojolicious::Controller';

sub list {
    my ($c) = @_;
    $c->url_for('Users#list');
}
"#;
    let ctrl_fa_hash = crate::builder::build(
        &parser.parse(ctrl_src_hash, None).unwrap(),
        ctrl_src_hash.as_bytes(),
    );
    let tree_hash = parser.parse(ctrl_src_hash, None).unwrap();
    let line = ctrl_src_hash.lines().nth(5).unwrap();
    let quote_start = line.find("'Users#list").unwrap();
    let past_hash_col = (quote_start + 1 + "Users#li".len()) as u32;
    let pos = Position {
        line: 5,
        character: past_hash_col,
    };
    let items = completion_items(&ctrl_fa_hash, &tree_hash, ctrl_src_hash, pos, &idx, None);
    let hash_item = items
        .iter()
        .find(|i| i.label == "Users#list")
        .expect("Users#list must be offered when cursor is past the #");
    assert_eq!(hash_item.insert_text, None);
    let Some(CompletionTextEdit::Edit(ref te)) = hash_item.text_edit else {
        panic!(
            "expected textEdit for `Users#list`; got {:?}",
            hash_item.text_edit
        );
    };
    assert_eq!(te.new_text, "Users#list");
}

/// Red pin (user QA): accepting a dispatch completion APPENDED
/// the label instead of replacing the typed text — `url_for('/fall|')`
/// accepting `/fallback` yielded `url_for('/fall/fallback')`.
/// Root cause: `descendant_for_point_range` returns the enclosing
/// `string_literal` (not `string_content`) when the cursor sits
/// at the content's end boundary, because content ranges are
/// half-open. `string_content_span_at` then fell into the
/// zero-width "empty literal" branch and returned `(cursor,
/// cursor)` — textEdit replacing nothing = append. Fix descends
/// into the literal to find a `string_content` child before
/// giving up.
///
/// This pin covers three cursor positions, each of which previously
/// hit the wrapper-instead-of-content path:
///   1. INSIDE the content (baseline — already worked).
///   2. AT the content's end boundary (just before closing quote).
///   3. ON the closing quote itself.
/// All three must return a textEdit range covering the full
/// `string_content` span, so accepting the completion replaces
/// the typed prefix with the label cleanly.
#[test]
fn completion_dispatch_textedit_range_at_content_boundary() {
    use crate::module_index::ModuleIndex;
    use tower_lsp::lsp_types::CompletionTextEdit;

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

any '/fallback' => sub { my ($c) = @_; };
"#;
    let app_fa = std::sync::Arc::new(crate::builder::build(
        &{
            let mut p = tree_sitter::Parser::new();
            p.set_language(&ts_parser_perl::LANGUAGE.into()).unwrap();
            p.parse(app_src, None).unwrap()
        },
        app_src.as_bytes(),
    ));

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

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

sub list {
    my ($c) = @_;
    $c->url_for('/fall');
}
"#;
    let ctrl_fa = crate::builder::build(
        &{
            let mut p = tree_sitter::Parser::new();
            p.set_language(&ts_parser_perl::LANGUAGE.into()).unwrap();
            p.parse(ctrl_src, None).unwrap()
        },
        ctrl_src.as_bytes(),
    );
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(ctrl_src, None).unwrap();

    // `    $c->url_for('/fall');`
    let line_idx = 5u32;
    let line = ctrl_src.lines().nth(line_idx as usize).unwrap();
    let quote_start = line.find("'/fall'").unwrap();
    let content_start = (quote_start + 1) as u32; // `/`
    let content_end = content_start + "/fall".len() as u32; // just after `l`
    let closing_quote_col = content_end; // the `'`

    // Three cursor positions to exercise: inside the content,
    // at the content's end boundary, and on the closing quote.
    let cursor_variants = [
        ("inside content", content_start + 3), // between `a` and `l`
        ("end of content", content_end),       // just after `l`, before `'`
        ("on closing quote", closing_quote_col),
    ];

    for (label, col) in cursor_variants {
        let items = completion_items(
            &ctrl_fa,
            &tree,
            ctrl_src,
            Position {
                line: line_idx,
                character: col,
            },
            &idx,
            None,
        );
        let item = items
            .iter()
            .find(|i| i.label == "/fallback")
            .unwrap_or_else(|| {
                panic!(
                    "{}: /fallback must be offered at col {}; \
                                           got labels: {:?}",
                    label,
                    col,
                    items.iter().map(|i| &i.label).collect::<Vec<_>>()
                )
            });

        let Some(CompletionTextEdit::Edit(ref te)) = item.text_edit else {
            panic!("{}: expected textEdit; got {:?}", label, item.text_edit);
        };
        // Range must cover the FULL typed content, not zero-width.
        // That way accepting `/fallback` REPLACES `/fall`, not
        // appends to it — the pre-fix failure mode that produced
        // `'/fall/fallback'`.
        assert_eq!(
            te.range.start.character, content_start,
            "{}: range start must hug the first content char; got range {:?}",
            label, te.range,
        );
        assert_eq!(
            te.range.end.character, content_end,
            "{}: range end must hug the closing quote (exclusive of it); got range {:?}",
            label, te.range,
        );
        assert_eq!(
            te.new_text, "/fallback",
            "{}: newText is the bare label — no seasonal redundancy",
            label,
        );
    }
}

/// Bug: typing `,` inside a known dispatch call (`->emit('x', |)`)
/// triggered completion which ran the global sub/module firehose —
/// useless here. Now suppresses imported/unimported function
/// completions when we're inside a known dispatcher call; sig
/// help remains the right affordance for guiding arg shape.
#[test]
fn completion_after_comma_in_dispatch_call_suppresses_firehose() {
    let src = r#"
package My::Emitter;
use parent 'Mojo::EventEmitter';

sub wire_one {}
sub wire_two {}
sub completely_unrelated {}

sub wire {
    my $self = shift;
    $self->on('connect', sub { my ($s, $sock) = @_; });
}

sub fire {
    my $self = shift;
    $self->emit('connect', );
}
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let analysis = crate::builder::build(&tree, src.as_bytes());
    let idx = ModuleIndex::new_for_test();

    let (line_idx, line) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("->emit('connect',"))
        .unwrap();
    let col = line.find(", )").unwrap() + 2;
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

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

    assert!(
        !labels.contains(&"completely_unrelated"),
        "unrelated sub must not appear in dispatch arg completion: {:?}",
        labels
    );
    assert!(
        !labels.contains(&"wire_one"),
        "wire_one leak — dispatch arg completion should stay quiet: {:?}",
        labels
    );
}

/// Mid-string completion for route targets. Cursor inside
/// `->to('Users#lis|')` offers methods on Users, prefix-filtered
/// by `lis`. Generic for ANY plugin that emits MethodCallRef at
/// a string span (routes today, Catalyst forwards, etc.).
#[test]
fn completion_mid_string_route_target_scoped_to_invocant() {
    // Same-file Users package so the test is self-contained. Real
    // use would have Users in a separate file via workspace index;
    // the lookup path is the same (complete_methods_for_class
    // walks inheritance + module index).
    let src = r#"
package Users;
sub list {}
sub login {}
sub logout {}
sub delete_user {}

package MyApp;
use Mojolicious::Lite;

my $r = app->routes;
$r->get('/users')->to('Users#lis');
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let analysis = crate::builder::build(&tree, src.as_bytes());
    let idx = ModuleIndex::new_for_test();

    // Cursor just after 'lis' in 'Users#lis' — active editing state.
    let (line_idx, line) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("Users#lis"))
        .unwrap();
    let col = line.find("Users#lis").unwrap() + "Users#lis".len();
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

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

    // Prefix-filtered: only `list` starts with `lis`; `login`,
    // `logout`, `delete_user` don't.
    assert!(
        labels.contains(&"list"),
        "list must be offered for prefix `lis`: {:?}",
        labels
    );
    assert!(
        !labels.contains(&"login"),
        "login does NOT start with `lis` — must be filtered out: {:?}",
        labels
    );
    assert!(
        !labels.contains(&"logout"),
        "logout does NOT start with `lis` — must be filtered out: {:?}",
        labels
    );
    assert!(
        !labels.contains(&"delete_user"),
        "delete_user is unrelated — must not appear: {:?}",
        labels
    );

    // Top-priority sort — the mid-string completion path is the
    // only sensible one at this cursor position.
    let list = items.iter().find(|i| i.label == "list").unwrap();
    assert!(
        list.sort_text
            .as_deref()
            .unwrap_or("zzz")
            .starts_with("000"),
        "mid-string method completion should be top-priority: {:?}",
        list.sort_text
    );
}

/// Mid-string completion for routes before `#` is typed — cursor at
/// `->to('Us|')`. The invocant portion isn't complete yet, so the
/// plugin won't have emitted a MethodCallRef. Graceful fallthrough
/// to general completion (or nothing) is the expected behavior.
#[test]
fn completion_mid_string_before_hash_falls_through() {
    let src = r#"
package MyApp;
use Mojolicious::Lite;

my $r = app->routes;
$r->get('/users')->to('Us');
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let analysis = crate::builder::build(&tree, src.as_bytes());
    let idx = ModuleIndex::new_for_test();

    let (line_idx, line) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("'Us'"))
        .unwrap();
    let col = line.find("'Us'").unwrap() + "'Us".len();
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    // Doesn't assert what IS offered — just that it doesn't panic
    // and doesn't return complete nonsense. This is the honest
    // edge-case: without a `#` yet, no plugin-emitted ref exists.
    let items = completion_items(&analysis, &tree, src, pos, &idx, None);
    let _ = items;
}

/// Completion skips when the method isn't a declared dispatcher, even
/// if handlers exist on the class. (Empty dispatchers == "any" by
/// convention, but mojo-events declares ["emit"] specifically.)
#[test]
fn completion_skips_non_dispatcher_method() {
    let src = r#"package My::Emitter;
use parent 'Mojo::EventEmitter';

sub wire {
    my $self = shift;
    $self->on('connect', sub { my ($s) = @_; });
}

sub other {
    my $self = shift;
    $self->unrelated_method();
}
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let analysis = crate::builder::build(&tree, src.as_bytes());
    let idx = ModuleIndex::new_for_test();

    let (line_idx, line) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("->unrelated_method()"))
        .unwrap();
    let col = line.find("method(").unwrap() + "method(".len();
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    let items = completion_items(&analysis, &tree, src, pos, &idx, None);
    assert!(
        !items.iter().any(|i| i.label == "connect"),
        "non-dispatcher method must not surface handler completions"
    );
}

/// No handler params means no specialized sig help — fall through to
/// the regular method-signature path (or return None if ->emit isn't
/// locally defined, as in this test).
#[test]
fn sig_help_returns_none_when_no_handler_registered() {
    let src = r#"package My::Emitter;
use parent 'Mojo::EventEmitter';

sub fire {
    my $self = shift;
    $self->emit('never_registered', )
}
"#;
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(src, None).unwrap();
    let analysis = crate::builder::build(&tree, src.as_bytes());
    let idx = ModuleIndex::new_for_test();

    let pos = {
        let line_idx = src
            .lines()
            .enumerate()
            .find(|(_, l)| l.contains("never_registered"))
            .map(|(i, _)| i)
            .unwrap();
        let line = src.lines().nth(line_idx).unwrap();
        let col = line.find(", )").unwrap() + 2;
        Position {
            line: line_idx as u32,
            character: col as u32,
        }
    };

    let sig = signature_help(&analysis, &tree, src, pos, &idx);
    assert!(
        sig.is_none(),
        "no handler_params → no string-dispatch sig; also no local ->emit def"
    );
}

// ---- data-printer plugin: full intelligence ----

/// Build a CachedModule under the real package name we want, with
/// arbitrary source. `fake_cached` always synthesizes a `package
/// Fake;` source — useless when the caller needs the cached
/// module to expose subs under a specific name like `Data::Printer`.
fn cached_under(name: &str, source: &str) -> std::sync::Arc<crate::module_index::CachedModule> {
    let analysis = parse_analysis(source);
    std::sync::Arc::new(crate::module_index::CachedModule::new(
        std::path::PathBuf::from(format!("/fake/{}.pm", name.replace("::", "/"))),
        std::sync::Arc::new(analysis),
    ))
}

#[test]
fn data_printer_use_ddp_resolves_p_to_data_printer() {
    // The end-to-end intelligence pin. `use DDP` is a literal alias
    // for `use Data::Printer` (DDP.pm just `push our @ISA, 'Data::Printer'`).
    // Hover/K, gd, and sig-help on `p` must reach Data::Printer's
    // real `sub p` — not DDP. The plugin's synthetic Import
    // (module_name: "Data::Printer", imported_symbols: [p, np]) is
    // what carries this; resolve_imported_function is the seam every
    // intelligence feature routes through.
    let source = "use DDP;\np $foo;\n";
    let analysis = parse_analysis(source);
    let module_index = crate::module_index::ModuleIndex::new_for_test();

    // Stub Data::Printer.pm. The real module has a custom `import`
    // (no @EXPORT), but `sub p` is a normal sub the builder picks
    // up — exactly what users get from cpan.
    module_index.insert_cache(
            "Data::Printer",
            Some(cached_under(
                "Data::Printer",
                "package Data::Printer;\nsub p { my (undef, %props) = @_; }\nsub np { my (undef, %props) = @_; }\n1;\n",
            )),
        );

    let resolved = resolve_imported_function(&analysis, "p", &module_index);
    assert!(
        resolved.is_some(),
        "use DDP must alias to Data::Printer; resolve_imported_function for `p` returned None — \
             imports were: {:?}",
        analysis
            .imports
            .iter()
            .map(|i| (
                i.module_name.clone(),
                i.imported_symbols
                    .iter()
                    .map(|s| s.local_name.clone())
                    .collect::<Vec<_>>(),
            ))
            .collect::<Vec<_>>()
    );
    let (import, _path, remote) = resolved.unwrap();
    assert_eq!(
        import.module_name, "Data::Printer",
        "alias must route to Data::Printer, not DDP"
    );
    assert_eq!(remote, "p", "local `p` maps to remote `p`");

    // np too — both DDP-installed names.
    let np = resolve_imported_function(&analysis, "np", &module_index);
    assert!(
        np.is_some(),
        "use DDP must also resolve `np` to Data::Printer"
    );
    assert_eq!(np.unwrap().0.module_name, "Data::Printer");
}

#[test]
fn data_printer_use_data_printer_resolves_p_to_data_printer() {
    // Same test for the non-alias case. `use Data::Printer;` with no
    // qw list — the plugin's synthetic Import claims `p`/`np` so
    // resolve_imported_function pairs them with the real sub.
    let source = "use Data::Printer;\np $foo;\n";
    let analysis = parse_analysis(source);
    let module_index = crate::module_index::ModuleIndex::new_for_test();
    module_index.insert_cache(
            "Data::Printer",
            Some(cached_under(
                "Data::Printer",
                "package Data::Printer;\nsub p { my (undef, %props) = @_; }\nsub np { my (undef, %props) = @_; }\n1;\n",
            )),
        );

    let resolved = resolve_imported_function(&analysis, "p", &module_index);
    assert!(
        resolved.is_some(),
        "use Data::Printer (no qw list) must still let resolve_imported_function find p"
    );
    assert_eq!(resolved.unwrap().0.module_name, "Data::Printer");
}

#[test]
fn data_printer_use_line_options_completion() {
    // `use DDP { | }` — cursor inside the options hashref. The
    // plugin's on_completion hook recognizes "current_use_module
    // matches DDP/Data::Printer and cursor_inside is a Hash" and
    // returns the documented option keys (caller_info, colored,
    // class_method, output, ...). No core hard-codes the option
    // list — it lives in the plugin.
    let source = "use DDP { };\n";
    let analysis = parse_analysis(source);
    let module_index = crate::module_index::ModuleIndex::new_for_test();

    // Cursor between the braces. Source: "use DDP { };" → col 10
    // is one past the opening brace (which lives at col 9).
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(source, None).unwrap();

    let pos = Position {
        line: 0,
        character: 10,
    };
    let items = completion_items(&analysis, &tree, source, pos, &module_index, None);

    let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
    // Sample of keys from Data::Printer's actual options. If the
    // plugin doesn't ship these specific names, swap to whichever
    // ones the plugin advertises — the contract is "DDP options
    // surface here", not "this exact list".
    for key in &["caller_info", "colored", "class_method", "output"] {
        assert!(
            labels.iter().any(|l| l == key),
            "use DDP {{ }} option completion must offer `{}`; got: {:?}",
            key,
            labels,
        );
    }
}

// ---- witness-bag chain typing: pin-the-fix on the real demo ----

/// Pin against the actual demo file. Loads
/// `test_files/plugin_mojo_demo.pl` + stubs of the Mojolicious
/// hierarchy registered into the module index, then asserts:
/// (a) `$r` at line 71 resolves to a known class.
/// (b) `->to` on line 71 is a MethodCall ref.
/// (c) `->to`'s invocant resolves to a class via
///     `FileAnalysis::method_call_invocant_class` (the bag-routed
///     resolver every reader — hover, gd, gr, rename — funnels
///     through).
///
/// Two possible failure modes the test distinguishes:
///   - `$r` is typed but `->to`'s invocant fails → crossfile
///     chain hop is the gap (find_method_return_type's CrossFile
///     branch).
///   - `$r` isn't typed at all → earlier hop broken first.
#[test]
fn test_demo_file_chain_to_resolves_on_line_71() {
    use std::fs;
    use std::path::PathBuf;

    // Project root: the worktree (= CARGO_MANIFEST_DIR).
    let root: PathBuf = env!("CARGO_MANIFEST_DIR").into();
    let demo = root.join("test_files/plugin_mojo_demo.pl");
    let demo_source = fs::read_to_string(&demo).expect("demo file present");

    // Index the project's test_files/ as the workspace.
    let idx = ModuleIndex::new_for_test();
    idx.set_workspace_root(Some(root.to_str().unwrap()));
    let files = crate::file_store::FileStore::new();
    let _indexed = crate::module_resolver::index_workspace_with_index(
        &root.join("test_files"),
        &files,
        Some(&idx),
    );

    // Use the ACTUAL Mojolicious library from @INC — the same
    // code nvim analyzes. If Mojo isn't installed, skip cleanly
    // so CI on bare systems doesn't break.
    let inc_paths = crate::module_resolver::discover_inc_paths();
    let insert_real = |name: &str| -> bool {
        let mut p = crate::module_resolver::create_parser();
        match crate::module_resolver::resolve_and_parse(&inc_paths, name, &mut p) {
            Some(cached) => {
                idx.insert_cache(name, Some(cached));
                true
            }
            None => false,
        }
    };
    let have_mojo = insert_real("Mojolicious")
        && insert_real("Mojolicious::Routes")
        && insert_real("Mojolicious::Routes::Route")
        && insert_real("Mojolicious::Lite");
    if !have_mojo {
        eprintln!("SKIP: Mojolicious not installed in @INC");
        return;
    }
    let _ = PathBuf::new(); // keep the import used in both branches

    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(&demo_source, None).unwrap();
    let mut analysis = crate::builder::build(&tree, demo_source.as_bytes());

    // Cross-file enrichment — same step the backend runs on open.
    // Resolves MethodCallBindings against the module_index so
    // `my $r = $app->routes;` becomes a TypeConstraint. Without
    // this, the backend's `enrich_analysis(uri)` hasn't fired
    // yet and the whole chain is un-typed.
    analysis.enrich_imported_types_with_keys(Some(&idx));

    // Find line 71 ($r->get('/users')->to('Users#list');).
    let (line_idx, chain_line) = demo_source
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("$r->get('/users')") && l.contains("->to('Users#list')"))
        .expect("chain line present in demo");

    // Position on `to` — the 't' character.
    let to_col = chain_line.find("->to(").unwrap() + 2;
    let r_col = chain_line.find("$r").unwrap();
    let get_col = chain_line.find("->get(").unwrap() + 2;

    let pt = |col: usize| tree_sitter::Point {
        row: line_idx,
        column: col,
    };

    // Diagnostics — what does the analysis actually see?
    let r_ty_bag = analysis.inferred_type_via_bag("$r", pt(r_col));
    let r_ty_legacy = analysis.inferred_type("$r", pt(r_col)).cloned();
    let mcb_for_r: Vec<_> = analysis
        .method_call_bindings
        .iter()
        .filter(|b| b.variable == "$r")
        .collect();
    let cb_for_r: Vec<_> = analysis
        .call_bindings
        .iter()
        .filter(|b| b.variable == "$r")
        .collect();
    // Is `app` even known as a symbol/import?
    let app_known = analysis.symbols.iter().any(|s| s.name == "app");
    // Is Mojolicious in the module index?
    let mojo_cached = idx.get_cached("Mojolicious").is_some();
    let routes_cached = idx.get_cached("Mojolicious::Routes").is_some();
    let route_cached = idx.get_cached("Mojolicious::Routes::Route").is_some();
    eprintln!(
        "DIAG: $r bag={:?}  legacy={:?}  mcbs={:?}  cbs={:?}  app_sym={}  \
             mojo_cached={}  routes_cached={}  route_cached={}",
        r_ty_bag,
        r_ty_legacy,
        mcb_for_r
            .iter()
            .map(|b| format!("{}.{}", b.invocant_var, b.method_name))
            .collect::<Vec<_>>(),
        cb_for_r.iter().map(|b| &b.func_name).collect::<Vec<_>>(),
        app_known,
        mojo_cached,
        routes_cached,
        route_cached,
    );

    // (a) `$r` is typed. This uses the EXACT path cursor_context
    // uses to type an invocant — inferred_type_via_bag.
    let r_ty = r_ty_bag;
    let r_class = r_ty.as_ref().and_then(|t| t.class_name());
    assert!(
        r_class.is_some(),
        "$r should be typed (any class) at {}:{}; got {:?}",
        line_idx + 1,
        r_col,
        r_ty,
    );

    // (b) At `->get`'s 'g', there's a MethodCall ref. Its
    // invocant is `$r`. Resolve it cross-file.
    let get_ref = analysis.ref_at(pt(get_col)).expect("ref at ->get");
    assert_eq!(get_ref.target_name, "get");
    if matches!(get_ref.kind, crate::file_analysis::RefKind::MethodCall { .. }) {
        let _ = (&tree, demo_source.as_bytes(), &idx, get_col);
        let klass = analysis.method_call_invocant_class(get_ref, Some(&idx));
        assert!(
            klass.is_some(),
            "`->get`'s invocant (= $r) should resolve to SOME class; got {:?}",
            klass,
        );
    }

    // (c) The `->to` hop. Real Mojolicious::Routes::Route::get
    // is `shift->_generate_route(GET => @_)` — our implicit-
    // return witnessing records that get's return chains
    // through _generate_route. _generate_route's own return is
    // `return defined $name ? $route->name($name) : $route;` —
    // a complex conditional whose arms depend on $route's
    // chain-built type. That depth of cross-file chain
    // resolution is a separate follow-up; for now we assert
    // the MethodCall ref exists and carries the right target,
    // but leave the class-resolution assertion as a diagnostic
    // rather than hard-fail.
    let to_ref = analysis.ref_at(pt(to_col)).expect("ref at ->to");
    assert_eq!(to_ref.target_name, "to");
    assert!(
        matches!(
            to_ref.kind,
            crate::file_analysis::RefKind::MethodCall { .. }
        ),
        "ref at ->to is a MethodCall"
    );
    if matches!(to_ref.kind, crate::file_analysis::RefKind::MethodCall { .. }) {
        let _ = (&tree, demo_source.as_bytes(), &idx, to_col);
        let klass = analysis.method_call_invocant_class(to_ref, Some(&idx));
        eprintln!(
            "DIAG: ->to invocant class (real Mojo): {:?} \
                 (None expected until deep chain through \
                 _generate_route/requires/to is resolved)",
            klass,
        );
    }
}

#[test]
fn data_printer_use_line_options_completion_for_data_printer_module() {
    // Same flow, non-alias name. The plugin can't be DDP-specific.
    let source = "use Data::Printer { };\n";
    let analysis = parse_analysis(source);
    let module_index = crate::module_index::ModuleIndex::new_for_test();

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

    // "use Data::Printer { };" — col 20 sits between the braces.
    let pos = Position {
        line: 0,
        character: 20,
    };
    let items = completion_items(&analysis, &tree, source, pos, &module_index, None);

    let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
    assert!(
        labels.iter().any(|l| *l == "caller_info"),
        "use Data::Printer {{ }} must surface options too; got: {:?}",
        labels,
    );
}
// ---- witness-driven chain completion (spike) ----

/// Decomposition: parse real Mojolicious/Routes/Route.pm
/// in-place (not via module index) and probe each hop of the
/// `$self->_route()->requires()->to()` chain separately. Plus
/// probe `$self->_generate_route(...)`. Reports what each
/// specific hop resolves to — so we know exactly which step
/// in the chain is actually dying.
#[test]
fn test_route_pm_chain_decomposition() {
    use std::fs;
    use std::path::PathBuf;
    let inc = crate::module_resolver::discover_inc_paths();
    let route_path = inc
        .iter()
        .map(|p| p.join("Mojolicious/Routes/Route.pm"))
        .find(|p| p.exists());
    let route_path: PathBuf = match route_path {
        Some(p) => p,
        None => {
            eprintln!("SKIP: Mojo not installed");
            return;
        }
    };
    let src = fs::read_to_string(&route_path).unwrap();

    // Parse Route.pm itself — `$self` inside = Route.
    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(&src, None).unwrap();
    let analysis = crate::builder::build(&tree, src.as_bytes());

    // Probe: find the `_generate_route` sub body and report
    // what we see on each hop.
    let inspect_sym = |name: &str| {
        for sym in &analysis.symbols {
            if sym.name != name {
                continue;
            }
            if !matches!(
                sym.kind,
                crate::file_analysis::SymKind::Sub | crate::file_analysis::SymKind::Method
            ) {
                continue;
            }
            if matches!(&sym.detail, crate::file_analysis::SymbolDetail::Sub { .. }) {
                let return_type = analysis.symbol_return_type_via_bag(sym.id, None);
                eprintln!("  sym[{:24}] return_type={:?}", name, return_type);
                return;
            }
        }
        eprintln!("  sym[{:24}] NOT FOUND", name);
    };
    eprintln!("======== symbol return types in Route.pm ========");
    for name in [
        "get",
        "post",
        "any",
        "to",
        "name",
        "requires",
        "_generate_route",
        "_route",
        "add_child",
        "pattern",
        "is_reserved",
        "root",
    ] {
        inspect_sym(name);
    }

    // Find `_generate_route`'s body block. Its last statement
    // is `return defined $name ? $route->name($name) : $route;`.
    // Probe each subexpression type via resolve_expression_type.
    fn find_sub_body<'t>(
        n: tree_sitter::Node<'t>,
        src: &[u8],
        name: &str,
    ) -> Option<tree_sitter::Node<'t>> {
        if n.kind() == "subroutine_declaration_statement" {
            if let Some(nm) = n.child_by_field_name("name") {
                if nm.utf8_text(src).ok() == Some(name) {
                    return n.child_by_field_name("body");
                }
            }
        }
        for i in 0..n.named_child_count() {
            if let Some(c) = n.named_child(i) {
                if let Some(r) = find_sub_body(c, src, name) {
                    return Some(r);
                }
            }
        }
        None
    }
    let body = find_sub_body(tree.root_node(), src.as_bytes(), "_generate_route")
        .expect("_generate_route body");

    // Inside _generate_route, find:
    //   (a) the `my $route = CHAIN` assignment
    //   (b) the final `return TERNARY` expression
    fn find_var_decl_for<'t>(
        n: tree_sitter::Node<'t>,
        src: &[u8],
        var: &str,
    ) -> Option<tree_sitter::Node<'t>> {
        if n.kind() == "assignment_expression" {
            if let Some(left) = n.child_by_field_name("left") {
                if left.utf8_text(src).map(|s| s.trim()).ok() == Some(&format!("my {}", var)) {
                    return n.child_by_field_name("right");
                }
            }
        }
        for i in 0..n.named_child_count() {
            if let Some(c) = n.named_child(i) {
                if let Some(r) = find_var_decl_for(c, src, var) {
                    return Some(r);
                }
            }
        }
        None
    }
    let route_rhs = find_var_decl_for(body, src.as_bytes(), "$route").expect("my $route = ... RHS");

    eprintln!();
    eprintln!("======== `my $route = RHS` decomposition ========");
    eprintln!(
        "RHS shape: {}  kind={}",
        route_rhs.utf8_text(src.as_bytes()).unwrap_or(""),
        route_rhs.kind()
    );

    // Probe chain hops from innermost outward. Each node in a
    // chain a->b->c has: outer is c's method_call_expression,
    // its invocant is the a->b method_call_expression, whose
    // invocant is `$self`.
    fn report_node_type(
        label: &str,
        n: tree_sitter::Node,
        analysis: &crate::file_analysis::FileAnalysis,
        src: &[u8],
    ) {
        let text = n.utf8_text(src).unwrap_or("").trim();
        let ty = analysis.resolve_expression_type(n, src, None);
        eprintln!(
            "  [{label:>12}] `{text:.60}`\n                kind={} → ty={:?}",
            n.kind(),
            ty
        );
    }

    // Walk the chain inside-out and report each level's type.
    let mut cur = Some(route_rhs);
    let mut depth = 0;
    while let Some(n) = cur {
        let label = match depth {
            0 => "outer",
            1 => "mid1",
            2 => "mid2",
            3 => "mid3",
            _ => "inner",
        };
        report_node_type(label, n, &analysis, src.as_bytes());
        if n.kind() == "method_call_expression" {
            cur = n.child_by_field_name("invocant");
            depth += 1;
        } else {
            break;
        }
    }

    eprintln!();
    eprintln!("======== return TERNARY probe ========");
    // Find the return_expression in body.
    fn find_return<'t>(n: tree_sitter::Node<'t>) -> Option<tree_sitter::Node<'t>> {
        if n.kind() == "return_expression" {
            return Some(n);
        }
        for i in 0..n.named_child_count() {
            if let Some(c) = n.named_child(i) {
                if let Some(r) = find_return(c) {
                    return Some(r);
                }
            }
        }
        None
    }
    let ret = find_return(body).expect("return in _generate_route");
    let ternary = ret.named_child(0).expect("return child");
    eprintln!(
        "  return child kind = {}  text = `{}`",
        ternary.kind(),
        ternary.utf8_text(src.as_bytes()).unwrap_or("").trim()
    );
    if ternary.kind() == "conditional_expression" {
        let consequent = ternary.child_by_field_name("consequent");
        let alternative = ternary.child_by_field_name("alternative");
        if let Some(a) = consequent {
            report_node_type("then-arm", a, &analysis, src.as_bytes());
        }
        if let Some(b) = alternative {
            report_node_type("else-arm", b, &analysis, src.as_bytes());
        }
    }
}

/// Direct proof: enumerate each chain link's resolvability on
/// the real demo + real Mojolicious. Prints a truth table;
/// asserts specifically that `->to` does NOT resolve (the gap
/// the user flagged) so this test becomes a tripwire: if a
/// future fix makes `->to` resolve, this test will fail and
/// force us to promote it to a "works" assertion.
#[test]
fn test_demo_chain_empirical_truth_table() {
    use std::fs;
    use std::path::PathBuf;

    let root: PathBuf = env!("CARGO_MANIFEST_DIR").into();
    let demo = root.join("test_files/plugin_mojo_demo.pl");
    let demo_source = fs::read_to_string(&demo).expect("demo file");

    let idx = ModuleIndex::new_for_test();
    idx.set_workspace_root(Some(root.to_str().unwrap()));
    let files = crate::file_store::FileStore::new();
    let _ = crate::module_resolver::index_workspace_with_index(
        &root.join("test_files"),
        &files,
        Some(&idx),
    );

    let inc = crate::module_resolver::discover_inc_paths();
    let install = |name: &str| -> bool {
        let mut p = crate::module_resolver::create_parser();
        match crate::module_resolver::resolve_and_parse(&inc, name, &mut p) {
            Some(c) => {
                idx.insert_cache(name, Some(c));
                true
            }
            None => false,
        }
    };
    if !(install("Mojolicious")
        && install("Mojolicious::Routes")
        && install("Mojolicious::Routes::Route")
        && install("Mojolicious::Lite"))
    {
        eprintln!("SKIP: Mojolicious not installed");
        return;
    }

    let mut parser = tree_sitter::Parser::new();
    parser
        .set_language(&ts_parser_perl::LANGUAGE.into())
        .unwrap();
    let tree = parser.parse(&demo_source, None).unwrap();
    let mut analysis = crate::builder::build(&tree, demo_source.as_bytes());
    analysis.enrich_imported_types_with_keys(Some(&idx));

    let (line_idx, chain_line) = demo_source
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("$r->get('/users')") && l.contains("->to('Users#list')"))
        .expect("demo chain line present");

    let r_col = chain_line.find("$r").unwrap();
    let get_col = chain_line.find("->get(").unwrap() + 2;
    let to_col = chain_line.find("->to(").unwrap() + 2;
    let pt = |c: usize| tree_sitter::Point {
        row: line_idx,
        column: c,
    };

    // --- Link 1: $r's type ---
    let r_ty = analysis.inferred_type_via_bag("$r", pt(r_col));
    let r_class = r_ty
        .as_ref()
        .and_then(|t| t.class_name())
        .map(|s| s.to_string());

    // --- Link 2: ->get's invocant class (= $r's class) ---
    let get_ref = analysis.ref_at(pt(get_col)).expect("ref at ->get");
    let get_invocant_class = if matches!(get_ref.kind, crate::file_analysis::RefKind::MethodCall { .. }) {
        analysis.method_call_invocant_class(get_ref, Some(&idx))
    } else {
        None
    };

    // --- Link 3: ->get's RETURN type (what `$r->get(...)` evaluates to) ---
    // Find the method_call_expression node for `$r->get('/users')`.
    let mcall_node = {
        fn find_getcall<'a>(n: tree_sitter::Node<'a>, src: &[u8]) -> Option<tree_sitter::Node<'a>> {
            if n.kind() == "method_call_expression" {
                if let Some(m) = n.child_by_field_name("method") {
                    if m.utf8_text(src).ok() == Some("get") {
                        return Some(n);
                    }
                }
            }
            for i in 0..n.named_child_count() {
                if let Some(c) = n.named_child(i) {
                    if let Some(r) = find_getcall(c, src) {
                        return Some(r);
                    }
                }
            }
            None
        }
        find_getcall(tree.root_node(), demo_source.as_bytes()).expect("->get node")
    };
    let get_return_ty =
        analysis.resolve_expression_type(mcall_node, demo_source.as_bytes(), Some(&idx));

    // --- Link 4: ->to's invocant class (= ->get's return class) ---
    let to_ref = analysis.ref_at(pt(to_col)).expect("ref at ->to");
    let to_invocant_class = if matches!(to_ref.kind, crate::file_analysis::RefKind::MethodCall { .. }) {
        analysis.method_call_invocant_class(to_ref, Some(&idx))
    } else {
        None
    };

    // Also directly inspect the cached Route module's stored
    // return types + self-method tails for each method on the
    // chain's path.
    let route_cached = idx.get_cached("Mojolicious::Routes::Route").unwrap();
    let inspect = |name: &str| -> Option<InferredType> {
        for sym in &route_cached.analysis.symbols {
            if sym.name != name {
                continue;
            }
            if !matches!(
                sym.kind,
                crate::file_analysis::SymKind::Sub | crate::file_analysis::SymKind::Method
            ) {
                continue;
            }
            if matches!(&sym.detail, crate::file_analysis::SymbolDetail::Sub { .. }) {
                return route_cached.analysis.symbol_return_type_via_bag(sym.id, None);
            }
        }
        None
    };
    let gen_rt = inspect("_generate_route");
    let get_rt = inspect("get");
    let to_rt = inspect("to");
    let requires_rt = inspect("requires");
    let _route_rt = inspect("_route");

    eprintln!("======== chain truth table ========");
    eprintln!("  $r              class = {:?}", r_class);
    eprintln!("  ->get invocant  class = {:?}", get_invocant_class);
    eprintln!("  ->get RETURN    type  = {:?}", get_return_ty);
    eprintln!("  ->to  invocant  class = {:?}", to_invocant_class);
    eprintln!("  ---- cached Route symbols ----");
    eprintln!("  get             rt={:?}", get_rt);
    eprintln!("  _generate_route rt={:?}", gen_rt);
    eprintln!("  requires        rt={:?}", requires_rt);
    eprintln!("  to              rt={:?}", to_rt);
    eprintln!("  _route          rt={:?}", _route_rt);
    eprintln!("====================================");

    // The chain pin. With:
    //   - mojo-routes plugin's `_route` override pinning the
    //     return type inference can't reach, AND
    //   - the post-walk `ChainTypingReducer` (PreFold mode)
    //     symbolically executing every `my $X = <expr>` rhs (no
    //     "is it a chain" branch — same recursion every consumer
    //     uses), AND
    //   - the same reducer's return-arm refresh running before the
    //     second fold so `_generate_route`'s ternary return picks
    //     up the now-typed `$route`,
    // the full `$r->get(...)->to(...)` chain resolves end-to-end.
    // Each link is pinned individually so a regression localizes
    // to a specific hop instead of "the chain broke".
    assert!(
        r_class.is_some(),
        "(link 1) $r must resolve to a class; got None"
    );
    assert_eq!(r_class.as_deref(), Some("Mojolicious::Routes"));
    assert!(
        get_invocant_class.is_some(),
        "(link 2) ->get's invocant class must resolve; got None"
    );
    assert!(
        get_return_ty.is_some(),
        "(link 3) ->get's RETURN type must resolve through \
             _generate_route → _route's plugin override"
    );
    assert_eq!(
        get_return_ty.as_ref().and_then(|t| t.class_name()),
        Some("Mojolicious::Routes::Route"),
        "->get returns the Route class so ->to can chain off it"
    );
    assert!(
        to_invocant_class.is_some(),
        "(link 4) ->to's invocant class must resolve — THIS is \
             the chain hop the spike was unblocking"
    );
    assert_eq!(
        to_invocant_class.as_deref(),
        Some("Mojolicious::Routes::Route"),
        "->to is invoked on a Route, so cursor-on-`to` \
                    completion / hover / goto-def all reach \
                    Mojolicious::Routes::Route::to"
    );

    // Cross-check the cached symbols: every verb method
    // (get/post/put/etc.) tail-delegates through _generate_route,
    // and _generate_route's body folds via the chain typer +
    // refreshed return-arm typing.
    assert_eq!(
        _route_rt.as_ref().and_then(|t| t.class_name()),
        Some("Mojolicious::Routes::Route"),
        "_route is the override anchor",
    );
    assert_eq!(
        gen_rt.as_ref().and_then(|t| t.class_name()),
        Some("Mojolicious::Routes::Route"),
        "_generate_route folds because $route is now typed",
    );
    assert_eq!(
        get_rt.as_ref().and_then(|t| t.class_name()),
        Some("Mojolicious::Routes::Route"),
        "get tail-delegates to _generate_route which has a type",
    );
}

/// E2E: the motivator. `$r->get('/x')->|` at the cursor — the
/// public `completion_items` API must offer methods from the
/// route class (Route::to, Route::name, etc.), proving the
/// witness-bag-driven chain typing works all the way through
/// CursorContext → resolve_node_type → resolve_expression_type →
/// find_method_return_type → complete_methods_for_class.
///
/// No special casing. Zero hardcoded chain rules. If this
/// passes, the mojo-demo `$r->get('/x')->to(...)` gets
/// "intellismarts" on `->to` through witness flow.
#[test]
fn test_e2e_mojo_style_chain_completion_offers_chained_class_methods() {
    let src = r#"package MyApp::Route;
sub new { my $c = shift; bless {}, $c }
sub get {
    my $self = shift;
    $self->{_path} = shift;
    return $self;
}
sub to {
    my $self = shift;
    $self->{_target} = shift;
    return $self;
}
sub name {
    my $self = shift;
    $self->{_name} = shift;
    return $self;
}

package main;
my $r = MyApp::Route->new;
$r->get('/users')->
"#;
    let analysis = parse_analysis(src);
    let tree = crate::document::Document::new(src.to_string())
        .unwrap()
        .tree;
    let idx = ModuleIndex::new_for_test();

    // Cursor right after the trailing `->` on the chain line.
    let (line_idx, line) = src
        .lines()
        .enumerate()
        .find(|(_, l)| l.contains("$r->get('/users')->"))
        .unwrap();
    let col = line.rfind("->").unwrap() + 2;
    let pos = Position {
        line: line_idx as u32,
        character: col as u32,
    };

    let items = completion_items(&analysis, &tree, src, pos, &idx, None);
    let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
    for expected in &["to", "name", "get"] {
        assert!(
            labels.contains(expected),
            "expected `{}` in completion after `$r->get('/users')->`, \
                 got {} items: {:?}",
            expected,
            labels.len(),
            labels
        );
    }
}