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
use mago_allocator::Arena;
use std::sync::Arc;

use mago_word::Word;
use mago_word::ascii_lowercase_word;
use mago_word::word;

use mago_codex::identifier::method::MethodIdentifier;
use mago_codex::metadata::class_like::ClassLikeMetadata;
use mago_codex::ttype::atomic::TAtomic;
use mago_codex::ttype::atomic::generic::TGenericParameter;
use mago_codex::ttype::atomic::object::TObject;
use mago_codex::ttype::atomic::object::r#enum::TEnum;
use mago_codex::ttype::atomic::object::named::TNamedObject;
use mago_codex::ttype::expander::StaticClassType;
use mago_codex::ttype::get_specialized_template_type;
use mago_codex::ttype::union::TUnion;
use mago_codex::ttype::wrap_atomic;
use mago_php_version::feature::Feature;
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 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::ResolutionOrigin;
use crate::resolver::class_name::ResolvedClassname;
use crate::resolver::class_name::resolve_classnames_from_expression;
use crate::resolver::method::MethodResolutionResult;
use crate::resolver::method::ResolvedMethod;
use crate::resolver::method::report_magic_call_without_call_method;
use crate::resolver::method::report_non_documented_method;
use crate::resolver::method::report_non_existent_method;
use crate::resolver::method::report_possibly_missing_magic_call;
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;

/// Resolves all possible static method targets from a class expression and a member selector.
///
/// This utility handles the logic for `ClassName::method` by:
/// 1. Resolving the `ClassName` expression to get all possible class types.
/// 2. Resolving the `method` selector to get potential method names.
/// 3. Finding matching methods and validating them against static access rules.
/// 4. Reporting issues like calling a non-static method, or calling a method on an interface.
pub fn resolve_static_method_targets<'ctx, 'ast, 'arena, A>(
    context: &mut Context<'ctx, 'arena, A>,
    block_context: &mut BlockContext<'ctx>,
    artifacts: &mut AnalysisArtifacts,
    class_expr: &'ast Expression<'arena>,
    method_selector: &'ast ClassLikeMemberSelector<'arena>,
    access_span: Span,
) -> Result<MethodResolutionResult, AnalysisError>
where
    A: Arena,
{
    let mut result = MethodResolutionResult::default();

    let class_resolutions = resolve_classnames_from_expression(context, block_context, artifacts, class_expr, false)?;
    if let Some(class_type) = artifacts.get_expression_type(class_expr)
        && class_type.is_nullable()
    {
        result.encountered_null = true;
    }
    let selector_resolutions = resolve_member_selector(context, block_context, artifacts, method_selector)?;

    let mut method_names = vec![];
    for selector in &selector_resolutions {
        if selector.is_dynamic() {
            result.has_dynamic_selector = true;
        }
        if let Some(name) = selector.name() {
            method_names.push(name);
        } else {
            result.has_invalid_target = true;
        }
    }

    for resolved_classname in &class_resolutions {
        if resolved_classname.is_possibly_invalid() {
            result.has_ambiguous_target = true;
            if resolved_classname.origin == ResolutionOrigin::Invalid {
                result.has_invalid_target = true;
            }

            continue;
        }

        for method_name in &method_names {
            let resolved_methods = resolve_method_from_classname(
                context,
                block_context,
                block_context.scope.get_class_like(),
                *method_name,
                class_expr.span(),
                method_selector.span(),
                resolved_classname,
                &mut result,
                method_selector,
                access_span,
            );

            result.resolved_methods.extend(resolved_methods);
        }
    }

    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)
}

