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
/// Goto-definition resolution — core entry points.
///
/// Given a cursor position in a PHP file this module:
///   1. Extracts the symbol (class / interface / trait / enum name) under the cursor.
///   2. Resolves it to a fully-qualified name using the file's `use` map and namespace.
///   3. Locates the file on disk via PSR-4 mappings.
///   4. Finds the exact line of the symbol's declaration inside that file.
///   5. Returns an LSP `Location` the editor can jump to.
///
/// Member-access resolution (methods, properties, constants via `->`, `?->`,
/// `::`) is handled by the sibling [`super::member`] module.
///
/// Variable definition resolution (`$var` → most recent assignment /
/// declaration) is handled by the sibling [`super::variable`] module.
use std::collections::HashMap;

use crate::symbol_map::VarDefKind;
use tower_lsp::lsp_types::*;

use super::member::{MemberAccessHint, MemberDefinitionCtx};
use super::point_location;
use crate::Backend;
use crate::composer;
use crate::symbol_map::{SelfStaticParentKind, SymbolKind};
use crate::types::{AccessKind, ClassInfo};
use crate::util::{find_class_at_offset, position_to_offset, short_name};

impl Backend {
    /// Handle a "go to definition" request.
    ///
    /// Returns `Some(Location)` when the symbol under the cursor can be
    /// resolved to a file and a position inside that file, or `None` when
    /// resolution fails at any step.
    pub(crate) fn resolve_definition(
        &self,
        uri: &str,
        content: &str,
        position: Position,
    ) -> Option<Location> {
        // Consult precomputed symbol map (retries one byte earlier for
        // end-of-token edge cases).
        let symbol = self.lookup_symbol_at_position(uri, content, position);
        symbol
            .as_ref()
            .and_then(|s| self.resolve_from_symbol(&s.kind, uri, content, position, s.start))
    }

    /// Look up the symbol at the given byte offset in the precomputed
    /// symbol map for `uri`.
    ///
    /// Returns a cloned [`SymbolKind`] to avoid holding the mutex lock
    /// across the resolution logic.
    pub(crate) fn lookup_symbol_map(
        &self,
        uri: &str,
        offset: u32,
    ) -> Option<crate::symbol_map::SymbolSpan> {
        let maps = self.symbol_maps.read();
        let map = maps.get(uri)?;
        map.lookup(offset).cloned()
    }

    /// Look up the symbol span at a cursor position, handling end-of-token
    /// edge cases by retrying one byte earlier when the exact offset
    /// produces no result.
    pub(crate) fn lookup_symbol_at_position(
        &self,
        uri: &str,
        content: &str,
        position: Position,
    ) -> Option<crate::symbol_map::SymbolSpan> {
        let offset = crate::util::position_to_offset(content, position);
        self.lookup_symbol_map(uri, offset).or_else(|| {
            if offset > 0 {
                self.lookup_symbol_map(uri, offset - 1)
            } else {
                None
            }
        })
    }

    /// Look up the most recent variable definition before `cursor_offset`
    /// in the precomputed symbol map for `uri`.
    ///
    /// Returns a cloned [`VarDefSite`] (if found) so that the mutex lock
    /// is not held across the resolution logic.
    fn lookup_var_definition(
        &self,
        uri: &str,
        var_name: &str,
        cursor_offset: u32,
    ) -> Option<crate::symbol_map::VarDefSite> {
        let maps = self.symbol_maps.read();
        let map = maps.get(uri)?;
        let scope_start = map.find_enclosing_scope(cursor_offset);
        map.find_var_definition(var_name, cursor_offset, scope_start)
            .cloned()
    }

    /// If the cursor is physically sitting on a variable definition token
    /// (assignment LHS, parameter, foreach binding, etc.), return the
    /// [`VarDefKind`] so the caller can decide how to handle it.
    pub(crate) fn lookup_var_def_kind_at(
        &self,
        uri: &str,
        var_name: &str,
        cursor_offset: u32,
    ) -> Option<VarDefKind> {
        let maps = self.symbol_maps.read();
        let map = maps.get(uri)?;
        map.var_def_kind_at(var_name, cursor_offset).cloned()
    }

