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
use std::collections::HashMap;
use tower_lsp::lsp_types::*;
use tree_sitter::{Point, Tree};

use crate::cursor_context::{self, CursorContext};
use crate::file_analysis::{
    contains_point, format_inferred_type, CompletionCandidate, FileAnalysis, FoldKind,
    HandlerOwner, InferredType, OutlineSymbol, ParamInfo, RefKind, Span,
    SymKind as FaSymKind, SymbolDetail, PRIORITY_AUTO_ADD_QW, PRIORITY_BARE_IMPORT,
    PRIORITY_EXPLICIT_IMPORT, PRIORITY_UNIMPORTED,
};
use crate::module_index::{CachedModule, ModuleIndex, SubInfo};
use std::sync::Arc;

// ---- Coordinate conversion ----

fn point_to_position(p: Point) -> Position {
    Position {
        line: p.row as u32,
        character: p.column as u32,
    }
}

pub fn position_to_point(pos: Position) -> Point {
    Point::new(pos.line as usize, pos.character as usize)
}

pub fn span_to_range(span: Span) -> Range {
    Range {
        start: point_to_position(span.start),
        end: point_to_position(span.end),
    }
}

// ---- Symbol conversion ----

fn fa_sym_kind_to_lsp(kind: &FaSymKind) -> SymbolKind {
    match kind {
        FaSymKind::Sub => SymbolKind::FUNCTION,
        FaSymKind::Method => SymbolKind::METHOD,
        FaSymKind::Variable | FaSymKind::Field => SymbolKind::VARIABLE,
        FaSymKind::Package => SymbolKind::NAMESPACE,
        FaSymKind::Class => SymbolKind::CLASS,
        FaSymKind::Module => SymbolKind::MODULE,
        FaSymKind::HashKeyDef => SymbolKind::KEY,
        // Handler's actual LSP kind depends on the plugin's
        // `display` choice — this fallback only fires for paths
        // that don't carry detail, which is rare. Event is the
        // conservative default.
        FaSymKind::Handler => SymbolKind::EVENT,
        FaSymKind::Namespace => SymbolKind::NAMESPACE,
    }
}

/// Plugin-chosen Handler display → LSP SymbolKind. Called from the
/// outline path where OutlineSymbol carries `handler_display`.
fn handler_display_to_symbol_kind(d: &crate::file_analysis::HandlerDisplay) -> SymbolKind {
    use crate::file_analysis::HandlerDisplay as H;
    match d {
        H::Event => SymbolKind::EVENT,
        H::Method => SymbolKind::METHOD,
        H::Function => SymbolKind::FUNCTION,
        H::Field => SymbolKind::FIELD,
        H::Property => SymbolKind::PROPERTY,
        H::Constant => SymbolKind::CONSTANT,
        // Helper / Route / Task / Dispatch → FUNCTION. LSP's
        // `SymbolKind` enum is frozen; the distinguishing word lives
        // in `detail` / baked into `name` so client configs can
        // surface it without protocol extension.
        H::Helper | H::Route | H::Task | H::Action => SymbolKind::FUNCTION,
    }
}

fn handler_display_to_completion_kind(d: &crate::file_analysis::HandlerDisplay) -> CompletionItemKind {
    use crate::file_analysis::HandlerDisplay as H;
    match d {
        H::Event => CompletionItemKind::EVENT,
        H::Method => CompletionItemKind::METHOD,
        H::Function => CompletionItemKind::FUNCTION,
        H::Field => CompletionItemKind::FIELD,
        H::Property => CompletionItemKind::PROPERTY,
        H::Constant => CompletionItemKind::CONSTANT,
        H::Helper | H::Route | H::Task | H::Action => CompletionItemKind::FUNCTION,
    }
}

/// The LSP `SymbolKind` we'd emit for an outline node. Pulled out so
/// tests can pin behavior without reconstructing the conversion.
pub fn outline_lsp_kind(s: &OutlineSymbol) -> SymbolKind {
    match s.handler_display {
        Some(ref d) => handler_display_to_symbol_kind(d),
        None => fa_sym_kind_to_lsp(&s.kind),
    }
}

#[allow(deprecated)]
fn outline_to_document_symbol(s: &OutlineSymbol) -> DocumentSymbol {
    let children: Vec<DocumentSymbol> = s.children.iter().map(outline_to_document_symbol).collect();
    let kind = outline_lsp_kind(s);
    DocumentSymbol {
        name: s.name.clone(),
        detail: s.detail.clone(),
        kind,
        tags: None,
        deprecated: None,
        range: span_to_range(s.span),
        selection_range: span_to_range(s.selection_span),
        children: if children.is_empty() {
            None
        } else {
            Some(children)
        },
    }
}

// ---- Public LSP adapter functions ----

#[allow(deprecated)]
pub fn extract_symbols(analysis: &FileAnalysis) -> Vec<DocumentSymbol> {
    analysis.document_symbols()
        .iter()
        .map(outline_to_document_symbol)
        .collect()
}

#[allow(deprecated)]
/// Surface a plugin-controlled namespace in `workspace/symbol` results.
/// The namespace isn't a Perl symbol, but users want to jump to "where
/// my Minion tasks live" or "the mojo app for this package" — this
/// puts it on the same search surface as packages/subs.
#[allow(deprecated)]
pub fn plugin_namespace_to_workspace_info(
    ns: &crate::file_analysis::PluginNamespace,
    uri: Url,
) -> SymbolInformation {
    SymbolInformation {
        name: format!("[{}] {}", ns.kind, ns.id),
        kind: SymbolKind::NAMESPACE,
        tags: None,
        deprecated: None,
        location: Location {
            uri,
            range: span_to_range(ns.decl_span),
        },
        container_name: Some(ns.plugin_id.clone()),
    }
}

#[allow(deprecated)]
pub fn symbol_to_workspace_info(sym: &crate::file_analysis::Symbol, uri: Url) -> Option<SymbolInformation> {
    use crate::file_analysis::SymKind as FaSymKind;
    // Only include significant symbols (subs, methods, packages, classes)
    match sym.kind {
        FaSymKind::Sub | FaSymKind::Method | FaSymKind::Package | FaSymKind::Class => {}
        _ => return None,
    }
    Some(SymbolInformation {
        name: sym.name.clone(),
        kind: fa_sym_kind_to_lsp(&sym.kind),
        tags: None,
        deprecated: None,
        location: Location {
            uri,
            range: span_to_range(sym.selection_span),
        },
        container_name: sym.package.clone(),
    })
}

pub fn find_definition(
    analysis: &FileAnalysis,
    pos: Position,
    uri: &Url,
    module_index: &ModuleIndex,
    tree: &Tree,
    source: &str,
) -> Option<GotoDefinitionResponse> {
    let point = position_to_point(pos);

    // Try local definition first
    if let Some(span) = analysis.find_definition(point, Some(tree), Some(source.as_bytes()), Some(module_index)) {
        return Some(GotoDefinitionResponse::Scalar(Location {
            uri: uri.clone(),
            range: span_to_range(span),
        }));
    }

    // Check if cursor is on a function call that matches an imported symbol
    if let Some(r) = analysis.ref_at(point) {
        if matches!(r.kind, RefKind::FunctionCall { .. }) {
            if let Some((import, module_path, remote_name)) =
                resolve_imported_function(analysis, &r.target_name, module_index)
            {
                // Jump to the module's use statement in the current file
                // (or the .pm file if we can resolve it). Cross-file
                // sub_info lookup uses REMOTE name — distinct from
                // target_name for renaming imports.
                if let Ok(module_uri) = Url::from_file_path(&module_path) {
                    // Try to get the actual definition line from the module index.
                    let def_line = module_index
                        .get_cached(&import.module_name)
                        .and_then(|cached| cached.sub_info(&remote_name).map(|s| s.def_line()));
                    let def_range = match def_line {
                        Some(line) => Range {
                            start: Position { line, character: 0 },
                            end: Position { line, character: 0 },
                        },
                        None => Range::default(),
                    };

                    let pm_location = Location {
                        uri: module_uri,
                        range: def_range,
                    };

                    // If cursor is inside the use statement itself (on the import name),
                    // jump directly to the .pm definition — no need to also show the use stmt.
                    if contains_point(&import.span, point) {
                        return Some(GotoDefinitionResponse::Scalar(pm_location));
                    }

                    return Some(GotoDefinitionResponse::Array(vec![
                        // First: the use statement in this file
                        Location {
                            uri: uri.clone(),
                            range: span_to_range(import.span),
                        },
                        // Second: the sub definition in the .pm file
                        pm_location,
                    ]));
                }
                // Fall back to just the use statement
                return Some(GotoDefinitionResponse::Scalar(Location {
                    uri: uri.clone(),
                    range: span_to_range(import.span),
                }));
            }
        }

        // Cross-file package goto-def: resolve module name via module index
        if matches!(r.kind, RefKind::PackageRef) {
            if let Some(path) = module_index.module_path_cached(&r.target_name) {
                if let Ok(module_uri) = Url::from_file_path(&path) {
                    return Some(GotoDefinitionResponse::Scalar(Location {
                        uri: module_uri,
                        range: Range::default(),
                    }));
                }
            }
        }

        // Cross-file DispatchCall goto-def: a `$consumer->emit('ready', ...)`
        // in one file should jump to `$producer->on('ready', sub)` in
        // another. `find_definition` above only walks the current file's
        // symbols; for DispatchCall we enumerate every cached module
        // looking for Handlers matching (owner, name). Multiple stacked
        // registrations → return all as an Array so the editor can show
        // the picker.
        if let RefKind::DispatchCall { owner: Some(owner), .. } = &r.kind {
            use crate::file_analysis::SymbolDetail;
            let mut locs: Vec<Location> = Vec::new();
            for module_name in module_index.modules_with_symbol(&r.target_name) {
                let Some(cached) = module_index.get_cached(&module_name) else { continue };
                for sym in &cached.analysis.symbols {
                    if sym.name != r.target_name { continue; }
                    if let SymbolDetail::Handler { owner: o, .. } = &sym.detail {
                        if o == owner {
                            if let Ok(module_uri) = Url::from_file_path(&cached.path) {
                                locs.push(Location {
                                    uri: module_uri,
                                    range: span_to_range(sym.selection_span),
                                });
                            }
                        }
                    }
                }
            }
            if !locs.is_empty() {
                return Some(if locs.len() == 1 {
                    GotoDefinitionResponse::Scalar(locs.into_iter().next().unwrap())
                } else {
                    GotoDefinitionResponse::Array(locs)
                });
            }
        }

        // Cross-file method goto-def: resolve inherited methods through module index
        if matches!(r.kind, RefKind::MethodCall { .. }) {
            use crate::file_analysis::MethodResolution;
            let class_name = analysis.method_call_invocant_class(r, Some(module_index));
            if let Some(ref cn) = class_name {
                if let Some(MethodResolution::CrossFile { ref class }) = analysis.resolve_method_in_ancestors(cn, &r.target_name, Some(module_index)) {
                    if let Some(cached) = module_index.get_cached(class) {
                        if let Some(sub_info) = cached.sub_info(&r.target_name) {
                            if let Ok(module_uri) = Url::from_file_path(&cached.path) {
                                let line = sub_info.def_line();
                                let def_range = Range {
                                    start: Position { line, character: 0 },
                                    end: Position { line, character: 0 },
                                };
                                return Some(GotoDefinitionResponse::Scalar(Location {
                                    uri: module_uri,
                                    range: def_range,
                                }));
                            }
                        }
                    }
                }
            }
        }
    }

    None
}

