mir-analyzer 0.65.0

Analysis engine for the mir PHP static analyzer
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
use super::ExpressionAnalyzer;
use crate::flow_state::FlowState;
use mir_issues::{IssueKind, Severity};
use mir_types::{Atomic, Type};
use php_ast::owned::{ArrayAccessExpr, ArrayElement, Expr, ExprKind};
use std::sync::Arc;

/// For a spread (`...`) element in an array literal, return the union of key types
/// across all array atomics. Mirrors [`crate::call::spread_element_type`], which does
/// the same for value types. E.g. `array<string, int>` → `string`, `list<int>` → `int`.
fn spread_key_type(db: &dyn crate::db::MirDatabase, arr_ty: &Type) -> Type {
    use mir_types::atomic::ArrayKey;

    let mut result = Type::empty();
    for atomic in arr_ty.types.iter() {
        match atomic {
            Atomic::TArray { key, .. } | Atomic::TNonEmptyArray { key, .. } => {
                for t in key.types.iter() {
                    result.add_type(t.clone());
                }
            }
            Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => {
                result.add_type(Atomic::TInt);
            }
            Atomic::TKeyedArray { properties, .. } => {
                // Widen to the base scalar type, same as the `Int` arm just
                // above — a spread's key domain is "any key this array has",
                // not each individual key kept as its own literal.
                for key in properties.keys() {
                    match key {
                        ArrayKey::Int(_) => result.add_type(Atomic::TInt),
                        ArrayKey::String(_) => result.add_type(Atomic::TString),
                    }
                }
            }
            // Traversable<TKey, TValue>/Iterator/IteratorAggregate/Generator — resolve
            // the real item types via the class's own `@implements`
            // annotation (or `current()`/`key()`/`getIterator()` chain), not
            // a naive `type_params[0]` positional guess — a spreadable
            // object's own declared template list isn't necessarily
            // exactly `[TKey, TValue]` in that order.
            Atomic::TNamedObject { fqcn, type_params } => {
                if let Some((key, _value)) =
                    crate::stmt::resolve_iterator_item_types(db, fqcn, type_params, 4)
                {
                    for t in key.types.iter() {
                        result.add_type(t.clone());
                    }
                } else {
                    return Type::mixed();
                }
            }
            _ => return Type::mixed(),
        }
    }
    if result.types.is_empty() {
        Type::mixed()
    } else {
        result
    }
}

/// Whether `fqcn` implements `ArrayAccess`, directly or via an ancestor
/// class/interface — `$obj[$idx]` on such a receiver is governed by the
/// class's own `offsetGet`/`offsetSet`/`offsetExists` signatures, not the
/// plain-PHP-array "offset must be an array-key" rule.
pub(super) fn implements_array_access(
    db: &dyn crate::db::MirDatabase,
    fqcn: &mir_types::Name,
) -> bool {
    let bare = fqcn.as_ref().trim_start_matches('\\');
    crate::db::class_ancestors_by_fqcn(db, crate::db::Fqcn::from_str(db, bare))
        .iter()
        .any(|a| {
            a.trim_start_matches('\\')
                .eq_ignore_ascii_case("ArrayAccess")
        })
}

