php-lsp 0.1.52

A PHP Language Server Protocol implementation
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
mod keyword;
pub use keyword::{keyword_completions, magic_constant_completions};

mod symbols;
pub use symbols::{
    builtin_completions, superglobal_completions, symbol_completions, symbol_completions_before,
};

mod member;
use member::{
    all_instance_members, all_static_members, magic_method_completions, resolve_receiver_class,
    resolve_static_receiver,
};

mod namespace;
use namespace::{
    collect_classes_with_ns, collect_fqns_with_prefix, current_file_namespace, typed_prefix,
    use_completion_prefix, use_insert_position,
};

use std::sync::Arc;

use tower_lsp::lsp_types::{
    CompletionItem, CompletionItemKind, InsertTextFormat, Position, Range, TextEdit, Url,
};

use tower_lsp::lsp_types::{Documentation, MarkupContent, MarkupKind};

use crate::ast::{ParsedDoc, format_type_hint};
use crate::docblock::find_docblock;
use crate::hover::format_params_str;
use crate::phpstorm_meta::PhpStormMeta;
use crate::type_map::{
    TypeMap, enclosing_class_at, members_of_class, params_of_function, params_of_method,
};
use crate::util::{camel_sort_key, fuzzy_camel_match, utf16_offset_to_byte};
use std::collections::HashMap;

/// Build a `CompletionItem` for a callable (function or method).
///
/// If the function has parameters the item uses snippet format with `$1`
/// inside the parentheses so the cursor lands there.  Zero-parameter
/// callables insert `name()` as plain text.
fn callable_item(label: &str, kind: CompletionItemKind, has_params: bool) -> CompletionItem {
    if has_params {
        CompletionItem {
            label: label.to_string(),
            kind: Some(kind),
            insert_text: Some(format!("{}($1)", label)),
            insert_text_format: Some(InsertTextFormat::SNIPPET),
            ..Default::default()
        }
    } else {
        CompletionItem {
            label: label.to_string(),
            kind: Some(kind),
            insert_text: Some(format!("{}()", label)),
            ..Default::default()
        }
    }
}

/// Build a named-argument `CompletionItem` for a callable when param names are
/// known.  Produces a label like `create(name:, age:)` and a snippet like
/// `create(name: $1, age: $2)`.  Returns `None` when the param list is empty
/// (no advantage over the positional item in that case).
fn named_arg_item(
    label: &str,
    kind: CompletionItemKind,
    params: &[php_ast::Param<'_, '_>],
) -> Option<CompletionItem> {
    if params.is_empty() {
        return None;
    }
    let named_label = format!(
        "{}({})",
        label,
        params
            .iter()
            .map(|p| format!("{}:", p.name))
            .collect::<Vec<_>>()
            .join(", ")
    );
    let snippet = format!(
        "{}({})",
        label,
        params
            .iter()
            .enumerate()
            .map(|(i, p)| format!("{}: ${}", p.name, i + 1))
            .collect::<Vec<_>>()
            .join(", ")
    );
    Some(CompletionItem {
        label: named_label,
        kind: Some(kind),
        insert_text: Some(snippet),
        insert_text_format: Some(InsertTextFormat::SNIPPET),
        detail: Some("named args".to_string()),
        ..Default::default()
    })
}

/// Build the full signature string for a callable, e.g.
/// `"function foo(string $bar, int $baz): bool"`.
fn build_function_sig(
    name: &str,
    params: &[php_ast::Param<'_, '_>],
    return_type: Option<&php_ast::TypeHint<'_, '_>>,
) -> String {
    let params_str = format_params_str(params);
    let ret = return_type
        .map(|r| format!(": {}", format_type_hint(r)))
        .unwrap_or_default();
    format!("function {}({}){}", name, params_str, ret)
}

/// Build a `Documentation` value from a docblock found before `sym_name` in `doc`.
fn docblock_docs(doc: &ParsedDoc, sym_name: &str) -> Option<Documentation> {
    let db = find_docblock(doc.source(), &doc.program().stmts, sym_name)?;
    let md = db.to_markdown();
    if md.is_empty() {
        None
    } else {
        Some(Documentation::MarkupContent(MarkupContent {
            kind: MarkupKind::Markdown,
            value: md,
        }))
    }
}

/// If the `(` trigger occurs inside an attribute like `#[ClassName(`, extract
/// the attribute class name so we can offer its `__construct` parameter names.
fn resolve_attribute_class(source: &str, position: Position) -> Option<String> {
    let line = source.lines().nth(position.line as usize)?;
    let col = utf16_offset_to_byte(line, position.character as usize);
    let before = line[..col].trim_end_matches('(').trim_end();
    // Look backwards on the same line for `#[ClassName` or `#[\NS\ClassName`
    let hash_pos = before.rfind("#[")?;
    let after_bracket = before[hash_pos + 2..].trim_start();
    // Strip leading backslashes (FQN), keep the short name
    let name: String = after_bracket
        .trim_start_matches('\\')
        .rsplit('\\')
        .next()
        .unwrap_or("")
        .chars()
        .take_while(|c| c.is_alphanumeric() || *c == '_')
        .collect();
    if name.is_empty() { None } else { Some(name) }
}

fn resolve_call_params(
    source: &str,
    doc: &ParsedDoc,
    other_docs: &[Arc<ParsedDoc>],
    position: Position,
) -> Vec<String> {
    let line = match source.lines().nth(position.line as usize) {
        Some(l) => l,
        None => return vec![],
    };
    let col = utf16_offset_to_byte(line, position.character as usize);
    let before = &line[..col];
    let before = before.strip_suffix('(').unwrap_or(before);
    let func_name: String = before
        .chars()
        .rev()
        .take_while(|&c| c.is_alphanumeric() || c == '_')
        .collect::<String>()
        .chars()
        .rev()
        .collect();
    if func_name.is_empty() {
        return vec![];
    }
    let mut params = params_of_function(doc, &func_name);
    if params.is_empty() {
        for other in other_docs {
            params = params_of_function(other, &func_name);
            if !params.is_empty() {
                break;
            }
        }
    }
    params
}

/// Optional context for completion requests that enables richer results
/// (e.g. auto-import edits, `->` scoping to a class).
#[derive(Default)]
pub struct CompletionCtx<'a> {
    pub source: Option<&'a str>,
    pub position: Option<Position>,
    pub meta: Option<&'a PhpStormMeta>,
    pub doc_uri: Option<&'a Url>,
    pub file_imports: Option<&'a HashMap<String, String>>,
}