fn resolve_method_from_classname<'ctx, 'arena, A>(
    context: &mut Context<'ctx, 'arena, A>,
    block_context: &BlockContext<'ctx>,
    current_class_metadata: Option<&'ctx ClassLikeMetadata>,
    method_name: Word,
    class_span: Span,
    method_span: Span,
    classname: &ResolvedClassname,
    result: &mut MethodResolutionResult,
    selector: &ClassLikeMemberSelector<'arena>,
    access_span: Span,
) -> Vec<ResolvedMethod>
where
    A: Arena,
{
    let mut resolve_method_from_class_id =
        |fq_class_id: Word,
         is_relative: bool,
         from_instance: bool,
         from_class_string: bool,
         method_name: Word,
         has_magic_static_call: bool,
         result: Option<&mut MethodResolutionResult>| {
            let Some(defining_class_metadata) = context.codebase.get_class_like(fq_class_id.as_bytes()) else {
                return (false, None);
            };

            if !from_instance && !is_relative && defining_class_metadata.kind.is_interface() && !has_magic_static_call {
                report_static_call_on_interface(
                    context,
                    defining_class_metadata.original_name,
                    class_span,
                    from_class_string,
                );

                if !from_class_string {
                    if let Some(result) = result {
                        result.has_invalid_target = true;
                    }
                    return (true, None);
                }
            }

            let Some(method) = resolve_method_from_metadata(
                context,
                block_context,
                current_class_metadata,
                method_name,
                fq_class_id,
                defining_class_metadata,
                classname,
                result,
                selector,
                access_span,
                class_span,
                has_magic_static_call,
            ) else {
                return (false, None);
            };

            if !method.is_static
                && !is_relative
                && !current_class_metadata.is_some_and(|current_class_metadata| {
                    current_class_metadata.name == defining_class_metadata.name
                        || current_class_metadata.has_parent(defining_class_metadata.name)
                })
            {
                report_non_static_access(context, &method.method_identifier, method_span);
                return (true, None);
            }

            if !from_instance
                && !is_relative
                && method.is_static
                && defining_class_metadata.kind.is_trait()
                && context.settings.version.is_deprecated(Feature::CallStaticMethodOnTrait)
            {
                report_deprecated_static_access_on_trait(context, defining_class_metadata.original_name, class_span);
            }

            (true, Some(method))
        };

    let mut resolved_methods = vec![];
    let mut could_method_ever_exist = false;
    let mut first_class_id = None;
    let mut magic_call_could_exist = false;

    let magic_method_to_check = if classname.is_parent() { word("__call") } else { word("__callStatic") };
    if let Some(fq_class_id) = classname.fqcn {
        let (_, resolved_magic_call_method) = resolve_method_from_class_id(
            fq_class_id,
            classname.is_relative(),
            classname.is_object_instance(),
            classname.is_from_class_string(),
            magic_method_to_check,
            true,
            None,
        );

        magic_call_could_exist |= resolved_magic_call_method.is_some();

        let (could_method_exist, resolved_method) = resolve_method_from_class_id(
            fq_class_id,
            classname.is_relative(),
            classname.is_object_instance(),
            classname.is_from_class_string(),
            method_name,
            resolved_magic_call_method.is_some(),
            Some(result),
        );

        if let Some(resolved_method) = resolved_method {
            resolved_methods.push(resolved_method);
        }

        could_method_ever_exist |= could_method_exist;
        first_class_id = Some(fq_class_id);
    }

    for intersection in &classname.intersections {
        let Some(fq_class_id) = intersection.fqcn else {
            continue;
        };

        let (_, resolved_magic_call_method) = resolve_method_from_class_id(
            fq_class_id,
            intersection.is_relative() || classname.is_relative(),
            intersection.is_object_instance() || classname.is_object_instance(),
            intersection.is_from_class_string(),
            magic_method_to_check,
            true,
            None,
        );

        magic_call_could_exist |= resolved_magic_call_method.is_some();

        let (could_method_exist, resolved_method) = resolve_method_from_class_id(
            fq_class_id,
            intersection.is_relative() || classname.is_relative(),
            intersection.is_object_instance() || classname.is_object_instance(),
            intersection.is_from_class_string(),
            method_name,
            resolved_magic_call_method.is_some(),
            Some(result),
        );

        if let Some(resolved_method) = resolved_method {
            resolved_methods.push(resolved_method);
        }

        could_method_ever_exist |= could_method_exist;
        if first_class_id.is_none() {
            first_class_id = Some(fq_class_id);
        }
    }

    // If method not found, try to find in mixins
    if resolved_methods.is_empty()
        && let Some(fq_class_id) = first_class_id
        && let Some(class_metadata) = context.codebase.get_class_like(fq_class_id.as_bytes())
        && !class_metadata.mixins.is_empty()
        // Try to find method in mixin types
        && let Some(resolved_method) = find_static_method_in_mixins(
            context,
            block_context,
            &class_metadata.mixins,
            method_name,
            selector,
            access_span,
        )
    {
        if magic_call_could_exist {
            resolved_methods.push(resolved_method);
        } else {
            if class_metadata.flags.is_final() {
                report_non_existent_mixin_static_method(
                    context,
                    class_span,
                    method_span,
                    fq_class_id,
                    method_name,
                    resolved_method.classname,
                );

                result.has_invalid_target = true;
            } else {
                report_possibly_non_existent_mixin_static_method(
                    context,
                    class_span,
                    method_span,
                    fq_class_id,
                    method_name,
                    resolved_method.classname,
                );
            }

            resolved_methods.push(resolved_method);
        }
    }

    if resolved_methods.is_empty() {
        if let Some(fq_class_id) = first_class_id {
            result.has_invalid_target = true;

            if !could_method_ever_exist {
                if magic_call_could_exist {
                    report_non_documented_method(context, class_span, method_span, fq_class_id, method_name);
                } else {
                    report_non_existent_method(context, class_span, method_span, fq_class_id, method_name);
                }
            }
        } else {
            result.has_ambiguous_target = true;
        }
    }

    resolved_methods
}

