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
//! Import class code action.
//!
//! When the cursor is on an unresolved class name (a `ClassReference` in
//! the symbol map that cannot be resolved via use-map, namespace, or
//! local classes), offer code actions to add a `use` statement for each
//! matching class found in the class index, classmap, and stubs.

use std::collections::HashMap;

use tower_lsp::lsp_types::*;

use crate::Backend;
use crate::completion::use_edit::{analyze_use_block, build_use_edit, use_import_conflicts};
use crate::diagnostics::unknown_classes::UNKNOWN_CLASS_CODE;

use crate::symbol_map::SymbolKind;
use crate::util::{is_class_keyword, short_name};

impl Backend {
    /// Collect "Import class" code actions for the cursor position.
    ///
    /// For each unresolved `ClassReference` that overlaps with the
    /// request range, search the class index, classmap, and stubs for
    /// classes whose short name matches, and offer a code action per
    /// candidate.
    pub(crate) fn collect_import_class_actions(
        &self,
        uri: &str,
        content: &str,
        params: &CodeActionParams,
        out: &mut Vec<CodeActionOrCommand>,
    ) {
        // ── Gather file context ─────────────────────────────────────────
        let file_use_map: HashMap<String, String> = self.file_use_map(uri);

        let file_namespace: Option<String> = self.namespace_map.read().get(uri).cloned().flatten();

        let symbol_map = match self.symbol_maps.read().get(uri) {
            Some(sm) => sm.clone(),
            None => return,
        };

        let local_classes: Vec<crate::types::ClassInfo> = self
            .ast_map
            .read()
            .get(uri)
            .map(|v| {
                v.iter()
                    .map(|c| crate::types::ClassInfo::clone(c))
                    .collect()
            })
            .unwrap_or_default();

        // Convert LSP range to byte offsets for comparison with symbol spans.
        let request_start = crate::util::position_to_byte_offset(content, params.range.start);
        let request_end = crate::util::position_to_byte_offset(content, params.range.end);

        // ── Find ClassReference spans overlapping the request range ─────
        let affinity_table = crate::completion::class_completion::build_affinity_table(
            &file_use_map,
            &file_namespace,
        );
        for span in &symbol_map.spans {
            // Check overlap: span overlaps the request range if
            // span.start < request_end && span.end > request_start
            if span.start as usize >= request_end || span.end as usize <= request_start {
                continue;
            }

            let (ref_name, is_fqn) = match &span.kind {
                SymbolKind::ClassReference { name, is_fqn } => (name.as_str(), *is_fqn),
                _ => continue,
            };

            // Skip already-qualified names — they don't need importing.
            if is_fqn || ref_name.contains('\\') {
                continue;
            }

            // Skip if the name is already imported via use-map.
            if file_use_map.contains_key(ref_name) {
                continue;
            }

            // Skip if it resolves as a local class (same file).
            if local_classes.iter().any(|c| c.name == ref_name) {
                continue;
            }

            // Skip if it resolves via same-namespace lookup.
            if let Some(ns) = &file_namespace {
                let ns_qualified = format!("{}\\{}", ns, ref_name);
                if self.find_or_load_class(&ns_qualified).is_some() {
                    continue;
                }
            }

            // Skip if the unqualified name resolves in global scope
            // (and the file has no namespace, so no import needed).
            if file_namespace.is_none() && self.find_or_load_class(ref_name).is_some() {
                continue;
            }

            // ── Name is unresolved — find import candidates ─────────────
            let candidates = self.find_import_candidates(ref_name, &affinity_table);

            if candidates.is_empty() {
                continue;
            }

            let use_block = analyze_use_block(content);
            let doc_uri: Url = match uri.parse() {
                Ok(u) => u,
                Err(_) => continue,
            };

            // Find any unknown_class diagnostics from the request context
            // that overlap this span so we can attach them to the code
            // action.  This lets editors show the import action as a
            // quick-fix for the diagnostic.
            let matching_diagnostics: Vec<Diagnostic> = params
                .context
                .diagnostics
                .iter()
                .filter(|d| {
                    matches!(
                        &d.code,
                        Some(NumberOrString::String(code)) if code == UNKNOWN_CLASS_CODE
                    )
                })
                .cloned()
                .collect();

            for fqn in &candidates {
                // Skip candidates that would conflict with an existing
                // import (e.g. a different class with the same short name
                // is already imported).
                if use_import_conflicts(fqn, &file_use_map) {
                    continue;
                }

                let edits = match build_use_edit(fqn, &use_block, &file_namespace) {
                    Some(e) => e,
                    // No edit needed (global class, no namespace) — skip.
                    None => continue,
                };

                let title = format!("Import `{}`", fqn);

                let mut changes = HashMap::new();
                changes.insert(doc_uri.clone(), edits);

                out.push(CodeActionOrCommand::CodeAction(CodeAction {
                    title,
                    kind: Some(CodeActionKind::QUICKFIX),
                    diagnostics: if matching_diagnostics.is_empty() {
                        None
                    } else {
                        Some(matching_diagnostics.clone())
                    },
                    edit: Some(WorkspaceEdit {
                        changes: Some(changes),
                        document_changes: None,
                        change_annotations: None,
                    }),
                    command: None,
                    is_preferred: if candidates.len() == 1 {
                        Some(true)
                    } else {
                        None
                    },
                    disabled: None,
                    data: None,
                }));
            }

            // Only process the first unresolved reference at the cursor.
            // Multiple overlapping references at the exact same position
            // are unlikely, and processing one keeps the action list tidy.
            break;
        }

        // ── Also check MemberAccess spans for unresolved static subjects ─
        // e.g. `Foo::bar()` where `Foo` is not imported — the symbol map
        // records this as a MemberAccess with subject_text "Foo", not a
        // ClassReference.  We handle this by looking for static member
        // accesses whose subject is an unresolved short name.
        self.collect_import_from_static_access(
            uri,
            content,
            params,
            request_start,
            request_end,
            &file_use_map,
            &file_namespace,
            &local_classes,
            &symbol_map,
            out,
        );
    }