/// Completions filtered by trigger character, with optional context
/// so that `->` completions can be scoped to the variable's class.
pub fn filtered_completions_at(
    doc: &ParsedDoc,
    other_docs: &[Arc<ParsedDoc>],
    trigger_character: Option<&str>,
    ctx: &CompletionCtx<'_>,
) -> Vec<CompletionItem> {
    let source = ctx.source;
    let position = ctx.position;
    let meta = ctx.meta;
    let doc_uri = ctx.doc_uri;
    let empty_imports = HashMap::new();
    let imports = ctx.file_imports.unwrap_or(&empty_imports);
    match trigger_character {
        Some("$") => {
            let mut items = superglobal_completions();
            items.extend(
                symbol_completions(doc)
                    .into_iter()
                    .filter(|i| i.kind == Some(CompletionItemKind::VARIABLE)),
            );
            items
        }
        Some(">") => {
            // Arrow: $obj->  or  $this->
            if let (Some(src), Some(pos)) = (source, position) {
                let type_map = TypeMap::from_docs_with_meta(doc, other_docs, meta);
                if let Some(class_names) = resolve_receiver_class(src, doc, pos, &type_map) {
                    // Feature 5: support union types (Foo|Bar)
                    let mut items = Vec::new();
                    let mut seen = std::collections::HashSet::new();
                    for class_name in class_names.split('|') {
                        let class_name = class_name.trim();
                        for item in all_instance_members(class_name, doc, other_docs) {
                            if seen.insert(item.label.clone()) {
                                items.push(item);
                            }
                        }
                    }
                    if !items.is_empty() {
                        return items;
                    }
                }
            }
            // Fallback: all methods from current doc
            symbol_completions(doc)
                .into_iter()
                .filter(|i| i.kind == Some(CompletionItemKind::METHOD))
                .collect()
        }
        Some(":") => {
            // Static access: ClassName:: / self:: / static:: / parent::
            if let (Some(src), Some(pos)) = (source, position)
                && let Some(class_name) = resolve_static_receiver(src, doc, other_docs, pos)
            {
                let items = all_static_members(&class_name, doc, other_docs);
                if !items.is_empty() {
                    return items;
                }
            }
            vec![]
        }
        Some("[") => {
            // PHP attribute: #[ — suggest attribute classes
            if let (Some(src), Some(pos)) = (source, position) {
                let line = src.lines().nth(pos.line as usize).unwrap_or("");
                let col = utf16_offset_to_byte(line, pos.character as usize);
                let before = &line[..col];
                if before.trim_end_matches('[').trim_end().ends_with('#') {
                    let mut items: Vec<CompletionItem> = Vec::new();
                    let cur_ns = current_file_namespace(&doc.program().stmts);
                    let mut seen = std::collections::HashSet::new();

                    // Current doc: no auto-import needed (same file).
                    let mut cur_classes = Vec::new();
                    collect_classes_with_ns(&doc.program().stmts, "", &mut cur_classes);
                    for (label, _kind, _fqn) in cur_classes {
                        if seen.insert(label.clone()) {
                            items.push(CompletionItem {
                                label,
                                kind: Some(CompletionItemKind::CLASS),
                                ..Default::default()
                            });
                        }
                    }

                    // Other docs: add `use` statement when crossing namespaces.
                    for other in other_docs {
                        let mut classes = Vec::new();
                        collect_classes_with_ns(&other.program().stmts, "", &mut classes);
                        for (label, _kind, fqn) in classes {
                            if !seen.insert(label.clone()) {
                                continue;
                            }
                            let in_same_ns =
                                !cur_ns.is_empty() && fqn == format!("{}\\{}", cur_ns, label);
                            let is_global = !fqn.contains('\\');
                            let already = imports.contains_key(&label);
                            let additional_text_edits = if !in_same_ns && !is_global && !already {
                                let insert_pos = use_insert_position(src);
                                Some(vec![TextEdit {
                                    range: Range {
                                        start: insert_pos,
                                        end: insert_pos,
                                    },
                                    new_text: format!("use {};\n", fqn),
                                }])
                            } else {
                                None
                            };
                            items.push(CompletionItem {
                                label,
                                kind: Some(CompletionItemKind::CLASS),
                                detail: if fqn.contains('\\') { Some(fqn) } else { None },
                                additional_text_edits,
                                ..Default::default()
                            });
                        }
                    }
                    return items;
                }
            }
            vec![]
        }
        Some("(") => {
            // Named argument: funcName(
            if let (Some(src), Some(pos)) = (source, position) {
                let params = resolve_call_params(src, doc, other_docs, pos);
                if !params.is_empty() {
                    return params
                        .into_iter()
                        .map(|p| CompletionItem {
                            label: format!("{p}:"),
                            kind: Some(CompletionItemKind::VARIABLE),
                            ..Default::default()
                        })
                        .collect();
                }
                // Attribute constructor: #[ClassName(
                if let Some(attr_class) = resolve_attribute_class(src, pos) {
                    let mut attr_params = params_of_method(doc, &attr_class, "__construct");
                    if attr_params.is_empty() {
                        for other in other_docs {
                            attr_params = params_of_method(other, &attr_class, "__construct");
                            if !attr_params.is_empty() {
                                break;
                            }
                        }
                    }
                    if !attr_params.is_empty() {
                        return attr_params
                            .into_iter()
                            .map(|p| CompletionItem {
                                label: format!("{p}:"),
                                kind: Some(CompletionItemKind::VARIABLE),
                                detail: Some(format!("#{attr_class} argument")),
                                ..Default::default()
                            })
                            .collect();
                    }
                }
            }
            vec![]
        }
        _ => {
            // Feature 4: detect `use ` context and suggest FQNs from other docs
            if let (Some(src), Some(pos)) = (source, position)
                && let Some(use_prefix) = use_completion_prefix(src, pos)
            {
                let mut use_items: Vec<CompletionItem> = Vec::new();
                for other in other_docs {
                    collect_fqns_with_prefix(
                        &other.program().stmts,
                        "",
                        &use_prefix,
                        &mut use_items,
                    );
                }
                // Also check current doc
                collect_fqns_with_prefix(&doc.program().stmts, "", &use_prefix, &mut use_items);
                if !use_items.is_empty() {
                    return use_items;
                }
            }

            // Feature 9: include/require path completions
            if let (Some(src), Some(pos), Some(uri)) = (source, position, doc_uri)
                && let Some(prefix) = include_path_prefix(src, pos)
            {
                let items = include_path_completions(uri, &prefix);
                if !items.is_empty() {
                    return items;
                }
            }

            // Feature 3: Sub-namespace \ completions outside use statement
            if let (Some(src), Some(pos)) = (source, position)
                && let Some(prefix) = typed_prefix(Some(src), Some(pos))
                && prefix.contains('\\')
            {
                // Check we're NOT in a use statement
                let is_use = use_completion_prefix(src, pos).is_some();
                if !is_use {
                    let mut ns_items: Vec<CompletionItem> = Vec::new();
                    for other in other_docs {
                        let mut classes = Vec::new();
                        collect_classes_with_ns(&other.program().stmts, "", &mut classes);
                        for (label, kind, fqn) in classes {
                            if fqn.to_lowercase().starts_with(&prefix.to_lowercase()) {
                                ns_items.push(CompletionItem {
                                    label: label.clone(),
                                    kind: Some(kind),
                                    insert_text: Some(label),
                                    detail: Some(fqn),
                                    ..Default::default()
                                });
                            }
                        }
                    }
                    let mut classes = Vec::new();
                    collect_classes_with_ns(&doc.program().stmts, "", &mut classes);
                    for (label, kind, fqn) in classes {
                        if fqn.to_lowercase().starts_with(&prefix.to_lowercase()) {
                            ns_items.push(CompletionItem {
                                label: label.clone(),
                                kind: Some(kind),
                                insert_text: Some(label),
                                detail: Some(fqn),
                                ..Default::default()
                            });
                        }
                    }
                    if !ns_items.is_empty() {
                        return ns_items;
                    }
                }
            }

            // Feature 7: match arm completions
            if let (Some(src), Some(pos)) = (source, position)
                && let Some(match_items) = match_arm_completions(src, doc, other_docs, pos, meta)
                && !match_items.is_empty()
            {
                let mut all = match_items;
                // extend with normal items below, but return early here
                let mut normal_items = keyword_completions();
                normal_items.extend(magic_constant_completions());
                normal_items.extend(builtin_completions());
                normal_items.extend(superglobal_completions());
                normal_items.extend(symbol_completions(doc));
                all.extend(normal_items);
                return all;
            }

            // Feature 5: Magic method completions in class body
            let mut magic_items: Vec<CompletionItem> = Vec::new();
            if let (Some(src), Some(pos)) = (source, position)
                && enclosing_class_at(src, doc, pos).is_some()
            {
                magic_items.extend(magic_method_completions());
            }

            let mut items = keyword_completions();
            items.extend(magic_constant_completions());
            items.extend(builtin_completions());
            items.extend(superglobal_completions());
            // Feature 2: scope variable completions to before cursor line
            let sym_items = if let (Some(_src), Some(pos)) = (source, position) {
                symbol_completions_before(doc, pos.line)
            } else {
                symbol_completions(doc)
            };
            items.extend(sym_items);
            items.extend(magic_items);

            let cur_ns = current_file_namespace(&doc.program().stmts);

            for other in other_docs {
                // Class-like symbols: add `use` insertion when needed.
                let mut classes: Vec<(String, CompletionItemKind, String)> = Vec::new();
                collect_classes_with_ns(&other.program().stmts, "", &mut classes);
                for (label, kind, fqn) in classes {
                    let additional_text_edits = if let Some(src) = source {
                        let in_same_ns =
                            !cur_ns.is_empty() && fqn == format!("{}\\{}", cur_ns, label);
                        let is_global = !fqn.contains('\\');
                        let already = imports.contains_key(&label);
                        if !in_same_ns && !is_global && !already {
                            let pos = use_insert_position(src);
                            Some(vec![TextEdit {
                                range: Range {
                                    start: pos,
                                    end: pos,
                                },
                                new_text: format!("use {};\n", fqn),
                            }])
                        } else {
                            None
                        }
                    } else {
                        None
                    };
                    items.push(CompletionItem {
                        label,
                        kind: Some(kind),
                        detail: if fqn.contains('\\') { Some(fqn) } else { None },
                        additional_text_edits,
                        ..Default::default()
                    });
                }
                // Non-class symbols (functions, methods, constants) need no use statement.
                let cross: Vec<CompletionItem> = symbol_completions(other)
                    .into_iter()
                    .filter(|i| {
                        !matches!(
                            i.kind,
                            Some(CompletionItemKind::CLASS)
                                | Some(CompletionItemKind::INTERFACE)
                                | Some(CompletionItemKind::ENUM)
                        ) && i.kind != Some(CompletionItemKind::VARIABLE)
                    })
                    .collect();
                items.extend(cross);
            }
            let mut seen = std::collections::HashSet::new();
            items.retain(|i| seen.insert(i.label.clone()));

            // Extract the typed prefix for fuzzy camel/underscore filtering.
            let prefix = typed_prefix(source, position).unwrap_or_default();
            if prefix.contains('\\') {
                // Namespace-qualified prefix: filter by FQN prefix match.
                let ns_prefix = prefix.trim_start_matches('\\').to_lowercase();
                items.retain(|i| {
                    let fqn = i.detail.as_deref().unwrap_or(&i.label);
                    fqn.to_lowercase().starts_with(&ns_prefix)
                });
            } else if !prefix.is_empty() {
                items.retain(|i| fuzzy_camel_match(&prefix, &i.label));
                for item in &mut items {
                    item.sort_text = Some(camel_sort_key(&prefix, &item.label));
                    item.filter_text = Some(item.label.clone());
                }
            }
            items
        }
    }
}

