php-lsp 0.11.0

A PHP Language Server Protocol implementation
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
mod attribute;
use attribute::attribute_completions;

mod include_path;
use include_path::{include_path_completions, include_path_prefix};

mod keyword;
pub use keyword::{keyword_completions, magic_constant_completions};

mod match_arm;
use match_arm::match_arm_completions;

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

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

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

use std::sync::Arc;

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

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

use crate::document::ast::{ParsedDoc, format_type_hint};
use crate::hover::format_params_str;
use crate::lang::docblock::find_docblock;
use crate::lang::phpstorm_meta::PhpStormMeta;
use crate::text::{camel_sort_key, utf16_offset_to_byte};
use crate::types::type_map::{TypeMap, enclosing_class_at, params_of_function, params_of_method};
use std::collections::HashMap;

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

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

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

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

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

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

/// Workspace-index-backed class lookup: maps a short class name to the
/// `ParsedDoc` that defines it. Used by `all_instance_members` and
/// `all_static_members` to avoid scanning all workspace docs linearly.
pub type ClassDocLookup<'a> = &'a dyn Fn(&str) -> Option<Arc<ParsedDoc>>;

/// Optional context for completion requests that enables richer results
/// (e.g. auto-import edits, `->` scoping to a class).
#[derive(Default)]
pub struct CompletionCtx<'a> {
    pub source: Option<&'a str>,
    pub position: Option<Position>,
    pub meta: Option<&'a PhpStormMeta>,
    pub doc_uri: Option<&'a Url>,
    pub file_imports: Option<&'a HashMap<String, String>>,
    /// Optional O(1) class-document lookup backed by the workspace index.
    /// When `Some`, `all_instance_members` and `all_static_members` use it
    /// to find the defining doc directly instead of scanning `other_docs`
    /// linearly (O(n files × inheritance depth) → O(depth)).
    /// Pass `None` to fall back to the existing linear scan.
    pub find_class_doc: Option<ClassDocLookup<'a>>,
    /// Retained mir body analysis for the primary doc. Receiver-variable types
    /// (`$obj->`, match subjects) are read from its `symbol_at`; `None` in unit
    /// tests that don't supply it.
    pub analysis: Option<&'a mir_analyzer::FileAnalysis>,
    /// Optional cross-request cache for the whole-doc [`TypeMap`]. The backend
    /// wires this to `DocumentStore::cached_type_map` so the receiver-type
    /// paths (`->`, `::`, match arms) reuse one map per document revision
    /// instead of walking the full AST on every completion request. `None`
    /// (unit tests) builds the map fresh.
    pub type_map: Option<&'a dyn Fn() -> Arc<TypeMap>>,
    /// mir-analyzer session for querying phpstorm-stubs member info on
    /// built-in PHP classes. `None` in unit tests that don't require stubs.
    pub session: Option<std::sync::Arc<mir_analyzer::AnalysisSession>>,
}

/// Whole-doc [`TypeMap`] through the ctx cache when wired, else a fresh build.
fn whole_doc_type_map(
    ctx: &CompletionCtx<'_>,
    doc: &ParsedDoc,
    meta: Option<&PhpStormMeta>,
) -> Arc<TypeMap> {
    match ctx.type_map {
        Some(get) => get(),
        None => Arc::new(TypeMap::from_doc_with_meta(doc, meta)),
    }
}

