phpantom_lsp 0.7.0

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

use crate::common::{create_test_backend, create_test_backend_with_stubs};
use phpantom_lsp::Backend;
use phpantom_lsp::php_type::PhpType;
use tower_lsp::LanguageServer;
use tower_lsp::lsp_types::*;

// ─── Helper ─────────────────────────────────────────────────────────────────

/// Open a file in the backend and request completion at the given position.
async fn complete_at(
    backend: &Backend,
    uri: &Url,
    text: &str,
    line: u32,
    character: u32,
) -> Vec<CompletionItem> {
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: text.to_string(),
            },
        })
        .await;

    let result = backend
        .completion(CompletionParams {
            text_document_position: TextDocumentPositionParams {
                text_document: TextDocumentIdentifier { uri: uri.clone() },
                position: Position { line, character },
            },
            work_done_progress_params: WorkDoneProgressParams::default(),
            partial_result_params: PartialResultParams::default(),
            context: None,
        })
        .await
        .unwrap();

    match result {
        Some(CompletionResponse::Array(items)) => items,
        Some(CompletionResponse::List(list)) => list.items,
        None => vec![],
    }
}

/// Filter completion items to only those with kind == CLASS.
fn class_items(items: &[CompletionItem]) -> Vec<&CompletionItem> {
    items
        .iter()
        .filter(|i| i.kind == Some(CompletionItemKind::CLASS))
        .collect()
}

/// Extract labels from a list of completion items.
fn labels(items: &[CompletionItem]) -> Vec<&str> {
    items.iter().map(|i| i.label.as_str()).collect()
}

/// Find a completion item by its FQN (stored in the `detail` field).
fn find_by_fqn<'a>(items: &'a [&CompletionItem], fqn: &str) -> Option<&'a CompletionItem> {
    items
        .iter()
        .find(|i| i.detail.as_deref() == Some(fqn))
        .copied()
}

/// Extract FQNs from a list of completion items (via the `detail` field).
fn fqn_labels<'a>(items: &'a [&'a CompletionItem]) -> Vec<&'a str> {
    items.iter().filter_map(|i| i.detail.as_deref()).collect()
}

/// Load scaffolding classes into the backend's ast_map so the context
/// filter can inspect their `ClassLikeKind` / `is_final` / `is_abstract`.
async fn load_scaffolding(backend: &Backend) {
    let scaffolding_uri = Url::parse("file:///scaffolding.php").unwrap();
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: scaffolding_uri,
                language_id: "php".to_string(),
                version: 1,
                text: concat!(
                    "<?php\n",
                    "namespace Scaffold;\n",
                    "class ConcreteClass {}\n",
                    "final class FinalClass {}\n",
                    "abstract class AbstractClass {}\n",
                    "interface SomeInterface {}\n",
                    "interface AnotherInterface {}\n",
                    "trait SomeTrait {}\n",
                    "trait AnotherTrait {}\n",
                    "enum SomeEnum {}\n",
                )
                .to_string(),
            },
        })
        .await;
}

// ─── extends (class) ────────────────────────────────────────────────────────

/// `extends` in a class declaration should include non-final classes
/// and exclude interfaces, traits, enums, and final classes.
#[tokio::test]
async fn test_extends_class_excludes_interface() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_ext_cls.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\nclass Foo extends Some";

    let items = complete_at(&backend, &uri, text, 2, 25).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"SomeInterface"),
        "extends (class) should not offer interfaces, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"SomeTrait"),
        "extends (class) should not offer traits, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"SomeEnum"),
        "extends (class) should not offer enums, got: {lbls:?}"
    );
}

/// `extends` in a class should exclude final classes.
#[tokio::test]
async fn test_extends_class_excludes_final() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_ext_final.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\nclass Foo extends Final";

    let items = complete_at(&backend, &uri, text, 2, 25).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"FinalClass"),
        "extends (class) should not offer final classes, got: {lbls:?}"
    );
}

/// `extends` in a class should include abstract classes (they are valid
/// extension targets).
#[tokio::test]
async fn test_extends_class_includes_abstract() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_ext_abs.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\nclass Foo extends Abstract";

    let items = complete_at(&backend, &uri, text, 2, 29).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"AbstractClass"),
        "extends (class) should offer abstract classes, got: {lbls:?}"
    );
}

/// `extends` in a class should include concrete non-final classes.
#[tokio::test]
async fn test_extends_class_includes_concrete() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_ext_conc.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\nclass Foo extends Concrete";

    let items = complete_at(&backend, &uri, text, 2, 29).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"ConcreteClass"),
        "extends (class) should offer concrete classes, got: {lbls:?}"
    );
}

/// `extends` in an `abstract class` declaration should still be
/// detected as a class extends context.
#[tokio::test]
async fn test_extends_abstract_class_filters() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_ext_abscls.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\nabstract class Foo extends Some";

    let items = complete_at(&backend, &uri, text, 2, 34).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"SomeInterface"),
        "extends after abstract class should not offer interfaces, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"SomeTrait"),
        "extends after abstract class should not offer traits, got: {lbls:?}"
    );
}

/// `extends` after `final class` should also work correctly.
#[tokio::test]
async fn test_extends_final_class_filters() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    // Note: `final class Foo extends ...` is technically odd
    // (the result is a final class extending something), but PHP allows it.
    let uri = Url::parse("file:///test_ext_fincls.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\nfinal class Foo extends Some";

    let items = complete_at(&backend, &uri, text, 2, 31).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"SomeInterface"),
        "extends after final class should not offer interfaces, got: {lbls:?}"
    );
}

// ─── extends (interface) ────────────────────────────────────────────────────

/// `extends` in an interface declaration should only offer interfaces.
#[tokio::test]
async fn test_extends_interface_only_interfaces() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_ext_iface.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\ninterface Foo extends Some";

    let items = complete_at(&backend, &uri, text, 2, 29).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"SomeInterface"),
        "extends (interface) should offer interfaces, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"ConcreteClass"),
        "extends (interface) should not offer classes, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"SomeTrait"),
        "extends (interface) should not offer traits, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"SomeEnum"),
        "extends (interface) should not offer enums, got: {lbls:?}"
    );
}

/// `extends` in an interface with comma-separated parents should still
/// filter to interfaces only.
#[tokio::test]
async fn test_extends_interface_comma_separated() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_ext_iface_comma.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\ninterface Foo extends SomeInterface, Another";

    let items = complete_at(&backend, &uri, text, 2, 47).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"AnotherInterface"),
        "extends (interface) with comma should offer interfaces, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"AnotherTrait"),
        "extends (interface) with comma should not offer traits, got: {lbls:?}"
    );
}

// ─── implements ─────────────────────────────────────────────────────────────

/// `implements` should only offer interfaces.
#[tokio::test]
async fn test_implements_only_interfaces() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_impl.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\nclass Foo implements Some";

    let items = complete_at(&backend, &uri, text, 2, 28).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"SomeInterface"),
        "implements should offer interfaces, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"ConcreteClass"),
        "implements should not offer classes, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"SomeTrait"),
        "implements should not offer traits, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"SomeEnum"),
        "implements should not offer enums, got: {lbls:?}"
    );
}

/// `implements` with comma-separated interfaces.
#[tokio::test]
async fn test_implements_comma_separated() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_impl_comma.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\nclass Foo implements SomeInterface, Another";

    let items = complete_at(&backend, &uri, text, 2, 44).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"AnotherInterface"),
        "implements with comma should offer interfaces, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"AnotherTrait"),
        "implements with comma should not offer traits, got: {lbls:?}"
    );
}

/// `implements` should suppress constants and functions.
#[tokio::test]
async fn test_implements_excludes_constants_and_functions() {
    let backend = crate::common::create_test_backend_with_function_stubs();

    let uri = Url::parse("file:///test_impl_no_const.php").unwrap();
    let text = "<?php\nclass Foo implements str";

    let items = complete_at(&backend, &uri, text, 1, 27).await;

    // Functions like str_contains should NOT appear.
    let func_items: Vec<&CompletionItem> = items
        .iter()
        .filter(|i| i.kind == Some(CompletionItemKind::FUNCTION))
        .collect();
    assert!(
        func_items.is_empty(),
        "implements should not offer functions, got: {:?}",
        labels(&items)
    );

    let const_items: Vec<&CompletionItem> = items
        .iter()
        .filter(|i| i.kind == Some(CompletionItemKind::CONSTANT))
        .collect();
    assert!(
        const_items.is_empty(),
        "implements should not offer constants, got: {:?}",
        labels(&items)
    );
}

// ─── use (trait) ────────────────────────────────────────────────────────────

/// `use` inside a class body should only offer traits.
#[tokio::test]
async fn test_trait_use_only_traits() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_trait_use.php").unwrap();
    let text = concat!(
        "<?php\n",
        "namespace Scaffold;\n",
        "class Bar {\n",
        "    use Some\n",
        "}\n",
    );

    let items = complete_at(&backend, &uri, text, 3, 12).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"SomeTrait"),
        "trait use should offer traits, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"SomeInterface"),
        "trait use should not offer interfaces, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"ConcreteClass"),
        "trait use should not offer classes, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"SomeEnum"),
        "trait use should not offer enums, got: {lbls:?}"
    );
}

/// `use` inside a class body with comma-separated traits.
#[tokio::test]
async fn test_trait_use_comma_separated() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_trait_use_comma.php").unwrap();
    let text = concat!(
        "<?php\n",
        "namespace Scaffold;\n",
        "class Bar {\n",
        "    use SomeTrait, Another\n",
        "}\n",
    );

    let items = complete_at(&backend, &uri, text, 3, 26).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"AnotherTrait"),
        "trait use with comma should offer traits, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"AnotherInterface"),
        "trait use with comma should not offer interfaces, got: {lbls:?}"
    );
}

/// Top-level `use` (namespace import) should NOT filter — show everything.
#[tokio::test]
async fn test_top_level_use_no_filter() {
    let backend = create_test_backend();

    // Load classes in a namespace so they appear in class name completions
    // when the test file types a `use` import for them.
    let scaffolding_uri = Url::parse("file:///ns_scaffolding.php").unwrap();
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: scaffolding_uri,
                language_id: "php".to_string(),
                version: 1,
                text: concat!(
                    "<?php\n",
                    "namespace Qx;\n",
                    "class QxConcreteClass {}\n",
                    "interface QxSomeInterface {}\n",
                    "trait QxSomeTrait {}\n",
                    "enum QxSomeEnum {}\n",
                )
                .to_string(),
            },
        })
        .await;

    let uri = Url::parse("file:///test_ns_use.php").unwrap();
    let text = "<?php\nuse Qx";

    let items = complete_at(&backend, &uri, text, 1, 6).await;
    let cls = class_items(&items);
    // Top-level `use` should offer all kinds: classes, interfaces,
    // traits, and enums — no kind-filtering should be applied.
    // Labels are FQNs in UseImport context because the user is writing
    // a fully-qualified import statement.
    // Labels may be short names or FQNs depending on whether the prefix
    // contains a namespace separator.  Use the `detail` field (which
    // always holds the FQN) for reliable lookup.
    let fqns = fqn_labels(&cls);
    assert!(
        fqns.contains(&"Qx\\QxConcreteClass"),
        "top-level use should offer classes, got: {fqns:?}"
    );
    assert!(
        fqns.contains(&"Qx\\QxSomeInterface"),
        "top-level use should offer interfaces, got: {fqns:?}"
    );
    assert!(
        fqns.contains(&"Qx\\QxSomeTrait"),
        "top-level use should offer traits, got: {fqns:?}"
    );
    assert!(
        fqns.contains(&"Qx\\QxSomeEnum"),
        "top-level use should offer enums, got: {fqns:?}"
    );
}

