mago-analyzer 1.45.0

A PHP static analyzer that can detect type errors in PHP code, and provide suggestions for fixing them.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
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
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
use foldhash::HashSet;
use mago_allocator::Arena;

use mago_codex::identifier::method::MethodIdentifier;
use mago_codex::metadata::CodebaseMetadata;
use mago_codex::metadata::class_like::ClassLikeMetadata;
use mago_codex::metadata::function_like::FunctionLikeMetadata;
use mago_codex::misc::GenericParent;
use mago_codex::ttype::TType;
use mago_codex::ttype::atomic::TAtomic;
use mago_codex::ttype::atomic::generic::TGenericParameter;
use mago_codex::ttype::atomic::mixed::TMixed;
use mago_codex::ttype::atomic::object::TObject;
use mago_codex::ttype::atomic::object::named::TNamedObject;
use mago_codex::ttype::comparator::ComparisonResult;
use mago_codex::ttype::comparator::union_comparator::is_contained_by;
use mago_codex::ttype::expander::StaticClassType;
use mago_codex::ttype::get_mixed;
use mago_codex::ttype::get_specialized_template_type;
use mago_codex::ttype::template::GenericTemplate;
use mago_codex::ttype::template::TemplateResult;
use mago_codex::ttype::union::TUnion;
use mago_reporting::Annotation;
use mago_reporting::Issue;
use mago_span::HasSpan;
use mago_span::Span;
use mago_syntax::cst::ClassLikeMemberSelector;
use mago_syntax::cst::Expression;
use mago_word::Word;
use mago_word::ascii_lowercase_word;
use mago_word::word;

use crate::analyzable::Analyzable;
use crate::artifacts::AnalysisArtifacts;
use crate::code::IssueCode;
use crate::context::Context;
use crate::context::block::BlockContext;
use crate::error::AnalysisError;
use crate::resolver::class_name::report_non_existent_class_like;
use crate::resolver::selector::resolve_member_selector;
use crate::utils::names::display_class_like_name;
use crate::utils::names::display_method_name;
use crate::visibility::check_method_visibility;
use crate::visibility::is_method_visible;

#[derive(Debug)]
pub struct ResolvedMethod {
    /// The name of the class this method is called on, not necessarily the same
    /// as the class of the method itself, especially in cases of inheritance.
    pub classname: Word,
    /// The method identifiers that were successfully resolved.
    pub method_identifier: MethodIdentifier,
    /// The type of `$this` or the static class type if it's a static method.
    pub static_class_type: StaticClassType,
    /// The object the method was found on when it was reached through a `@mixin`.
    /// `Some` marks the method as mixin-resolved, which lets its `static` return
    /// type rebind to the receiver; template inference reads the mixin class's
    /// template arguments from it.
    pub declaring_object: Option<TNamedObject>,
    /// True if this method is static, meaning it can be called without an instance.
    pub is_static: bool,
    /// If Some, this method was found in a mixin but the target class lacks the magic method
    /// needed to forward the call. Contains the mixin class name and whether the target is final.
    pub mixin_without_magic_method: Option<MixinWithoutMagicMethod>,
}

/// Represents a method found in a mixin where the calling class lacks the required magic method.
#[derive(Debug, Clone)]
pub struct MixinWithoutMagicMethod {
    /// The name of the mixin class where the method was found.
    pub mixin_class_name: Word,
    /// Whether the target class (that has the mixin) is final.
    pub target_is_final: bool,
}

/// A method found on an object, before being turned into a [`ResolvedMethod`].
pub struct MethodCandidate<'ctx> {
    /// Metadata of the class the method was found on.
    pub metadata: &'ctx ClassLikeMetadata,
    /// The identifier of the declaring method.
    pub method_identifier: MethodIdentifier,
    /// The object type the method was found on (the mixin object for
    /// `@mixin`-resolved methods, otherwise the receiver).
    pub object: TObject,
    /// The name of the class the method was resolved against: the receiver's
    /// class, or the mixin / require-extends class the method was found on.
    pub classname: Word,
    /// See [`ResolvedMethod::mixin_without_magic_method`].
    pub mixin_without_magic_method: Option<MixinWithoutMagicMethod>,
    /// The receiver object when the method was reached through `@mixin`, so
    /// `$this`/`static` bind to the calling object instead of the mixin class.
    pub receiver_object: Option<TObject>,
}

/// Holds the results of resolving a method call, including valid targets and summary flags.
#[derive(Default, Debug)]
pub struct MethodResolutionResult {
    /// The template result containing any type variables and bounds.
    pub template_result: TemplateResult,
    /// A list of resolved methods, each with its template result and identifiers.
    pub resolved_methods: Vec<ResolvedMethod>,
    /// `__call` methods to fall back to when a called method is not declared but
    /// is handled by a magic `__call`.
    pub magic_call_methods: Vec<ResolvedMethod>,
    /// True if any selector was dynamic (e.g., from a generic string), making the method name unknown.
    pub has_dynamic_selector: bool,
    /// True if any resolution path involved an object with an ambiguous type (e.g., `mixed`, generic `object`).
    pub has_ambiguous_target: bool,
    /// True if any resolution path was definitively invalid (e.g., method not found, call on non-object).
    pub has_invalid_target: bool,
    /// True if an access on a `mixed` type was encountered.
    pub encountered_mixed: bool,
    /// True if an access on a `null` type was encountered.
    pub encountered_null: bool,
    /// True if all resolved methods have non-nullable return types.
    /// When combined with `encountered_null` and nullsafe access, indicates
    /// the null in the result type came ONLY from nullsafe short-circuit.
    pub all_methods_non_nullable_return: bool,
}

