1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
use std::collections::HashSet;
use std::path::PathBuf;
/// Go-to-implementation support (`textDocument/implementation`).
///
/// When the cursor is on an interface name, abstract class name, or any
/// non-final class name, this module finds all concrete implementations
/// (and, for concrete class targets, all subclasses including abstract
/// ones) and returns their locations. The same applies to method calls
/// where the owning type is an interface or abstract class.
///
/// When the cursor is on a method *definition* inside a concrete class, the
/// reverse direction is also supported: the handler finds the interface or
/// abstract class that declares the method and jumps to it.
///
/// Final classes cannot be extended, so go-to-implementation is a no-op
/// for them.
///
/// # Resolution strategy
///
/// 1. **Determine the target symbol** — consult the precomputed `SymbolMap`
/// for the word under the cursor.
/// 2. **Identify the target type** — resolve the symbol to a `ClassInfo` and
/// check whether it is a non-final class or interface.
/// 3. **Scan for implementors** — walk all classes known to the server
/// (`ast_map`, `class_index`, `classmap`, PSR-4 directories) and collect
/// those whose `interfaces` list or `parent_class` matches the target type.
/// 4. **Return locations** — for class-level requests, return the class
/// declaration position; for method-level requests, return the method
/// position in each implementing class.
/// 5. **Reverse jump** — for `MemberDeclaration` symbols on a concrete class,
/// walk the class's interfaces and parent abstract classes to find the
/// prototype method declaration and return its location.
use std::sync::Arc;
use tower_lsp::lsp_types::*;
use super::member::MemberKind;
use super::point_location;
use crate::Backend;
use crate::completion::resolver::ResolutionCtx;
use crate::symbol_map::{SelfStaticParentKind, SymbolKind};
use crate::types::{ClassInfo, ClassLikeKind, FileContext, MAX_INHERITANCE_DEPTH, ResolvedType};
use crate::util::{collect_php_files, find_class_at_offset, position_to_offset, short_name};
impl Backend {
/// Entry point for `textDocument/implementation`.
///
/// Returns a list of locations where the symbol under the cursor is
/// concretely implemented. Returns `None` if the cursor is not on a
/// resolvable interface/abstract symbol.
pub(crate) fn resolve_implementation(
&self,
uri: &str,
content: &str,
position: Position,
) -> Option<Vec<Location>> {
// ── 1. Extract the word under the cursor ────────────────────────
// Primary path: consult the precomputed symbol map.
let symbol = self.lookup_symbol_at_position(uri, content, position);
if let Some(ref sym) = symbol {
match &sym.kind {
// Member access — delegate directly to member implementation
// resolution using the structured symbol information.
SymbolKind::MemberAccess { member_name, .. } => {
let ctx = self.file_context(uri);
return self.resolve_member_implementations(
uri,
content,
position,
member_name.as_str(),
&ctx,
);
}
// Class reference or declaration — resolve as a class/interface name.
SymbolKind::ClassReference { name, .. } | SymbolKind::ClassDeclaration { name } => {
let ctx = self.file_context(uri);
return self.resolve_class_implementation(uri, content, name, &ctx, sym.start);
}
// self/static/parent — resolve the keyword to the current
// class and check whether it is an interface/abstract.
SymbolKind::SelfStaticParent(ssp_kind) => {
let ctx = self.file_context(uri);
let class_loader = self.class_loader(&ctx);
let current_class = find_class_at_offset(&ctx.classes, sym.start);
let target = match ssp_kind {
SelfStaticParentKind::Parent => current_class
.and_then(|cc| cc.parent_class.as_ref())
.and_then(|p| class_loader(p).map(Arc::unwrap_or_clone)),
_ => current_class.cloned(),
};
if let Some(ref t) = target {
return self
.resolve_class_implementation(uri, content, &t.name, &ctx, sym.start);
}
return None;
}
// Member declaration — reverse jump: from a concrete method
// definition to the interface/abstract method it implements.
SymbolKind::MemberDeclaration { name, .. } => {
let ctx = self.file_context(uri);
let class_loader = self.class_loader(&ctx);
let current_class = find_class_at_offset(&ctx.classes, sym.start);
if let Some(cls) = current_class {
return self.resolve_reverse_implementation(
uri,
content,
cls,
name,
&class_loader,
);
}
return None;
}
// Other symbol kinds (variables, function calls, etc.)
// are not meaningful for go-to-implementation.
_ => return None,
}
}
// No symbol map span covers the cursor — nothing to resolve.
None
}
/// Resolve go-to-implementation for a class/interface name.
///
/// Resolves `name` to a fully-qualified class, checks that it is an
/// interface or abstract class (or a non-final concrete class that
/// may have subclasses), finds all implementors/subclasses, and
/// returns their declaration locations.
fn resolve_class_implementation(
&self,
uri: &str,
content: &str,
name: &str,
ctx: &FileContext,
name_offset: u32,
) -> Option<Vec<Location>> {
let class_loader = self.class_loader(ctx);
let fqn = ctx.resolve_name_at(name, name_offset);
let target = class_loader(&fqn)
.or_else(|| class_loader(name))
.map(Arc::unwrap_or_clone)?;
// Final classes cannot be extended, so there are no implementations.
if target.is_final {
return None;
}
// Whether the target is a concrete (non-abstract, non-interface)
// class. When it is, we include abstract subclasses in the
// results because the user is exploring the class hierarchy
// rather than looking for instantiable implementations.
let target_is_concrete = target.kind != ClassLikeKind::Interface && !target.is_abstract;
let target_short = target.name.clone();
// Compute target FQN from the class's own namespace (most
// reliable), then fall back to class_index, then to the FQN we
// resolved from the use-map, and finally to the short name.
let target_fqn = {
let from_class = crate::util::build_fqn(&target.name, &target.file_namespace);
if from_class.contains('\\') {
from_class
} else {
self.class_fqn_for_short(&target_short).unwrap_or_else(|| {
if fqn.contains('\\') {
fqn.clone()
} else {
target_short.clone()
}
})
}
};
let implementors = self.find_implementors(
&target_short,
&target_fqn,
&class_loader,
target_is_concrete,
false,
);
if implementors.is_empty() {
return None;
}
let mut locations = Vec::new();
for imp in &implementors {
if let Some(loc) = self.locate_class_declaration(imp, uri, content) {
locations.push(loc);
}
}
if locations.is_empty() {
None
} else {
Some(locations)
}
}
/// Reverse jump: from a method definition in a concrete class to the
/// interface or abstract class that declares the prototype.
///
/// When the cursor is on a method name at its definition site (e.g.
/// `public function handle()` in a class that implements `Handler`),
/// this finds the interface/abstract method declaration and returns
/// its location.
fn resolve_reverse_implementation(
&self,
uri: &str,
content: &str,
current_class: &ClassInfo,
member_name: &str,
class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
) -> Option<Vec<Location>> {
// For interfaces and abstract classes, the forward direction
// applies: find concrete implementors that define the method.
if current_class.kind == ClassLikeKind::Interface || current_class.is_abstract {
return self.resolve_interface_member_implementations(
uri,
content,
current_class,
member_name,
class_loader,
);
}
let mut locations = Vec::new();
// Check implemented interfaces for a method with the same name.
let all_ifaces = self.collect_all_interfaces(current_class, class_loader);
for iface_name in &all_ifaces {
if let Some(iface) = class_loader(iface_name) {
let has_member = iface.methods.iter().any(|m| m.name == member_name)
|| iface.properties.iter().any(|p| p.name == member_name);
if has_member {
let member_kind = if iface.methods.iter().any(|m| m.name == member_name) {
MemberKind::Method
} else {
MemberKind::Property
};
if let Some((class_uri, class_content)) =
self.find_class_file_content(iface_name, uri, content)
&& let Some(member_pos) = Self::find_member_position_in_class(
&class_content,
member_name,
member_kind,
&iface,
)
&& let Ok(parsed_uri) = Url::parse(&class_uri)
{
let loc = point_location(parsed_uri, member_pos);
if !locations.contains(&loc) {
locations.push(loc);
}
}
}
}
}
// Check parent abstract classes for an abstract method with the
// same name.
let mut current = current_class.parent_class.clone();
let mut depth = 0u32;
while let Some(ref parent_name) = current {
if depth >= MAX_INHERITANCE_DEPTH {
break;
}
depth += 1;
if let Some(parent_cls) = class_loader(parent_name) {
// Only consider abstract methods on abstract parents.
if parent_cls.is_abstract || parent_cls.kind == ClassLikeKind::Interface {
let has_method = parent_cls.methods.iter().any(|m| m.name == member_name);
if has_method
&& let Some((class_uri, class_content)) =
self.find_class_file_content(parent_name, uri, content)
&& let Some(member_pos) = Self::find_member_position_in_class(
&class_content,
member_name,
MemberKind::Method,
&parent_cls,
)
&& let Ok(parsed_uri) = Url::parse(&class_uri)
{
let loc = point_location(parsed_uri, member_pos);
if !locations.contains(&loc) {
locations.push(loc);
}
}
}
current = parent_cls.parent_class.clone();
} else {
break;
}
}
if locations.is_empty() {
None
} else {
Some(locations)
}
}
/// Collect all interface names from a class and its parent chain.
///
/// Walks the class's `interfaces` list and its parent class chain,
/// collecting all interface names (including those inherited from
/// parents). Also walks interface-extends chains transitively.
fn collect_all_interfaces(
&self,
cls: &ClassInfo,
class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
) -> Vec<String> {
let mut result = Vec::new();
let mut seen = HashSet::new();
// Direct interfaces.
for iface in &cls.interfaces {
if seen.insert(iface.clone()) {
result.push(iface.clone());
// Also collect interfaces that this interface extends.
self.collect_parent_interfaces(iface, class_loader, &mut result, &mut seen);
}
}
// Interfaces from parent classes.
let mut current = cls.parent_class.clone();
let mut depth = 0u32;
while let Some(ref parent_name) = current {
if depth >= MAX_INHERITANCE_DEPTH {
break;
}
depth += 1;
if let Some(parent_cls) = class_loader(parent_name) {
for iface in &parent_cls.interfaces {
if seen.insert(iface.clone()) {
result.push(iface.clone());
self.collect_parent_interfaces(iface, class_loader, &mut result, &mut seen);
}
}
current = parent_cls.parent_class.clone();
} else {
break;
}
}
result
}
/// Recursively collect interfaces that an interface extends.
fn collect_parent_interfaces(
&self,
iface_name: &str,
class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
result: &mut Vec<String>,
seen: &mut HashSet<String>,
) {
let Some(iface) = class_loader(iface_name) else {
return;
};
// Check parent_class (first extended interface).
if let Some(ref parent) = iface.parent_class
&& seen.insert(parent.clone())
{
result.push(parent.clone());
self.collect_parent_interfaces(parent, class_loader, result, seen);
}
// Check interfaces list (multi-extends).
for parent_iface in &iface.interfaces {
if seen.insert(parent_iface.clone()) {
result.push(parent_iface.clone());
self.collect_parent_interfaces(parent_iface, class_loader, result, seen);
}
}
}
/// Resolve implementations of a method on an interface/abstract class
/// when invoked from the interface declaration itself (reverse jump
/// from an interface method to concrete implementations).
fn resolve_interface_member_implementations(
&self,
uri: &str,
content: &str,
interface_class: &ClassInfo,
member_name: &str,
class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
) -> Option<Vec<Location>> {
let target_short = interface_class.name.clone();
let target_fqn = self
.class_fqn_for_short(&target_short)
.unwrap_or(target_short.clone());
let implementors =
self.find_implementors(&target_short, &target_fqn, class_loader, false, false);
let member_kind = if interface_class
.methods
.iter()
.any(|m| m.name == member_name)
{
MemberKind::Method
} else if interface_class
.properties
.iter()
.any(|p| p.name == member_name)
{
MemberKind::Property
} else {
MemberKind::Constant
};
let mut locations = Vec::new();
for imp in &implementors {
// Check that the implementor owns (not inherits) this member.
let owns_member = match member_kind {
MemberKind::Method => imp.methods.iter().any(|m| m.name == member_name),
MemberKind::Property => imp.properties.iter().any(|p| p.name == member_name),
MemberKind::Constant => imp.constants.iter().any(|c| c.name == member_name),
};
if !owns_member {
continue;
}
if let Some((class_uri, class_content)) =
self.find_class_file_content(&imp.name, uri, content)
&& let Some(member_pos) = Self::find_member_position_in_class(
&class_content,
member_name,
member_kind,
imp,
)
&& let Ok(parsed_uri) = Url::parse(&class_uri)
{
let loc = point_location(parsed_uri, member_pos);
if !locations.contains(&loc) {
locations.push(loc);
}
}
}
if locations.is_empty() {
None
} else {
Some(locations)
}
}
/// Resolve implementations of a method call on an interface/abstract class.
fn resolve_member_implementations(
&self,
uri: &str,
content: &str,
position: Position,
member_name: &str,
ctx: &FileContext,
) -> Option<Vec<Location>> {
// Extract the subject (left side of -> or ::).
let (subject, access_kind) = self.lookup_member_access_context(uri, content, position)?;
let cursor_offset = position_to_offset(content, position);
let current_class = find_class_at_offset(&ctx.classes, cursor_offset);
let class_loader = self.class_loader(ctx);
let function_loader = self.function_loader(ctx);
// Resolve the subject to candidate classes.
let rctx = ResolutionCtx {
current_class,
all_classes: &ctx.classes,
content,
cursor_offset,
class_loader: &class_loader,
resolved_class_cache: Some(&self.resolved_class_cache),
function_loader: Some(&function_loader),
};
let candidates = ResolvedType::into_arced_classes(
crate::completion::resolver::resolve_target_classes(&subject, access_kind, &rctx),
);
if candidates.is_empty() {
return None;
}
// Check if ANY candidate is an interface or abstract class with this
// method. If so, find all implementors that have the method.
let mut all_locations = Vec::new();
for candidate in &candidates {
if candidate.kind != ClassLikeKind::Interface && !candidate.is_abstract {
continue;
}
// Verify the method exists on this interface/abstract class
// (directly or inherited).
let merged = crate::virtual_members::resolve_class_fully_cached(
candidate,
&class_loader,
&self.resolved_class_cache,
);
let has_method = merged.methods.iter().any(|m| m.name == member_name);
let has_property = merged.properties.iter().any(|p| p.name == member_name);
if !has_method && !has_property {
continue;
}
let member_kind = if has_method {
MemberKind::Method
} else {
MemberKind::Property
};
let target_short = candidate.name.clone();
let target_fqn = self
.class_fqn_for_short(&target_short)
.unwrap_or(target_short.clone());
let implementors =
self.find_implementors(&target_short, &target_fqn, &class_loader, false, false);
for imp in &implementors {
// Check that the implementor actually has this member.
let imp_merged = crate::virtual_members::resolve_class_fully_cached(
imp,
&class_loader,
&self.resolved_class_cache,
);
let imp_has = match member_kind {
MemberKind::Method => imp_merged.methods.iter().any(|m| m.name == member_name),
MemberKind::Property => {
imp_merged.properties.iter().any(|p| p.name == member_name)
}
MemberKind::Constant => {
imp_merged.constants.iter().any(|c| c.name == member_name)
}
};
if !imp_has {
continue;
}
// Find the member position in the implementor's file.
// We want the member defined directly on this class (not
// inherited), so check the un-merged class first.
let owns_member = match member_kind {
MemberKind::Method => imp.methods.iter().any(|m| m.name == member_name),
MemberKind::Property => imp.properties.iter().any(|p| p.name == member_name),
MemberKind::Constant => imp.constants.iter().any(|c| c.name == member_name),
};
if !owns_member {
// The member is inherited — the implementor doesn't
// override it, so there's no definition to jump to
// in this class.
continue;
}
if let Some((class_uri, class_content)) =
self.find_class_file_content(&imp.name, uri, content)
&& let Some(member_pos) = Self::find_member_position_in_class(
&class_content,
member_name,
member_kind,
imp,
)
&& let Ok(parsed_uri) = Url::parse(&class_uri)
{
let loc = point_location(parsed_uri, member_pos);
if !all_locations.contains(&loc) {
all_locations.push(loc);
}
}
}
}
// If no interface/abstract candidate was found, try treating the
// request as a regular "find all overrides" — useful for concrete
// base-class methods too.
if all_locations.is_empty() {
return None;
}
Some(all_locations)
}
/// Find all classes that implement or extend the target.
///
/// Scans:
/// 1. All classes already in `ast_map` (open files + autoload-discovered)
/// 2. All classes loadable via `class_index`
/// 3. Classmap files not yet loaded — string pre-filter then parse
/// 4. Embedded PHP stubs — string pre-filter then lazy parse
/// 5. User PSR-4 directories — walk for `.php` files not covered by
/// the classmap, string pre-filter then parse. Vendor PSR-4 roots
/// are skipped because vendor classes are assumed complete in the
/// classmap (Phase 3).
///
/// When `include_abstract` is `false` (the default for interface and
/// abstract-class targets), abstract subclasses are excluded from the
/// results so that only concrete implementations are returned. When
/// `true` (used for concrete-class targets), abstract subclasses are
/// included because the user is exploring the full class hierarchy.
///
/// When `direct_only` is `true`, only classes/interfaces/enums whose
/// `extends`, `implements`, or `use` clause **directly** names the
/// target are returned. Transitive relationships (e.g. a class that
/// extends another class that implements the target interface) are
/// excluded. This mode is used by the type hierarchy protocol where
/// the client walks the tree one level at a time.
pub(crate) fn find_implementors(
&self,
target_short: &str,
target_fqn: &str,
class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
include_abstract: bool,
direct_only: bool,
) -> Vec<ClassInfo> {
let mut result: Vec<ClassInfo> = Vec::new();
// Track by FQN to avoid short-name collisions across namespaces.
let mut seen_fqns: HashSet<String> = HashSet::new();
// ── Phase 1: scan ast_map ───────────────────────────────────────
// Collect all candidate classes first, then drop the lock before
// calling class_loader (which may re-lock ast_map).
let ast_candidates: Vec<ClassInfo> = {
let map = self.ast_map.read();
map.values()
.flat_map(|classes| classes.iter().map(|c| ClassInfo::clone(c)))
.collect()
};
for cls in &ast_candidates {
let cls_fqn = crate::util::build_fqn(&cls.name, &cls.file_namespace);
if self.class_implements_or_extends(
cls,
target_short,
target_fqn,
class_loader,
include_abstract,
direct_only,
) && seen_fqns.insert(cls_fqn)
{
result.push(cls.clone());
}
}
// ── Phase 2: scan class_index for classes not yet in ast_map ────
let index_entries: Vec<(String, String)> = {
let idx = self.class_index.read();
idx.iter()
.map(|(fqn, uri)| (fqn.clone(), uri.clone()))
.collect()
};
for (fqn, _uri) in &index_entries {
if seen_fqns.contains(fqn) {
continue;
}
if let Some(cls) = class_loader(fqn)
&& self.class_implements_or_extends(
&cls,
target_short,
target_fqn,
class_loader,
include_abstract,
direct_only,
)
{
let cls_fqn = crate::util::build_fqn(&cls.name, &cls.file_namespace);
if seen_fqns.insert(cls_fqn) {
result.push(Arc::unwrap_or_clone(cls));
}
}
}
// ── Phase 3: scan classmap files with string pre-filter ─────────
// Collect unique file paths from the classmap (one file may define
// multiple classes, so we de-duplicate by path and scan each file
// at most once). Files already present in ast_map were covered by
// Phase 1 and can be skipped.
let classmap_paths: HashSet<PathBuf> = self.classmap.read().values().cloned().collect();
let loaded_uris: HashSet<String> = self.ast_map.read().keys().cloned().collect();
for path in &classmap_paths {
let uri = crate::util::path_to_uri(path);
if loaded_uris.contains(&uri) {
continue;
}
// Cheap pre-filter: read the raw file and skip it if the
// source doesn't mention the target name at all.
let raw = match std::fs::read_to_string(path) {
Ok(r) => r,
Err(_) => continue,
};
if !raw.contains(target_short) {
continue;
}
// Parse the file, cache it, and check every class it defines.
if let Some(classes) = self.parse_and_cache_file(path) {
for cls in &classes {
let cls_fqn = crate::util::build_fqn(&cls.name, &cls.file_namespace);
if seen_fqns.contains(&cls_fqn) {
continue;
}
if self.class_implements_or_extends(
cls,
target_short,
target_fqn,
class_loader,
include_abstract,
direct_only,
) {
seen_fqns.insert(cls_fqn);
result.push(ClassInfo::clone(cls));
}
}
}
}
// ── Phase 4: scan embedded stubs with string pre-filter ─────────
// Stubs are static strings baked into the binary. A cheap text
// search for the target name narrows candidates before we parse.
// Parsing is lazy and cached in ast_map, so subsequent lookups
// hit Phase 1.
let stub_idx = self.stub_index.read();
for (&stub_name, &stub_source) in &*stub_idx {
if seen_fqns.contains(stub_name) {
continue;
}
// Cheap pre-filter: skip stubs whose source doesn't mention
// the target name at all.
if !stub_source.contains(target_short) {
continue;
}
if let Some(cls) = class_loader(stub_name)
&& self.class_implements_or_extends(
&cls,
target_short,
target_fqn,
class_loader,
include_abstract,
direct_only,
)
{
let cls_fqn = crate::util::build_fqn(&cls.name, &cls.file_namespace);
if seen_fqns.insert(cls_fqn) {
result.push(Arc::unwrap_or_clone(cls));
}
}
}
// ── Phase 5: scan user PSR-4 directories for files not in classmap ──
// The user may have created classes that are not yet in the
// classmap. Walk user PSR-4 roots only — vendor classes are
// assumed complete in the classmap (Phase 3) and should not
// require a filesystem walk.
let workspace_root = self.workspace_root.read().clone();
if let Some(workspace_root) = workspace_root {
// The vendor dir paths are needed by collect_php_files even
// though we only walk user PSR-4 roots. A fallback mapping
// like `"" => "."` resolves to the workspace root, so the
// walk must still skip vendor directories (and hidden
// directories like .git).
let vendor_dir_paths = self.vendor_dir_paths.lock().clone();
let psr4_dirs: Vec<PathBuf> = {
let mappings = self.psr4_mappings.read();
mappings
.iter()
.map(|m| workspace_root.join(&m.base_path))
.filter(|p| p.is_dir())
.collect()
};
// Refresh loaded URIs — Phase 3 may have added entries.
let loaded_uris_p5: HashSet<String> = self.ast_map.read().keys().cloned().collect();
for dir in &psr4_dirs {
for php_file in collect_php_files(dir, &vendor_dir_paths) {
// Skip files already covered by the classmap (Phase 3).
if classmap_paths.contains(&php_file) {
continue;
}
let uri = crate::util::path_to_uri(&php_file);
if loaded_uris_p5.contains(&uri) {
continue;
}
let raw = match std::fs::read_to_string(&php_file) {
Ok(r) => r,
Err(_) => continue,
};
if !raw.contains(target_short) {
continue;
}
if let Some(classes) = self.parse_and_cache_file(&php_file) {
for cls in &classes {
let cls_fqn = crate::util::build_fqn(&cls.name, &cls.file_namespace);
if seen_fqns.contains(&cls_fqn) {
continue;
}
if self.class_implements_or_extends(
cls,
target_short,
target_fqn,
class_loader,
include_abstract,
direct_only,
) {
seen_fqns.insert(cls_fqn);
result.push(ClassInfo::clone(cls));
}
}
}
}
}
}
result
}
/// Check whether `cls` implements the target interface or extends the
/// target class (directly or transitively through its parent chain).
///
/// Comparisons use fully-qualified names to avoid false positives when
/// two interfaces in different namespaces share the same short name.
///
/// When `include_abstract` is `false`, abstract classes and interfaces
/// are skipped (only concrete implementations are returned). When
/// `true`, abstract subclasses are included in the results.
fn class_implements_or_extends(
&self,
cls: &ClassInfo,
target_short: &str,
target_fqn: &str,
class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
include_abstract: bool,
direct_only: bool,
) -> bool {
// Build the FQN of the candidate class for comparison.
let cls_fqn = crate::util::build_fqn(&cls.name, &cls.file_namespace);
// Skip the target class itself.
if cls_fqn == target_fqn || cls.name == target_short {
return false;
}
// In direct_only mode (type hierarchy), interfaces that extend
// the target are valid subtypes, and traits that use the target
// are too. In normal mode (go-to-implementation), interfaces
// are never implementations.
if !direct_only {
if cls.kind == ClassLikeKind::Interface {
return false;
}
if cls.is_abstract && !include_abstract {
return false;
}
}
// Whether the target has a known FQN (contains a namespace
// separator). When it does, short-name comparison is skipped
// to avoid false positives between identically-named classes in
// different namespaces (e.g. App\Logger vs Vendor\Logger).
let has_fqn = target_fqn.contains('\\');
// Direct `implements` match (interfaces are FQN after resolution).
for iface in &cls.interfaces {
if iface == target_fqn || (!has_fqn && short_name(iface) == target_short) {
return true;
}
}
// Direct `extends` match (for abstract class implementations).
if let Some(ref parent) = cls.parent_class
&& (parent == target_fqn || (!has_fqn && short_name(parent) == target_short))
{
return true;
}
// In direct_only mode we only care about the immediate
// extends/implements/use clauses checked above.
if direct_only {
return false;
}
// ── Transitive check: walk the interface-extends chains ─────────
// If ClassC implements InterfaceB, and InterfaceB extends
// InterfaceA, a go-to-implementation on InterfaceA should find
// ClassC. Load each directly-implemented interface and
// recursively check whether it extends the target.
for iface in &cls.interfaces {
if Self::interface_extends_target(iface, target_short, target_fqn, class_loader, 0) {
return true;
}
}
// ── Transitive check: walk the parent class chain ───────────────
// A class might extend another class that implements the target
// interface. Walk up to a bounded depth to find it.
let mut current = cls.parent_class.clone();
let mut depth = 0u32;
while let Some(ref parent_name) = current {
if depth >= MAX_INHERITANCE_DEPTH {
break;
}
depth += 1;
if let Some(parent_cls) = class_loader(parent_name) {
// Check if the parent implements the target interface.
for iface in &parent_cls.interfaces {
if iface == target_fqn || (!has_fqn && short_name(iface) == target_short) {
return true;
}
// Also walk the interface's own extends chain.
if Self::interface_extends_target(
iface,
target_short,
target_fqn,
class_loader,
0,
) {
return true;
}
}
// Check if the parent IS the target (for abstract class chains).
let parent_fqn =
crate::util::build_fqn(&parent_cls.name, &parent_cls.file_namespace);
if parent_fqn == target_fqn {
return true;
}
current = parent_cls.parent_class.clone();
} else {
break;
}
}
false
}
/// Check whether `iface_name` transitively extends the target interface.
///
/// Loads the interface via `class_loader`, then checks its
/// `parent_class` (single-extends) and `interfaces` (multi-extends)
/// lists recursively up to [`MAX_INHERITANCE_DEPTH`].
fn interface_extends_target(
iface_name: &str,
target_short: &str,
target_fqn: &str,
class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
depth: u32,
) -> bool {
if depth >= MAX_INHERITANCE_DEPTH {
return false;
}
let Some(iface_cls) = class_loader(iface_name) else {
return false;
};
// Check `parent_class` (first extended interface stored here for
// backward compatibility).
if let Some(ref parent) = iface_cls.parent_class {
let parent_short = short_name(parent);
if parent_short == target_short || parent == target_fqn {
return true;
}
if Self::interface_extends_target(
parent,
target_short,
target_fqn,
class_loader,
depth + 1,
) {
return true;
}
}
// Check all entries in `interfaces` (covers multi-extends for
// interfaces that extend more than one parent).
for parent_iface in &iface_cls.interfaces {
let parent_short = short_name(parent_iface);
if parent_short == target_short || parent_iface == target_fqn {
return true;
}
if Self::interface_extends_target(
parent_iface,
target_short,
target_fqn,
class_loader,
depth + 1,
) {
return true;
}
}
false
}
/// Find a member position scoped to a specific class body.
///
/// When multiple classes in the same file define a method with the same
/// name, [`find_member_position`](Self::find_member_position) would
/// always return the first match. This variant restricts the search
/// to lines that fall within the class's `start_offset..end_offset`
/// byte range so that each implementing class resolves to its own
/// definition.
fn find_member_position_in_class(
content: &str,
member_name: &str,
kind: MemberKind,
cls: &ClassInfo,
) -> Option<Position> {
// Fast path: use stored AST offset when available.
let name_offset = cls.member_name_offset(member_name, kind.as_str());
if name_offset.is_some() {
return Self::find_member_position(content, member_name, kind, name_offset);
}
// Convert byte offsets to line numbers.
let start_line = content
.get(..cls.start_offset as usize)
.map(|s| s.matches('\n').count())
.unwrap_or(0);
let end_line = content
.get(..cls.end_offset as usize)
.map(|s| s.matches('\n').count())
.unwrap_or(usize::MAX);
// Build a sub-content containing only the class body lines and
// delegate to the existing searcher, adjusting the result line.
let class_lines: Vec<&str> = content
.lines()
.skip(start_line)
.take(end_line - start_line + 1)
.collect();
let class_body = class_lines.join("\n");
Self::find_member_position(&class_body, member_name, kind, None).map(|pos| Position {
line: pos.line + start_line as u32,
character: pos.character,
})
}
/// Get the FQN for a class given its short name, by looking it up in
/// the `class_index`.
fn class_fqn_for_short(&self, target_short: &str) -> Option<String> {
let idx = self.class_index.read();
// Look for an entry whose short name matches.
for fqn in idx.keys() {
let short = short_name(fqn);
if short == target_short {
return Some(fqn.clone());
}
}
None
}
/// Find the location of a class declaration for an implementor.
fn locate_class_declaration(
&self,
cls: &ClassInfo,
current_uri: &str,
current_content: &str,
) -> Option<Location> {
let (class_uri, class_content) =
self.find_class_file_content(&cls.name, current_uri, current_content)?;
if cls.keyword_offset == 0 {
return None;
}
let position = crate::util::offset_to_position(&class_content, cls.keyword_offset as usize);
let parsed_uri = Url::parse(&class_uri).ok()?;
Some(point_location(parsed_uri, position))
}
}