/// Resolve the value type `$obj[$idx]` yields for an `ArrayAccess`-implementing
/// receiver: prefer an explicit `@implements ArrayAccess<TKey, TValue>`
/// annotation (substituting the receiver's own concrete type args), falling
/// back to `offsetGet()`'s resolved return type. `None` means `fqcn` doesn't
/// implement `ArrayAccess` at all.
fn resolve_array_access_value_type(
    db: &dyn crate::db::MirDatabase,
    fqcn: &mir_types::Name,
    type_params: &[Type],
) -> Option<Type> {
    if !implements_array_access(db, fqcn) {
        return None;
    }
    let bare = fqcn.as_ref().trim_start_matches('\\');
    let class = crate::db::find_class_like(db, crate::db::Fqcn::from_str(db, bare))?;
    let class_tps = crate::db::class_template_params(db, bare).unwrap_or_default();
    let own_bindings = crate::generic::build_class_bindings(&class_tps, type_params);

    // The `@implements ArrayAccess<TKey, TValue>` annotation is always
    // declared directly on `bare` itself (own-declared, not inherited), so
    // own-bindings-wins is always correct for this branch.
    let mut annotation_bindings = own_bindings.clone();
    for (k, v) in crate::db::inherited_template_bindings(db, bare, &annotation_bindings) {
        annotation_bindings.entry(k).or_insert(v);
    }
    let annotated = class
        .implements_type_args()
        .iter()
        .find_map(|(iface, args)| {
            (iface
                .trim_start_matches('\\')
                .eq_ignore_ascii_case("ArrayAccess"))
            .then_some(args)
        });
    if let Some(args) = annotated {
        if args.len() >= 2 {
            return Some(args[1].substitute_templates(&annotation_bindings));
        }
    }

    // `offsetGet()` may be declared directly on `bare` or inherited from an
    // ancestor — the merge direction depends on which one actually declares
    // it (a same-named template letter reused by both must resolve to the
    // declaring class's own binding, not the receiver's).
    let (owner, def) =
        crate::db::find_method_in_chain(db, crate::db::Fqcn::from_str(db, bare), "offsetget")?;
    let ty = def
        .return_type
        .as_deref()
        .cloned()
        .unwrap_or_else(Type::mixed);
    let mut bindings = own_bindings.clone();
    let inherited = crate::db::inherited_template_bindings(db, bare, &own_bindings);
    if owner.as_ref() == bare {
        for (k, v) in inherited {
            bindings.entry(k).or_insert(v);
        }
    } else {
        bindings.extend(inherited);
    }
    Some(ty.substitute_templates(&bindings))
}

/// Write-side counterpart of [`resolve_array_access_value_type`]: the value
/// type `$obj[$idx] = $value` must satisfy for an `ArrayAccess`-implementing
/// receiver. Prefers the same `@implements ArrayAccess<TKey, TValue>`
/// annotation (annotation applies to both directions), falling back to
/// `offsetSet()`'s second parameter's declared type. `None` means `fqcn`
/// doesn't implement `ArrayAccess`, or `offsetSet` has no declared value
/// param type to check against.
pub(super) fn resolve_array_access_offset_set_value_type(
    db: &dyn crate::db::MirDatabase,
    fqcn: &mir_types::Name,
    type_params: &[Type],
) -> Option<Type> {
    if !implements_array_access(db, fqcn) {
        return None;
    }
    let bare = fqcn.as_ref().trim_start_matches('\\');
    let class = crate::db::find_class_like(db, crate::db::Fqcn::from_str(db, bare))?;
    let class_tps = crate::db::class_template_params(db, bare).unwrap_or_default();
    let own_bindings = crate::generic::build_class_bindings(&class_tps, type_params);

    let mut annotation_bindings = own_bindings.clone();
    for (k, v) in crate::db::inherited_template_bindings(db, bare, &annotation_bindings) {
        annotation_bindings.entry(k).or_insert(v);
    }
    let annotated = class
        .implements_type_args()
        .iter()
        .find_map(|(iface, args)| {
            (iface
                .trim_start_matches('\\')
                .eq_ignore_ascii_case("ArrayAccess"))
            .then_some(args)
        });
    if let Some(args) = annotated {
        if args.len() >= 2 {
            return Some(args[1].substitute_templates(&annotation_bindings));
        }
    }

    let (owner, def) =
        crate::db::find_method_in_chain(db, crate::db::Fqcn::from_str(db, bare), "offsetset")?;
    let param_ty = def.params.get(1)?.ty.as_deref().cloned()?;
    let mut bindings = own_bindings.clone();
    let inherited = crate::db::inherited_template_bindings(db, bare, &own_bindings);
    if owner.as_ref() == bare {
        for (k, v) in inherited {
            bindings.entry(k).or_insert(v);
        }
    } else {
        bindings.extend(inherited);
    }
    Some(param_ty.substitute_templates(&bindings))
}