pub fn find_references(analysis: &FileAnalysis, pos: Position, uri: &Url, tree: &Tree, source: &str, module_index: Option<&ModuleIndex>) -> Vec<Location> {
    analysis.find_references(position_to_point(pos), Some(tree), Some(source.as_bytes()), module_index)
        .into_iter()
        .map(|span| Location {
            uri: uri.clone(),
            range: span_to_range(span),
        })
        .collect()
}

pub fn rename(
    analysis: &FileAnalysis,
    pos: Position,
    uri: &Url,
    new_name: &str,
    tree: Option<&tree_sitter::Tree>,
    source: Option<&str>,
) -> Option<WorkspaceEdit> {
    let edits = analysis.rename_at(
        position_to_point(pos), new_name, tree, source.map(|s| s.as_bytes()),
    )?;

    let text_edits: Vec<TextEdit> = edits
        .into_iter()
        .map(|(span, new_text)| TextEdit {
            range: span_to_range(span),
            new_text,
        })
        .collect();

    let mut changes = HashMap::new();
    changes.insert(uri.clone(), text_edits);

    Some(WorkspaceEdit {
        changes: Some(changes),
        ..Default::default()
    })
}

fn fa_completion_kind(kind: &FaSymKind) -> CompletionItemKind {
    match kind {
        FaSymKind::Sub => CompletionItemKind::FUNCTION,
        FaSymKind::Method => CompletionItemKind::METHOD,
        FaSymKind::Variable | FaSymKind::Field => CompletionItemKind::VARIABLE,
        FaSymKind::Package => CompletionItemKind::CLASS,
        FaSymKind::Class => CompletionItemKind::CLASS,
        FaSymKind::Module => CompletionItemKind::MODULE,
        FaSymKind::HashKeyDef => CompletionItemKind::PROPERTY,
        FaSymKind::Handler => CompletionItemKind::EVENT,
        FaSymKind::Namespace => CompletionItemKind::MODULE,
    }
}

fn candidate_to_completion_item(c: CompletionCandidate) -> CompletionItem {
    let additional_text_edits = if c.additional_edits.is_empty() {
        None
    } else {
        Some(
            c.additional_edits
                .iter()
                .map(|(span, text)| TextEdit {
                    range: span_to_range(*span),
                    new_text: text.clone(),
                })
                .collect(),
        )
    };
    // `filter_text` is what LSP clients match the typed prefix against
    // when narrowing the completion list client-side. By default it's
    // the label. But when `insert_text` differs (e.g. dispatch-target
    // candidates insert `'connect'` while the label is just `connect`),
    // some clients fall back to `insert_text` for filtering — then
    // typing `c` after `(` stops matching because insert_text starts
    // with `'`. Set filter_text explicitly to the bare label so
    // client-side filtering keys on the name regardless.
    let filter_text = Some(c.label.clone());

    // Sort text places dispatch handlers ABOVE anything
    // complete_general can produce. Both default to sort_priority 0;
    // tied at "000" they interleave alphabetically (connect, fire,
    // message, wire) which makes handlers look like they're mixed
    // into noise. Prefixing with a space character ensures the
    // handler group sorts first as a block — space (0x20) < digit
    // (0x30) lexicographically. Non-handlers keep the existing
    // priority-based ordering.
    let sort_text = if matches!(c.kind, FaSymKind::Handler) {
        Some(format!(" {:03}{}", c.sort_priority, c.label))
    } else {
        Some(format!("{:03}", c.sort_priority))
    };
    let kind = if let Some(ref d) = c.display_override {
        handler_display_to_completion_kind(d)
    } else {
        fa_completion_kind(&c.kind)
    };
    CompletionItem {
        label: c.label,
        kind: Some(kind),
        detail: c.detail,
        insert_text: c.insert_text,
        filter_text,
        sort_text,
        additional_text_edits,
        ..Default::default()
    }
}

pub fn completion_items(
    analysis: &FileAnalysis,
    tree: &Tree,
    source: &str,
    pos: Position,
    module_index: &ModuleIndex,
    stable_packages: Option<&[(String, usize)]>,
) -> Vec<CompletionItem> {
    let point = position_to_point(pos);

    // Plugin query hook — runs BEFORE the native path. A plugin can
    // contribute items and optionally claim exclusivity for the slot
    // (e.g. Minion's arg-0 task-name completion: pure tasks, no
    // Minion instance-method firehose).
    if let Some(qctx) = cursor_context::build_plugin_query_context(analysis, tree, source.as_bytes(), point) {
        let registry = crate::builder::default_plugin_registry();
        let (uses, parents) = analysis.trigger_view_at(point);
        let query = crate::plugin::TriggerQuery {
            package_uses: &uses,
            package_parents: &parents,
        };
        let mut plugin_items: Vec<CompletionItem> = Vec::new();
        let mut exclusive = false;
        for p in registry.applicable(&query) {
            if let Some(answer) = p.on_completion(&qctx) {
                if answer.exclusive { exclusive = true; }
                for c in answer.items {
                    plugin_items.push(plugin_completion_to_item(c));
                }
                // Plugin-delegated dispatch-target completion: walk
                // Handler symbols whose owner matches and contribute
                // their names as items. Saves each plugin from
                // reimplementing the symbol-table scan.
                if let Some(req) = answer.dispatch_targets_for {
                    plugin_items.extend(dispatch_target_items_for(
                        analysis, module_index, &req.owner_class, &req.dispatcher_names,
                    ));
                }
            }
        }
        if exclusive {
            return plugin_items;
        }
        if !plugin_items.is_empty() {
            let native = completion_items_native(analysis, tree, source, pos, module_index, stable_packages);
            let mut out = plugin_items;
            out.extend(native);
            return out;
        }
    }

    completion_items_native(analysis, tree, source, pos, module_index, stable_packages)
}

/// Original native completion path. Renamed from `completion_items`
/// so the plugin-aware wrapper above can fall through to it.
fn completion_items_native(
    analysis: &FileAnalysis,
    tree: &Tree,
    source: &str,
    pos: Position,
    module_index: &ModuleIndex,
    stable_packages: Option<&[(String, usize)]>,
) -> Vec<CompletionItem> {
    let point = position_to_point(pos);

    // Try tree-based detection first for expression-based contexts
    let ctx = cursor_context::detect_cursor_context_tree_with_index(
        tree, source.as_bytes(), point, analysis, Some(module_index),
    )
        .unwrap_or_else(|| cursor_context::detect_cursor_context(source, point, Some(analysis)));

    // Mid-string completion for plugin-emitted MethodCallRefs. When the
    // cursor sits inside the span of a MethodCallRef emitted by a plugin
    // (e.g. `->to('Users#lis|')` in mojo-routes), offer methods on the
    // target class — prefix-filtered by whatever's been typed since the
    // `#` (or the whole prefix if none). This generalizes: any plugin
    // that drops a MethodCallRef at a string span gets scoped method
    // completion for free. Runs first so it preempts the generic paths.
    if let Some(refs) = refs_at_point_matching(analysis, point, |r|
        matches!(r.kind, RefKind::MethodCall { .. })
    ) {
        for r in &refs {
            if let RefKind::MethodCall { invocant, .. } = &r.kind {
                let early = mid_string_methodref_completions(
                    analysis, module_index, invocant, source, point, r.span,
                );
                if !early.is_empty() {
                    return early;
                }
            }
        }
    }

    // Dispatch-target completions are orthogonal to the context match:
    // a user typing inside `$obj->emit(^)` is simultaneously after a `->`
    // (tree detects `Method`) and inside call args (general path would
    // apply too). Pull the call context out once, prepend handler
    // completions at arg-0, and — just as importantly — SUPPRESS the
    // global sub/module firehose at arg-N>0 so comma-triggered
    // completion inside a dispatch call doesn't dump hundreds of
    // unrelated symbols. Sig help is the right affordance past arg-0;
    // completion gets out of the way.
    // Dispatch-target items are built into a separate vec so we can
    // retarget their textEdit range to the string-content span when
    // the cursor is mid-string. Keeping them out of the shared
    // `candidates` buffer avoids having to filter by kind later —
    // identifier completions (variables/subs/methods) pass through
    // the usual candidate → item conversion untouched.
    let mut dispatch_items: Vec<CompletionItem> = Vec::new();
    let mut candidates: Vec<CompletionCandidate> = Vec::new();
    let mut suppress_firehose = false;
    if let Some(call_ctx) = cursor_context::find_call_context(tree, source.as_bytes(), point) {
        if call_ctx.is_method {
            let dispatch_class = analysis.invocant_text_to_class(call_ctx.invocant.as_deref(), point);
            let has_any_handlers = dispatch_class.as_ref().is_some_and(|c|
                class_has_dispatch_handlers(analysis, module_index, c, &call_ctx.name)
            );
            // Debug line for dispatch completion — one-shot diagnoses
            // every "starting to type kills completion" / "no routes
            // offered" report. Includes the four values that together
            // determine whether dispatch fires and which handlers pass
            // the ancestor-walk filter: call name, invocant text,
            // resolved class (None = inferred_type miss), active_param
            // (>0 short-circuits to vars-only), and has_any_handlers
            // (false = bridges empty or filter mismatch).
            log::debug!(
                "completion dispatch: method={:?} invocant={:?} class={:?} active_param={} has_handlers={}",
                call_ctx.name, call_ctx.invocant, dispatch_class,
                call_ctx.active_param, has_any_handlers,
            );

            if call_ctx.active_param == 0 && has_any_handlers {
                // arg-0 of a known dispatcher: handlers at the top,
                // suppress the global sub/module firehose that would
                // otherwise drown them.
                let dispatch_cands = dispatch_target_completions(
                    analysis,
                    module_index,
                    call_ctx.invocant.as_deref(),
                    &call_ctx.name,
                    point,
                    tree,
                );
                dispatch_items.extend(
                    dispatch_cands.into_iter().map(candidate_to_completion_item),
                );
                // When the cursor is inside the string arg
                // (`url_for('/us|ers/profile')`) pin each item's
                // textEdit to the string-content span. The client's
                // default word-at-cursor (nvim's `iskeyword` default
                // excludes `/`, `#`, `:`) can't see across those
                // chars, so filter_text alone is dropped for labels
                // like `/users/profile` or `Users#list`. textEdit.range
                // tells the client "filter by the whole in-range
                // text" — works regardless of keyword class.
                if let Some(span) = string_content_span_at(tree, point) {
                    retarget_items_to_span(&mut dispatch_items, span);
                }
                suppress_firehose = true;
            } else if call_ctx.active_param > 0 && has_any_handlers
                && !matches!(ctx, CursorContext::HashKey { .. })
            {
                // Past arg-0 in a known dispatcher: the only sensible
                // completion is variables-in-scope (candidates for
                // passing as the next arg). Sig help handles shape
                // guidance. Short-circuit the context match entirely.
                //
                // EXCEPT when the cursor is sitting inside a nested
                // hash literal — that's a HashKey context and the
                // callee (or a plugin) has real keys to offer for it
                // (Minion's `enqueue(..., [...], { | })` options).
                // Skipping the short-circuit there lets the HashKey
                // match run and populate `priority`/`queue`/etc.
                let vars_only: Vec<CompletionCandidate> = analysis.complete_general(point)
                    .into_iter()
                    .filter(|c| matches!(c.kind, FaSymKind::Variable | FaSymKind::Field))
                    .collect();
                candidates.extend(vars_only);
                return candidates.drain(..).map(candidate_to_completion_item).collect();
            }
        }
    }

    candidates.extend::<Vec<CompletionCandidate>>(match ctx {
        CursorContext::Variable { sigil } => analysis.complete_variables(point, sigil),
        CursorContext::Method { ref invocant_type, ref invocant_text } => {
            if let Some(ref ty) = invocant_type {
                if let Some(cn) = ty.class_name() {
                    analysis.complete_methods_for_class(cn, Some(module_index))
                } else {
                    // Ref types get deref snippet completions (handled below)
                    Vec::new()
                }
            } else {
                analysis.complete_methods(invocant_text, point)
            }
        }
        CursorContext::HashKey { ref owner_type, ref var_text, ref source_sub } => {
            // Keys already written in the enclosing hash literal —
            // they shouldn't re-appear in the suggestions. Scoped to
            // the hash_expression directly so unrelated nearby calls
            // don't interfere. Works for both class-typed hashes and
            // sub-owned ones.
            let used = cursor_context::used_keys_in_enclosing_hash(tree, source.as_bytes(), point);
            let class_name = owner_type.as_ref().and_then(|t| t.class_name());
            let candidates = if let Some(cn) = class_name {
                analysis.complete_hash_keys_for_class(cn, point)
            } else if let Some(ref sub_name) = source_sub {
                // Routes to HashKeyOwner::Sub { name } — catches both
                // plugin-emitted HashKeyDefs (minion enqueue options)
                // AND body-derived keys from `$opts->{...}` accesses
                // in a final-hashref param. Previously this branch
                // was skipped when owner_type was None, so real hash
                // literals at a call-arg position returned nothing.
                analysis.complete_hash_keys_for_sub(sub_name, point)
            } else {
                analysis.complete_hash_keys(var_text, point)
            };
            candidates.into_iter().filter(|c| !used.contains(&c.label)).collect()
        }
        CursorContext::UseStatement { ref module_prefix, in_import_list, ref module_name } => {
            if in_import_list {
                if let Some(ref name) = module_name {
                    return complete_import_list(name, module_index);
                }
            } else {
                return complete_module_names(module_prefix, module_index);
            }
            Vec::new()
        }
        CursorContext::QualifiedPath { ref package } => {
            // `Foo::Bar::<cursor>` — return subs declared in (or
            // inherited by) that package, qualified with the package
            // prefix so the client filter matches against what the
            // user typed. Suppress the global firehose; this branch
            // is the answer.
            return qualified_path_completions(analysis, module_index, package);
        }
        CursorContext::General => {
            let mut items = Vec::new();
            // Keyval arg completions if inside a call at key position.
            // (Dispatch-target completions are handled above the match
            // regardless of context, so they apply whether tree detection
            // decides we're in Method, General, or anything else.)
            if let Some(call_ctx) =
                cursor_context::find_call_context(tree, source.as_bytes(), point)
            {
                if call_ctx.at_key_position {
                    items.extend(analysis.complete_keyval_args(
                        &call_ctx.name,
                        call_ctx.is_method,
                        call_ctx.invocant.as_deref(),
                        point,
                        &call_ctx.used_keys,
                        Some(module_index),
                    ));
                }
            }
            items.extend(analysis.complete_general(point));

            // Global sub/module firehose: useful at top-level
            // positions, harmful when we just offered dispatch
            // handlers at arg-0 (they'd drown in it). `suppress_firehose`
            // is set above when we know the cursor is at arg-0 of a
            // known dispatcher call.
            if !suppress_firehose {
                items.extend(imported_function_completions(analysis, module_index));
                items.extend(unimported_function_completions(analysis, module_index, point, stable_packages));
            }

            items
        }
    });

    let mut items: Vec<CompletionItem> = candidates
        .drain(..)
        .map(candidate_to_completion_item)
        .collect();
    // Dispatch items stay at the top — their sort_text already leads
    // with a space so they group above the priority-numbered rest,
    // but the authoritative ordering is "dispatch first" so they're
    // prepended explicitly.
    if !dispatch_items.is_empty() {
        let mut with_dispatch = dispatch_items;
        with_dispatch.extend(items);
        items = with_dispatch;
    }

    // Ref-type deref snippets when completing after ->
    if let CursorContext::Method { ref invocant_type, .. } = ctx {
        if let Some(ref ty) = invocant_type {
            if !ty.is_object() {
                items.extend(ref_type_snippet_completions(ty));
            }
        }
    }

    items
}