    /// If the cursor is on a variable at its assignment definition site,
    /// return the `effective_from` offset (end of the assignment statement).
    ///
    /// This lets hover adjust the cursor offset so that the assignment's
    /// own RHS is included in the resolution — without it, hovering on
    /// the `$` of `$x = new Foo()` misses the assignment because the
    /// statement start coincides with the cursor offset and the
    /// "skip statements at or after cursor" guard excludes it.
    pub(crate) fn lookup_var_def_effective_from(
        &self,
        uri: &str,
        var_name: &str,
        cursor_offset: u32,
    ) -> Option<u32> {
        let maps = self.symbol_maps.read();
        let map = maps.get(uri)?;
        let def = map.var_def_at(var_name, cursor_offset)?;
        if matches!(def.kind, VarDefKind::Assignment) {
            Some(def.effective_from)
        } else {
            None
        }
    }

    /// Dispatch a symbol-map hit to the appropriate resolution path.
    ///
    /// Each [`SymbolKind`] variant maps directly to existing resolution
    /// logic — the symbol map replaces the former text-scanning step
    /// with an O(log n) binary search.
    fn resolve_from_symbol(
        &self,
        kind: &SymbolKind,
        uri: &str,
        content: &str,
        position: Position,
        cursor_offset: u32,
    ) -> Option<Location> {
        match kind {
            SymbolKind::Variable { name } => {
                let var_name = format!("${}", name);

                // Try the precomputed var_defs map first.
                // This avoids re-parsing the file at request time.

                // First, check if the cursor is physically on a definition
                // token (assignment LHS, parameter, foreach binding, etc.).
                // This must be checked before `find_var_definition` because
                // for assignments the definition's `effective_from` is past
                // the LHS token — the lookup would skip the definition and
                // find an earlier one instead of recognising "at definition".
                if let Some(def_kind) = self.lookup_var_def_kind_at(uri, name, cursor_offset) {
                    // Closure captures (`use ($var)`) are not terminal
                    // definition sites — the user wants to jump to the
                    // outer assignment, so we fall through to the
                    // outer-scope lookup.
                    if def_kind != VarDefKind::ClosureCapture {
                        // The cursor is on a variable at its definition
                        // site.  Return the symbol's own location so
                        // editors can fall back to Find References.
                        let parsed_uri = Url::parse(uri).ok()?;
                        let start =
                            crate::util::offset_to_position(content, cursor_offset as usize);
                        let end = crate::util::offset_to_position(
                            content,
                            cursor_offset as usize + 1 + name.len(),
                        );
                        return Some(Location {
                            uri: parsed_uri,
                            range: Range { start, end },
                        });
                    }
                }

                if let Some(var_def) = self.lookup_var_definition(uri, name, cursor_offset) {
                    // Found a prior definition — jump there.
                    let token_end = var_def.offset + 1 + var_def.name.len() as u32;
                    let target_uri = Url::parse(uri).ok()?;
                    let start_pos =
                        crate::util::offset_to_position(content, var_def.offset as usize);
                    let end_pos = crate::util::offset_to_position(content, token_end as usize);
                    return Some(Location {
                        uri: target_uri,
                        range: Range {
                            start: start_pos,
                            end: end_pos,
                        },
                    });
                }

                // Fallback: AST-based variable resolution.
                if let Some(location) =
                    Self::resolve_variable_definition(content, uri, position, &var_name)
                {
                    return Some(location);
                }
                None
            }

            SymbolKind::MemberAccess {
                subject_text,
                member_name,
                is_static,
                is_method_call,
                ..
            } => {
                let access_kind = if *is_static {
                    AccessKind::DoubleColon
                } else {
                    AccessKind::Arrow
                };
                let access_hint = if *is_method_call {
                    MemberAccessHint::MethodCall
                } else {
                    MemberAccessHint::PropertyAccess
                };
                let mctx = MemberDefinitionCtx {
                    member_name,
                    subject: subject_text,
                    access_kind,
                    access_hint,
                };
                self.resolve_member_definition_with(uri, content, position, &mctx)
            }

            SymbolKind::SelfStaticParent(ssp_kind) => {
                self.resolve_self_static_parent(uri, content, position, *ssp_kind)
            }

            SymbolKind::ClassReference { name, is_fqn } => {
                self.resolve_class_reference(uri, content, name, *is_fqn, cursor_offset)
            }

            SymbolKind::ClassDeclaration { name } | SymbolKind::MemberDeclaration { name, .. } => {
                // The cursor is on a declaration name.  Return the
                // symbol's own location so that editors can detect
                // "definition == current position" and fall back to
                // Find References (e.g. VS Code's
                // editor.gotoLocation.alternativeDefinitionCommand).
                let parsed_uri = Url::parse(uri).ok()?;
                let start = crate::util::offset_to_position(content, cursor_offset as usize);
                let end =
                    crate::util::offset_to_position(content, cursor_offset as usize + name.len());
                Some(Location {
                    uri: parsed_uri,
                    range: Range { start, end },
                })
            }

            SymbolKind::FunctionCall { name, .. } => {
                // Build FQN candidates: the resolved name, the raw name,
                // and (if namespaced) the namespace-qualified version.
                let ctx = self.file_context(uri);
                let fqn = ctx.resolve_name_at(name, cursor_offset);
                let mut candidates = vec![fqn];
                if name.contains('\\') && !candidates.contains(name) {
                    candidates.push(name.clone());
                }
                if !candidates.contains(name) {
                    candidates.push(name.clone());
                }
                self.resolve_function_definition(&candidates)
            }

            SymbolKind::ConstantReference { name } => {
                let ctx = self.file_context(uri);
                let fqn = ctx.resolve_name_at(name, cursor_offset);
                let mut candidates = vec![fqn];
                if !candidates.contains(name) {
                    candidates.push(name.clone());
                }
                // Try class constant (Name::CONST) first — but the symbol
                // map records class constants as MemberAccess, so this path
                // handles standalone `define()` constants and bare constant
                // references only.
                self.resolve_constant_definition(&candidates)
            }
        }
    }

