mago-analyzer 1.6.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
use std::rc::Rc;

use mago_atom::Atom;
use mago_atom::concat_atom;
use mago_codex::ttype::add_optional_union_type;
use mago_codex::ttype::get_mixed;
use mago_codex::ttype::get_never;
use mago_codex::ttype::get_null;
use mago_span::HasSpan;
use mago_span::Span;
use mago_syntax::ast::ClassLikeMemberSelector;
use mago_syntax::ast::Expression;
use mago_syntax::ast::NullSafePropertyAccess;
use mago_syntax::ast::PropertyAccess;
use mago_syntax::ast::Variable;

use crate::analyzable::Analyzable;
use crate::artifacts::AnalysisArtifacts;
use crate::context::Context;
use crate::context::block::BlockContext;
use crate::error::AnalysisError;
use crate::resolver::property::resolve_instance_properties;
use crate::utils::expression::get_expression_id;
use crate::utils::expression::get_property_access_expression_id;

impl<'ast, 'arena> Analyzable<'ast, 'arena> for PropertyAccess<'arena> {
    fn analyze<'ctx>(
        &'ast self,
        context: &mut Context<'ctx, 'arena>,
        block_context: &mut BlockContext<'ctx>,
        artifacts: &mut AnalysisArtifacts,
    ) -> Result<(), AnalysisError> {
        analyze_property_access(
            context,
            block_context,
            artifacts,
            self.span(),
            self.object,
            self.arrow.span(),
            &self.property,
            false,
        )
    }
}

impl<'ast, 'arena> Analyzable<'ast, 'arena> for NullSafePropertyAccess<'arena> {
    fn analyze<'ctx>(
        &'ast self,
        context: &mut Context<'ctx, 'arena>,
        block_context: &mut BlockContext<'ctx>,
        artifacts: &mut AnalysisArtifacts,
    ) -> Result<(), AnalysisError> {
        analyze_property_access(
            context,
            block_context,
            artifacts,
            self.span(),
            self.object,
            self.question_mark_arrow.span(),
            &self.property,
            true,
        )
    }
}

#[inline]
fn analyze_property_access<'ctx, 'ast, 'arena>(
    context: &mut Context<'ctx, 'arena>,
    block_context: &mut BlockContext<'ctx>,
    artifacts: &mut AnalysisArtifacts,
    span: Span,
    object: &'ast Expression<'arena>,
    arrow_span: Span,
    property_selector: &'ast ClassLikeMemberSelector<'arena>,
    is_null_safe: bool,
) -> Result<(), AnalysisError> {
    let property_access_id = get_property_access_expression_id(
        object,
        property_selector,
        is_null_safe,
        block_context.scope.get_class_like_name(),
        context.resolved_names,
        Some(context.codebase),
    );

    if context.settings.memoize_properties
        && let Some(property_access_id) = &property_access_id
        && let Some(existing_type) = block_context.locals.get(property_access_id).cloned()
    {
        add_memoized_property_reference(context, block_context, artifacts, object, property_selector)?;

        artifacts.set_rc_expression_type(&span, existing_type);

        return Ok(());
    }

    let resolution_result = resolve_instance_properties(
        context,
        block_context,
        artifacts,
        object,
        property_selector,
        arrow_span,
        is_null_safe,
        false, // `for_assignment`
    )?;

    let mut resulting_expression_type = None;
    if !resolution_result.has_error_path {
        for resolved_property in resolution_result.properties {
            resulting_expression_type = Some(add_optional_union_type(
                resolved_property.property_type,
                resulting_expression_type.as_ref(),
                context.codebase,
            ));
        }

        if resolution_result.has_ambiguous_path
            || resolution_result.encountered_mixed
            || resolution_result.has_possibly_defined_property
        {
            resulting_expression_type =
                Some(add_optional_union_type(get_mixed(), resulting_expression_type.as_ref(), context.codebase));
        }

        if resolution_result.has_invalid_path || resolution_result.encountered_null {
            resulting_expression_type =
                Some(add_optional_union_type(get_null(), resulting_expression_type.as_ref(), context.codebase));
        }
    }

    let mut resulting_type = resulting_expression_type.unwrap_or_else(get_never);

    if is_null_safe
        && let Some(var_id) = get_expression_id(
            object,
            block_context.scope.get_class_like_name(),
            context.resolved_names,
            Some(context.codebase),
        )
    {
        artifacts
            .true_branch_only_assertions
            .entry((span.start.offset, span.end.offset))
            .or_default()
            .entry(var_id)
            .or_default()
            .push(vec![mago_codex::assertion::Assertion::IsNotType(mago_codex::ttype::atomic::TAtomic::Null)]);
    }

    let object_has_nullsafe_null = artifacts.get_expression_type(object).is_some_and(|t| t.has_nullsafe_null());
    if resolution_result.all_properties_non_nullable
        && ((is_null_safe && resolution_result.encountered_null) || object_has_nullsafe_null)
    {
        resulting_type.set_nullsafe_null(true);
    }

    let resulting_type = Rc::new(resulting_type);
    if let Some(property_access_id) = property_access_id {
        block_context.locals.insert(property_access_id, resulting_type.clone());
    }

    artifacts.set_rc_expression_type(&span, resulting_type);

    Ok(())
}