    /// Check static member access subjects for unresolved class names.
    #[allow(clippy::too_many_arguments)]
    fn collect_import_from_static_access(
        &self,
        uri: &str,
        content: &str,
        _params: &CodeActionParams,
        request_start: usize,
        request_end: usize,
        file_use_map: &HashMap<String, String>,
        file_namespace: &Option<String>,
        local_classes: &[crate::types::ClassInfo],
        symbol_map: &crate::symbol_map::SymbolMap,
        out: &mut Vec<CodeActionOrCommand>,
    ) {
        let affinity_table =
            crate::completion::class_completion::build_affinity_table(file_use_map, file_namespace);
        for span in &symbol_map.spans {
            if span.start as usize >= request_end || span.end as usize <= request_start {
                continue;
            }

            let subject = match &span.kind {
                SymbolKind::MemberAccess {
                    subject_text,
                    is_static: true,
                    ..
                } => subject_text.as_str(),
                _ => continue,
            };

            // Only handle simple unqualified names (not $this, self, parent, etc.)
            if subject.starts_with('$') || subject.contains('\\') || is_class_keyword(subject) {
                continue;
            }

            // Already imported?
            if file_use_map.contains_key(subject) {
                continue;
            }

            // Local class?
            if local_classes.iter().any(|c| c.name == subject) {
                continue;
            }

            // Resolves via namespace?
            if let Some(ns) = file_namespace {
                let ns_qualified = format!("{}\\{}", ns, subject);
                if self.find_or_load_class(&ns_qualified).is_some() {
                    continue;
                }
            }

            if file_namespace.is_none() && self.find_or_load_class(subject).is_some() {
                continue;
            }

            let candidates = self.find_import_candidates(subject, &affinity_table);
            if candidates.is_empty() {
                continue;
            }

            // The span covers the whole `Foo::bar` expression. We only
            // want the subject part for the diagnostic range, but for
            // the code action the span range is fine.
            let use_block = analyze_use_block(content);
            let doc_uri: Url = match uri.parse() {
                Ok(u) => u,
                Err(_) => continue,
            };

            for fqn in &candidates {
                if use_import_conflicts(fqn, file_use_map) {
                    continue;
                }

                let edits = match build_use_edit(fqn, &use_block, file_namespace) {
                    Some(e) => e,
                    None => continue,
                };

                let title = format!("Import `{}`", fqn);

                let mut changes = HashMap::new();
                changes.insert(doc_uri.clone(), edits);

                out.push(CodeActionOrCommand::CodeAction(CodeAction {
                    title,
                    kind: Some(CodeActionKind::QUICKFIX),
                    diagnostics: None,
                    edit: Some(WorkspaceEdit {
                        changes: Some(changes),
                        document_changes: None,
                        change_annotations: None,
                    }),
                    command: None,
                    is_preferred: if candidates.len() == 1 {
                        Some(true)
                    } else {
                        None
                    },
                    disabled: None,
                    data: None,
                }));
            }

            break;
        }
    }