/// `use` inside a class body should suppress constants and functions.
#[tokio::test]
async fn test_trait_use_excludes_constants_and_functions() {
    let backend = crate::common::create_test_backend_with_function_stubs();

    let uri = Url::parse("file:///test_trait_use_no_fn.php").unwrap();
    let text = concat!("<?php\n", "class Foo {\n", "    use str\n", "}\n",);

    let items = complete_at(&backend, &uri, text, 2, 11).await;

    let func_items: Vec<&CompletionItem> = items
        .iter()
        .filter(|i| i.kind == Some(CompletionItemKind::FUNCTION))
        .collect();
    assert!(
        func_items.is_empty(),
        "trait use should not offer functions, got: {:?}",
        labels(&items)
    );
}

// ─── instanceof ─────────────────────────────────────────────────────────────

/// `instanceof` should offer classes, interfaces, and enums but NOT traits.
#[tokio::test]
async fn test_instanceof_excludes_traits() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_instanceof.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\n$x instanceof Some";

    let items = complete_at(&backend, &uri, text, 2, 18).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"SomeTrait"),
        "instanceof should not offer traits, got: {lbls:?}"
    );
}

/// `instanceof` should include interfaces.
#[tokio::test]
async fn test_instanceof_includes_interfaces() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_instanceof_iface.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\n$x instanceof Some";

    let items = complete_at(&backend, &uri, text, 2, 18).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"SomeInterface"),
        "instanceof should offer interfaces, got: {lbls:?}"
    );
}

/// `instanceof` should include classes.
#[tokio::test]
async fn test_instanceof_includes_classes() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_instanceof_cls.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\n$x instanceof Concrete";

    let items = complete_at(&backend, &uri, text, 2, 21).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"ConcreteClass"),
        "instanceof should offer classes, got: {lbls:?}"
    );
}

/// `instanceof` should include enums.
#[tokio::test]
async fn test_instanceof_includes_enums() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_instanceof_enum.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\n$x instanceof Some";

    let items = complete_at(&backend, &uri, text, 2, 18).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"SomeEnum"),
        "instanceof should offer enums, got: {lbls:?}"
    );
}

/// `instanceof` should suppress constants and functions.
#[tokio::test]
async fn test_instanceof_excludes_constants_and_functions() {
    let backend = crate::common::create_test_backend_with_function_stubs();

    let uri = Url::parse("file:///test_instanceof_no_fn.php").unwrap();
    let text = "<?php\n$x instanceof str";

    let items = complete_at(&backend, &uri, text, 1, 17).await;

    let func_items: Vec<&CompletionItem> = items
        .iter()
        .filter(|i| i.kind == Some(CompletionItemKind::FUNCTION))
        .collect();
    assert!(
        func_items.is_empty(),
        "instanceof should not offer functions, got: {:?}",
        labels(&items)
    );
}

// ─── extends (class) suppresses constants/functions ─────────────────────────

/// `extends` should suppress constants and functions.
#[tokio::test]
async fn test_extends_excludes_constants_and_functions() {
    let backend = crate::common::create_test_backend_with_function_stubs();

    let uri = Url::parse("file:///test_ext_no_fn.php").unwrap();
    let text = "<?php\nclass Foo extends str";

    let items = complete_at(&backend, &uri, text, 1, 24).await;

    let func_items: Vec<&CompletionItem> = items
        .iter()
        .filter(|i| i.kind == Some(CompletionItemKind::FUNCTION))
        .collect();
    assert!(
        func_items.is_empty(),
        "extends should not offer functions, got: {:?}",
        labels(&items)
    );
}

// ─── Multi-line declarations ────────────────────────────────────────────────

/// `implements` on the next line after the class declaration.
#[tokio::test]
async fn test_implements_multiline() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_impl_ml.php").unwrap();
    let text = concat!(
        "<?php\n",
        "namespace Scaffold;\n",
        "class Foo\n",
        "    implements Some\n",
    );

    let items = complete_at(&backend, &uri, text, 3, 19).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"SomeInterface"),
        "multi-line implements should offer interfaces, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"ConcreteClass"),
        "multi-line implements should not offer classes, got: {lbls:?}"
    );
}

/// `extends` on the next line after `class Foo`.
#[tokio::test]
async fn test_extends_multiline() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_ext_ml.php").unwrap();
    let text = concat!(
        "<?php\n",
        "namespace Scaffold;\n",
        "class Foo\n",
        "    extends Concrete\n",
    );

    let items = complete_at(&backend, &uri, text, 3, 20).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"ConcreteClass"),
        "multi-line extends should offer classes, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"SomeInterface"),
        "multi-line extends should not offer interfaces, got: {lbls:?}"
    );
}

/// `implements` with comma-separated interfaces across lines.
#[tokio::test]
async fn test_implements_multiline_comma() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_impl_ml_comma.php").unwrap();
    let text = concat!(
        "<?php\n",
        "namespace Scaffold;\n",
        "class Foo implements\n",
        "    SomeInterface,\n",
        "    Another\n",
    );

    let items = complete_at(&backend, &uri, text, 4, 11).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"AnotherInterface"),
        "multi-line implements comma should offer interfaces, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"AnotherTrait"),
        "multi-line implements comma should not offer traits, got: {lbls:?}"
    );
}

// ─── new context still works ────────────────────────────────────────────────

/// The `new` context detection should still work via `detect_class_name_context`.
#[tokio::test]
async fn test_new_context_still_filters() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_new_ctx.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\nnew Some";

    let items = complete_at(&backend, &uri, text, 2, 8).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"SomeInterface"),
        "new should not offer interfaces, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"SomeTrait"),
        "new should not offer traits, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"SomeEnum"),
        "new should not offer enums, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"AbstractClass"),
        "new should not offer abstract classes, got: {lbls:?}"
    );
}

// ─── Default context ────────────────────────────────────────────────────────

/// In a plain context (no keyword), all class-like types should appear.
#[tokio::test]
async fn test_plain_context_offers_everything() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_plain.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\nSome";

    let items = complete_at(&backend, &uri, text, 2, 4).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"SomeInterface"),
        "plain context should offer interfaces, got: {lbls:?}"
    );
    assert!(
        lbls.contains(&"SomeTrait"),
        "plain context should offer traits, got: {lbls:?}"
    );
    assert!(
        lbls.contains(&"SomeEnum"),
        "plain context should offer enums, got: {lbls:?}"
    );
}

// ─── Unloaded classes pass through ──────────────────────────────────────────

/// Classes that are not loaded (only in class_index) should pass through
/// the filter since their kind is unknown.
#[tokio::test]
async fn test_unloaded_classes_pass_through_filter() {
    let backend = create_test_backend_with_stubs();

    // Put a class in the class_index but do NOT load it into ast_map.
    {
        let mut idx = backend.class_index().write();
        idx.insert(
            "UnknownKind\\MysteryClass".to_string(),
            "file:///vendor/mystery.php".to_string(),
        );
    }

    let uri = Url::parse("file:///test_unloaded.php").unwrap();
    let text = "<?php\nclass Foo implements Mystery";

    let items = complete_at(&backend, &uri, text, 1, 31).await;
    let cls = class_items(&items);
    let fqns = fqn_labels(&cls);

    assert!(
        fqns.contains(&"UnknownKind\\MysteryClass"),
        "unloaded classes should pass through the filter, got: {fqns:?}"
    );
}

// ─── Stubs pass through ────────────────────────────────────────────────────

/// Stub interfaces are filtered out of extends-class context even before
/// being fully parsed, thanks to the lightweight source scanner.
#[tokio::test]
async fn test_stub_interface_filtered_in_extends_class() {
    let backend = create_test_backend_with_stubs();

    let uri = Url::parse("file:///test_stub_filter.php").unwrap();
    // BackedEnum is an interface stub.  Even without a full parse, the
    // lightweight source scanner (`detect_stub_class_kind`) identifies it
    // as an interface and filters it out of extends-class context.
    let text = "<?php\nclass Foo extends Backed";

    let items = complete_at(&backend, &uri, text, 1, 27).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"BackedEnum"),
        "stub interface should be filtered out of extends-class context, got: {lbls:?}"
    );
}

/// After a stub is parsed and loaded into ast_map, the context filter
/// still correctly excludes it (via the fast path in ast_map).
#[tokio::test]
async fn test_parsed_stub_interface_filtered_in_extends_class() {
    let backend = create_test_backend_with_stubs();

    // Force the BackedEnum stub to be parsed by requesting it.
    // We do this by opening a file that references it.
    let ref_uri = Url::parse("file:///ref.php").unwrap();
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: ref_uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: concat!("<?php\n", "enum Color: string { case Red = 'red'; }\n",).to_string(),
            },
        })
        .await;

    // Trigger completion on Color to force enum stub parsing.
    let _ = complete_at(
        &backend,
        &ref_uri,
        concat!(
            "<?php\n",
            "enum Color: string { case Red = 'red'; }\n",
            "Color::Red->",
        ),
        2,
        12,
    )
    .await;

    // BackedEnum is an interface, so extends (class) should filter it
    // out whether detected via ast_map (fast path) or source scan.
    let uri = Url::parse("file:///test_stub_parsed.php").unwrap();
    let text = "<?php\nclass Foo extends Backed";
    let items = complete_at(&backend, &uri, text, 1, 27).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"BackedEnum"),
        "parsed stub interface should be filtered out of extends-class context, got: {lbls:?}"
    );
}

// ─── Keyword at unusual positions ───────────────────────────────────────────

/// `instanceof` with extra whitespace before the name.
#[tokio::test]
async fn test_instanceof_extra_whitespace() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_instanceof_ws.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\n$x instanceof    Some";

    let items = complete_at(&backend, &uri, text, 2, 21).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"SomeTrait"),
        "instanceof with extra whitespace should still filter traits, got: {lbls:?}"
    );
}