fn resolve_method_from_metadata<'ctx, 'arena, A>(
    context: &mut Context<'ctx, 'arena, A>,
    block_context: &BlockContext<'ctx>,
    current_class_metadata: Option<&'ctx ClassLikeMetadata>,
    method_name: Word,
    fq_class_id: Word,
    defining_class_metadata: &'ctx ClassLikeMetadata,
    classname: &ResolvedClassname,
    result: Option<&mut MethodResolutionResult>,
    selector: &ClassLikeMemberSelector<'arena>,
    access_span: Span,
    class_span: Span,
    has_magic_static_call: bool,
) -> Option<ResolvedMethod>
where
    A: Arena,
{
    let method_id = MethodIdentifier::new(defining_class_metadata.original_name, method_name);
    let declaring_method_id = context.codebase.get_declaring_method_identifier(&method_id);
    let (declaring_method_id, function_like) = match context.codebase.get_method_by_id(&declaring_method_id) {
        Some(fl) => (declaring_method_id, fl),
        None => {
            let mut found = None;
            for required_class in
                defining_class_metadata.require_extends.iter().chain(defining_class_metadata.require_implements.iter())
            {
                let Some(required_metadata) = context.codebase.get_class_like(required_class.as_bytes()) else {
                    continue;
                };
                let req_method_id = MethodIdentifier::new(required_metadata.original_name, method_name);
                let req_declaring_id = context.codebase.get_declaring_method_identifier(&req_method_id);
                if let Some(fl) = context.codebase.get_method_by_id(&req_declaring_id) {
                    found = Some((req_declaring_id, fl));
                    break;
                }
            }

            found?
        }
    };

    if let Some(result) = result
        && !check_method_visibility(
            context,
            block_context,
            method_id.get_class_name().as_bytes(),
            method_id.get_method_name().as_bytes(),
            access_span,
            Some(selector.span()),
        )
    {
        result.has_invalid_target = true;
    }

    if function_like.flags.is_magic_method()
        && !has_magic_static_call
        && !defining_class_metadata.kind.is_interface()
        && !has_real_ancestor_method(context, block_context, defining_class_metadata, method_name)
    {
        let is_static = !classname.is_parent();

        if defining_class_metadata.flags.is_final() && !defining_class_metadata.flags.is_abstract() {
            report_magic_call_without_call_method(
                context,
                class_span,
                selector.span(),
                method_id.get_class_name(),
                method_name,
                is_static,
            );
        } else {
            report_possibly_missing_magic_call(
                context,
                class_span,
                selector.span(),
                method_id.get_class_name(),
                method_name,
                is_static,
            );
        }
    }

    let static_class_type = if let Some(current_class_metadata) = current_class_metadata
        && classname.is_relative()
    {
        let object = get_metadata_object(context, current_class_metadata, current_class_metadata);

        StaticClassType::Object(object)
    } else if defining_class_metadata.kind.is_enum() {
        StaticClassType::Object(TObject::Enum(TEnum { name: defining_class_metadata.original_name, case: None }))
    } else if !classname.intersections.is_empty() {
        if let TAtomic::Object(object) = classname.get_object_type(context.codebase) {
            StaticClassType::Object(object)
        } else {
            StaticClassType::Name(fq_class_id)
        }
    } else {
        StaticClassType::Name(fq_class_id)
    };

    // Get the class it was called on - need original name for callable creation
    let called_on_class_metadata = context.codebase.get_class_like(fq_class_id.as_bytes())?;

    Some(ResolvedMethod {
        // Use the original name of the class it was called on
        // This is important for first-class callables with static return types
        classname: called_on_class_metadata.original_name,
        method_identifier: declaring_method_id,
        static_class_type,
        declaring_object: None,
        is_static: function_like.method_metadata.as_ref().is_some_and(|m| m.is_static),
        mixin_without_magic_method: None,
    })
}