/// The offset (key) type `$obj[$idx]`/`$obj[$idx] = $v` expects for an
/// `ArrayAccess`-implementing receiver — the `TKey` counterpart of
/// [`resolve_array_access_value_type`]. Prefers the `@implements
/// ArrayAccess<TKey, TValue>` annotation, falling back to `offsetGet()`'s
/// own `$offset` parameter type (declaring `offsetSet`'s first param would
/// be equally valid; `offsetGet` is used since a class implementing
/// `ArrayAccess` always declares it, unlike a write-only collection).
pub(super) fn resolve_array_access_key_type(
    db: &dyn crate::db::MirDatabase,
    fqcn: &mir_types::Name,
    type_params: &[Type],
) -> Option<Type> {
    if !implements_array_access(db, fqcn) {
        return None;
    }
    let bare = fqcn.as_ref().trim_start_matches('\\');
    let class = crate::db::find_class_like(db, crate::db::Fqcn::from_str(db, bare))?;
    let class_tps = crate::db::class_template_params(db, bare).unwrap_or_default();
    let own_bindings = crate::generic::build_class_bindings(&class_tps, type_params);

    let mut annotation_bindings = own_bindings.clone();
    for (k, v) in crate::db::inherited_template_bindings(db, bare, &annotation_bindings) {
        annotation_bindings.entry(k).or_insert(v);
    }
    let annotated = class
        .implements_type_args()
        .iter()
        .find_map(|(iface, args)| {
            (iface
                .trim_start_matches('\\')
                .eq_ignore_ascii_case("ArrayAccess"))
            .then_some(args)
        });
    if let Some(args) = annotated {
        if !args.is_empty() {
            return Some(args[0].substitute_templates(&annotation_bindings));
        }
    }

    let (owner, def) =
        crate::db::find_method_in_chain(db, crate::db::Fqcn::from_str(db, bare), "offsetget")?;
    let param_ty = def.params.first()?.ty.as_deref().cloned()?;
    let mut bindings = own_bindings.clone();
    let inherited = crate::db::inherited_template_bindings(db, bare, &own_bindings);
    if owner.as_ref() == bare {
        for (k, v) in inherited {
            bindings.entry(k).or_insert(v);
        }
    } else {
        bindings.extend(inherited);
    }
    Some(param_ty.substitute_templates(&bindings))
}