/// `instanceof` should not match partial keyword like `notinstanceof`.
#[tokio::test]
async fn test_instanceof_not_partial_keyword() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_instanceof_partial.php").unwrap();
    // "notinstanceof" is not a valid keyword - make sure we don't
    // accidentally match.
    let text = "<?php\nnamespace Scaffold;\n$x = notinstanceof Some";

    let items = complete_at(&backend, &uri, text, 2, 25).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    // In a non-keyword context, traits should be offered.
    // (The "notinstanceof" is not a real keyword, so it falls through to Any.)
    assert!(
        lbls.contains(&"SomeTrait"),
        "partial keyword match should not filter, got: {lbls:?}"
    );
}

// ─── implements after extends ───────────────────────────────────────────────

/// `class Foo extends Bar implements Baz` — implements should filter.
#[tokio::test]
async fn test_implements_after_extends() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_impl_after_ext.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\nclass Foo extends ConcreteClass implements Some";

    let items = complete_at(&backend, &uri, text, 2, 49).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"SomeInterface"),
        "implements after extends should offer interfaces, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"SomeTrait"),
        "implements after extends should not offer traits, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"ConcreteClass"),
        "implements after extends should not offer classes, got: {lbls:?}"
    );
}

// ─── enum implements ────────────────────────────────────────────────────────

/// Enum `implements` should also only offer interfaces.
#[tokio::test]
async fn test_enum_implements() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///test_enum_impl.php").unwrap();
    let text = "<?php\nnamespace Scaffold;\nenum Foo implements Some";

    let items = complete_at(&backend, &uri, text, 2, 27).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"SomeInterface"),
        "enum implements should offer interfaces, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"ConcreteClass"),
        "enum implements should not offer classes, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"SomeTrait"),
        "enum implements should not offer traits, got: {lbls:?}"
    );
}

// ─── Unloaded stubs are filtered via source scanning ────────────────────────
//
// The stub source is embedded in memory, so even without parsing into
// ast_map we can scan the raw PHP to determine the declaration kind.

/// A stub class should be excluded from `interface extends` even when
/// it has never been parsed (source scan detects `class` keyword).
#[tokio::test]
async fn test_unloaded_stub_class_excluded_from_extends_interface() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert(
        "DirectoryIterator",
        "<?php\nclass DirectoryIterator extends SplFileInfo implements SeekableIterator {}\n",
    );
    stubs.insert(
        "SeekableIterator",
        "<?php\ninterface SeekableIterator extends Iterator {}\n",
    );
    let backend = Backend::new_test_with_stubs(stubs);

    // Do NOT trigger any resolution — stubs remain unloaded.
    let uri = Url::parse("file:///test_unloaded_stub_ext_iface.php").unwrap();
    let text = "<?php\ninterface A extends Directory";

    let items = complete_at(&backend, &uri, text, 1, 29).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"DirectoryIterator"),
        "unloaded stub class should be excluded from interface extends, got: {lbls:?}"
    );
}

/// A stub interface should be included in `interface extends` even when
/// it has never been parsed.
#[tokio::test]
async fn test_unloaded_stub_interface_included_in_extends_interface() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert(
        "SeekableIterator",
        "<?php\ninterface SeekableIterator extends Iterator {}\n",
    );
    let backend = Backend::new_test_with_stubs(stubs);

    let uri = Url::parse("file:///test_unloaded_stub_iface_ok.php").unwrap();
    let text = "<?php\ninterface A extends Seekable";

    let items = complete_at(&backend, &uri, text, 1, 29).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"SeekableIterator"),
        "unloaded stub interface should be included in interface extends, got: {lbls:?}"
    );
}

/// A stub class should be excluded from `use` (trait) context even when
/// unloaded.
#[tokio::test]
async fn test_unloaded_stub_class_excluded_from_trait_use() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert(
        "DirectoryIterator",
        "<?php\nclass DirectoryIterator extends SplFileInfo {}\n",
    );
    let backend = Backend::new_test_with_stubs(stubs);

    let uri = Url::parse("file:///test_unloaded_stub_trait_use.php").unwrap();
    let text = concat!("<?php\n", "class Foo {\n", "    use Directory\n", "}\n",);

    let items = complete_at(&backend, &uri, text, 2, 19).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"DirectoryIterator"),
        "unloaded stub class should be excluded from trait use, got: {lbls:?}"
    );
}

/// A stub interface should be excluded from `implements` when the stub
/// is actually a class (source scan detects `class` keyword).
#[tokio::test]
async fn test_unloaded_stub_class_excluded_from_implements() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert(
        "DirectoryIterator",
        "<?php\nclass DirectoryIterator extends SplFileInfo implements SeekableIterator {}\n",
    );
    stubs.insert("JsonSerializable", "<?php\ninterface JsonSerializable {}\n");
    let backend = Backend::new_test_with_stubs(stubs);

    let uri = Url::parse("file:///test_unloaded_stub_impl.php").unwrap();
    let text = "<?php\nclass Foo implements Directory";

    let items = complete_at(&backend, &uri, text, 1, 31).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"DirectoryIterator"),
        "unloaded stub class should be excluded from implements, got: {lbls:?}"
    );
}

/// A stub interface should be included in `implements` when unloaded.
#[tokio::test]
async fn test_unloaded_stub_interface_included_in_implements() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert("JsonSerializable", "<?php\ninterface JsonSerializable {}\n");
    let backend = Backend::new_test_with_stubs(stubs);

    let uri = Url::parse("file:///test_unloaded_stub_impl_ok.php").unwrap();
    let text = "<?php\nclass Foo implements JsonSerializable";

    let items = complete_at(&backend, &uri, text, 1, 34).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"JsonSerializable"),
        "unloaded stub interface should be included in implements, got: {lbls:?}"
    );
}

/// An unloaded stub interface should be excluded from `new` context.
#[tokio::test]
async fn test_unloaded_stub_interface_excluded_from_new() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert("SpanInterface", "<?php\ninterface SpanInterface {}\n");
    let backend = Backend::new_test_with_stubs(stubs);

    let uri = Url::parse("file:///test_unloaded_stub_new.php").unwrap();
    let text = "<?php\nnew SpanInterface";

    let items = complete_at(&backend, &uri, text, 1, 17).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"SpanInterface"),
        "unloaded stub interface should be excluded from new context, got: {lbls:?}"
    );
}

/// An unloaded abstract stub class should be excluded from `new` context.
#[tokio::test]
async fn test_unloaded_stub_abstract_excluded_from_new() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert(
        "DatePeriod",
        "<?php\nabstract class DatePeriod implements IteratorAggregate {}\n",
    );
    let backend = Backend::new_test_with_stubs(stubs);

    let uri = Url::parse("file:///test_unloaded_stub_abs_new.php").unwrap();
    let text = "<?php\nnew DatePeriod";

    let items = complete_at(&backend, &uri, text, 1, 14).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"DatePeriod"),
        "unloaded abstract stub class should be excluded from new context, got: {lbls:?}"
    );
}

/// An unloaded concrete stub class should be included in `new` context.
#[tokio::test]
async fn test_unloaded_stub_concrete_class_included_in_new() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert(
        "DirectoryIterator",
        "<?php\nclass DirectoryIterator extends SplFileInfo {}\n",
    );
    let backend = Backend::new_test_with_stubs(stubs);

    let uri = Url::parse("file:///test_unloaded_stub_cls_new.php").unwrap();
    let text = "<?php\nnew DirectoryIterator";

    let items = complete_at(&backend, &uri, text, 1, 21).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"DirectoryIterator"),
        "unloaded concrete stub class should be included in new context, got: {lbls:?}"
    );
}

/// An unloaded stub class should be excluded from `extends` (interface).
/// This is the exact scenario reported: `interface B extends DirectoryIterator`.
#[tokio::test]
async fn test_unloaded_stub_class_excluded_from_extends_interface_second_use() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert(
        "DirectoryIterator",
        "<?php\nclass DirectoryIterator extends SplFileInfo {}\n",
    );
    stubs.insert("SpanInterface", "<?php\ninterface SpanInterface {}\n");
    let backend = Backend::new_test_with_stubs(stubs);

    // First use: class extends (class context) — should include the class.
    let uri1 = Url::parse("file:///test_first_use.php").unwrap();
    let text1 = "<?php\nclass A1 extends Directory";
    let items1 = complete_at(&backend, &uri1, text1, 1, 27).await;
    let cls1 = class_items(&items1);
    let lbls1: Vec<&str> = cls1.iter().map(|i| i.label.as_str()).collect();
    assert!(
        lbls1.contains(&"DirectoryIterator"),
        "class extends should include stub class, got: {lbls1:?}"
    );

    // Second use: interface extends — should exclude the class.
    let uri2 = Url::parse("file:///test_second_use.php").unwrap();
    let text2 = "<?php\ninterface B extends Directory";
    let items2 = complete_at(&backend, &uri2, text2, 1, 30).await;
    let cls2 = class_items(&items2);
    let lbls2: Vec<&str> = cls2.iter().map(|i| i.label.as_str()).collect();
    assert!(
        !lbls2.contains(&"DirectoryIterator"),
        "interface extends should exclude stub class, got: {lbls2:?}"
    );

    // Interface extends should include the interface.
    let uri3 = Url::parse("file:///test_third_use.php").unwrap();
    let text3 = "<?php\ninterface C extends Span";
    let items3 = complete_at(&backend, &uri3, text3, 1, 25).await;
    let cls3 = class_items(&items3);
    let lbls3: Vec<&str> = cls3.iter().map(|i| i.label.as_str()).collect();
    assert!(
        lbls3.contains(&"SpanInterface"),
        "interface extends should include stub interface, got: {lbls3:?}"
    );
}

/// `instanceof` should exclude stub traits (even when unloaded).
#[tokio::test]
async fn test_unloaded_stub_trait_excluded_from_instanceof() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert("SomeSplTrait", "<?php\ntrait SomeSplTrait {}\n");
    stubs.insert("JsonSerializable", "<?php\ninterface JsonSerializable {}\n");
    let backend = Backend::new_test_with_stubs(stubs);

    let uri = Url::parse("file:///test_unloaded_instanceof_trait.php").unwrap();
    let text = "<?php\n$x instanceof SomeSpl";

    let items = complete_at(&backend, &uri, text, 1, 20).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"SomeSplTrait"),
        "unloaded stub trait should be excluded from instanceof, got: {lbls:?}"
    );
}

/// `instanceof` should include stub interfaces (even when unloaded).
#[tokio::test]
async fn test_unloaded_stub_interface_included_in_instanceof() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert("JsonSerializable", "<?php\ninterface JsonSerializable {}\n");
    let backend = Backend::new_test_with_stubs(stubs);

    let uri = Url::parse("file:///test_unloaded_instanceof_iface.php").unwrap();
    let text = "<?php\n$x instanceof JsonSerializable";

    let items = complete_at(&backend, &uri, text, 1, 28).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"JsonSerializable"),
        "unloaded stub interface should be included in instanceof, got: {lbls:?}"
    );
}