    /// Resolve a `ClassReference` symbol to its definition.
    ///
    /// Tries same-file lookup (ast_map), then cross-file via PSR-4.
    /// When `is_fqn` is `true`, the name is already fully-qualified
    /// (the original PHP source used a leading `\`) and should be used
    /// as-is without namespace resolution.
    pub(super) fn resolve_class_reference(
        &self,
        uri: &str,
        content: &str,
        name: &str,
        is_fqn: bool,
        cursor_offset: u32,
    ) -> Option<Location> {
        let mut candidates = if is_fqn {
            // Already fully-qualified — use as-is.
            vec![name.to_string()]
        } else {
            let ctx = self.file_context(uri);
            let fqn = ctx.resolve_name_at(name, cursor_offset);
            let mut c = vec![fqn];
            if name.contains('\\') && !c.contains(&name.to_string()) {
                c.push(name.to_string());
            }
            c
        };
        // Always include the bare name as a last-resort candidate.
        if !candidates.contains(&name.to_string()) {
            candidates.push(name.to_string());
        }

        // Same-file lookup.
        for fqn in &candidates {
            if let Some(location) = self.find_definition_in_ast_map(fqn, content, uri) {
                return Some(location);
            }
        }

        // Cross-file lookup via class_index + ast_map.
        //
        // Classes discovered during autoload scanning (classmap, opened
        // files, previously navigated-to vendor files) live in
        // class_index (FQN → URI) and ast_map (URI → [ClassInfo]).
        for fqn in &candidates {
            let target_uri = self.class_index.read().get(fqn.as_str()).cloned();
            if let Some(ref target_uri) = target_uri
                && let Some(location) = self.find_definition_in_ast_map_cross_file(fqn, target_uri)
            {
                return Some(location);
            }
        }

        // Cross-file via Composer classmap: direct FQN → file path lookup.
        // This covers vendor classes that haven't been loaded into ast_map
        // yet (cold Ctrl+Click on a class never used in completion/hover).
        for fqn in &candidates {
            if let Some(file_path) = self.classmap.read().get(fqn.as_str()).cloned()
                && let Some(location) = self.resolve_class_in_file(&file_path, fqn)
            {
                return Some(location);
            }
        }

        // Cross-file via PSR-4: parse on demand and cache.
        // PSR-4 mappings only cover user code (from composer.json).
        // Vendor classes are resolved by the classmap above.
        let workspace_root = self.workspace_root.read().clone();

        if let Some(workspace_root) = workspace_root {
            let mappings = self.psr4_mappings.read();
            for fqn in &candidates {
                if let Some(file_path) =
                    composer::resolve_class_path(&mappings, &workspace_root, fqn)
                    && let Some(location) = self.resolve_class_in_file(&file_path, fqn)
                {
                    return Some(location);
                }
            }
        }

        // ── Template parameter fallback ─────────────────────────────────
        // If no class was found, the name might be a template parameter
        // (e.g. `TKey`, `TModel`) defined in a `@template` tag on the
        // enclosing class or method docblock.
        if let Some(tpl_def) = self.lookup_template_def(uri, name, cursor_offset) {
            let target_uri = Url::parse(uri).ok()?;
            let start_pos = crate::util::offset_to_position(content, tpl_def.name_offset as usize);
            let end_pos = crate::util::offset_to_position(
                content,
                (tpl_def.name_offset + tpl_def.name.len() as u32) as usize,
            );
            return Some(Location {
                uri: target_uri,
                range: Range {
                    start: start_pos,
                    end: end_pos,
                },
            });
        }

        None
    }