/// Complete module names on `use` lines from resolved + @INC-scanned modules.
fn complete_module_names(prefix: &str, module_index: &ModuleIndex) -> Vec<CompletionItem> {
    let modules = module_index.complete_module_names(prefix);
    modules.into_iter().map(|(name, is_resolved)| {
        let (detail, priority) = if is_resolved {
            (Some("indexed".to_string()), 10u8)
        } else {
            (Some("available".to_string()), 50u8)
        };
        CompletionItem {
            label: name.clone(),
            kind: Some(CompletionItemKind::MODULE),
            detail,
            sort_text: Some(format!("{:03}{}", priority, name)),
            ..Default::default()
        }
    }).collect()
}

/// Complete import list items for `use Module qw(|)`.
fn complete_import_list(module_name: &str, module_index: &ModuleIndex) -> Vec<CompletionItem> {
    let cached: Arc<CachedModule> = match module_index.get_cached(module_name) {
        Some(c) => c,
        None => return vec![CompletionItem {
            label: format!("loading {}...", module_name),
            kind: Some(CompletionItemKind::TEXT),
            detail: Some("Module is being indexed".to_string()),
            insert_text: Some(String::new()),
            sort_text: Some("999".to_string()),
            ..Default::default()
        }],
    };

    let mut items = Vec::new();
    let mut seen = std::collections::HashSet::new();

    for name in &cached.analysis.export {
        if seen.insert(name.clone()) {
            let detail = cached.sub_info(name)
                .and_then(|s| s.return_type())
                .map(|rt| format!("@EXPORT → {}", format_inferred_type(&rt)))
                .or(Some("@EXPORT".to_string()));
            items.push(CompletionItem {
                label: name.clone(),
                kind: Some(CompletionItemKind::FUNCTION),
                detail,
                sort_text: Some(format!("010{}", name)),
                ..Default::default()
            });
        }
    }

    for name in &cached.analysis.export_ok {
        if seen.insert(name.clone()) {
            let detail = cached.sub_info(name)
                .and_then(|s| s.return_type())
                .map(|rt| format!("{}", format_inferred_type(&rt)));
            items.push(CompletionItem {
                label: name.clone(),
                kind: Some(CompletionItemKind::FUNCTION),
                detail,
                sort_text: Some(format!("020{}", name)),
                ..Default::default()
            });
        }
    }

    items
}