/// A stub file with multiple declarations: the scanner should find the
/// right one by name.
#[tokio::test]
async fn test_unloaded_stub_multi_declaration_file() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    // Both point to the same source file (like real stubs do).
    let multi_source = concat!(
        "<?php\n",
        "interface Countable {\n",
        "    public function count(): int;\n",
        "}\n",
        "class ArrayObject implements IteratorAggregate, ArrayAccess, Countable {\n",
        "}\n",
    );
    stubs.insert("Countable", multi_source);
    stubs.insert("ArrayObject", multi_source);
    let backend = Backend::new_test_with_stubs(stubs);

    // `implements` should include Countable (interface) but exclude ArrayObject (class).
    let uri = Url::parse("file:///test_multi_decl.php").unwrap();
    let text = "<?php\nclass Foo implements Countable";
    let items = complete_at(&backend, &uri, text, 1, 30).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();
    assert!(
        lbls.contains(&"Countable"),
        "implements should include Countable (interface in multi-decl file), got: {lbls:?}"
    );

    let uri2 = Url::parse("file:///test_multi_decl2.php").unwrap();
    let text2 = "<?php\nclass Foo implements ArrayObject";
    let items2 = complete_at(&backend, &uri2, text2, 1, 31).await;
    let cls2 = class_items(&items2);
    let lbls2: Vec<&str> = cls2.iter().map(|i| i.label.as_str()).collect();
    assert!(
        !lbls2.contains(&"ArrayObject"),
        "implements should exclude ArrayObject (class in multi-decl file), got: {lbls2:?}"
    );
}

/// `extends` (class) should include a concrete stub class and exclude
/// a final stub class — all via source scanning, no parsing.
#[tokio::test]
async fn test_unloaded_stub_final_class_excluded_from_extends_class() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert("FinalStubClass", "<?php\nfinal class FinalStubClass {}\n");
    stubs.insert("NormalStubClass", "<?php\nclass NormalStubClass {}\n");
    let backend = Backend::new_test_with_stubs(stubs);

    let uri = Url::parse("file:///test_final_stub.php").unwrap();
    let text = "<?php\nclass Foo extends FinalStub";
    let items = complete_at(&backend, &uri, text, 1, 27).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();
    assert!(
        !lbls.contains(&"FinalStubClass"),
        "extends (class) should exclude final stub class, got: {lbls:?}"
    );

    let uri2 = Url::parse("file:///test_normal_stub.php").unwrap();
    let text2 = "<?php\nclass Foo extends NormalStub";
    let items2 = complete_at(&backend, &uri2, text2, 1, 28).await;
    let cls2 = class_items(&items2);
    let lbls2: Vec<&str> = cls2.iter().map(|i| i.label.as_str()).collect();
    assert!(
        lbls2.contains(&"NormalStubClass"),
        "extends (class) should include normal stub class, got: {lbls2:?}"
    );
}

// ─── Loaded stubs are filtered ──────────────────────────────────────────────

/// Once a stub class is parsed and in the ast_map, the context filter
/// should exclude it from positions where its kind is invalid.
/// BadUrlException is a class — `interface A extends BadUrlException`
/// should not offer it.
#[tokio::test]
async fn test_loaded_stub_class_excluded_from_extends_interface() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert(
        "BadUrlException",
        "<?php\nclass BadUrlException extends \\Exception {}\n",
    );
    stubs.insert(
        "SomeStubInterface",
        "<?php\ninterface SomeStubInterface {}\n",
    );
    let backend = Backend::new_test_with_stubs(stubs);

    // Force the stubs to be parsed by opening a file that references them.
    let ref_uri = Url::parse("file:///ref_stub.php").unwrap();
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: ref_uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: concat!(
                    "<?php\n",
                    "class Preload extends BadUrlException {}\n",
                    "class Preload2 implements SomeStubInterface {}\n",
                )
                .to_string(),
            },
        })
        .await;

    // Trigger resolution so the stubs get parsed into ast_map.
    let _ = complete_at(
        &backend,
        &ref_uri,
        concat!(
            "<?php\n",
            "class Preload extends BadUrlException {}\n",
            "class Preload2 implements SomeStubInterface {}\n",
            "$x = new Preload(); $x->",
        ),
        3,
        24,
    )
    .await;

    // Now: interface extends should exclude the loaded class stub
    // but include the loaded interface stub.
    let uri = Url::parse("file:///test_loaded_stub.php").unwrap();
    // Use partial "S" which matches SomeStubInterface.
    let text = "<?php\ninterface A extends S";

    let items = complete_at(&backend, &uri, text, 1, 23).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"SomeStubInterface"),
        "loaded interface stub should be included in interface extends, got: {lbls:?}"
    );

    // Also check with partial "Bad" to verify the class is excluded.
    let uri2 = Url::parse("file:///test_loaded_stub2.php").unwrap();
    let text2 = "<?php\ninterface A extends Bad";

    let items2 = complete_at(&backend, &uri2, text2, 1, 25).await;
    let cls2 = class_items(&items2);
    let lbls2: Vec<&str> = cls2.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls2.contains(&"BadUrlException"),
        "loaded class stub should be excluded from interface extends, got: {lbls2:?}"
    );
}

/// A loaded class stub should be excluded from trait-use context.
#[tokio::test]
async fn test_loaded_stub_class_excluded_from_trait_use() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert(
        "JsonException",
        "<?php\nclass JsonException extends \\Exception {}\n",
    );
    let backend = Backend::new_test_with_stubs(stubs);

    // Force the stub to be parsed.
    let ref_uri = Url::parse("file:///ref_stub2.php").unwrap();
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: ref_uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: "<?php\nclass Preload extends JsonException {}\n".to_string(),
            },
        })
        .await;
    let _ = complete_at(
        &backend,
        &ref_uri,
        "<?php\nclass Preload extends JsonException {}\n$x = new Preload(); $x->",
        2,
        24,
    )
    .await;

    let uri = Url::parse("file:///test_loaded_trait_use.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class A extends JsonException {\n",
        "    use Json\n",
        "}\n",
    );

    let items = complete_at(&backend, &uri, text, 2, 12).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"JsonException"),
        "loaded class stub should be excluded from trait use, got: {lbls:?}"
    );
}

/// After using a symbol once (forcing it to load), the filter should
/// apply on subsequent completions in a different file.
#[tokio::test]
async fn test_loaded_class_filtered_on_second_use() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert(
        "BadUrlException",
        "<?php\nclass BadUrlException extends \\Exception {}\n",
    );
    let backend = Backend::new_test_with_stubs(stubs);

    // First use: `interface A extends BadUrlException {}` — loads the stub.
    let first_uri = Url::parse("file:///first_use.php").unwrap();
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: first_uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: "<?php\nclass Preload extends BadUrlException {}\n".to_string(),
            },
        })
        .await;
    let _ = complete_at(
        &backend,
        &first_uri,
        "<?php\nclass Preload extends BadUrlException {}\n$x = new Preload(); $x->",
        2,
        24,
    )
    .await;

    // Second use in a different file:
    let second_uri = Url::parse("file:///second_use.php").unwrap();
    let text = "<?php\ninterface B extends BadUrl";

    let items = complete_at(&backend, &second_uri, text, 1, 27).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"BadUrlException"),
        "after loading, class stub should be filtered from interface extends, got: {lbls:?}"
    );
}

// ─── Classmap entries are filtered when loaded ──────────────────────────────

/// A classmap entry that is loaded as an interface should be excluded
/// from class-extends context.
#[tokio::test]
async fn test_classmap_loaded_interface_excluded_from_extends_class() {
    let backend = create_test_backend();

    // Load an interface into ast_map.
    let iface_uri = Url::parse("file:///app/Contracts/Searchable.php").unwrap();
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: iface_uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: "<?php\nnamespace App\\Contracts;\ninterface Searchable {}\n".to_string(),
            },
        })
        .await;

    // Put it in the classmap.
    {
        let mut cmap = backend.classmap().write();
        cmap.insert(
            "App\\Contracts\\Searchable".to_string(),
            PathBuf::from(iface_uri.path()),
        );
    }

    let uri = Url::parse("file:///test_cmap_filter.php").unwrap();
    let text = "<?php\nclass Foo extends Searchable";

    let items = complete_at(&backend, &uri, text, 1, 28).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"App\\Contracts\\Searchable"),
        "loaded interface in classmap should be excluded from class extends, got: {lbls:?}"
    );
}

/// A classmap entry that is loaded as a trait should be excluded from
/// implements context.
#[tokio::test]
async fn test_classmap_loaded_trait_excluded_from_implements() {
    let backend = create_test_backend();

    let trait_uri = Url::parse("file:///app/Traits/Sortable.php").unwrap();
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: trait_uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: "<?php\nnamespace App\\Traits;\ntrait Sortable {}\n".to_string(),
            },
        })
        .await;

    {
        let mut cmap = backend.classmap().write();
        cmap.insert(
            "App\\Traits\\Sortable".to_string(),
            PathBuf::from(trait_uri.path()),
        );
    }

    let uri = Url::parse("file:///test_cmap_trait.php").unwrap();
    let text = "<?php\nclass Foo implements Sortable";

    let items = complete_at(&backend, &uri, text, 1, 31).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"App\\Traits\\Sortable"),
        "loaded trait in classmap should be excluded from implements, got: {lbls:?}"
    );
}

// ─── Heuristic sort demotion for unloaded classes ───────────────────────────

/// In `extends` (class) context, names that look like interfaces should
/// be demoted (higher sort_text prefix) behind normal names.
#[tokio::test]
async fn test_extends_class_demotes_interface_looking_names() {
    let backend = create_test_backend();

    // The heuristic matches on the SHORT name (last segment after \).
    // "ZxUserInterface" ends with "Interface" → demoted.
    // "IZxLogger" starts with I[A-Z] → demoted.
    // "ZxUserRepository" has no interface/abstract pattern → normal sort.
    {
        let mut cmap = backend.classmap().write();
        cmap.insert(
            "App\\ZxUserInterface".to_string(),
            PathBuf::from("/vendor/a.php"),
        );
        cmap.insert(
            "App\\ZxUserRepository".to_string(),
            PathBuf::from("/vendor/b.php"),
        );
        cmap.insert("App\\IZxLogger".to_string(), PathBuf::from("/vendor/c.php"));
    }

    let uri = Url::parse("file:///test_ext_demote.php").unwrap();
    // Partial "Zx" matches the first two; separate request for "IZx".
    let text = "<?php\nclass Foo extends Zx";
    let items_zx = complete_at(&backend, &uri, text, 1, 24).await;

    let uri2 = Url::parse("file:///test_ext_demote2.php").unwrap();
    let text2 = "<?php\nclass Foo extends IZx";
    let items_izx = complete_at(&backend, &uri2, text2, 1, 25).await;

    let mut items = items_zx;
    items.extend(items_izx);
    let cls = class_items(&items);

    let repo_item = find_by_fqn(&cls, "App\\ZxUserRepository");
    let iface_item = find_by_fqn(&cls, "App\\ZxUserInterface");
    let ilogger_item = find_by_fqn(&cls, "App\\IZxLogger");

    assert!(repo_item.is_some(), "ZxUserRepository should be present");
    assert!(
        iface_item.is_some(),
        "ZxUserInterface should be present (unloaded, passes through)"
    );
    assert!(
        ilogger_item.is_some(),
        "IZxLogger should be present (unloaded, passes through)"
    );

    // Interface-looking names should have a higher (worse) sort prefix.
    let repo_sort = repo_item.unwrap().sort_text.as_deref().unwrap_or("");
    let iface_sort = iface_item.unwrap().sort_text.as_deref().unwrap_or("");
    let ilogger_sort = ilogger_item.unwrap().sort_text.as_deref().unwrap_or("");

    assert!(
        repo_sort < iface_sort,
        "ZxUserRepository ({repo_sort}) should sort before ZxUserInterface ({iface_sort}) in extends-class context"
    );
    assert!(
        repo_sort < ilogger_sort,
        "ZxUserRepository ({repo_sort}) should sort before IZxLogger ({ilogger_sort}) in extends-class context"
    );
}