fn match_arm_completions(
    source: &str,
    doc: &ParsedDoc,
    other_docs: &[Arc<ParsedDoc>],
    position: Position,
    meta: Option<&PhpStormMeta>,
) -> Option<Vec<CompletionItem>> {
    let start_line = position.line as usize;
    let end_line = start_line.saturating_sub(5);
    for line_idx in (end_line..=start_line).rev() {
        let line = source.lines().nth(line_idx)?;
        if let Some(cap) = extract_match_subject(line) {
            let type_map = TypeMap::from_docs_with_meta(doc, other_docs, meta);
            let class_name = if cap == "this" {
                enclosing_class_at(source, doc, position)?
            } else {
                type_map.get(&format!("${cap}"))?.to_string()
            };
            let all_docs: Vec<&ParsedDoc> = std::iter::once(doc)
                .chain(other_docs.iter().map(|d| d.as_ref()))
                .collect();
            for d in &all_docs {
                let members = members_of_class(d, &class_name);
                if !members.constants.is_empty() {
                    return Some(
                        members
                            .constants
                            .iter()
                            .map(|c| CompletionItem {
                                label: format!("{class_name}::{c}"),
                                kind: Some(CompletionItemKind::CONSTANT),
                                ..Default::default()
                            })
                            .collect(),
                    );
                }
            }
        }
    }
    None
}

/// Returns the path prefix typed inside a string on an include/require line, or None.
/// Only triggers for relative paths (starting with `./`, `../`, or empty after the quote)
/// so that absolute-path strings are left alone.
fn include_path_prefix(source: &str, position: Position) -> Option<String> {
    let line = source.lines().nth(position.line as usize)?;
    let trimmed = line.trim_start();
    if !trimmed.starts_with("include") && !trimmed.starts_with("require") {
        return None;
    }
    // Find the string being typed
    let col = utf16_offset_to_byte(line, position.character as usize);
    let before = &line[..col];
    let quote_pos = before.rfind(['\'', '"'])?;
    let typed = &before[quote_pos + 1..];
    // Only offer completions for relative paths (./  ../  or empty start)
    // and not for absolute paths (starting with /) or PHP stream wrappers.
    if typed.starts_with('/') || typed.contains("://") {
        return None;
    }
    Some(typed.to_string())
}