/// Completion items for `Package::<cursor>` — subs declared in that
/// package (cross-file + local + inherited) PLUS sub-packages nested
/// underneath. Typing `Mojo::` shows both the methods on Mojo itself
/// and the available namespaces (`Util`, `Base`, `IOLoop`, …) so the
/// user can drill in without leaving completion. Subs sort first
/// (priority 010), sub-packages second (020).
fn qualified_path_completions(
    analysis: &FileAnalysis,
    module_index: &ModuleIndex,
    package: &str,
) -> Vec<CompletionItem> {
    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut items: Vec<CompletionItem> = Vec::new();

    // Subs declared in this package (cross-file + local + inherited).
    // Insert the bare name — the typed `Package::` prefix stays put.
    for c in analysis.complete_methods_for_class(package, Some(module_index)) {
        if !seen.insert(c.label.clone()) {
            continue;
        }
        items.push(CompletionItem {
            label: c.label.clone(),
            kind: Some(CompletionItemKind::FUNCTION),
            detail: c.detail.clone().or_else(|| Some(format!("from {}", package))),
            sort_text: Some(format!("010{}", c.label)),
            insert_text: Some(c.label),
            ..Default::default()
        });
    }

    // Sub-packages — both cross-file modules whose name starts with
    // `Package::` AND in-file `package Package::Other` declarations.
    // Label is the suffix (what follows the typed prefix), so the
    // client's `Package::<typed>` filter matches naturally.
    let prefix = format!("{}::", package);
    let mut subpaths: Vec<(String, &'static str)> = Vec::new();
    for (name, is_resolved) in module_index.complete_module_names(&prefix) {
        let hint = if is_resolved { "indexed" } else { "available" };
        subpaths.push((name, hint));
    }
    for sym in &analysis.symbols {
        if !matches!(sym.kind, FaSymKind::Package | FaSymKind::Class) {
            continue;
        }
        if sym.name.starts_with(&prefix) && sym.name != package {
            subpaths.push((sym.name.clone(), "in-file"));
        }
    }
    for (name, hint) in subpaths {
        let suffix = match name.strip_prefix(&prefix) {
            Some(s) if !s.is_empty() => s.to_string(),
            _ => continue,
        };
        if !seen.insert(suffix.clone()) {
            continue;
        }
        items.push(CompletionItem {
            label: suffix.clone(),
            kind: Some(CompletionItemKind::MODULE),
            detail: Some(hint.to_string()),
            sort_text: Some(format!("020{}", suffix)),
            insert_text: Some(suffix),
            ..Default::default()
        });
    }
    items
}

/// Returns snippet completions for ref-type dereference after `->`.
fn ref_type_snippet_completions(ty: &InferredType) -> Vec<CompletionItem> {
    match ty {
        InferredType::ArrayRef => vec![CompletionItem {
            label: "[index]".to_string(),
            kind: Some(CompletionItemKind::SNIPPET),
            detail: Some("array dereference".to_string()),
            insert_text: Some("[$0]".to_string()),
            insert_text_format: Some(InsertTextFormat::SNIPPET),
            sort_text: Some("000".to_string()),
            ..Default::default()
        }],
        InferredType::CodeRef { .. } => vec![CompletionItem {
            label: "(args)".to_string(),
            kind: Some(CompletionItemKind::SNIPPET),
            detail: Some("code dereference".to_string()),
            insert_text: Some("($0)".to_string()),
            insert_text_format: Some(InsertTextFormat::SNIPPET),
            sort_text: Some("000".to_string()),
            ..Default::default()
        }],
        InferredType::HashRef => vec![CompletionItem {
            label: "{key}".to_string(),
            kind: Some(CompletionItemKind::SNIPPET),
            detail: Some("hash dereference".to_string()),
            insert_text: Some("{$0}".to_string()),
            insert_text_format: Some(InsertTextFormat::SNIPPET),
            sort_text: Some("000".to_string()),
            ..Default::default()
        }],
        _ => Vec::new(),
    }
}

pub fn hover_info(
    analysis: &FileAnalysis,
    source: &str,
    pos: Position,
    module_index: &ModuleIndex,
    tree: &Tree,
) -> Option<Hover> {
    let point = position_to_point(pos);

    // Try local hover first
    if let Some(markdown) = analysis.hover_info(point, source, Some(tree), Some(module_index)) {
        return Some(Hover {
            contents: HoverContents::Markup(MarkupContent {
                kind: MarkupKind::Markdown,
                value: markdown,
            }),
            range: None,
        });
    }

    // Check if cursor is on an imported function call or a Perl
    // builtin. Builtin docs come from `module_index.builtin_doc`,
    // which the resolver thread hydrates from SQLite (parsed from
    // `perlfunc.pod` only on cold-cache miss).
    if let Some(r) = analysis.ref_at(point) {
        if matches!(r.kind, RefKind::FunctionCall { .. }) {
            if is_perl_builtin(&r.target_name) {
                if let Some(markdown) = module_index.builtin_doc(&r.target_name) {
                    return Some(Hover {
                        contents: HoverContents::Markup(MarkupContent {
                            kind: MarkupKind::Markdown,
                            value: markdown,
                        }),
                        range: None,
                    });
                }
            }
            if let Some((import, _path, remote_name)) =
                resolve_imported_function(analysis, &r.target_name, module_index)
            {
                let mut parts = Vec::new();

                // Show signature if available. Cross-file lookup uses
                // the REMOTE name — for a renaming import (`del` →
                // `delete`), cursor is on `del` but sub_info lives
                // under `delete` in the cached module.
                if let Some(cached) = module_index.get_cached(&import.module_name) {
                    if let Some(sub_info) = cached.sub_info(&remote_name) {
                        // Present the sig under the LOCAL name — that's
                        // what the user typed and what hover should lead
                        // with; the remote name is just how we fetched it.
                        let sig = format_imported_signature(&r.target_name, &sub_info);
                        parts.push(format!("```perl\n{}\n```", sig));
                        if let Some(doc) = sub_info.doc() {
                            parts.push(doc.to_string());
                        }
                    }
                }

                if remote_name != r.target_name {
                    parts.push(format!(
                        "*imported from `{}` (as `{}`)*",
                        import.module_name, remote_name
                    ));
                } else {
                    parts.push(format!("*imported from `{}`*", import.module_name));
                }
                let markdown = parts.join("\n\n");
                return Some(Hover {
                    contents: HoverContents::Markup(MarkupContent {
                        kind: MarkupKind::Markdown,
                        value: markdown,
                    }),
                    range: None,
                });
            }
        }
    }

    None
}

pub fn document_highlights(analysis: &FileAnalysis, pos: Position, tree: &tree_sitter::Tree, source: &str, module_index: Option<&ModuleIndex>) -> Vec<DocumentHighlight> {
    use crate::file_analysis::AccessKind;
    analysis.find_highlights(position_to_point(pos), Some(tree), Some(source.as_bytes()), module_index)
        .into_iter()
        .map(|(span, access)| DocumentHighlight {
            range: span_to_range(span),
            kind: Some(match access {
                AccessKind::Write => DocumentHighlightKind::WRITE,
                _ => DocumentHighlightKind::READ,
            }),
        })
        .collect()
}

pub fn selection_ranges(tree: &Tree, pos: Position) -> SelectionRange {
    let spans = cursor_context::selection_ranges(tree, position_to_point(pos));
    // Build linked list from innermost to outermost
    let mut result: Option<SelectionRange> = None;
    for span in spans.into_iter().rev() {
        result = Some(SelectionRange {
            range: span_to_range(span),
            parent: result.map(Box::new),
        });
    }
    result.unwrap_or(SelectionRange {
        range: Range::default(),
        parent: None,
    })
}

pub fn folding_ranges(analysis: &FileAnalysis) -> Vec<FoldingRange> {
    analysis.fold_ranges
        .iter()
        .map(|f| FoldingRange {
            start_line: f.start_line as u32,
            start_character: None,
            end_line: f.end_line as u32,
            end_character: None,
            kind: Some(match f.kind {
                FoldKind::Region => FoldingRangeKind::Region,
                FoldKind::Comment => FoldingRangeKind::Comment,
            }),
            collapsed_text: None,
        })
        .collect()
}

// ---- Signature help ----

/// Does this class have ANY registered Handlers matching the method
/// name as a declared dispatcher? Used to decide whether we're in a
/// "known dispatch call" context — gates the noise-suppression logic
/// around it so the firehose of unrelated subs only gets suppressed
/// when we actually know this is a dispatcher call site.
fn class_has_dispatch_handlers(
    analysis: &FileAnalysis,
    module_index: &ModuleIndex,
    class: &str,
    dispatcher: &str,
) -> bool {
    // Funnels through `for_each_dispatch_handler_on_class` (the
    // ancestor-aware bridge walker) so this predicate agrees with
    // `dispatch_target_completions`: if completion would offer at
    // least one handler, this returns true. `found` short-circuits
    // semantically — the walker still visits every class, but per-
    // class closure exits cheaply once the flag is set.
    let mut found = false;
    analysis.for_each_dispatch_handler_on_class(
        class,
        dispatcher,
        Some(module_index),
        |_sym, _prov| { found = true; },
    );
    found
}

/// Span of the string-literal's CONTENT (between the quotes) at `point`,
/// if the cursor is inside one. Returns `None` for non-string contexts.
///
/// Used by mid-string completions (dispatch-target handlers, method-ref
/// mid-string) to anchor a `TextEdit` range. Without this, the client's
/// word-at-cursor heuristic (nvim's `iskeyword` default excludes `/`
/// and `#`) mis-extracts the typed prefix for non-identifier labels
/// like `/users/profile` or `Users#list` and drops valid matches.
/// Setting `textEdit.range` to the content span makes the client match
/// the whole in-range text against the label.
///
/// Empty strings (`url_for('')`): no `string_content` child exists, so
/// fall back to a zero-width span at the cursor. Any prefix match
/// against "" passes, which is the right answer for "user hasn't
/// typed anything in the string yet".
fn string_content_span_at(tree: &Tree, point: Point) -> Option<Span> {
    let mut node = tree.root_node().descendant_for_point_range(point, point)?;
    for _ in 0..4 {
        match node.kind() {
            "string_content" => {
                return Some(Span {
                    start: node.start_position(),
                    end: node.end_position(),
                });
            }
            "string_literal" | "interpolated_string_literal" => {
                // Boundary case: when the cursor sits at the END of
                // the content (just before the closing quote) or on
                // the closing quote itself, `descendant_for_point_range`
                // lands on the literal wrapper instead of `string_content`
                // — content ranges are half-open, so the end column
                // isn't "contained". Look down for a `string_content`
                // child and use its span. Otherwise we'd return a
                // zero-width range at cursor, which makes textEdit
                // APPEND the label after the user's typed text
                // (`'/fall' → '/fall/fallback'`) instead of replacing it.
                let mut walker = node.walk();
                for child in node.named_children(&mut walker) {
                    if child.kind() == "string_content" {
                        return Some(Span {
                            start: child.start_position(),
                            end: child.end_position(),
                        });
                    }
                }
                // Genuinely empty literal (`''` with cursor between the
                // quotes). Zero-width range at cursor is correct here —
                // there's nothing to replace.
                return Some(Span { start: point, end: point });
            }
            _ => {}
        }
        let Some(p) = node.parent() else { break };
        node = p;
    }
    None
}

/// Rewrite each item's replace range to `span`, materialized as a
/// `TextEdit` on `text_edit`. Used for mid-string completions where
/// the client's default word-extraction would otherwise misfilter the
/// item (see `string_content_span_at`).
///
/// `newText` is the bare `label` — NOT `insert_text`. `insert_text`
/// from other code paths can carry wrapping quotes (`'connect'` for
/// the bare-parens case), and the replace range we're setting already
/// sits INSIDE the existing string's quotes. Threading insert_text
/// through here would insert `'connect'` inside `''` → `''connect''`.
/// Using the label keeps the invariant simple: whatever span we're
/// replacing, the replacement is the identifier text, no decoration.
/// `insert_text` is also cleared — textEdit takes precedence in the
/// LSP spec, and leaving both set confuses some clients.
fn retarget_items_to_span(items: &mut [CompletionItem], span: Span) {
    let range = span_to_range(span);
    for item in items {
        item.text_edit = Some(tower_lsp::lsp_types::CompletionTextEdit::Edit(
            tower_lsp::lsp_types::TextEdit { range, new_text: item.label.clone() },
        ));
        item.insert_text = None;
    }
}

/// True if the cursor sits somewhere that makes wrapping-quotes in the
/// insert_text wrong. Two cases:
///   * cursor in a `string_literal` / `interpolated_string_literal`
///     (the quotes are already typed)
///   * cursor at a fat-comma LHS autoquote position (the `=>` will
///     autoquote whatever bareword lands there)
fn cursor_in_string_or_autoquote(tree: &Tree, point: Point) -> bool {
    let Some(mut node) = tree.root_node().descendant_for_point_range(point, point) else {
        return false;
    };
    // Walk upward a handful of levels — tree-sitter may hand back a
    // token node first; the enclosing string_literal is typically one
    // or two parents up.
    for _ in 0..4 {
        match node.kind() {
            "string_literal" | "interpolated_string_literal"
            | "string_content" | "autoquoted_bareword" => return true,
            _ => {}
        }
        let Some(p) = node.parent() else { break };
        node = p;
    }
    false
}

/// Completions for the first arg of a string-dispatched method call.
/// Walks every Handler symbol (local + cross-file via module index),
/// filters by (owner class matches receiver, dispatcher matches method
/// name), and returns each as a CompletionItem. Stacked registrations
/// dedup on name; the completion shows the param shape in detail so
/// you know what args the handler will get.
fn dispatch_target_completions(
    analysis: &FileAnalysis,
    module_index: &ModuleIndex,
    invocant: Option<&str>,
    method_name: &str,
    point: Point,
    tree: &Tree,
) -> Vec<CompletionCandidate> {
    let class = match analysis.invocant_text_to_class(invocant, point) {
        Some(c) => c,
        None => return Vec::new(),
    };

    // Quote-aware insert_text. Three cases:
    //   * cursor inside a string_literal (`->emit('|')`) — the quotes
    //     are already there, emit bare name.
    //   * cursor at fat-comma LHS autoquote position (`->emit(|=>...)`)
    //     — no quotes needed, Perl auto-quotes barewords on fat-comma
    //     LHS. (Dispatch shouldn't normally fire here, but defensive.)
    //   * anywhere else — emit with surrounding quotes so one accept
    //     keystroke produces `'name'` in bare parens.
    // Implemented as a closure so the branching stays adjacent to the
    // decision and every emitted candidate is consistent.
    let needs_quotes = !cursor_in_string_or_autoquote(tree, point);

    // Accumulate (handler_name → display_params + provenance) so stacked
    // registrations across files appear once in the completion list.
    // The walker funnels local + namespace-bridged + cross-file via
    // `for_each_entity_bridged_to` (rule #8) and walks ancestors so
    // `$c->url_for('|')` on a `Users` controller surfaces routes whose
    // Handlers live on `Mojolicious::Controller` (the shared base).
    let mut acc: std::collections::BTreeMap<String, (Vec<String>, String)> =
        std::collections::BTreeMap::new();
    analysis.for_each_dispatch_handler_on_class(
        &class, method_name, Some(module_index),
        |sym, provenance| {
            let SymbolDetail::Handler { params, .. } = &sym.detail else { return };
            let display: Vec<String> = params
                .iter()
                .filter(|p| !p.is_invocant)
                .map(|p| p.name.clone())
                .collect();
            acc.entry(sym.name.clone()).or_insert((display, provenance.to_string()));
        },
    );

    acc.into_iter().map(|(name, (params, provenance))| {
        let detail = if params.is_empty() {
            format!("handler on {}  ({})", class, provenance)
        } else {
            format!("handler on {} ({})  — {}", class, params.join(", "), provenance)
        };
        CompletionCandidate {
            label: name.clone(),
            // Handler kind flows to CompletionItemKind::EVENT via
            // `fa_completion_kind` — consistent with outline and hover.
            kind: FaSymKind::Handler,
            detail: Some(detail),
            // Bare inside quotes / autoquote, quoted otherwise — see
            // `needs_quotes` above. Accepting the suggestion lands
            // correct source text regardless of where the cursor was.
            insert_text: Some(if needs_quotes {
                format!("'{}'", name)
            } else {
                name.clone()
            }),
            // Top of the list: handlers are the canonical completion in
            // this position when a dispatcher is declared for them.
            sort_priority: 0,
            additional_edits: Vec::new(),
                display_override: None,
        }
    }).collect()
}

/// Collect refs whose span contains `point` and match a predicate.
/// Small generic helper — used by mid-string completion to find the
/// (typically unique) MethodCallRef at the cursor.
fn refs_at_point_matching<'a>(
    analysis: &'a FileAnalysis,
    point: Point,
    pred: impl Fn(&crate::file_analysis::Ref) -> bool,
) -> Option<Vec<&'a crate::file_analysis::Ref>> {
    let out: Vec<&crate::file_analysis::Ref> = analysis.refs.iter()
        .filter(|r| span_contains_point(&r.span, point) && pred(r))
        .collect();
    if out.is_empty() { None } else { Some(out) }
}