/// In `implements` context, names that look like abstract/base classes
/// should be demoted behind normal names.
#[tokio::test]
async fn test_implements_demotes_abstract_looking_names() {
    let backend = create_test_backend();

    // "YxLoggable" has no abstract pattern → normal sort.
    // "AbstractYxHandler" starts with "Abstract" → demoted.
    // "BaseYxController" starts with "Base[A-Z]" → demoted.
    {
        let mut cmap = backend.classmap().write();
        cmap.insert(
            "App\\YxLoggable".to_string(),
            PathBuf::from("/vendor/a.php"),
        );
        cmap.insert(
            "App\\AbstractYxHandler".to_string(),
            PathBuf::from("/vendor/b.php"),
        );
        cmap.insert(
            "App\\BaseYxController".to_string(),
            PathBuf::from("/vendor/c.php"),
        );
    }

    let uri = Url::parse("file:///test_impl_demote.php").unwrap();
    // Partial "Yx" matches YxLoggable; separate requests for the others.
    let text_yx = "<?php\nclass Foo implements Yx";
    let items_yx = complete_at(&backend, &uri, text_yx, 1, 27).await;

    let uri2 = Url::parse("file:///test_impl_demote2.php").unwrap();
    let text_abs = "<?php\nclass Foo implements AbstractYx";
    let items_abs = complete_at(&backend, &uri2, text_abs, 1, 35).await;

    let uri3 = Url::parse("file:///test_impl_demote3.php").unwrap();
    let text_base = "<?php\nclass Foo implements BaseYx";
    let items_base = complete_at(&backend, &uri3, text_base, 1, 31).await;

    let mut items = items_yx;
    items.extend(items_abs);
    items.extend(items_base);
    let cls = class_items(&items);

    let loggable_item = find_by_fqn(&cls, "App\\YxLoggable");
    let abstract_item = find_by_fqn(&cls, "App\\AbstractYxHandler");
    let base_item = find_by_fqn(&cls, "App\\BaseYxController");

    assert!(loggable_item.is_some(), "YxLoggable should be present");
    assert!(
        abstract_item.is_some(),
        "AbstractYxHandler should be present (unloaded)"
    );
    assert!(
        base_item.is_some(),
        "BaseYxController should be present (unloaded)"
    );

    let loggable_sort = loggable_item.unwrap().sort_text.as_deref().unwrap_or("");
    let abstract_sort = abstract_item.unwrap().sort_text.as_deref().unwrap_or("");
    let base_sort = base_item.unwrap().sort_text.as_deref().unwrap_or("");

    assert!(
        loggable_sort < abstract_sort,
        "YxLoggable ({loggable_sort}) should sort before AbstractYxHandler ({abstract_sort}) in implements context"
    );
    assert!(
        loggable_sort < base_sort,
        "YxLoggable ({loggable_sort}) should sort before BaseYxController ({base_sort}) in implements context"
    );
}

/// In `use` (trait) context, names that look like interfaces or abstract
/// classes should be demoted.
#[tokio::test]
async fn test_trait_use_demotes_non_trait_looking_names() {
    let backend = create_test_backend();

    // "WxHasTimestamps" has no interface/abstract pattern → normal sort.
    // "WxUserInterface" ends with "Interface" → demoted (likely_non_instantiable).
    // "AbstractWxModel" starts with "Abstract" → demoted (likely_non_instantiable).
    {
        let mut cmap = backend.classmap().write();
        cmap.insert(
            "App\\WxHasTimestamps".to_string(),
            PathBuf::from("/vendor/a.php"),
        );
        cmap.insert(
            "App\\WxUserInterface".to_string(),
            PathBuf::from("/vendor/b.php"),
        );
        cmap.insert(
            "App\\AbstractWxModel".to_string(),
            PathBuf::from("/vendor/c.php"),
        );
    }

    let uri = Url::parse("file:///test_use_demote.php").unwrap();
    // Partial "Wx" matches WxHasTimestamps and WxUserInterface.
    let text_wx = concat!("<?php\n", "class Bar {\n", "    use Wx\n", "}\n",);
    let items_wx = complete_at(&backend, &uri, text_wx, 2, 10).await;

    // Separate request for "AbstractWx".
    let uri2 = Url::parse("file:///test_use_demote2.php").unwrap();
    let text_abs = concat!("<?php\n", "class Bar {\n", "    use AbstractWx\n", "}\n",);
    let items_abs = complete_at(&backend, &uri2, text_abs, 2, 18).await;

    let mut items = items_wx;
    items.extend(items_abs);
    let cls = class_items(&items);

    let ts_item = find_by_fqn(&cls, "App\\WxHasTimestamps");
    let iface_item = find_by_fqn(&cls, "App\\WxUserInterface");
    let abs_item = find_by_fqn(&cls, "App\\AbstractWxModel");

    assert!(ts_item.is_some(), "WxHasTimestamps should be present");
    assert!(
        iface_item.is_some(),
        "WxUserInterface should be present (unloaded)"
    );
    assert!(
        abs_item.is_some(),
        "AbstractWxModel should be present (unloaded)"
    );

    let ts_sort = ts_item.unwrap().sort_text.as_deref().unwrap_or("");
    let iface_sort = iface_item.unwrap().sort_text.as_deref().unwrap_or("");
    let abs_sort = abs_item.unwrap().sort_text.as_deref().unwrap_or("");

    assert!(
        ts_sort < iface_sort,
        "WxHasTimestamps ({ts_sort}) should sort before WxUserInterface ({iface_sort}) in trait-use context"
    );
    assert!(
        ts_sort < abs_sort,
        "WxHasTimestamps ({ts_sort}) should sort before AbstractWxModel ({abs_sort}) in trait-use context"
    );
}

/// In `instanceof` context, no heuristic demotion should be applied —
/// classes, interfaces, and enums are all equally valid.
#[tokio::test]
async fn test_instanceof_no_heuristic_demotion() {
    let backend = create_test_backend();

    {
        let mut cmap = backend.classmap().write();
        cmap.insert(
            "App\\UserInterface".to_string(),
            PathBuf::from("/vendor/a.php"),
        );
        cmap.insert(
            "App\\UserRepository".to_string(),
            PathBuf::from("/vendor/b.php"),
        );
    }

    let uri = Url::parse("file:///test_instanceof_sort.php").unwrap();
    let text = "<?php\n$x instanceof User";

    let items = complete_at(&backend, &uri, text, 1, 21).await;
    let cls = class_items(&items);

    let repo_item = find_by_fqn(&cls, "App\\UserRepository");
    let iface_item = find_by_fqn(&cls, "App\\UserInterface");

    assert!(repo_item.is_some(), "UserRepository should be present");
    assert!(iface_item.is_some(), "UserInterface should be present");

    // sort_text format: {quality}{tier}{affinity:4}{demote}{gap:3}_{name}
    // Demote flag is at position 6.  Neither should be demoted in
    // instanceof context.
    let demote_flag = |item: &CompletionItem| -> char {
        item.sort_text
            .as_deref()
            .and_then(|s| s.chars().nth(6))
            .unwrap_or('?')
    };

    assert_eq!(
        demote_flag(repo_item.unwrap()),
        '0',
        "UserRepository should not be demoted in instanceof context"
    );
    assert_eq!(
        demote_flag(iface_item.unwrap()),
        '0',
        "UserInterface should not be demoted in instanceof context"
    );
}

/// In `extends` (interface) context, names that look like interfaces
/// should NOT be demoted (they're the desired result).
#[tokio::test]
async fn test_extends_interface_does_not_demote_interface_names() {
    let backend = create_test_backend();

    {
        let mut cmap = backend.classmap().write();
        cmap.insert(
            "App\\LoggerInterface".to_string(),
            PathBuf::from("/vendor/a.php"),
        );
        cmap.insert("App\\Loggable".to_string(), PathBuf::from("/vendor/b.php"));
    }

    let uri = Url::parse("file:///test_ext_iface_sort.php").unwrap();
    let text = "<?php\ninterface Foo extends Log";

    let items = complete_at(&backend, &uri, text, 1, 28).await;
    let cls = class_items(&items);

    let logger_item = find_by_fqn(&cls, "App\\LoggerInterface");
    let loggable_item = find_by_fqn(&cls, "App\\Loggable");

    assert!(logger_item.is_some(), "LoggerInterface should be present");
    assert!(loggable_item.is_some(), "Loggable should be present");

    // sort_text format: {quality}{tier}{affinity:4}{demote}{gap:3}_{name}
    // Demote flag is at position 6.  Neither should be demoted in
    // extends-interface context.
    let demote_flag = |item: &CompletionItem| -> char {
        item.sort_text
            .as_deref()
            .and_then(|s| s.chars().nth(6))
            .unwrap_or('?')
    };

    assert_eq!(
        demote_flag(logger_item.unwrap()),
        '0',
        "LoggerInterface should not be demoted in interface extends context"
    );
    assert_eq!(
        demote_flag(loggable_item.unwrap()),
        '0',
        "Loggable should not be demoted in interface extends context"
    );
}

// ─── Anonymous classes excluded ─────────────────────────────────────────────

/// Load a file containing an anonymous class into the backend for the
/// anonymous-class exclusion tests below.
async fn load_anon_scaffolding(backend: &Backend) {
    let uri = Url::parse("file:///anon_scaffolding.php").unwrap();
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri,
                language_id: "php".to_string(),
                version: 1,
                text: concat!(
                    "<?php\n",
                    "namespace AnonTest;\n",
                    "class AnonContainer {\n",
                    "    public function make() {\n",
                    "        return new class extends AnonContainer {};\n",
                    "    }\n",
                    "}\n",
                )
                .to_string(),
            },
        })
        .await;
}

