forked from PHPantom-dev/phpantom_lsp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinheritance.rs
More file actions
1581 lines (1463 loc) · 63.6 KB
/
Copy pathinheritance.rs
File metadata and controls
1581 lines (1463 loc) · 63.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::atom::{Atom, AtomSet, atom};
use std::collections::HashMap;
/// Base class inheritance resolution.
///
/// This module handles merging members from parent classes and traits
/// into a single `ClassInfo`. The resulting merged class contains the
/// base set of members visible on an instance / static access,
/// respecting PHP's precedence rules:
///
/// class own > traits > parent chain
///
/// `@mixin` members are handled separately by
/// [`PHPDocProvider`](crate::virtual_members::phpdoc::PHPDocProvider) in
/// the virtual member provider layer.
///
/// This module also supports **generic type substitution**: when a child
/// class declares `@extends Parent<ConcreteType1, ConcreteType2>` and the
/// parent has `@template T1` / `@template T2`, the inherited methods and
/// properties have their template parameter references replaced with the
/// concrete types.
use std::sync::Arc;
#[cfg(test)]
use std::borrow::Cow;
/// A borrow-or-owned handle to a `ClassInfo`, used to walk the parent
/// chain in [`resolve_class_with_inheritance`] without cloning the root
/// class.
///
/// The first iteration borrows the caller-provided `&ClassInfo` (zero
/// allocation). Subsequent iterations hold the `Arc<ClassInfo>` returned
/// by the class loader (a cheap Arc move).
pub(crate) enum ClassRef<'a> {
Borrowed(&'a ClassInfo),
Owned(Arc<ClassInfo>),
}
impl std::ops::Deref for ClassRef<'_> {
type Target = ClassInfo;
#[inline]
fn deref(&self) -> &ClassInfo {
match self {
ClassRef::Borrowed(r) => r,
ClassRef::Owned(a) => a,
}
}
}
/// Bundles the trait-level configuration passed through
/// [`merge_traits_into`] so the function stays within clippy's
/// argument-count limit.
pub(crate) struct TraitContext<'a> {
/// Generic type arguments for `@use Trait<Type>` declarations.
pub use_generics: &'a [(Atom, Vec<PhpType>)],
/// `insteadof` precedence declarations.
pub precedences: &'a [TraitPrecedence],
/// `as` alias declarations.
pub aliases: &'a [TraitAlias],
}
/// Tracks member names already present during inheritance merging.
///
/// Passed through `resolve_class_with_inheritance` and `merge_traits_into`
/// (including recursive calls) so that every addition is checked in O(1)
/// instead of scanning the full member vectors.
pub(crate) struct MergeDedup {
/// Method names already merged, lowercased (PHP method names are
/// case-insensitive, so a child `getvalue()` overrides a parent
/// `getValue()`).
pub methods: AtomSet,
/// Property names already merged.
pub properties: AtomSet,
/// Constant names already merged.
pub constants: AtomSet,
}
/// Reserve the names of `@method` tags declared in `docblock` into the
/// method dedup set.
///
/// A `@method` tag declares a method on the class that carries it. That
/// declaration overrides any method of the same name inherited from a
/// superclass, exactly like a real overriding method would. The virtual
/// members themselves are synthesized later by the PHPDoc provider; this
/// only stakes the claim so the inheritance walk stops merging the inherited
/// real method over the `@method` declaration.
fn reserve_method_tag_names(docblock: Option<&str>, dedup: &mut MergeDedup) {
let Some(doc) = docblock else {
return;
};
if !doc.contains("@method") {
return;
}
for m in crate::docblock::extract_method_tags(doc) {
dedup
.methods
.insert(crate::atom::ascii_lowercase_atom(&m.name));
}
}
impl MergeDedup {
/// Build from the members already present on a `ClassInfo`.
fn from_class(class: &ClassInfo) -> Self {
Self {
methods: class
.methods
.iter()
.map(|m| crate::atom::ascii_lowercase_atom(&m.name))
.collect(),
properties: class.properties.iter().map(|p| p.name).collect(),
constants: class.constants.iter().map(|c| c.name).collect(),
}
}
}
use crate::php_type::PhpType;
use crate::types::{
ClassInfo, MAX_INHERITANCE_DEPTH, MAX_TRAIT_DEPTH, MethodInfo, ParameterInfo, PropertyInfo,
TraitAlias, TraitPrecedence, Visibility,
};
use crate::util::short_name;
use crate::virtual_members::laravel::{
extends_eloquent_model, factory_to_model_fqn, model_to_factory_fqn,
};
// ─── Docblock Enrichment ────────────────────────────────────────────────────
/// Whether a child's effective type equals its native type, meaning no
/// docblock override was applied.
///
/// Returns `true` when the child wrote no `@return` / `@var` / `@param`
/// tag (so the effective type is just the native hint). Returns `false`
/// when the child provided its own docblock type — in that case the
/// child's type is an intentional override and should not be replaced.
fn lacks_docblock_override(effective: &Option<PhpType>, native: &Option<PhpType>) -> bool {
match (effective, native) {
// No effective type at all — nothing to override.
(None, _) => true,
// Effective type present but no native type — the child wrote
// a docblock-only type (e.g. `@return list<Pen>` with no native
// hint). That is an intentional override.
(Some(_), None) => false,
// Both present — if they are equivalent, the child didn't write
// a docblock (the effective type is just the native hint echoed).
(Some(eff), Some(nat)) => eff.equivalent(nat),
}
}
/// Whether an ancestor's type is richer than the child's native type.
///
/// Returns `true` when the ancestor has an effective type that differs
/// from its own native type (meaning the ancestor wrote a docblock).
fn ancestor_has_richer_type(effective: &Option<PhpType>, native: &Option<PhpType>) -> bool {
match (effective, native) {
// Ancestor has an effective type but no native type — it came
// from a docblock (e.g. interface method with `@return list<Pen>`
// and no native hint).
(Some(_), None) => true,
// Both present — richer if they differ (docblock overrides native).
(Some(eff), Some(nat)) => !eff.equivalent(nat),
// No effective type — nothing richer to offer.
_ => false,
}
}
/// Enrich a child method with docblock information from an ancestor method.
///
/// Propagates return types, parameter types, descriptions, template
/// parameters, conditional return types, and type assertions from the
/// ancestor when the child lacks its own docblock overrides.
///
/// **Return type rule:** If the child's `return_type` equals its
/// `native_return_type` (no docblock), and the ancestor's `return_type`
/// differs from its `native_return_type` (has docblock), copy the
/// ancestor's `return_type` to the child. If the child has no
/// `return_type` at all, always inherit the ancestor's.
///
/// **Parameter rule:** Match by position (not by name, since the child
/// may rename parameters). Same effective-vs-native comparison as
/// return types.
///
/// **Description rule:** Inherit `description` and `return_description`
/// when the child has `None`.
pub(crate) fn enrich_method_from_ancestor(existing: &mut MethodInfo, ancestor: &MethodInfo) {
// ── Return type ─────────────────────────────────────────────
// Propagate when (a) the child has no return type at all, or
// (b) the child's effective type equals its native type (no
// docblock override) and the ancestor has a richer docblock type.
if existing.return_type.is_none() && ancestor.return_type.is_some()
|| lacks_docblock_override(&existing.return_type, &existing.native_return_type)
&& ancestor_has_richer_type(&ancestor.return_type, &ancestor.native_return_type)
{
existing.return_type = ancestor.return_type.clone();
}
// ── Template parameters ─────────────────────────────────────
if existing.template_params.is_empty() && !ancestor.template_params.is_empty() {
existing.template_params = ancestor.template_params.clone();
existing.template_param_bounds = ancestor.template_param_bounds.clone();
existing.template_bindings = ancestor.template_bindings.clone();
// Template return types like `T` only make sense when the
// template params are present — inherit the return type too
// if we haven't already set it.
if existing.return_type.is_none() {
existing.return_type = ancestor.return_type.clone();
}
}
// ── Conditional return type ─────────────────────────────────
if existing.conditional_return.is_none() && ancestor.conditional_return.is_some() {
existing.conditional_return = ancestor.conditional_return.clone();
}
// ── Type assertions ─────────────────────────────────────────
if existing.type_assertions.is_empty() && !ancestor.type_assertions.is_empty() {
existing.type_assertions = ancestor.type_assertions.clone();
}
// ── Parameters ──────────────────────────────────────────────
// For constructors, use **name-based** matching instead of
// positional. PHP constructors don't follow Liskov substitution
// — a child constructor can have a completely different signature
// (different parameter count, order, types). Positional
// enrichment would incorrectly map ancestor param types onto
// unrelated child params (e.g. Exception's `$code` type `int`
// onto a child's `$message` param at position 1).
//
// This follows PHPStan's `PhpDocInheritanceResolver`: for
// `__construct` the positional parameter name list falls back to
// the child's own names, so only same-named parameters inherit.
if existing.name == "__construct" {
enrich_constructor_parameters_by_name(&mut existing.parameters, &ancestor.parameters);
} else {
enrich_parameters_from_ancestor(&mut existing.parameters, &ancestor.parameters);
}
// ── Descriptions ────────────────────────────────────────────
if existing.description.is_none() && ancestor.description.is_some() {
existing.description = ancestor.description.clone();
}
if existing.return_description.is_none() && ancestor.return_description.is_some() {
existing.return_description = ancestor.return_description.clone();
}
}
/// Enrich child parameters from ancestor parameters, matched by position.
///
/// When a child parameter's `type_hint` equals its `native_type_hint`
/// (no docblock override) and the ancestor parameter has a richer type,
/// copy the ancestor's `type_hint`. Also inherit `description` when
/// the child parameter has none.
fn enrich_parameters_from_ancestor(
existing_params: &mut [ParameterInfo],
ancestor_params: &[ParameterInfo],
) {
for (existing_param, ancestor_param) in existing_params.iter_mut().zip(ancestor_params) {
enrich_single_parameter(existing_param, ancestor_param);
}
}
/// Enrich constructor parameters from ancestor parameters, matched by name.
///
/// Unlike regular methods (which follow Liskov substitution and can
/// safely use positional matching), constructors can have completely
/// different signatures. Only parameters with the **same name** in
/// both the child and ancestor are enriched.
fn enrich_constructor_parameters_by_name(
existing_params: &mut [ParameterInfo],
ancestor_params: &[ParameterInfo],
) {
for existing_param in existing_params.iter_mut() {
if let Some(ancestor_param) = ancestor_params
.iter()
.find(|ap| ap.name == existing_param.name)
{
enrich_single_parameter(existing_param, ancestor_param);
}
}
}
/// Enrich a single child parameter from an ancestor parameter.
///
/// Copies the ancestor's `type_hint` when the child lacks a docblock
/// override, the ancestor has a richer type, **and** the child's
/// native type is not a specific concrete type.
///
/// PHP allows contravariant parameter types: a concrete class may
/// declare `?int` where the interface says `int`, or Carbon's
/// `setTimezone(DateTimeZone|string|int)` may widen DateTime's
/// `setTimezone(DateTimeZone)`. In those cases the child's native
/// type is an intentional widening and must not be narrowed.
///
/// However, when the child's native type is a placeholder like
/// `object` or `mixed` (common in `@implements`/`@extends` generic
/// patterns where the interface declares `object $entity` and the
/// `@implements` tag substitutes the template to a concrete type),
/// the ancestor's enriched type should flow through.
fn enrich_single_parameter(existing_param: &mut ParameterInfo, ancestor_param: &ParameterInfo) {
// Type hint enrichment — the child must lack a docblock override
// AND the ancestor must have a richer type (docblock that goes
// beyond its native hint). Additionally, skip enrichment when
// the child has a specific native type (not `object`/`mixed`)
// because the child's declaration is intentional and may be
// wider than the ancestor's (contravariant parameters).
let child_has_specific_native = existing_param.native_type_hint.as_ref().is_some_and(|nt| {
!nt.is_object() && !nt.is_mixed() && !nt.is_array_like() && !nt.is_iterable()
});
if !child_has_specific_native
&& lacks_docblock_override(&existing_param.type_hint, &existing_param.native_type_hint)
&& ancestor_has_richer_type(&ancestor_param.type_hint, &ancestor_param.native_type_hint)
{
existing_param.type_hint = ancestor_param.type_hint.clone();
}
// Description enrichment
if existing_param.description.is_none() && ancestor_param.description.is_some() {
existing_param.description = ancestor_param.description.clone();
}
}
/// Enrich a child property with docblock information from an ancestor
/// property.
///
/// Propagates type hints and descriptions from the ancestor when the
/// child lacks its own docblock overrides. The same
/// effective-vs-native comparison is used as for method return types.
pub(crate) fn enrich_property_from_ancestor(existing: &mut PropertyInfo, ancestor: &PropertyInfo) {
// ── Type hint ───────────────────────────────────────────────
// Same logic as method return types: propagate when the child
// has no type or has only the native hint without a docblock
// override, and the ancestor provides a richer type.
if existing.type_hint.is_none() && ancestor.type_hint.is_some()
|| lacks_docblock_override(&existing.type_hint, &existing.native_type_hint)
&& ancestor_has_richer_type(&ancestor.type_hint, &ancestor.native_type_hint)
{
existing.type_hint = ancestor.type_hint.clone();
}
// ── Description ─────────────────────────────────────────────
if existing.description.is_none() && ancestor.description.is_some() {
existing.description = ancestor.description.clone();
}
}
/// Resolve a class together with all inherited members from its parent
/// chain.
///
/// Walks up the `extends` chain via `class_loader`, collecting public and
/// protected methods, properties, and constants from each ancestor.
/// If a child already defines a member with the same name as a parent
/// member, the child's version wins (even if the signatures differ).
///
/// Private members are never inherited.
///
/// When the child declares `@extends Parent<Type1, Type2>` and the parent
/// has `@template` parameters, the inherited members have their template
/// parameter types replaced with the concrete types from the `@extends`
/// annotation. This substitution chains through the entire ancestry.
///
/// A depth limit of 20 prevents infinite loops from circular inheritance.
pub(crate) fn resolve_class_with_inheritance(
class: &ClassInfo,
class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
) -> ClassInfo {
let mut merged = class.clone();
// Build dedup sets from the class's own members. These are passed
// through trait merging and the parent chain walk so that every
// addition is tracked in O(1) across all recursion levels.
let mut dedup = MergeDedup::from_class(&merged);
// Stake a claim on the class's own `@method` tag names before merging
// any inherited members. A `@method` declaration overrides a method of
// the same name inherited from a superclass, exactly like a real
// overriding method would (the virtual members themselves are
// synthesized later by the PHPDoc provider — here we only prevent the
// inheritance walk from merging the inherited real method over them).
reserve_method_tag_names(class.class_docblock.as_deref(), &mut dedup);
// 1. Merge traits used by this class.
// PHP precedence: class methods > trait methods > inherited methods.
// Since `merged` already contains the class's own members, we only
// add trait members that don't collide with existing ones.
merge_traits_into(
&mut merged,
&class.used_traits,
&TraitContext {
use_generics: &class.use_generics,
precedences: &class.trait_precedences,
aliases: &class.trait_aliases,
},
class_loader,
0,
&mut dedup,
&class.fqn(),
);
// 2. Walk up the `extends` chain and merge parent members.
//
// `current` holds a reference to the class whose `parent_class`,
// `extends_generics`, `used_traits`, etc. we read at each level.
// For the first iteration this is the root `class` (a borrow —
// zero allocation). After that it becomes the `Arc<ClassInfo>`
// returned by `class_loader` (a cheap Arc move).
let mut current: ClassRef<'_> = ClassRef::Borrowed(class);
let mut depth = 0;
// The substitution map accumulates as we walk the chain.
// It maps template parameter names → concrete types, and is
// re-computed at each level based on the `@extends` generics
// of the current class and the `@template` params of the parent.
let mut active_subs: HashMap<String, PhpType> = HashMap::new();
// Seed the initial substitution map from the root class's
// `@extends` generics. If the root class has
// `@extends Collection<int, Language>`, this will be applied
// when we load `Collection` as the first parent.
//
// We don't apply it yet — it's matched against the parent's
// template_params in the loop below.
while let Some(ref parent_name) = current.parent_class {
depth += 1;
if depth > MAX_INHERITANCE_DEPTH {
break;
}
let parent = if let Some(p) = class_loader(parent_name) {
p
} else {
break;
};
// Stake a claim on this ancestor's `@method` tag names at its depth
// in the hierarchy, so that a real method of the same name inherited
// from a *farther* ancestor does not shadow the `@method`
// declaration. Reserved before the ancestor's own members are
// merged so a real method on this same ancestor still wins over its
// own `@method` tag.
reserve_method_tag_names(parent.class_docblock.as_deref(), &mut dedup);
// Build the substitution map for this parent level.
//
// Look through current's `extends_generics` for an entry
// whose class name matches this parent, and zip its type
// arguments with the parent's `template_params`.
let mut level_subs = build_substitution_map(¤t, &parent, &active_subs);
// ── Convention-based Factory fallback ────────────────────
// When a factory class extends `Factory` without
// `@extends Factory<Model>`, derive the model class from
// the naming convention (e.g. `Database\Factories\UserFactory`
// → `App\Models\User`) and substitute `TModel` automatically.
if level_subs.is_empty()
&& !parent.template_params.is_empty()
&& is_factory_class(parent_name)
{
let factory_fqn = current.fqn();
if let Some(model_fqn) = factory_to_model_fqn(&factory_fqn)
&& class_loader(&model_fqn).is_some()
{
for param in &parent.template_params {
level_subs.insert(param.to_string(), PhpType::Named(model_fqn.clone()));
}
}
}
// ── Template bound fallback ─────────────────────────────
// When a subclass extends a generic parent without providing
// explicit `@extends` generics and no convention-based
// substitution filled the map, fall back to the template
// parameter bounds (e.g. `@template T of object` → `object`)
// so that inherited methods don't leak raw template names.
if !parent.template_params.is_empty() {
for param_name in &parent.template_params {
if !level_subs.contains_key(param_name.to_string().as_str()) {
let bound = parent
.template_param_bounds
.get(param_name)
.cloned()
.unwrap_or_else(PhpType::mixed);
level_subs.insert(param_name.to_string(), bound);
}
}
}
// Merge traits used by the parent class as well, so that
// grandparent-level trait members are visible.
// Apply the current level's template substitutions to the
// parent's `@use` generics. Without this, a chain like:
//
// /** @extends DataCollection<int, DeliveryOption> */
// class DeliveryOptionCollection extends DataCollection
//
// where DataCollection has:
// /** @use EnumerableMethods<TKey, TValue> */
//
// would pass the raw `TKey`/`TValue` template params to the
// trait instead of the concrete `int`/`DeliveryOption` types.
let substituted_use_generics: Vec<(Atom, Vec<PhpType>)> = if level_subs.is_empty() {
parent.use_generics.clone()
} else {
parent
.use_generics
.iter()
.map(|(name, args)| {
let substituted_args: Vec<PhpType> =
args.iter().map(|arg| arg.substitute(&level_subs)).collect();
(*name, substituted_args)
})
.collect()
};
merge_traits_into(
&mut merged,
&parent.used_traits,
&TraitContext {
use_generics: &substituted_use_generics,
precedences: &parent.trait_precedences,
aliases: &parent.trait_aliases,
},
class_loader,
0,
&mut dedup,
&parent.fqn(),
);
// Merge parent methods — skip private.
// When the child already has a method with the same name,
// enrich it with the parent's richer docblock types instead
// of silently discarding the parent's type information.
for method in &parent.methods {
if method.visibility == Visibility::Private {
continue;
}
if !dedup
.methods
.insert(crate::atom::ascii_lowercase_atom(&method.name))
{
// Child already has this method — enrich it from parent.
let mut ancestor_method = (**method).clone();
if !level_subs.is_empty() {
apply_substitution_to_method(&mut ancestor_method, &level_subs);
}
if let Some(existing) = merged
.methods
.make_mut()
.iter_mut()
.find(|m| m.name.eq_ignore_ascii_case(&method.name))
{
enrich_method_from_ancestor(Arc::make_mut(existing), &ancestor_method);
}
continue;
}
if level_subs.is_empty() {
// Replace bare `self` in return type with the declaring
// (parent) class name so that `self` resolves to the class
// that defines the method, not the inheriting child.
if method
.return_type
.as_ref()
.is_some_and(|r| r.contains_bare_self())
{
let mut m = (**method).clone();
if let Some(ref mut rt) = m.return_type {
*rt = rt.replace_bare_self(&parent.fqn());
}
merged.methods.push(Arc::new(m));
} else {
merged.methods.push(Arc::clone(method));
}
} else {
let mut ancestor_method = (**method).clone();
apply_substitution_to_method(&mut ancestor_method, &level_subs);
// Replace bare `self` after substitution.
if let Some(ref mut rt) = ancestor_method.return_type
&& rt.contains_bare_self()
{
*rt = rt.replace_bare_self(&parent.fqn());
}
merged.methods.push(Arc::new(ancestor_method));
}
}
// Merge parent properties — same enrichment logic.
for property in &parent.properties {
if property.visibility == Visibility::Private {
continue;
}
let mut ancestor_property = property.clone();
if !level_subs.is_empty() {
apply_substitution_to_property(&mut ancestor_property, &level_subs);
}
if !dedup.properties.insert(property.name) {
// Child already has this property — enrich it from parent.
if let Some(existing) = merged
.properties
.make_mut()
.iter_mut()
.find(|p| p.name == property.name)
{
enrich_property_from_ancestor(existing, &ancestor_property);
}
continue;
}
merged.properties.push(ancestor_property);
}
// Merge parent constants
for constant in &parent.constants {
if constant.visibility == Visibility::Private {
continue;
}
if !dedup.constants.insert(constant.name) {
continue;
}
merged.constants.push(constant.clone());
}
// Carry the substitution map forward for the next level.
// If `Collection` extends `AbstractCollection<TKey, TValue>`,
// we need to apply the current substitutions to those type
// arguments so that `TKey` → `int` flows through.
active_subs = level_subs;
current = ClassRef::Owned(parent);
}
// 3. Enrich methods from implemented interfaces.
// When a class overrides an interface method without a return type,
// propagate the interface method's return type (with template
// substitution from `@implements` generics).
for iface_name in &class.interfaces {
let Some(iface) = class_loader(iface_name) else {
continue;
};
// Build substitution map from @implements/@template-implements generics.
let iface_subs =
build_substitution_map(&ClassRef::Borrowed(class), &iface, &HashMap::new());
for method in &iface.methods {
// Only enrich methods that the class already has (i.e. overrides).
if let Some(existing) = merged
.methods
.make_mut()
.iter_mut()
.find(|m| m.name.eq_ignore_ascii_case(&method.name))
{
let mut ancestor_method = (**method).clone();
if !iface_subs.is_empty() {
apply_substitution_to_method(&mut ancestor_method, &iface_subs);
}
enrich_method_from_ancestor(Arc::make_mut(existing), &ancestor_method);
}
}
}
// Refine the `value` property on backed enums. The `BackedEnum`
// interface declares `public readonly int|string $value`, but each
// concrete backed enum knows its specific backing type. Replace
// the generic union with the precise type so that hover, completion,
// and diagnostics see `string` or `int` instead of `int|string`.
if let Some(ref backed) = merged.backed_type {
let specific_type = match backed {
crate::types::BackedEnumType::String => PhpType::Named("string".to_string()),
crate::types::BackedEnumType::Int => PhpType::Named("int".to_string()),
};
if let Some(prop) = merged
.properties
.make_mut()
.iter_mut()
.find(|p| p.name == "value")
{
prop.type_hint = Some(specific_type);
}
}
merged
}
/// Look up a method's return type through the inheritance chain.
///
/// Resolves inheritance for `class`, finds the method named
/// `method_name`, and returns its `return_type`. This is a
/// convenience wrapper around [`resolve_class_fully`](crate::virtual_members::resolve_class_fully)
/// that eliminates the repeated merge → find → extract pattern
/// used across many modules.
///
/// Uses full resolution (base inheritance + virtual member providers)
/// so that virtual methods from `@method` tags, `@mixin` classes,
/// and framework providers are included.
pub(crate) fn resolve_method_return_type(
class: &ClassInfo,
method_name: &str,
class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
) -> Option<PhpType> {
// Try the class directly first — it may already be fully resolved
// with generic substitutions applied. Falling through to the cache
// would return the un-substituted base class (keyed by bare FQN),
// losing template parameter substitutions like TModel → Product.
if let Some(m) = class.get_method(method_name) {
return m.return_type.clone();
}
let cache = crate::virtual_members::active_resolved_class_cache();
let merged =
crate::virtual_members::resolve_class_fully_maybe_cached(class, class_loader, cache);
merged
.methods
.iter()
.find(|m| m.name == method_name)
.and_then(|m| m.return_type.clone())
}
/// Look up a property's type hint through the inheritance chain.
///
/// Resolves inheritance for `class`, finds the property named
/// `prop_name`, and returns its `type_hint`. This is a
/// convenience wrapper around [`resolve_class_fully`](crate::virtual_members::resolve_class_fully)
/// that eliminates the repeated merge → find → extract pattern
/// used across many modules.
///
/// Uses full resolution (base inheritance + virtual member providers)
/// so that virtual properties from `@property` tags, `@mixin` classes,
/// and framework providers are included.
pub(crate) fn resolve_property_type_hint(
class: &ClassInfo,
prop_name: &str,
class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
) -> Option<PhpType> {
// Try the class directly first — it may already have the property
// with generic substitutions applied.
if let Some(p) = class.properties.iter().find(|p| p.name == prop_name)
&& p.type_hint.is_some()
{
let hint = p.type_hint.clone().unwrap();
return Some(replace_self_in_property_type(hint, class));
}
let cache = crate::virtual_members::active_resolved_class_cache();
let merged =
crate::virtual_members::resolve_class_fully_maybe_cached(class, class_loader, cache);
if let Some(hint) = merged
.properties
.iter()
.find(|p| p.name == prop_name)
.and_then(|p| p.type_hint.clone())
{
return Some(replace_self_in_property_type(hint, class));
}
// Fallback: if the class has a `__get` method with method-level
// template parameters and an IndexAccess return type (e.g.
// `@template K as key-of<TData>` / `@return TData[K]`), infer K
// from the property name and evaluate the indexed access.
// Try the original class first — it may already carry generic
// substitutions (e.g. from `apply_generic_args`) so `__get`'s
// return type is already concrete.
if let Some(ty) = resolve_magic_get_return_type(class, prop_name) {
return Some(ty);
}
resolve_magic_get_return_type(&merged, prop_name)
}
/// Replace `self`/`static`/`$this` references in a property type with
/// the owning class's fully qualified name.
///
/// Skips replacement for synthetic classes (like `__object_shape`) where
/// `self` refers to the caller's context, not the synthetic class itself.
fn replace_self_in_property_type(ty: PhpType, class: &ClassInfo) -> PhpType {
if ty.contains_self_ref() && !class.name.starts_with("__") {
ty.replace_self(&class.fqn())
} else {
ty
}
}
/// Try to resolve a property access through a `__get` magic method that
/// uses method-level `@template` with `key-of` bounds and `T[K]` return.
///
/// For example, given:
/// ```php
/// /** @template TData as array */
/// abstract class DataBag {
/// /** @template K as key-of<TData> @return TData[K] */
/// public function __get(string $property) { ... }
/// }
/// /** @extends DataBag<array{a: int, b: string}> */
/// class FooBag extends DataBag {}
/// ```
/// After class-level substitution, `__get` on the merged `FooBag` has
/// return type `array{a: int, b: string}[K]`. This function infers
/// `K = 'a'` from the property name and evaluates to `int`.
fn resolve_magic_get_return_type(class: &ClassInfo, prop_name: &str) -> Option<PhpType> {
let get_method = class
.methods
.iter()
.find(|m| m.name.eq_ignore_ascii_case("__get"))?;
let return_type = get_method.return_type.as_ref()?;
// When __get has no template params, return the declared return type
// directly (with self/static resolved to the owning class).
if get_method.template_params.is_empty() {
let resolved = if return_type.contains_self_ref() {
return_type.replace_self(&class.fqn())
} else {
return_type.clone()
};
return Some(resolved);
}
// Build a substitution map: for each method-level template parameter,
// try to infer its value from the property name being accessed.
let mut method_subs = std::collections::HashMap::new();
for tparam in &get_method.template_params {
// The template param is typically bounded by key-of<SomeShape>.
// After class-level substitution the bound is already concrete
// (e.g. key-of<array{a: int, b: string}> → 'a'|'b').
// We infer the template value as a literal string matching the
// property name.
method_subs.insert(tparam.to_string(), PhpType::Literal(prop_name.to_string()));
}
let resolved = return_type.substitute(&method_subs);
// Only return if the substitution actually resolved to something
// concrete (not still an IndexAccess with an unresolved key).
if matches!(&resolved, PhpType::IndexAccess(_, _)) {
return None;
}
Some(resolved)
}
/// Recursively merge members from the given traits into `merged`.
///
/// Traits can themselves `use` other traits (composition), so this
/// function recurses up to `MAX_TRAIT_DEPTH` levels. Members that
/// already exist in `merged` (by name) are skipped — this naturally
/// implements the PHP precedence rule where the current class's own
/// members win over trait members, and earlier-listed traits win
/// over later ones.
///
/// Private trait members *are* merged (unlike parent class private
/// members), because PHP copies trait members into the using class
/// regardless of visibility.
///
/// When `use_generics` contains an entry for a trait (e.g.
/// `@use SomeTrait<ConcreteType>`) and the trait declares
/// `@template T`, the inherited methods and properties have their
/// template parameter types replaced with the concrete types.
fn merge_traits_into(
merged: &mut ClassInfo,
trait_names: &[Atom],
ctx: &TraitContext<'_>,
class_loader: &dyn Fn(&str) -> Option<Arc<ClassInfo>>,
depth: u32,
dedup: &mut MergeDedup,
self_class_name: &str,
) {
if depth > MAX_TRAIT_DEPTH {
return;
}
for trait_name in trait_names {
let trait_info = if let Some(t) = class_loader(trait_name) {
t
} else {
continue;
};
// Build a substitution map for this trait if the using class
// declared `@use TraitName<Type1, Type2>` and the trait has
// `@template` parameters.
let mut trait_subs =
build_trait_substitution_map(trait_name, &trait_info, ctx.use_generics);
// ── Convention-based HasFactory fallback ─────────────────
// When a model uses `HasFactory` without `@use HasFactory<X>`,
// derive the factory class from the naming convention
// (e.g. `App\Models\User` → `Database\Factories\UserFactory`)
// and substitute `TFactory` automatically.
if trait_subs.is_empty()
&& !trait_info.template_params.is_empty()
&& is_has_factory_trait(trait_name)
&& extends_eloquent_model(merged, class_loader)
{
let model_fqn = merged.fqn();
let factory_fqn = model_to_factory_fqn(&model_fqn);
if class_loader(&factory_fqn).is_some() {
for param in &trait_info.template_params {
trait_subs.insert(param.to_string(), PhpType::Named(factory_fqn.clone()));
}
}
}
// ── Template bound fallback ─────────────────────────────
// When a class uses a generic trait without `@use` generics
// and no convention-based provider filled the map, fall back
// to the template parameter bounds (e.g. `@template T of object`
// → `object`) so inherited methods don't leak raw template names.
if !trait_info.template_params.is_empty() {
for param_name in &trait_info.template_params {
if !trait_subs.contains_key(param_name.to_string().as_str()) {
let bound = trait_info
.template_param_bounds
.get(param_name)
.cloned()
.unwrap_or_else(PhpType::mixed);
trait_subs.insert(param_name.to_string(), bound);
}
}
}
// Recursively merge traits used by this trait (trait composition).
// The sub-trait's own `@use` generics (from the trait's docblock)
// apply, not the outer class's.
if !trait_info.used_traits.is_empty() {
merge_traits_into(
merged,
&trait_info.used_traits,
&TraitContext {
use_generics: &trait_info.use_generics,
precedences: &trait_info.trait_precedences,
aliases: &trait_info.trait_aliases,
},
class_loader,
depth + 1,
dedup,
self_class_name,
);
}
// Walk the `parent_class` (extends) chain so that interface
// inheritance is resolved. For example, `BackedEnum extends
// UnitEnum` — loading `BackedEnum` alone would miss `UnitEnum`'s
// members (`cases()`, `$name`) unless we follow the chain here.
// The same depth counter is shared to prevent infinite loops.
let mut current = trait_info.clone();
let mut parent_depth = depth;
while let Some(ref parent_name) = current.parent_class {
parent_depth += 1;
if parent_depth > MAX_TRAIT_DEPTH {
break;
}
let parent = if let Some(p) = class_loader(parent_name) {
p
} else {
break;
};
// Also follow the parent's own used_traits.
if !parent.used_traits.is_empty() {
merge_traits_into(
merged,
&parent.used_traits,
&TraitContext {
use_generics: &parent.use_generics,
precedences: &parent.trait_precedences,
aliases: &parent.trait_aliases,
},
class_loader,
parent_depth + 1,
dedup,
self_class_name,
);
}
// Merge parent methods (skip private, skip duplicates)
for method in &parent.methods {
if method.visibility == Visibility::Private {
continue;
}
if !dedup
.methods
.insert(crate::atom::ascii_lowercase_atom(&method.name))
{
continue;
}
merged.methods.push(Arc::clone(method));
}
// Merge parent properties
for property in &parent.properties {
if property.visibility == Visibility::Private {
continue;
}
if !dedup.properties.insert(property.name) {
continue;
}
merged.properties.push(property.clone());
}
// Merge parent constants
for constant in &parent.constants {
if constant.visibility == Visibility::Private {
continue;
}
if !dedup.constants.insert(constant.name) {
continue;
}
merged.constants.push(constant.clone());
}