/// Resolves all possible method targets from an object expression and a member selector.
///
/// This utility handles the logic for `$object->selector` by:
///
/// 1. Analyzing the `$object` expression to find its type.
/// 2. Resolving the `selector` to get potential method names.
/// 3. Finding all matching methods on the object's possible types.
/// 4. Reporting any issues found, such as "method not found" or "call on mixed".
pub fn resolve_method_targets<'ctx, 'ast, 'arena, A>(
    context: &mut Context<'ctx, 'arena, A>,
    block_context: &mut BlockContext<'ctx>,
    artifacts: &mut AnalysisArtifacts,
    object: &'ast Expression<'arena>,
    selector: &'ast ClassLikeMemberSelector<'arena>,
    is_null_safe: bool,
    access_span: Span,
) -> Result<MethodResolutionResult, AnalysisError>
where
    A: Arena,
{
    let mut result = MethodResolutionResult::default();
    let mut asserted_descendant_method_references = Vec::new();

    let was_inside_general_use = block_context.flags.inside_general_use();
    block_context.flags.set_inside_general_use(true);
    object.analyze(context, block_context, artifacts)?;
    block_context.flags.set_inside_general_use(was_inside_general_use);

    let resolved_selectors = resolve_member_selector(context, block_context, artifacts, selector)?;
    let mut method_names = Vec::new();

    for resolved_selector in resolved_selectors {
        if resolved_selector.is_dynamic() {
            result.has_dynamic_selector = true;
        }

        if let Some(name) = resolved_selector.name() {
            method_names.push(ascii_lowercase_word(name.as_bytes()));
        } else {
            result.has_invalid_target = true;
        }
    }

    if let Some(object_type) = artifacts.get_expression_type(object) {
        let mut object_atomics = object_type.types.iter().collect::<Vec<_>>();

        while let Some(object_atomic) = object_atomics.pop() {
            if let TAtomic::GenericParameter(TGenericParameter { constraint, .. }) = object_atomic {
                object_atomics.extend(constraint.types.iter());
                continue;
            }

            if object_atomic.is_never() {
                continue;
            }

            if object_atomic.is_null() {
                result.encountered_null = true;
                if !object_type.ignore_nullable_issues() && !is_null_safe && !object_type.has_nullsafe_null() {
                    result.has_invalid_target = true;

                    context.collector.report_with_code(
                        if object_type.is_null() {
                            IssueCode::MethodAccessOnNull
                        } else {
                            IssueCode::PossibleMethodAccessOnNull
                        },
                        Issue::error("Attempting to call a method on `null`.")
                            .with_annotation(
                                Annotation::primary(object.span()).with_message("This expression can be `null`"),
                            )
                            .with_help("Use the nullsafe operator (`?->`) if `null` is an expected value."),
                    );
                }

                continue;
            }

            let TAtomic::Object(obj_type) = object_atomic else {
                if object_atomic.is_mixed() {
                    result.encountered_mixed = true;
                } else {
                    result.has_invalid_target = true;
                }

                report_call_on_non_object(context, object_atomic, object.span(), selector.span());
                continue;
            };

            let resolved_magic_call_method = resolve_method_from_object(
                context,
                block_context,
                object,
                selector,
                obj_type,
                word(b"__call"),
                access_span,
                true,
                &mut result,
            );

            let mut had_undocumented_magic_call = false;
            for &method_name in &method_names {
                let resolved_methods = resolve_method_from_object(
                    context,
                    block_context,
                    object,
                    selector,
                    obj_type,
                    method_name,
                    access_span,
                    !resolved_magic_call_method.is_empty(),
                    &mut result,
                );

                if resolved_methods.is_empty() {
                    collect_asserted_descendant_method_references(
                        context,
                        block_context,
                        obj_type,
                        method_name,
                        &mut asserted_descendant_method_references,
                    );
                }

                if resolved_methods.is_empty() {
                    if let Some(classname) = obj_type.get_name() {
                        let method_name_bytes: &[u8] = method_name.as_ref();
                        let has_method_assertion = type_has_method_assertion(obj_type, method_name_bytes);

                        if !has_method_assertion {
                            if resolved_magic_call_method.is_empty() {
                                report_non_existent_method(
                                    context,
                                    object.span(),
                                    selector.span(),
                                    classname,
                                    method_name,
                                );

                                result.has_invalid_target = true;
                            } else {
                                report_non_documented_method(
                                    context,
                                    object.span(),
                                    selector.span(),
                                    classname,
                                    method_name,
                                );

                                had_undocumented_magic_call = true;
                            }
                        }
                    } else {
                        // ambiguous
                    }
                } else {
                    // Check if any resolved method was found in a mixin without magic method support
                    for resolved_method in &resolved_methods {
                        if let Some(mixin_info) = &resolved_method.mixin_without_magic_method
                            && let Some(classname) = obj_type.get_name()
                        {
                            if mixin_info.target_is_final {
                                // Final class - error, method can never work at runtime
                                report_non_existent_mixin_method(
                                    context,
                                    object.span(),
                                    selector.span(),
                                    classname,
                                    method_name,
                                    mixin_info.mixin_class_name,
                                );
                                result.has_invalid_target = true;
                            } else {
                                // Non-final class - warning, subclass might implement __call
                                report_possibly_non_existent_mixin_method(
                                    context,
                                    object.span(),
                                    selector.span(),
                                    classname,
                                    method_name,
                                    mixin_info.mixin_class_name,
                                );
                            }
                        }
                    }
                }

                result.resolved_methods.extend(resolved_methods);
            }

            if had_undocumented_magic_call {
                result.magic_call_methods.extend(resolved_magic_call_method);
            }
        }
    } else {
        result.has_invalid_target = true;
        result.encountered_mixed = true;
        report_call_on_non_object(context, &TAtomic::Mixed(TMixed::new()), object.span(), selector.span());
    }

    for method_id in asserted_descendant_method_references {
        artifacts.symbol_references.add_reference_for_method_call(&block_context.scope, &method_id);
    }

    // Compute whether all resolved methods have non-nullable return types.
    // This is used to determine if null in the result type came only from nullsafe short-circuit.
    result.all_methods_non_nullable_return = !result.resolved_methods.is_empty()
        && result.resolved_methods.iter().all(|resolved_method| {
            context
                .codebase
                .get_method_by_id(&resolved_method.method_identifier)
                .and_then(|method| method.return_type_metadata.as_ref())
                .is_some_and(|return_type| !return_type.type_union.is_nullable())
        });

    Ok(result)
}