fn span_contains_point(span: &crate::file_analysis::Span, p: Point) -> bool {
    let a = (span.start.row, span.start.column);
    let b = (span.end.row, span.end.column);
    let pp = (p.row, p.column);
    a <= pp && pp <= b
}

/// Mid-string completion for a cursor inside a plugin-emitted
/// `MethodCallRef`. Offers methods on the invocant class (walking
/// inheritance + workspace), prefix-filtered by whatever the user has
/// typed since the start of the ref's span.
///
/// The core is deliberately ignorant of plugin-specific string formats
/// (no `#` splitting, no `::` splitting — that's Mojo-routes syntax
/// bleeding in). It's the plugin's job to emit a tight span that
/// covers only the method-name portion of its string; the core just
/// slices `source[ref.span.start..cursor]` and uses that as the prefix.
/// If a plugin wants fuzzier matching behavior it can widen its spans;
/// the semantics stay plugin-controlled.
fn mid_string_methodref_completions(
    analysis: &FileAnalysis,
    module_index: &ModuleIndex,
    invocant_class: &str,
    source: &str,
    point: Point,
    ref_span: crate::file_analysis::Span,
) -> Vec<CompletionItem> {
    // Pull the typed prefix out of the live source text — not from the
    // parser, because during active editing the two diverge.
    let lines: Vec<&str> = source.lines().collect();
    if ref_span.start.row >= lines.len() || point.row >= lines.len() {
        return Vec::new();
    }
    let typed = if ref_span.start.row == point.row {
        let line = lines[point.row];
        let start = ref_span.start.column.min(line.len());
        let end = point.column.min(line.len());
        &line[start..end]
    } else {
        // Multi-line ref spans: conservative — only use the current line.
        let line = lines[point.row];
        &line[..point.column.min(line.len())]
    };

    let candidates = analysis.complete_methods_for_class(invocant_class, Some(module_index));
    let mut items: Vec<CompletionItem> = candidates
        .into_iter()
        .filter(|c| typed.is_empty() || c.label.starts_with(typed))
        .map(|c| {
            let mut item = candidate_to_completion_item(c);
            item.sort_text = Some(format!("000{}", item.label));
            item
        })
        .collect();
    // Anchor the replace range to the ref's span (already tight on
    // the method-name portion — plugins control its width). Without
    // this, labels containing non-identifier chars (`Ctrl#act` past
    // the `#`) get dropped by the client's word-match. Same fix as
    // dispatch-target items, same reason.
    retarget_items_to_span(&mut items, ref_span);
    items
}

/// Materialize `PluginCompletion` items for every Handler symbol
/// whose owner matches `owner_class` and whose `dispatchers` list
/// contains any of `dispatcher_names`. Walks the local analysis AND
/// every cross-file cached module. Used by plugin-delegated
/// dispatch-name completion (Minion enqueue arg-0, Mojo emit arg-0,
/// etc.).
fn dispatch_target_items_for(
    analysis: &FileAnalysis,
    module_index: &ModuleIndex,
    owner_class: &str,
    dispatcher_names: &[String],
) -> Vec<CompletionItem> {
    use crate::file_analysis::SymbolDetail;
    let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
    let mut out: Vec<CompletionItem> = Vec::new();
    let mut emit = |sym: &crate::file_analysis::Symbol| {
        let SymbolDetail::Handler { display, .. } = &sym.detail else { return };
        if !seen.insert(sym.name.clone()) { return; }
        let detail = display.outline_word().map(|s| s.to_string());
        out.push(CompletionItem {
            label: sym.name.clone(),
            kind: Some(handler_display_to_completion_kind(display)),
            detail,
            filter_text: Some(sym.name.clone()),
            sort_text: Some(format!(" 000{}", sym.name)),
            insert_text: Some(format!("'{}'", sym.name)),
            ..Default::default()
        });
    };
    for sym in analysis.handlers_for_owner(owner_class, dispatcher_names) {
        emit(sym);
    }
    module_index.for_each_cached(|_, cached| {
        for sym in cached.analysis.handlers_for_owner(owner_class, dispatcher_names) {
            emit(sym);
        }
    });
    out
}

/// Convert a plugin's minimal `PluginSignatureHelp` to the full LSP
/// `SignatureHelp` shape. Core fills in `active_signature` and the
/// per-parameter scaffolding so plugin-side Rhai stays ergonomic.
fn plugin_sig_to_lsp(p: crate::plugin::PluginSignatureHelp) -> SignatureHelp {
    let parameters: Vec<ParameterInformation> = p.params.iter().cloned()
        .map(|label| ParameterInformation {
            label: ParameterLabel::Simple(label),
            documentation: None,
        })
        .collect();
    SignatureHelp {
        signatures: vec![SignatureInformation {
            label: p.label,
            documentation: None,
            parameters: Some(parameters),
            active_parameter: Some(p.active_param as u32),
        }],
        active_signature: Some(0),
        active_parameter: Some(p.active_param as u32),
    }
}

/// Convert a plugin completion hint to LSP `CompletionItemKind`.
fn plugin_completion_kind_hint(h: &crate::plugin::CompletionKindHint) -> CompletionItemKind {
    use crate::plugin::CompletionKindHint as K;
    match h {
        K::Function | K::Task | K::Helper | K::Route => CompletionItemKind::FUNCTION,
        K::Method => CompletionItemKind::METHOD,
        K::Field => CompletionItemKind::FIELD,
        K::Property => CompletionItemKind::PROPERTY,
        K::Value => CompletionItemKind::VALUE,
        K::Event => CompletionItemKind::EVENT,
        K::Operator => CompletionItemKind::OPERATOR,
        K::Keyword => CompletionItemKind::KEYWORD,
    }
}

fn plugin_completion_to_item(p: crate::plugin::PluginCompletion) -> CompletionItem {
    let filter_text = Some(p.label.clone());
    let kind = plugin_completion_kind_hint(&p.kind);
    // Map the semantic hint to an outline-style detail word so the
    // client can distinguish Task/Helper/Route from plain Function.
    let detail = p.detail.or_else(|| match p.kind {
        crate::plugin::CompletionKindHint::Task => Some("task".into()),
        crate::plugin::CompletionKindHint::Helper => Some("helper".into()),
        crate::plugin::CompletionKindHint::Route => Some("route".into()),
        _ => None,
    });
    CompletionItem {
        label: p.label,
        kind: Some(kind),
        detail,
        insert_text: p.insert_text,
        filter_text,
        sort_text: Some(" 000".into()), // space prefix sorts above digit-prefixed priorities
        ..Default::default()
    }
}

/// Find the enclosing method_call_expression at `point` and return any
/// `DispatchCall` ref whose span sits inside that call's argument list.
/// Returns `(handler_name, owner_class, dispatcher)` — all three are
/// already plugin-resolved, so the caller inherits const-folding and
/// receiver-type inference without re-deriving them.
fn dispatch_info_for_enclosing_call(
    analysis: &FileAnalysis,
    tree: &Tree,
    _source: &[u8],
    point: Point,
) -> Option<(String, String, String)> {
    // Walk up from the cursor until we hit the enclosing method call.
    let mut node = tree.root_node().descendant_for_point_range(point, point)?;
    let call = loop {
        if node.kind() == "method_call_expression" {
            break node;
        }
        node = node.parent()?;
    };
    let call_start = crate::file_analysis::Span {
        start: call.start_position(),
        end: call.end_position(),
    };

    // First DispatchCall ref whose span is contained by this call.
    for r in &analysis.refs {
        let RefKind::DispatchCall { dispatcher, owner } = &r.kind else { continue };
        if !span_contains_span(&call_start, &r.span) { continue; }
        let Some(HandlerOwner::Class(class)) = owner.clone() else { continue };
        return Some((r.target_name.clone(), class, dispatcher.clone()));
    }
    None
}

fn span_contains_span(outer: &crate::file_analysis::Span, inner: &crate::file_analysis::Span) -> bool {
    let o_start = (outer.start.row, outer.start.column);
    let o_end   = (outer.end.row,   outer.end.column);
    let i_start = (inner.start.row, inner.start.column);
    let i_end   = (inner.end.row,   inner.end.column);
    o_start <= i_start && i_end <= o_end
}

/// Build sig help for a known (class, dispatcher, handler_name). Walks
/// the current file's symbols AND every cached module — otherwise a
/// consumer file that emits against a producer-defined handler gets no
/// sig help, even though hover already walks cross-file (the two must
/// agree — same abstraction, same reach).
fn string_dispatch_signature_for(
    analysis: &FileAnalysis,
    module_index: Option<&ModuleIndex>,
    class: &str,
    dispatcher: &str,
    handler_name: &str,
    active_param: usize,
) -> Option<SignatureHelp> {
    let mut signatures: Vec<SignatureInformation> = Vec::new();

    // Shared builder — used both for in-file and cross-file symbol walks
    // so a handler's sig is formatted identically regardless of where
    // it lives.
    let push_sig = |signatures: &mut Vec<SignatureInformation>,
                    sym: &crate::file_analysis::Symbol,
                    provenance: Option<&str>| {
        let SymbolDetail::Handler { owner, dispatchers, params, .. } = &sym.detail else { return };
        let HandlerOwner::Class(n) = owner;
        if n != class { return; }
        let dispatcher_ok = dispatchers.is_empty()
            || dispatchers.iter().any(|d| d == dispatcher);
        if !dispatcher_ok || params.is_empty() { return; }

        let display: Vec<&ParamInfo> = params
            .iter()
            .filter(|p| !p.is_invocant)
            .collect();
        let labels: Vec<String> = display.iter()
            .map(|p| match &p.default {
                Some(d) => format!("{} = {}", p.name, d),
                None => p.name.clone(),
            })
            .collect();
        let parameters: Vec<ParameterInformation> = labels.iter()
            .map(|l| ParameterInformation {
                label: ParameterLabel::Simple(l.clone()),
                documentation: None,
            })
            .collect();
        let doc = match provenance {
            Some(p) => format!(
                "{} handler on `{}`, registered at {} line {}",
                handler_name, class, p, sym.selection_span.start.row + 1,
            ),
            None => format!(
                "{} handler on `{}`, registered at line {}",
                handler_name, class, sym.selection_span.start.row + 1,
            ),
        };
        signatures.push(SignatureInformation {
            label: format!("{}('{}', {})", dispatcher, handler_name, labels.join(", ")),
            documentation: Some(Documentation::String(doc)),
            parameters: Some(parameters),
            active_parameter: None,
        });
    };

    for sym in &analysis.symbols {
        if sym.name != handler_name { continue; }
        push_sig(&mut signatures, sym, None);
    }
    if let Some(idx) = module_index {
        for module_name in idx.modules_with_symbol(handler_name) {
            let Some(cached) = idx.get_cached(&module_name) else { continue };
            for sym in &cached.analysis.symbols {
                if sym.name != handler_name { continue; }
                push_sig(&mut signatures, sym, Some(module_name.as_str()));
            }
        }
    }

    if signatures.is_empty() { return None; }
    Some(SignatureHelp {
        signatures,
        active_signature: Some(0),
        active_parameter: Some(active_param.saturating_sub(1) as u32),
    })
}

/// Resolve the class of an invocant expression at a given cursor point.
///   * `$self` / `__PACKAGE__`  → enclosing package at that position
///   * bare `Pkg::Name`         → the literal class
///   * `$var`                   → looked up via `analysis.inferred_type`
/// Returns `None` when the expression doesn't resolve to a known class.
/// Text-driven entry point: resolve invocant → class, then delegate to
/// `string_dispatch_signature_for`. Used for mid-editing states where
/// no DispatchCall ref exists yet.
fn string_dispatch_signature(
    analysis: &FileAnalysis,
    module_index: Option<&ModuleIndex>,
    invocant: Option<&str>,
    dispatcher: &str,
    handler_name: &str,
    active_param: usize,
    point: Point,
) -> Option<SignatureHelp> {
    let class = analysis.invocant_text_to_class(invocant, point)?;
    string_dispatch_signature_for(analysis, module_index, &class, dispatcher, handler_name, active_param)
}

