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
use crate::common::create_test_backend;
use tower_lsp::LanguageServer;
use tower_lsp::lsp_types::*;

// ─── Interface Completion Tests ─────────────────────────────────────────────

#[tokio::test]
async fn test_completion_interface_type_hint_resolves_methods() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///iface.php").unwrap();
    let text = concat!(
        "<?php\n",
        "interface Loggable {\n",
        "    public function log(string $message): void;\n",
        "    public function getLogLevel(): int;\n",
        "}\n",
        "class Service {\n",
        "    public function run(Loggable $logger): void {\n",
        "        $logger->\n",
        "    }\n",
        "}\n",
    );

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: text.to_string(),
        },
    };
    backend.did_open(open_params).await;

    // Cursor right after `$logger->` on line 7
    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 7,
                character: 17,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(completion_params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return results for interface-typed parameter"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let names: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                names.iter().any(|n| n.starts_with("log(")),
                "Should contain interface method 'log', got: {:?}",
                names
            );
            assert!(
                names.iter().any(|n| n.starts_with("getLogLevel(")),
                "Should contain interface method 'getLogLevel', got: {:?}",
                names
            );
        }
        _ => panic!("Expected Array response"),
    }
}

#[tokio::test]
async fn test_completion_interface_constant_via_double_colon() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///iface_const.php").unwrap();
    let text = concat!(
        "<?php\n",
        "interface HasStatus {\n",
        "    const STATUS_ACTIVE = 1;\n",
        "    const STATUS_INACTIVE = 0;\n",
        "    public function getStatus(): int;\n",
        "}\n",
        "class Foo {\n",
        "    public function bar(): void {\n",
        "        HasStatus::\n",
        "    }\n",
        "}\n",
    );

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: text.to_string(),
        },
    };
    backend.did_open(open_params).await;

    // Cursor right after `HasStatus::` on line 8
    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 8,
                character: 19,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(completion_params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return results for interface constant access"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let names: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                names.contains(&"STATUS_ACTIVE"),
                "Should contain constant 'STATUS_ACTIVE', got: {:?}",
                names
            );
            assert!(
                names.contains(&"STATUS_INACTIVE"),
                "Should contain constant 'STATUS_INACTIVE', got: {:?}",
                names
            );
        }
        _ => panic!("Expected Array response"),
    }
}

// ─── Basic Completion Tests ─────────────────────────────────────────────────

#[tokio::test]
async fn test_completion_returns_none_when_nothing_matches() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///test.php").unwrap();
    let text = "<?php\n$x = 1;\n".to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 1,
                character: 0,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(completion_params).await.unwrap();
    assert!(
        result.is_none(),
        "Completion should return None when nothing matches"
    );
}