fn get_metadata_object<'ctx, A>(
    context: &Context<'ctx, '_, A>,
    class_like_metadata: &'ctx ClassLikeMetadata,
    current_class_metadata: &'ctx ClassLikeMetadata,
) -> TObject
where
    A: Arena,
{
    if class_like_metadata.kind.is_enum() {
        return TObject::Enum(TEnum { name: class_like_metadata.original_name, case: None });
    }

    let mut intersections = vec![];
    for required_interface in &class_like_metadata.require_implements {
        let Some(interface_metadata) = context.codebase.get_interface(required_interface.as_bytes()) else {
            continue;
        };

        let TObject::Named(mut interface_type) =
            get_metadata_object(context, interface_metadata, current_class_metadata)
        else {
            continue;
        };

        let interface_intersactions = std::mem::take(&mut interface_type.intersection_types);

        interface_type.is_static = false;
        interface_type.is_this = false;
        intersections.push(TAtomic::Object(TObject::Named(interface_type)));
        if let Some(interface_intersactions) = interface_intersactions {
            intersections.extend(interface_intersactions);
        }
    }

    for required_class in &class_like_metadata.require_extends {
        let Some(parent_class_metadata) = context.codebase.get_class_like(required_class.as_bytes()) else {
            continue;
        };

        let TObject::Named(mut parent_type) =
            get_metadata_object(context, parent_class_metadata, current_class_metadata)
        else {
            continue;
        };

        let parent_intersections = std::mem::take(&mut parent_type.intersection_types);

        parent_type.is_static = false;
        parent_type.is_this = false;
        intersections.push(TAtomic::Object(TObject::Named(parent_type)));
        if let Some(parent_intersections) = parent_intersections {
            intersections.extend(parent_intersections);
        }
    }

    TObject::Named(TNamedObject {
        name: class_like_metadata.original_name,
        type_parameters: if class_like_metadata.template_types.is_empty() {
            None
        } else {
            Some(
                class_like_metadata
                    .template_types
                    .iter()
                    .map(|(&parameter_name, template)| {
                        if let Some(parameter) = get_specialized_template_type(
                            context.codebase,
                            parameter_name,
                            class_like_metadata.name,
                            current_class_metadata,
                            None,
                        ) {
                            parameter
                        } else {
                            let defining_entity = &template.defining_entity;
                            let constraint = &template.constraint;

                            wrap_atomic(TAtomic::GenericParameter(TGenericParameter {
                                parameter_name,
                                constraint: Arc::new(constraint.clone()),
                                defining_entity: *defining_entity,
                                intersection_types: None,
                            }))
                        }
                    })
                    .collect::<Vec<_>>(),
            )
        },
        variances: None,
        is_static: true,
        is_this: true,
        intersection_types: if intersections.is_empty() { None } else { Some(intersections) },
        remapped_parameters: false,
    })
}