pub fn signature_help(
    analysis: &FileAnalysis,
    tree: &Tree,
    text: &str,
    pos: Position,
    module_index: &ModuleIndex,
) -> Option<SignatureHelp> {
    let point = position_to_point(pos);

    // Plugin query hook — runs BEFORE native sig help. Plugin can
    // show a custom sig (arrayref-wrapped handler args) OR silently
    // claim the slot to suppress native sig (cursor in an options
    // hash of a dispatcher — native would mis-show the task sig).
    let mut skip_string_dispatch = false;
    if let Some(qctx) = cursor_context::build_plugin_query_context(analysis, tree, text.as_bytes(), point) {
        let registry = crate::builder::default_plugin_registry();
        let (uses, parents) = analysis.trigger_view_at(point);
        let query = crate::plugin::TriggerQuery {
            package_uses: &uses,
            package_parents: &parents,
        };
        for p in registry.applicable(&query) {
            match p.on_signature_help(&qctx) {
                Some(crate::plugin::PluginSigHelpAnswer::Show(psig)) => {
                    return Some(plugin_sig_to_lsp(psig));
                }
                Some(crate::plugin::PluginSigHelpAnswer::Silent) => {
                    return None;
                }
                Some(crate::plugin::PluginSigHelpAnswer::ShowHandler {
                    owner_class, dispatcher, handler_name, active_param,
                }) => {
                    // Core-side Handler lookup — same machinery the
                    // native DispatchCall path uses, just triggered by
                    // plugin instead of ref. `active_param` is a
                    // displayed index; `string_dispatch_signature_for`
                    // applies the +1 offset to match its internal
                    // convention (params[0] is invocant, stripped).
                    if let Some(sig) = string_dispatch_signature_for(
                        analysis, Some(module_index),
                        &owner_class, &dispatcher, &handler_name,
                        active_param + 1,
                    ) {
                        return Some(sig);
                    }
                    // Plugin claimed the slot but no Handler was found
                    // — suppress native to avoid fallthrough mis-fires.
                    return None;
                }
                Some(crate::plugin::PluginSigHelpAnswer::ShowCallSig) => {
                    // Plugin recognizes this call but the cursor isn't
                    // in its args slot. Skip the native string-dispatch
                    // fallback (which would key the task's sig off the
                    // OUTER call's positional count) and fall through
                    // to the method's OWN signature.
                    skip_string_dispatch = true;
                    break;
                }
                None => {}
            }
        }
    }

    // Step 1: cursor_context finds the enclosing call
    let call_ctx = cursor_context::find_call_context(tree, text.as_bytes(), point)?;

    // Step 1a: string-dispatch specialization. `$x->emit('ready', CURSOR)`
    // is a method call whose string arg routes to a registered handler;
    // when handler_params are on record for that (class, event_name) pair,
    // surface them instead of the emit() method's own generic signature.
    // Stacked defs (multiple `->on('ready', sub {...})` wire-ups) each
    // contribute one `SignatureInformation` so users see every handler
    // shape they might be dispatching to.
    // Arrayref-wrapped handler args (Minion's `enqueue(task, [@args])`)
    // are handled by the plugin's `on_signature_help` IoC hook earlier
    // in this function — the hook sees the Array container + active
    // slot and returns the task sig. No core-side arrayref branching.

    if !skip_string_dispatch && call_ctx.is_method && call_ctx.active_param >= 1 {
        // Primary path: find the DispatchCall ref the plugin already
        // emitted for this call site. Its `target_name`, `owner`, and
        // `dispatcher` were all computed with the builder's full
        // knowledge — including const-folding `$dynamic` back to
        // `'connect'` — so sig help inherits folding for free and
        // can't drift from what hover shows.
        if let Some((handler_name, owner_class, dispatcher)) =
            dispatch_info_for_enclosing_call(analysis, tree, text.as_bytes(), point)
        {
            if let Some(sig) = string_dispatch_signature_for(
                analysis,
                Some(module_index),
                &owner_class,
                &dispatcher,
                &handler_name,
                call_ctx.active_param,
            ) {
                return Some(sig);
            }
        }

        // Fallback: no DispatchCall ref at this call site (e.g. no plugin
        // declared the method as a dispatcher). Try the text-level
        // first-arg string; this covers mid-editing states where a ref
        // hasn't been emitted yet.
        if let Some(ref name) = call_ctx.first_arg_string {
            if let Some(sig) = string_dispatch_signature(
                analysis,
                Some(module_index),
                call_ctx.invocant.as_deref(),
                &call_ctx.name,
                name,
                call_ctx.active_param,
                point,
            ) {
                return Some(sig);
            }
        }
    }

    // Step 2: file_analysis resolves the sub signature (local + cross-file)
    if let Some(sig_info) = analysis.signature_for_call(
        &call_ctx.name,
        call_ctx.is_method,
        call_ctx.invocant.as_deref(),
        point,
        Some(module_index),
    ) {
        // Build param labels with inferred types
        let param_labels: Vec<String> = sig_info
            .params
            .iter()
            .enumerate()
            .map(|(i, p)| {
                let base = if let Some(ref default) = p.default {
                    format!("{} = {}", p.name, default)
                } else {
                    p.name.clone()
                };
                // Skip $self/$class — type is obvious
                if p.name == "$self" || p.name == "$class" {
                    return base;
                }
                // Cross-file: use pre-resolved param types
                if let Some(ref types) = sig_info.param_types {
                    if let Some(Some(ref type_tag)) = types.get(i) {
                        return format!("{}: {}", base, type_tag);
                    }
                    return base;
                }
                // Local: look up inferred type at end of sub body —
                // route through the witness bag so framework + branch
                // + arity rules refine the answer.
                if let Some(ty) = analysis.inferred_type_via_bag(&p.name, sig_info.body_end) {
                    format!("{}: {}", base, format_inferred_type(&ty))
                } else {
                    base
                }
            })
            .collect();

        let params: Vec<ParameterInformation> = param_labels
            .iter()
            .map(|label| ParameterInformation {
                label: ParameterLabel::Simple(label.clone()),
                documentation: None,
            })
            .collect();

        let label = format!("{}({})", sig_info.name, param_labels.join(", "));

        return Some(SignatureHelp {
            signatures: vec![SignatureInformation {
                label,
                documentation: None,
                parameters: Some(params),
                active_parameter: Some(call_ctx.active_param as u32),
            }],
            active_signature: Some(0),
            active_parameter: Some(call_ctx.active_param as u32),
        });
    }

    None
}

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

// Token type/modifier indices are defined in file_analysis.rs (TOK_*, MOD_*).

pub fn semantic_token_types() -> Vec<SemanticTokenType> {
    vec![
        SemanticTokenType::VARIABLE,       // 0: variables
        SemanticTokenType::PARAMETER,      // 1: sub parameters
        SemanticTokenType::FUNCTION,       // 2: function calls
        SemanticTokenType::METHOD,         // 3: method calls
        SemanticTokenType::MACRO,          // 4: framework DSL keywords
        SemanticTokenType::PROPERTY,       // 5: hash keys
        SemanticTokenType::NAMESPACE,      // 6: package/class names
        SemanticTokenType::REGEXP,         // 7: regex literals
        SemanticTokenType::ENUM_MEMBER,    // 8: constants
        SemanticTokenType::KEYWORD,        // 9: $self/$class
    ]
}

pub fn semantic_token_modifiers() -> Vec<SemanticTokenModifier> {
    vec![
        SemanticTokenModifier::DECLARATION,      // 0
        SemanticTokenModifier::READONLY,         // 1
        SemanticTokenModifier::MODIFICATION,     // 2
        SemanticTokenModifier::DEFAULT_LIBRARY,  // 3
        SemanticTokenModifier::DEPRECATED,       // 4
        SemanticTokenModifier::STATIC,           // 5
        SemanticTokenModifier::new("scalar"),    // 6
        SemanticTokenModifier::new("array"),     // 7
        SemanticTokenModifier::new("hash"),      // 8
    ]
}

/// Returns inlay hints for the given range.
///
/// Shows type annotations for variable declarations with non-obvious inferred types,
/// and return type annotations for sub/method declarations.
pub fn inlay_hints(analysis: &FileAnalysis, range: Range) -> Vec<InlayHint> {
    let start = position_to_point(range.start);
    let end = position_to_point(range.end);
    let mut hints = Vec::new();

    for sym in &analysis.symbols {
        let decl_point = sym.selection_span.end;
        // Skip symbols outside the requested range
        if decl_point.row < start.row || decl_point.row > end.row {
            continue;
        }

        match sym.kind {
            FaSymKind::Variable => {
                // Skip $self — always the enclosing class, too noisy
                if sym.name == "$self" {
                    continue;
                }
                if let Some(ty) = analysis.inferred_type_via_bag(&sym.name, sym.span.start) {
                    // Only show Object/HashRef/ArrayRef/CodeRef/Regexp — not Numeric/String
                    if matches!(ty, InferredType::Numeric | InferredType::String) {
                        continue;
                    }
                    hints.push(InlayHint {
                        position: point_to_position(decl_point),
                        label: InlayHintLabel::String(format!(": {}", format_inferred_type(&ty))),
                        kind: Some(InlayHintKind::TYPE),
                        text_edits: None,
                        tooltip: None,
                        padding_left: Some(true),
                        padding_right: None,
                        data: None,
                    });
                }
            }
            FaSymKind::Sub | FaSymKind::Method => {
                // Plugin-synthesized subs/methods often have
                // return_type set to internal proxy classes (Mojo
                // helpers' `_Helper::users` chain, DBIC ResultSet
                // wrappers, etc.). The kind icon + hover already
                // carry the useful info; the inlay hint just
                // repeats a long dotted class name at every
                // declaration. Suppress it for framework symbols.
                if sym.namespace.is_framework() {
                    continue;
                }
                if matches!(sym.detail, SymbolDetail::Sub { .. }) {
                    if let Some(rt) = analysis.symbol_return_type_via_bag(sym.id, None) {
                        // Only show non-trivial return types
                        if matches!(rt, InferredType::Numeric | InferredType::String) {
                            continue;
                        }
                        hints.push(InlayHint {
                            position: point_to_position(decl_point),
                            label: InlayHintLabel::String(format!(
                                "{}",
                                format_inferred_type(&rt)
                            )),
                            kind: Some(InlayHintKind::TYPE),
                            text_edits: None,
                            tooltip: None,
                            padding_left: Some(true),
                            padding_right: None,
                            data: None,
                        });
                    }
                }
            }
            _ => {}
        }
    }

    hints
}

pub fn semantic_tokens(analysis: &FileAnalysis) -> Vec<SemanticToken> {
    let tokens = analysis.semantic_tokens();

    let mut result = Vec::new();
    let mut prev_line: u32 = 0;
    let mut prev_start: u32 = 0;

    for t in &tokens {
        let line = t.span.start.row as u32;
        let start = t.span.start.column as u32;
        let length = if t.span.start.row == t.span.end.row {
            (t.span.end.column as u32).saturating_sub(start).max(1)
        } else {
            1
        };

        let delta_line = line - prev_line;
        let delta_start = if delta_line == 0 {
            start.saturating_sub(prev_start)
        } else {
            start
        };

        result.push(SemanticToken {
            delta_line,
            delta_start,
            length,
            token_type: t.token_type,
            token_modifiers_bitset: t.modifiers,
        });

        prev_line = line;
        prev_start = start;
    }

    result
}