impl<'a> ExpressionAnalyzer<'a> {
    pub(super) fn analyze_array(&mut self, elements: &[ArrayElement], ctx: &mut FlowState) -> Type {
        use mir_types::atomic::{ArrayKey, KeyedProperty};

        if elements.is_empty() {
            return Type::single(Atomic::TKeyedArray {
                properties: Box::default(),
                is_open: false,
                is_list: true,
            });
        }

        let mut keyed_props: indexmap::IndexMap<ArrayKey, KeyedProperty> =
            indexmap::IndexMap::new();
        let mut is_list = true;
        let mut can_be_keyed = true;
        let mut next_int_key: i64 = 0;

        // Accumulated in the same pass as the keyed-shape attempt above, so
        // that a spread or a non-literal key partway through only falls back
        // to the generic TArray shape below — it never re-analyzes any
        // element's value/key expression a second time.
        let mut all_value_types = Type::empty();
        let mut key_union = Type::empty();
        // Keys whose current `keyed_props` entry came from a spread rather
        // than an explicit literal key — a later literal key overriding one
        // of these is the common, intentional `[...$defaults, 'k' => $v]`
        // override idiom, not a copy-paste duplicate, so it's exempted from
        // the `DuplicateArrayKey` check below.
        let mut spread_contributed_keys: std::collections::HashSet<ArrayKey> =
            std::collections::HashSet::new();

        for elem in elements.iter() {
            if elem.unpack {
                let value_ty = self.analyze(&elem.value, ctx);
                all_value_types.merge_with(&crate::call::spread_element_type(self.db, &value_ty));
                key_union.merge_with(&spread_key_type(self.db, &value_ty));
                // A spread of a single, closed, string-keyed shape (the common
                // `[...$defaults, ...$overrides]` config-merge idiom) can still
                // contribute precise per-key properties instead of forcing the
                // generic-array fallback for the WHOLE literal. Int-keyed
                // sources need renumbering this fast path doesn't attempt, so
                // those (and anything wider than one shape atom) still fall back.
                let spread_shape_props = match value_ty.types.as_slice() {
                    [Atomic::TKeyedArray {
                        properties,
                        is_open: false,
                        ..
                    }] if properties.keys().all(|k| matches!(k, ArrayKey::String(_))) => {
                        Some(properties.clone())
                    }
                    _ => None,
                };
                match spread_shape_props {
                    Some(props) if can_be_keyed => {
                        for (k, prop) in props.iter() {
                            keyed_props.insert(k.clone(), prop.clone());
                            spread_contributed_keys.insert(k.clone());
                        }
                        is_list = false;
                    }
                    _ => can_be_keyed = false,
                }
                continue;
            }
            let value_ty = self.analyze(&elem.value, ctx);
            let array_key = if let Some(key_expr) = &elem.key {
                is_list = false;
                let key_ty = self.analyze(key_expr, ctx);
                // Float keys are silently truncated to int in PHP; TIntegralFloat is always
                // whole-valued so the truncation is lossless — suppress the warning for it.
                if key_ty.contains(|t| matches!(t, Atomic::TFloat | Atomic::TLiteralFloat(..)))
                    && !key_ty.contains(|t| matches!(t, Atomic::TIntegralFloat))
                {
                    self.emit(
                        IssueKind::ImplicitFloatToIntCast {
                            from: key_ty.to_string(),
                        },
                        Severity::Warning,
                        key_expr.span,
                    );
                }
                // Coerce to PHP's canonical array-key representation first —
                // a numeric string canonicalizes to int ("0", "42", ...), and
                // a bool/float/null key literal (or constant expression
                // folded to one) casts the same way a real write would.
                let key_ty = super::helpers::coerce_array_key_type(&key_ty);
                key_union.merge_with(&key_ty);
                match key_ty.types.as_slice() {
                    [Atomic::TLiteralString(s)] => Some(ArrayKey::String(s.clone())),
                    [Atomic::TLiteralInt(i)] => {
                        next_int_key = *i + 1;
                        Some(ArrayKey::Int(*i))
                    }
                    _ => {
                        can_be_keyed = false;
                        None
                    }
                }
            } else {
                let k = ArrayKey::Int(next_int_key);
                next_int_key += 1;
                key_union.add_type(Atomic::TInt);
                Some(k)
            };
            all_value_types.merge_with(&value_ty);

            // Once a prior element already forced the generic-array fallback
            // (a spread, or a key that didn't resolve to a single literal),
            // there's no shape left to build — only the accumulators above
            // still matter for the remaining elements.
            if !can_be_keyed {
                continue;
            }
            let array_key = array_key.expect("can_be_keyed is only true when a key was resolved");
            // A repeated key silently overwrites the earlier entry at runtime
            // (`['a' => 1, 'b' => 2, 'a' => 3]` evaluates to `['a' => 3, 'b' =>
            // 2]`) — almost always a copy-paste mistake, not intentional.
            // Exempt a key whose current entry came from a spread: overriding
            // a spread-contributed key with an explicit literal is the common,
            // intentional `[...$defaults, 'k' => $v]` idiom, not a duplicate.
            if keyed_props.contains_key(&array_key) && !spread_contributed_keys.contains(&array_key)
            {
                let key_str = match &array_key {
                    ArrayKey::String(s) => format!("'{s}'"),
                    ArrayKey::Int(i) => i.to_string(),
                };
                self.emit(
                    IssueKind::DuplicateArrayKey { key: key_str },
                    Severity::Warning,
                    elem.key.as_ref().map_or(elem.value.span, |k| k.span),
                );
            }
            spread_contributed_keys.remove(&array_key);
            keyed_props.insert(
                array_key,
                KeyedProperty {
                    ty: value_ty,
                    optional: false,
                },
            );
        }

        if can_be_keyed {
            // `[$obj, 'method']` / `['ClassName', 'method']`: PHP's array-callable
            // shape. Record the method as referenced here, at the literal itself,
            // regardless of how the array is later used (call_user_func(...),
            // Closure::fromCallable(...), or invoked directly) — otherwise a
            // private method reachable only this way is falsely flagged unused.
            if is_list && elements.len() == 2 {
                if let ExprKind::String(method_name) = &elements[1].value.kind {
                    if let Some(receiver_ty) = keyed_props.get(&ArrayKey::Int(0)).map(|p| &p.ty) {
                        self.record_array_callable_method_ref(
                            &elements[0].value,
                            receiver_ty,
                            method_name,
                            elements[1].value.span,
                        );
                    }
                }
            }
            return Type::single(Atomic::TKeyedArray {
                properties: Box::new(keyed_props),
                is_open: false,
                is_list,
            });
        }

        // Fallback: generic TArray. `all_value_types`/`key_union` were already
        // accumulated in the loop above — every element's value/key
        // expression is analyzed exactly once regardless of which shape
        // (keyed or generic) ends up being returned.
        if key_union.is_empty() {
            key_union.add_type(Atomic::TInt);
        }
        Type::single(Atomic::TArray {
            key: Box::new(key_union),
            value: Box::new(all_value_types),
        })
    }

