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

// ─── Basic: $var->prop-> ────────────────────────────────────────────────────

/// A variable assigned via `new Foo()` should allow property chain
/// completion: `$user->address->` should offer `Address` members.
#[tokio::test]
async fn test_var_property_chain_simple() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///var_prop_chain.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Address {\n",
        "    public string $city;\n",
        "    public string $zip;\n",
        "    public function format(): string {}\n",
        "}\n",
        "class User {\n",
        "    public Address $address;\n",
        "    public string $name;\n",
        "}\n",
        "function demo() {\n",
        "    $user = new User();\n",
        "    $user->address->\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 `$user->address->` on line 12
    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 12,
                character: 22,
            },
        },
        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 $user->address->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("city")),
                "Should include 'city' property from Address. Got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("zip")),
                "Should include 'zip' property from Address. Got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("format")),
                "Should include 'format' method from Address. Got: {:?}",
                labels
            );
            // Should NOT include User members
            assert!(
                !labels.iter().any(|l| l.starts_with("name")),
                "Should NOT include 'name' from User. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── Deep chain: $var->prop->subprop-> ──────────────────────────────────────

/// Two levels of property chain: `$order->customer->address->`
/// should offer members of `Address`.
#[tokio::test]
async fn test_var_property_chain_deep() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///deep_chain.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Address {\n",
        "    public string $street;\n",
        "    public string $city;\n",
        "}\n",
        "class Customer {\n",
        "    public Address $address;\n",
        "    public string $email;\n",
        "}\n",
        "class Order {\n",
        "    public Customer $customer;\n",
        "    public float $total;\n",
        "}\n",
        "function demo() {\n",
        "    $order = new Order();\n",
        "    $order->customer->address->\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 `$order->customer->address->` on line 15
    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 15,
                character: 34,
            },
        },
        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 $order->customer->address->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("street")),
                "Should include 'street' from Address. Got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("city")),
                "Should include 'city' from Address. Got: {:?}",
                labels
            );
            // Should NOT include members from Customer or Order
            assert!(
                !labels.iter().any(|l| l.starts_with("email")),
                "Should NOT include 'email' from Customer. Got: {:?}",
                labels
            );
            assert!(
                !labels.iter().any(|l| l.starts_with("total")),
                "Should NOT include 'total' from Order. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── Parameter type hint ────────────────────────────────────────────────────

/// When a function parameter has a type hint, property chains should work:
/// `function f(User $user) { $user->address-> }`
#[tokio::test]
async fn test_var_property_chain_from_parameter() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///param_chain.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Address {\n",
        "    public string $city;\n",
        "    public function getZip(): string {}\n",
        "}\n",
        "class User {\n",
        "    public Address $address;\n",
        "}\n",
        "function processUser(User $user) {\n",
        "    $user->address->\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;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 9,
                character: 22,
            },
        },
        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 parameter $user->address->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("city")),
                "Should include 'city' from Address. Got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("getZip")),
                "Should include 'getZip' from Address. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── Nullsafe operator: $var?->prop-> ───────────────────────────────────────

/// Nullsafe access `$var?->prop->` should resolve the same as `$var->prop->`.
#[tokio::test]
async fn test_var_property_chain_nullsafe() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///nullsafe_chain.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Engine {\n",
        "    public int $horsepower;\n",
        "    public function start(): void {}\n",
        "}\n",
        "class Car {\n",
        "    public ?Engine $engine;\n",
        "}\n",
        "function demo(?Car $car) {\n",
        "    $car?->engine->\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;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 9,
                character: 21,
            },
        },
        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 $car?->engine->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("horsepower")),
                "Should include 'horsepower' from Engine. Got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("start")),
                "Should include 'start' from Engine. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── Docblock @var annotation ───────────────────────────────────────────────

/// When a variable's type is declared via `@var`, property chains should work.
#[tokio::test]
async fn test_var_property_chain_from_docblock_var() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///docblock_chain.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Settings {\n",
        "    public bool $debug;\n",
        "    public string $locale;\n",
        "}\n",
        "class Config {\n",
        "    public Settings $settings;\n",
        "}\n",
        "function demo() {\n",
        "    /** @var Config $config */\n",
        "    $config = getConfig();\n",
        "    $config->settings->\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;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 11,
                character: 24,
            },
        },
        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 @var annotated $config->settings->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("debug")),
                "Should include 'debug' from Settings. Got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("locale")),
                "Should include 'locale' from Settings. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── Mixed chain: $var->method()->prop-> ────────────────────────────────────

/// Method call in the middle of a chain: `$var->getCustomer()->address->`
/// should resolve `getCustomer()` return type, then look up `address` on it.
#[tokio::test]
async fn test_var_method_then_property_chain() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///method_prop_chain.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Address {\n",
        "    public string $city;\n",
        "}\n",
        "class Customer {\n",
        "    public Address $address;\n",
        "}\n",
        "class Order {\n",
        "    public function getCustomer(): Customer {}\n",
        "}\n",
        "function demo() {\n",
        "    $order = new Order();\n",
        "    $order->getCustomer()->address->\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;

    // `$order->getCustomer()->address->` is on line 12
    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 12,
                character: 38,
            },
        },
        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 $order->getCustomer()->address->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("city")),
                "Should include 'city' from Address. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── Inside a class method (non-$this variable) ────────────────────────────