/// Records references to child methods that can satisfy a `method_exists()` assertion.
fn collect_asserted_descendant_method_references<'ctx, A>(
    context: &Context<'ctx, '_, A>,
    block_context: &BlockContext<'ctx>,
    object_type: &TObject,
    method_name: Word,
    references: &mut Vec<MethodIdentifier>,
) where
    A: Arena,
{
    if !type_has_method_assertion(object_type, method_name.as_bytes()) {
        return;
    }

    let Some(class_name) = object_type.get_name() else {
        return;
    };

    for descendant in context.codebase.get_all_descendants(class_name.as_bytes()) {
        if !context.codebase.method_exists(descendant.as_bytes(), method_name.as_bytes())
            || !is_method_visible(context, block_context, descendant.as_bytes(), method_name.as_bytes())
        {
            continue;
        }

        let method_id =
            context.codebase.get_declaring_method_identifier(&MethodIdentifier::new(descendant, method_name));
        if !references.contains(&method_id) {
            references.push(method_id);
        }
    }
}

pub fn resolve_method_from_object<'ctx, 'ast, 'arena, A>(
    context: &mut Context<'ctx, 'arena, A>,
    block_context: &BlockContext<'ctx>,
    object: &'ast Expression<'arena>,
    selector: &'ast ClassLikeMemberSelector<'arena>,
    object_type: &TObject,
    method_name: Word,
    access_span: Span,
    has_magic_call: bool,
    result: &mut MethodResolutionResult,
) -> Vec<ResolvedMethod>
where
    A: Arena,
{
    let mut resolved_methods = vec![];

    let candidates = get_method_candidates_from_object(
        context,
        block_context,
        object,
        selector,
        object_type,
        object_type,
        method_name,
        access_span,
        has_magic_call,
        result,
    );

    for candidate in candidates {
        let MethodCandidate {
            metadata,
            method_identifier: declaring_method_id,
            object,
            classname,
            mixin_without_magic_method,
            receiver_object,
        } = candidate;
        let declaring_class_metadata =
            context.codebase.get_class_like(declaring_method_id.get_class_name().as_bytes()).unwrap_or(metadata);

        // Collect class-template bounds from the object the method was found on:
        // for `@mixin`-resolved methods that is the mixin object, whose parameters
        // instantiate `metadata`'s templates; the receiver's parameters do not.
        let class_template_parameters = super::class_template_type_collector::collect(
            context.codebase,
            metadata,
            declaring_class_metadata,
            Some(&object),
        );

        if let Some(class_template_parameters) = class_template_parameters {
            result.template_result.add_lower_bounds(class_template_parameters);
        }

        for (index, parameter) in object.get_type_parameters().unwrap_or_default().iter().enumerate() {
            let Some(template_name) = metadata.get_template_name_for_index(index) else {
                continue;
            };

            result
                .template_result
                .template_types
                .entry(template_name)
                .or_default()
                .push(GenericTemplate::new(GenericParent::ClassLike(metadata.name), parameter.clone()));
        }

        let (static_class_type, declaring_object) = match receiver_object {
            Some(receiver) => {
                let declaring_object = match object {
                    TObject::Named(named) => Some(named),
                    // A non-named mixin object (an enum) carries no type parameters;
                    // a bare named object keeps template inference from falling back
                    // to the receiver's parameters.
                    other => other.get_name().map(TNamedObject::new),
                };
                (StaticClassType::Object(receiver), declaring_object)
            }
            None => (StaticClassType::Object(object), None),
        };

        resolved_methods.push(ResolvedMethod {
            method_identifier: declaring_method_id,
            static_class_type,
            declaring_object,
            classname,
            is_static: false,
            mixin_without_magic_method,
        });
    }

    resolved_methods
}