    /// Look up a template parameter definition for `name` at
    /// `cursor_offset` in the precomputed symbol map for `uri`.
    fn lookup_template_def(
        &self,
        uri: &str,
        name: &str,
        cursor_offset: u32,
    ) -> Option<crate::symbol_map::TemplateParamDef> {
        let maps = self.symbol_maps.read();
        let map = maps.get(uri)?;
        map.find_template_def(name, cursor_offset).cloned()
    }

    // ─── Constant Definition Resolution ─────────────────────────────────────

    /// Resolve a standalone constant to its `define('NAME', …)` call site.
    ///
    /// Checks `global_defines` (user-defined constants discovered from parsed
    /// files) for a matching constant name, reads the source file, and returns
    /// a `Location` pointing at the `define(` call.  When not found, checks
    /// the `autoload_constant_index` (populated by the full-scan for
    /// non-Composer projects) and lazily parses the defining file via
    /// `update_ast`.  Built-in constants from `stub_constant_index` are not
    /// navigable (they have no real file).
    fn resolve_constant_definition(&self, candidates: &[String]) -> Option<Location> {
        // ── Phase 1: Look up the constant in global_defines. ──
        let found = {
            let dmap = self.global_defines.read();
            let mut result = None;
            for candidate in candidates {
                if let Some(info) = dmap.get(candidate.as_str()) {
                    result = Some((info.file_uri.clone(), info.name_offset));
                    break;
                }
            }
            result
        };

        // ── Phase 1.5: Check autoload_constant_index (byte-level scan). ──
        // The lightweight `find_symbols` byte-level scan discovers
        // constant names at startup without a full AST parse, for both
        // non-Composer projects (workspace scan) and Composer projects
        // (autoload_files.php scan).  When a candidate matches, we
        // lazily call `update_ast` to get the complete `DefineInfo`
        // and re-check global_defines.
        let found = if found.is_some() {
            found
        } else {
            let idx = self.autoload_constant_index.read();
            let mut lazy_result = None;
            for candidate in candidates {
                if let Some(path) = idx.get(candidate.as_str()) {
                    let path = path.clone();
                    drop(idx);

                    if let Ok(content) = std::fs::read_to_string(&path) {
                        let uri = crate::util::path_to_uri(&path);
                        self.update_ast(&uri, &content);

                        let dmap = self.global_defines.read();
                        for retry in candidates {
                            if let Some(info) = dmap.get(retry.as_str()) {
                                lazy_result = Some((info.file_uri.clone(), info.name_offset));
                                break;
                            }
                        }
                    }
                    break;
                }
            }
            lazy_result
        };

        // ── Phase 1.75: Last-resort lazy parse of known autoload files ──
        // The byte-level scanner misses constants inside conditional
        // blocks (e.g. `if (!defined(...))` guards).  As a safety net,
        // lazily parse each known autoload file via `update_ast` until
        // the constant is found.  Each file is parsed at most once:
        // subsequent lookups hit Phase 1 (`global_defines`).
        let found = if found.is_some() {
            found
        } else {
            let paths = self.autoload_file_paths.read().clone();
            let mut lazy_result = None;
            for path in &paths {
                let uri = crate::util::path_to_uri(path);
                if self.ast_map.read().contains_key(&uri) {
                    continue;
                }

                if let Ok(content) = std::fs::read_to_string(path) {
                    self.update_ast(&uri, &content);

                    let dmap = self.global_defines.read();
                    for candidate in candidates {
                        if let Some(info) = dmap.get(candidate.as_str()) {
                            lazy_result = Some((info.file_uri.clone(), info.name_offset));
                            break;
                        }
                    }
                    if lazy_result.is_some() {
                        break;
                    }
                }
            }
            lazy_result
        };

        let (file_uri, name_offset) = found?;

        // Read the file content (try open files first, then disk).
        let file_content = self.get_file_content(&file_uri)?;

        // Use the stored byte offset.  An offset of 0 means "not
        // available" — return None in that case (should not happen for
        // constants discovered via `update_ast` since the parser always
        // sets the offset).
        if name_offset == 0 {
            return None;
        }
        let position = crate::util::offset_to_position(&file_content, name_offset as usize);
        let parsed_uri = Url::parse(&file_uri).ok()?;

        Some(point_location(parsed_uri, position))
    }