/// Build completion items for include/require path strings.
///
/// `prefix` is the partial path typed so far (e.g. `"../lib/"` or `"./"`).
/// The returned `insert_text` for each item is the full replacement text
/// from the opening quote to the end of the completed entry, so that the
/// LSP client can replace the whole typed path (not just the last segment).
fn include_path_completions(doc_uri: &Url, prefix: &str) -> Vec<CompletionItem> {
    use std::path::Path;

    let doc_path = match doc_uri.to_file_path() {
        Ok(p) => p,
        Err(_) => return vec![],
    };
    let doc_dir = match doc_path.parent() {
        Some(d) => d.to_path_buf(),
        None => return vec![],
    };

    // Split prefix into a directory part (already traversed) and the partial filename.
    let (dir_prefix, typed_file) = if prefix.ends_with('/') || prefix.ends_with('\\') {
        (prefix.to_string(), String::new())
    } else {
        let p = Path::new(prefix);
        let parent = p
            .parent()
            .map(|p| {
                let s = p.to_string_lossy();
                if s.is_empty() {
                    String::new()
                } else {
                    format!("{}/", s)
                }
            })
            .unwrap_or_default();
        let file = p
            .file_name()
            .map(|f| f.to_string_lossy().into_owned())
            .unwrap_or_default();
        (parent, file)
    };

    let dir_to_list = doc_dir.join(&dir_prefix);

    let entries = match std::fs::read_dir(&dir_to_list) {
        Ok(e) => e,
        Err(_) => return vec![],
    };

    let mut items = Vec::new();
    for entry in entries.flatten() {
        let name = entry.file_name().to_string_lossy().into_owned();
        // Skip hidden files/dirs unless the prefix already starts with a dot.
        if name.starts_with('.') && !typed_file.starts_with('.') {
            continue;
        }
        let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
        let is_php = name.ends_with(".php") || name.ends_with(".inc") || name.ends_with(".phtml");
        if !is_dir && !is_php {
            continue;
        }
        let entry_name = if is_dir {
            format!("{}/", name)
        } else {
            name.clone()
        };
        // insert_text is the full path from the opening quote so the whole
        // typed prefix (e.g. "../lib/") is preserved in the replacement.
        let insert_text = format!("{}{}", dir_prefix, entry_name);
        items.push(CompletionItem {
            label: name,
            kind: Some(if is_dir {
                CompletionItemKind::FOLDER
            } else {
                CompletionItemKind::FILE
            }),
            insert_text: Some(insert_text),
            ..Default::default()
        });
    }
    items.sort_by(|a, b| {
        // Directories first, then files
        let a_dir = a.kind == Some(CompletionItemKind::FOLDER);
        let b_dir = b.kind == Some(CompletionItemKind::FOLDER);
        b_dir.cmp(&a_dir).then(a.label.cmp(&b.label))
    });
    items
}