pub fn get_method_candidates_from_object<'ctx, 'ast, 'arena, 'object, A>(
    context: &mut Context<'ctx, 'arena, A>,
    block_context: &BlockContext<'ctx>,
    object: &'ast Expression<'arena>,
    selector: &'ast ClassLikeMemberSelector<'arena>,
    object_type: &'object TObject,
    outer_object: &'object TObject,
    method_name: Word,
    access_span: Span,
    has_magic_call: bool,
    result: &mut MethodResolutionResult,
) -> Vec<MethodCandidate<'ctx>>
where
    A: Arena,
{
    let mut candidates = vec![];

    let Some(name) = object_type.get_name() else {
        if std::ptr::eq(object_type, outer_object) {
            result.has_ambiguous_target = true;

            if !has_magic_call {
                let method_name_bytes: &[u8] = method_name.as_ref();
                let has_method_assertion = type_has_method_assertion(object_type, method_name_bytes);
                if !has_method_assertion {
                    report_call_on_ambiguous_object(context, object.span(), selector.span());
                }
            }
        }

        return candidates;
    };

    let Some(class_metadata) = context.codebase.get_class_like(name.as_bytes()) else {
        result.has_invalid_target = true;
        report_non_existent_class_like(context, object.span(), name);
        return candidates;
    };

    let mut method_id = MethodIdentifier::new(class_metadata.original_name, method_name);
    if !context.codebase.method_identifier_exists(&method_id) {
        method_id = context.codebase.get_declaring_method_identifier(&method_id);
    }

    if let Some(function_like_metadata) = context.codebase.get_method_by_id(&method_id) {
        if !check_method_visibility(
            context,
            block_context,
            class_metadata.original_name.as_bytes(),
            method_name.as_bytes(),
            access_span,
            Some(selector.span()),
        ) {
            result.has_invalid_target = true;
        }

        if !check_where_method_constraints(
            context,
            object_type,
            object,
            selector,
            class_metadata,
            function_like_metadata,
            class_metadata.original_name,
        ) {
            result.has_invalid_target = true;
        }

        if function_like_metadata.flags.is_magic_method() {
            let lowercase_method = ascii_lowercase_word(method_name.as_bytes());
            let is_pseudo = class_metadata.pseudo_methods.contains(&lowercase_method)
                || class_metadata.all_parent_classes.iter().any(|parent_name| {
                    context
                        .codebase
                        .get_class_like(parent_name.as_bytes())
                        .is_some_and(|parent| parent.pseudo_methods.contains(&lowercase_method))
                });

            let mut is_inherited = false;

            if is_pseudo {
                for parent_class_name in &class_metadata.all_parent_classes {
                    if let Some(parent_metadata) = context.codebase.get_class_like(parent_class_name.as_bytes())
                        && parent_metadata.methods.contains(&lowercase_method)
                        && !parent_metadata.pseudo_methods.contains(&lowercase_method)
                    {
                        is_inherited = true;
                        break;
                    }
                }
            }

            if function_like_metadata.flags.is_static() {
                result.has_invalid_target = true;

                report_dynamic_static_method_call(
                    context,
                    object.span(),
                    selector.span(),
                    class_metadata.original_name,
                    method_name,
                    has_magic_call,
                );
            } else if !has_magic_call && !is_inherited && !class_metadata.kind.is_interface() {
                if class_metadata.flags.is_final() && !class_metadata.flags.is_abstract() {
                    report_magic_call_without_call_method(
                        context,
                        object.span(),
                        selector.span(),
                        class_metadata.original_name,
                        method_name,
                        false,
                    );
                } else {
                    report_possibly_missing_magic_call(
                        context,
                        object.span(),
                        selector.span(),
                        class_metadata.original_name,
                        method_name,
                        false,
                    );
                }
            } else {
                // call is on an inherited or interface member with magic call available; no extra diagnostic needed
            }
        }

        candidates.push(MethodCandidate {
            metadata: class_metadata,
            method_identifier: method_id,
            object: outer_object.clone(),
            classname: name,
            mixin_without_magic_method: None,
            receiver_object: None,
        });
    } else if !class_metadata.require_extends.is_empty() || !class_metadata.require_implements.is_empty() {
        for required_class in class_metadata.require_extends.iter().chain(class_metadata.require_implements.iter()) {
            let Some(required_metadata) = context.codebase.get_class_like(required_class.as_bytes()) else {
                continue;
            };

            let mut required_method_id = MethodIdentifier::new(required_metadata.original_name, method_name);
            if !context.codebase.method_identifier_exists(&required_method_id) {
                required_method_id = context.codebase.get_declaring_method_identifier(&required_method_id);
            }

            if context.codebase.get_method_by_id(&required_method_id).is_some() {
                candidates.push(MethodCandidate {
                    metadata: required_metadata,
                    method_identifier: required_method_id,
                    object: outer_object.clone(),
                    classname: *required_class,
                    mixin_without_magic_method: None,
                    receiver_object: None,
                });
                break;
            }
        }
    } else if !class_metadata.mixins.is_empty() {
        // Search mixins for the method. If has_magic_call is false, we track that
        // the method was found in a mixin without the required magic method.
        let mixin_types = collect_mixin_types(context.codebase, class_metadata, outer_object, &class_metadata.mixins);

        for (mixin_class_name, mixin_object) in mixin_types {
            let Some(mixin_metadata) = context.codebase.get_class_like(mixin_class_name.as_bytes()) else {
                continue;
            };

            let mut mixin_method_id = MethodIdentifier::new(mixin_metadata.original_name, method_name);
            if !context.codebase.method_identifier_exists(&mixin_method_id) {
                mixin_method_id = context.codebase.get_declaring_method_identifier(&mixin_method_id);
            }

            if let Some(function_like_metadata) = context.codebase.get_method_by_id(&mixin_method_id) {
                if !check_method_visibility(
                    context,
                    block_context,
                    mixin_metadata.original_name.as_bytes(),
                    method_name.as_bytes(),
                    access_span,
                    Some(selector.span()),
                ) {
                    result.has_invalid_target = true;
                    continue;
                }

                if let Some(method_metadata) = &function_like_metadata.method_metadata
                    && !method_metadata.visibility.is_public()
                {
                    continue;
                }

                // Track if this method was found without magic call support
                let mixin_info = if has_magic_call {
                    None
                } else {
                    Some(MixinWithoutMagicMethod { mixin_class_name, target_is_final: class_metadata.flags.is_final() })
                };

                // Bind `$this`/`static` in the mixin method's return type to the
                // receiver, not the mixin class: `@mixin` methods behave as if
                // declared on the class carrying the tag.
                candidates.push(MethodCandidate {
                    metadata: mixin_metadata,
                    method_identifier: mixin_method_id,
                    object: mixin_object.clone(),
                    classname: mixin_class_name,
                    mixin_without_magic_method: mixin_info,
                    receiver_object: Some(outer_object.clone()),
                });
            }
        }
    } else {
        // method already resolved on the class itself, or no required-extends/mixins to search
    }

    if let Some(intersection_types) = object_type.get_intersection_types() {
        for intersected_atomic in intersection_types {
            match intersected_atomic {
                TAtomic::Object(intersected_object) => {
                    // Recursively search in the intersection types
                    candidates.extend(get_method_candidates_from_object(
                        context,
                        block_context,
                        object,
                        selector,
                        intersected_object,
                        object_type,
                        method_name,
                        access_span,
                        has_magic_call,
                        result,
                    ));
                }
                TAtomic::GenericParameter(generic_parameter) => {
                    // If the intersection type is a generic parameter, we need to check its constraint
                    for constraint_atomic in generic_parameter.constraint.types.as_ref() {
                        if let TAtomic::Object(intersected_object) = constraint_atomic {
                            // Recursively search in the intersection types
                            candidates.extend(get_method_candidates_from_object(
                                context,
                                block_context,
                                object,
                                selector,
                                intersected_object,
                                object_type,
                                method_name,
                                access_span,
                                has_magic_call,
                                result,
                            ));
                        }
                    }
                }
                _ => {
                    // For other atomic types, we do not need to do anything special
                }
            }
        }
    }

    let mut seen = HashSet::default();
    candidates.retain(|candidate| seen.insert(candidate.method_identifier));

    candidates
}