#[tokio::test]
async fn test_completion_suggests_php_keywords() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///keywords.php").unwrap();
    let text = concat!("<?php\n", "function demo(): void {\n", "    ret\n", "}\n",).to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    // Cursor right after `ret` on line 2.
    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 2,
                character: 7,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(completion_params).await.unwrap();
    assert!(
        result.is_some(),
        "Completion should return keyword suggestions for a keyword prefix"
    );

    let items = match result.unwrap() {
        CompletionResponse::Array(items) => items,
        CompletionResponse::List(list) => list.items,
    };
    assert!(
        items
            .iter()
            .any(|i| i.label == "return" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Expected `return` keyword completion, got: {:?}",
        items.iter().map(|i| i.label.clone()).collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn test_completion_does_not_suggest_return_at_top_level() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///keywords_top_level.php").unwrap();
    let text = concat!("<?php\n", "ret\n").to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 1,
                character: 3,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(completion_params).await.unwrap();
    let items = match result {
        Some(CompletionResponse::Array(items)) => items,
        Some(CompletionResponse::List(list)) => list.items,
        None => Vec::new(),
    };
    assert!(
        !items
            .iter()
            .any(|i| i.label == "return" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Top-level completion should not suggest `return`, got: {:?}",
        items.iter().map(|i| i.label.clone()).collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn test_completion_suggests_break_inside_loop_only() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///keywords_break.php").unwrap();
    let text = concat!(
        "<?php\n",
        "function loopDemo(bool $cond): void {\n",
        "    while ($cond) {\n",
        "        br\n",
        "    }\n",
        "}\n",
        "function nonLoopDemo(): void {\n",
        "    br\n",
        "}\n",
    )
    .to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    let loop_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
            position: Position {
                line: 3,
                character: 10,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let loop_result = backend.completion(loop_params).await.unwrap();
    let loop_items = match loop_result.unwrap() {
        CompletionResponse::Array(items) => items,
        CompletionResponse::List(list) => list.items,
    };
    assert!(
        loop_items
            .iter()
            .any(|i| i.label == "break" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Inside loop completion should suggest `break`, got: {:?}",
        loop_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );

    let non_loop_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 7,
                character: 6,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let non_loop_result = backend.completion(non_loop_params).await.unwrap();
    let non_loop_items = match non_loop_result {
        Some(CompletionResponse::Array(items)) => items,
        Some(CompletionResponse::List(list)) => list.items,
        None => Vec::new(),
    };
    assert!(
        !non_loop_items
            .iter()
            .any(|i| i.label == "break" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Outside loop completion should not suggest `break`, got: {:?}",
        non_loop_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn test_completion_suggests_continue_in_loop_not_switch() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///keywords_continue.php").unwrap();
    let text = concat!(
        "<?php\n",
        "function loopDemo(): void {\n",
        "    foreach ([1, 2] as $v) {\n",
        "        con\n",
        "    }\n",
        "}\n",
        "function switchDemo(): void {\n",
        "    switch (1) {\n",
        "        case 1:\n",
        "            con\n",
        "    }\n",
        "}\n",
    )
    .to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    // `continue` inside a foreach loop — should be suggested.
    let loop_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
            position: Position {
                line: 3,
                character: 11,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let loop_result = backend.completion(loop_params).await.unwrap();
    let loop_items = match loop_result {
        Some(CompletionResponse::Array(items)) => items,
        Some(CompletionResponse::List(list)) => list.items,
        None => Vec::new(),
    };
    assert!(
        loop_items
            .iter()
            .any(|i| i.label == "continue" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "`continue` should be suggested inside a loop, got: {:?}",
        loop_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );

    // `continue` inside a switch (but not a loop) — should NOT be suggested.
    let switch_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 9,
                character: 15,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let switch_result = backend.completion(switch_params).await.unwrap();
    let switch_items = match switch_result {
        Some(CompletionResponse::Array(items)) => items,
        Some(CompletionResponse::List(list)) => list.items,
        None => Vec::new(),
    };
    assert!(
        !switch_items
            .iter()
            .any(|i| i.label == "continue" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "`continue` should NOT be suggested inside a switch (without a loop), got: {:?}",
        switch_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn test_completion_suggests_case_default_inside_switch() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///keywords_switch.php").unwrap();
    let text = concat!(
        "<?php\n",
        "function switchDemo(int $x): void {\n",
        "    switch ($x) {\n",
        "        case 1:\n",
        "            break;\n",
        "        cas\n",
        "    }\n",
        "}\n",
        "function nonSwitchDemo(): void {\n",
        "    cas\n",
        "}\n",
    )
    .to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    // `case` inside a switch — should be suggested.
    let switch_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
            position: Position {
                line: 5,
                character: 11,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let switch_result = backend.completion(switch_params).await.unwrap();
    let switch_items = match switch_result {
        Some(CompletionResponse::Array(items)) => items,
        Some(CompletionResponse::List(list)) => list.items,
        None => Vec::new(),
    };
    assert!(
        switch_items
            .iter()
            .any(|i| i.label == "case" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "`case` should be suggested inside a switch, got: {:?}",
        switch_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );

    // `case` outside a switch — should NOT be suggested.
    let non_switch_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 9,
                character: 7,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let non_switch_result = backend.completion(non_switch_params).await.unwrap();
    let non_switch_items = match non_switch_result {
        Some(CompletionResponse::Array(items)) => items,
        Some(CompletionResponse::List(list)) => list.items,
        None => Vec::new(),
    };
    assert!(
        !non_switch_items
            .iter()
            .any(|i| i.label == "case" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "`case` should NOT be suggested outside a switch, got: {:?}",
        non_switch_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn test_completion_interface_body_keyword_restrictions() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///keywords_interface_body.php").unwrap();
    let text = concat!("<?php\n", "interface Loggable {\n", "    pu\n", "}\n",).to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    let params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 2,
                character: 6,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let result = backend.completion(params).await.unwrap();
    let items = match result {
        Some(CompletionResponse::Array(items)) => items,
        Some(CompletionResponse::List(list)) => list.items,
        None => Vec::new(),
    };

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

    assert!(
        keyword_labels.contains(&"public"),
        "`public` should be suggested in interface body, got: {:?}",
        keyword_labels
    );
    // Interfaces only allow `public`, `function`, and `const`.
    for excluded in &["private", "protected", "static", "abstract", "readonly"] {
        assert!(
            !keyword_labels.contains(excluded),
            "`{excluded}` should NOT be suggested in interface body, got: {:?}",
            keyword_labels
        );
    }
}

#[tokio::test]
async fn test_completion_suggests_namespace_only_at_top_level() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///keywords_namespace.php").unwrap();
    let text = concat!(
        "<?php\n",
        "nam\n",
        "function demo(): void {\n",
        "    nam\n",
        "}\n",
    )
    .to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    let top_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
            position: Position {
                line: 1,
                character: 3,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let top_result = backend.completion(top_params).await.unwrap();
    let top_items = match top_result.unwrap() {
        CompletionResponse::Array(items) => items,
        CompletionResponse::List(list) => list.items,
    };
    assert!(
        top_items
            .iter()
            .any(|i| i.label == "namespace" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Top-level completion should suggest `namespace`, got: {:?}",
        top_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );

    let fn_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 3,
                character: 7,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let fn_result = backend.completion(fn_params).await.unwrap();
    let fn_items = match fn_result {
        Some(CompletionResponse::Array(items)) => items,
        Some(CompletionResponse::List(list)) => list.items,
        None => Vec::new(),
    };
    assert!(
        !fn_items
            .iter()
            .any(|i| i.label == "namespace" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Function-scope completion should not suggest `namespace`, got: {:?}",
        fn_items.iter().map(|i| i.label.clone()).collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn test_completion_suggests_extends_implements_only_in_declaration_header() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///keywords_decl_header.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Child ex\n",
        "class Another extends Base im\n",
        "interface Contract im\n",
        "function demo(): void {\n",
        "    ex\n",
        "}\n",
    )
    .to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    // `class Child ex|`
    let extends_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
            position: Position {
                line: 1,
                character: 14,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let extends_items = match backend.completion(extends_params).await.unwrap().unwrap() {
        CompletionResponse::Array(items) => items,
        CompletionResponse::List(list) => list.items,
    };
    assert!(
        extends_items
            .iter()
            .any(|i| i.label == "extends" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Class declaration header should suggest `extends`, got: {:?}",
        extends_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );

    // `class Another extends Base im|`
    let impl_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
            position: Position {
                line: 2,
                character: 29,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let impl_items = match backend.completion(impl_params).await.unwrap().unwrap() {
        CompletionResponse::Array(items) => items,
        CompletionResponse::List(list) => list.items,
    };
    assert!(
        impl_items
            .iter()
            .any(|i| i.label == "implements" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Class declaration header should suggest `implements`, got: {:?}",
        impl_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );

    // `interface Contract im|` should NOT suggest implements.
    let iface_impl_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
            position: Position {
                line: 3,
                character: 21,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let iface_result = backend.completion(iface_impl_params).await.unwrap();
    let iface_items = match iface_result {
        Some(CompletionResponse::Array(items)) => items,
        Some(CompletionResponse::List(list)) => list.items,
        None => Vec::new(),
    };
    assert!(
        !iface_items
            .iter()
            .any(|i| i.label == "implements" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Interface declaration header should not suggest `implements`, got: {:?}",
        iface_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );

    // `function demo() { ex| }` should NOT suggest extends.
    let fn_extends_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 5,
                character: 6,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let fn_result = backend.completion(fn_extends_params).await.unwrap();
    let fn_items = match fn_result {
        Some(CompletionResponse::Array(items)) => items,
        Some(CompletionResponse::List(list)) => list.items,
        None => Vec::new(),
    };
    assert!(
        !fn_items
            .iter()
            .any(|i| i.label == "extends" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Function scope should not suggest `extends`, got: {:?}",
        fn_items.iter().map(|i| i.label.clone()).collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn test_completion_class_body_keywords_are_contextual() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///keywords_class_body.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class User {\n",
        "    pu\n",
        "    if\n",
        "    ca\n",
        "}\n",
        "enum Status {\n",
        "    ca\n",
        "}\n",
    )
    .to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    // `class User { pu| }` => should suggest `public`.
    let vis_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
            position: Position {
                line: 2,
                character: 6,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let vis_items = match backend.completion(vis_params).await.unwrap().unwrap() {
        CompletionResponse::Array(items) => items,
        CompletionResponse::List(list) => list.items,
    };
    assert!(
        vis_items
            .iter()
            .any(|i| i.label == "public" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Class body should suggest visibility keyword `public`, got: {:?}",
        vis_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );

    // `class User { if| }` => should NOT suggest `if`.
    let if_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
            position: Position {
                line: 3,
                character: 6,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let if_items = match backend.completion(if_params).await.unwrap() {
        Some(CompletionResponse::Array(items)) => items,
        Some(CompletionResponse::List(list)) => list.items,
        None => Vec::new(),
    };
    assert!(
        !if_items
            .iter()
            .any(|i| i.label == "if" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Class body should not suggest statement keyword `if`, got: {:?}",
        if_items.iter().map(|i| i.label.clone()).collect::<Vec<_>>()
    );

    // `class User { ca| }` => should NOT suggest enum `case`.
    let class_case_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
            position: Position {
                line: 4,
                character: 6,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let class_case_items = match backend.completion(class_case_params).await.unwrap() {
        Some(CompletionResponse::Array(items)) => items,
        Some(CompletionResponse::List(list)) => list.items,
        None => Vec::new(),
    };
    assert!(
        !class_case_items
            .iter()
            .any(|i| i.label == "case" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Class body should not suggest enum keyword `case`, got: {:?}",
        class_case_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );

    // `enum Status { ca| }` => should suggest `case`.
    let enum_case_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 7,
                character: 6,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let enum_case_items = match backend.completion(enum_case_params).await.unwrap().unwrap() {
        CompletionResponse::Array(items) => items,
        CompletionResponse::List(list) => list.items,
    };
    assert!(
        enum_case_items
            .iter()
            .any(|i| i.label == "case" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Enum body should suggest `case`, got: {:?}",
        enum_case_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn test_completion_after_visibility_suggests_member_keywords() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///keywords_after_visibility.php").unwrap();
    let text = concat!("<?php\n", "class User {\n", "    public \n", "}\n",).to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    // Cursor right after `public ` on line 2.
    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 2,
                character: 11,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(completion_params).await.unwrap();
    let items = match result.unwrap() {
        CompletionResponse::Array(items) => items,
        CompletionResponse::List(list) => list.items,
    };

    assert!(
        items
            .iter()
            .any(|i| i.label == "function" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "After visibility, completion should suggest `function`, got: {:?}",
        items.iter().map(|i| i.label.clone()).collect::<Vec<_>>()
    );
    assert!(
        items
            .iter()
            .any(|i| i.label == "const" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "After visibility, completion should suggest `const`, got: {:?}",
        items.iter().map(|i| i.label.clone()).collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn test_completion_suggests_backed_enum_types_after_enum_colon() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///keywords_enum_backed_type.php").unwrap();
    let text = concat!("<?php\n", "enum Role: \n", "enum Status: st\n",).to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    // Cursor right after `enum Role: ` on line 1.
    let empty_prefix_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri: uri.clone() },
            position: Position {
                line: 1,
                character: 11,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let empty_prefix_items = match backend
        .completion(empty_prefix_params)
        .await
        .unwrap()
        .unwrap()
    {
        CompletionResponse::Array(items) => items,
        CompletionResponse::List(list) => list.items,
    };
    assert!(
        empty_prefix_items
            .iter()
            .any(|i| i.label == "string" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Backed enum type completion should suggest `string`, got: {:?}",
        empty_prefix_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );
    assert!(
        empty_prefix_items
            .iter()
            .any(|i| i.label == "int" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Backed enum type completion should suggest `int`, got: {:?}",
        empty_prefix_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );

    // Cursor right after `enum Status: st` on line 2.
    let st_prefix_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 2,
                character: 15,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };
    let st_prefix_items = match backend.completion(st_prefix_params).await.unwrap().unwrap() {
        CompletionResponse::Array(items) => items,
        CompletionResponse::List(list) => list.items,
    };
    assert!(
        st_prefix_items
            .iter()
            .any(|i| i.label == "string" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Backed enum type prefix `st` should suggest `string`, got: {:?}",
        st_prefix_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );
    assert!(
        !st_prefix_items
            .iter()
            .any(|i| i.label == "int" && i.kind == Some(CompletionItemKind::KEYWORD)),
        "Backed enum type prefix `st` should not suggest `int`, got: {:?}",
        st_prefix_items
            .iter()
            .map(|i| i.label.clone())
            .collect::<Vec<_>>()
    );
}

#[tokio::test]
async fn test_completion_inside_class_returns_methods() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///user.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class User {\n",
        "    function login() {}\n",
        "    function logout() {}\n",
        "    function test() {\n",
        "        $this->\n",
        "    }\n",
        "}\n",
    )
    .to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    // Cursor right after `$this->` on line 5
    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 5,
                character: 15,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(completion_params).await.unwrap();
    assert!(result.is_some(), "Completion should return results");

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            // Should have 3 non-static methods (login, logout, test)
            let method_items: Vec<&CompletionItem> = items
                .iter()
                .filter(|i| i.kind == Some(CompletionItemKind::METHOD))
                .collect();
            assert_eq!(method_items.len(), 3, "Should return 3 method completions");

            let filter_texts: Vec<&str> = method_items
                .iter()
                .map(|i| i.filter_text.as_deref().unwrap())
                .collect();
            assert!(filter_texts.contains(&"login"), "Should contain 'login'");
            assert!(filter_texts.contains(&"logout"), "Should contain 'logout'");

            // Check labels show full signature
            for item in &method_items {
                let label = &item.label;
                assert!(
                    label.contains("(") && label.contains(")"),
                    "Label '{}' should contain full signature with parens",
                    label
                );
            }

            // Check insert_text is a snippet with parens (no required params here)
            for item in &method_items {
                let insert = item.insert_text.as_deref().unwrap();
                let filter = item.filter_text.as_deref().unwrap();
                assert!(
                    insert.starts_with(filter) && insert.contains("()"),
                    "insert_text '{}' should be a snippet starting with '{}' and containing parens",
                    insert,
                    filter
                );
                assert_eq!(
                    item.insert_text_format,
                    Some(InsertTextFormat::SNIPPET),
                    "insert_text_format should be Snippet"
                );
            }
        }
        _ => panic!("Expected CompletionResponse::Array"),
    }
}

#[tokio::test]
async fn test_completion_outside_class_returns_fallback() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///user.php").unwrap();
    let text = "<?php\n\nclass User {\n    function login() {}\n}\n\n$x = 1;\n".to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    // Cursor outside the class (line 6: $x = 1;)
    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 6,
                character: 0,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(completion_params).await.unwrap();
    assert!(
        result.is_none(),
        "Cursor outside class with no operator should return None"
    );
}

#[tokio::test]
async fn test_completion_with_multiple_classes() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///multi.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Foo {\n",
        "    function doFoo() {}\n",
        "    function doBar() {}\n",
        "}\n",
        "class Bar {\n",
        "    function handleRequest() {}\n",
        "    function test() {\n",
        "        $this->\n",
        "    }\n",
        "}\n",
    )
    .to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    // Verify two classes were parsed
    let classes = backend
        .get_classes_for_uri(uri.as_ref())
        .expect("ast_map should have entry");
    assert_eq!(classes.len(), 2);

    // Cursor right after `$this->` on line 8 inside Bar
    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 8,
                character: 15,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(completion_params).await.unwrap();
    assert!(result.is_some());

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let method_items: Vec<&CompletionItem> = items
                .iter()
                .filter(|i| i.kind == Some(CompletionItemKind::METHOD))
                .collect();
            // Bar has handleRequest and test — both non-static
            assert_eq!(method_items.len(), 2, "Bar has two methods");
            let names: Vec<&str> = method_items
                .iter()
                .map(|i| i.filter_text.as_deref().unwrap())
                .collect();
            assert!(names.contains(&"handleRequest"));
            assert!(names.contains(&"test"));
        }
        _ => panic!("Expected CompletionResponse::Array"),
    }
}

#[tokio::test]
async fn test_completion_empty_class_falls_back() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///empty.php").unwrap();
    let text = "<?php\nclass Empty {\n}\n".to_string();

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text,
        },
    };
    backend.did_open(open_params).await;

    // Cursor inside the empty class body
    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 1,
                character: 14,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(completion_params).await.unwrap();
    // Empty class has no methods or properties, so should return None
    assert!(
        result.is_none(),
        "Empty class with no members should return None"
    );
}

#[tokio::test]
async fn test_completion_no_access_operator_shows_fallback() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///all.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Svc {\n",
        "    public static function create(): self {}\n",
        "    public function run(): void {}\n",
        "    public static string $instance = '';\n",
        "    public int $count = 0;\n",
        "    const MAX = 10;\n",
        "    \n",
        "}\n",
    );

    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: text.to_string(),
        },
    };
    backend.did_open(open_params).await;

    // Cursor on blank line 7 inside the class body (no `->` or `::`)
    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 7,
                character: 4,
            },
        },
        work_done_progress_params: WorkDoneProgressParams::default(),
        partial_result_params: PartialResultParams::default(),
        context: None,
    };

    let result = backend.completion(completion_params).await.unwrap();
    // Without `->` or `::`, no class members should be suggested
    assert!(result.is_none(), "No access operator should return None");
}