// ---- Import resolution helpers ----

/// Build completion candidates for functions imported via `use` statements.
/// Offers all @EXPORT_OK from already-imported modules — not just the ones
/// currently in the qw() list. Functions not yet imported get an auto-import
/// edit that adds them to the existing qw() list.
fn imported_function_completions(
    analysis: &FileAnalysis,
    module_index: &ModuleIndex,
) -> Vec<CompletionCandidate> {
    use crate::file_analysis::Span;
    let mut candidates = Vec::new();
    let mut seen = std::collections::HashSet::new();

    for import in &analysis.imports {
        let cached: Option<Arc<CachedModule>> = module_index.get_cached(&import.module_name);

        // 1. Always offer explicitly imported symbols (from the qw list).
        // Dedup/dispatch by LOCAL name (what the user types); resolve
        // detail against REMOTE name (what exists in the source module)
        // so renaming imports like `del` → `delete` show the real doc.
        for is in &import.imported_symbols {
            let local = &is.local_name;
            if !seen.insert(local.clone()) {
                continue;
            }
            if !analysis.symbols_named(local).is_empty() {
                continue;
            }
            let detail = completion_detail_for_import(is.remote(), cached.as_deref(), &import.module_name);
            candidates.push(CompletionCandidate {
                label: local.clone(),
                kind: FaSymKind::Sub,
                detail: Some(detail),
                insert_text: None,
                sort_priority: PRIORITY_EXPLICIT_IMPORT,
                additional_edits: vec![],
                display_override: None,
            });
        }

        // 2. Offer additional @EXPORT_OK functions (not yet imported) if we can resolve the module
        if let Some(ref cached) = cached {
            let fa = &cached.analysis;
            let all_exported: Vec<&String> = if import.imported_symbols.is_empty() {
                // Bare `use Foo;` — offer @EXPORT
                fa.export.iter().collect()
            } else {
                // `use Foo qw(bar)` — offer remaining @EXPORT + @EXPORT_OK
                let mut all = Vec::new();
                all.extend(fa.export.iter());
                all.extend(fa.export_ok.iter());
                all
            };

            for name in all_exported {
                // Skip already-offered (explicitly imported) and locally defined
                if !seen.insert(name.clone()) {
                    continue;
                }
                if !analysis.symbols_named(name).is_empty() {
                    continue;
                }

                let rt_prefix = cached.sub_info(name)
                    .and_then(|s| s.return_type())
                    .map(|rt| format!("{} ", format_inferred_type(&rt)))
                    .unwrap_or_default();

                let (detail, priority, additional_edits) =
                    if let Some(close_pos) = import.qw_close_paren {
                        // Auto-add to existing qw() list
                        let insert_point = Span {
                            start: close_pos,
                            end: close_pos,
                        };
                        (
                            format!("{}{} (auto-import)", rt_prefix, import.module_name),
                            PRIORITY_AUTO_ADD_QW,
                            vec![(insert_point, format!(" {}", name))],
                        )
                    } else {
                        // No qw() list to edit (bare `use Foo;`)
                        (
                            format!("{}imported from {}", rt_prefix, import.module_name),
                            PRIORITY_BARE_IMPORT,
                            vec![],
                        )
                    };

                candidates.push(CompletionCandidate {
                    label: name.clone(),
                    kind: FaSymKind::Sub,
                    detail: Some(detail),
                    insert_text: None,
                    sort_priority: priority,
                    additional_edits,
                    display_override: None,
                });
            }
        }
    }

    candidates
}

/// Build completion candidates for functions from modules that aren't imported
/// at all. Each candidate carries an `additional_edit` that inserts a full
/// `use Module qw(func);` statement.
fn unimported_function_completions(
    analysis: &FileAnalysis,
    module_index: &ModuleIndex,
    point: Point,
    stable_packages: Option<&[(String, usize)]>,
) -> Vec<CompletionCandidate> {
    use crate::file_analysis::Span;
    let mut candidates = Vec::new();

    // Collect already-imported module names so we skip them.
    let imported_modules: std::collections::HashSet<&str> = analysis
        .imports
        .iter()
        .map(|i| i.module_name.as_str())
        .collect();

    let mut insert_pos = find_use_insertion_position(analysis, point, stable_packages);

    // If the computed position is after the cursor, fall back to inserting
    // after the nearest import or package statement ABOVE the cursor.
    if insert_pos.line as usize > point.row {
        // Find the last import above the cursor
        let last_import_above = analysis.imports.iter().rev()
            .find(|imp| imp.span.start.row < point.row);
        if let Some(imp) = last_import_above {
            insert_pos = Position { line: imp.span.end.row as u32 + 1, character: 0 };
        } else {
            // Find the last package statement above the cursor
            let last_pkg_above = analysis.symbols.iter().rev()
                .find(|s| matches!(s.kind, FaSymKind::Package | FaSymKind::Class) && s.selection_span.start.row < point.row);
            if let Some(pkg) = last_pkg_above {
                insert_pos = Position { line: pkg.selection_span.start.row as u32 + 1, character: 0 };
            }
            // else: keep original position (top of file)
        }
    }

    let insert_span = Span {
        start: tree_sitter::Point {
            row: insert_pos.line as usize,
            column: insert_pos.character as usize,
        },
        end: tree_sitter::Point {
            row: insert_pos.line as usize,
            column: insert_pos.character as usize,
        },
    };

    module_index.for_each_cached(|module_name, cached| {
        if imported_modules.contains(module_name) {
            return;
        }

        let fa = &cached.analysis;
        let all_exported = fa.export.iter().chain(fa.export_ok.iter());
        for name in all_exported {
            // Skip functions already defined locally
            if !analysis.symbols_named(name).is_empty() {
                continue;
            }
            candidates.push(CompletionCandidate {
                label: name.clone(),
                kind: FaSymKind::Sub,
                detail: Some(format!("{} (auto-import)", module_name)),
                insert_text: None,
                sort_priority: PRIORITY_UNIMPORTED,
                additional_edits: vec![(
                    insert_span,
                    format!("use {} qw({});\n", module_name, name),
                )],
                display_override: None,
            });
        }
    });

    // Sort for deterministic order
    candidates.sort_by(|a, b| a.label.cmp(&b.label).then(a.detail.cmp(&b.detail)));
    candidates
}

/// Find which import provides a given function name.
/// Checks both explicitly imported symbols and all @EXPORT/@EXPORT_OK
/// from already-imported modules. Single DashMap lookup per module.
///
/// Returns the matched Import, the module's path, and the REMOTE name
/// (the sub's actual name in the source module — differs from the
/// caller's `func_name` only for renaming imports like `del` → `delete`).
/// Callers use the remote name for `cached.sub_info(...)` lookups so
/// hover/gd/sig-help reach the real sub.
fn resolve_imported_function<'a>(
    analysis: &'a FileAnalysis,
    func_name: &str,
    module_index: &ModuleIndex,
) -> Option<(&'a crate::file_analysis::Import, std::path::PathBuf, String)> {
    for import in &analysis.imports {
        if let Some(cached) = module_index.get_cached(&import.module_name) {
            let explicit = import.imported_symbols.iter().find(|s| s.local_name == *func_name);
            if let Some(is) = explicit {
                return Some((import, cached.path.clone(), is.remote().to_string()));
            }
            // Export lists are always in the remote namespace — a name
            // appearing there matches a same-name use at the call site.
            let in_export_lists = cached.analysis.export.iter().any(|s| s == func_name)
                || cached.analysis.export_ok.iter().any(|s| s == func_name);
            if in_export_lists {
                return Some((import, cached.path.clone(), func_name.to_string()));
            }
        } else if let Some(is) = import.imported_symbols.iter().find(|s| s.local_name == *func_name) {
            // Module not cached yet but explicitly listed in qw() — trust the import.
            if let Some(path) = module_index.module_path_cached(&import.module_name) {
                return Some((import, path, is.remote().to_string()));
            }
        }
    }
    None
}

fn completion_detail_for_import(
    name: &str,
    cached: Option<&CachedModule>,
    module_name: &str,
) -> String {
    if let Some(cached) = cached {
        if let Some(sub_info) = cached.sub_info(name) {
            if let Some(rt) = sub_info.return_type() {
                return format!("{} ({})", format_inferred_type(&rt), module_name);
            }
        }
    }
    format!("imported from {}", module_name)
}

fn format_imported_signature(name: &str, sub_info: &SubInfo<'_>) -> String {
    let params_str = sub_info
        .params()
        .iter()
        .map(|p| p.name.as_str())
        .collect::<Vec<_>>()
        .join(", ");
    let mut sig = format!("sub {}({})", name, params_str);
    if let Some(rt) = sub_info.return_type() {
        sig.push_str(&format!("{}", format_inferred_type(&rt)));
    }
    sig
}

// ---- Diagnostics ----

/// Sorted list of Perl built-in functions. Used to avoid false-positive
/// "unresolved function" diagnostics. Checked via binary_search.
static PERL_BUILTINS: &[&str] = &[
    "abs", "accept", "alarm", "atan2",
    "bind", "binmode", "bless",
    "caller", "chdir", "chmod", "chomp", "chop", "chown", "chr", "chroot", "close",
    "closedir", "connect", "cos", "crypt",
    "dbmclose", "dbmopen", "defined", "delete", "die", "do", "dump",
    "each", "endgrent", "endhostent", "endnetent", "endprotoent", "endpwent",
    "endservent", "eof", "eval", "exec", "exists", "exit",
    "fcntl", "fileno", "flock", "fork", "format", "formline",
    "getc", "getgrent", "getgrgid", "getgrnam", "gethostbyaddr", "gethostbyname",
    "gethostent", "getlogin", "getnetbyaddr", "getnetbyname", "getnetent",
    "getpeername", "getpgrp", "getppid", "getpriority", "getprotobyname",
    "getprotobynumber", "getprotoent", "getpwent", "getpwnam", "getpwuid",
    "getservbyname", "getservbyport", "getservent", "getsockname", "getsockopt",
    "glob", "gmtime", "goto", "grep",
    "hex",
    "import", "index", "int", "ioctl",
    "join",
    "keys", "kill",
    "last", "lc", "lcfirst", "length", "link", "listen", "local", "localtime", "log",
    "lstat",
    "map", "mkdir", "msgctl", "msgget", "msgrcv", "msgsnd",
    "my",
    "new", "next", "no",
    "oct", "open", "opendir", "ord", "our",
    "pack", "pipe", "pop", "pos", "print", "printf", "prototype", "push",
    "quotemeta",
    "rand", "read", "readdir", "readline", "readlink", "readpipe", "recv", "redo",
    "ref", "rename", "require", "reset", "return", "reverse", "rewinddir", "rindex",
    "rmdir",
    "say", "scalar", "seek", "seekdir", "select", "semctl", "semget", "semop", "send",
    "setgrent", "sethostent", "setnetent", "setpgrp", "setpriority", "setprotoent",
    "setpwent", "setservent", "setsockopt", "shift", "shmctl", "shmget", "shmread",
    "shmwrite", "shutdown", "sin", "sleep", "socket", "socketpair", "sort", "splice",
    "split", "sprintf", "sqrt", "srand", "stat", "state", "study", "sub", "substr",
    "symlink", "syscall", "sysopen", "sysread", "sysseek", "system", "syswrite",
    "tell", "telldir", "tie", "tied", "time", "times", "truncate",
    "uc", "ucfirst", "umask", "undef", "unlink", "unpack", "unshift", "untie", "use",
    "utime",
    "values", "vec",
    "wait", "waitpid", "wantarray", "warn", "write",
];