/// Returns `true` when `cursor_byte` falls inside a PHP string literal or
/// comment. Scans the source from the beginning with a simple state machine;
/// handles single/double-quoted strings (with backslash escapes), `// …` and
/// `# …` line comments, and `/* … */` block comments. Heredoc/nowdoc are not
/// tracked — they are too rare in interactive editing contexts to warrant the
/// complexity, and missing them produces a false-negative (completions shown
/// inside a heredoc), not a false-positive (completions suppressed outside one).
pub(crate) fn cursor_in_string_or_comment(source: &str, cursor_byte: usize) -> bool {
    #[derive(PartialEq)]
    enum S {
        Normal,
        Single,
        Double,
        Line,
        Block,
    }
    let bytes = source.as_bytes();
    let limit = bytes.len().min(cursor_byte);
    let mut i = 0usize;
    let mut state = S::Normal;
    while i < limit {
        match state {
            S::Normal => match bytes[i] {
                b'\'' => {
                    state = S::Single;
                    i += 1;
                }
                b'"' => {
                    state = S::Double;
                    i += 1;
                }
                b'/' if i + 1 < limit && bytes[i + 1] == b'/' => {
                    state = S::Line;
                    i += 2;
                }
                // `#[` is a PHP 8 attribute — not a comment.
                b'#' if !(i + 1 < limit && bytes[i + 1] == b'[') => {
                    state = S::Line;
                    i += 1;
                }
                b'/' if i + 1 < limit && bytes[i + 1] == b'*' => {
                    state = S::Block;
                    i += 2;
                }
                _ => {
                    i += 1;
                }
            },
            S::Single => match bytes[i] {
                b'\\' => {
                    i += 2;
                }
                b'\'' => {
                    state = S::Normal;
                    i += 1;
                }
                _ => {
                    i += 1;
                }
            },
            S::Double => match bytes[i] {
                b'\\' => {
                    i += 2;
                }
                b'"' => {
                    state = S::Normal;
                    i += 1;
                }
                _ => {
                    i += 1;
                }
            },
            S::Line => {
                if bytes[i] == b'\n' {
                    state = S::Normal;
                }
                i += 1;
            }
            S::Block => {
                if bytes[i] == b'*' && i + 1 < limit && bytes[i + 1] == b'/' {
                    state = S::Normal;
                    i += 2;
                } else {
                    i += 1;
                }
            }
        }
    }
    state != S::Normal
}