/// Property chains on local variables inside a class method should work
/// independently of `$this`.
#[tokio::test]
async fn test_var_property_chain_inside_class() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///inside_class.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Logger {\n",
        "    public function log(string $msg): void {}\n",
        "}\n",
        "class Database {\n",
        "    public Logger $logger;\n",
        "}\n",
        "class Service {\n",
        "    public function run() {\n",
        "        $db = new Database();\n",
        "        $db->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;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 10,
                character: 21,
            },
        },
        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 $db->logger->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("log")),
                "Should include 'log' from Logger. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── Property with docblock type (not native hint) ──────────────────────────

/// When a property's type is declared via `@var` docblock rather than a
/// native type hint, the chain should still resolve.
#[tokio::test]
async fn test_var_property_chain_docblock_property_type() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///docblock_prop_type.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Renderer {\n",
        "    public function render(): string {}\n",
        "}\n",
        "class View {\n",
        "    /** @var Renderer */\n",
        "    public $renderer;\n",
        "}\n",
        "function demo() {\n",
        "    $view = new View();\n",
        "    $view->renderer->\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;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 10,
                character: 22,
            },
        },
        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 docblock-typed $view->renderer->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("render")),
                "Should include 'render' from Renderer. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── Property with inherited type ───────────────────────────────────────────

/// Property chain should work when the property is inherited from a parent.
#[tokio::test]
async fn test_var_property_chain_inherited_property() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///inherited_prop.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Connection {\n",
        "    public function query(string $sql): void {}\n",
        "    public function close(): void {}\n",
        "}\n",
        "class BaseRepository {\n",
        "    public Connection $conn;\n",
        "}\n",
        "class UserRepository extends BaseRepository {\n",
        "}\n",
        "function demo() {\n",
        "    $repo = new UserRepository();\n",
        "    $repo->conn->\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;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 12,
                character: 18,
            },
        },
        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 $repo->conn-> (inherited property)"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("query")),
                "Should include 'query' from Connection. Got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("close")),
                "Should include 'close' from Connection. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── Cross-file PSR-4 resolution ────────────────────────────────────────────

/// Property chain where the intermediate class is in another file,
/// loaded via PSR-4 autoloading.
#[tokio::test]
async fn test_var_property_chain_cross_file_psr4() {
    let composer = r#"{"autoload":{"psr-4":{"App\\":"src/"}}}"#;

    let address_php = concat!(
        "<?php\n",
        "namespace App;\n",
        "\n",
        "class Address {\n",
        "    public string $city;\n",
        "    public string $country;\n",
        "    public function fullAddress(): string {}\n",
        "}\n",
    );

    let user_php = concat!(
        "<?php\n",
        "namespace App;\n",
        "\n",
        "class User {\n",
        "    public Address $address;\n",
        "    public string $name;\n",
        "}\n",
    );

    let controller_php = concat!(
        "<?php\n",
        "namespace App;\n",
        "\n",
        "class Controller {\n",
        "    public function show(User $user) {\n",
        "        $user->address->\n",
        "    }\n",
        "}\n",
    );

    let (backend, _dir) = create_psr4_workspace(
        composer,
        &[
            ("src/Address.php", address_php),
            ("src/User.php", user_php),
            ("src/Controller.php", controller_php),
        ],
    );

    let uri = Url::parse("file:///src/Controller.php").unwrap();
    let open_params = DidOpenTextDocumentParams {
        text_document: TextDocumentItem {
            uri: uri.clone(),
            language_id: "php".to_string(),
            version: 1,
            text: controller_php.to_string(),
        },
    };
    backend.did_open(open_params).await;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 5,
                character: 24,
            },
        },
        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 PSR-4 $user->address->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("city")),
                "Should include 'city' from cross-file Address. Got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("country")),
                "Should include 'country' from cross-file Address. Got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("fullAddress")),
                "Should include 'fullAddress' from cross-file Address. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── Top-level code (no enclosing class) ────────────────────────────────────

/// Property chains should work in top-level code (not inside a class).
#[tokio::test]
async fn test_var_property_chain_top_level() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///top_level_chain.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Point {\n",
        "    public float $x;\n",
        "    public float $y;\n",
        "}\n",
        "class Shape {\n",
        "    public Point $origin;\n",
        "}\n",
        "$shape = new Shape();\n",
        "$shape->origin->\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;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 9,
                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 top-level $shape->origin->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("x")),
                "Should include 'x' from Point. Got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("y")),
                "Should include 'y' from Point. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── Return type property chain ─────────────────────────────────────────────