fn check_where_method_constraints<A>(
    context: &mut Context<'_, '_, A>,
    object_type: &TObject,
    object: &Expression,
    selector: &ClassLikeMemberSelector,
    class_like_metadata: &ClassLikeMetadata,
    function_like_metadata: &FunctionLikeMetadata,
    defining_class_id: Word,
) -> bool
where
    A: Arena,
{
    let Some(method_metadata) = function_like_metadata.method_metadata.as_ref() else {
        return true;
    };

    if method_metadata.where_constraints.is_empty() {
        return true;
    }

    for (&template_name, constraint) in &method_metadata.where_constraints {
        let actual_template_type = get_specialized_template_type(
            context.codebase,
            template_name,
            defining_class_id,
            class_like_metadata,
            object_type.get_type_parameters(),
        )
        .unwrap_or_else(get_mixed);

        if is_contained_by(
            context.codebase,
            &actual_template_type,
            &constraint.type_union,
            false,
            false,
            false,
            &mut ComparisonResult::default(),
        ) {
            continue;
        }

        let required_constraint_str = constraint.type_union.get_id();
        let actual_template_type_str = actual_template_type.get_id();

        context.collector.report_with_code(
            IssueCode::WhereConstraintViolation,
            Issue::error(format!(
                "Method call violates `@where` constraint for template `{template_name}`.",
            ))
            .with_annotation(
                Annotation::primary(selector.span())
                    .with_message("This method cannot be called here..."),
            )
            .with_annotation(
                Annotation::secondary(object.span())
                    .with_message(format!(
                        "...because this object's template parameter `{template_name}` is type `{actual_template_type_str}`...",
                    )),
            )
            .with_annotation(
                Annotation::secondary(constraint.span)
                    .with_message(format!(
                        "...but this `@where` clause requires it to be `{required_constraint_str}`.",
                    )),
            )
            .with_note(
                "The `@where` tag on a method adds a constraint that must be satisfied by the object's generic types at the time of the call."
            )
            .with_help(
                format!("Ensure the object's template parameter `{template_name}` satisfies the `{required_constraint_str}` constraint before calling this method.")
            ),
        );

        return false;
    }

    true
}