    // ─── Function Definition Resolution ─────────────────────────────────────

    /// Try to resolve a standalone function name to its definition.
    ///
    /// Searches the `global_functions` map (populated from autoload files,
    /// opened/changed files, and cached stub functions) for any of the
    /// given candidate names.  If not found there, falls back to the
    /// embedded PHP stubs via `find_or_load_function` — which parses the
    /// stub lazily and caches it in `global_functions` for future lookups.
    ///
    /// When found, reads the source file and locates the `function name(`
    /// declaration line.  Stub functions (with `phpantom-stub-fn://` URIs)
    /// are not navigable so they are skipped for go-to-definition but
    /// still loaded into the cache for return-type resolution.
    fn resolve_function_definition(&self, candidates: &[String]) -> Option<Location> {
        // ── Step 1: Check global_functions (user code + cached stubs) ──
        let found = {
            let fmap = self.global_functions.read();
            let mut result = None;
            for candidate in candidates {
                if let Some((uri, info)) = fmap.get(candidate.as_str()) {
                    result = Some((uri.clone(), info.clone()));
                    break;
                }
            }
            result
        };

        // ── Step 2: Try embedded PHP stubs as fallback ──
        let (file_uri, func_info) = if let Some(pair) = found {
            pair
        } else {
            // Build &str candidates for find_or_load_function.
            let str_candidates: Vec<&str> = candidates.iter().map(|s| s.as_str()).collect();
            let loaded = self.find_or_load_function(&str_candidates)?;

            // After find_or_load_function, the function is cached in
            // global_functions.  Look it up to get the URI.
            let fmap = self.global_functions.read();
            let mut result = None;
            for candidate in candidates {
                if let Some((uri, info)) = fmap.get(candidate.as_str()) {
                    result = Some((uri.clone(), info.clone()));
                    break;
                }
            }
            result.unwrap_or_else(|| {
                // Fallback: use a synthetic URI with the loaded info.
                (format!("phpantom-stub-fn://{}", loaded.name), loaded)
            })
        };

        // Stub functions don't have real file locations — skip
        // go-to-definition for them (they're still useful for return-type
        // resolution via the function_loader).
        if file_uri.starts_with("phpantom-stub-fn://") {
            return None;
        }

        // Read the file content (try open files first, then disk).
        let file_content = self.get_file_content(&file_uri)?;

        // Use the stored byte offset.  A name_offset of 0 means "not
        // available" — return None in that case (should not happen for
        // user code since the parser always sets the offset).
        if func_info.name_offset == 0 {
            return None;
        }
        let position =
            crate::util::offset_to_position(&file_content, func_info.name_offset as usize);
        let parsed_uri = Url::parse(&file_uri).ok()?;

        Some(point_location(parsed_uri, position))
    }