    /// Resolve and record a method reference for the `[receiver, 'method']`
    /// array-callable shape. `receiver_expr`/`receiver_ty` are the array's
    /// first element (already analyzed by the caller); `method_name` is the
    /// literal string of the second. No-op if the receiver isn't a resolvable
    /// object type or class-string literal, or the method doesn't exist.
    fn record_array_callable_method_ref(
        &mut self,
        receiver_expr: &Expr,
        receiver_ty: &Type,
        method_name: &str,
        method_span: php_ast::Span,
    ) {
        // `by_class_name` is true when the receiver names its class directly
        // (a string literal or `Foo::class`) rather than being an object
        // instance — in that case the class itself must also be recorded as
        // referenced, or a class reachable only through an array-callable
        // (routing tables, PSR-14 listeners, ...) is falsely flagged
        // UnusedClass. An object-typed receiver's own construction/type hint
        // already records that separately.
        let (fqcn, by_class_name): (Option<Arc<str>>, bool) =
            if let ExprKind::String(class_name) = &receiver_expr.kind {
                (
                    Some(Arc::from(
                        crate::db::resolve_name(self.db, self.file.as_ref(), class_name.as_ref())
                            .as_str(),
                    )),
                    true,
                )
            } else {
                // An object-typed or class-string-typed receiver's
                // `TNamedObject`/`TClassString` fqcn is already the canonical
                // resolved name (set at inference time), unlike a raw
                // source-text class-string literal — no `resolve_name`
                // needed. `Foo::class` in this position evaluates to
                // `TClassString`, not `TNamedObject`, so it must be checked
                // in addition to `named_object_fqcn()`.
                receiver_ty
                    .remove_null()
                    .types
                    .iter()
                    .find_map(|a| match a {
                        Atomic::TClassString(Some(name)) => Some((Arc::from(name.as_str()), true)),
                        _ => a.named_object_fqcn().map(|f| (Arc::from(f), false)),
                    })
                    .map_or((None, false), |(f, by_name)| (Some(f), by_name))
            };
        let Some(fqcn) = fqcn else { return };
        if by_class_name {
            self.record_ref(Arc::from(format!("cls:{fqcn}")), receiver_expr.span);
        }
        let method_name_lower = crate::util::php_ident_lowercase(method_name);
        if let Some(resolved) =
            crate::call::method::resolve_method_from_db(self.db, &fqcn, &method_name_lower)
        {
            self.record_ref(
                Arc::from(format!(
                    "meth:{}::{}",
                    resolved.owner_fqcn, method_name_lower
                )),
                method_span,
            );
        }
    }