/// In a plain (unfiltered) context, the named class should appear but
/// `__anonymous@*` entries should not.
#[tokio::test]
async fn test_anonymous_class_excluded_plain_context() {
    let backend = create_test_backend();
    load_anon_scaffolding(&backend).await;

    let uri = Url::parse("file:///anon_plain.php").unwrap();
    let text = "<?php\nnamespace AnonTest;\nAnon";
    let items = complete_at(&backend, &uri, text, 2, 4).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    let fqns = fqn_labels(&cls);
    assert!(
        fqns.contains(&"AnonTest\\AnonContainer"),
        "plain context should offer AnonContainer, got: {fqns:?}"
    );
    assert!(
        !lbls.iter().any(|l| l.starts_with("__anonymous")),
        "plain context should not offer anonymous classes, got: {lbls:?}"
    );
}

/// `extends` (class) should not offer `__anonymous@*`.
#[tokio::test]
async fn test_anonymous_class_excluded_extends() {
    let backend = create_test_backend();
    load_anon_scaffolding(&backend).await;

    let uri = Url::parse("file:///anon_ext.php").unwrap();
    let text = "<?php\nnamespace AnonTest;\nclass Foo extends Anon";
    let items = complete_at(&backend, &uri, text, 2, 25).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.iter().any(|l| l.starts_with("__anonymous")),
        "extends (class) should not offer anonymous classes, got: {lbls:?}"
    );
}

/// `implements` should not offer `__anonymous@*`.
#[tokio::test]
async fn test_anonymous_class_excluded_implements() {
    let backend = create_test_backend();
    load_anon_scaffolding(&backend).await;

    let uri = Url::parse("file:///anon_impl.php").unwrap();
    let text = "<?php\nnamespace AnonTest;\nclass Foo implements Anon";
    let items = complete_at(&backend, &uri, text, 2, 28).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.iter().any(|l| l.starts_with("__anonymous")),
        "implements should not offer anonymous classes, got: {lbls:?}"
    );
}

/// `instanceof` should not offer `__anonymous@*`.
#[tokio::test]
async fn test_anonymous_class_excluded_instanceof() {
    let backend = create_test_backend();
    load_anon_scaffolding(&backend).await;

    let uri = Url::parse("file:///anon_instanceof.php").unwrap();
    let text = "<?php\nnamespace AnonTest;\n$x instanceof Anon";
    let items = complete_at(&backend, &uri, text, 2, 18).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.iter().any(|l| l.starts_with("__anonymous")),
        "instanceof should not offer anonymous classes, got: {lbls:?}"
    );
}

/// `new` should not offer `__anonymous@*`.
#[tokio::test]
async fn test_anonymous_class_excluded_new() {
    let backend = create_test_backend();
    load_anon_scaffolding(&backend).await;

    let uri = Url::parse("file:///anon_new.php").unwrap();
    let text = "<?php\nnamespace AnonTest;\nnew Anon";
    let items = complete_at(&backend, &uri, text, 2, 8).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.iter().any(|l| l.starts_with("__anonymous")),
        "new should not offer anonymous classes, got: {lbls:?}"
    );
}

/// `use` (trait) inside a class body should not offer `__anonymous@*`.
#[tokio::test]
async fn test_anonymous_class_excluded_trait_use() {
    let backend = create_test_backend();
    load_anon_scaffolding(&backend).await;

    let uri = Url::parse("file:///anon_trait_use.php").unwrap();
    let text = "<?php\nnamespace AnonTest;\nclass Bar {\n    use Anon\n}\n";
    let items = complete_at(&backend, &uri, text, 3, 12).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.iter().any(|l| l.starts_with("__anonymous")),
        "trait use should not offer anonymous classes, got: {lbls:?}"
    );
}

// ─── Loaded stub filtered across all contexts ───────────────────────────────

/// After a final stub class is loaded (parsed into ast_map), it should be
/// filtered out of every context except `instanceof` and `Any`.
/// This simulates the user's real-world scenario: use a stub class once
/// (e.g. `new V8JsScriptException()`), then trigger completion in
/// extends/implements/use contexts where it does not belong.
#[tokio::test]
async fn test_loaded_final_stub_class_filtered_in_all_contexts() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert(
        "V8JsScriptException",
        "<?php\nfinal class V8JsScriptException extends \\Exception {}\n",
    );
    let backend = Backend::new_test_with_stubs(stubs);

    // Force the stub to be loaded by resolving it through a member access.
    let load_uri = Url::parse("file:///load_stub.php").unwrap();
    let load_text = concat!(
        "<?php\n",
        "class Preload extends V8JsScriptException {}\n",
        "$x = new Preload(); $x->",
    );
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: load_uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: load_text.to_string(),
            },
        })
        .await;
    let _ = complete_at(&backend, &load_uri, load_text, 2, 24).await;

    // ── extends (class) — final class must be excluded ──
    let uri1 = Url::parse("file:///test_final_ext_class.php").unwrap();
    let text1 = "<?php\nclass A extends V8Js";
    let items1 = complete_at(&backend, &uri1, text1, 1, 22).await;
    let cls1 = class_items(&items1);
    let lbls1: Vec<&str> = cls1.iter().map(|i| i.label.as_str()).collect();
    assert!(
        !lbls1.contains(&"V8JsScriptException"),
        "loaded final class should be excluded from class extends, got: {lbls1:?}"
    );

    // ── extends (interface) — class must be excluded ──
    let uri2 = Url::parse("file:///test_final_ext_iface.php").unwrap();
    let text2 = "<?php\ninterface B extends V8Js";
    let items2 = complete_at(&backend, &uri2, text2, 1, 26).await;
    let cls2 = class_items(&items2);
    let lbls2: Vec<&str> = cls2.iter().map(|i| i.label.as_str()).collect();
    assert!(
        !lbls2.contains(&"V8JsScriptException"),
        "loaded final class should be excluded from interface extends, got: {lbls2:?}"
    );

    // ── implements — class must be excluded ──
    let uri3 = Url::parse("file:///test_final_impl.php").unwrap();
    let text3 = "<?php\nclass C implements V8Js";
    let items3 = complete_at(&backend, &uri3, text3, 1, 25).await;
    let cls3 = class_items(&items3);
    let lbls3: Vec<&str> = cls3.iter().map(|i| i.label.as_str()).collect();
    assert!(
        !lbls3.contains(&"V8JsScriptException"),
        "loaded final class should be excluded from implements, got: {lbls3:?}"
    );

    // ── use (trait) — class must be excluded ──
    let uri4 = Url::parse("file:///test_final_trait.php").unwrap();
    let text4 = "<?php\nclass D {\n    use V8Js\n}\n";
    let items4 = complete_at(&backend, &uri4, text4, 2, 11).await;
    let cls4 = class_items(&items4);
    let lbls4: Vec<&str> = cls4.iter().map(|i| i.label.as_str()).collect();
    assert!(
        !lbls4.contains(&"V8JsScriptException"),
        "loaded final class should be excluded from trait use, got: {lbls4:?}"
    );

    // ── new — final class IS instantiable, so it SHOULD appear ──
    let uri5 = Url::parse("file:///test_final_new.php").unwrap();
    let text5 = "<?php\nnew V8Js";
    let items5 = complete_at(&backend, &uri5, text5, 1, 8).await;
    let cls5 = class_items(&items5);
    let lbls5: Vec<&str> = cls5.iter().map(|i| i.label.as_str()).collect();
    assert!(
        lbls5.contains(&"V8JsScriptException"),
        "loaded final class should be included in new context, got: {lbls5:?}"
    );

    // ── instanceof — class SHOULD appear ──
    let uri6 = Url::parse("file:///test_final_instanceof.php").unwrap();
    let text6 = "<?php\n$x instanceof V8Js";
    let items6 = complete_at(&backend, &uri6, text6, 1, 21).await;
    let cls6 = class_items(&items6);
    let lbls6: Vec<&str> = cls6.iter().map(|i| i.label.as_str()).collect();
    assert!(
        lbls6.contains(&"V8JsScriptException"),
        "loaded final class should be included in instanceof context, got: {lbls6:?}"
    );
}

// ─── Real multi-class stub source ───────────────────────────────────────────

/// Simulate the real phpstorm-stubs structure: a single source file
/// containing multiple classes (V8Js, V8JsScriptException, etc.).
/// All stub_index keys point to the same source.  Verify that the
/// lightweight scanner and the loaded-class path both filter correctly.
static V8JS_REAL_STUB: &str = "\
<?php

class V8Js
{
    public const V8_VERSION = '';

    public function __construct($object_name = 'PHP', array $variables = []) {}

    /**
     * @return V8JsScriptException|null
     */
    public function getPendingException() {}

    public function executeString($script, $identifier = '') {}
}

final class V8JsScriptException extends Exception
{
    final public function getJsFileName() {}
    final public function getJsLineNumber() {}
}

final class V8JsTimeLimitException extends Exception {}

final class V8JsMemoryLimitException extends Exception {}
";