    /// Search all known class sources for classes whose short name matches
    /// `name` (case-insensitive).
    ///
    /// Returns a deduplicated, sorted list of fully-qualified class names.
    fn find_import_candidates(
        &self,
        name: &str,
        affinity_table: &HashMap<String, u32>,
    ) -> Vec<String> {
        let mut candidates = Vec::new();
        let name_lower = name.to_lowercase();

        // ── 1. class_index ──────────────────────────────────────────────
        {
            let idx = self.class_index.read();
            for fqn in idx.keys() {
                if short_name(fqn).to_lowercase() == name_lower {
                    candidates.push(fqn.clone());
                }
            }
        }

        // ── 2. Composer classmap ────────────────────────────────────────
        {
            let cmap = self.classmap.read();
            for fqn in cmap.keys() {
                if short_name(fqn).to_lowercase() == name_lower
                    && !candidates
                        .iter()
                        .any(|c: &String| c.eq_ignore_ascii_case(fqn))
                {
                    candidates.push(fqn.clone());
                }
            }
        }

        // ── 3. ast_map (already-parsed files) ───────────────────────────
        {
            let amap = self.ast_map.read();
            let nmap = self.namespace_map.read();
            for (file_uri, classes) in amap.iter() {
                let ns = nmap.get(file_uri).and_then(|o| o.as_deref());
                for cls in classes {
                    if cls.name.to_lowercase() == name_lower {
                        let fqn = match ns {
                            Some(ns) => format!("{}\\{}", ns, cls.name),
                            None => cls.name.clone(),
                        };
                        if !candidates
                            .iter()
                            .any(|c: &String| c.eq_ignore_ascii_case(&fqn))
                        {
                            candidates.push(fqn);
                        }
                    }
                }
            }
        }

        // ── 4. Stubs (built-in PHP classes) ─────────────────────────────
        // Stubs are global-namespace classes, so the FQN is the short name.
        // Only add if the file has a namespace (otherwise no import needed).
        let stub_idx = self.stub_index.read();
        for &stub_name in stub_idx.keys() {
            if short_name(stub_name).to_lowercase() == name_lower
                && !candidates
                    .iter()
                    .any(|c: &String| c.eq_ignore_ascii_case(stub_name))
            {
                candidates.push(stub_name.to_string());
            }
        }

        candidates.sort();
        candidates.dedup();

        // Sort by affinity score descending, with alphabetical tiebreak.
        candidates.sort_by(|a, b| {
            let score_a = crate::completion::class_completion::affinity_score(a, affinity_table);
            let score_b = crate::completion::class_completion::affinity_score(b, affinity_table);
            score_b.cmp(&score_a).then_with(|| a.cmp(b))
        });

        candidates
    }
}

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

    // ── find_import_candidates smoke test ───────────────────────────────

    #[test]
    fn find_candidates_from_classmap() {
        let backend = crate::Backend::new_test();
        // Populate classmap with a known class.
        {
            let mut cmap = backend.classmap.write();
            cmap.insert(
                "App\\Models\\User".to_string(),
                "/fake/path/User.php".into(),
            );
            cmap.insert(
                "App\\Http\\Request".to_string(),
                "/fake/path/Request.php".into(),
            );
        }

        let table = std::collections::HashMap::new();
        let candidates = backend.find_import_candidates("User", &table);
        assert!(candidates.contains(&"App\\Models\\User".to_string()));
        assert!(!candidates.contains(&"App\\Http\\Request".to_string()));
    }

    #[test]
    fn find_candidates_case_insensitive() {
        let backend = crate::Backend::new_test();
        {
            let mut cmap = backend.classmap.write();
            cmap.insert(
                "Vendor\\Obscure\\ZYGOMORPHIC".to_string(),
                "/fake/path.php".into(),
            );
        }

        let table = std::collections::HashMap::new();
        let candidates = backend.find_import_candidates("Zygomorphic", &table);
        assert_eq!(candidates.len(), 1);
        assert_eq!(candidates[0], "Vendor\\Obscure\\ZYGOMORPHIC");
    }

    #[test]
    fn find_candidates_deduplicates() {
        let backend = crate::Backend::new_test();
        // Add the same FQN to both class_index and classmap.
        {
            let mut idx = backend.class_index.write();
            idx.insert("App\\Foo".to_string(), "file:///foo.php".to_string());
        }
        {
            let mut cmap = backend.classmap.write();
            cmap.insert("App\\Foo".to_string(), "/foo.php".into());
        }

        let table = std::collections::HashMap::new();
        let candidates = backend.find_import_candidates("Foo", &table);
        let count = candidates.iter().filter(|c| *c == "App\\Foo").count();
        assert_eq!(count, 1, "should not have duplicates");
    }

    // ── Integration-style test with code action collection ──────────────

    #[test]
    fn import_action_offered_for_unresolved_class() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nnamespace App;\n\nnew Request();\n";

        // Parse the file so the symbol map is populated.
        backend.update_ast(uri, content);

        // Add a candidate to the classmap.
        {
            let mut cmap = backend.classmap.write();
            cmap.insert(
                "Illuminate\\Http\\Request".to_string(),
                "/vendor/laravel/framework/src/Illuminate/Http/Request.php".into(),
            );
        }

        // Build a request range covering "Request" on line 3.
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(3, 4),
                end: Position::new(3, 11),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        assert!(
            actions.iter().any(|a| {
                if let CodeActionOrCommand::CodeAction(ca) = a {
                    ca.title.contains("Illuminate\\Http\\Request")
                } else {
                    false
                }
            }),
            "expected an import action for Illuminate\\Http\\Request, got: {:?}",
            actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(ca) => ca.title.clone(),
                    CodeActionOrCommand::Command(c) => c.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn no_import_action_when_already_imported() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nnamespace App;\n\nuse Illuminate\\Http\\Request;\n\nnew Request();\n";

        backend.update_ast(uri, content);

        {
            let mut cmap = backend.classmap.write();
            cmap.insert(
                "Illuminate\\Http\\Request".to_string(),
                "/vendor/laravel/framework/src/Illuminate/Http/Request.php".into(),
            );
        }

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(5, 4),
                end: Position::new(5, 11),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        // No import actions should be offered — Request is already imported.
        let import_actions: Vec<_> = actions
            .iter()
            .filter(|a| match a {
                CodeActionOrCommand::CodeAction(ca) => ca.title.starts_with("Import"),
                _ => false,
            })
            .collect();
        assert!(
            import_actions.is_empty(),
            "should not offer import when already imported, got: {:?}",
            import_actions
        );
    }

    #[test]
    fn no_import_action_for_fqn_reference() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nnamespace App;\n\nnew \\Illuminate\\Http\\Request();\n";

        backend.update_ast(uri, content);

        {
            let mut cmap = backend.classmap.write();
            cmap.insert(
                "Illuminate\\Http\\Request".to_string(),
                "/vendor/laravel/framework/src/Illuminate/Http/Request.php".into(),
            );
        }

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(3, 5),
                end: Position::new(3, 35),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let import_actions: Vec<_> = actions
            .iter()
            .filter(|a| match a {
                CodeActionOrCommand::CodeAction(ca) => ca.title.starts_with("Import"),
                _ => false,
            })
            .collect();
        assert!(
            import_actions.is_empty(),
            "should not offer import for FQN reference"
        );
    }

    #[test]
    fn import_action_inserts_use_statement() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\nnamespace App;\n\nnew Request();\n";

        backend.update_ast(uri, content);

        {
            let mut cmap = backend.classmap.write();
            cmap.insert(
                "Illuminate\\Http\\Request".to_string(),
                "/vendor/laravel/framework/src/Illuminate/Http/Request.php".into(),
            );
        }

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(3, 4),
                end: Position::new(3, 11),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let action = actions
            .iter()
            .find_map(|a| match a {
                CodeActionOrCommand::CodeAction(ca)
                    if ca.title.contains("Illuminate\\Http\\Request") =>
                {
                    Some(ca)
                }
                _ => None,
            })
            .expect("expected import action");

        // Verify the edit inserts a use statement.
        let edit = action.edit.as_ref().expect("expected workspace edit");
        let changes = edit.changes.as_ref().expect("expected changes");
        let file_edits = changes
            .get(&uri.parse::<Url>().unwrap())
            .expect("expected edits for the file");
        assert_eq!(file_edits.len(), 1);
        assert_eq!(file_edits[0].new_text, "use Illuminate\\Http\\Request;\n");
    }

    #[test]
    fn import_skips_conflict_with_existing_import() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        // Already importing a *different* Request class.
        let content = "<?php\nnamespace App;\n\nuse Symfony\\Component\\HttpFoundation\\Request;\n\nnew Request();\n";

        backend.update_ast(uri, content);

        {
            let mut cmap = backend.classmap.write();
            cmap.insert(
                "Illuminate\\Http\\Request".to_string(),
                "/vendor/laravel/framework/src/Illuminate/Http/Request.php".into(),
            );
        }

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(5, 4),
                end: Position::new(5, 11),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        // Should not offer importing Illuminate\Http\Request because
        // Symfony's Request is already imported with the same short name.
        let import_actions: Vec<_> = actions
            .iter()
            .filter(|a| match a {
                CodeActionOrCommand::CodeAction(ca) => {
                    ca.title.contains("Illuminate\\Http\\Request")
                }
                _ => false,
            })
            .collect();
        assert!(
            import_actions.is_empty(),
            "should not offer conflicting import"
        );
    }

    // ── No-namespace file tests ─────────────────────────────────────────

    #[test]
    fn import_action_offered_in_no_namespace_file_for_new_expression() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        // File has NO namespace declaration.
        let content = "<?php\n\nnew Request();\n";

        backend.update_ast(uri, content);

        {
            let mut cmap = backend.classmap.write();
            cmap.insert(
                "Illuminate\\Http\\Request".to_string(),
                "/vendor/laravel/framework/src/Illuminate/Http/Request.php".into(),
            );
        }

        // Range covering "Request" on line 2.
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(2, 4),
                end: Position::new(2, 11),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        assert!(
            actions.iter().any(|a| {
                if let CodeActionOrCommand::CodeAction(ca) = a {
                    ca.title.contains("Illuminate\\Http\\Request")
                } else {
                    false
                }
            }),
            "expected an import action for Illuminate\\Http\\Request in no-namespace file, got: {:?}",
            actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(ca) => ca.title.clone(),
                    CodeActionOrCommand::Command(c) => c.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn import_action_offered_in_no_namespace_file_for_static_call() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        // File has NO namespace — reproduces issue #59.
        let content = "<?php\n\nfunction () {\n    return Carbon::now();\n};\n";

        backend.update_ast(uri, content);

        {
            let mut cmap = backend.classmap.write();
            cmap.insert(
                "Carbon\\Carbon".to_string(),
                "/vendor/nesbot/carbon/src/Carbon/Carbon.php".into(),
            );
        }

        // Range covering "Carbon" on line 3 (the class name in Carbon::now()).
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(3, 11),
                end: Position::new(3, 17),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        assert!(
            actions.iter().any(|a| {
                if let CodeActionOrCommand::CodeAction(ca) = a {
                    ca.title.contains("Carbon\\Carbon")
                } else {
                    false
                }
            }),
            "expected an import action for Carbon\\Carbon in no-namespace file, got: {:?}",
            actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(ca) => ca.title.clone(),
                    CodeActionOrCommand::Command(c) => c.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn import_action_inserts_use_after_php_open_in_no_namespace_file() {
        let backend = crate::Backend::new_test();
        let uri = "file:///test.php";
        let content = "<?php\n\nnew Request();\n";

        backend.update_ast(uri, content);

        {
            let mut cmap = backend.classmap.write();
            cmap.insert(
                "Illuminate\\Http\\Request".to_string(),
                "/vendor/laravel/framework/src/Illuminate/Http/Request.php".into(),
            );
        }

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(2, 4),
                end: Position::new(2, 11),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let action = actions
            .iter()
            .find_map(|a| match a {
                CodeActionOrCommand::CodeAction(ca)
                    if ca.title.contains("Illuminate\\Http\\Request") =>
                {
                    Some(ca)
                }
                _ => None,
            })
            .expect("expected import action");

        let edit = action.edit.as_ref().expect("expected workspace edit");
        let changes = edit.changes.as_ref().expect("expected changes");
        let file_edits = changes
            .get(&uri.parse::<Url>().unwrap())
            .expect("expected edits for the file");
        assert_eq!(file_edits.len(), 1);
        assert_eq!(file_edits[0].new_text, "use Illuminate\\Http\\Request;\n");
        // Should insert after `<?php` (line 1), not line 0.
        assert_eq!(file_edits[0].range.start.line, 1);
    }

    #[test]
    fn no_import_action_for_known_global_class_in_no_namespace_file() {
        let backend = crate::Backend::new_test();
        let uri_dep = "file:///dep.php";
        let content_dep = "<?php\nclass Helper {}\n";
        backend.update_ast(uri_dep, content_dep);

        {
            let mut idx = backend.class_index.write();
            idx.insert("Helper".to_string(), uri_dep.to_string());
        }

        let uri = "file:///test.php";
        let content = "<?php\n\nnew Helper();\n";
        backend.update_ast(uri, content);

        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(2, 4),
                end: Position::new(2, 10),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        let import_actions: Vec<_> = actions
            .iter()
            .filter(|a| match a {
                CodeActionOrCommand::CodeAction(ca) => ca.title.starts_with("Import"),
                _ => false,
            })
            .collect();
        assert!(
            import_actions.is_empty(),
            "should not offer import for a known global class in no-namespace file, got: {:?}",
            import_actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(ca) => ca.title.clone(),
                    _ => String::new(),
                })
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn import_action_offered_when_namespaced_class_in_ast_map() {
        // Reproduces issue #59: when a namespaced class like `Carbon\Carbon`
        // is already parsed and in the ast_map, `find_or_load_class("Carbon")`
        // must NOT match it — the bare name `"Carbon"` is a global-scope
        // lookup and should not resolve to `Carbon\Carbon`.
        //
        // Without the fix, `find_class_in_ast_map("Carbon")` ignores the
        // namespace filter when `expected_ns` is `None`, so ANY class with
        // short name `Carbon` matches.  The import action then skips it
        // thinking "this class resolves in global scope".
        let backend = crate::Backend::new_test();

        // Parse the dependency file so Carbon\Carbon is in the ast_map.
        let uri_dep = "file:///vendor/carbon.php";
        let content_dep = "<?php\nnamespace Carbon;\n\nclass Carbon {}\n";
        backend.update_ast(uri_dep, content_dep);
        {
            let mut idx = backend.class_index.write();
            idx.insert("Carbon\\Carbon".to_string(), uri_dep.to_string());
        }

        // The file under edit has NO namespace.
        let uri = "file:///test.php";
        let content = "<?php\n\nfunction () {\n    return Carbon::now();\n};\n";
        backend.update_ast(uri, content);

        // Range covering "Carbon" on line 3.
        let params = CodeActionParams {
            text_document: TextDocumentIdentifier {
                uri: uri.parse().unwrap(),
            },
            range: Range {
                start: Position::new(3, 11),
                end: Position::new(3, 17),
            },
            context: CodeActionContext {
                diagnostics: vec![],
                only: None,
                trigger_kind: None,
            },
            work_done_progress_params: Default::default(),
            partial_result_params: Default::default(),
        };

        let actions = backend.handle_code_action(uri, content, &params);
        assert!(
            actions.iter().any(|a| {
                if let CodeActionOrCommand::CodeAction(ca) = a {
                    ca.title.contains("Carbon\\Carbon")
                } else {
                    false
                }
            }),
            "expected an import action for Carbon\\Carbon when the namespaced class is in ast_map, got: {:?}",
            actions
                .iter()
                .map(|a| match a {
                    CodeActionOrCommand::CodeAction(ca) => ca.title.clone(),
                    CodeActionOrCommand::Command(c) => c.title.clone(),
                })
                .collect::<Vec<_>>()
        );
    }
}