    // ─── Word Extraction & FQN Resolution ───────────────────────────────────

    /// Resolve a short or partially-qualified name to a fully-qualified name
    /// using the file's `use` map and namespace context.
    ///
    /// This is a thin wrapper around [`crate::util::resolve_to_fqn`] kept
    /// for API compatibility with callers that use `Self::resolve_to_fqn`.
    pub fn resolve_to_fqn(
        name: &str,
        use_map: &HashMap<String, String>,
        namespace: &Option<String>,
    ) -> String {
        crate::util::resolve_to_fqn(name, use_map, namespace)
    }

    /// Resolve a class definition in a file on disk.
    ///
    /// This is the cross-file counterpart of [`find_definition_in_ast_map`].
    /// It ensures the target file is parsed and cached in `ast_map`, then
    /// uses the stored `keyword_offset` to produce a precise `Location`
    /// without text searching.
    pub(super) fn resolve_class_in_file(
        &self,
        file_path: &std::path::Path,
        fqn: &str,
    ) -> Option<Location> {
        let target_uri_string = crate::util::path_to_uri(file_path);

        // Ensure the file is parsed and cached.  If the file is already in
        // `ast_map` (opened via `did_open`, loaded from autoload files, or
        // parsed in a previous cross-file jump), `parse_and_cache_file`
        // will re-parse it — but the cost is negligible compared to the
        // disk I/O we'd do anyway.  A future optimisation can skip the
        // re-parse when an `ast_map` entry already exists.
        let already_cached = self.ast_map.read().contains_key(&target_uri_string);

        if !already_cached {
            self.parse_and_cache_file(file_path);
        }

        // Use AST-based lookup (keyword_offset).
        self.find_definition_in_ast_map_cross_file(fqn, &target_uri_string)
    }

    /// Like [`find_definition_in_ast_map`] but for cross-file jumps where
    /// we know the target file's URI (not the current file).
    ///
    /// Reads the file content and class list from the caches, finds the
    /// matching `ClassInfo`, and returns a `Location` using the stored
    /// `keyword_offset`.
    fn find_definition_in_ast_map_cross_file(
        &self,
        fqn: &str,
        target_uri: &str,
    ) -> Option<Location> {
        let sn = short_name(fqn);

        let classes = self.ast_map.read().get(target_uri).cloned()?;

        // Match by short name + namespace, same logic as
        // `find_definition_in_ast_map`.
        let class_info = classes.iter().find(|c| {
            if c.name != sn {
                return false;
            }
            c.fqn() == fqn
        })?;

        let content = self.get_file_content(target_uri)?;
        let parsed_uri = Url::parse(target_uri).ok()?;

        if class_info.keyword_offset == 0 {
            return None;
        }
        let position =
            crate::util::offset_to_position(&content, class_info.keyword_offset as usize);

        Some(point_location(parsed_uri, position))
    }

    /// Try to find the definition of a class in the current file by checking
    /// the ast_map.
    pub(super) fn find_definition_in_ast_map(
        &self,
        fqn: &str,
        content: &str,
        uri: &str,
    ) -> Option<Location> {
        let short_name = short_name(fqn);

        let classes = self.ast_map.read().get(uri).cloned()?;

        let class_info = classes.iter().find(|c| {
            if c.name != short_name {
                return false;
            }
            // Build the FQN of this class in the current file and compare
            // against the requested FQN to avoid false matches when two
            // namespaces contain classes with the same short name.
            let file_namespace = self.namespace_map.read().get(uri).cloned().flatten();
            let class_fqn = match &file_namespace {
                Some(ns) => format!("{}\\{}", ns, c.name),
                None => c.name.clone(),
            };
            class_fqn == fqn
        })?;

        if class_info.keyword_offset == 0 {
            return None;
        }
        let position = crate::util::offset_to_position(content, class_info.keyword_offset as usize);

        // Build a file URI from the current URI string.
        let parsed_uri = Url::parse(uri).ok()?;

        Some(point_location(parsed_uri, position))
    }