fn report_call_on_non_object<A>(
    context: &mut Context<'_, '_, A>,
    atomic_type: &TAtomic,
    obj_span: Span,
    selector_span: Span,
) where
    A: Arena,
{
    let type_str = atomic_type.get_id();

    context.collector.report_with_code(
        if atomic_type.is_mixed() { IssueCode::MixedMethodAccess } else { IssueCode::InvalidMethodAccess },
        Issue::error(format!("Attempting to access a method on a non-object type (`{type_str}`)."))
            .with_annotation(Annotation::primary(selector_span).with_message("Cannot call method here"))
            .with_annotation(
                Annotation::secondary(obj_span).with_message(format!("This expression has type `{type_str}`")),
            ),
    );
}

fn report_call_on_ambiguous_object<A>(context: &mut Context<'_, '_, A>, obj_span: Span, selector_span: Span)
where
    A: Arena,
{
    context.collector.report_with_code(
        IssueCode::AmbiguousObjectMethodAccess,
        Issue::warning("Cannot statically verify method call on a generic `object` type.")
            .with_annotation(Annotation::primary(selector_span).with_message("Cannot verify this method call"))
            .with_annotation(
                Annotation::secondary(obj_span).with_message("This expression has the general type `object`"),
            )
            .with_help("Provide a more specific type hint for the object for robust analysis."),
    );
}

pub(super) fn report_non_existent_method<A>(
    context: &mut Context<'_, '_, A>,
    obj_span: Span,
    selector_span: Span,
    classname: Word,
    method_name: Word,
) where
    A: Arena,
{
    let classname = display_class_like_name(context, classname);
    let method_name = display_method_name(context, classname, method_name);
    context.collector.report_with_code(
        IssueCode::NonExistentMethod,
        Issue::error(format!("Method `{method_name}` does not exist on type `{classname}`."))
            .with_annotation(Annotation::primary(selector_span).with_message("This method selection is invalid"))
            .with_annotation(
                Annotation::secondary(obj_span).with_message(format!("This expression has type `{classname}`")),
            )
            .with_help(format!("Ensure the `{method_name}` method is defined in the `{classname}` class-like.")),
    );
}

pub(super) fn report_non_documented_method<A>(
    context: &mut Context<'_, '_, A>,
    obj_span: Span,
    selector_span: Span,
    classname: Word,
    method_name: Word,
) where
    A: Arena,
{
    let classname = display_class_like_name(context, classname);
    let method_name = display_method_name(context, classname, method_name);
    context.collector.report_with_code(
        IssueCode::NonDocumentedMethod,
        Issue::warning(format!(
            "Ambiguous method call to `{method_name}` on class `{classname}`."
        ))
        .with_annotation(
            Annotation::primary(selector_span).with_message("This method is not explicitly defined"),
        )
        .with_annotation(
            Annotation::secondary(obj_span).with_message(format!("On an object of type `{classname}`")),
        )
        .with_note(
            "While this call might be handled by `__call()` or `__callStatic()`, Mago cannot verify its arguments or return type without a corresponding `@method` docblock tag.",
        )
        .with_help(format!(
            "To enable full analysis, add a `@method` tag to the docblock of the `{classname}` class. For example: `/** @method returnType {method_name}(argType $argName) */`"
        )),
    );
}

/// Reports a warning when a method is found in a mixin but the target class lacks __call.
/// This is a warning because a subclass might implement __call.
fn report_possibly_non_existent_mixin_method<A>(
    context: &mut Context<'_, '_, A>,
    obj_span: Span,
    selector_span: Span,
    classname: Word,
    method_name: Word,
    mixin_classname: Word,
) where
    A: Arena,
{
    let mixin_classname = display_class_like_name(context, mixin_classname);
    let method_name = display_method_name(context, classname, method_name);
    let classname = display_class_like_name(context, classname);
    context.collector.report_with_code(
        IssueCode::PossiblyNonExistentMethod,
        Issue::warning(format!(
            "Method `{method_name}` might not exist on type `{classname}` at runtime."
        ))
        .with_annotation(
            Annotation::primary(selector_span).with_message("Method might not exist"),
        )
        .with_annotation(
            Annotation::secondary(obj_span).with_message(format!("On an instance of `{classname}`")),
        )
        .with_note(format!(
            "The method `{method_name}` is defined in mixin class `{mixin_classname}`, but `{classname}` does not have a `__call` method to forward the call."
        ))
        .with_note(
            "A subclass of this class could implement `__call` to handle this, so the call might succeed at runtime."
        )
        .with_help(format!(
            "Add a `__call` method to `{classname}`, or make `{classname}` final if this should be an error."
        )),
    );
}

/// Reports an error when a method is found in a mixin but the target final class lacks __call.
/// This is an error because no subclass can exist to implement __call.
fn report_non_existent_mixin_method<A>(
    context: &mut Context<'_, '_, A>,
    obj_span: Span,
    selector_span: Span,
    classname: Word,
    method_name: Word,
    mixin_classname: Word,
) where
    A: Arena,
{
    let mixin_classname = display_class_like_name(context, mixin_classname);
    let method_name = display_method_name(context, classname, method_name);
    let classname = display_class_like_name(context, classname);
    context.collector.report_with_code(
        IssueCode::NonExistentMethod,
        Issue::error(format!(
            "Method `{method_name}` does not exist on final type `{classname}`."
        ))
        .with_annotation(
            Annotation::primary(selector_span).with_message("Method does not exist"),
        )
        .with_annotation(
            Annotation::secondary(obj_span).with_message(format!("On an instance of final class `{classname}`")),
        )
        .with_note(format!(
            "The method `{method_name}` is defined in mixin class `{mixin_classname}`, but `{classname}` is final and does not have a `__call` method to forward the call."
        ))
        .with_help(format!(
            "Add a `__call` method to `{classname}` to handle mixin method calls."
        )),
    );
}