/// Returns `true` if any ancestor class or used trait provides a real, non-magic implementation
/// of `method_name` that is accessible from the current scope.
///
/// An `@method` tag may shadow such an inherited method (e.g. to refine its return type); the
/// call is then backed by a real implementation, so no `__callStatic` is required. Traits are
/// consulted directly because an ancestor's method slot may itself hold a pseudo-method even
/// though a used trait provides the real one. Inaccessible methods don't count: PHP routes those
/// calls through `__callStatic`, so the magic handler is still required.
fn has_real_ancestor_method<'ctx, A>(
    context: &Context<'ctx, '_, A>,
    block_context: &BlockContext<'ctx>,
    class_metadata: &ClassLikeMetadata,
    method_name: Word,
) -> bool
where
    A: Arena,
{
    let method_name_lc = ascii_lowercase_word(method_name.as_bytes());

    class_metadata.all_parent_classes.iter().chain(class_metadata.used_traits.iter()).any(|ancestor_name| {
        context.codebase.get_class_like(ancestor_name.as_bytes()).is_some_and(|ancestor| {
            ancestor.declaring_method_ids.get(&method_name_lc).is_some_and(|declaring_id| {
                context.codebase.get_method_by_id(declaring_id).is_some_and(|m| !m.flags.is_magic_method())
                    && is_method_visible(context, block_context, ancestor_name.as_bytes(), method_name_lc.as_bytes())
            })
        })
    })
}

fn report_non_static_access<A>(context: &mut Context<'_, '_, A>, method_id: &MethodIdentifier, span: Span)
where
    A: Arena,
{
    let class_lower = method_id.get_class_name();
    let method_lower = method_id.get_method_name();
    let class_name = display_class_like_name(context, class_lower);
    let method_name = display_method_name(context, class_lower, method_lower);

    context.collector.report_with_code(
        IssueCode::InvalidStaticMethodAccess,
        Issue::error(format!("Cannot call non-static method `{class_name}::{method_name}` statically."))
            .with_annotation(Annotation::primary(span).with_message("This is a non-static method"))
            .with_help("To call this method, you must first create an instance of the class (e.g., `$obj = new MyClass(); $obj->method();`)."),
    );
}

fn report_static_call_on_interface<A>(context: &mut Context<'_, '_, A>, name: Word, span: Span, from_class_string: bool)
where
    A: Arena,
{
    let name = display_class_like_name(context, name);
    if from_class_string {
        context.collector.report_with_code(
            IssueCode::PossiblyStaticAccessOnInterface,
            Issue::warning(format!("Potential static method call on interface `{name}` via `class-string`."))
                .with_annotation(
                    Annotation::primary(span)
                        .with_message("This `class-string` could resolve to an interface name at runtime"),
                )
                .with_note(
                    format!("While a `class-string<{name}>` can hold a concrete class name (which is valid), it can also hold the interface name itself, which would cause a fatal error.")
                )
                .with_help("Ensure the variable or expression always holds the name of a concrete class, not an interface."),
        );
    } else {
        context.collector.report_with_code(
            IssueCode::StaticAccessOnInterface,
            Issue::error(format!("Cannot call a static method directly on an interface (`{name}`)."))
                .with_annotation(Annotation::primary(span).with_message("This is a direct static call on an interface"))
                .with_note(
                    "Static methods belong to classes that implement behavior, not interfaces that only define contracts.",
                )
                .with_help("Call this method on a concrete class that implements this interface instead."),
        );
    }
}

fn report_deprecated_static_access_on_trait<A>(context: &mut Context<'_, '_, A>, name: Word, span: Span)
where
    A: Arena,
{
    let name = display_class_like_name(context, name);
    context.collector.report_with_code(
        IssueCode::DeprecatedFeature,
        Issue::warning(format!("Calling static methods directly on traits (`{name}`) is deprecated."))
            .with_annotation(Annotation::primary(span).with_message("This is a trait"))
            .with_help("Static methods should be called on a class that uses the trait."),
    );
}

/// Reports a warning when a static method is found in a mixin but the target class lacks __callStatic.
/// This is a warning because a subclass might implement __callStatic.
fn report_possibly_non_existent_mixin_static_method<A>(
    context: &mut Context<'_, '_, A>,
    class_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!(
            "Static 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(class_span).with_message(format!("On class `{classname}`")),
        )
        .with_note(format!(
            "The method `{method_name}` is defined in mixin class `{mixin_classname}`, but `{classname}` does not have a `__callStatic` method to forward the call."
        ))
        .with_note(
            "A subclass of this class could implement `__callStatic` to handle this, so the call might succeed at runtime."
        )
        .with_help(format!(
            "Add a `__callStatic` method to `{classname}`, or make `{classname}` final if this should be an error."
        )),
    );
}