    /// Find the position (line, character) of a class / interface / trait / enum
    /// declaration inside the given file content.
    ///
    /// Searches for patterns like:
    ///   `class ClassName`
    ///   `interface ClassName`
    ///   `trait ClassName`
    ///   `enum ClassName`
    ///   `abstract class ClassName`
    ///   `final class ClassName`
    ///   `readonly class ClassName`
    ///
    /// Returns the position of the keyword (`class`, `interface`, etc.) on
    /// the matching line.
    /// Resolve `self`, `static`, or `parent` keywords to a class definition.
    ///
    /// - `self` / `static` → jump to the enclosing class declaration.
    /// - `parent` → jump to the parent class declaration (from `extends`).
    fn resolve_self_static_parent(
        &self,
        uri: &str,
        content: &str,
        position: Position,
        ssp_kind: SelfStaticParentKind,
    ) -> Option<Location> {
        let cursor_offset = position_to_offset(content, position);

        let classes: Vec<std::sync::Arc<ClassInfo>> =
            self.ast_map.read().get(uri).cloned().unwrap_or_default();

        let current_class = find_class_at_offset(&classes, cursor_offset)?;

        if matches!(
            ssp_kind,
            SelfStaticParentKind::Self_ | SelfStaticParentKind::Static | SelfStaticParentKind::This
        ) {
            // Jump to the enclosing class definition in the current file.
            if current_class.keyword_offset == 0 {
                return None;
            }
            let target_position =
                crate::util::offset_to_position(content, current_class.keyword_offset as usize);
            let parsed_uri = Url::parse(uri).ok()?;
            return Some(point_location(parsed_uri, target_position));
        }

        // SelfStaticParentKind::Parent
        let parent_name = current_class.parent_class.as_ref()?;

        // Try to find the parent class in the current file first.
        // Use keyword_offset when available (the parent class is in the
        // same file's ast_map entry).
        let parent_in_file = classes.iter().find(|c| c.name == *parent_name);
        let parent_pos = parent_in_file
            .filter(|pc| pc.keyword_offset > 0)
            .map(|pc| crate::util::offset_to_position(content, pc.keyword_offset as usize));
        if let Some(pos) = parent_pos {
            let parsed_uri = Url::parse(uri).ok()?;
            return Some(point_location(parsed_uri, pos));
        }

        // Resolve the parent class name to a FQN using use-map / namespace.
        let ctx = self.file_context(uri);

        let fqn = ctx.resolve_name_at(parent_name, cursor_offset);

        // Try class_index / ast_map lookup via find_class_file_content.
        if let Some((class_uri, class_content)) = self.find_class_file_content(&fqn, uri, content) {
            // Use keyword_offset from the ast_map entry for the cross-file class.
            let cross_class = self.find_class_in_ast_map(&fqn);
            if let Some(ref cc) = cross_class
                && cc.keyword_offset > 0
                && let Ok(parsed_uri) = Url::parse(&class_uri)
            {
                let pos =
                    crate::util::offset_to_position(&class_content, cc.keyword_offset as usize);
                return Some(point_location(parsed_uri, pos));
            }
        }

        // Try Composer classmap: direct FQN → file path lookup.
        {
            let candidates = [fqn.as_str(), parent_name.as_str()];
            for candidate in &candidates {
                if let Some(file_path) = self.classmap.read().get(*candidate).cloned()
                    && let Some(location) = self.resolve_class_in_file(&file_path, candidate)
                {
                    return Some(location);
                }
            }
        }

        // Try PSR-4 resolution as a last resort.
        // PSR-4 mappings only cover user code (from composer.json).
        // Vendor classes are resolved by the classmap above.
        let workspace_root = self.workspace_root.read().clone();

        if let Some(workspace_root) = workspace_root {
            let mappings = self.psr4_mappings.read();
            let candidates = [fqn.as_str(), parent_name.as_str()];
            for candidate in &candidates {
                if let Some(file_path) =
                    composer::resolve_class_path(&mappings, &workspace_root, candidate)
                    && let Some(location) = self.resolve_class_in_file(&file_path, candidate)
                {
                    return Some(location);
                }
            }
        }

        None
    }
}