#[tokio::test]
async fn test_real_multi_class_stub_unloaded_filtering() {
    // All four classes share the same source, just like real stubs.
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert("V8Js", V8JS_REAL_STUB);
    stubs.insert("V8JsScriptException", V8JS_REAL_STUB);
    stubs.insert("V8JsTimeLimitException", V8JS_REAL_STUB);
    stubs.insert("V8JsMemoryLimitException", V8JS_REAL_STUB);
    let backend = Backend::new_test_with_stubs(stubs);

    // Do NOT load any stubs — test the lightweight scanner path.

    // extends (class): V8Js is a plain class → included.
    // V8JsScriptException is final → excluded.
    let uri1 = Url::parse("file:///test_v8_ext_class.php").unwrap();
    let text1 = "<?php\nclass A extends V8Js";
    let items1 = complete_at(&backend, &uri1, text1, 1, 22).await;
    let cls1 = class_items(&items1);
    let lbls1: Vec<&str> = cls1.iter().map(|i| i.label.as_str()).collect();
    assert!(
        lbls1.contains(&"V8Js"),
        "non-final class V8Js should be included in class extends, got: {lbls1:?}"
    );
    assert!(
        !lbls1.contains(&"V8JsScriptException"),
        "final class V8JsScriptException should be excluded from class extends, got: {lbls1:?}"
    );
    assert!(
        !lbls1.contains(&"V8JsTimeLimitException"),
        "final class V8JsTimeLimitException should be excluded from class extends, got: {lbls1:?}"
    );

    // extends (interface): all are classes → none should appear.
    let uri2 = Url::parse("file:///test_v8_ext_iface.php").unwrap();
    let text2 = "<?php\ninterface B extends V8Js";
    let items2 = complete_at(&backend, &uri2, text2, 1, 26).await;
    let cls2 = class_items(&items2);
    let lbls2: Vec<&str> = cls2.iter().map(|i| i.label.as_str()).collect();
    assert!(
        !lbls2.contains(&"V8Js"),
        "class V8Js should be excluded from interface extends, got: {lbls2:?}"
    );
    assert!(
        !lbls2.contains(&"V8JsScriptException"),
        "class V8JsScriptException should be excluded from interface extends, got: {lbls2:?}"
    );

    // implements: all are classes → none should appear.
    let uri3 = Url::parse("file:///test_v8_impl.php").unwrap();
    let text3 = "<?php\nclass C implements V8Js";
    let items3 = complete_at(&backend, &uri3, text3, 1, 25).await;
    let cls3 = class_items(&items3);
    let lbls3: Vec<&str> = cls3.iter().map(|i| i.label.as_str()).collect();
    assert!(
        !lbls3.contains(&"V8JsScriptException"),
        "class should be excluded from implements, got: {lbls3:?}"
    );

    // trait use: all are classes → none should appear.
    let uri4 = Url::parse("file:///test_v8_trait.php").unwrap();
    let text4 = "<?php\nclass D {\n    use V8Js\n}\n";
    let items4 = complete_at(&backend, &uri4, text4, 2, 11).await;
    let cls4 = class_items(&items4);
    let lbls4: Vec<&str> = cls4.iter().map(|i| i.label.as_str()).collect();
    assert!(
        !lbls4.contains(&"V8JsScriptException"),
        "class should be excluded from trait use, got: {lbls4:?}"
    );

    // new: V8Js (non-final, non-abstract) → included.
    // V8JsScriptException (final but concrete) → included.
    let uri5 = Url::parse("file:///test_v8_new.php").unwrap();
    let text5 = "<?php\nnew V8Js";
    let items5 = complete_at(&backend, &uri5, text5, 1, 8).await;
    let cls5 = class_items(&items5);
    let lbls5: Vec<&str> = cls5.iter().map(|i| i.label.as_str()).collect();
    assert!(
        lbls5.contains(&"V8Js"),
        "concrete class should be included in new, got: {lbls5:?}"
    );
    assert!(
        lbls5.contains(&"V8JsScriptException"),
        "final concrete class should be included in new, got: {lbls5:?}"
    );

    // instanceof: all classes should appear.
    let uri6 = Url::parse("file:///test_v8_instanceof.php").unwrap();
    let text6 = "<?php\n$x instanceof V8Js";
    let items6 = complete_at(&backend, &uri6, text6, 1, 21).await;
    let cls6 = class_items(&items6);
    let lbls6: Vec<&str> = cls6.iter().map(|i| i.label.as_str()).collect();
    assert!(
        lbls6.contains(&"V8Js"),
        "class should be included in instanceof, got: {lbls6:?}"
    );
    assert!(
        lbls6.contains(&"V8JsScriptException"),
        "class should be included in instanceof, got: {lbls6:?}"
    );
}

#[tokio::test]
async fn test_real_multi_class_stub_loaded_filtering() {
    let mut stubs: std::collections::HashMap<&'static str, &'static str> =
        std::collections::HashMap::new();
    stubs.insert("V8Js", V8JS_REAL_STUB);
    stubs.insert("V8JsScriptException", V8JS_REAL_STUB);
    stubs.insert("V8JsTimeLimitException", V8JS_REAL_STUB);
    stubs.insert("V8JsMemoryLimitException", V8JS_REAL_STUB);
    let backend = Backend::new_test_with_stubs(stubs);

    // Load the stub by resolving V8JsScriptException through member access.
    let load_uri = Url::parse("file:///load_v8.php").unwrap();
    let load_text = concat!(
        "<?php\n",
        "class Preload extends V8JsScriptException {}\n",
        "$x = new Preload(); $x->",
    );
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: load_uri.clone(),
                language_id: "php".to_string(),
                version: 1,
                text: load_text.to_string(),
            },
        })
        .await;
    let _ = complete_at(&backend, &load_uri, load_text, 2, 24).await;

    // After loading, the same filtering should apply via the ast_map fast path.

    // extends (class): final classes excluded, V8Js included.
    let uri1 = Url::parse("file:///test_v8_loaded_ext.php").unwrap();
    let text1 = "<?php\nclass A extends V8Js";
    let items1 = complete_at(&backend, &uri1, text1, 1, 22).await;
    let cls1 = class_items(&items1);
    let lbls1: Vec<&str> = cls1.iter().map(|i| i.label.as_str()).collect();
    assert!(
        lbls1.contains(&"V8Js"),
        "loaded non-final class V8Js should be included in class extends, got: {lbls1:?}"
    );
    assert!(
        !lbls1.contains(&"V8JsScriptException"),
        "loaded final class should be excluded from class extends, got: {lbls1:?}"
    );

    // implements: all are classes → excluded.
    let uri2 = Url::parse("file:///test_v8_loaded_impl.php").unwrap();
    let text2 = "<?php\nclass C implements V8Js";
    let items2 = complete_at(&backend, &uri2, text2, 1, 25).await;
    let cls2 = class_items(&items2);
    let lbls2: Vec<&str> = cls2.iter().map(|i| i.label.as_str()).collect();
    assert!(
        !lbls2.contains(&"V8JsScriptException"),
        "loaded class should be excluded from implements, got: {lbls2:?}"
    );

    // new: final concrete classes are instantiable.
    let uri3 = Url::parse("file:///test_v8_loaded_new.php").unwrap();
    let text3 = "<?php\nnew V8Js";
    let items3 = complete_at(&backend, &uri3, text3, 1, 8).await;
    let cls3 = class_items(&items3);
    let lbls3: Vec<&str> = cls3.iter().map(|i| i.label.as_str()).collect();
    assert!(
        lbls3.contains(&"V8JsScriptException"),
        "loaded final concrete class should be included in new, got: {lbls3:?}"
    );
}

// ─── use import context ─────────────────────────────────────────────────────

/// Top-level `use` should only offer class-like names, not constants or
/// functions (unlike the plain/Any context).
#[tokio::test]
async fn test_use_import_excludes_constants_and_functions() {
    let backend = create_test_backend_with_stubs();

    let scaffolding_uri = Url::parse("file:///use_scaffold.php").unwrap();
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: scaffolding_uri,
                language_id: "php".to_string(),
                version: 1,
                text: concat!("<?php\n", "namespace Scaffold;\n", "class SomeWidget {}\n",)
                    .to_string(),
            },
        })
        .await;

    // Register a global function so we can verify it's excluded.
    {
        let mut fmap = backend.global_functions().write();
        fmap.insert(
            "some_widget_func".to_string(),
            (
                "file:///funcs.php".to_string(),
                phpantom_lsp::types::FunctionInfo {
                    name: "some_widget_func".to_string(),
                    name_offset: 0,
                    parameters: vec![],
                    return_type: None,
                    native_return_type: None,
                    description: None,
                    return_description: None,
                    links: vec![],
                    see_refs: vec![],
                    namespace: None,
                    conditional_return: None,
                    type_assertions: vec![],
                    deprecation_message: None,
                    deprecated_replacement: None,
                    template_params: vec![],
                    template_bindings: vec![],
                    throws: vec![],
                    is_polyfill: false,
                },
            ),
        );
    }

    let uri = Url::parse("file:///use_test.php").unwrap();
    // `use Some` — top-level use import context.
    let text = concat!("<?php\n", "use Some\n",);

    let items = complete_at(&backend, &uri, text, 1, 8).await;

    let has_class = items
        .iter()
        .any(|i| i.kind == Some(CompletionItemKind::CLASS));
    let has_function = items
        .iter()
        .any(|i| i.kind == Some(CompletionItemKind::FUNCTION));

    assert!(has_class, "use import should offer classes, got: {items:?}");
    assert!(
        !has_function,
        "use import should NOT offer functions, got labels: {:?}",
        labels(&items)
    );
}

/// Typing `use f` should inject "function" as a keyword suggestion.
#[tokio::test]
async fn test_use_import_suggests_function_keyword() {
    let backend = create_test_backend_with_stubs();

    let uri = Url::parse("file:///use_f.php").unwrap();
    let text = concat!("<?php\n", "use f\n",);

    let items = complete_at(&backend, &uri, text, 1, 5).await;

    let kw_items: Vec<&CompletionItem> = items
        .iter()
        .filter(|i| i.kind == Some(CompletionItemKind::KEYWORD))
        .collect();
    let kw_labels: Vec<&str> = kw_items.iter().map(|i| i.label.as_str()).collect();

    assert!(
        kw_labels.contains(&"function"),
        "`use f` should suggest 'function' keyword, got: {kw_labels:?}"
    );

    // The keyword insert_text should include a trailing space.
    let func_kw = kw_items.iter().find(|i| i.label == "function").unwrap();
    assert_eq!(
        func_kw.insert_text.as_deref(),
        Some("function "),
        "function keyword insert_text should have trailing space"
    );
}

/// Typing `use c` should inject "const" as a keyword suggestion.
#[tokio::test]
async fn test_use_import_suggests_const_keyword() {
    let backend = create_test_backend_with_stubs();

    let uri = Url::parse("file:///use_c.php").unwrap();
    let text = concat!("<?php\n", "use c\n",);

    let items = complete_at(&backend, &uri, text, 1, 5).await;

    let kw_labels: Vec<&str> = items
        .iter()
        .filter(|i| i.kind == Some(CompletionItemKind::KEYWORD))
        .map(|i| i.label.as_str())
        .collect();

    assert!(
        kw_labels.contains(&"const"),
        "`use c` should suggest 'const' keyword, got: {kw_labels:?}"
    );
}

/// Typing `use F` (uppercase) should NOT suggest the "function" keyword
/// because PHP keywords are case-sensitive lowercase.
#[tokio::test]
async fn test_use_import_no_keyword_for_uppercase() {
    let backend = create_test_backend_with_stubs();

    let uri = Url::parse("file:///use_upper.php").unwrap();
    let text = concat!("<?php\n", "use F\n",);

    let items = complete_at(&backend, &uri, text, 1, 5).await;

    let kw_labels: Vec<&str> = items
        .iter()
        .filter(|i| i.kind == Some(CompletionItemKind::KEYWORD))
        .map(|i| i.label.as_str())
        .collect();

    assert!(
        !kw_labels.contains(&"function"),
        "`use F` (uppercase) should NOT suggest 'function', got: {kw_labels:?}"
    );
}