/// Adds symbol reference for a memoized property access.
///
/// When property access is memoized, we still need to track the symbol reference
/// so that unused property detection works correctly.
fn add_memoized_property_reference<'ctx, 'ast, 'arena>(
    context: &mut Context<'ctx, 'arena>,
    block_context: &mut BlockContext<'ctx>,
    artifacts: &mut AnalysisArtifacts,
    object: &'ast Expression<'arena>,
    property_selector: &'ast ClassLikeMemberSelector<'arena>,
) -> Result<(), AnalysisError> {
    let property_name = match property_selector {
        ClassLikeMemberSelector::Identifier(ident) => concat_atom!("$", ident.value),
        _ => return Ok(()),
    };

    let is_this = matches!(object, Expression::Variable(Variable::Direct(var)) if var.name == "$this");
    let mut declaring_classes: Vec<Atom> = Vec::new();

    if is_this {
        if let Some(class_name) = block_context.scope.get_class_like_name()
            && let Some(declaring_class) = context.codebase.get_declaring_property_class(&class_name, &property_name)
        {
            declaring_classes.push(declaring_class);
        }
    } else if let Some(object_type) = artifacts.get_rc_expression_type(object) {
        for atomic in object_type.types.iter() {
            for class_name in atomic.get_all_object_names() {
                if let Some(declaring_class) =
                    context.codebase.get_declaring_property_class(&class_name, &property_name)
                {
                    declaring_classes.push(declaring_class);
                }
            }
        }
    }

    // Add references (after releasing the immutable borrow)
    for declaring_class in declaring_classes {
        artifacts.symbol_references.add_reference_for_property_read(
            &block_context.scope,
            declaring_class,
            property_name,
        );
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use indoc::indoc;

    use crate::code::IssueCode;
    use crate::test_analysis;

    test_analysis! {
        name = accessing_generic_property,
        code = indoc! {r"
            <?php

            /**
             * @template K
             * @template V
             */
            class Collection
            {
                /**
                 * @var array<K, V>
                 */
                public $items = [];
            }

            /**
             * @param Collection<int, non-empty-string> $collection
             *
             * @return null|non-empty-string
             */
            function read_entries(Collection $collection, int $key): null|string {
                return $collection->items[$key] ?? null;
            }
        "}
    }

    test_analysis! {
        name = accessing_string_enum_properties,
        code = indoc! {r"
            <?php

            enum Color: string {
                case Red = 'red';
                case Green = 'green';
                case Blue = 'blue';
            }

            /**
             * @return 'Red'|'Green'|'Blue'
             */
            function get_color_name(Color $color): string {
                return $color->name;
            }

            /**
             * @return 'red'|'green'|'blue'
             */
            function get_color_value(Color $color): string {
                return $color->value;
            }

            /**
             * @return 'Red'
             */
            function get_specific_case_name(): string {
                return Color::Red->name;
            }

            /**
             * @return 'red'
             */
            function get_specific_case_value(): string {
                return Color::Red->value;
            }
        "}
    }

    test_analysis! {
        name = accessing_int_enum_properties,
        code = indoc! {r"
            <?php

            enum Color: int {
                case Red = 0;
                case Green = 1;
                case Blue = 2;
            }

            /**
             * @return 'Red'|'Green'|'Blue'
             */
            function get_color_name(Color $color): string {
                return $color->name;
            }

            /**
             * @return 0|1|2
             */
            function get_color_value(Color $color): int {
                return $color->value;
            }

            /**
             * @return 'Red'
             */
            function get_specific_case_name(): string {
                return Color::Red->name;
            }

            /**
             * @return 0
             */
            function get_specific_case_value(): int {
                return Color::Red->value;
            }
        "}
    }

    test_analysis! {
        name = accessing_enum_properties,
        code = indoc! {r"
            <?php

            enum Color {
                case Red;
                case Green;
                case Blue;
            }

            /**
             * @return 'Red'|'Green'|'Blue'
             */
            function get_color_name(Color $color): string {
                return $color->name;
            }

            /**
             * @return 'Red'
             */
            function get_specific_case_name(): string {
                return Color::Red->name;
            }
        "}
    }

    test_analysis! {
        name = redundant_nullsafe_property_access,
        code = indoc! {r"
            <?php

            class Foo {
                public string $bar = '';
            }

            function test(Foo $foo): void {
                echo $foo?->bar;
            }
        "},
        issues = [
            IssueCode::RedundantNullsafeOperator,
        ]
    }

    test_analysis! {
        name = accessing_property_on_null,
        code = indoc! {r"
            <?php

            class Foo {
                public string $bar = '';
            }

            function test(?Foo $foo): void {
                echo $foo->bar;
            }
        "},
        issues = [
            IssueCode::PossiblyNullPropertyAccess,
        ]
    }

    test_analysis! {
        name = accessing_property_on_null_inside_coalescing,
        code = indoc! {r"
            <?php

            class Foo {
                public string $bar = '';
            }

            function test(?Foo $foo): void {
                $bar = $foo->bar ?? 'default';

                echo $bar;
            }
        "},
    }

    test_analysis! {
        name = accessing_property_on_null_inside_isset,
        code = indoc! {r#"
            <?php

            class Foo {
                public string $bar = '';
            }

            function test(?Foo $foo): void {
                if (isset($foo->bar)) {
                    echo "Property exists";
                }
            }
        "#},
    }

    test_analysis! {
        name = accessing_property_on_nullsafe,
        code = indoc! {r"
            <?php

            class Foo {
                public string $bar = '';
            }

            function test(?Foo $foo): void {
                echo $foo?->bar;
            }
        "},
        issues = []
    }

    test_analysis! {
        name = accessing_property_on_mixed,
        code = indoc! {r"
            <?php

            function test(mixed $value): void {
                echo $value->bar;
            }
        "},
        issues = [
            IssueCode::MixedPropertyAccess,
            IssueCode::MixedArgument,
        ]
    }

    test_analysis! {
        name = accessing_property_on_non_object,
        code = indoc! {r"
            <?php

            function test(int $value): void {
                echo $value->bar;
            }
        "},
        issues = [
            IssueCode::InvalidPropertyAccess,
        ]
    }

    test_analysis! {
        name = accessing_non_existent_property,
        code = indoc! {r"
            <?php

            class Foo {
                public string $bar = '';
            }

            function i_take_null(null $_): void {}

            function test(Foo $foo): void {
                i_take_null($foo->baz);
            }
        "},
        issues = [
            IssueCode::NonExistentProperty,
            IssueCode::MixedArgument,
        ]
    }

    test_analysis! {
        name = accessing_property_on_generic_object,
        code = indoc! {r"
            <?php

            /**
             * @template T
             */
            class GenericClass {
                /**
                 * @var T
                 */
                public $value;
            }

            /**
             * @param GenericClass<int> $generic
             *
             * @return int
             */
            function test(GenericClass $generic): int {
                return $generic->value;
            }
        "}
    }

    test_analysis! {
        name = property_access_definite_null_error,
        code = indoc! {r"
            <?php

            function test(): null {
                $obj = null;
                $value = $obj->property;
                return $value;
            }
        "},
        issues = [
            IssueCode::NullPropertyAccess,
        ]
    }

    test_analysis! {
        name = property_access_dynamic_name_unknown_type,
        code = indoc! {r#"
            <?php

            class Foo { public string $known = "val"; }

            function test(): string {
                $obj = new Foo();
                return $obj->{$propName};
             }
        "#},
        issues = [
            IssueCode::UndefinedVariable,
            IssueCode::InvalidMemberSelector,
            IssueCode::MixedReturnStatement,
        ]
    }

    test_analysis! {
        name = property_access_dynamic_name_literal_string,
        code = indoc! {r#"
            <?php
            class Foo { public string $known = "val"; }

            function test(): string {
                $obj = new Foo();
                $propName = "k" . "nown";
                return $obj->{$propName};
            }
        "#},
    }

    test_analysis! {
        name = property_access_dynamic_name_invalid_type,
        code = indoc! {r#"
            <?php

            class Foo { public string $known = "val"; }

            function test(): string {
                $obj = new Foo();
                $propName = 123;
                return $obj->{$propName};
            }
        "#},
        issues = [
            IssueCode::InvalidMemberSelector,
            IssueCode::InvalidReturnStatement,
        ]
    }

    test_analysis! {
        name = property_access_on_generic_object_type_error,
        code = indoc! {r"
            <?php

            function get_prop(object $obj): mixed {
                return $obj->some_property;
            }
        "},
        issues = [IssueCode::AmbiguousObjectPropertyAccess]
    }

    test_analysis! {
        name = property_access_nullsafe_on_nullable_union_valid,
        code = indoc! {r#"
            <?php
            class Bar { public string $prop = "value"; }

            function get_prop_safe(Bar|null $obj): ?string {
                return $obj?->prop;
            }
        "#},
    }

    test_analysis! {
        name = property_access_on_interface_variable,
        code = indoc! {r"
            <?php

            interface MyInterface {}

            function get_prop_from_interface(MyInterface $iface): null {
                return $iface->some_prop;
            }
        "},
        issues = [
            IssueCode::NonExistentProperty,
            IssueCode::MixedReturnStatement,
        ]
    }

    test_analysis! {
        name = property_access_on_enum_variable,
        code = indoc! {r"
            <?php

            enum X {}

            function get_prop_from_enum(X $x): null {
                return $x->some_prop;
            }
        "},
        issues = [
            IssueCode::NonExistentProperty,
        ]
    }

    test_analysis! {
        name = property_access_on_final_class_variable,
        code = indoc! {r"
            <?php

            final class X {}

            function get_prop_from_final_class(X $x): null {
                return $x->some_prop;
            }
        "},
        issues = [
            IssueCode::NonExistentProperty,
        ]
    }

    test_analysis! {
        name = property_access_chain_intermediate_possibly_null,
        code = indoc! {r#"
            <?php

            class A { public ?B $b_prop = null; }
            class B { public string $c_prop = "value"; }

            function get_nested(A $a): ?string {
                return $a->b_prop->c_prop;
            }
        "#},
        issues = [
            IssueCode::PossiblyNullPropertyAccess
        ]
    }

    test_analysis! {
        name = property_access_chain_nullsafe_intermediate,
        code = indoc! {r#"
            <?php

            class A { public ?B $b_prop = null; }
            class B { public string $c_prop = "value"; }

            function get_nested_safe(A $a): ?string {
                return $a->b_prop?->c_prop;
            }
        "#},
    }

    test_analysis! {
        name = property_access_on_void_function_result,
        code = indoc! {r"
            <?php

            function returns_void(): void {}

            $result = returns_void();
            echo $result->property;
        "},
        issues = [
            IssueCode::NullPropertyAccess,
        ]
    }

    test_analysis! {
        name = property_access_multiple_selectors,
        code = indoc! {r"
            <?php

            class a
            {
                public string $x = '';
                public bool $y = false;
            }

            class b
            {
                public int $x = 1;
                public float $y = 1.2;
            }

            /**
             * @template T of scalar
             */
            class c
            {
                /**
                 * @var list<T>
                 */
                public array $x = [];

                public false $y = false;
            }

            /**
             * @param a|b|c<int> $o
             * @param 'x'|'y' $p
             * @return bool|float|string|int|list<int>
             */
            function get(a|b|c $o, string $p): bool|float|string|int|array
            {
                return $o->{$p};
            }
        "},
    }

    test_analysis! {
        name = accessing_non_existent_class_property,
        code = indoc! {r"
            <?php

            function example($class): void {
                if ($class instanceof NonExistingClass) {
                    $class->bar;
                }
            }
        "},
        issues = [
            IssueCode::NonExistentClassLike,
            IssueCode::UnusedStatement,
        ]
    }

    test_analysis! {
        name = trait_property_access,
        code = indoc! {r#"
            <?php

            trait A {
                private string $x = "hello 1";
                protected string $y = "hello 2";
            }

            class B {
                use A;

                public function c(): void {
                    echo $this->x; // private property access
                    echo $this->y; // protected property access
                }
            }

            new B()->c();
        "#},
    }
}