/// Completions filtered by trigger character, with optional context
/// so that `->` completions can be scoped to the variable's class.
pub fn filtered_completions_at(
    doc: &ParsedDoc,
    other_docs: &[Arc<ParsedDoc>],
    trigger_character: Option<&str>,
    ctx: &CompletionCtx<'_>,
) -> Vec<CompletionItem> {
    let source = ctx.source;
    let position = ctx.position;

    let doc_uri = ctx.doc_uri;

    // Suppress all completions when the cursor is inside a string literal or
    // comment — except for include/require path strings, where file-path
    // completions are legitimate inside the string argument.
    if let (Some(src), Some(pos)) = (source, position) {
        let cursor_byte = doc.view().byte_of_position(pos) as usize;
        if cursor_in_string_or_comment(src, cursor_byte) && include_path_prefix(src, pos).is_none()
        {
            return vec![];
        }
    }
    let meta = ctx.meta;
    let empty_imports = HashMap::new();
    let imports = ctx.file_imports.unwrap_or(&empty_imports);

    match trigger_character {
        Some("$") => {
            let mut items = superglobal_completions();
            items.extend(
                symbol_completions(doc)
                    .into_iter()
                    .filter(|i| i.kind == Some(CompletionItemKind::VARIABLE)),
            );
            items
        }
        Some(">") => {
            // Arrow: $obj->  or  $this->
            if let (Some(src), Some(pos)) = (source, position) {
                let type_map = whole_doc_type_map(ctx, doc, meta);
                if let Some(class_names) =
                    resolve_receiver_class(src, doc, pos, ctx.analysis, &type_map)
                {
                    // Feature 5: support union types (Foo|Bar)
                    let mut items = Vec::new();
                    let mut seen = std::collections::HashSet::new();
                    for class_name in class_names.split('|') {
                        let class_name = class_name.trim();
                        for item in all_instance_members(
                            class_name,
                            doc,
                            other_docs,
                            ctx.find_class_doc,
                            ctx.session.as_deref(),
                        ) {
                            if seen.insert(item.label.clone()) {
                                items.push(item);
                            }
                        }
                    }
                    if !items.is_empty() {
                        return items;
                    }
                }
            }
            // Fallback: all methods from current doc
            symbol_completions(doc)
                .into_iter()
                .filter(|i| i.kind == Some(CompletionItemKind::METHOD))
                .collect()
        }
        Some(":") => {
            // Static access: ClassName:: / self:: / static:: / parent::
            if let (Some(src), Some(pos)) = (source, position)
                && let Some(class_name) =
                    resolve_static_receiver(src, doc, other_docs, pos, imports)
            {
                let items = all_static_members(
                    &class_name,
                    doc,
                    other_docs,
                    ctx.find_class_doc,
                    ctx.session.as_deref(),
                );
                if !items.is_empty() {
                    return items;
                }
            }
            vec![]
        }
        Some("[") => {
            // PHP attribute: #[ — suggest only #[\Attribute]-annotated classes.
            if let (Some(src), Some(pos)) = (source, position) {
                let line = src.lines().nth(pos.line as usize).unwrap_or("");
                let col = utf16_offset_to_byte(line, pos.character as usize);
                let before = &line[..col];
                if before.trim_end_matches('[').trim_end().ends_with('#') {
                    return attribute_completions(src, pos, doc, other_docs, imports);
                }
            }
            vec![]
        }
        Some("(") => {
            // Named argument: funcName(
            if let (Some(src), Some(pos)) = (source, position) {
                let params = resolve_call_params(src, doc, other_docs, pos);
                if !params.is_empty() {
                    return params
                        .into_iter()
                        .map(|p| CompletionItem {
                            label: format!("{p}:"),
                            kind: Some(CompletionItemKind::VARIABLE),
                            ..Default::default()
                        })
                        .collect();
                }
                // Attribute constructor: #[ClassName(
                if let Some(attr_class) = resolve_attribute_class(src, pos) {
                    let mut attr_params = params_of_method(doc, &attr_class, "__construct");
                    if attr_params.is_empty() {
                        for other in other_docs {
                            attr_params = params_of_method(other, &attr_class, "__construct");
                            if !attr_params.is_empty() {
                                break;
                            }
                        }
                    }
                    if !attr_params.is_empty() {
                        return attr_params
                            .into_iter()
                            .map(|p| CompletionItem {
                                label: format!("{p}:"),
                                kind: Some(CompletionItemKind::VARIABLE),
                                detail: Some(format!("#{attr_class} argument")),
                                ..Default::default()
                            })
                            .collect();
                    }
                }
            }
            vec![]
        }
        _ => {
            // Static access context: ClassName::member (invoked without trigger char).
            // Strip any identifier chars being typed as the member prefix.
            if let (Some(src), Some(pos)) = (source, position) {
                let line = src.lines().nth(pos.line as usize).unwrap_or("");
                let col = utf16_offset_to_byte(line, pos.character as usize);
                let before = &line[..col];
                let pre_colon = before.trim_end_matches(|c: char| c.is_alphanumeric() || c == '_');
                if pre_colon.ends_with("::") {
                    let colon_end_char = pre_colon.encode_utf16().count() as u32;
                    let colon_pos = tower_lsp::lsp_types::Position {
                        line: pos.line,
                        character: colon_end_char,
                    };
                    if let Some(class_name) =
                        resolve_static_receiver(src, doc, other_docs, colon_pos, imports)
                    {
                        let items = all_static_members(
                            &class_name,
                            doc,
                            other_docs,
                            ctx.find_class_doc,
                            ctx.session.as_deref(),
                        );
                        if !items.is_empty() {
                            return items;
                        }
                    }
                }
            }

            // Detect $obj->member context (invoked completion without trigger char).
            // Returns only the receiver class's instance members so unrelated class
            // methods don't pollute the list.
            if let (Some(src), Some(pos)) = (source, position) {
                let line = src.lines().nth(pos.line as usize).unwrap_or("");
                let col = utf16_offset_to_byte(line, pos.character as usize);
                let before = &line[..col];
                // Strip any identifier chars the user is typing as the member prefix.
                let pre_arrow = before.trim_end_matches(|c: char| c.is_alphanumeric() || c == '_');
                let has_arrow = pre_arrow.ends_with("->") || pre_arrow.ends_with("?->");
                if has_arrow {
                    // Synthesise a cursor that sits right at the end of the arrow so
                    // that `resolve_receiver_class` — which strips the trailing `->` /
                    // `?->` itself — can locate the receiver.  This correctly handles
                    // simple variables ($obj->), `(new Foo())->`, method chains
                    // ($obj->getUser()->), and nullable operators ($obj?->).
                    let arrow_end_char = pre_arrow.encode_utf16().count() as u32;
                    let arrow_pos = tower_lsp::lsp_types::Position {
                        line: pos.line,
                        character: arrow_end_char,
                    };
                    let type_map = whole_doc_type_map(ctx, doc, meta);
                    if let Some(cls) =
                        resolve_receiver_class(src, doc, arrow_pos, ctx.analysis, &type_map)
                    {
                        let mut items = Vec::new();
                        let mut seen = std::collections::HashSet::new();
                        for class_name in cls.split('|') {
                            for item in all_instance_members(
                                class_name.trim(),
                                doc,
                                other_docs,
                                ctx.find_class_doc,
                                ctx.session.as_deref(),
                            ) {
                                if seen.insert(item.label.clone()) {
                                    items.push(item);
                                }
                            }
                        }
                        if !items.is_empty() {
                            // Apply fuzzy filtering based on the typed prefix.
                            let prefix = before.strip_prefix(pre_arrow).unwrap_or("").to_string();
                            if !prefix.is_empty() {
                                let fq = crate::text::FuzzyQuery::new(&prefix);
                                items.retain(|i| {
                                    let match_against = if i.label.starts_with('$') {
                                        i.label.strip_prefix('$').unwrap_or(&i.label)
                                    } else {
                                        &i.label
                                    };
                                    fq.camel_match(match_against)
                                });
                                for item in &mut items {
                                    let match_against = if item.label.starts_with('$') {
                                        item.label.strip_prefix('$').unwrap_or(&item.label)
                                    } else {
                                        &item.label
                                    };
                                    item.sort_text =
                                        Some(crate::text::camel_sort_key(&prefix, match_against));
                                    item.filter_text = Some(item.label.clone());
                                }
                            }
                            return items;
                        }
                    }
                }
            }

            // Attribute context: #[ or #[PartialName — invoked without trigger char.
            if let (Some(src), Some(pos)) = (source, position) {
                let line = src.lines().nth(pos.line as usize).unwrap_or("");
                let col = utf16_offset_to_byte(line, pos.character as usize);
                let before = &line[..col];
                let pre_ident =
                    before.trim_end_matches(|c: char| c.is_alphanumeric() || c == '_' || c == '\\');
                if pre_ident.trim_end().ends_with("#[") || pre_ident.trim_end() == "#[" {
                    let items = attribute_completions(src, pos, doc, other_docs, imports);
                    if !items.is_empty() {
                        return items;
                    }
                }
            }

            // Feature 4: detect `use ` context and suggest FQNs from other docs
            if let (Some(src), Some(pos)) = (source, position)
                && let Some(use_prefix) = use_completion_prefix(src, pos)
            {
                let mut use_items: Vec<CompletionItem> = Vec::new();
                for other in other_docs {
                    collect_fqns_with_prefix(
                        &other.program().stmts,
                        "",
                        &use_prefix,
                        &mut use_items,
                    );
                }
                // Also check current doc
                collect_fqns_with_prefix(&doc.program().stmts, "", &use_prefix, &mut use_items);
                if !use_items.is_empty() {
                    return use_items;
                }
            }

            // Feature 9: include/require path completions
            if let (Some(src), Some(pos), Some(uri)) = (source, position, doc_uri)
                && let Some(prefix) = include_path_prefix(src, pos)
            {
                // When in include/require context, return path completions (even if empty)
                // instead of falling back to keywords/symbols
                let items = include_path_completions(uri, &prefix);
                return items;
            }

            // Classes (label, kind, FQN) per other doc, collected lazily once
            // per request: the sub-namespace branch below falls through to the
            // default cross-file loop when nothing matches, which previously
            // re-collected the same lists from every doc's AST a second time.
            let other_classes_cell: std::cell::OnceCell<
                Vec<Vec<(String, CompletionItemKind, String)>>,
            > = std::cell::OnceCell::new();
            let other_classes = || {
                other_classes_cell.get_or_init(|| {
                    other_docs
                        .iter()
                        .map(|other| {
                            let mut classes = Vec::new();
                            collect_classes_with_ns(&other.program().stmts, "", &mut classes);
                            classes
                        })
                        .collect()
                })
            };

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

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

                // Deduplicate by label (first occurrence wins)
                let mut seen = std::collections::HashSet::new();
                all.retain(|i| seen.insert(i.label.clone()));

                return all;
            }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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