-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathcompletion_variable_names.rs
More file actions
3760 lines (3292 loc) · 123 KB
/
Copy pathcompletion_variable_names.rs
File metadata and controls
3760 lines (3292 loc) · 123 KB
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
mod common;
use common::create_test_backend;
use phpantom_lsp::Backend;
use tower_lsp::LanguageServer;
use tower_lsp::lsp_types::*;
/// Helper: open a file and request completion at the given line/character.
async fn complete_at(
backend: &Backend,
uri: &Url,
text: &str,
line: u32,
character: u32,
) -> Vec<CompletionItem> {
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: uri.clone() },
position: Position { line, character },
},
work_done_progress_params: WorkDoneProgressParams::default(),
partial_result_params: PartialResultParams::default(),
context: None,
};
match backend.completion(completion_params).await.unwrap() {
Some(CompletionResponse::Array(items)) => items,
Some(CompletionResponse::List(list)) => list.items,
_ => vec![],
}
}
// ─── extract_partial_variable_name unit tests ───────────────────────────────
#[test]
fn test_extract_partial_variable_name_simple() {
let content = "<?php\n$user\n";
let result = Backend::extract_partial_variable_name(
content,
Position {
line: 1,
character: 5,
},
);
assert_eq!(result, Some("$user".to_string()));
}
#[test]
fn test_extract_partial_variable_name_partial() {
let content = "<?php\n$us\n";
let result = Backend::extract_partial_variable_name(
content,
Position {
line: 1,
character: 3,
},
);
assert_eq!(result, Some("$us".to_string()));
}
#[test]
fn test_extract_partial_variable_name_bare_dollar() {
let content = "<?php\n$\n";
let result = Backend::extract_partial_variable_name(
content,
Position {
line: 1,
character: 1,
},
);
assert_eq!(
result,
Some("$".to_string()),
"Bare '$' should return Some(\"$\") to trigger showing all variables"
);
}
#[test]
fn test_extract_partial_variable_name_underscore_prefix() {
let content = "<?php\n$_SE\n";
let result = Backend::extract_partial_variable_name(
content,
Position {
line: 1,
character: 4,
},
);
assert_eq!(result, Some("$_SE".to_string()));
}
#[test]
fn test_extract_partial_variable_name_not_a_variable() {
let content = "<?php\nfoo\n";
let result = Backend::extract_partial_variable_name(
content,
Position {
line: 1,
character: 3,
},
);
assert!(
result.is_none(),
"Non-variable identifiers should return None"
);
}
#[test]
fn test_extract_partial_variable_name_class_name() {
let content = "<?php\nMyClass\n";
let result = Backend::extract_partial_variable_name(
content,
Position {
line: 1,
character: 7,
},
);
assert!(result.is_none(), "Class names (no $) should return None");
}
#[test]
fn test_extract_partial_variable_name_variable_variable_skipped() {
let content = "<?php\n$$var\n";
let result = Backend::extract_partial_variable_name(
content,
Position {
line: 1,
character: 5,
},
);
assert!(
result.is_none(),
"Variable variables ($$var) should return None"
);
}
#[test]
fn test_extract_partial_variable_name_after_arrow_returns_none() {
// After `->`, member completion handles this, not variable name completion.
// The `->$` pattern doesn't actually occur in PHP (->prop not ->$prop),
// but just make sure our guard works.
let content = "<?php\n$obj->$prop\n";
// Position at end of `$prop` — the `$prop` portion starts at col 6
// extract walks back: p,r,o,p,$ — finds $ at col 6
// then checks chars[4]='>' chars[5]='$' — not `->` at [i-2][i-1]
// Actually the guard checks chars[i-2] and chars[i-1] where i is the position of `$`
// i=6, chars[4]='-', chars[5]='>' → that IS `->` at positions i-2, i-1
// Wait, let me re-check. The `$` is at index 6. i-1=5 is '>', i-2=4 is '-'. Yes, that's `->`.
let result = Backend::extract_partial_variable_name(
content,
Position {
line: 1,
character: 11,
},
);
assert!(
result.is_none(),
"Variable after '->' should return None (member access context)"
);
}
// ─── Variable name completion integration tests ─────────────────────────────
/// Typing `$us` should suggest `$user` when `$user` is defined in the file.
#[tokio::test]
async fn test_completion_variable_name_basic() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_basic.php").unwrap();
let text = concat!("<?php\n", "$user = new stdClass();\n", "$us\n",);
// Cursor at end of `$us` on line 2
let items = complete_at(&backend, &uri, text, 2, 3).await;
let var_items: Vec<_> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.collect();
let labels: Vec<&str> = var_items.iter().map(|i| i.label.as_str()).collect();
assert!(
labels.contains(&"$user"),
"Should suggest $user when typing $us. Got: {:?}",
labels
);
}
/// Typing `$` alone should show all variables in the file.
#[tokio::test]
async fn test_completion_bare_dollar_shows_all_variables() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_dollar.php").unwrap();
let text = concat!(
"<?php\n",
"$name = 'Alice';\n",
"$age = 30;\n",
"$email = 'alice@example.com';\n",
"$\n",
);
// Cursor right after `$` on line 4
let items = complete_at(&backend, &uri, text, 4, 1).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
var_labels.contains(&"$name"),
"Should suggest $name. Got: {:?}",
var_labels
);
assert!(
var_labels.contains(&"$age"),
"Should suggest $age. Got: {:?}",
var_labels
);
assert!(
var_labels.contains(&"$email"),
"Should suggest $email. Got: {:?}",
var_labels
);
}
/// Variables should be deduplicated — even if `$user` appears multiple times.
#[tokio::test]
async fn test_completion_variable_names_deduplicated() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_dedup.php").unwrap();
let text = concat!(
"<?php\n",
"$user = getUser();\n",
"$user->name;\n",
"echo $user;\n",
"$us\n",
);
let items = complete_at(&backend, &uri, text, 4, 3).await;
let user_items: Vec<_> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE) && i.label == "$user")
.collect();
assert_eq!(
user_items.len(),
1,
"Should have exactly one $user completion (deduplicated). Got: {}",
user_items.len()
);
}
/// PHP superglobals should appear in variable completion.
#[tokio::test]
async fn test_completion_superglobals() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_super.php").unwrap();
let text = concat!("<?php\n", "$_GE\n",);
let items = complete_at(&backend, &uri, text, 1, 4).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
var_labels.contains(&"$_GET"),
"Should suggest $_GET superglobal. Got: {:?}",
var_labels
);
}
/// All PHP superglobals should be available when typing `$_`.
#[tokio::test]
async fn test_completion_all_superglobals() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_all_super.php").unwrap();
let text = concat!("<?php\n", "$_\n",);
let items = complete_at(&backend, &uri, text, 1, 2).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
let expected_superglobals = [
"$_GET",
"$_POST",
"$_REQUEST",
"$_SESSION",
"$_COOKIE",
"$_SERVER",
"$_FILES",
"$_ENV",
];
for sg in &expected_superglobals {
assert!(
var_labels.contains(sg),
"Should suggest superglobal {}. Got: {:?}",
sg,
var_labels
);
}
}
/// Superglobals should have detail "PHP superglobal" and be marked deprecated
/// (grayed out in the UI).
#[tokio::test]
async fn test_completion_superglobal_detail() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_sg_detail.php").unwrap();
let text = concat!("<?php\n", "$_POST\n",);
let items = complete_at(&backend, &uri, text, 1, 6).await;
let post = items.iter().find(|i| i.label == "$_POST");
assert!(post.is_some(), "Should find $_POST in completions");
let post = post.unwrap();
assert_eq!(
post.detail.as_deref(),
Some("PHP superglobal"),
"Superglobals should have 'PHP superglobal' as detail"
);
assert!(
post.tags
.as_ref()
.is_some_and(|t| t.contains(&CompletionItemTag::DEPRECATED)),
"Superglobals should be tagged deprecated (grayed out)"
);
}
/// User-defined variables should have detail "variable".
#[tokio::test]
async fn test_completion_variable_detail() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_detail.php").unwrap();
let text = concat!("<?php\n", "$myVariable = 42;\n", "$myV\n",);
let items = complete_at(&backend, &uri, text, 2, 4).await;
let my_var = items.iter().find(|i| i.label == "$myVariable");
assert!(my_var.is_some(), "Should find $myVariable in completions");
assert_eq!(
my_var.unwrap().detail.as_deref(),
Some("variable"),
"User variables should have 'variable' as detail"
);
}
/// Variable completions should use CompletionItemKind::VARIABLE.
#[tokio::test]
async fn test_completion_variable_kind() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_kind.php").unwrap();
let text = concat!("<?php\n", "$count = 42;\n", "$cou\n",);
let items = complete_at(&backend, &uri, text, 2, 4).await;
let count_item = items.iter().find(|i| i.label == "$count");
assert!(count_item.is_some(), "Should find $count in completions");
assert_eq!(
count_item.unwrap().kind,
Some(CompletionItemKind::VARIABLE),
"Variable completions should use VARIABLE kind"
);
}
/// Superglobals should sort after user-defined variables.
#[tokio::test]
async fn test_completion_superglobals_sort_after_variables() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_sg_sort.php").unwrap();
let text = concat!("<?php\n", "$_GET['name'];\n", "$_myVar = 1;\n", "$_\n",);
// Cursor at `$_` on line 3 — matches both $_myVar and superglobals
let items = complete_at(&backend, &uri, text, 3, 2).await;
let var_items: Vec<_> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.collect();
let my_var = var_items.iter().find(|i| i.label == "$_myVar");
let get_sg = var_items.iter().find(|i| i.label == "$_GET");
assert!(
my_var.is_some(),
"Should find $_myVar. Got: {:?}",
var_items.iter().map(|i| &i.label).collect::<Vec<_>>()
);
assert!(
get_sg.is_some(),
"Should find $_GET. Got: {:?}",
var_items.iter().map(|i| &i.label).collect::<Vec<_>>()
);
let my_var = my_var.unwrap();
let get_sg = get_sg.unwrap();
// User-defined variables should NOT be deprecated
assert!(
!my_var
.tags
.as_ref()
.is_some_and(|t| t.contains(&CompletionItemTag::DEPRECATED)),
"User-defined variables should not be tagged deprecated"
);
// Superglobals should be deprecated (grayed out)
assert!(
get_sg
.tags
.as_ref()
.is_some_and(|t| t.contains(&CompletionItemTag::DEPRECATED)),
"Superglobals should be tagged deprecated (grayed out)"
);
// sort_text of user variable should come before superglobal
assert!(
my_var.sort_text.as_deref().unwrap() < get_sg.sort_text.as_deref().unwrap(),
"User variables (sort_text={:?}) should sort before superglobals (sort_text={:?})",
my_var.sort_text,
get_sg.sort_text
);
}
/// Variable completions use `text_edit` with an explicit replacement range
/// that covers the `$` prefix, preventing the double-dollar problem in
/// editors like Helix and Neovim.
#[tokio::test]
async fn test_completion_variable_uses_text_edit_with_dollar() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_insert.php").unwrap();
let text = concat!("<?php\n", "$result = compute();\n", "$res\n",);
let items = complete_at(&backend, &uri, text, 2, 4).await;
let result_item = items.iter().find(|i| i.label == "$result");
assert!(result_item.is_some(), "Should find $result in completions");
let item = result_item.unwrap();
// Should use text_edit (not insert_text) with an explicit range
// covering the typed prefix including `$`.
match &item.text_edit {
Some(CompletionTextEdit::Edit(te)) => {
assert_eq!(
te.new_text, "$result",
"text_edit new_text should be $result"
);
// Range should start at the `$` (line 2, col 0) and end at cursor (line 2, col 4).
assert_eq!(te.range.start, Position::new(2, 0));
assert_eq!(te.range.end, Position::new(2, 4));
}
other => panic!("Expected text_edit with Edit variant, got: {:?}", other),
}
}
/// Variables from function parameters should be suggested.
#[tokio::test]
async fn test_completion_variable_from_function_params() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_params.php").unwrap();
let text = concat!(
"<?php\n",
"function greet(string $firstName, string $lastName): string {\n",
" return $fir\n",
"}\n",
);
// Cursor at end of `$fir` on line 2
let items = complete_at(&backend, &uri, text, 2, 15).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
var_labels.contains(&"$firstName"),
"Should suggest $firstName from function params. Got: {:?}",
var_labels
);
}
/// Variables from method parameters should be suggested.
#[tokio::test]
async fn test_completion_variable_from_method_params() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_method_params.php").unwrap();
let text = concat!(
"<?php\n",
"class UserService {\n",
" public function findUser(int $userId, string $role): void {\n",
" $user\n",
" }\n",
"}\n",
);
// Cursor at end of `$user` on line 3
let items = complete_at(&backend, &uri, text, 3, 13).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
var_labels.contains(&"$userId"),
"Should suggest $userId from method params. Got: {:?}",
var_labels
);
}
/// Variables defined AFTER the cursor should NOT be suggested.
/// PHP variables don't exist until assigned, so suggesting a variable
/// defined hundreds of lines later is incorrect and confusing.
#[tokio::test]
async fn test_completion_variable_from_later_in_file() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_later.php").unwrap();
let text = concat!("<?php\n", "$ear\n", "$earlyVar = 1;\n", "$laterVar = 2;\n",);
// Cursor at end of `$ear` on line 1 — both $earlyVar and $laterVar
// are defined AFTER the cursor, so neither should be suggested.
let items = complete_at(&backend, &uri, text, 1, 4).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
!var_labels.contains(&"$earlyVar"),
"$earlyVar is defined after the cursor and should NOT be suggested. Got: {:?}",
var_labels
);
assert!(
!var_labels.contains(&"$laterVar"),
"$laterVar is defined after the cursor and should NOT be suggested. Got: {:?}",
var_labels
);
}
/// Variables defined BEFORE the cursor should still be suggested.
#[tokio::test]
async fn test_completion_variable_defined_before_cursor() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_before.php").unwrap();
let text = concat!("<?php\n", "$earlyVar = 1;\n", "$laterVar = 2;\n", "$ear\n",);
// Cursor at end of `$ear` on line 3 — both variables are defined
// BEFORE the cursor, so both should be suggested.
let items = complete_at(&backend, &uri, text, 3, 4).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
var_labels.contains(&"$earlyVar"),
"Should suggest $earlyVar (defined before cursor). Got: {:?}",
var_labels
);
}
/// A variable defined far below the cursor (e.g. line 535 vs line 15)
/// should NOT appear in completions.
#[tokio::test]
async fn test_completion_variable_far_below_cursor_not_suggested() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_far_below.php").unwrap();
// Build a file where the cursor is near the top and a matching
// variable is defined much further down.
let mut text = String::from("<?php\n$amb\n");
// Add many blank lines to simulate distance
for _ in 0..100 {
text.push_str("// filler line\n");
}
text.push_str("$ambiguous = new stdClass();\n");
// Cursor at end of `$amb` on line 1
let items = complete_at(&backend, &uri, &text, 1, 4).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
!var_labels.contains(&"$ambiguous"),
"$ambiguous is defined far below the cursor and should NOT be suggested. Got: {:?}",
var_labels
);
}
/// The variable currently being typed should NOT appear in its own completions.
#[tokio::test]
async fn test_completion_excludes_variable_at_cursor() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_exclude.php").unwrap();
let text = concat!("<?php\n", "$uniqueTestVar\n",);
// Cursor at end of `$uniqueTestVar` on line 1 — only occurrence
let items = complete_at(&backend, &uri, text, 1, 14).await;
let self_items: Vec<_> = items
.iter()
.filter(|i| i.label == "$uniqueTestVar")
.collect();
assert!(
self_items.is_empty(),
"Should NOT suggest the variable being typed at the cursor. Got: {:?}",
self_items.iter().map(|i| &i.label).collect::<Vec<_>>()
);
}
/// Variable completion should NOT trigger after `->` (member access).
#[tokio::test]
async fn test_completion_variable_not_after_arrow() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_no_arrow.php").unwrap();
let text = concat!(
"<?php\n",
"class Foo { public string $name; }\n",
"$foo = new Foo();\n",
"$foo->na\n",
);
let items = complete_at(&backend, &uri, text, 3, 8).await;
// After `->`, we should NOT get standalone variable name completions
// (member completion handles this context).
let standalone_var_items: Vec<_> = items
.iter()
.filter(|i| {
i.kind == Some(CompletionItemKind::VARIABLE) && i.detail.as_deref() == Some("variable")
})
.collect();
assert!(
standalone_var_items.is_empty(),
"Standalone variable names should not appear after '->'. Got: {:?}",
standalone_var_items
.iter()
.map(|i| &i.label)
.collect::<Vec<_>>()
);
}
/// Multiple variables with similar prefixes should all be suggested.
#[tokio::test]
async fn test_completion_multiple_matching_variables() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_multi.php").unwrap();
let text = concat!(
"<?php\n",
"$userData = [];\n",
"$userName = 'Alice';\n",
"$userEmail = 'alice@test.com';\n",
"$userAge = 30;\n",
"$user\n",
);
// Cursor at end of `$user` on line 5
let items = complete_at(&backend, &uri, text, 5, 5).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
var_labels.contains(&"$userData"),
"Should suggest $userData. Got: {:?}",
var_labels
);
assert!(
var_labels.contains(&"$userName"),
"Should suggest $userName. Got: {:?}",
var_labels
);
assert!(
var_labels.contains(&"$userEmail"),
"Should suggest $userEmail. Got: {:?}",
var_labels
);
assert!(
var_labels.contains(&"$userAge"),
"Should suggest $userAge. Got: {:?}",
var_labels
);
}
/// `$this` should be suggested inside a class method even when it
/// doesn't appear elsewhere in the file (it's a built-in variable).
#[tokio::test]
async fn test_completion_this_inside_method() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_this.php").unwrap();
let text = concat!(
"<?php\n",
"class MyClass {\n",
" public function doSomething(): void {\n",
" $th\n",
" }\n",
"}\n",
);
let items = complete_at(&backend, &uri, text, 3, 11).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
var_labels.contains(&"$this"),
"Should suggest $this inside a class method (built-in). Got: {:?}",
var_labels
);
}
/// Variables in foreach loops should be suggested.
#[tokio::test]
async fn test_completion_variable_from_foreach() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_foreach.php").unwrap();
let text = concat!(
"<?php\n",
"$items = [1, 2, 3];\n",
"foreach ($items as $key => $value) {\n",
" echo $val\n",
"}\n",
);
// Prefix is `$val` — should match `$value`
let items = complete_at(&backend, &uri, text, 3, 13).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
var_labels.contains(&"$value"),
"Should suggest $value from foreach. Got: {:?}",
var_labels
);
}
/// Foreach loop key variable should be suggested with a matching prefix.
#[tokio::test]
async fn test_completion_variable_from_foreach_key() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_foreach_key.php").unwrap();
let text = concat!(
"<?php\n",
"$items = [1, 2, 3];\n",
"foreach ($items as $key => $value) {\n",
" echo $ke\n",
"}\n",
);
// Prefix is `$ke` — should match `$key`
let items = complete_at(&backend, &uri, text, 3, 12).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
var_labels.contains(&"$key"),
"Should suggest $key from foreach. Got: {:?}",
var_labels
);
}
/// Variables from catch blocks should be suggested.
#[tokio::test]
async fn test_completion_variable_from_catch() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_catch.php").unwrap();
let text = concat!(
"<?php\n",
"try {\n",
" riskyOperation();\n",
"} catch (Exception $exception) {\n",
" echo $exc\n",
"}\n",
);
let items = complete_at(&backend, &uri, text, 4, 13).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
var_labels.contains(&"$exception"),
"Should suggest $exception from catch block. Got: {:?}",
var_labels
);
}
/// `$GLOBALS` should be suggested when typing `$GL`.
#[tokio::test]
async fn test_completion_globals_superglobal() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_globals.php").unwrap();
let text = concat!("<?php\n", "$GL\n",);
let items = complete_at(&backend, &uri, text, 1, 3).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
var_labels.contains(&"$GLOBALS"),
"Should suggest $GLOBALS superglobal. Got: {:?}",
var_labels
);
}
/// `$argc` and `$argv` should be suggested.
#[tokio::test]
async fn test_completion_argc_argv() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_cli.php").unwrap();
let text = concat!("<?php\n", "$arg\n",);
let items = complete_at(&backend, &uri, text, 1, 4).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
var_labels.contains(&"$argc"),
"Should suggest $argc. Got: {:?}",
var_labels
);
assert!(
var_labels.contains(&"$argv"),
"Should suggest $argv. Got: {:?}",
var_labels
);
}
/// Variable completion should work inside an if block.
#[tokio::test]
async fn test_completion_variable_inside_if_block() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_if.php").unwrap();
let text = concat!(
"<?php\n",
"$config = loadConfig();\n",
"$connection = null;\n",
"if ($config) {\n",
" $con\n",
"}\n",
);
let items = complete_at(&backend, &uri, text, 4, 8).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
var_labels.contains(&"$config"),
"Should suggest $config. Got: {:?}",
var_labels
);
assert!(
var_labels.contains(&"$connection"),
"Should suggest $connection. Got: {:?}",
var_labels
);
}
/// Non-variable identifiers (class names, functions) should NOT trigger
/// variable completion.
#[tokio::test]
async fn test_completion_no_variable_for_classname() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_no_class.php").unwrap();
let text = concat!("<?php\n", "MyClass\n",);
let items = complete_at(&backend, &uri, text, 1, 7).await;
// This should trigger class/function/constant completion, NOT variable
let var_items: Vec<_> = items
.iter()
.filter(|i| {
i.kind == Some(CompletionItemKind::VARIABLE) && i.detail.as_deref() == Some("variable")
})
.collect();
assert!(
var_items.is_empty(),
"Class name identifiers should not produce variable completions. Got: {:?}",
var_items.iter().map(|i| &i.label).collect::<Vec<_>>()
);
}
/// Variable completion should work with variables containing underscores.
#[tokio::test]
async fn test_completion_variable_with_underscores() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_underscore.php").unwrap();
let text = concat!("<?php\n", "$my_long_variable_name = 'hello';\n", "$my_lo\n",);
let items = complete_at(&backend, &uri, text, 2, 6).await;
let var_labels: Vec<&str> = items
.iter()
.filter(|i| i.kind == Some(CompletionItemKind::VARIABLE))
.map(|i| i.label.as_str())
.collect();
assert!(
var_labels.contains(&"$my_long_variable_name"),
"Should suggest $my_long_variable_name. Got: {:?}",
var_labels
);
}
/// Variable completion should be case-insensitive for matching.
#[tokio::test]
async fn test_completion_variable_case_insensitive() {
let backend = create_test_backend();
let uri = Url::parse("file:///var_case.php").unwrap();
let text = concat!("<?php\n", "$MyVariable = 42;\n", "$myv\n",);
let items = complete_at(&backend, &uri, text, 2, 4).await;