/// When a method return type is used to type a variable,
/// property chains on that variable should work.
#[tokio::test]
async fn test_var_property_chain_from_method_return() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///return_chain.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Stats {\n",
        "    public int $count;\n",
        "    public float $average;\n",
        "}\n",
        "class Report {\n",
        "    public Stats $stats;\n",
        "}\n",
        "class ReportFactory {\n",
        "    public function create(): Report {}\n",
        "}\n",
        "function demo() {\n",
        "    $factory = new ReportFactory();\n",
        "    $report = $factory->create();\n",
        "    $report->stats->\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;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 14,
                character: 21,
            },
        },
        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 $report->stats->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("count")),
                "Should include 'count' from Stats. Got: {:?}",
                labels
            );
            assert!(
                labels.iter().any(|l| l.starts_with("average")),
                "Should include 'average' from Stats. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── No false positives: nonexistent property ───────────────────────────────

/// When the intermediate property doesn't exist, completion should
/// return no results (not crash or fall through to wrong results).
#[tokio::test]
async fn test_var_property_chain_nonexistent_property() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///no_prop.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class User {\n",
        "    public string $name;\n",
        "}\n",
        "function demo() {\n",
        "    $user = new User();\n",
        "    $user->nonexistent->\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;

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

    let result = backend.completion(completion_params).await.unwrap();
    // Should return None — no crash, no wrong results.
    assert!(
        result.is_none(),
        "Should return None for nonexistent property chain, got: {:?}",
        result
    );
}

// ─── Foreach variable property chain ────────────────────────────────────────

/// When a foreach value variable is typed via a generic iterable,
/// property chains on it should work.
#[tokio::test]
async fn test_var_property_chain_foreach_value() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///foreach_chain.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Address {\n",
        "    public string $city;\n",
        "}\n",
        "class User {\n",
        "    public Address $address;\n",
        "}\n",
        "class Service {\n",
        "    public function process() {\n",
        "        /** @var list<User> $users */\n",
        "        $users = loadUsers();\n",
        "        foreach ($users as $user) {\n",
        "            $user->address->\n",
        "        }\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;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 12,
                character: 30,
            },
        },
        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 foreach $user->address->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("city")),
                "Should include 'city' from Address via foreach chain. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── Promoted constructor property chain ────────────────────────────────────

/// Property chains should work with PHP 8 promoted properties.
#[tokio::test]
async fn test_var_property_chain_promoted_property() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///promoted_chain.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Formatter {\n",
        "    public function format(string $val): string {}\n",
        "}\n",
        "class Printer {\n",
        "    public function __construct(\n",
        "        public Formatter $formatter,\n",
        "    ) {}\n",
        "}\n",
        "function demo() {\n",
        "    $printer = new Printer(new Formatter());\n",
        "    $printer->formatter->\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;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 11,
                character: 26,
            },
        },
        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 $printer->formatter->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("format")),
                "Should include 'format' from Formatter. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── Static property not confused ───────────────────────────────────────────

/// `$var->prop->` should NOT offer static members of the property's type
/// when using arrow access.
#[tokio::test]
async fn test_var_property_chain_no_static_members() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///no_static.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Cache {\n",
        "    public function get(string $key): mixed {}\n",
        "    public static function flush(): void {}\n",
        "    public static int $hits = 0;\n",
        "}\n",
        "class App {\n",
        "    public Cache $cache;\n",
        "}\n",
        "function demo() {\n",
        "    $app = new App();\n",
        "    $app->cache->\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;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 11,
                character: 18,
            },
        },
        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 $app->cache->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("get")),
                "Should include instance method 'get' from Cache. Got: {:?}",
                labels
            );
            // Static method `flush` should NOT appear for `->` access
            assert!(
                !labels.iter().any(|l| l.starts_with("flush")),
                "Should NOT include static method 'flush' via ->. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}

// ─── $this->prop still works (regression check) ─────────────────────────────

/// Verify that the existing `$this->prop->` path still works correctly
/// and is not broken by the new non-`$this` property chain logic.
#[tokio::test]
async fn test_this_property_chain_still_works() {
    let backend = create_test_backend();

    let uri = Url::parse("file:///this_regression.php").unwrap();
    let text = concat!(
        "<?php\n",
        "class Logger {\n",
        "    public function info(string $msg): void {}\n",
        "}\n",
        "class Service {\n",
        "    public Logger $logger;\n",
        "    public function run() {\n",
        "        $this->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;

    let completion_params = CompletionParams {
        text_document_position: TextDocumentPositionParams {
            text_document: TextDocumentIdentifier { uri },
            position: Position {
                line: 7,
                character: 23,
            },
        },
        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 still work for $this->logger->"
    );

    match result.unwrap() {
        CompletionResponse::Array(items) => {
            let labels: Vec<&str> = items.iter().map(|i| i.label.as_str()).collect();
            assert!(
                labels.iter().any(|l| l.starts_with("info")),
                "Should include 'info' from Logger via $this->. Got: {:?}",
                labels
            );
        }
        CompletionResponse::List(_) => panic!("Expected Array response"),
    }
}