/// `use function` context should only show functions, not classes.
#[tokio::test]
async fn test_use_function_shows_only_functions() {
    let backend = create_test_backend_with_stubs();

    // Register a function that will match our partial.
    {
        let mut fmap = backend.global_functions().write();
        fmap.insert(
            "array_merge".to_string(),
            (
                "file:///funcs.php".to_string(),
                phpantom_lsp::types::FunctionInfo {
                    name: "array_merge".to_string(),
                    name_offset: 0,
                    parameters: vec![],
                    return_type: Some(PhpType::parse("array")),
                    native_return_type: None,
                    description: None,
                    return_description: None,
                    links: vec![],
                    see_refs: vec![],
                    namespace: None,
                    conditional_return: None,
                    type_assertions: vec![],
                    deprecation_message: None,
                    deprecated_replacement: None,
                    template_params: vec![],
                    template_bindings: vec![],
                    throws: vec![],
                    is_polyfill: false,
                },
            ),
        );
    }

    let uri = Url::parse("file:///use_func.php").unwrap();
    let text = concat!("<?php\n", "use function array_m\n",);

    let items = complete_at(&backend, &uri, text, 1, 20).await;

    let has_function = items
        .iter()
        .any(|i| i.kind == Some(CompletionItemKind::FUNCTION));
    let has_class = items
        .iter()
        .any(|i| i.kind == Some(CompletionItemKind::CLASS));

    assert!(
        has_function,
        "`use function` should offer functions, got: {:?}",
        labels(&items)
    );
    assert!(
        !has_class,
        "`use function` should NOT offer classes, got: {:?}",
        labels(&items)
    );
}

/// `use const` context should only show constants, not classes or functions.
#[tokio::test]
async fn test_use_const_shows_only_constants() {
    let backend = create_test_backend_with_stubs();

    // Register a constant that will match our partial.
    {
        let mut dmap = backend.global_defines().write();
        dmap.insert(
            "APP_VERSION".to_string(),
            phpantom_lsp::DefineInfo {
                file_uri: "file:///config.php".to_string(),
                name_offset: 0,
                value: Some("'1.0.0'".to_string()),
            },
        );
    }

    let uri = Url::parse("file:///use_const.php").unwrap();
    let text = concat!("<?php\n", "use const APP_V\n",);

    let items = complete_at(&backend, &uri, text, 1, 15).await;

    let has_constant = items
        .iter()
        .any(|i| i.kind == Some(CompletionItemKind::CONSTANT));
    let has_class = items
        .iter()
        .any(|i| i.kind == Some(CompletionItemKind::CLASS));
    let has_function = items
        .iter()
        .any(|i| i.kind == Some(CompletionItemKind::FUNCTION));

    assert!(
        has_constant,
        "`use const` should offer constants, got: {:?}",
        labels(&items)
    );
    assert!(
        !has_class,
        "`use const` should NOT offer classes, got: {:?}",
        labels(&items)
    );
    assert!(
        !has_function,
        "`use const` should NOT offer functions, got: {:?}",
        labels(&items)
    );
}

/// Trait `use` inside a class body should NOT be affected by the new
/// When typing `use De` and picking `Decimal\Decimal`, the result should be
/// `use Decimal\Decimal;` — NOT `use Decimal;` with a redundant additional
/// `use Decimal\Decimal;` text edit.
#[tokio::test]
async fn test_use_import_inserts_fqn_no_redundant_text_edit() {
    let backend = create_test_backend();

    // Load a namespaced class so it appears in completions.
    let scaffolding_uri = Url::parse("file:///decimal_scaffolding.php").unwrap();
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: scaffolding_uri,
                language_id: "php".to_string(),
                version: 1,
                text: "<?php\nnamespace Decimal;\nclass Decimal {}\n".to_string(),
            },
        })
        .await;

    let uri = Url::parse("file:///test_use_fqn.php").unwrap();
    let text = "<?php\nuse De";

    let items = complete_at(&backend, &uri, text, 1, 6).await;
    let cls = class_items(&items);
    let decimal = cls
        .iter()
        .find(|i| i.detail.as_deref() == Some("Decimal\\Decimal"))
        .expect("should find Decimal\\Decimal in completions");

    // The insert text must be the FQN (not just the short name).
    let insert = decimal.insert_text.as_deref().unwrap_or("");
    assert!(
        insert.contains("Decimal\\Decimal"),
        "insert_text should be the FQN, got: {insert:?}"
    );

    // There must be NO additional text edit (no redundant `use` statement).
    assert!(
        decimal.additional_text_edits.is_none()
            || decimal.additional_text_edits.as_ref().unwrap().is_empty(),
        "should not generate a redundant use text edit, got: {:?}",
        decimal.additional_text_edits
    );
}

/// Same-namespace classes should still show the FQN in UseImport context,
/// not a simplified relative name (which would be invalid in a `use` statement).
#[tokio::test]
async fn test_use_import_same_namespace_still_uses_fqn() {
    let backend = create_test_backend();

    // Load a class in namespace App\Models.
    let scaffolding_uri = Url::parse("file:///models_scaffolding.php").unwrap();
    backend
        .did_open(DidOpenTextDocumentParams {
            text_document: TextDocumentItem {
                uri: scaffolding_uri,
                language_id: "php".to_string(),
                version: 1,
                text: "<?php\nnamespace App\\Models;\nclass Order {}\n".to_string(),
            },
        })
        .await;

    // The test file is in the SAME namespace.
    let uri = Url::parse("file:///test_same_ns_use.php").unwrap();
    let text = "<?php\nnamespace App\\Models;\nuse App\\Models\\Or";

    let items = complete_at(&backend, &uri, text, 2, 19).await;
    let cls = class_items(&items);
    let order = cls
        .iter()
        .find(|i| i.detail.as_deref() == Some("App\\Models\\Order"))
        .expect("should find App\\Models\\Order in completions");

    // The insert text must be the full FQN, not just "Order".
    let insert = order.insert_text.as_deref().unwrap_or("");
    assert!(
        insert.contains("App\\Models\\Order"),
        "insert_text should be the full FQN even in same namespace, got: {insert:?}"
    );
}

/// UseImport logic — it should still only offer traits.
#[tokio::test]
async fn test_trait_use_not_affected_by_use_import() {
    let backend = create_test_backend();
    load_scaffolding(&backend).await;

    let uri = Url::parse("file:///trait_use_unchanged.php").unwrap();
    let text = concat!(
        "<?php\n",
        "namespace Scaffold;\n",
        "class Foo {\n",
        "    use Some\n",
        "}\n",
    );

    let items = complete_at(&backend, &uri, text, 3, 12).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        lbls.contains(&"SomeTrait"),
        "trait use should still offer traits, got: {lbls:?}"
    );
    assert!(
        !lbls.contains(&"ConcreteClass"),
        "trait use should still exclude classes, got: {lbls:?}"
    );
}

/// Use-map entries that resolve to stub interfaces or classes must be
/// filtered out in `TraitUse` context.  Previously, unloaded stubs in
/// the use-map bypassed the context filter because
/// `matches_context_or_unloaded` returned `true` for anything not in
/// the ast_map.
#[tokio::test]
async fn test_trait_use_filters_stub_use_map_entries() {
    use std::collections::HashMap;

    let mut stubs: HashMap<&'static str, &'static str> = HashMap::new();
    // Stringable is an interface — must NOT appear in trait-use.
    stubs.insert(
        "Stringable",
        "<?php\ninterface Stringable {\n    public function __toString(): string;\n}\n",
    );
    // Exception is a class — must NOT appear in trait-use.
    stubs.insert(
        "Cassandra\\Exception",
        "<?php\nnamespace Cassandra;\nclass Exception extends \\Exception {}\n",
    );
    // A stub trait — MUST appear in trait-use.
    stubs.insert(
        "Cassandra\\RetryPolicy",
        "<?php\nnamespace Cassandra;\ntrait RetryPolicy {}\n",
    );
    let backend = Backend::new_test_with_stubs(stubs);

    let uri = Url::parse("file:///test_trait_use_stub_usemap.php").unwrap();
    // Test with partial "S" — matches Stringable (interface, should be
    // excluded) but not RetryPolicy or Exception.
    let text_s = concat!(
        "<?php\n",
        "namespace Demo;\n",
        "use Stringable;\n",
        "use Cassandra\\Exception;\n",
        "use Cassandra\\RetryPolicy;\n",
        "class A {\n",
        "    use S\n",
        "}\n",
    );
    let items_s = complete_at(&backend, &uri, text_s, 6, 9).await;
    let cls_s = class_items(&items_s);
    let lbls_s: Vec<&str> = cls_s.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls_s.contains(&"Stringable"),
        "stub interface Stringable should be excluded from trait use, got: {lbls_s:?}"
    );

    // Test with partial "E" — matches Exception (class, should be
    // excluded) but not RetryPolicy or Stringable.
    let uri_e = Url::parse("file:///test_trait_use_stub_usemap_e.php").unwrap();
    let text_e = concat!(
        "<?php\n",
        "namespace Demo;\n",
        "use Stringable;\n",
        "use Cassandra\\Exception;\n",
        "use Cassandra\\RetryPolicy;\n",
        "class A {\n",
        "    use E\n",
        "}\n",
    );
    let items_e = complete_at(&backend, &uri_e, text_e, 6, 9).await;
    let cls_e = class_items(&items_e);
    let lbls_e: Vec<&str> = cls_e.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls_e.contains(&"Cassandra\\Exception"),
        "stub class Cassandra\\Exception should be excluded from trait use, got: {lbls_e:?}"
    );

    // Test with partial "R" — matches RetryPolicy (trait, should be
    // included).
    let uri_r = Url::parse("file:///test_trait_use_stub_usemap_r.php").unwrap();
    let text_r = concat!(
        "<?php\n",
        "namespace Demo;\n",
        "use Stringable;\n",
        "use Cassandra\\Exception;\n",
        "use Cassandra\\RetryPolicy;\n",
        "class A {\n",
        "    use R\n",
        "}\n",
    );
    let items_r = complete_at(&backend, &uri_r, text_r, 6, 9).await;
    let cls_r = class_items(&items_r);
    let fqns_r = fqn_labels(&cls_r);

    assert!(
        fqns_r.contains(&"Cassandra\\RetryPolicy"),
        "stub trait RetryPolicy should be included in trait use, got: {fqns_r:?}"
    );
}

/// Use-map entries whose FQN is not found in any class source (ast_map,
/// class_index, classmap, stub_index) must be rejected in narrow
/// contexts like `TraitUse`.  A non-existent import like
/// `use Cassandra\ExceptionInterface;` should not pollute trait-use
/// completions.
#[tokio::test]
async fn test_trait_use_rejects_unknown_use_map_entries() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///test_trait_use_unknown.php").unwrap();
    // `Cassandra\ExceptionInterface` does not exist in any index.
    let text = concat!(
        "<?php\n",
        "namespace Demo;\n",
        "use Cassandra\\ExceptionInterface;\n",
        "class A {\n",
        "    use E\n",
        "}\n",
    );

    let items = complete_at(&backend, &uri, text, 4, 9).await;
    let cls = class_items(&items);
    let lbls: Vec<&str> = cls.iter().map(|i| i.label.as_str()).collect();

    assert!(
        !lbls.contains(&"Cassandra\\ExceptionInterface"),
        "unknown use-map entry should be excluded from trait use, got: {lbls:?}"
    );
}