/// Reports an error when a static method is found in a mixin but the target final class lacks __callStatic.
/// This is an error because no subclass can exist to implement __callStatic.
fn report_non_existent_mixin_static_method<A>(
    context: &mut Context<'_, '_, A>,
    class_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!(
            "Static 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(class_span).with_message(format!("On 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 `__callStatic` method to forward the call."
        ))
        .with_help(format!(
            "Add a `__callStatic` method to `{classname}` to handle mixin method calls."
        )),
    );
}

/// Searches for a static method in mixin types.
/// Returns Some(ResolvedMethod) if found, None otherwise.
///
/// Note: For static method calls, we cannot resolve generic mixin types (e.g., `@mixin T`)
/// to concrete types because static calls don't have an instance with type parameters.
/// In such cases, we fall back to using the constraint type.
fn find_static_method_in_mixins<'ctx, 'arena, A>(
    context: &mut Context<'ctx, 'arena, A>,
    block_context: &BlockContext<'ctx>,
    mixins: &[TUnion],
    method_name: Word,
    selector: &ClassLikeMemberSelector<'arena>,
    access_span: Span,
) -> Option<ResolvedMethod>
where
    A: Arena,
{
    for mixin_type in mixins {
        for mixin_atomic in mixin_type.types.as_ref() {
            match mixin_atomic {
                TAtomic::Object(TObject::Named(named)) => {
                    if let Some(result) = find_static_method_in_single_mixin(
                        context,
                        block_context,
                        named.name,
                        method_name,
                        selector,
                        access_span,
                    ) {
                        return Some(result);
                    }
                }
                TAtomic::Object(TObject::Enum(enum_type)) => {
                    if let Some(result) = find_static_method_in_single_mixin(
                        context,
                        block_context,
                        enum_type.name,
                        method_name,
                        selector,
                        access_span,
                    ) {
                        return Some(result);
                    }
                }
                TAtomic::GenericParameter(TGenericParameter { constraint, .. }) => {
                    // For static calls, we cannot resolve generic parameters since there's no instance.
                    // Fall back to using the constraint type.
                    for constraint_atomic in constraint.types.as_ref() {
                        let constraint_class_name = match constraint_atomic {
                            TAtomic::Object(TObject::Named(named)) => named.name,
                            TAtomic::Object(TObject::Enum(enum_type)) => enum_type.name,
                            _ => continue,
                        };

                        if let Some(result) = find_static_method_in_single_mixin(
                            context,
                            block_context,
                            constraint_class_name,
                            method_name,
                            selector,
                            access_span,
                        ) {
                            return Some(result);
                        }
                    }
                }
                _ => {}
            }
        }
    }

    None
}

/// Searches for a static method in a single mixin class.
fn find_static_method_in_single_mixin<'ctx, 'arena, A>(
    context: &mut Context<'ctx, 'arena, A>,
    block_context: &BlockContext<'ctx>,
    mixin_class_name: Word,
    method_name: Word,
    selector: &ClassLikeMemberSelector<'arena>,
    access_span: Span,
) -> Option<ResolvedMethod>
where
    A: Arena,
{
    let mixin_metadata = context.codebase.get_class_like(mixin_class_name.as_bytes())?;

    let method_id = MethodIdentifier::new(mixin_metadata.original_name, method_name);
    let declaring_method_id = context.codebase.get_declaring_method_identifier(&method_id);
    let function_like = context.codebase.get_method_by_id(&declaring_method_id)?;

    // Mixin methods should only be accessible if public
    if let Some(method_metadata) = &function_like.method_metadata
        && !method_metadata.visibility.is_public()
    {
        return None;
    }

    // Check visibility
    if !check_method_visibility(
        context,
        block_context,
        method_id.get_class_name().as_bytes(),
        method_id.get_method_name().as_bytes(),
        access_span,
        Some(selector.span()),
    ) {
        return None;
    }

    let static_class_type = if mixin_metadata.kind.is_enum() {
        StaticClassType::Object(TObject::Enum(TEnum { name: mixin_metadata.original_name, case: None }))
    } else {
        StaticClassType::Name(mixin_class_name)
    };

    Some(ResolvedMethod {
        classname: mixin_metadata.original_name,
        method_identifier: declaring_method_id,
        static_class_type,
        declaring_object: None,
        is_static: function_like.method_metadata.as_ref().is_some_and(|m| m.is_static),
        mixin_without_magic_method: None,
    })
}