pub(super) fn report_possibly_missing_magic_call<A>(
    context: &mut Context<'_, '_, A>,
    obj_span: Span,
    selector_span: Span,
    classname: Word,
    method_name: Word,
    is_static: bool,
) where
    A: Arena,
{
    let magic_method_name = if is_static { "__callStatic" } else { "__call" };
    let classname = display_class_like_name(context, classname);
    let method_name = display_method_name(context, classname, method_name);

    context.collector.report_with_code(
        IssueCode::PossiblyNonExistentMethod,
        Issue::warning(format!(
            "Call to documented magic method `{method_name}()` on a class that may not handle it."
        ))
        .with_annotation(
            Annotation::primary(selector_span).with_message("This magic method is documented but may not be callable"),
        )
        .with_annotation(
            Annotation::secondary(obj_span)
                .with_message(format!("Class `{classname}` is missing the `{magic_method_name}` method")),
        )
        .with_note(format!(
            "The class `{classname}` has a `@method` tag for `{method_name}` but does not have a `{magic_method_name}` method to handle the call. A subclass could provide `{magic_method_name}` at runtime, so this is only a warning; if `{classname}` were final, this would be a hard error."
        ))
        .with_help(format!(
            "Add a `{magic_method_name}` method to `{classname}`, or make `{classname}` final if calls to `{method_name}` should be rejected outright."
        )),
    );
}

pub(super) fn report_magic_call_without_call_method<A>(
    context: &mut Context<'_, '_, A>,
    obj_span: Span,
    selector_span: Span,
    classname: Word,
    method_name: Word,
    is_static: bool,
) where
    A: Arena,
{
    let magic_method_name = if is_static { "__callStatic" } else { "__call" };
    let classname = display_class_like_name(context, classname);
    let method_name = display_method_name(context, classname, method_name);

    context.collector.report_with_code(
        IssueCode::MissingMagicMethod,
        Issue::error(format!(
            "Call to documented magic method `{method_name}()` on a class that cannot handle it."
        ))
        .with_annotation(
            Annotation::primary(selector_span)
                .with_message("This magic method is documented but cannot be called"),
        )
        .with_annotation(
            Annotation::secondary(obj_span).with_message(format!("Class `{classname}` is missing the `{magic_method_name}` method")),
        )
        .with_note(
            format!("The class `{classname}` has a `@method` tag for `{method_name}` but does not have a `{magic_method_name}` method to handle the call. This will cause a fatal `Error` at runtime.")
        )
        .with_help(
            format!("Add a `{magic_method_name}` method to the `{classname}` class to handle calls to magic methods.")
        ),
    );
}

pub(super) fn report_dynamic_static_method_call<A>(
    context: &mut Context<'_, '_, A>,
    obj_span: Span,
    selector_span: Span,
    classname: Word,
    method_name: Word,
    has_magic_call: bool,
) where
    A: Arena,
{
    let classname = display_class_like_name(context, classname);
    let method_name = display_method_name(context, classname, method_name);
    let mut issue =
        Issue::error(format!("Cannot call magic static method `{classname}::{method_name}` on an instance."))
            .with_annotation(
                Annotation::primary(selector_span)
                    .with_message("This magic method is static and must be called statically"),
            )
            .with_annotation(
                Annotation::secondary(obj_span).with_message(format!("Called on an instance of `{classname}`")),
            );

    if has_magic_call {
        issue = issue
            .with_note(format!(
                "The magic method `{method_name}` is documented as `static` and is intended to be handled by `__callStatic()`."
            ))
            .with_note(
                "However, because it's being called on an instance (`->`), the call will be routed to the existing `__call()` method instead."
            )
            .with_note(
                "This is likely not the intended behavior and may lead to unexpected errors."
            );
    } else {
        issue = issue
            .with_note(
                "Magic methods defined with `@method static` are handled by `__callStatic()`."
            )
            .with_note(
                "When called on an instance (`->`), PHP attempts to route the call to a `__call()` method."
            )
            .with_note(format!(
                "Since the class `{classname}` is missing a `__call()` method, this will cause a fatal `Error` at runtime."
            ));
    }

    context.collector.report_with_code(
        IssueCode::DynamicStaticMethodCall,
        issue.with_help(format!("Call this method statically instead: `{classname}::{method_name}`.")),
    );
}