fn extract_match_subject(line: &str) -> Option<String> {
    let trimmed = line.trim();
    let after = trimmed.strip_prefix("match")?.trim_start();
    let after = after.strip_prefix('(')?;
    let inner: String = after.chars().take_while(|&c| c != ')').collect();
    let var = inner.trim().trim_start_matches('$');
    if var.is_empty() {
        None
    } else {
        Some(var.to_string())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn doc(source: &str) -> ParsedDoc {
        ParsedDoc::parse(source.to_string())
    }

    fn labels(items: &[CompletionItem]) -> Vec<&str> {
        items.iter().map(|i| i.label.as_str()).collect()
    }

    #[test]
    fn keywords_list_is_non_empty() {
        let kws = keyword_completions();
        assert!(
            kws.len() >= 20,
            "expected at least 20 keywords, got {}",
            kws.len()
        );
    }

    #[test]
    fn keywords_contain_common_php_keywords() {
        let kws = keyword_completions();
        let ls = labels(&kws);
        for expected in &[
            "function",
            "class",
            "return",
            "foreach",
            "match",
            "namespace",
        ] {
            assert!(ls.contains(expected), "missing keyword: {expected}");
        }
    }

    #[test]
    fn all_keyword_items_have_keyword_kind() {
        for item in keyword_completions() {
            assert_eq!(item.kind, Some(CompletionItemKind::KEYWORD));
        }
    }

    #[test]
    fn magic_constants_all_present() {
        let items = magic_constant_completions();
        let ls: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
        for name in &[
            "__FILE__",
            "__DIR__",
            "__LINE__",
            "__CLASS__",
            "__FUNCTION__",
            "__METHOD__",
            "__NAMESPACE__",
            "__TRAIT__",
        ] {
            assert!(ls.contains(name), "missing magic constant: {name}");
        }
    }

    #[test]
    fn magic_constants_have_constant_kind() {
        for item in magic_constant_completions() {
            assert_eq!(
                item.kind,
                Some(CompletionItemKind::CONSTANT),
                "{} should have CONSTANT kind",
                item.label
            );
        }
    }

    #[test]
    fn resolve_attribute_class_extracts_name() {
        let src = "<?php\n#[Route(\n";
        // Position right after the '(' on line 1
        let pos = Position {
            line: 1,
            character: 8,
        };
        let result = resolve_attribute_class(src, pos);
        assert_eq!(result.as_deref(), Some("Route"));
    }

    #[test]
    fn resolve_attribute_class_fqn_extracts_short_name() {
        let src = "<?php\n#[\\Symfony\\Component\\Routing\\Route(\n";
        let pos = Position {
            line: 1,
            character: 38,
        };
        let result = resolve_attribute_class(src, pos);
        assert_eq!(result.as_deref(), Some("Route"));
    }

    #[test]
    fn resolve_attribute_class_returns_none_for_regular_call() {
        let src = "<?php\nsomeFunction(\n";
        let pos = Position {
            line: 1,
            character: 14,
        };
        let result = resolve_attribute_class(src, pos);
        assert!(result.is_none(), "should not match regular function call");
    }

    #[test]
    fn extracts_top_level_function_name() {
        let d = doc("<?php\nfunction greet() {}");
        let items = symbol_completions(&d);
        assert!(labels(&items).contains(&"greet"));
        let greet = items.iter().find(|i| i.label == "greet").unwrap();
        assert_eq!(greet.kind, Some(CompletionItemKind::FUNCTION));
    }

    #[test]
    fn extracts_top_level_class_name() {
        let d = doc("<?php\nclass MyService {}");
        let items = symbol_completions(&d);
        assert!(labels(&items).contains(&"MyService"));
        let cls = items.iter().find(|i| i.label == "MyService").unwrap();
        assert_eq!(cls.kind, Some(CompletionItemKind::CLASS));
    }

    #[test]
    fn extracts_class_method_names() {
        let d = doc("<?php\nclass Calc { public function add() {} public function sub() {} }");
        let items = symbol_completions(&d);
        let ls = labels(&items);
        assert!(ls.contains(&"add"), "missing 'add'");
        assert!(ls.contains(&"sub"), "missing 'sub'");
        for item in items
            .iter()
            .filter(|i| i.label == "add" || i.label == "sub")
        {
            assert_eq!(item.kind, Some(CompletionItemKind::METHOD));
        }
    }

    #[test]
    fn extracts_function_parameters_as_variables() {
        let d = doc("<?php\nfunction process($input, $count) {}");
        let items = symbol_completions(&d);
        let ls = labels(&items);
        assert!(ls.contains(&"$input"), "missing '$input'");
        assert!(ls.contains(&"$count"), "missing '$count'");
    }

    #[test]
    fn extracts_symbols_inside_namespace() {
        let d = doc("<?php\nnamespace App {\nfunction render() {}\nclass View {}\n}");
        let items = symbol_completions(&d);
        let ls = labels(&items);
        assert!(ls.contains(&"render"), "missing 'render'");
        assert!(ls.contains(&"View"), "missing 'View'");
    }

    #[test]
    fn extracts_interface_name() {
        let d = doc("<?php\ninterface Serializable {}");
        let items = symbol_completions(&d);
        let item = items.iter().find(|i| i.label == "Serializable");
        assert!(item.is_some(), "missing 'Serializable'");
        assert_eq!(item.unwrap().kind, Some(CompletionItemKind::INTERFACE));
    }

    #[test]
    fn variable_assignment_produces_variable_item() {
        let d = doc("<?php\n$name = 'Alice';");
        let items = symbol_completions(&d);
        assert!(labels(&items).contains(&"$name"), "missing '$name'");
    }

    #[test]
    fn class_property_appears_in_completions() {
        let d = doc("<?php\nclass User { public string $name; private int $age; }");
        let items = symbol_completions(&d);
        let ls = labels(&items);
        assert!(ls.contains(&"$name"), "missing '$name'");
        assert!(ls.contains(&"$age"), "missing '$age'");
        for item in items
            .iter()
            .filter(|i| i.label == "$name" || i.label == "$age")
        {
            assert_eq!(item.kind, Some(CompletionItemKind::PROPERTY));
        }
    }

    #[test]
    fn class_constant_appears_in_completions() {
        let d = doc("<?php\nclass Status { const ACTIVE = 1; const INACTIVE = 0; }");
        let items = symbol_completions(&d);
        let ls = labels(&items);
        assert!(ls.contains(&"ACTIVE"), "missing 'ACTIVE'");
        assert!(ls.contains(&"INACTIVE"), "missing 'INACTIVE'");
    }

    #[test]
    fn dollar_trigger_returns_only_variables() {
        let d = doc("<?php\nfunction greet($name) {}\nclass Foo {}\n$bar = 1;");
        let items = filtered_completions_at(&d, &[], Some("$"), &CompletionCtx::default());
        assert!(!items.is_empty(), "should have variable items");
        for item in &items {
            assert_eq!(item.kind, Some(CompletionItemKind::VARIABLE));
        }
        let ls = labels(&items);
        assert!(!ls.contains(&"greet"), "should not contain function");
        assert!(!ls.contains(&"Foo"), "should not contain class");
    }

    #[test]
    fn arrow_trigger_returns_only_methods() {
        let d = doc("<?php\nclass Calc { public function add() {} public function sub() {} }");
        let items = filtered_completions_at(&d, &[], Some(">"), &CompletionCtx::default());
        assert!(!items.is_empty(), "should have method items");
        for item in &items {
            assert_eq!(item.kind, Some(CompletionItemKind::METHOD));
        }
    }

    #[test]
    fn none_trigger_returns_keywords_functions_classes() {
        let d = doc("<?php\nfunction greet() {}\nclass MyApp {}");
        let items = filtered_completions_at(&d, &[], None, &CompletionCtx::default());
        let ls = labels(&items);
        assert!(
            ls.contains(&"function"),
            "should contain keyword 'function'"
        );
        assert!(ls.contains(&"greet"), "should contain function 'greet'");
        assert!(ls.contains(&"MyApp"), "should contain class 'MyApp'");
    }

    #[test]
    fn builtins_appear_in_default_completions() {
        let d = doc("<?php");
        let items = filtered_completions_at(&d, &[], None, &CompletionCtx::default());
        let ls = labels(&items);
        assert!(ls.contains(&"strlen"), "missing strlen");
        assert!(ls.contains(&"array_map"), "missing array_map");
        assert!(ls.contains(&"json_encode"), "missing json_encode");
    }

    #[test]
    fn colon_trigger_returns_static_members() {
        let src = "<?php\nclass Cfg { public static function load(): void {} public static int $debug = 0; const VERSION = '1'; }\nCfg::";
        let d = doc(src);
        let pos = Position {
            line: 2,
            character: 5,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some(":"),
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let ls = labels(&items);
        assert!(ls.contains(&"load"), "missing static method");
        assert!(ls.contains(&"VERSION"), "missing constant");
    }

    #[test]
    fn inherited_methods_appear_in_arrow_completion() {
        let src = "<?php\nclass Base { public function baseMethod() {} }\nclass Child extends Base { public function childMethod() {} }\n$c = new Child();\n$c->";
        let d = doc(src);
        let pos = Position {
            line: 4,
            character: 4,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some(">"),
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let ls = labels(&items);
        assert!(ls.contains(&"baseMethod"), "missing inherited baseMethod");
        assert!(ls.contains(&"childMethod"), "missing childMethod");
    }

    #[test]
    fn param_named_arg_completion() {
        let src = "<?php\nfunction connect(string $host, int $port): void {}\nconnect(";
        let d = doc(src);
        let pos = Position {
            line: 2,
            character: 8,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some("("),
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let ls = labels(&items);
        assert!(ls.contains(&"host:"), "missing host:");
        assert!(ls.contains(&"port:"), "missing port:");
    }

    #[test]
    fn cross_file_symbols_appear_in_default_completions() {
        let d = doc("<?php\nfunction localFn() {}");
        let other = Arc::new(ParsedDoc::parse(
            "<?php\nclass RemoteService {}\nfunction remoteHelper() {}".to_string(),
        ));
        let items = filtered_completions_at(&d, &[other], None, &CompletionCtx::default());
        let ls = labels(&items);
        assert!(ls.contains(&"localFn"), "missing local function");
        assert!(ls.contains(&"RemoteService"), "missing cross-file class");
        assert!(ls.contains(&"remoteHelper"), "missing cross-file function");
    }

    #[test]
    fn cross_file_variables_not_included_in_default_completions() {
        let d = doc("<?php\n$localVar = 1;");
        let other = Arc::new(ParsedDoc::parse("<?php\n$remoteVar = 2;".to_string()));
        let items = filtered_completions_at(&d, &[other], None, &CompletionCtx::default());
        let ls = labels(&items);
        assert!(
            !ls.contains(&"$remoteVar"),
            "cross-file variable should not appear"
        );
    }

    #[test]
    fn cross_file_class_gets_use_insertion() {
        let current_src = "<?php\nnamespace App;\n\n$x = new ";
        let d = doc(current_src);
        let other = Arc::new(ParsedDoc::parse(
            "<?php\nnamespace Lib;\nclass Mailer {}".to_string(),
        ));
        let pos = Position {
            line: 3,
            character: 9,
        };
        let items = filtered_completions_at(
            &d,
            &[other],
            None,
            &CompletionCtx {
                source: Some(current_src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let mailer = items.iter().find(|i| i.label == "Mailer");
        assert!(mailer.is_some(), "Mailer should appear in completions");
        let edits = mailer.unwrap().additional_text_edits.as_ref();
        assert!(edits.is_some(), "Mailer should have additionalTextEdits");
        let edit_text = &edits.unwrap()[0].new_text;
        assert!(
            edit_text.contains("use Lib\\Mailer;"),
            "edit should insert 'use Lib\\Mailer;', got: {edit_text}"
        );
    }

    #[test]
    fn same_namespace_class_gets_no_use_insertion() {
        let current_src = "<?php\nnamespace Lib;\n$x = new ";
        let d = doc(current_src);
        let other = Arc::new(ParsedDoc::parse(
            "<?php\nnamespace Lib;\nclass Mailer {}".to_string(),
        ));
        let pos = Position {
            line: 2,
            character: 9,
        };
        let items = filtered_completions_at(
            &d,
            &[other],
            None,
            &CompletionCtx {
                source: Some(current_src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let mailer = items.iter().find(|i| i.label == "Mailer");
        assert!(mailer.is_some(), "Mailer should appear in completions");
        assert!(
            mailer.unwrap().additional_text_edits.is_none(),
            "same-namespace class should not get a use edit"
        );
    }

    #[test]
    fn function_with_params_gets_snippet() {
        let d = doc("<?php\nfunction process($input) {}");
        let items = symbol_completions(&d);
        let item = items.iter().find(|i| i.label == "process").unwrap();
        assert_eq!(item.insert_text_format, Some(InsertTextFormat::SNIPPET));
        assert_eq!(item.insert_text.as_deref(), Some("process($1)"));
    }

    #[test]
    fn function_without_params_gets_plain_call() {
        let d = doc("<?php\nfunction doThing() {}");
        let items = symbol_completions(&d);
        let item = items.iter().find(|i| i.label == "doThing").unwrap();
        // No snippet format needed for zero-arg functions.
        assert_eq!(item.insert_text.as_deref(), Some("doThing()"));
        assert_ne!(item.insert_text_format, Some(InsertTextFormat::SNIPPET));
    }

    #[test]
    fn builtin_functions_get_snippet() {
        let items = builtin_completions();
        let strlen = items.iter().find(|i| i.label == "strlen").unwrap();
        assert_eq!(strlen.insert_text_format, Some(InsertTextFormat::SNIPPET));
        assert_eq!(strlen.insert_text.as_deref(), Some("strlen($1)"));
    }

    #[test]
    fn enum_arrow_completion_includes_name_property() {
        let src = "<?php\nenum Suit { case Hearts; }\n$s = new Suit();\n$s->";
        let d = doc(src);
        let pos = Position {
            line: 3,
            character: 4,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some(">"),
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        assert!(
            items.iter().any(|i| i.label == "name"),
            "enum should have ->name"
        );
    }

    #[test]
    fn backed_enum_arrow_completion_includes_value_property() {
        let src =
            "<?php\nenum Status: string { case Active = 'active'; }\n$s = new Status();\n$s->";
        let d = doc(src);
        let pos = Position {
            line: 3,
            character: 4,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some(">"),
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        assert!(
            items.iter().any(|i| i.label == "name"),
            "backed enum should have ->name"
        );
        assert!(
            items.iter().any(|i| i.label == "value"),
            "backed enum should have ->value"
        );
    }

    #[test]
    fn pure_enum_arrow_completion_has_no_value_property() {
        let src = "<?php\nenum Suit { case Hearts; }\n$s = new Suit();\n$s->";
        let d = doc(src);
        let pos = Position {
            line: 3,
            character: 4,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some(">"),
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        assert!(
            !items.iter().any(|i| i.label == "value"),
            "pure enum should not have ->value"
        );
    }

    #[test]
    fn superglobals_appear_on_dollar_trigger() {
        let d = doc("<?php\n");
        let items = filtered_completions_at(&d, &[], Some("$"), &CompletionCtx::default());
        let ls = labels(&items);
        assert!(ls.contains(&"$_SERVER"), "missing $_SERVER");
        assert!(ls.contains(&"$_GET"), "missing $_GET");
        assert!(ls.contains(&"$_POST"), "missing $_POST");
        assert!(ls.contains(&"$_SESSION"), "missing $_SESSION");
        assert!(ls.contains(&"$GLOBALS"), "missing $GLOBALS");
    }

    #[test]
    fn superglobals_appear_in_default_completions() {
        let d = doc("<?php\n");
        let items = filtered_completions_at(&d, &[], None, &CompletionCtx::default());
        let ls = labels(&items);
        assert!(
            ls.contains(&"$_SERVER"),
            "missing $_SERVER in default completions"
        );
    }

    #[test]
    fn instanceof_narrowing_provides_arrow_completions() {
        // $x instanceof Foo should narrow $x to Foo inside the if body
        let src =
            "<?php\nclass Foo { public function doFoo() {} }\nif ($x instanceof Foo) {\n    $x->";
        let d = doc(src);
        let pos = Position {
            line: 3,
            character: 8,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some(">"),
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let ls = labels(&items);
        assert!(
            ls.contains(&"doFoo"),
            "instanceof narrowing should make Foo methods available"
        );
    }

    #[test]
    fn constructor_chain_arrow_completion() {
        let src = "<?php\nclass Builder { public function build() {} public function reset() {} }\n(new Builder())->";
        let d = doc(src);
        let pos = Position {
            line: 2,
            character: 16,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some(">"),
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let ls = labels(&items);
        assert!(
            ls.contains(&"build"),
            "constructor chain should complete Builder methods"
        );
        assert!(
            ls.contains(&"reset"),
            "constructor chain should complete Builder methods"
        );
    }

    // Feature 4: use statement FQN completions
    #[test]
    fn use_statement_suggests_fqns() {
        let d = doc("<?php\nuse ");
        let other = Arc::new(ParsedDoc::parse(
            "<?php\nnamespace App\\Services;\nclass Mailer {}".to_string(),
        ));
        let pos = Position {
            line: 1,
            character: 4,
        };
        let items = filtered_completions_at(
            &d,
            &[other],
            None,
            &CompletionCtx {
                source: Some("<?php\nuse "),
                position: Some(pos),
                ..Default::default()
            },
        );
        assert!(
            items.iter().any(|i| i.label.contains("Mailer")),
            "use completion should suggest Mailer"
        );
    }

    // Feature 5: union type param completions
    #[test]
    fn union_type_param_completes_both_classes() {
        let src = "<?php\nclass Foo { public function fooMethod() {} }\nclass Bar { public function barMethod() {} }\n/**\n * @param Foo|Bar $x\n */\nfunction handle($x) {\n    $x->";
        let d = doc(src);
        let pos = Position {
            line: 7,
            character: 8,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some(">"),
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let ls = labels(&items);
        assert!(
            ls.contains(&"fooMethod"),
            "should complete Foo methods from union"
        );
        assert!(
            ls.contains(&"barMethod"),
            "should complete Bar methods from union"
        );
    }

    // Feature 6: attribute bracket completions
    #[test]
    fn attribute_bracket_suggests_classes() {
        let d = doc("<?php\nclass Route {}\nclass Middleware {}\n#[");
        let pos = Position {
            line: 3,
            character: 2,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some("["),
            &CompletionCtx {
                source: Some("<?php\nclass Route {}\nclass Middleware {}\n#["),
                position: Some(pos),
                ..Default::default()
            },
        );
        let ls = labels(&items);
        assert!(ls.contains(&"Route"), "should suggest Route as attribute");
        assert!(
            ls.contains(&"Middleware"),
            "should suggest Middleware as attribute"
        );
    }

    #[test]
    fn attribute_bracket_cross_ns_gets_use_insertion() {
        let current_src = "<?php\nnamespace App\\Controllers;\n\n#[";
        let d = doc(current_src);
        let other = Arc::new(ParsedDoc::parse(
            "<?php\nnamespace App\\Attributes;\nclass Route {}".to_string(),
        ));
        let pos = Position {
            line: 3,
            character: 2,
        };
        let items = filtered_completions_at(
            &d,
            &[other],
            Some("["),
            &CompletionCtx {
                source: Some(current_src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let route = items.iter().find(|i| i.label == "Route");
        assert!(
            route.is_some(),
            "Route should appear in attribute completions"
        );
        let edits = route.unwrap().additional_text_edits.as_ref();
        assert!(
            edits.is_some(),
            "Route attribute should have additionalTextEdits for auto-import"
        );
        let edit_text = &edits.unwrap()[0].new_text;
        assert!(
            edit_text.contains("use App\\Attributes\\Route;"),
            "edit should insert 'use App\\Attributes\\Route;', got: {edit_text}"
        );
    }

    #[test]
    fn attribute_bracket_same_ns_no_use_insertion() {
        let current_src = "<?php\nnamespace App\\Attributes;\n\n#[";
        let d = doc(current_src);
        let other = Arc::new(ParsedDoc::parse(
            "<?php\nnamespace App\\Attributes;\nclass Route {}".to_string(),
        ));
        let pos = Position {
            line: 3,
            character: 2,
        };
        let items = filtered_completions_at(
            &d,
            &[other],
            Some("["),
            &CompletionCtx {
                source: Some(current_src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let route = items.iter().find(|i| i.label == "Route");
        assert!(
            route.is_some(),
            "Route should appear in attribute completions"
        );
        assert!(
            route.unwrap().additional_text_edits.is_none(),
            "same-namespace attribute class should not get a use edit"
        );
    }

    // Feature 7: match arm completions
    #[test]
    fn match_arm_suggests_enum_cases() {
        let src = "<?php\nenum Status { case Active; case Inactive; case Pending; }\n$s = new Status();\nmatch ($s) {\n    ";
        let d = doc(src);
        let pos = Position {
            line: 4,
            character: 4,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            None,
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let ls = labels(&items);
        assert!(
            ls.iter().any(|l| l.contains("Active")),
            "match should suggest Status::Active"
        );
    }

    // Feature 10: readonly property recognition
    #[test]
    fn readonly_property_has_detail_tag() {
        let src = "<?php\nclass Config { public readonly string $name; }\n$c = new Config();\n$c->";
        let d = doc(src);
        let pos = Position {
            line: 3,
            character: 4,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some(">"),
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let name_item = items.iter().find(|i| i.label == "$name");
        assert!(name_item.is_some(), "should have $name in completions");
        assert_eq!(
            name_item.unwrap().detail.as_deref(),
            Some("readonly"),
            "$name should be tagged readonly"
        );
    }

    // Feature 2: variables scoped to cursor line
    #[test]
    fn variables_after_cursor_not_suggested() {
        let src = "<?php\n$early = new Foo();\n// cursor here\n$late = new Bar();";
        let d = doc(src);
        let pos = Position {
            line: 2,
            character: 0,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            None,
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let ls = labels(&items);
        assert!(ls.contains(&"$early"), "$early should be suggested");
        assert!(
            !ls.contains(&"$late"),
            "$late declared after cursor should not be suggested"
        );
    }

    // Feature 3: sub-namespace backslash completions
    #[test]
    fn backslash_prefix_suggests_matching_classes() {
        let d = doc("<?php\n$x = new App\\");
        let other = Arc::new(ParsedDoc::parse(
            "<?php\nnamespace App\\Services;\nclass Mailer {}\nclass Logger {}".to_string(),
        ));
        let pos = Position {
            line: 1,
            character: 18,
        };
        let items = filtered_completions_at(
            &d,
            &[other],
            None,
            &CompletionCtx {
                source: Some("<?php\n$x = new App\\"),
                position: Some(pos),
                ..Default::default()
            },
        );
        let ls = labels(&items);
        assert!(
            ls.contains(&"Mailer"),
            "should suggest Mailer under App\\Services"
        );
    }

    // Feature 1: nullsafe ?-> completions
    #[test]
    fn nullsafe_arrow_triggers_member_completions() {
        let src = "<?php\nclass Service { public function run() {} public string $status; }\n$s = new Service();\n$s?->";
        let d = doc(src);
        let pos = Position {
            line: 3,
            character: 5,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some(">"),
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let ls = labels(&items);
        assert!(ls.contains(&"run"), "?-> should complete Service::run()");
        assert!(
            ls.iter().any(|l| l.contains("status")),
            "?-> should complete Service::$status"
        );
    }

    // Feature 5: magic methods in class body
    #[test]
    fn magic_methods_suggested_in_class_body() {
        let src = "<?php\nclass Foo {\n    __\n}";
        let d = doc(src);
        let pos = Position {
            line: 2,
            character: 6,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            None,
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let ls = labels(&items);
        assert!(ls.contains(&"__construct"), "should suggest __construct");
        assert!(ls.contains(&"__toString"), "should suggest __toString");
    }

    #[test]
    fn arrow_trigger_does_not_complete_on_unknown_receiver() {
        // $unknown-> has no type info, so no class members should be returned.
        // The fallback returns methods from the current doc, but since the doc
        // has no class, the result should be empty (no methods available).
        let src = "<?php\n$unknown->";
        let d = doc(src);
        let pos = Position {
            line: 1,
            character: 10,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some(">"),
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        // No class is defined in this doc, so the fallback method list is empty.
        assert!(
            items.is_empty(),
            "unknown receiver should yield no completions, got: {:?}",
            labels(&items)
        );
    }

    #[test]
    fn static_trigger_shows_only_static_members() {
        // ClassName:: should only return static methods/constants, NOT instance methods.
        let src = concat!(
            "<?php\n",
            "class MyClass {\n",
            "    public static function staticMethod(): void {}\n",
            "    public function instanceMethod(): void {}\n",
            "    public static int $staticProp = 0;\n",
            "    const MY_CONST = 42;\n",
            "}\n",
            "MyClass::",
        );
        let d = doc(src);
        let pos = Position {
            line: 7,
            character: 9,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some(":"),
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let ls = labels(&items);
        assert!(ls.contains(&"staticMethod"), "should include static method");
        assert!(ls.contains(&"MY_CONST"), "should include constant");
        assert!(
            !ls.contains(&"instanceMethod"),
            "should NOT include instance method in static completion, got: {:?}",
            ls
        );
    }

    // ── Snapshot tests ───────────────────────────────────────────────────────

    use expect_test::expect;

    #[test]
    fn snapshot_keyword_completions_present() {
        // Verify a handful of core PHP keywords appear in the default completion list.
        let items = keyword_completions();
        let mut ls: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
        ls.sort_unstable();
        // Snapshot just the first 10 sorted keywords so the test is stable even
        // if new keywords are added later.
        let first_ten = ls[..10.min(ls.len())].join("\n");
        expect![[r#"
            abstract
            and
            array
            as
            break
            callable
            case
            catch
            class
            clone"#]]
        .assert_eq(&first_ten);
    }

    #[test]
    fn snapshot_symbol_completions_for_simple_class() {
        let d = doc(
            "<?php\nclass Counter { public function increment(): void {} public function reset(): void {} }",
        );
        let items = symbol_completions(&d);
        let mut ls: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
        ls.sort_unstable();
        expect![[r#"
            Counter
            increment
            reset"#]]
        .assert_eq(&ls.join("\n"));
    }

    #[test]
    fn snapshot_symbol_completions_for_function_with_params() {
        let d = doc("<?php\nfunction connect(string $host, int $port): void {}");
        let items = symbol_completions(&d);
        let mut ls: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
        ls.sort_unstable();
        expect![[r#"
            $host
            $port
            connect
            connect(host:, port:)"#]]
        .assert_eq(&ls.join("\n"));
    }

    #[test]
    fn snapshot_arrow_completions_for_typed_var() {
        let src = "<?php\nclass Greeter { public function sayHello(): void {} public function sayBye(): void {} }\n$g = new Greeter();\n$g->";
        let d = doc(src);
        let pos = Position {
            line: 3,
            character: 4,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            Some(">"),
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let mut ls: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
        ls.sort_unstable();
        expect![[r#"
            sayBye
            sayHello"#]]
        .assert_eq(&ls.join("\n"));
    }

    // ── Array destructuring variable suggestions ─────────────────────────────

    #[test]
    fn array_destructuring_short_syntax_produces_variables() {
        // [$a, $b] = someFunction() — both variables should be suggested.
        let d = doc("<?php\n[$first, $second] = getSomething();");
        let items = symbol_completions(&d);
        let ls = labels(&items);
        assert!(
            ls.contains(&"$first"),
            "$first from array destructuring should be in completions"
        );
        assert!(
            ls.contains(&"$second"),
            "$second from array destructuring should be in completions"
        );
    }

    #[test]
    fn array_destructuring_variables_have_variable_kind() {
        let d = doc("<?php\n[$x, $y, $z] = getData();");
        let items = symbol_completions(&d);
        for name in &["$x", "$y", "$z"] {
            let item = items.iter().find(|i| i.label.as_str() == *name);
            assert!(item.is_some(), "{name} should be in completions");
            assert_eq!(
                item.unwrap().kind,
                Some(CompletionItemKind::VARIABLE),
                "{name} should have VARIABLE kind"
            );
        }
    }

    #[test]
    fn array_destructuring_respects_cursor_line_scope() {
        // Variables from array destructuring after the cursor line should not appear.
        let src = "<?php\n// cursor here\n[$early] = getA();\n[$late] = getB();";
        let d = doc(src);
        // cursor at line 1 (the comment line)
        let pos = Position {
            line: 1,
            character: 0,
        };
        let items = filtered_completions_at(
            &d,
            &[],
            None,
            &CompletionCtx {
                source: Some(src),
                position: Some(pos),
                ..Default::default()
            },
        );
        let ls = labels(&items);
        assert!(
            !ls.contains(&"$early"),
            "$early declared after cursor should not appear"
        );
        assert!(
            !ls.contains(&"$late"),
            "$late declared after cursor should not appear"
        );
    }

    // ── Include/require path completions ────────────────────────────────────

    #[test]
    fn include_path_prefix_returns_none_for_non_include_line() {
        let src = "<?php\n$x = 'some string';";
        let pos = Position {
            line: 1,
            character: 14,
        };
        assert!(
            include_path_prefix(src, pos).is_none(),
            "should not trigger on non-include line"
        );
    }

    #[test]
    fn include_path_prefix_returns_none_for_absolute_path() {
        let src = "<?php\nrequire '/absolute/path/file.php';";
        let pos = Position {
            line: 1,
            character: 30,
        };
        assert!(
            include_path_prefix(src, pos).is_none(),
            "should not trigger for absolute paths"
        );
    }

    #[test]
    fn include_path_prefix_returns_none_for_stream_wrapper() {
        let src = "<?php\nrequire 'phar://archive.phar/file.php';";
        let pos = Position {
            line: 1,
            character: 35,
        };
        assert!(
            include_path_prefix(src, pos).is_none(),
            "should not trigger for stream wrappers"
        );
    }

    #[test]
    fn include_path_prefix_returns_relative_dot_slash() {
        let src = "<?php\nrequire './lib/Helper";
        let pos = Position {
            line: 1,
            character: 23,
        };
        let result = include_path_prefix(src, pos);
        assert_eq!(
            result.as_deref(),
            Some("./lib/Helper"),
            "should return the typed relative path prefix"
        );
    }

    #[test]
    fn include_path_prefix_returns_double_dot_prefix() {
        let src = "<?php\ninclude '../utils/";
        let pos = Position {
            line: 1,
            character: 22,
        };
        let result = include_path_prefix(src, pos);
        assert_eq!(
            result.as_deref(),
            Some("../utils/"),
            "should return ../utils/ prefix"
        );
    }

    #[test]
    fn include_path_prefix_returns_empty_for_bare_quote() {
        let src = "<?php\nrequire '";
        let pos = Position {
            line: 1,
            character: 10,
        };
        let result = include_path_prefix(src, pos);
        assert_eq!(
            result.as_deref(),
            Some(""),
            "bare quote should return empty prefix (list current dir)"
        );
    }

    #[test]
    fn include_path_completions_lists_relative_directory() {
        use std::fs;

        let tmp = tempfile::tempdir().expect("tmpdir");
        let subdir = tmp.path().join("lib");
        fs::create_dir_all(&subdir).expect("create lib dir");
        fs::write(subdir.join("Helper.php"), "<?php").expect("write Helper.php");
        fs::write(subdir.join("Utils.php"), "<?php").expect("write Utils.php");
        // Non-PHP file that should be excluded
        fs::write(subdir.join("README.md"), "# readme").expect("write README.md");

        let doc_path = tmp.path().join("index.php");
        let doc_uri = Url::from_file_path(&doc_path).expect("doc uri");

        // Prefix "./lib/" — should list the lib directory contents
        let items = include_path_completions(&doc_uri, "./lib/");
        let ls: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
        assert!(ls.contains(&"Helper.php"), "should list Helper.php");
        assert!(ls.contains(&"Utils.php"), "should list Utils.php");
        assert!(
            !ls.contains(&"README.md"),
            "non-PHP files should be excluded"
        );
    }

    #[test]
    fn include_path_completions_insert_text_includes_directory_prefix() {
        use std::fs;

        let tmp = tempfile::tempdir().expect("tmpdir");
        let subdir = tmp.path().join("src");
        fs::create_dir_all(&subdir).expect("create src dir");
        fs::write(subdir.join("Boot.php"), "<?php").expect("write Boot.php");

        let doc_path = tmp.path().join("main.php");
        let doc_uri = Url::from_file_path(&doc_path).expect("doc uri");

        let items = include_path_completions(&doc_uri, "./src/");
        let boot = items.iter().find(|i| i.label == "Boot.php");
        assert!(boot.is_some(), "Boot.php should be in completions");
        assert_eq!(
            boot.unwrap().insert_text.as_deref(),
            Some("./src/Boot.php"),
            "insert_text should include the directory prefix"
        );
    }

    #[test]
    fn include_path_completions_is_empty_for_non_existent_directory() {
        let tmp = tempfile::tempdir().expect("tmpdir");
        let doc_path = tmp.path().join("index.php");
        let doc_uri = Url::from_file_path(&doc_path).expect("doc uri");

        let items = include_path_completions(&doc_uri, "./nonexistent/");
        assert!(
            items.is_empty(),
            "should return empty list for non-existent directory"
        );
    }

    #[test]
    fn include_path_completions_dir_entries_have_folder_kind() {
        use std::fs;

        let tmp = tempfile::tempdir().expect("tmpdir");
        let subdir = tmp.path().join("modules");
        fs::create_dir_all(&subdir).expect("create modules dir");

        let doc_path = tmp.path().join("index.php");
        let doc_uri = Url::from_file_path(&doc_path).expect("doc uri");

        let items = include_path_completions(&doc_uri, "");
        let modules = items.iter().find(|i| i.label == "modules");
        assert!(modules.is_some(), "modules dir should be in completions");
        assert_eq!(
            modules.unwrap().kind,
            Some(CompletionItemKind::FOLDER),
            "directory should have FOLDER kind"
        );
        assert_eq!(
            modules.unwrap().insert_text.as_deref(),
            Some("modules/"),
            "directory insert_text should end with /"
        );
    }
}