    pub(super) fn analyze_array_access(
        &mut self,
        aa: &ArrayAccessExpr,
        expr: &Expr,
        ctx: &mut FlowState,
    ) -> Type {
        // Purity check: `$GLOBALS['x']` reaches the same external mutable
        // state as `global $x;`, but only the `global` statement was ever
        // checked — accessing the superglobal array directly inside a
        // @pure function bypassed the check entirely. Any OTHER superglobal
        // ($_SESSION/$_ENV/$_SERVER/etc.) is exactly the same shape of
        // external mutable state, previously unrecognized here at all.
        if ctx.is_in_pure_fn {
            if let ExprKind::Variable(name) = &aa.array.kind {
                let bare = name.trim_start_matches('$');
                if crate::util::is_superglobal_name(bare) {
                    let variable = aa
                        .index
                        .as_ref()
                        .and_then(|idx| super::helpers::extract_string_from_expr(idx))
                        .unwrap_or_else(|| bare.to_string());
                    self.emit(
                        IssueKind::ImpureGlobalVariable { variable },
                        Severity::Warning,
                        expr.span,
                    );
                }
            }
        }
        let prev_in_array_access_base = self.in_array_access_base;
        self.in_array_access_base = true;
        let arr_ty = self.analyze(&aa.array, ctx);
        self.in_array_access_base = prev_in_array_access_base;
        // `ArrayAccess` receivers (WeakMap, SplObjectStorage, user collections)
        // define their own offset type via offsetGet/offsetSet/offsetExists —
        // the plain-PHP-array "offset must be an array-key" rule below doesn't
        // apply to them (e.g. WeakMap is keyed by `object`).
        let receiver_is_array_access = arr_ty.types.iter().any(
            |a| matches!(a, Atomic::TNamedObject { fqcn, .. } if implements_array_access(self.db, fqcn)),
        );
        if let Some(idx) = &aa.index {
            let idx_ty = self.analyze(idx, ctx);
            if receiver_is_array_access {
                // The array-key rule below is plain-PHP-array-only; skip it —
                // but the offset must still satisfy the receiver's own
                // declared TKey (from an @implements ArrayAccess<TKey,TValue>
                // annotation, or offsetGet()'s own $offset param type).
                if !idx_ty.is_mixed() {
                    for a in &arr_ty.types {
                        if let Atomic::TNamedObject { fqcn, type_params } = a {
                            if let Some(expected_key) =
                                resolve_array_access_key_type(self.db, fqcn, type_params)
                            {
                                if !expected_key.is_mixed()
                                    && !super::helpers::property_assign_compatible(
                                        &idx_ty,
                                        &expected_key,
                                        self.db,
                                    )
                                {
                                    self.emit(
                                        IssueKind::InvalidArgument {
                                            param: "offset".to_string(),
                                            fn_name: "offsetGet".to_string(),
                                            expected: expected_key.to_string(),
                                            actual: idx_ty.to_string(),
                                        },
                                        Severity::Error,
                                        idx.span,
                                    );
                                }
                            }
                        }
                    }
                }
            } else if idx_ty.contains(|t| matches!(t, Atomic::TFloat | Atomic::TLiteralFloat(..))) {
                // Float keys are silently truncated to int in PHP
                self.emit(
                    IssueKind::ImplicitFloatToIntCast {
                        from: idx_ty.to_string(),
                    },
                    Severity::Warning,
                    idx.span,
                );
            } else if idx_ty.is_mixed() {
                self.emit(IssueKind::MixedArrayOffset, Severity::Info, idx.span);
            } else if !idx_ty.types.is_empty()
                && idx_ty.types.iter().all(|a| {
                    matches!(
                        a,
                        Atomic::TNamedObject { .. }
                            | Atomic::TObject
                            | Atomic::TArray { .. }
                            | Atomic::TList { .. }
                            | Atomic::TKeyedArray { .. }
                            | Atomic::TNonEmptyArray { .. }
                            | Atomic::TNonEmptyList { .. }
                            | Atomic::TClosure { .. }
                    )
                })
            {
                self.emit(
                    IssueKind::InvalidArrayOffset {
                        expected: "array-key".to_string(),
                        actual: idx_ty.to_string(),
                    },
                    Severity::Error,
                    idx.span,
                );
            }
        }

        if arr_ty.is_mixed() {
            self.emit(IssueKind::MixedArrayAccess, Severity::Info, expr.span);
            return Type::mixed();
        }

        // InvalidArrayAccess: definitely non-subscriptable type (not array, not string, not object)
        if !arr_ty.is_mixed()
            && !arr_ty.types.is_empty()
            && arr_ty.types.iter().all(|a| {
                matches!(
                    a,
                    Atomic::TInt
                        | Atomic::TLiteralInt(_)
                        | Atomic::TIntRange { .. }
                        | Atomic::TPositiveInt
                        | Atomic::TFloat
                        | Atomic::TIntegralFloat
                        | Atomic::TLiteralFloat(_, _)
                        | Atomic::TBool
                        | Atomic::TTrue
                        | Atomic::TFalse
                )
            })
        {
            self.emit(
                IssueKind::InvalidArrayAccess {
                    ty: arr_ty.to_string(),
                },
                Severity::Error,
                expr.span,
            );
            return Type::mixed();
        }

        // PossiblyInvalidArrayAccess: union has some subscriptable members and some that aren't.
        let is_invalid_for_access = |a: &Atomic| {
            matches!(
                a,
                Atomic::TInt
                    | Atomic::TLiteralInt(_)
                    | Atomic::TIntRange { .. }
                    | Atomic::TPositiveInt
                    | Atomic::TFloat
                    | Atomic::TIntegralFloat
                    | Atomic::TLiteralFloat(_, _)
                    | Atomic::TBool
                    | Atomic::TTrue
                    | Atomic::TFalse
            )
        };
        if !arr_ty.is_mixed()
            && !arr_ty.types.is_empty()
            && !self.in_existence_check
            && arr_ty.types.iter().any(is_invalid_for_access)
            && !arr_ty.types.iter().all(is_invalid_for_access)
        {
            self.emit(
                IssueKind::PossiblyInvalidArrayAccess {
                    ty: arr_ty.to_string(),
                },
                Severity::Info,
                expr.span,
            );
        }

        if arr_ty.contains(|t| matches!(t, Atomic::TNull)) && arr_ty.is_single() {
            self.emit(IssueKind::NullArrayAccess, Severity::Error, expr.span);
            return Type::mixed();
        }
        if arr_ty.is_nullable() && !self.in_existence_check {
            self.emit(
                IssueKind::PossiblyNullArrayAccess,
                Severity::Info,
                expr.span,
            );
        }

        let literal_key: Option<mir_types::atomic::ArrayKey> = aa
            .index
            .as_ref()
            .and_then(|idx| super::helpers::literal_array_key_of_kind(&idx.kind));

        let idx_span = aa.index.as_ref().map(|i| i.span).unwrap_or(expr.span);

        // When every atomic in the union is a shape and the index is a
        // literal key, merge the key's type across every union member
        // instead of returning as soon as the first shape happens to match —
        // `array{a: int}|array{a: string}` accessed via `$x['a']` must yield
        // `int|string`, not just the first arm's `int`.
        if let Some(ref key) = literal_key {
            if !arr_ty.types.is_empty()
                && arr_ty
                    .types
                    .iter()
                    .all(|a| matches!(a, Atomic::TKeyedArray { .. }))
            {
                let mut result = Type::empty();
                for atomic in &arr_ty.types {
                    let Atomic::TKeyedArray {
                        properties,
                        is_open,
                        ..
                    } = atomic
                    else {
                        unreachable!("filtered to TKeyedArray above")
                    };
                    if let Some(prop) = properties.get(key) {
                        // An optional key (`array{b?: string}`) may be absent at
                        // runtime — accessing it can yield null via the array's
                        // undefined-offset warning-then-null semantics, so the
                        // result must include null, not just the declared value type.
                        if prop.optional {
                            let mut widened = prop.ty.clone();
                            widened.add_type(Atomic::TNull);
                            result.merge_with(&widened);
                        } else {
                            result.merge_with(&prop.ty);
                        }
                    } else if !is_open && !self.in_existence_check {
                        let key_str = match key {
                            mir_types::atomic::ArrayKey::String(s) => s.to_string(),
                            mir_types::atomic::ArrayKey::Int(i) => i.to_string(),
                        };
                        self.emit(
                            IssueKind::NonExistentArrayOffset { key: key_str },
                            Severity::Error,
                            idx_span,
                        );
                        return Type::mixed();
                    } else {
                        for prop in properties.values() {
                            result.merge_with(&prop.ty);
                        }
                    }
                }
                return if result.types.is_empty() {
                    Type::mixed()
                } else {
                    result
                };
            }
        }

        // A heterogeneous union (shape alongside a generic array/list/string/
        // object) must merge every atom's contribution, same reasoning as the
        // all-shapes branch above — returning on the first matching atom
        // silently drops every other union member's contribution (e.g.
        // `array{a:int}|array<string,string>` accessed via `$x['a']` must
        // yield `int|string`, not just the shape arm's `int`).
        let mut result = Type::empty();
        let mut contributed = false;
        for atomic in &arr_ty.types {
            match atomic {
                Atomic::TKeyedArray {
                    properties,
                    is_open,
                    ..
                } => {
                    contributed = true;
                    if let Some(ref key) = literal_key {
                        if let Some(prop) = properties.get(key) {
                            if prop.optional {
                                let mut widened = prop.ty.clone();
                                widened.add_type(Atomic::TNull);
                                result.merge_with(&widened);
                            } else {
                                result.merge_with(&prop.ty);
                            }
                        } else if !is_open && !self.in_existence_check {
                            let key_str = match key {
                                mir_types::atomic::ArrayKey::String(s) => s.to_string(),
                                mir_types::atomic::ArrayKey::Int(i) => i.to_string(),
                            };
                            self.emit(
                                IssueKind::NonExistentArrayOffset { key: key_str },
                                Severity::Error,
                                idx_span,
                            );
                            return Type::mixed();
                        } else {
                            for prop in properties.values() {
                                result.merge_with(&prop.ty);
                            }
                        }
                    } else {
                        for prop in properties.values() {
                            result.merge_with(&prop.ty);
                        }
                    }
                }
                Atomic::TArray { value, .. } | Atomic::TNonEmptyArray { value, .. } => {
                    contributed = true;
                    result.merge_with(value);
                }
                Atomic::TList { value } | Atomic::TNonEmptyList { value } => {
                    contributed = true;
                    result.merge_with(value);
                }
                Atomic::TString | Atomic::TLiteralString(_) => {
                    contributed = true;
                    result.merge_with(&Type::single(Atomic::TString));
                }
                Atomic::TNamedObject { fqcn, type_params } => {
                    if let Some(value_ty) =
                        resolve_array_access_value_type(self.db, fqcn, type_params)
                    {
                        contributed = true;
                        result.merge_with(&value_ty);
                    }
                }
                _ => {}
            }
        }
        if contributed && !result.types.is_empty() {
            result
        } else {
            Type::mixed()
        }
    }
}