/// Checks if a type has a known method assertion for the given method name.
///
/// This checks for `HasMethod` types or intersection types containing them.
/// Comparison is case-insensitive since PHP method names are case-insensitive.
fn type_has_method_assertion(object_type: &TObject, method_name: &[u8]) -> bool {
    match object_type {
        TObject::HasMethod(has_method) => {
            if has_method.has_method(method_name) {
                return true;
            }

            has_method.intersection_types.as_ref().is_some_and(|types| {
                types.iter().any(|atomic| {
                    if let TAtomic::Object(obj) = atomic { type_has_method_assertion(obj, method_name) } else { false }
                })
            })
        }
        TObject::HasProperty(has_property) => has_property.intersection_types.as_ref().is_some_and(|types| {
            types.iter().any(|atomic| {
                if let TAtomic::Object(obj) = atomic { type_has_method_assertion(obj, method_name) } else { false }
            })
        }),
        TObject::Named(named_object) => named_object.get_intersection_types().is_some_and(|intersection_types| {
            intersection_types.iter().any(|atomic| {
                if let TAtomic::Object(obj) = atomic { type_has_method_assertion(obj, method_name) } else { false }
            })
        }),
        _ => false,
    }
}

fn collect_mixin_types(
    codebase: &CodebaseMetadata,
    class_metadata: &ClassLikeMetadata,
    outer_object: &TObject,
    mixins: &[TUnion],
) -> Vec<(Word, TObject)> {
    let mut results = Vec::new();
    let mut visited = HashSet::default();
    collect_mixin_types_into(codebase, class_metadata, outer_object, mixins, &mut results, &mut visited);

    results
}

fn collect_mixin_types_into(
    codebase: &CodebaseMetadata,
    class_metadata: &ClassLikeMetadata,
    outer_object: &TObject,
    mixins: &[TUnion],
    results: &mut Vec<(Word, TObject)>,
    visited: &mut HashSet<Word>,
) {
    let mut direct: Vec<(Word, &TObject)> = Vec::new();

    for mixin_type in mixins {
        for mixin_atomic in mixin_type.types.as_ref() {
            match mixin_atomic {
                TAtomic::Object(obj @ TObject::Named(named)) => {
                    direct.push((ascii_lowercase_word(named.name.as_bytes()), obj));
                }
                TAtomic::Object(obj @ TObject::Enum(enum_type)) => {
                    direct.push((ascii_lowercase_word(enum_type.name.as_bytes()), obj));
                }
                TAtomic::GenericParameter(TGenericParameter {
                    parameter_name, constraint, defining_entity, ..
                }) => {
                    let mut resolved = false;

                    if let TObject::Named(named_object) = outer_object
                        && let Some(type_params) = named_object.get_type_parameters()
                        && let GenericParent::ClassLike(defining_class) = defining_entity
                        && named_object.name.as_bytes().eq_ignore_ascii_case(defining_class.as_bytes())
                        && let Some(index) = class_metadata.get_template_index_for_name(*parameter_name)
                        && let Some(concrete_type) = type_params.get(index)
                    {
                        for atomic in concrete_type.types.as_ref() {
                            match atomic {
                                TAtomic::Object(obj @ TObject::Named(named)) => {
                                    direct.push((ascii_lowercase_word(named.name.as_bytes()), obj));
                                    resolved = true;
                                }
                                TAtomic::Object(obj @ TObject::Enum(enum_type)) => {
                                    direct.push((ascii_lowercase_word(enum_type.name.as_bytes()), obj));
                                    resolved = true;
                                }
                                _ => {}
                            }
                        }
                    }

                    if !resolved {
                        for constraint_atomic in constraint.types.as_ref() {
                            match constraint_atomic {
                                TAtomic::Object(obj @ TObject::Named(named)) => {
                                    direct.push((ascii_lowercase_word(named.name.as_bytes()), obj));
                                }
                                TAtomic::Object(obj @ TObject::Enum(enum_type)) => {
                                    direct.push((ascii_lowercase_word(enum_type.name.as_bytes()), obj));
                                }
                                _ => {}
                            }
                        }
                    }
                }
                _ => {}
            }
        }
    }

    for (name, obj) in direct {
        if !visited.insert(name) {
            continue;
        }

        let specialized_obj = specialize_mixin_object(codebase, class_metadata, outer_object, obj);
        let obj = specialized_obj.as_ref().unwrap_or(obj);

        results.push((name, obj.clone()));

        if let Some(mixin_metadata) = codebase.get_class_like(name.as_bytes())
            && !mixin_metadata.mixins.is_empty()
        {
            collect_mixin_types_into(codebase, mixin_metadata, obj, &mixin_metadata.mixins, results, visited);
        }
    }
}

/// Substitutes the carrier class's template parameters inside a mixin tag's type
/// arguments (`@mixin Builder<TItem>`) with the receiver's actual type arguments.
fn specialize_mixin_object(
    codebase: &CodebaseMetadata,
    carrier_metadata: &ClassLikeMetadata,
    carrier_object: &TObject,
    mixin_object: &TObject,
) -> Option<TObject> {
    let TObject::Named(named) = mixin_object else {
        return None;
    };

    let parameters = named.type_parameters.as_deref()?;

    if !parameters.iter().any(|parameter| parameter.has_template_types()) {
        return None;
    }

    let TObject::Named(carrier) = carrier_object else {
        return None;
    };

    let carrier_parameters = carrier.type_parameters.as_ref()?;
    let mut named = named.clone();
    named.type_parameters = Some(
        parameters
            .iter()
            .map(|parameter| {
                super::class_template_type_collector::resolve_template_parameter(
                    codebase,
                    parameter,
                    carrier_metadata,
                    carrier_parameters,
                )
                .unwrap_or_else(|| parameter.clone())
            })
            .collect(),
    );

    Some(TObject::Named(named))
}