fn is_perl_builtin(name: &str) -> bool {
    PERL_BUILTINS.binary_search(&name).is_ok()
}


pub fn collect_diagnostics(analysis: &FileAnalysis, module_index: &ModuleIndex) -> Vec<Diagnostic> {
    let mut diagnostics = Vec::new();

    for r in &analysis.refs {
        if !matches!(r.kind, RefKind::FunctionCall { .. }) {
            continue;
        }
        let name = &r.target_name;

        // Skip package-qualified calls like Foo::bar()
        if name.contains("::") {
            continue;
        }

        // Skip code deref calls like &{$var}()
        if name.starts_with('&') {
            continue;
        }

        // Skip Perl builtins
        if is_perl_builtin(name) {
            continue;
        }

        // Skip locally defined subs
        if !analysis.symbols_named(name).is_empty() {
            continue;
        }

        // Skip functions implicitly imported by OOP frameworks (has, extends, etc.)
        if analysis.framework_imports.contains(name.as_str()) {
            continue;
        }

        // Skip if explicitly listed in any import's qw(...),
        // or auto-imported via @EXPORT on a bare `use Foo;` (no qw list).
        let explicitly_imported = analysis.imports.iter().any(|imp| {
            if imp.imported_symbols.iter().any(|s| s.local_name == *name) {
                return true;
            }
            // Bare `use Foo;` — check if function is in @EXPORT (auto-imported)
            if imp.imported_symbols.is_empty() {
                if let Some(cached) = module_index.get_cached(&imp.module_name) {
                    if cached.analysis.export.iter().any(|s| s == name) {
                        return true;
                    }
                }
            }
            false
        });
        if explicitly_imported {
            continue;
        }

        // Check if an imported module exports this function
        let range = span_to_range(r.span);
        if let Some((import, _path, _remote)) = resolve_imported_function(analysis, name, module_index) {
            // Importable but not yet in the qw() list → actionable hint
            diagnostics.push(Diagnostic {
                range,
                severity: Some(DiagnosticSeverity::HINT),
                code: Some(NumberOrString::String("unresolved-function".into())),
                source: Some("perl-lsp".into()),
                message: format!(
                    "'{}' is exported by {} but not imported",
                    name, import.module_name,
                ),
                data: Some(serde_json::json!({
                    "module": import.module_name,
                    "function": name,
                })),
                ..Default::default()
            });
        } else {
            // Search ALL cached modules for this function.
            let exporters = module_index.find_exporters(name);
            if !exporters.is_empty() {
                let msg = if exporters.len() == 1 {
                    format!(
                        "'{}' is exported by {} (not yet imported)",
                        name, exporters[0],
                    )
                } else {
                    format!(
                        "'{}' is exported by {} and {} other module(s)",
                        name,
                        exporters[0],
                        exporters.len() - 1,
                    )
                };
                diagnostics.push(Diagnostic {
                    range,
                    severity: Some(DiagnosticSeverity::HINT),
                    code: Some(NumberOrString::String("unresolved-function".into())),
                    source: Some("perl-lsp".into()),
                    message: msg,
                    data: Some(serde_json::json!({
                        "modules": exporters,
                        "function": name,
                    })),
                    ..Default::default()
                });
            } else {
                diagnostics.push(Diagnostic {
                    range,
                    severity: Some(DiagnosticSeverity::INFORMATION),
                    code: Some(NumberOrString::String("unresolved-function".into())),
                    source: Some("perl-lsp".into()),
                    message: format!("'{}' is not defined in this file", name),
                    ..Default::default()
                });
            }
        }
    }

    // 5e: Unresolved method diagnostics for locally-defined classes
    let universal_methods = [
        "new", "AUTOLOAD", "DESTROY", "can", "isa", "DOES", "VERSION",
        // DBIC meta-methods (inherited from DBIx::Class::Core)
        "add_columns", "add_column", "set_primary_key", "table", "resultset_class",
        "has_many", "has_one", "belongs_to", "might_have", "many_to_many",
        "load_components",
        // Moose/Moo meta-methods
        "meta",
    ];
    for r in &analysis.refs {
        let (invocant, _invocant_span) = match &r.kind {
            RefKind::MethodCall { invocant, invocant_span, .. } => (invocant, invocant_span),
            _ => continue,
        };
        let method_name = &r.target_name;

        // Skip universal methods
        if universal_methods.contains(&method_name.as_str()) {
            continue;
        }

        // Resolve invocant to class name
        let class_name = if !invocant.starts_with('$')
            && !invocant.starts_with('@')
            && !invocant.starts_with('%')
        {
            Some(invocant.clone())
        } else {
            analysis.inferred_type_via_bag(invocant, r.span.start)
                .and_then(|ty| ty.class_name().map(|s| s.to_string()))
        };
        let class_name = match class_name {
            Some(cn) => cn,
            None => continue,
        };

        // Only fire for locally-defined classes
        let is_local_class = analysis.symbols.iter().any(|s| {
            matches!(s.kind, FaSymKind::Class | FaSymKind::Package) && s.name == class_name
        });
        if !is_local_class {
            continue;
        }

        // Check the class has at least one method (otherwise likely external)
        let has_methods = analysis.symbols.iter().any(|s| {
            matches!(s.kind, FaSymKind::Sub | FaSymKind::Method)
                && analysis.symbol_in_class(s.id, &class_name)
        });
        if !has_methods {
            continue;
        }

        // Check if the method exists in the class (walks inheritance chain)
        if analysis.resolve_method_in_ancestors(&class_name, method_name, Some(module_index)).is_some() {
            continue;
        }

        diagnostics.push(Diagnostic {
            range: span_to_range(r.span),
            severity: Some(DiagnosticSeverity::HINT),
            code: Some(NumberOrString::String("unresolved-method".into())),
            source: Some("perl-lsp".into()),
            message: format!(
                "'{}' is not defined in {}",
                method_name, class_name,
            ),
            ..Default::default()
        });
    }

    diagnostics
}

// ---- Code actions ----

/// Find the position to insert a new `use` statement, scoped to the package at `point`.
/// Uses line-range approach: finds which package range the cursor is in,
/// then inserts after the last `use` in that range.
/// `stable_packages` provides fallback package lines from the stable outline
/// when the current parse lost packages due to error recovery.
fn find_use_insertion_position(
    analysis: &FileAnalysis,
    point: Point,
    stable_packages: Option<&[(String, usize)]>,
) -> Position {
    // Collect package declaration lines from current parse
    let mut pkg_lines: Vec<usize> = analysis.symbols.iter()
        .filter(|s| matches!(s.kind, FaSymKind::Package | FaSymKind::Class))
        .map(|s| s.selection_span.start.row)
        .collect();

    // If the stable outline has MORE packages than the current parse,
    // merge them in — the parse lost some due to error recovery.
    if let Some(stable) = stable_packages {
        if stable.len() > pkg_lines.len() {
            for (_, line) in stable {
                if !pkg_lines.contains(line) {
                    pkg_lines.push(*line);
                }
            }
        }
    }
    pkg_lines.sort();

    // Find the package range containing `point`
    let pkg_start = pkg_lines.iter().rev()
        .find(|&&line| line <= point.row)
        .copied()
        .unwrap_or(0);
    let pkg_end = pkg_lines.iter()
        .find(|&&line| line > point.row)
        .copied()
        .unwrap_or(usize::MAX);

    // Find the last import within this package's line range
    let last_import = analysis.imports.iter().rev().find(|imp| {
        imp.span.start.row >= pkg_start && imp.span.start.row < pkg_end
    });

    if let Some(imp) = last_import {
        Position {
            line: imp.span.end.row as u32 + 1,
            character: 0,
        }
    } else {
        // No imports in this package range — insert after the package statement
        Position {
            line: pkg_start as u32 + 1,
            character: 0,
        }
    }
}

pub fn code_actions(
    diagnostics: &[Diagnostic],
    analysis: &FileAnalysis,
    uri: &Url,
) -> Vec<CodeActionOrCommand> {
    let mut actions = Vec::new();

    for diag in diagnostics {
        let code_matches = matches!(
            &diag.code,
            Some(NumberOrString::String(s)) if s == "unresolved-function"
        );
        if !code_matches {
            continue;
        }
        let data = match &diag.data {
            Some(d) => d,
            None => continue,
        };
        let func_name = match data.get("function").and_then(|v| v.as_str()) {
            Some(f) => f,
            None => continue,
        };

        // Case 1: Already-imported module — add function to existing qw() list
        if let Some(module_name) = data.get("module").and_then(|v| v.as_str()) {
            if let Some(action) =
                make_add_to_qw_action(analysis, uri, diag, module_name, func_name)
            {
                actions.push(action);
            }
            continue;
        }

        // Case 2: New import — add `use Module qw(func);` statement
        if let Some(modules) = data.get("modules").and_then(|v| v.as_array()) {
            let diag_point = position_to_point(diag.range.start);
            let mut insert_pos = find_use_insertion_position(analysis, diag_point, None);
            // If position is after the diagnostic, fall back to nearest import/package above
            if insert_pos.line > diag.range.start.line {
                let last_import_above = analysis.imports.iter().rev()
                    .find(|imp| imp.span.start.row < diag_point.row);
                if let Some(imp) = last_import_above {
                    insert_pos = Position { line: imp.span.end.row as u32 + 1, character: 0 };
                } else {
                    let last_pkg_above = analysis.symbols.iter().rev()
                        .find(|s| matches!(s.kind, FaSymKind::Package | FaSymKind::Class) && s.selection_span.start.row < diag_point.row);
                    if let Some(pkg) = last_pkg_above {
                        insert_pos = Position { line: pkg.selection_span.start.row as u32 + 1, character: 0 };
                    }
                }
            }
            for (i, module_val) in modules.iter().enumerate() {
                if let Some(module_name) = module_val.as_str() {
                    let new_text = format!("use {} qw({});\n", module_name, func_name);
                    let edit = TextEdit {
                        range: Range {
                            start: insert_pos,
                            end: insert_pos,
                        },
                        new_text,
                    };
                    let mut changes = HashMap::new();
                    changes.insert(uri.clone(), vec![edit]);

                    actions.push(CodeActionOrCommand::CodeAction(CodeAction {
                        title: format!("Add 'use {} qw({})'", module_name, func_name),
                        kind: Some(CodeActionKind::QUICKFIX),
                        diagnostics: Some(vec![diag.clone()]),
                        edit: Some(WorkspaceEdit {
                            changes: Some(changes),
                            ..Default::default()
                        }),
                        is_preferred: Some(i == 0 && modules.len() == 1),
                        ..Default::default()
                    }));
                }
            }
        }
    }

    actions
}

/// Generate a code action that adds a function to an existing `qw()` import list.
fn make_add_to_qw_action(
    analysis: &FileAnalysis,
    uri: &Url,
    diag: &Diagnostic,
    module_name: &str,
    func_name: &str,
) -> Option<CodeActionOrCommand> {
    let import = analysis
        .imports
        .iter()
        .find(|imp| imp.module_name == module_name)?;
    let close_pos = import.qw_close_paren?;
    let insert_pos = point_to_position(close_pos);
    let edit = TextEdit {
        range: Range {
            start: insert_pos,
            end: insert_pos,
        },
        new_text: format!(" {}", func_name),
    };
    let mut changes = HashMap::new();
    changes.insert(uri.clone(), vec![edit]);
    Some(CodeActionOrCommand::CodeAction(CodeAction {
        title: format!("Import '{}' from {}", func_name, module_name),
        kind: Some(CodeActionKind::QUICKFIX),
        diagnostics: Some(vec![diag.clone()]),
        edit: Some(WorkspaceEdit {
            changes: Some(changes),
            ..Default::default()
        }),
        is_preferred: Some(true),
        ..Default::default()
    }))
}

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