Skip to main content

mir_types/
union.rs

1use rustc_hash::FxHashMap;
2use serde::{Deserialize, Serialize};
3use smallvec::SmallVec;
4use std::sync::{Arc, OnceLock};
5
6use crate::atomic::{
7    ArrayKey, Atomic, IntRefinement, KeyedProperties, KeyedProperty, StringRefinement,
8};
9use crate::symbol::Name;
10
11/// Returns a cached empty `Arc<[Type]>` for `type_params` / `parts` fields.
12/// Re-uses a single Arc allocation so all empty parameter lists share one
13/// control block instead of allocating one per TNamedObject construction.
14pub fn empty_type_params() -> Arc<[Type]> {
15    static EMPTY: OnceLock<Arc<[Type]>> = OnceLock::new();
16    EMPTY.get_or_init(|| Arc::from([] as [Type; 0])).clone()
17}
18
19/// Convert a `Vec<Type>` to `Arc<[Type]>`, using the cached empty Arc when
20/// the vec is empty to avoid an allocation for the common no-generic case.
21pub fn vec_to_type_params(v: Vec<Type>) -> Arc<[Type]> {
22    if v.is_empty() {
23        empty_type_params()
24    } else {
25        Arc::from(v)
26    }
27}
28
29// Most unions contain 1-2 atomics (e.g. `string|null`), so we inline two.
30pub type AtomicVec = SmallVec<[Atomic; 2]>;
31
32/// Result of classifying a type for `clone` validity (see [`Type::clone_validity`]).
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum CloneValidity {
35    /// Every member is (or may be) an object — cloning is fine.
36    Cloneable,
37    /// Every member is definitely a non-object — cloning is an error.
38    Invalid,
39    /// Some members are non-objects, some are objects — cloning may be an error.
40    PossiblyInvalid,
41    /// Empty/unknown type — no diagnostic.
42    Unknown,
43}
44
45// ---------------------------------------------------------------------------
46// Type — the primary type carrier
47// ---------------------------------------------------------------------------
48
49#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
50pub struct Type {
51    pub types: AtomicVec,
52    /// The variable holding this type may not be initialized at this point.
53    pub possibly_undefined: bool,
54    /// This type originated from a docblock annotation rather than inference.
55    pub from_docblock: bool,
56    /// A `false`/`null` failure variant was deliberately stripped from this type
57    /// (e.g. `preg_split`'s regex-error `false`) because real code overwhelmingly
58    /// never checks for it. A defensive `=== false`/`=== null` check or a
59    /// `(string)`/`(array)` cast guarding against that exact stripped variant is
60    /// still legitimate, so the impossibility/redundancy checks (`ImpossibleIdenticalComparison`,
61    /// `RedundantCast`, the `=== null` narrowing divergence) exempt it instead of
62    /// flagging the caller's own defensive code.
63    pub falsy_stripped: bool,
64    /// This type was read from a generic array/list offset (`$arr[$key]`)
65    /// whose key presence isn't statically provable — PHP returns `null`
66    /// (with a warning) for a missing offset, so a defensive `=== null`/
67    /// `!== null` check against it is legitimate even though the inferred
68    /// value type itself doesn't literally include `null` (adding `null`
69    /// unconditionally to every generic-array read would drown real code in
70    /// `PossiblyNull*` noise for the overwhelmingly common case where the key
71    /// really is present). The impossibility/redundancy checks
72    /// (`ImpossibleIdenticalComparison`, the `=== null` narrowing divergence)
73    /// exempt it, mirroring `falsy_stripped`.
74    pub possibly_absent_offset: bool,
75}
76
77type IntBounds = (Option<i64>, Option<i64>);
78
79/// Inclusive `(min, max)` bounds of an int atomic; `None` bound is unbounded.
80fn int_bounds(a: &Atomic) -> Option<IntBounds> {
81    match a {
82        Atomic::TInt => Some((None, None)),
83        Atomic::TLiteralInt(n) => Some((Some(*n), Some(*n))),
84        Atomic::TPositiveInt => Some((Some(1), None)),
85        Atomic::TNonNegativeInt => Some((Some(0), None)),
86        Atomic::TNegativeInt => Some((None, Some(-1))),
87        Atomic::TIntRange { min, max } => Some((*min, *max)),
88        _ => None,
89    }
90}
91
92fn bounds_contain(outer: IntBounds, inner: IntBounds) -> bool {
93    let lo_ok = match (outer.0, inner.0) {
94        (None, _) => true,
95        (Some(o), Some(i)) => o <= i,
96        (Some(_), None) => false,
97    };
98    let hi_ok = match (outer.1, inner.1) {
99        (None, _) => true,
100        (Some(o), Some(i)) => o >= i,
101        (Some(_), None) => false,
102    };
103    lo_ok && hi_ok
104}
105
106/// Shapes a union keeps apart before [`Type::add_type`] starts folding them.
107/// Each `if` that optionally sets a key doubles the shapes in a union, and
108/// flow merges compare every pair, so a long run of such branches went
109/// exponential (Symfony's `MandrillApiTransport::getPayload` took 17s).
110/// Below the limit shapes stay apart: `count($a) === N` narrowing picks among
111/// them, and a key set on only some paths reads without `null`.
112const MAX_KEYED_SHAPES: usize = 8;
113
114/// The same limit for generic arrays and lists of one kind: a loop writing
115/// `$a[$k]['x']` under a run of `if`s forks the element type on every branch.
116const MAX_GENERIC_ARRAYS: usize = 8;
117
118/// String literals a union keeps before widening to `string`. Unions are
119/// scanned linearly on every merge, so a list built from thousands of
120/// literal-valued appends (a PHPStan baseline) went cubic.
121const MAX_LITERAL_STRINGS: usize = 128;
122
123/// `array<K1|K2, V1|V2>` for two generic arrays (or lists) of the same kind.
124pub(crate) fn combine_generic_arrays(a: &Atomic, b: &Atomic) -> Option<Atomic> {
125    let union = |x: &Type, y: &Type| {
126        let mut t = x.clone();
127        t.merge_with(y);
128        Box::new(t)
129    };
130    Some(match (a, b) {
131        (Atomic::TArray { key: ka, value: va }, Atomic::TArray { key: kb, value: vb }) => {
132            Atomic::TArray {
133                key: union(ka, kb),
134                value: union(va, vb),
135            }
136        }
137        (
138            Atomic::TNonEmptyArray { key: ka, value: va },
139            Atomic::TNonEmptyArray { key: kb, value: vb },
140        ) => Atomic::TNonEmptyArray {
141            key: union(ka, kb),
142            value: union(va, vb),
143        },
144        (Atomic::TList { value: va }, Atomic::TList { value: vb }) => Atomic::TList {
145            value: union(va, vb),
146        },
147        (Atomic::TNonEmptyList { value: va }, Atomic::TNonEmptyList { value: vb }) => {
148            Atomic::TNonEmptyList {
149                value: union(va, vb),
150            }
151        }
152        _ => return None,
153    })
154}
155
156/// Whether array `sub` adds nothing to `sup` of the same kind: its key and value fit, or
157/// for shapes, the same keys with fitting values. `mixed` and templates fit anything
158/// structurally, so they only cover themselves.
159fn array_covered(sub: &Atomic, sup: &Atomic) -> bool {
160    fn parts(a: &Atomic) -> Option<(Option<&Type>, &Type)> {
161        match a {
162            Atomic::TArray { key, value } | Atomic::TNonEmptyArray { key, value } => {
163                Some((Some(key), value))
164            }
165            Atomic::TList { value } | Atomic::TNonEmptyList { value } => Some((None, value)),
166            _ => None,
167        }
168    }
169    let fits = |x: &Type, y: &Type| {
170        values_covered(x, y) || (!is_opaque(x) && !is_opaque(y) && x.is_subtype_structural(y))
171    };
172    if std::mem::discriminant(sub) != std::mem::discriminant(sup) {
173        return false;
174    }
175    if let (
176        Atomic::TKeyedArray {
177            properties: pa,
178            is_open: oa,
179            is_list: la,
180        },
181        Atomic::TKeyedArray {
182            properties: pb,
183            is_open: ob,
184            is_list: lb,
185        },
186    ) = (sub, sup)
187    {
188        return oa == ob
189            && la == lb
190            && pa.len() == pb.len()
191            && pa.iter().all(|(key, x)| {
192                pb.get(key)
193                    .is_some_and(|y| x.optional == y.optional && values_covered(&x.ty, &y.ty))
194            })
195            && match (&pa.remainder, &pb.remainder) {
196                (None, None) => true,
197                (Some(a), Some(b)) => values_covered(a, b),
198                _ => false,
199            };
200    }
201    match (parts(sub), parts(sup)) {
202        (Some((sub_key, sub_value)), Some((sup_key, sup_value))) => {
203            fits(sub_value, sup_value)
204                && match (sub_key, sup_key) {
205                    (Some(a), Some(b)) => fits(a, b),
206                    _ => true,
207                }
208        }
209        _ => false,
210    }
211}
212
213/// Whether every member of `x` is in `y`, is an array `y` covers, or is a scalar literal
214/// or refinement of a `y` member; an int never fits a float. `mixed` and templates only
215/// cover themselves.
216fn values_covered(x: &Type, y: &Type) -> bool {
217    if is_opaque(x) || is_opaque(y) {
218        return x == y;
219    }
220    x.types.iter().all(|a| {
221        let scalar_refinement =
222            !matches!(a, Atomic::TKeyedArray { .. }) && crate::generalize::is_generalizable(a);
223        y.types.iter().any(|b| {
224            a == b
225                || array_covered(a, b)
226                || (scalar_refinement
227                    && !(a.is_int() && matches!(b, Atomic::TFloat))
228                    && atomic_subtype(a, b))
229        })
230    })
231}
232
233fn is_opaque(t: &Type) -> bool {
234    t.types
235        .iter()
236        .any(|a| matches!(a, Atomic::TMixed | Atomic::TTemplateParam { .. }))
237}
238
239/// One shape covering `a | b`: keys of both, with those set on one side only
240/// made optional and value types unioned. `None` when the shapes disagree on
241/// openness, list-ness or emptiness — folding `array{} | array{0: X}` to
242/// `array{0?: X}` would stop `if ($arr)` narrowing.
243fn combine_keyed_arrays(a: &Atomic, b: &Atomic) -> Option<Atomic> {
244    let (
245        Atomic::TKeyedArray {
246            properties: pa,
247            is_open: oa,
248            is_list: la,
249        },
250        Atomic::TKeyedArray {
251            properties: pb,
252            is_open: ob,
253            is_list: lb,
254        },
255    ) = (a, b)
256    else {
257        return None;
258    };
259    let non_empty = |p: &KeyedProperties| p.values().any(|v| !v.optional);
260    if oa != ob || la != lb || non_empty(pa) != non_empty(pb) {
261        return None;
262    }
263    let mut properties =
264        KeyedProperties::with_capacity_and_hasher(pa.len().max(pb.len()), Default::default());
265    for (key, x) in pa.iter() {
266        let prop = match pb.get(key) {
267            Some(y) => {
268                let mut ty = x.ty.clone();
269                ty.merge_with(&y.ty);
270                KeyedProperty {
271                    ty,
272                    optional: x.optional || y.optional,
273                }
274            }
275            // An open shape already admits the missing key with any value,
276            // so keeping the other side's type for it would be unsound.
277            None if *oa => continue,
278            None => KeyedProperty {
279                ty: x.ty.clone(),
280                optional: true,
281            },
282        };
283        properties.insert(key.clone(), prop);
284    }
285    if !*oa {
286        for (key, y) in pb.iter() {
287            if !pa.contains_key(key) {
288                properties.insert(
289                    key.clone(),
290                    KeyedProperty {
291                        ty: y.ty.clone(),
292                        optional: true,
293                    },
294                );
295            }
296        }
297    }
298    Some(Atomic::TKeyedArray {
299        properties: Arc::new(properties),
300        is_open: *oa,
301        is_list: *la,
302    })
303}
304
305impl Type {
306    // --- Constructors -------------------------------------------------------
307
308    pub fn empty() -> Self {
309        Self {
310            types: SmallVec::new(),
311            possibly_undefined: false,
312            from_docblock: false,
313            falsy_stripped: false,
314            possibly_absent_offset: false,
315        }
316    }
317
318    pub fn single(atomic: Atomic) -> Self {
319        let mut types = SmallVec::new();
320        types.push(atomic);
321        Self {
322            types,
323            possibly_undefined: false,
324            from_docblock: false,
325            falsy_stripped: false,
326            possibly_absent_offset: false,
327        }
328    }
329
330    pub fn mixed() -> Self {
331        Self::single(Atomic::TMixed)
332    }
333
334    pub fn void() -> Self {
335        Self::single(Atomic::TVoid)
336    }
337
338    pub fn never() -> Self {
339        Self::single(Atomic::TNever)
340    }
341
342    pub fn null() -> Self {
343        Self::single(Atomic::TNull)
344    }
345
346    pub fn bool() -> Self {
347        Self::single(Atomic::TBool)
348    }
349
350    pub fn int() -> Self {
351        Self::single(Atomic::TInt)
352    }
353
354    pub fn float() -> Self {
355        Self::single(Atomic::TFloat)
356    }
357
358    pub fn string() -> Self {
359        Self::single(Atomic::TString)
360    }
361
362    /// `int|string` — the canonical PHP array-key type, used as the default
363    /// key type when a docblock/inferred array has no more specific key.
364    pub fn array_key() -> Self {
365        let mut u = Self::single(Atomic::TInt);
366        u.add_type(Atomic::TString);
367        u
368    }
369
370    /// `T|null`
371    pub fn nullable(atomic: Atomic) -> Self {
372        // `mixed|null` = `mixed` — null is already included in mixed.
373        if matches!(atomic, Atomic::TMixed) {
374            return Self::mixed();
375        }
376        let mut types = SmallVec::new();
377        types.push(atomic);
378        types.push(Atomic::TNull);
379        Self {
380            types,
381            possibly_undefined: false,
382            from_docblock: false,
383            falsy_stripped: false,
384            possibly_absent_offset: false,
385        }
386    }
387
388    /// Build a union from multiple atomics, de-duplicating on the fly.
389    pub fn from_vec(atomics: Vec<Atomic>) -> Self {
390        let mut u = Self::empty();
391        for a in atomics {
392            u.add_type(a);
393        }
394        u
395    }
396
397    // --- Introspection -------------------------------------------------------
398
399    pub fn is_empty(&self) -> bool {
400        self.types.is_empty()
401    }
402
403    pub fn is_single(&self) -> bool {
404        self.types.len() == 1
405    }
406
407    pub fn is_nullable(&self) -> bool {
408        self.types.iter().any(|t| matches!(t, Atomic::TNull))
409    }
410
411    /// True when this is exactly `int|string` — the array-key domain, which
412    /// is already the maximal set of legal PHP array keys and so should be
413    /// treated like a "default"/unconstrained key, same as `mixed` would be
414    /// for a non-key type parameter.
415    pub fn is_array_key(&self) -> bool {
416        self.types.len() == 2
417            && self.types.iter().any(|t| matches!(t, Atomic::TInt))
418            && self.types.iter().any(|t| matches!(t, Atomic::TString))
419    }
420
421    pub fn is_mixed(&self) -> bool {
422        self.types.iter().any(|t| match t {
423            Atomic::TMixed => true,
424            Atomic::TTemplateParam { as_type, .. } => as_type.is_mixed(),
425            _ => false,
426        })
427    }
428
429    /// True only when the type contains `TMixed` atoms and no `TTemplateParam` atoms.
430    /// Unlike [`Self::is_mixed`], this does not treat an unconstrained template parameter as
431    /// "mixed" — a `T` placeholder is an intentionally parameterised type that will be
432    /// instantiated at the call site, so it must not trigger `MixedAssignment` warnings.
433    pub fn is_mixed_not_template(&self) -> bool {
434        self.is_mixed()
435            && !self
436                .types
437                .iter()
438                .any(|t| matches!(t, Atomic::TTemplateParam { .. }))
439    }
440
441    pub fn is_never(&self) -> bool {
442        self.types.iter().all(|t| matches!(t, Atomic::TNever)) && !self.types.is_empty()
443    }
444
445    /// Classify this type for `clone` validity. Recurses into template-param
446    /// bounds (like [`Type::is_mixed`]). Callers handle `mixed` separately.
447    pub fn clone_validity(&self) -> CloneValidity {
448        if self.types.is_empty() {
449            return CloneValidity::Unknown;
450        }
451        let mut has_non_object = false;
452        let mut has_other = false; // object or ambiguous (callable, mixed, conditional, …)
453        for t in &self.types {
454            match t {
455                Atomic::TTemplateParam { as_type, .. } => match as_type.clone_validity() {
456                    CloneValidity::Invalid => has_non_object = true,
457                    CloneValidity::PossiblyInvalid => {
458                        has_non_object = true;
459                        has_other = true;
460                    }
461                    CloneValidity::Cloneable | CloneValidity::Unknown => has_other = true,
462                },
463                other if other.is_definitely_non_object() => has_non_object = true,
464                _ => has_other = true,
465            }
466        }
467        match (has_non_object, has_other) {
468            (true, false) => CloneValidity::Invalid,
469            (true, true) => CloneValidity::PossiblyInvalid,
470            _ => CloneValidity::Cloneable,
471        }
472    }
473
474    pub fn is_void(&self) -> bool {
475        self.is_single() && matches!(self.types[0], Atomic::TVoid)
476    }
477
478    pub fn can_be_falsy(&self) -> bool {
479        self.types.iter().any(|t| t.can_be_falsy())
480    }
481
482    pub fn can_be_truthy(&self) -> bool {
483        self.types.iter().any(|t| t.can_be_truthy())
484    }
485
486    pub fn contains<F: Fn(&Atomic) -> bool>(&self, f: F) -> bool {
487        self.types.iter().any(f)
488    }
489
490    pub fn has_named_object(&self, fqcn: &str) -> bool {
491        self.types.iter().any(|t| match t {
492            Atomic::TNamedObject { fqcn: f, .. } => f.as_ref() == fqcn,
493            _ => false,
494        })
495    }
496
497    // --- Mutation ------------------------------------------------------------
498
499    /// Add an atomic to this union, skipping duplicates.
500    /// Subsumption rules: anything ⊆ TMixed; TLiteralInt ⊆ TInt; etc.
501    pub fn add_type(&mut self, atomic: Atomic) {
502        // If we already have TMixed, nothing to add.
503        if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
504            return;
505        }
506
507        // Adding TMixed subsumes everything.
508        if matches!(atomic, Atomic::TMixed) {
509            self.types.clear();
510            self.types.push(Atomic::TMixed);
511            return;
512        }
513
514        // Simplify trivial conditional types: (X is ? T : T) → T
515        // Recursively simplify branches first so nested trivial conditionals collapse.
516        let atomic = if let Atomic::TConditional { data } = &atomic {
517            let (if_true, if_false) = (&data.if_true, &data.if_false);
518            let mut simplified_true = Type::empty();
519            for t in &if_true.types {
520                simplified_true.add_type(t.clone());
521            }
522            let mut simplified_false = Type::empty();
523            for t in &if_false.types {
524                simplified_false.add_type(t.clone());
525            }
526            if simplified_true == simplified_false {
527                for t in simplified_true.types {
528                    self.add_type(t);
529                }
530                return;
531            }
532            atomic
533        } else {
534            atomic
535        };
536
537        if self.types.contains(&atomic) {
538            return;
539        }
540        self.add_absent_type(atomic);
541    }
542
543    /// [`Self::add_type`] for a plain atomic `self` neither holds nor is subsumed by as `mixed`.
544    fn add_absent_type(&mut self, atomic: Atomic) {
545        let mut atomic = crate::generalize::cap_array_depth(atomic);
546        // Past the limit, fold a new shape into a compatible existing one
547        // rather than growing the union (see `MAX_KEYED_SHAPES`).
548        if matches!(atomic, Atomic::TKeyedArray { .. })
549            && self
550                .types
551                .iter()
552                .filter(|t| matches!(t, Atomic::TKeyedArray { .. }))
553                .count()
554                >= MAX_KEYED_SHAPES
555        {
556            if let Some((idx, combined)) = self
557                .types
558                .iter()
559                .enumerate()
560                .find_map(|(i, t)| combine_keyed_arrays(t, &atomic).map(|c| (i, c)))
561            {
562                self.types.remove(idx);
563                if self.types.contains(&combined) {
564                    return;
565                }
566                atomic = combined;
567            }
568        }
569
570        // An array covered by another of its kind adds nothing; one it covers is
571        // dropped (`list<0> | list<int>` is `list<int>`, `array{a: 0} | array{a: int}` is `array{a: int}`).
572        if self.types.iter().any(|t| array_covered(&atomic, t)) {
573            return;
574        }
575        self.types.retain(|t| !array_covered(t, &atomic));
576
577        if matches!(
578            atomic,
579            Atomic::TArray { .. }
580                | Atomic::TNonEmptyArray { .. }
581                | Atomic::TList { .. }
582                | Atomic::TNonEmptyList { .. }
583        ) && self
584            .types
585            .iter()
586            .filter(|t| std::mem::discriminant(*t) == std::mem::discriminant(&atomic))
587            .count()
588            >= MAX_GENERIC_ARRAYS
589        {
590            if let Some((idx, combined)) = self
591                .types
592                .iter()
593                .enumerate()
594                .find_map(|(i, t)| combine_generic_arrays(t, &atomic).map(|c| (i, c)))
595            {
596                self.types.remove(idx);
597                if self.types.contains(&combined) {
598                    return;
599                }
600                atomic = combined;
601            }
602        }
603
604        // Int atomics absorb each other by bound containment (`5 | int<0, max>`
605        // → `int<0, max>`, `non-negative-int | int` → `int`).
606        if let Some(new_bounds) = int_bounds(&atomic) {
607            if self
608                .types
609                .iter()
610                .any(|t| int_bounds(t).is_some_and(|b| bounds_contain(b, new_bounds)))
611            {
612                return;
613            }
614            self.types
615                .retain(|t| !int_bounds(t).is_some_and(|b| bounds_contain(new_bounds, b)));
616        }
617        // `resource` covers closed handles too.
618        match atomic {
619            Atomic::TClosedResource | Atomic::TOpenResource
620                if self.types.contains(&Atomic::TResource) =>
621            {
622                return
623            }
624            Atomic::TResource => self
625                .types
626                .retain(|t| !matches!(t, Atomic::TClosedResource | Atomic::TOpenResource)),
627            _ => {}
628        }
629        // literal-int sits between the int literals and int.
630        const LITERAL_INT: Atomic = Atomic::TRefinedInt(IntRefinement::Literal);
631        match atomic {
632            Atomic::TRefinedInt(_) if self.types.contains(&Atomic::TInt) => return,
633            Atomic::TLiteralInt(_) if self.types.contains(&LITERAL_INT) => return,
634            LITERAL_INT => self.types.retain(|t| !matches!(t, Atomic::TLiteralInt(_))),
635            Atomic::TInt => self.types.retain(|t| !matches!(t, Atomic::TRefinedInt(_))),
636            _ => {}
637        }
638        // TLiteralString(s) is subsumed by TString.
639        if let Atomic::TLiteralString(_) = &atomic {
640            if self.types.iter().any(|t| matches!(t, Atomic::TString)) {
641                return;
642            }
643            let literals = self
644                .types
645                .iter()
646                .filter(|t| matches!(t, Atomic::TLiteralString(_)))
647                .count();
648            if literals >= MAX_LITERAL_STRINGS {
649                atomic = Atomic::TString;
650            }
651        }
652        // TNonEmptyString is subsumed by TString.
653        if matches!(
654            atomic,
655            Atomic::TNonEmptyString | Atomic::TNonFalsyString | Atomic::TRefinedString { .. }
656        ) && self.types.iter().any(|t| matches!(t, Atomic::TString))
657        {
658            return;
659        }
660        // non-falsy-string is subsumed by non-empty-string.
661        if matches!(atomic, Atomic::TNonFalsyString)
662            && self
663                .types
664                .iter()
665                .any(|t| matches!(t, Atomic::TNonEmptyString))
666        {
667            return;
668        }
669        if matches!(atomic, Atomic::TNonEmptyString) {
670            self.types.retain(|t| !matches!(t, Atomic::TNonFalsyString));
671        }
672        // TTrue / TFalse are subsumed by TBool.
673        if matches!(atomic, Atomic::TTrue | Atomic::TFalse)
674            && self.types.iter().any(|t| matches!(t, Atomic::TBool))
675        {
676            return;
677        }
678        // TTrue and TFalse together are exactly TBool — merge rather than
679        // keeping both literals once both are present.
680        if matches!(atomic, Atomic::TTrue) && self.types.iter().any(|t| matches!(t, Atomic::TFalse))
681        {
682            self.types.retain(|t| !matches!(t, Atomic::TFalse));
683            self.types.push(Atomic::TBool);
684            return;
685        }
686        if matches!(atomic, Atomic::TFalse) && self.types.iter().any(|t| matches!(t, Atomic::TTrue))
687        {
688            self.types.retain(|t| !matches!(t, Atomic::TTrue));
689            self.types.push(Atomic::TBool);
690            return;
691        }
692        // Adding TString widens away all TLiteralString and TNonEmptyString variants.
693        if matches!(atomic, Atomic::TString) {
694            self.types.retain(|t| {
695                !matches!(
696                    t,
697                    Atomic::TLiteralString(_)
698                        | Atomic::TNonEmptyString
699                        | Atomic::TNonFalsyString
700                        | Atomic::TRefinedString { .. }
701                )
702            });
703        }
704        // Adding TBool widens away TTrue/TFalse.
705        if matches!(atomic, Atomic::TBool) {
706            self.types
707                .retain(|t| !matches!(t, Atomic::TTrue | Atomic::TFalse));
708        }
709
710        // TNever is the bottom type: T | never = T.
711        if matches!(atomic, Atomic::TNever) {
712            if !self.types.is_empty() {
713                return;
714            }
715        } else {
716            self.types.retain(|t| !matches!(t, Atomic::TNever));
717        }
718
719        // Closed empty keyed array (array{}) is a subtype of any generic array or
720        // list. Remove it if we already have a generic array<K,V> or list<V>. An
721        // OPEN empty shape (array{...}) carries real information — it may hold
722        // unknown, possibly non-list, extra keys at runtime — so it's not
723        // subsumed and must not be dropped.
724        if let Atomic::TKeyedArray {
725            properties,
726            is_open,
727            ..
728        } = &atomic
729        {
730            if properties.is_empty() && !is_open {
731                // `array{} | non-empty-list<T>` is `list<T>`.
732                if let Some(idx) = self.types.iter().position(|t| {
733                    matches!(
734                        t,
735                        Atomic::TNonEmptyArray { .. } | Atomic::TNonEmptyList { .. }
736                    )
737                }) {
738                    let existing = self.types.remove(idx);
739                    let widened = Type::single(existing).widen_non_empty();
740                    for t in widened.types {
741                        self.add_absent_type(t);
742                    }
743                    return;
744                }
745                if self
746                    .types
747                    .iter()
748                    .any(|t| matches!(t, Atomic::TArray { .. } | Atomic::TList { .. }))
749                {
750                    return; // Don't add empty array, it's subsumed
751                }
752            }
753        }
754
755        // When adding a generic array or list, remove any CLOSED empty keyed
756        // arrays since they're subtypes (same reasoning as above, mirrored).
757        let is_generic_array_or_list = matches!(
758            &atomic,
759            Atomic::TArray { .. }
760                | Atomic::TNonEmptyArray { .. }
761                | Atomic::TList { .. }
762                | Atomic::TNonEmptyList { .. }
763        );
764        let mut atomic = atomic;
765        if is_generic_array_or_list {
766            let before = self.types.len();
767            self.types.retain(|t| {
768                if let Atomic::TKeyedArray {
769                    properties,
770                    is_open,
771                    ..
772                } = t
773                {
774                    !properties.is_empty() || *is_open
775                } else {
776                    true
777                }
778            });
779            // A dropped `array{}` makes a non-empty array possibly empty.
780            if self.types.len() != before {
781                if let Some(widened) = Type::single(atomic.clone()).widen_non_empty().types.pop() {
782                    if widened != atomic {
783                        if self.types.contains(&widened) {
784                            return;
785                        }
786                        atomic = widened;
787                    }
788                }
789            }
790        }
791
792        self.types.push(atomic);
793        if self.types.len() > crate::generalize::MAX_UNION_MEMBERS {
794            self.collapse_wide_union();
795        }
796    }
797
798    /// Generalizes a union past [`crate::generalize::MAX_UNION_MEMBERS`] members.
799    #[cold]
800    fn collapse_wide_union(&mut self) {
801        let literal = |t: &Atomic| matches!(t, Atomic::TLiteralString(_) | Atomic::TLiteralInt(_));
802        let counted = self.types.iter().filter(|t| !literal(t)).count();
803        if counted <= crate::generalize::MAX_UNION_MEMBERS
804            || !self
805                .types
806                .iter()
807                .any(|t| !literal(t) && crate::generalize::is_generalizable(t))
808        {
809            return;
810        }
811        let members = std::mem::take(&mut self.types);
812        for atomic in members {
813            let atomic = if literal(&atomic) {
814                atomic
815            } else {
816                crate::generalize::generalize_atomic(&atomic, crate::generalize::MAX_ARRAY_DEPTH)
817            };
818            self.add_type(atomic);
819        }
820    }
821
822    // --- Narrowing -----------------------------------------------------------
823
824    /// Remove `null` from the union (e.g. after a null check).
825    pub fn remove_null(&self) -> Type {
826        self.filter(|t| !matches!(t, Atomic::TNull))
827    }
828
829    /// Remove `false` from the union.
830    /// `TFalse` is dropped; `TBool` becomes `TTrue` since `bool - false = true`.
831    pub fn remove_false(&self) -> Type {
832        let mut result = self.filter(|t| !matches!(t, Atomic::TFalse | Atomic::TBool));
833        if self.types.iter().any(|t| matches!(t, Atomic::TBool)) {
834            result.add_type(Atomic::TTrue);
835        }
836        result
837    }
838
839    /// Remove `true` from the union.
840    /// `TTrue` is dropped; `TBool` becomes `TFalse` since `bool - true = false`.
841    pub fn remove_true(&self) -> Type {
842        let mut result = self.filter(|t| !matches!(t, Atomic::TTrue | Atomic::TBool));
843        if self.types.iter().any(|t| matches!(t, Atomic::TBool)) {
844            result.add_type(Atomic::TFalse);
845        }
846        result
847    }
848
849    /// Remove both `null` and `false` from the union (core type without nullable/falsy variants).
850    pub fn core_type(&self) -> Type {
851        self.remove_null().remove_false()
852    }
853
854    /// Keep only truthy atomics (e.g. after `if ($x)`).
855    pub fn narrow_to_truthy(&self) -> Type {
856        if self.is_mixed_not_template() {
857            return Type::mixed();
858        }
859        let mut result = Type::empty();
860        result.from_docblock = self.from_docblock;
861        for t in &self.types {
862            match t {
863                // An unconstrained/bounded template could resolve to anything at
864                // runtime, truthy or falsy — preserve it rather than dropping or
865                // widening it, the same way narrow_to_string/_int/etc. already do.
866                Atomic::TTemplateParam { .. } => result.add_type(t.clone()),
867                // Always-falsy — exclude entirely.
868                Atomic::TLiteralInt(0)
869                | Atomic::TLiteralFloat(0, 0)
870                | Atomic::TNull
871                | Atomic::TFalse => {}
872                Atomic::TLiteralString(s) if s.as_ref() == "" || s.as_ref() == "0" => {}
873                // bool contains both true (truthy) and false (falsy); truthy branch is true.
874                Atomic::TBool => result.add_type(Atomic::TTrue),
875                // array/list: empty ↔ falsy; truthy branch is non-empty-array/list.
876                Atomic::TArray { key, value } => result.add_type(Atomic::TNonEmptyArray {
877                    key: key.clone(),
878                    value: value.clone(),
879                }),
880                Atomic::TList { value } => result.add_type(Atomic::TNonEmptyList {
881                    value: value.clone(),
882                }),
883                // string: only "" and "0" are falsy.
884                Atomic::TString | Atomic::TNonEmptyString => {
885                    result.add_type(Atomic::TNonFalsyString)
886                }
887                // numeric-string: "0" is the only falsy value; non-zero numerics are truthy.
888                // No named "non-zero numeric-string" type exists; keep as-is conservatively.
889                // int<0, max> only has 0 as its falsy value; truthy branch is int<1, max>.
890                // (int<0, 0> is handled by the can_be_truthy() false guard below.)
891                Atomic::TNonNegativeInt => result.add_type(Atomic::TPositiveInt),
892                Atomic::TIntRange { min: Some(0), max } if max.is_none_or(|m| m >= 1) => {
893                    let atom = if max.is_none() {
894                        Atomic::TPositiveInt
895                    } else {
896                        Atomic::TIntRange {
897                            min: Some(1),
898                            max: *max,
899                        }
900                    };
901                    result.add_type(atom);
902                }
903                // int<min, 0>: 0 is the only falsy value; truthy branch excludes it → int<min, -1>.
904                Atomic::TIntRange { min, max: Some(0) } => {
905                    let atom = match min {
906                        None => Atomic::TNegativeInt,
907                        Some(n) if *n <= -1 => Atomic::TIntRange {
908                            min: *min,
909                            max: Some(-1),
910                        },
911                        _ => continue, // min >= 0 with max == 0 → range is {0} — can_be_truthy() handles this
912                    };
913                    result.add_type(atom);
914                }
915                // Anything else that can never be truthy — drop.
916                t if !t.can_be_truthy() => {}
917                _ => result.add_type(t.clone()),
918            }
919        }
920        result
921    }
922
923    /// Keep only falsy atomics (e.g. after `if (!$x)`).
924    pub fn narrow_to_falsy(&self) -> Type {
925        if self.is_mixed_not_template() {
926            return Type::from_vec(vec![
927                Atomic::TNull,
928                Atomic::TFalse,
929                Atomic::TLiteralInt(0),
930                Atomic::TLiteralString("".into()),
931                Atomic::TLiteralString("0".into()),
932            ]);
933        }
934        let mut result = Type::empty();
935        result.from_docblock = self.from_docblock;
936        for t in &self.types {
937            match t {
938                // An unconstrained/bounded template could resolve to anything at
939                // runtime, truthy or falsy — preserve it rather than dropping it
940                // (its own `can_be_falsy()` conservatively defaults to `false`,
941                // which would otherwise wrongly exclude it here).
942                Atomic::TTemplateParam { .. } => result.add_type(t.clone()),
943                // bool: only false is falsy; falsy branch is false.
944                Atomic::TBool => result.add_type(Atomic::TFalse),
945                // int: only 0 is falsy.
946                Atomic::TInt => result.add_type(Atomic::TLiteralInt(0)),
947                // float: only 0.0 is falsy.
948                Atomic::TFloat => result.add_type(Atomic::TLiteralFloat(0, 0)),
949                // string: only "" and "0" are falsy.
950                Atomic::TString => {
951                    result.add_type(Atomic::TLiteralString("".into()));
952                    result.add_type(Atomic::TLiteralString("0".into()));
953                }
954                // numeric-string: only "0" is a falsy numeric string.
955                Atomic::TNumericString => result.add_type(Atomic::TLiteralString("0".into())),
956                // non-negative-int: only 0 is falsy.
957                Atomic::TNonNegativeInt => result.add_type(Atomic::TLiteralInt(0)),
958                // int<0, hi>: only 0 is falsy.
959                Atomic::TIntRange {
960                    min: Some(0),
961                    max: Some(_) | None,
962                } => result.add_type(Atomic::TLiteralInt(0)),
963                // int<min, 0>: only 0 is falsy.
964                Atomic::TIntRange { max: Some(0), .. } => result.add_type(Atomic::TLiteralInt(0)),
965                t if !t.can_be_falsy() => {} // always truthy — exclude
966                _ => result.add_type(t.clone()),
967            }
968        }
969        result
970    }
971
972    /// Narrow this type as if `$x instanceof ClassName` is true.
973    ///
974    /// The instanceof check guarantees the value IS an instance of `class`, so we
975    /// replace any object / mixed constituents with the specific named object.  Scalar
976    /// constituents are dropped (they can never satisfy instanceof).
977    pub fn narrow_instanceof(&self, class: &str) -> Type {
978        let narrowed_ty = Atomic::TNamedObject {
979            fqcn: class.into(),
980            type_params: empty_type_params(),
981        };
982        // If any constituent is an object-like type, the result is the specific class.
983        let has_object = self.types.iter().any(|t| {
984            matches!(
985                t,
986                Atomic::TObject
987                    | Atomic::TObjectShape { .. }
988                    | Atomic::TNamedObject { .. }
989                    | Atomic::TMixed
990                    | Atomic::TNull // null fails instanceof, but mixed/object may include null
991            )
992        });
993        if has_object || self.is_empty() {
994            Type::single(narrowed_ty)
995        } else {
996            // Pure scalars — instanceof is always false here, but return the class
997            // defensively so callers don't see an empty union.
998            Type::single(narrowed_ty)
999        }
1000    }
1001
1002    /// Narrow as if `is_string($x)` is true. `mixed`/`scalar` become a concrete
1003    /// `string` (rather than staying `mixed`) so downstream string-only
1004    /// operations see a usable type instead of reporting `Mixed*`.
1005    pub fn narrow_to_string(&self) -> Type {
1006        self.filter_replacing(
1007            |t| t.is_string() || t.is_deferred(),
1008            |t| matches!(t, Atomic::TMixed | Atomic::TScalar),
1009            Atomic::TString,
1010        )
1011        .with_callable_form(self, Atomic::TCallableString)
1012    }
1013
1014    /// Narrow as if `is_int($x)` is true.
1015    pub fn narrow_to_int(&self) -> Type {
1016        self.filter_replacing(
1017            |t| t.is_int() || t.is_deferred(),
1018            |t| matches!(t, Atomic::TMixed | Atomic::TScalar | Atomic::TNumeric),
1019            Atomic::TInt,
1020        )
1021    }
1022
1023    /// Narrow as if `is_float($x)` is true.
1024    pub fn narrow_to_float(&self) -> Type {
1025        self.filter_replacing(
1026            |t| {
1027                matches!(
1028                    t,
1029                    Atomic::TFloat | Atomic::TIntegralFloat | Atomic::TLiteralFloat(..)
1030                ) || matches!(t, Atomic::TTemplateParam { .. } | Atomic::TValueOf { .. })
1031            },
1032            |t| matches!(t, Atomic::TMixed | Atomic::TScalar | Atomic::TNumeric),
1033            Atomic::TFloat,
1034        )
1035    }
1036
1037    /// Narrow as if `is_bool($x)` is true.
1038    pub fn narrow_to_bool(&self) -> Type {
1039        self.filter_replacing(
1040            |t| {
1041                matches!(
1042                    t,
1043                    Atomic::TBool
1044                        | Atomic::TTrue
1045                        | Atomic::TFalse
1046                        | Atomic::TTemplateParam { .. }
1047                        | Atomic::TValueOf { .. }
1048                )
1049            },
1050            |t| matches!(t, Atomic::TMixed | Atomic::TScalar),
1051            Atomic::TBool,
1052        )
1053    }
1054
1055    /// Narrow as if `is_null($x)` is true.
1056    pub fn narrow_to_null(&self) -> Type {
1057        self.filter_replacing(
1058            |t| matches!(t, Atomic::TNull | Atomic::TTemplateParam { .. }),
1059            |t| matches!(t, Atomic::TMixed),
1060            Atomic::TNull,
1061        )
1062    }
1063
1064    /// Narrow as if `is_array($x)` is true.
1065    pub fn narrow_to_array(&self) -> Type {
1066        self.filter_replacing(
1067            |t| t.is_array() || matches!(t, Atomic::TTemplateParam { .. }),
1068            |t| matches!(t, Atomic::TMixed),
1069            Atomic::TArray {
1070                key: Box::new(Type::mixed()),
1071                value: Box::new(Type::mixed()),
1072            },
1073        )
1074        .with_callable_form(self, callable_array())
1075    }
1076
1077    /// Turns a top-level `non-empty-list`/`non-empty-array` into `list`/`array`.
1078    pub fn widen_non_empty(&self) -> Type {
1079        let mut out = Type::empty();
1080        out.from_docblock = self.from_docblock;
1081        out.possibly_undefined = self.possibly_undefined;
1082        for a in &self.types {
1083            out.add_type(match a {
1084                Atomic::TNonEmptyList { value } => Atomic::TList {
1085                    value: value.clone(),
1086                },
1087                Atomic::TNonEmptyArray { key, value } => Atomic::TArray {
1088                    key: key.clone(),
1089                    value: value.clone(),
1090                },
1091                other => other.clone(),
1092            });
1093        }
1094        out
1095    }
1096
1097    /// Keeps the outer collection kind but turns every nested `non-empty-list`/`non-empty-array`
1098    /// into `list`/`array`, for comparisons that ignore element emptiness.
1099    pub fn widen_nested_non_empty(&self) -> Type {
1100        fn relax_all(ty: &Type) -> Type {
1101            map_atoms(ty, |a| match a {
1102                Atomic::TNonEmptyList { value } => Atomic::TList {
1103                    value: Box::new(relax_all(value)),
1104                },
1105                Atomic::TNonEmptyArray { key, value } => Atomic::TArray {
1106                    key: key.clone(),
1107                    value: Box::new(relax_all(value)),
1108                },
1109                other => map_values(other, relax_all),
1110            })
1111        }
1112        fn map_values(atomic: &Atomic, f: fn(&Type) -> Type) -> Atomic {
1113            match atomic {
1114                Atomic::TArray { key, value } => Atomic::TArray {
1115                    key: key.clone(),
1116                    value: Box::new(f(value)),
1117                },
1118                Atomic::TList { value } => Atomic::TList {
1119                    value: Box::new(f(value)),
1120                },
1121                Atomic::TNonEmptyArray { key, value } => Atomic::TNonEmptyArray {
1122                    key: key.clone(),
1123                    value: Box::new(f(value)),
1124                },
1125                Atomic::TNonEmptyList { value } => Atomic::TNonEmptyList {
1126                    value: Box::new(f(value)),
1127                },
1128                Atomic::TKeyedArray {
1129                    properties,
1130                    is_open,
1131                    is_list,
1132                } => Atomic::TKeyedArray {
1133                    properties: Arc::new(properties.map_types(f)),
1134                    is_open: *is_open,
1135                    is_list: *is_list,
1136                },
1137                other => other.clone(),
1138            }
1139        }
1140        fn map_atoms(ty: &Type, f: impl Fn(&Atomic) -> Atomic) -> Type {
1141            let mut result = Type::empty();
1142            result.possibly_undefined = ty.possibly_undefined;
1143            result.from_docblock = ty.from_docblock;
1144            for atomic in &ty.types {
1145                result.add_type(f(atomic));
1146            }
1147            result
1148        }
1149        map_atoms(self, |a| map_values(a, relax_all))
1150    }
1151
1152    /// Narrow array/list types to their non-empty variants (for `count() > 0` etc.),
1153    /// dropping the closed empty shape `array{}`.
1154    pub fn narrow_to_non_empty_collection(&self) -> Type {
1155        let mut out = Type::empty();
1156        out.from_docblock = self.from_docblock;
1157        for t in &self.types {
1158            match t {
1159                Atomic::TArray { key, value } => out.add_type(Atomic::TNonEmptyArray {
1160                    key: key.clone(),
1161                    value: value.clone(),
1162                }),
1163                Atomic::TList { value } => out.add_type(Atomic::TNonEmptyList {
1164                    value: value.clone(),
1165                }),
1166                Atomic::TKeyedArray {
1167                    properties,
1168                    is_open: false,
1169                    ..
1170                } if properties.is_empty() => {}
1171                _ => out.add_type(t.clone()),
1172            }
1173        }
1174        out
1175    }
1176
1177    /// Narrow array/list types when proven empty (e.g. `array_key_first($x) === null`,
1178    /// `$arr === []`). Drops the non-empty variants outright — they can never
1179    /// be empty — and narrows a plain `array`/`list` down to the same closed,
1180    /// zero-property `TKeyedArray` an empty `[]` literal itself types as, so
1181    /// e.g. `$values[0]` on a proven-empty branch is flagged as a
1182    /// `NonExistentArrayOffset` instead of silently keeping the pre-narrow
1183    /// element type. `TKeyedArray` atoms are left unchanged — narrowing an
1184    /// already-shaped array to "empty" when it may declare required
1185    /// properties is a separate, more nuanced case.
1186    pub fn narrow_to_empty_collection(&self) -> Type {
1187        let mut out = Type::empty();
1188        out.from_docblock = self.from_docblock;
1189        for t in &self.types {
1190            match t {
1191                Atomic::TNonEmptyArray { .. } | Atomic::TNonEmptyList { .. } => {}
1192                Atomic::TArray { .. } | Atomic::TList { .. } => {
1193                    out.add_type(Atomic::TKeyedArray {
1194                        properties: Arc::default(),
1195                        is_open: false,
1196                        is_list: true,
1197                    });
1198                }
1199                _ => out.add_type(t.clone()),
1200            }
1201        }
1202        out
1203    }
1204
1205    /// Narrow as if `array_is_list($x)` is true.
1206    /// Lists have sequential integer keys starting from 0, so:
1207    /// - `list<T>` / `non-empty-list<T>` are kept unchanged.
1208    /// - `array<int, T>` is narrowed to `list<T>` (could be sequential).
1209    /// - `non-empty-array<int, T>` is narrowed to `non-empty-list<T>`.
1210    /// - `TKeyedArray` (shape) is kept only when its own `is_list` flag is
1211    ///   already true — that flag is precise (set from the actual literal's
1212    ///   keys, or an explicit `list{...}` docblock), not a hint, so a
1213    ///   string-keyed or non-contiguous shape is correctly excluded.
1214    /// - `mixed` becomes `list<mixed>` (array_is_list implies array).
1215    /// - All other types (string-keyed arrays, non-arrays) are dropped.
1216    pub fn narrow_to_list(&self) -> Type {
1217        let mut out = Type::empty();
1218        out.from_docblock = self.from_docblock;
1219        for t in &self.types {
1220            match t {
1221                Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => out.add_type(t.clone()),
1222                // Guard on "key admits int" rather than "key is exactly TInt" —
1223                // `is_array($mixed)` narrows an unknown key to `Type::mixed()`,
1224                // which is a list candidate (the runtime shape is still unknown),
1225                // unlike a key statically known to exclude int entirely (e.g. a
1226                // docblock-declared `array<string, T>`), which must stay excluded.
1227                Atomic::TArray { key, value } if !key.narrow_to_int().is_empty() => {
1228                    out.add_type(Atomic::TList {
1229                        value: value.clone(),
1230                    });
1231                }
1232                Atomic::TNonEmptyArray { key, value } if !key.narrow_to_int().is_empty() => {
1233                    out.add_type(Atomic::TNonEmptyList {
1234                        value: value.clone(),
1235                    });
1236                }
1237                Atomic::TKeyedArray { is_list: true, .. } => out.add_type(t.clone()),
1238                Atomic::TMixed => out.add_type(Atomic::TList {
1239                    value: Box::new(Type::mixed()),
1240                }),
1241                _ => {}
1242            }
1243        }
1244        if out.is_empty() {
1245            self.filter(|t| matches!(t, Atomic::TList { .. } | Atomic::TNonEmptyList { .. }))
1246        } else {
1247            out
1248        }
1249    }
1250
1251    /// Narrow as if `is_object($x)` is true. A `mixed` becomes a concrete bare
1252    /// `object` (rather than staying `mixed`) so downstream object-only
1253    /// operations — `clone`, `instanceof`, method calls — see an object type
1254    /// instead of reporting `Mixed*`.
1255    pub fn narrow_to_object(&self) -> Type {
1256        let mut out = Type::empty();
1257        for t in &self.types {
1258            if matches!(t, Atomic::TMixed) {
1259                out.add_type(Atomic::TObject);
1260            } else if t.is_object() || matches!(t, Atomic::TTemplateParam { .. }) {
1261                out.add_type(t.clone());
1262            }
1263        }
1264        if out.types.is_empty() {
1265            self.filter(|t| t.is_object())
1266                .with_callable_form(self, Atomic::TObject)
1267        } else {
1268            out.with_callable_form(self, Atomic::TObject)
1269        }
1270    }
1271
1272    /// Adds `form` when `source` has a plain `callable`, which may be a function-name string,
1273    /// a `[class, method]` array or an invokable object.
1274    fn with_callable_form(mut self, source: &Type, form: Atomic) -> Type {
1275        if source
1276            .types
1277            .iter()
1278            .any(|t| matches!(t, Atomic::TCallable { .. }))
1279        {
1280            self.add_type(form);
1281        }
1282        self
1283    }
1284
1285    /// Narrow as if `is_callable($x)` is false: the `[class, method]` array a
1286    /// `callable` was narrowed to by `is_array()` is callable too.
1287    pub fn narrow_to_not_callable(&self) -> Type {
1288        let callable_array = callable_array();
1289        self.filter(|t| {
1290            !t.is_callable()
1291                && *t != callable_array
1292                && !matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.eq_ignore_ascii_case("Closure"))
1293        })
1294    }
1295
1296    /// Narrow as if `is_callable($x)` is true.
1297    ///
1298    /// PHP accepts closures, TCallable, strings (function names), arrays
1299    /// (['Class', 'method'] or [$obj, 'method']), and objects with __invoke.
1300    /// Keep all of these; only drop atoms that are definitely not callable
1301    /// (scalars, null, bool, etc.).
1302    pub fn narrow_to_callable(&self) -> Type {
1303        let narrowed = self.filter(|t| {
1304            t.is_callable()
1305                || t.is_string()
1306                || t.is_array()
1307                || t.is_object()
1308                || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1309        });
1310        // A bare `object` carries no known `__invoke` signature to compare
1311        // against a `callable`-typed target, so it stayed an object rather
1312        // than satisfying one — represent it as a generic callable instead,
1313        // matching what `is_callable()` actually proved. A `TNamedObject`
1314        // keeps its own class (its real `__invoke`, if any, is more precise
1315        // than a generic callable).
1316        let mut result = Type::empty();
1317        result.possibly_undefined = narrowed.possibly_undefined;
1318        result.from_docblock = narrowed.from_docblock;
1319        for atomic in narrowed.types {
1320            if matches!(atomic, Atomic::TObject | Atomic::TObjectShape { .. }) {
1321                result.add_type(Atomic::TCallable {
1322                    params: None,
1323                    return_type: None,
1324                    is_pure: false,
1325                });
1326            } else {
1327                result.add_type(atomic);
1328            }
1329        }
1330        result
1331    }
1332
1333    /// Narrow as if `is_scalar($x)` is true (int | string | float | bool).
1334    pub fn narrow_to_scalar(&self) -> Type {
1335        self.filter_replacing(
1336            |t| {
1337                t.is_string()
1338                    || t.is_int()
1339                    || matches!(
1340                        t,
1341                        Atomic::TFloat
1342                            | Atomic::TIntegralFloat
1343                            | Atomic::TLiteralFloat(..)
1344                            | Atomic::TBool
1345                            | Atomic::TTrue
1346                            | Atomic::TFalse
1347                            | Atomic::TScalar
1348                            | Atomic::TNumeric
1349                            | Atomic::TNumericString
1350                            | Atomic::TTemplateParam { .. }
1351                    )
1352            },
1353            |t| matches!(t, Atomic::TMixed),
1354            Atomic::TScalar,
1355        )
1356    }
1357
1358    /// Narrow as if `is_iterable($x)` is true (array | Traversable).
1359    /// For simplicity, this narrows to arrays or objects (can't easily verify interfaces).
1360    pub fn narrow_to_iterable(&self) -> Type {
1361        self.filter(|t| {
1362            t.is_array()
1363                || t.is_object()
1364                || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1365        })
1366    }
1367
1368    /// Narrow as if `is_countable($x)` is true (array | Countable).
1369    /// For simplicity, this narrows to arrays or objects (can't easily verify Countable interface).
1370    pub fn narrow_to_countable(&self) -> Type {
1371        self.filter(|t| {
1372            t.is_array()
1373                || t.is_object()
1374                || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1375        })
1376    }
1377
1378    /// Narrow as if `is_resource($x)` is true.
1379    pub fn narrow_to_resource(&self) -> Type {
1380        let mut out = self.filter(|t| match t {
1381            Atomic::TResource | Atomic::TOpenResource | Atomic::TMixed => true,
1382            Atomic::TTemplateParam { as_type, .. } => as_type.is_mixed(),
1383            _ => false,
1384        });
1385        for t in out.types.iter_mut() {
1386            if matches!(t, Atomic::TMixed) {
1387                *t = Atomic::TResource;
1388            }
1389        }
1390        out
1391    }
1392
1393    /// Narrow as if `class_exists($x)` returned true for a string variable.
1394    /// String atoms become `class-string`; existing class-string atoms pass through;
1395    /// mixed/scalar becomes `class-string`. Non-string atoms are dropped (returning
1396    /// empty so the caller can mark the branch as diverging).
1397    pub fn narrow_to_class_string(&self) -> Type {
1398        let mut out = Type::empty();
1399        out.from_docblock = self.from_docblock;
1400        for t in &self.types {
1401            match t {
1402                Atomic::TClassString(_) => out.add_type(t.clone()),
1403                _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
1404                    out.add_type(Atomic::TClassString(None));
1405                }
1406                _ => {}
1407            }
1408        }
1409        out
1410    }
1411
1412    /// Narrow as if `interface_exists($x)` returned true for a string variable.
1413    /// String atoms become `interface-string`; existing interface-string atoms pass
1414    /// through; mixed/scalar becomes `interface-string`. Non-string atoms are dropped
1415    /// (returning empty so the caller can mark the branch as diverging).
1416    pub fn narrow_to_interface_string(&self) -> Type {
1417        let mut out = Type::empty();
1418        out.from_docblock = self.from_docblock;
1419        for t in &self.types {
1420            match t {
1421                Atomic::TInterfaceString(_) => out.add_type(t.clone()),
1422                // A known class-string keeps its name — every interface-string is
1423                // also a valid class-string, so `interface_exists()` returning true
1424                // narrows the atom without losing which class it names.
1425                Atomic::TClassString(name) => {
1426                    out.add_type(Atomic::TInterfaceString(*name));
1427                }
1428                _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
1429                    out.add_type(Atomic::TInterfaceString(None));
1430                }
1431                _ => {}
1432            }
1433        }
1434        out
1435    }
1436
1437    // --- Merge (branch join) ------------------------------------------------
1438
1439    /// Merge two unions at a branch join point (e.g. after if/else).
1440    /// The result is the union of all types in both.
1441    pub fn merge(a: &Type, b: &Type) -> Type {
1442        // Fast path: b is empty — nothing to add.
1443        if b.types.is_empty() {
1444            let mut result = a.clone();
1445            result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1446            return result;
1447        }
1448        // Fast path: a is empty — clone b.
1449        if a.types.is_empty() {
1450            let mut result = b.clone();
1451            result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1452            return result;
1453        }
1454        // Fast path: a is already mixed — b cannot widen it further.
1455        if a.types.len() == 1 && matches!(a.types[0], Atomic::TMixed) {
1456            let mut result = a.clone();
1457            result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1458            return result;
1459        }
1460        // Fast path: b contains mixed — result collapses to mixed.
1461        if b.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1462            return Type {
1463                types: smallvec::smallvec![Atomic::TMixed],
1464                possibly_undefined: a.possibly_undefined || b.possibly_undefined,
1465                from_docblock: a.from_docblock || b.from_docblock,
1466                falsy_stripped: false,
1467                possibly_absent_offset: false,
1468            };
1469        }
1470        let mut result = a.clone();
1471        result.merge_with(b);
1472        result
1473    }
1474
1475    /// Merge `other` into `self` in-place (avoids cloning `self`).
1476    pub fn merge_with(&mut self, other: &Type) {
1477        if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1478            self.possibly_undefined |= other.possibly_undefined;
1479            return;
1480        }
1481        if other.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1482            self.types.clear();
1483            self.types.push(Atomic::TMixed);
1484            self.possibly_undefined |= other.possibly_undefined;
1485            return;
1486        }
1487        for atomic in &other.types {
1488            // `add_type` may rewrite a conditional, so only plain atomics short-circuit.
1489            if matches!(atomic, Atomic::TConditional { .. }) {
1490                self.add_type(atomic.clone());
1491            } else if !self.types.contains(atomic)
1492                && !self.types.iter().any(|t| matches!(t, Atomic::TMixed))
1493            {
1494                self.add_absent_type(atomic.clone());
1495            }
1496        }
1497        self.possibly_undefined |= other.possibly_undefined;
1498    }
1499
1500    /// Intersect with another union: keep only types present in `other`, widening
1501    /// where `self` contains `mixed` (which is compatible with everything).
1502    /// Used for match-arm subject narrowing.
1503    pub fn intersect_with(&self, other: &Type) -> Type {
1504        if self.is_mixed() {
1505            return other.clone();
1506        }
1507        if other.is_mixed() {
1508            return self.clone();
1509        }
1510        // Keep the more specific of each overlapping (self, other) atomic
1511        // pair — e.g. intersecting `int` with `1|2` must keep `1|2` (the
1512        // narrower side), not `int` (self's own, wider atomic): the whole
1513        // point of narrowing a variable against a match/switch arm's
1514        // literal conditions is to end up with the literal, not the bare
1515        // declared type it already had. Every matching pair is kept (not
1516        // just the first), so `int ∩ (1|2)` keeps both `1` and `2`.
1517        let mut result = Type::empty();
1518        for a in &self.types {
1519            for b in &other.types {
1520                if a == b {
1521                    result.add_type(a.clone());
1522                } else if atomic_subtype(b, a) {
1523                    result.add_type(b.clone());
1524                } else if atomic_subtype(a, b) {
1525                    result.add_type(a.clone());
1526                }
1527            }
1528        }
1529        if result.is_empty() {
1530            Type::never()
1531        } else {
1532            result
1533        }
1534    }
1535
1536    // --- Template substitution ----------------------------------------------
1537
1538    /// Replace template param references with their resolved types.
1539    pub fn substitute_templates(&self, bindings: &FxHashMap<Name, Type>) -> Type {
1540        if bindings.is_empty() {
1541            return self.clone();
1542        }
1543        // Most argument/return types are plain scalars or resolved objects
1544        // with nothing to substitute — skip the rebuild entirely.
1545        if !self.types.iter().any(atomic_may_contain_templates) {
1546            return self.clone();
1547        }
1548        let mut result = Type::empty();
1549        result.possibly_undefined = self.possibly_undefined;
1550        result.from_docblock = self.from_docblock;
1551        for atomic in &self.types {
1552            match atomic {
1553                Atomic::TTemplateParam { name, .. } => {
1554                    if let Some(resolved) = bindings.get(name) {
1555                        for t in &resolved.types {
1556                            result.add_type(t.clone());
1557                        }
1558                    } else {
1559                        result.add_type(atomic.clone());
1560                    }
1561                }
1562                Atomic::TArray { key, value } => {
1563                    result.add_type(Atomic::TArray {
1564                        key: Box::new(key.substitute_templates(bindings)),
1565                        value: Box::new(value.substitute_templates(bindings)),
1566                    });
1567                }
1568                Atomic::TList { value } => {
1569                    result.add_type(Atomic::TList {
1570                        value: Box::new(value.substitute_templates(bindings)),
1571                    });
1572                }
1573                Atomic::TNonEmptyArray { key, value } => {
1574                    result.add_type(Atomic::TNonEmptyArray {
1575                        key: Box::new(key.substitute_templates(bindings)),
1576                        value: Box::new(value.substitute_templates(bindings)),
1577                    });
1578                }
1579                Atomic::TNonEmptyList { value } => {
1580                    result.add_type(Atomic::TNonEmptyList {
1581                        value: Box::new(value.substitute_templates(bindings)),
1582                    });
1583                }
1584                Atomic::TKeyedArray {
1585                    properties,
1586                    is_open,
1587                    is_list,
1588                } => {
1589                    let new_props = properties.map_types(|ty| ty.substitute_templates(bindings));
1590                    result.add_type(Atomic::TKeyedArray {
1591                        properties: Arc::new(new_props),
1592                        is_open: *is_open,
1593                        is_list: *is_list,
1594                    });
1595                }
1596                Atomic::TCallable {
1597                    params,
1598                    return_type,
1599                    is_pure,
1600                } => {
1601                    result.add_type(Atomic::TCallable {
1602                        params: params.as_ref().map(|ps| {
1603                            Box::new(
1604                                ps.iter()
1605                                    .map(|p| substitute_in_fn_param(p, bindings))
1606                                    .collect(),
1607                            )
1608                        }),
1609                        return_type: return_type
1610                            .as_ref()
1611                            .map(|r| Box::new(r.substitute_templates(bindings))),
1612                        is_pure: *is_pure,
1613                    });
1614                }
1615                Atomic::TClosure { data } => {
1616                    result.add_type(Atomic::TClosure {
1617                        data: Box::new(crate::atomic::ClosureData {
1618                            params: data
1619                                .params
1620                                .iter()
1621                                .map(|p| substitute_in_fn_param(p, bindings))
1622                                .collect(),
1623                            return_type: data.return_type.substitute_templates(bindings),
1624                            this_type: data
1625                                .this_type
1626                                .as_ref()
1627                                .map(|t| t.substitute_templates(bindings)),
1628                            is_pure: data.is_pure,
1629                            is_static: data.is_static,
1630                            rejects_surplus_args: data.rejects_surplus_args,
1631                            is_impure: data.is_impure,
1632                        }),
1633                    });
1634                }
1635                Atomic::TConditional { data } => {
1636                    let param_name = &data.param_name;
1637                    let new_subject = data.subject.substitute_templates(bindings);
1638                    let new_if_true = data.if_true.substitute_templates(bindings);
1639                    let new_if_false = data.if_false.substitute_templates(bindings);
1640
1641                    // If param_name names a template that is bound in this substitution,
1642                    // resolve the conditional immediately using the same predicate logic as
1643                    // `resolve_conditional_returns` for the $param form.
1644                    let resolved = if let Some(name) = param_name {
1645                        if let Some(bound) = bindings.get(name) {
1646                            resolve_conditional_branch(
1647                                &new_subject,
1648                                bound,
1649                                &new_if_true,
1650                                &new_if_false,
1651                            )
1652                        } else {
1653                            None
1654                        }
1655                    } else {
1656                        None
1657                    };
1658
1659                    if let Some(branch) = resolved {
1660                        for t in branch.types {
1661                            result.add_type(t);
1662                        }
1663                    } else {
1664                        result.add_type(Atomic::TConditional {
1665                            data: Box::new(crate::atomic::ConditionalData {
1666                                param_name: *param_name,
1667                                subject: new_subject,
1668                                if_true: new_if_true,
1669                                if_false: new_if_false,
1670                            }),
1671                        });
1672                    }
1673                }
1674                Atomic::TKeyOf { target } => {
1675                    let new_target = target.substitute_templates(bindings);
1676                    if let Some(resolved) = eval_key_of_type(&new_target) {
1677                        result.merge_with(&resolved);
1678                    } else {
1679                        result.add_type(Atomic::TKeyOf {
1680                            target: Box::new(new_target),
1681                        });
1682                    }
1683                }
1684                Atomic::TValueOf { target } => {
1685                    let new_target = target.substitute_templates(bindings);
1686                    if let Some(resolved) = eval_value_of_type(&new_target) {
1687                        result.merge_with(&resolved);
1688                    } else {
1689                        result.add_type(Atomic::TValueOf {
1690                            target: Box::new(new_target),
1691                        });
1692                    }
1693                }
1694                Atomic::TIntersection { parts } => {
1695                    result.add_type(Atomic::TIntersection {
1696                        parts: vec_to_type_params(
1697                            parts
1698                                .iter()
1699                                .map(|p| p.substitute_templates(bindings))
1700                                .collect(),
1701                        ),
1702                    });
1703                }
1704                Atomic::TNamedObject { fqcn, type_params } => {
1705                    // See issue #26 for context.
1706                    if type_params.is_empty() && !fqcn.contains('\\') {
1707                        if let Some(resolved) = bindings.get(fqcn) {
1708                            for t in &resolved.types {
1709                                result.add_type(t.clone());
1710                            }
1711                            continue;
1712                        }
1713                    }
1714                    let new_params: Vec<Type> = type_params
1715                        .iter()
1716                        .map(|p| p.substitute_templates(bindings))
1717                        .collect();
1718                    result.add_type(Atomic::TNamedObject {
1719                        fqcn: *fqcn,
1720                        type_params: vec_to_type_params(new_params),
1721                    });
1722                }
1723                // class-string<T> → substitute T from bindings
1724                Atomic::TClassString(Some(param_name)) => {
1725                    if let Some(resolved) = bindings.get(param_name) {
1726                        for r_atomic in &resolved.types {
1727                            let cls_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1728                                Some(*fqcn)
1729                            } else {
1730                                None
1731                            };
1732                            result.add_type(Atomic::TClassString(cls_name));
1733                        }
1734                    } else {
1735                        result.add_type(atomic.clone());
1736                    }
1737                }
1738                // interface-string<T> → substitute T from bindings
1739                Atomic::TInterfaceString(Some(param_name)) => {
1740                    if let Some(resolved) = bindings.get(param_name) {
1741                        for r_atomic in &resolved.types {
1742                            let iface_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1743                                Some(*fqcn)
1744                            } else {
1745                                None
1746                            };
1747                            result.add_type(Atomic::TInterfaceString(iface_name));
1748                        }
1749                    } else {
1750                        result.add_type(atomic.clone());
1751                    }
1752                }
1753                _ => {
1754                    result.add_type(atomic.clone());
1755                }
1756            }
1757        }
1758        result
1759    }
1760
1761    /// Resolves `TConditional` atoms whose discriminator is known at the call site.
1762    ///
1763    /// `lookup(param_name)` returns the call-site argument type for the named parameter,
1764    /// or `None` if the argument is not available. Handles `is null`, `is string`, and
1765    /// `is array` conditions; other condition types pass through unchanged.
1766    pub fn resolve_conditional_returns<F>(self, lookup: F) -> Type
1767    where
1768        F: Fn(&str) -> Option<Type>,
1769    {
1770        self.resolve_conditional_inner(&lookup)
1771    }
1772
1773    fn resolve_conditional_inner<F>(self, lookup: &F) -> Type
1774    where
1775        F: Fn(&str) -> Option<Type>,
1776    {
1777        let mut result = Type::empty();
1778        for atomic in self.types {
1779            match atomic {
1780                Atomic::TConditional { ref data } => {
1781                    let (param_name, subject, if_true, if_false) = (
1782                        &data.param_name,
1783                        &data.subject,
1784                        &data.if_true,
1785                        &data.if_false,
1786                    );
1787                    let resolved =
1788                        param_name
1789                            .and_then(|name| lookup(name.as_ref()))
1790                            .and_then(|arg_ty| {
1791                                resolve_conditional_branch(subject, &arg_ty, if_true, if_false)
1792                            });
1793
1794                    if let Some(branch) = resolved {
1795                        // Recursively resolve nested conditionals in the selected branch.
1796                        for t in branch.resolve_conditional_inner(lookup).types {
1797                            result.add_type(t);
1798                        }
1799                    } else {
1800                        // Cannot resolve at this call site: widen to the union of both branches.
1801                        // Recursively resolve nested conditionals in each branch.
1802                        for t in if_true.clone().resolve_conditional_inner(lookup).types {
1803                            result.add_type(t);
1804                        }
1805                        for t in if_false.clone().resolve_conditional_inner(lookup).types {
1806                            result.add_type(t);
1807                        }
1808                    }
1809                }
1810                other => result.add_type(other),
1811            }
1812        }
1813        result
1814    }
1815
1816    // --- Subtype check -------------------------------------------------------
1817
1818    /// Returns true if every atomic in `self` is a subtype of some atomic in `other`,
1819    /// using **only structural rules** — no `extends` / `implements` walk.
1820    ///
1821    /// Two distinct user-defined classes are never related here, even when one
1822    /// extends the other. Within `mir-analyzer`, when a `db` is in scope,
1823    /// prefer `crate::subtype::is_subtype(db, sub, sup)` which layers
1824    /// inheritance resolution on top of this check.
1825    pub fn is_subtype_structural(&self, other: &Type) -> bool {
1826        if other.is_mixed() {
1827            return true;
1828        }
1829        if self.is_never() {
1830            return true; // never <: everything
1831        }
1832        self.types.iter().all(|a| {
1833            let fits = |a: &Atomic| other.accepts_atomic_structural(a);
1834            fits(a)
1835                || composite_parts(a).is_some_and(|parts| parts.iter().all(fits))
1836                || small_int_range(a)
1837                    .is_some_and(|mut values| values.all(|n| fits(&Atomic::TLiteralInt(n))))
1838        })
1839    }
1840
1841    /// Rewrites small bounded int ranges as literal ints so `int<-1, 1>` fits `-1|0|1`.
1842    pub fn expand_small_int_ranges(&self) -> Option<Type> {
1843        if !self.types.iter().any(|a| small_int_range(a).is_some()) {
1844            return None;
1845        }
1846        let mut out = Type::empty();
1847        for a in &self.types {
1848            match small_int_range(a) {
1849                Some(values) => values.for_each(|n| out.add_type(Atomic::TLiteralInt(n))),
1850                None => out.add_type(a.clone()),
1851            }
1852        }
1853        Some(out)
1854    }
1855
1856    /// Like `is_subtype_structural`, but a template atom is judged by its bound
1857    /// (an unbound one is `mixed` and fits anything).
1858    pub fn is_subtype_by_template_bounds(&self, other: &Type) -> bool {
1859        self.is_subtype_structural(other)
1860            || self.types.iter().all(|a| match a {
1861                Atomic::TTemplateParam { as_type, .. } => {
1862                    as_type.is_subtype_by_template_bounds(other)
1863                }
1864                _ => other.accepts_atomic_structural(a),
1865            })
1866    }
1867
1868    /// `sub <: self`, structurally, for a single atomic — equivalent to
1869    /// `Type::single(sub.clone()).is_subtype_structural(self)` without the
1870    /// clone and the temporary single-atomic union.
1871    pub fn accepts_atomic_structural(&self, sub: &Atomic) -> bool {
1872        if self.is_mixed() {
1873            return true;
1874        }
1875        // An int stays an int when the union lists int types; it widens to `float` only otherwise.
1876        let int_skips_float = sub.is_int() && self.types.iter().any(Atomic::is_int);
1877        matches!(sub, Atomic::TNever)
1878            || self.types.iter().any(|b| {
1879                !(int_skips_float && matches!(b, Atomic::TFloat)) && atomic_subtype(sub, b)
1880            })
1881    }
1882
1883    // --- Utilities ----------------------------------------------------------
1884
1885    fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Type {
1886        let mut result = Type::empty();
1887        result.possibly_undefined = self.possibly_undefined;
1888        result.from_docblock = self.from_docblock;
1889        for atomic in &self.types {
1890            if f(atomic) {
1891                result.types.push(atomic.clone());
1892            }
1893        }
1894        result
1895    }
1896
1897    /// Like `filter`, but atoms matching `placeholder` are substituted with
1898    /// `replacement` instead of passing through unchanged. Used so narrowing
1899    /// an unrefined `mixed`/`scalar`/`numeric` value (e.g. via `is_int($x)`)
1900    /// yields the concrete narrowed type instead of staying `mixed`.
1901    fn filter_replacing<K: Fn(&Atomic) -> bool, P: Fn(&Atomic) -> bool>(
1902        &self,
1903        keep: K,
1904        placeholder: P,
1905        replacement: Atomic,
1906    ) -> Type {
1907        let mut result = Type::empty();
1908        result.possibly_undefined = self.possibly_undefined;
1909        result.from_docblock = self.from_docblock;
1910        for atomic in &self.types {
1911            if keep(atomic) {
1912                result.add_type(atomic.clone());
1913            } else if placeholder(atomic) {
1914                result.add_type(replacement.clone());
1915            }
1916        }
1917        result
1918    }
1919
1920    /// Mark this union as possibly-undefined and return it.
1921    pub fn possibly_undefined(mut self) -> Self {
1922        self.possibly_undefined = true;
1923        self
1924    }
1925
1926    /// Mark this union as coming from a docblock annotation.
1927    pub fn from_docblock(mut self) -> Self {
1928        self.from_docblock = true;
1929        self
1930    }
1931
1932    /// Mark this union as having had a `false`/`null` failure variant stripped
1933    /// for flow purposes (see the field doc on [`Type::falsy_stripped`]).
1934    pub fn falsy_stripped(mut self) -> Self {
1935        self.falsy_stripped = true;
1936        self
1937    }
1938
1939    /// Mark this union as read from a generic array/list offset whose key
1940    /// presence isn't statically provable (see the field doc on
1941    /// [`Type::possibly_absent_offset`]).
1942    pub fn possibly_absent_offset(mut self) -> Self {
1943        self.possibly_absent_offset = true;
1944        self
1945    }
1946}
1947
1948// ---------------------------------------------------------------------------
1949// Conditional return resolution helpers
1950// ---------------------------------------------------------------------------
1951
1952/// Coarse value class of a runtime value.
1953///
1954/// One atom may hold several classes (a `bool` may hold `true` *or*
1955/// `false`; a `scalar` argument is one of the five scalar classes).
1956/// Literal refinements stay precise only where they matter: `int`/`float`
1957/// literals get their own class so that `int` and `float` literals decide
1958/// against each other's subjects; string literals collapse to
1959/// [`ValueClass::String`] (refined string kinds never feed a conditional
1960/// subject and would only cost match precision).
1961#[derive(Clone, PartialEq, Eq, Debug)]
1962enum ValueClass {
1963    Int,
1964    Float,
1965    True,
1966    False,
1967    String,
1968    Array,
1969    /// `list`-shaped arrays (sequential integer keys) — a refinement of [`Array`].
1970    List,
1971    Object,
1972    Resource,
1973    Null,
1974    /// `mixed`/`void` — a value of every class; it overlaps every other
1975    /// class, so a `mixed` argument rules out no branch.
1976    Top,
1977    /// Literal `int` — precise against `int`/`float` subjects: an `int`
1978    /// literal is not a float, a float literal is not an int.
1979    LitInt(i64),
1980    /// Literal `float` — the bit decomposition mirrors [`Atomic::TLiteralFloat`].
1981    LitFloat(i64, i64),
1982    /// A specific `string` literal.
1983    LitString(Arc<str>),
1984    /// `class-string` and its kin — a refinement of [`String`].
1985    ClassString,
1986}
1987
1988impl ValueClass {
1989    /// Whether a value of class `b` is necessarily a value of class `a`, i.e.
1990    /// whether the class lattice (`int` literal <: `int` <: `scalar`;
1991    /// `list` <: `array`; `true`/`false` <: `bool`; `mixed` <: everything)
1992    /// places `b` beneath `a`.
1993    fn includes(&self, b: &Self) -> bool {
1994        self == b
1995            || matches!(
1996                (self, b),
1997                (Self::Top, _)
1998                    | (Self::Int, Self::LitInt(_))
1999                    | (Self::Float, Self::LitFloat(..))
2000                    | (Self::String, Self::LitString(_))
2001                    | (Self::String, Self::ClassString)
2002                    | (Self::Array, Self::List)
2003            )
2004    }
2005
2006    /// Whether some value is of both classes. A string literal may name a class.
2007    fn overlaps(&self, b: &Self) -> bool {
2008        self.includes(b)
2009            || b.includes(self)
2010            || matches!(
2011                (self, b),
2012                (Self::ClassString, Self::LitString(_)) | (Self::LitString(_), Self::ClassString)
2013            )
2014    }
2015}
2016
2017/// The value classes an atom may hold.
2018///
2019/// Meta-types map to every class they may hold (`TBool` holds `true` *and*
2020/// `false`); opaque/deferred atoms (`TTemplateParam`, `TKeyOf`, …) map to
2021/// none — an argument of such a type rules out no branch.
2022fn value_classes(a: &Atomic) -> Vec<ValueClass> {
2023    use ValueClass::*;
2024    match a {
2025        // Integers (range bounds are not modeled: a subject `int` is a
2026        // family question).
2027        Atomic::TInt
2028        | Atomic::TIntRange { .. }
2029        | Atomic::TPositiveInt
2030        | Atomic::TNegativeInt
2031        | Atomic::TNonNegativeInt
2032        | Atomic::TRefinedInt(_) => vec![Int],
2033        Atomic::TLiteralInt(v) => vec![LitInt(*v)],
2034        // Floats.
2035        Atomic::TFloat | Atomic::TIntegralFloat => vec![Float],
2036        Atomic::TLiteralFloat(int_bits, frac_bits) => {
2037            vec![LitFloat(*int_bits, *frac_bits)]
2038        }
2039        // Bools.
2040        Atomic::TBool => vec![True, False],
2041        Atomic::TTrue => vec![True],
2042        Atomic::TFalse => vec![False],
2043        // Strings — every refined string kind maps to one class.
2044        Atomic::TString
2045        | Atomic::TNonEmptyString
2046        | Atomic::TNonFalsyString
2047        | Atomic::TRefinedString { .. }
2048        | Atomic::TNumericString
2049        | Atomic::TCallableString => vec![String],
2050        Atomic::TClassString(_)
2051        | Atomic::TInterfaceString(_)
2052        | Atomic::TEnumString
2053        | Atomic::TTraitString => vec![ClassString],
2054        Atomic::TLiteralString(s) => vec![LitString(s.clone())],
2055        // Arrays — `list` is a refinement of `array`.
2056        Atomic::TArray { .. }
2057        | Atomic::TPropertiesOf { .. }
2058        | Atomic::TNonEmptyArray { .. }
2059        | Atomic::TKeyedArray { is_list: false, .. } => vec![Array],
2060        Atomic::TList { .. }
2061        | Atomic::TNonEmptyList { .. }
2062        | Atomic::TKeyedArray { is_list: true, .. } => vec![List],
2063        // Objects — a specific class instance is an object at runtime.
2064        Atomic::TObject
2065        | Atomic::TObjectShape { .. }
2066        | Atomic::TNamedObject { .. }
2067        | Atomic::TStaticObject { .. }
2068        | Atomic::TSelf { .. }
2069        | Atomic::TParent { .. }
2070        | Atomic::TClosure { .. }
2071        | Atomic::TLiteralEnumCase { .. } => vec![Object],
2072        // Null. `void` maps to `Top` (a `void`-typed value is unknown; treating
2073        // it as "everything" keeps any branch it feeds undecidable).
2074        Atomic::TNull => vec![Null],
2075        Atomic::TResource | Atomic::TClosedResource | Atomic::TOpenResource => vec![Resource],
2076        Atomic::TVoid => vec![Top],
2077        // Everything / scalars.
2078        Atomic::TMixed => vec![Top],
2079        Atomic::TScalar => vec![Int, Float, True, False, String],
2080        // `numeric` may hold `int` or `float` values (a numeric *string*
2081        // can never be the discriminant of an `is numeric` subject).
2082        Atomic::TNumeric => vec![Int, Float],
2083        // Opaque / deferred — rules out no branch.
2084        Atomic::TCallable { .. }
2085        | Atomic::TNever
2086        | Atomic::TTemplateParam { .. }
2087        | Atomic::TKeyOf { .. }
2088        | Atomic::TValueOf { .. }
2089        | Atomic::TConditional { .. }
2090        | Atomic::TIntersection { .. } => Vec::new(),
2091    }
2092}
2093
2094/// Whether a conditional discriminant subject can be decided by value class.
2095///
2096/// Only the bare family kinds and scalar literals qualify. A refined subject (a named object, a
2097/// shape, a non-empty list, an enum case, …) carries value-level constraints
2098/// the class lattice cannot express — an argument that is *some* object is
2099/// not necessarily *that* class — so refined subjects stay undecidable, the
2100/// same behavior as the pre-class predicate (which had no arm for them).
2101fn subject_is_decidable(subject: &Atomic) -> bool {
2102    matches!(
2103        subject,
2104        Atomic::TNull
2105            | Atomic::TTrue
2106            | Atomic::TFalse
2107            | Atomic::TBool
2108            | Atomic::TString
2109            | Atomic::TClassString(None)
2110            | Atomic::TInt
2111            | Atomic::TFloat
2112            | Atomic::TLiteralString(_)
2113            | Atomic::TLiteralInt(_)
2114            | Atomic::TLiteralFloat(..)
2115            | Atomic::TArray { .. }
2116            | Atomic::TList { .. }
2117            | Atomic::TObject
2118            | Atomic::TObjectShape { .. }
2119            | Atomic::TResource
2120            | Atomic::TOpenResource
2121            | Atomic::TMixed
2122            | Atomic::TScalar
2123    )
2124}
2125
2126/// Resolve one branch of a conditional return type given the subject
2127/// discriminant and the actual argument type at the call site.
2128///
2129/// Returns `Some(branch)` when the branch can be determined statically, or
2130/// `None` to signal that the caller should widen to the union of both
2131/// branches.
2132///
2133/// Decision rule (value-class semantics): the discriminant and the argument
2134/// are compared *only on value classes* — the value sets the runtime type
2135/// system uses for narrowing. Class containment is the same lattice the
2136/// subtype relation uses for these kinds (`true` ⊆ `bool` ⊆ `scalar`,
2137/// `list` ⊆ `array`, `int`/`float` literals distinct, `mixed` ⊆ everything),
2138/// so a subject kind and an argument kind are related iff some contained
2139/// class relates them.
2140///
2141/// The true branch commits when every argument class is contained in some
2142/// subject class (every value the argument can hold is a subject value); the
2143/// false branch commits when every argument class is disjoint from every
2144/// subject class (no value the argument can hold is a subject value).
2145/// Otherwise the branch is undecidable and the caller widens to the union of
2146/// both branches.
2147fn resolve_conditional_branch(
2148    subject: &Type,
2149    arg_ty: &Type,
2150    if_true: &Type,
2151    if_false: &Type,
2152) -> Option<Type> {
2153    if arg_ty.types.is_empty() {
2154        return None;
2155    }
2156    // `T is void`: only `void` itself matches; a known non-void value never does.
2157    if let [Atomic::TVoid] = subject.types.as_slice() {
2158        return match arg_ty.types.as_slice() {
2159            [Atomic::TVoid] => Some(if_true.clone()),
2160            types
2161                if types.iter().all(|a| {
2162                    !matches!(a, Atomic::TVoid | Atomic::TMixed | Atomic::TNull)
2163                        && !value_classes(a).is_empty()
2164                }) =>
2165            {
2166                Some(if_false.clone())
2167            }
2168            _ => None,
2169        };
2170    }
2171    if subject.types.is_empty() || !subject.types.iter().all(subject_is_decidable) {
2172        return None;
2173    }
2174    let subject_classes: Vec<ValueClass> = subject.types.iter().flat_map(value_classes).collect();
2175    let arg_classes: Vec<ValueClass> = arg_ty.types.iter().flat_map(value_classes).collect();
2176    if arg_classes.is_empty() {
2177        // Opaque argument (template, `key-of`, …) — no branch is ruled out.
2178        return None;
2179    }
2180    let all_match = arg_classes
2181        .iter()
2182        .all(|c| subject_classes.iter().any(|s| s.includes(c)));
2183    let any_overlap = arg_classes
2184        .iter()
2185        .any(|c| subject_classes.iter().any(|s| s.overlaps(c)));
2186    if all_match {
2187        Some(if_true.clone())
2188    } else if !any_overlap {
2189        Some(if_false.clone())
2190    } else {
2191        None
2192    }
2193}
2194
2195// ---------------------------------------------------------------------------
2196// Template substitution helpers
2197// ---------------------------------------------------------------------------
2198
2199/// Whether `substitute_templates` could change this atomic: it is either a
2200/// template reference itself or a container/callable that may hold one.
2201/// Mirrors the substituting arms of that function's match — keep in sync.
2202fn atomic_may_contain_templates(atomic: &Atomic) -> bool {
2203    match atomic {
2204        // Bare unqualified names double as template refs (docblock parser
2205        // workaround, see substitute_templates); qualified names only matter
2206        // when they carry generic params.
2207        Atomic::TNamedObject { fqcn, type_params } => {
2208            !type_params.is_empty() || !fqcn.contains('\\')
2209        }
2210        Atomic::TTemplateParam { .. }
2211        | Atomic::TKeyOf { .. }
2212        | Atomic::TValueOf { .. }
2213        | Atomic::TArray { .. }
2214        | Atomic::TList { .. }
2215        | Atomic::TNonEmptyArray { .. }
2216        | Atomic::TNonEmptyList { .. }
2217        | Atomic::TKeyedArray { .. }
2218        | Atomic::TCallable { .. }
2219        | Atomic::TClosure { .. }
2220        | Atomic::TConditional { .. }
2221        | Atomic::TIntersection { .. }
2222        | Atomic::TClassString(Some(_))
2223        | Atomic::TInterfaceString(Some(_)) => true,
2224        _ => false,
2225    }
2226}
2227
2228pub fn eval_key_of_type(t: &Type) -> Option<Type> {
2229    let mut result = Type::empty();
2230    for atomic in &t.types {
2231        match atomic {
2232            Atomic::TArray { key, .. } | Atomic::TNonEmptyArray { key, .. } => {
2233                for k in &key.types {
2234                    result.add_type(k.clone());
2235                }
2236            }
2237            Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => {
2238                result.add_type(Atomic::TInt);
2239            }
2240            Atomic::TKeyedArray { properties, .. } => {
2241                for key in properties.keys() {
2242                    match key {
2243                        crate::atomic::ArrayKey::Int(n) => result.add_type(Atomic::TLiteralInt(*n)),
2244                        crate::atomic::ArrayKey::String(s) => {
2245                            result.add_type(Atomic::TLiteralString(s.clone()))
2246                        }
2247                    }
2248                }
2249            }
2250            _ => return None,
2251        }
2252    }
2253    (!result.types.is_empty()).then_some(result)
2254}
2255
2256pub fn eval_value_of_type(t: &Type) -> Option<Type> {
2257    let mut result = Type::empty();
2258    for atomic in &t.types {
2259        match atomic {
2260            Atomic::TArray { value, .. }
2261            | Atomic::TNonEmptyArray { value, .. }
2262            | Atomic::TList { value }
2263            | Atomic::TNonEmptyList { value } => {
2264                result.merge_with(value);
2265            }
2266            Atomic::TKeyedArray { properties, .. } => {
2267                for prop in properties.values() {
2268                    result.merge_with(&prop.ty);
2269                }
2270            }
2271            _ => return None,
2272        }
2273    }
2274    (!result.types.is_empty()).then_some(result)
2275}
2276
2277fn substitute_in_fn_param(
2278    p: &crate::atomic::FnParam,
2279    bindings: &FxHashMap<Name, Type>,
2280) -> crate::atomic::FnParam {
2281    crate::atomic::FnParam {
2282        name: p.name,
2283        ty: p.ty.as_ref().map(|t| {
2284            let u = t.to_union();
2285            let substituted = u.substitute_templates(bindings);
2286            crate::compact::SimpleType::from_union(substituted)
2287        }),
2288        out_ty: p.out_ty.as_ref().map(|t| {
2289            let u = t.to_union();
2290            let substituted = u.substitute_templates(bindings);
2291            crate::compact::SimpleType::from_union(substituted)
2292        }),
2293        default: p.default.as_ref().map(|d| {
2294            let u = d.to_union();
2295            let substituted = u.substitute_templates(bindings);
2296            crate::compact::SimpleType::from_union(substituted)
2297        }),
2298        is_variadic: p.is_variadic,
2299        is_byref: p.is_byref,
2300        is_optional: p.is_optional,
2301    }
2302}
2303
2304// ---------------------------------------------------------------------------
2305// Atomic subtype (no codebase — structural check only)
2306// ---------------------------------------------------------------------------
2307
2308/// Atomics that are exactly a union of other atomics, so a union spelling out
2309/// every part (e.g. `string|int|float|bool`) accepts them.
2310/// Widest bounded `int<min, max>` checked value by value against literal ints.
2311const MAX_EXPANDED_INT_RANGE_SPAN: i64 = 16;
2312
2313fn small_int_range(atomic: &Atomic) -> Option<std::ops::RangeInclusive<i64>> {
2314    match atomic {
2315        Atomic::TIntRange {
2316            min: Some(lo),
2317            max: Some(hi),
2318        } if hi
2319            .checked_sub(*lo)
2320            .is_some_and(|d| (0..MAX_EXPANDED_INT_RANGE_SPAN).contains(&d)) =>
2321        {
2322            Some(*lo..=*hi)
2323        }
2324        _ => None,
2325    }
2326}
2327
2328fn composite_parts(atomic: &Atomic) -> Option<&'static [Atomic]> {
2329    match atomic {
2330        Atomic::TScalar => Some(&[Atomic::TInt, Atomic::TFloat, Atomic::TString, Atomic::TBool]),
2331        Atomic::TNumeric => Some(&[Atomic::TInt, Atomic::TFloat, Atomic::TNumericString]),
2332        _ => None,
2333    }
2334}
2335
2336fn object_shape_subtype(have: &KeyedProperties, want: &KeyedProperties) -> bool {
2337    want.iter().all(|(name, wanted)| match have.get(name) {
2338        Some(had) => (wanted.optional || !had.optional) && had.ty.is_subtype_structural(&wanted.ty),
2339        None => wanted.optional,
2340    })
2341}
2342
2343/// Structural `sub <: sup` for a single atomic pair, without hierarchy resolution.
2344pub fn atomic_subtype(sub: &Atomic, sup: &Atomic) -> bool {
2345    if sub == sup {
2346        return true;
2347    }
2348    // Until resolved against its class, `properties-of<Cls>` is a string-keyed array.
2349    let string_keyed_array = || Atomic::TArray {
2350        key: Box::new(Type::string()),
2351        value: Box::new(Type::mixed()),
2352    };
2353    match (sub, sup) {
2354        (Atomic::TClosedResource, Atomic::TOpenResource) => return false,
2355        // A handle of unknown state may still be open.
2356        (Atomic::TResource, Atomic::TOpenResource) => return true,
2357        (Atomic::TClosedResource | Atomic::TOpenResource, _) => {
2358            return atomic_subtype(&Atomic::TResource, sup)
2359        }
2360        (Atomic::TPropertiesOf { .. }, _) => return atomic_subtype(&string_keyed_array(), sup),
2361        (_, Atomic::TPropertiesOf { .. }) => return atomic_subtype(sub, &string_keyed_array()),
2362        (Atomic::TObjectShape { properties: have }, Atomic::TObjectShape { properties: want }) => {
2363            return object_shape_subtype(have, want);
2364        }
2365        (Atomic::TObjectShape { .. }, _) => return atomic_subtype(&Atomic::TObject, sup),
2366        // Without the codebase a class's properties are unknown, so any object may satisfy a shape.
2367        (_, Atomic::TObjectShape { .. }) => return atomic_subtype(sub, &Atomic::TObject),
2368        _ => {}
2369    }
2370    match (sub, sup) {
2371        // Bottom type
2372        (Atomic::TNever, _) => true,
2373        // Top types — anything goes in both directions for mixed
2374        (_, Atomic::TMixed) => true,
2375        (Atomic::TMixed, _) => true,
2376        // Template param in supertype position: any value satisfies an unconstrained
2377        // template (as_type = mixed), or a constrained one if it satisfies the bound.
2378        // This handles union bounds like `T of string|list<I>|array<K, V>` where
2379        // I/K/V are free template params — any type satisfies them structurally.
2380        (_, Atomic::TTemplateParam { as_type, .. }) => {
2381            as_type.is_mixed() || as_type.types.iter().any(|b| atomic_subtype(sub, b))
2382        }
2383
2384        // Scalars
2385        (Atomic::TLiteralInt(_), Atomic::TInt) => true,
2386        (Atomic::TLiteralInt(_), Atomic::TNumeric) => true,
2387        (Atomic::TLiteralInt(_), Atomic::TScalar) => true,
2388        (Atomic::TLiteralInt(_), Atomic::TRefinedInt(IntRefinement::Literal)) => true,
2389        (Atomic::TRefinedInt(_), _) => atomic_subtype(&Atomic::TInt, sup),
2390        (_, Atomic::TRefinedInt(IntRefinement::Literal)) => false,
2391        // An unresolved mask accepts what int accepts.
2392        (_, Atomic::TRefinedInt(IntRefinement::MaskOf(_))) => atomic_subtype(sub, &Atomic::TInt),
2393        (Atomic::TLiteralInt(n), Atomic::TPositiveInt) => *n > 0,
2394        (Atomic::TLiteralInt(n), Atomic::TNonNegativeInt) => *n >= 0,
2395        (Atomic::TLiteralInt(n), Atomic::TNegativeInt) => *n < 0,
2396        (Atomic::TPositiveInt, Atomic::TInt) => true,
2397        (Atomic::TPositiveInt, Atomic::TNonNegativeInt) => true,
2398        (Atomic::TPositiveInt, Atomic::TNumeric) => true,
2399        (Atomic::TPositiveInt, Atomic::TScalar) => true,
2400        (Atomic::TNegativeInt, Atomic::TInt) => true,
2401        (Atomic::TNegativeInt, Atomic::TNumeric) => true,
2402        (Atomic::TNegativeInt, Atomic::TScalar) => true,
2403        (Atomic::TNonNegativeInt, Atomic::TInt) => true,
2404        (Atomic::TNonNegativeInt, Atomic::TNumeric) => true,
2405        (Atomic::TNonNegativeInt, Atomic::TScalar) => true,
2406        (Atomic::TIntRange { .. }, Atomic::TInt) => true,
2407        (Atomic::TIntRange { .. }, Atomic::TNumeric) => true,
2408        (Atomic::TIntRange { .. }, Atomic::TScalar) => true,
2409        // positive-int is int<1, ∞>: subtype of int<sup_min, ∞> when sup_min <= 1
2410        (Atomic::TPositiveInt, Atomic::TIntRange { min, max }) => {
2411            max.is_none() && min.is_none_or(|m| m <= 1)
2412        }
2413        // negative-int is int<-∞, -1>: subtype of int<-∞, sup_max> when sup_max >= -1
2414        (Atomic::TNegativeInt, Atomic::TIntRange { min, max }) => {
2415            min.is_none() && max.is_none_or(|m| m >= -1)
2416        }
2417        // non-negative-int is int<0, ∞>: subtype of int<sup_min, ∞> when sup_min <= 0
2418        (Atomic::TNonNegativeInt, Atomic::TIntRange { min, max }) => {
2419            max.is_none() && min.is_none_or(|m| m <= 0)
2420        }
2421        // A bounded int range is a subtype of a named int subtype when every value fits
2422        (Atomic::TIntRange { min: sub_min, .. }, Atomic::TPositiveInt) => {
2423            sub_min.is_some_and(|lo| lo >= 1)
2424        }
2425        (Atomic::TIntRange { min: sub_min, .. }, Atomic::TNonNegativeInt) => {
2426            sub_min.is_some_and(|lo| lo >= 0)
2427        }
2428        (Atomic::TIntRange { max: sub_max, .. }, Atomic::TNegativeInt) => {
2429            sub_max.is_some_and(|hi| hi <= -1)
2430        }
2431        // int<sub_min, sub_max> <: int<sup_min, sup_max> when ranges nest
2432        (
2433            Atomic::TIntRange {
2434                min: sub_min,
2435                max: sub_max,
2436            },
2437            Atomic::TIntRange {
2438                min: sup_min,
2439                max: sup_max,
2440            },
2441        ) => {
2442            let lower_ok = match (sub_min, sup_min) {
2443                (_, None) => true,
2444                (None, Some(_)) => false,
2445                (Some(sl), Some(su)) => sl >= su,
2446            };
2447            let upper_ok = match (sub_max, sup_max) {
2448                (None, None) | (Some(_), None) => true,
2449                (None, Some(_)) => false,
2450                (Some(sl), Some(su)) => sl <= su,
2451            };
2452            lower_ok && upper_ok
2453        }
2454
2455        (Atomic::TLiteralFloat(..), Atomic::TFloat) => true,
2456        (Atomic::TLiteralFloat(..), Atomic::TNumeric) => true,
2457        (Atomic::TLiteralFloat(..), Atomic::TScalar) => true,
2458
2459        (Atomic::TLiteralString(s), Atomic::TString) => {
2460            let _ = s;
2461            true
2462        }
2463        (Atomic::TLiteralString(s), Atomic::TCallableString) => {
2464            let _ = s;
2465            true
2466        }
2467        (Atomic::TLiteralString(s), Atomic::TNonEmptyString) => !s.is_empty(),
2468        (Atomic::TLiteralString(s), Atomic::TNonFalsyString) => !s.is_empty() && s.as_ref() != "0",
2469        // "0" is non-empty and numeric, but falsy.
2470        (Atomic::TNonEmptyString | Atomic::TNumericString, Atomic::TNonFalsyString) => false,
2471        // Otherwise non-falsy-string relates to other types as non-empty-string does.
2472        (Atomic::TNonFalsyString, _) => atomic_subtype(&Atomic::TNonEmptyString, sup),
2473        (_, Atomic::TNonFalsyString) => atomic_subtype(sub, &Atomic::TNonEmptyString),
2474        (
2475            Atomic::TLiteralString(s),
2476            Atomic::TRefinedString {
2477                refinement,
2478                non_empty,
2479            },
2480        ) => refinement.accepts(s) && !(*non_empty && s.is_empty()),
2481        // `Foo::class` is written in the source.
2482        (
2483            Atomic::TClassString(Some(_)),
2484            Atomic::TRefinedString {
2485                refinement: StringRefinement::Literal,
2486                ..
2487            },
2488        ) => true,
2489        (
2490            Atomic::TRefinedString {
2491                refinement: have,
2492                non_empty: have_non_empty,
2493            },
2494            Atomic::TRefinedString {
2495                refinement: want,
2496                non_empty: want_non_empty,
2497            },
2498        ) => have == want && (*have_non_empty || !want_non_empty),
2499        // Otherwise a refined string relates to wider types as its unrefined form does.
2500        (
2501            Atomic::TRefinedString {
2502                refinement: StringRefinement::DecimalInt,
2503                ..
2504            },
2505            _,
2506        ) => atomic_subtype(&Atomic::TNumericString, sup),
2507        (Atomic::TRefinedString { non_empty, .. }, _) => {
2508            let base = if *non_empty {
2509                Atomic::TNonEmptyString
2510            } else {
2511                Atomic::TString
2512            };
2513            atomic_subtype(&base, sup)
2514        }
2515        (_, Atomic::TRefinedString { .. }) => false,
2516        (Atomic::TLiteralString(s), Atomic::TNumericString | Atomic::TNumeric) => {
2517            s.parse::<f64>().is_ok()
2518        }
2519        // A literal string is type-compatible with class-string; validate_class_string_argument
2520        // separately checks whether the string names a real class (UndefinedClass).
2521        (Atomic::TLiteralString(_), Atomic::TClassString(_)) => true,
2522        // Same, for interface-string; validate_interface_string_argument checks existence
2523        // and that the name actually resolves to an interface.
2524        (Atomic::TLiteralString(_), Atomic::TInterfaceString(_)) => true,
2525        (Atomic::TLiteralString(_), Atomic::TScalar) => true,
2526        (Atomic::TNonEmptyString, Atomic::TString) => true,
2527        (Atomic::TCallableString, Atomic::TString) => true,
2528        // numeric-string is always non-empty (e.g. "42", "-1", "0.5") — "" is not numeric.
2529        (Atomic::TNumericString, Atomic::TNonEmptyString) => true,
2530        (Atomic::TNumericString, Atomic::TString) => true,
2531        // A class/interface/callable/enum/trait name can never be the empty
2532        // string in real PHP — every one of these string-subtype atoms is
2533        // always non-empty, same reasoning as numeric-string above.
2534        (Atomic::TClassString(_), Atomic::TNonEmptyString) => true,
2535        (Atomic::TInterfaceString(_), Atomic::TNonEmptyString) => true,
2536        (Atomic::TCallableString, Atomic::TNonEmptyString) => true,
2537        (Atomic::TEnumString, Atomic::TNonEmptyString) => true,
2538        (Atomic::TTraitString, Atomic::TNonEmptyString) => true,
2539        (Atomic::TClassString(_), Atomic::TString) => true,
2540        (Atomic::TInterfaceString(_), Atomic::TString) => true,
2541        // Every interface-string is a valid class-string: PHP doesn't distinguish
2542        // the two at runtime — both are just strings naming a class-like symbol.
2543        // Instantiability (`new $x()`) is guarded separately, since an interface
2544        // name can never be `new`-ed even though it satisfies class-string.
2545        (Atomic::TInterfaceString(_), Atomic::TClassString(None)) => true,
2546        (Atomic::TClassString(Some(_)), Atomic::TClassString(None)) => true,
2547        (Atomic::TInterfaceString(Some(a)), Atomic::TClassString(Some(b))) => a == b,
2548        (Atomic::TEnumString, Atomic::TString) => true,
2549        (Atomic::TTraitString, Atomic::TString) => true,
2550
2551        (Atomic::TTrue, Atomic::TBool) => true,
2552        (Atomic::TFalse, Atomic::TBool) => true,
2553
2554        (Atomic::TInt, Atomic::TNumeric) => true,
2555        (Atomic::TFloat, Atomic::TNumeric) => true,
2556        (Atomic::TIntegralFloat, Atomic::TNumeric) => true,
2557        (Atomic::TNumericString, Atomic::TNumeric) => true,
2558
2559        (Atomic::TInt, Atomic::TScalar) => true,
2560        (Atomic::TFloat, Atomic::TScalar) => true,
2561        (Atomic::TIntegralFloat, Atomic::TScalar) => true,
2562        (Atomic::TString, Atomic::TScalar) => true,
2563        (Atomic::TBool, Atomic::TScalar) => true,
2564        (Atomic::TNumeric, Atomic::TScalar) => true,
2565        (Atomic::TTrue, Atomic::TScalar) => true,
2566        (Atomic::TFalse, Atomic::TScalar) => true,
2567        // Every refined string atom is, at runtime, still just a `string` —
2568        // and therefore a `scalar` — same as the already-covered TLiteralString
2569        // and int-family refinements just above/below.
2570        (Atomic::TNonEmptyString, Atomic::TScalar) => true,
2571        (Atomic::TNumericString, Atomic::TScalar) => true,
2572        (Atomic::TCallableString, Atomic::TScalar) => true,
2573        (Atomic::TClassString(_), Atomic::TScalar) => true,
2574        (Atomic::TInterfaceString(_), Atomic::TScalar) => true,
2575        (Atomic::TEnumString, Atomic::TScalar) => true,
2576        (Atomic::TTraitString, Atomic::TScalar) => true,
2577
2578        // Object hierarchy (structural, no codebase)
2579        (Atomic::TNamedObject { .. }, Atomic::TObject) => true,
2580        (Atomic::TStaticObject { .. }, Atomic::TObject) => true,
2581        (Atomic::TSelf { .. }, Atomic::TObject) => true,
2582        // An enum-case literal is, at runtime, an object.
2583        (Atomic::TLiteralEnumCase { .. }, Atomic::TObject) => true,
2584        // self(X) and static(X) satisfy TNamedObject(X) with same FQCN
2585        (Atomic::TSelf { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
2586        (Atomic::TStaticObject { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
2587        // TNamedObject(X) satisfies self(X) / static(X) with same FQCN
2588        (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TSelf { fqcn: b }) => a == b,
2589        (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TStaticObject { fqcn: b }) => a == b,
2590        // An enum-case literal satisfies its own bare enum type (enums are
2591        // represented as TNamedObject).
2592        (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TNamedObject { fqcn, .. }) => {
2593            enum_fqcn == fqcn
2594        }
2595        (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TSelf { fqcn })
2596        | (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TStaticObject { fqcn }) => {
2597            enum_fqcn == fqcn
2598        }
2599        // Bare generic property accepts parameterized value: Box accepts Box<string>.
2600        // The reverse is NOT true — bare Box value does not satisfy Box<string> property
2601        // (invariant check). Only sup being bare (empty type_params) is the wildcard.
2602        (
2603            Atomic::TNamedObject {
2604                fqcn: sub_fqcn,
2605                type_params: sub_params,
2606            },
2607            Atomic::TNamedObject {
2608                fqcn: sup_fqcn,
2609                type_params: sup_params,
2610            },
2611        ) => {
2612            sub_fqcn == sup_fqcn
2613                && (sup_params.is_empty() || type_params_compatible(sub_params, sup_params))
2614        }
2615
2616        // TIntegralFloat is a subtype of float (all integral floats are floats)
2617        (Atomic::TIntegralFloat, Atomic::TFloat) => true,
2618
2619        // Literal int widens to float in PHP
2620        (Atomic::TLiteralInt(_), Atomic::TFloat) => true,
2621        (Atomic::TPositiveInt, Atomic::TFloat) => true,
2622        (Atomic::TNegativeInt, Atomic::TFloat) => true,
2623        (Atomic::TNonNegativeInt, Atomic::TFloat) => true,
2624        (Atomic::TInt, Atomic::TFloat) => true,
2625        (Atomic::TIntRange { .. }, Atomic::TFloat) => true,
2626
2627        // Literal int satisfies an int range only when the value is within bounds
2628        (Atomic::TLiteralInt(n), Atomic::TIntRange { min, max }) => {
2629            min.is_none_or(|lo| *n >= lo) && max.is_none_or(|hi| *n <= hi)
2630        }
2631
2632        // PHP callables: string and array are valid callable values
2633        (Atomic::TString, Atomic::TCallable { .. }) => true,
2634        (Atomic::TCallableString, Atomic::TCallable { .. }) => true,
2635        (Atomic::TNonEmptyString, Atomic::TCallable { .. }) => true,
2636        (Atomic::TLiteralString(_), Atomic::TCallable { .. }) => true,
2637        (Atomic::TArray { .. }, Atomic::TCallable { .. }) => true,
2638        (Atomic::TNonEmptyArray { .. }, Atomic::TCallable { .. }) => true,
2639        (Atomic::TKeyedArray { .. }, Atomic::TCallable { .. }) => true,
2640
2641        // Closure <: callable, typed Closure <: Closure
2642        (Atomic::TClosure { .. }, Atomic::TCallable { .. }) => true,
2643        // callable <: Closure: callable is wider but not flagged at default error level
2644        (Atomic::TCallable { .. }, Atomic::TClosure { .. }) => true,
2645        // TClosure <: TClosure: check arity, per-parameter contravariance, and
2646        // return covariance for scalar/array-shaped types, where a purely
2647        // structural check is reliable. A named-class (or nested-callable)
2648        // param/return is skipped rather than checked — this checker has no
2649        // database access to walk `extends`/`implements`, so it can't safely
2650        // tell a real Liskov violation apart from a legitimate subclass/
2651        // superclass substitution; treating it as compatible avoids false
2652        // positives on that far more common case at the cost of missing the
2653        // narrower nominal-variance violation.
2654        (Atomic::TClosure { data: sub }, Atomic::TClosure { data: sup }) => {
2655            fn has_nominal_type(t: &Type) -> bool {
2656                t.types.iter().any(|a| {
2657                    matches!(
2658                        a,
2659                        Atomic::TNamedObject { .. }
2660                            | Atomic::TSelf { .. }
2661                            | Atomic::TStaticObject { .. }
2662                            | Atomic::TTemplateParam { .. }
2663                            | Atomic::TClosure { .. }
2664                            | Atomic::TCallable { .. }
2665                    )
2666                })
2667            }
2668            let sub_required = sub
2669                .params
2670                .iter()
2671                .filter(|p| !p.is_optional && !p.is_variadic)
2672                .count();
2673            if sub_required > sup.params.len() {
2674                false
2675            } else {
2676                let params_ok = sup.params.iter().enumerate().all(|(i, sup_param)| {
2677                    let Some(sub_param) = sub.params.get(i) else {
2678                        return true;
2679                    };
2680                    if sub_param.is_optional || sub_param.is_variadic {
2681                        return true;
2682                    }
2683                    let (Some(sub_ty), Some(sup_ty)) =
2684                        (sub_param.ty.as_ref(), sup_param.ty.as_ref())
2685                    else {
2686                        return true;
2687                    };
2688                    let (sub_u, sup_u) = (sub_ty.to_union(), sup_ty.to_union());
2689                    if has_nominal_type(&sub_u) || has_nominal_type(&sup_u) {
2690                        return true;
2691                    }
2692                    // Contravariance: whatever `sup` promises to pass must be
2693                    // acceptable to `sub`'s declared parameter type.
2694                    sup_u.is_subtype_structural(&sub_u)
2695                });
2696                params_ok
2697                    && (sub.return_type.is_mixed()
2698                        || sup.return_type.is_mixed()
2699                        // A void callback discards its return value, so any
2700                        // return type satisfies it — PHP places no
2701                        // constraint on what an implementation returns here.
2702                        || sup.return_type.is_void()
2703                        || has_nominal_type(&sub.return_type)
2704                        || has_nominal_type(&sup.return_type)
2705                        || sub.return_type.is_subtype_structural(&sup.return_type))
2706            }
2707        }
2708        // callable <: callable (trivial)
2709        (Atomic::TCallable { .. }, Atomic::TCallable { .. }) => true,
2710        // TClosure satisfies `Closure` named object or `object`
2711        (Atomic::TClosure { .. }, Atomic::TNamedObject { fqcn, .. }) => {
2712            fqcn.as_ref().eq_ignore_ascii_case("closure")
2713        }
2714        (Atomic::TClosure { .. }, Atomic::TObject) => true,
2715        // bare `Closure` (named object without signature) satisfies any typed Closure(): T
2716        (Atomic::TNamedObject { fqcn, .. }, Atomic::TClosure { .. }) => {
2717            fqcn.as_ref().eq_ignore_ascii_case("closure")
2718        }
2719        // `Closure` named-object satisfies `callable`
2720        (Atomic::TNamedObject { fqcn, .. }, Atomic::TCallable { .. }) => {
2721            fqcn.as_ref().eq_ignore_ascii_case("closure")
2722        }
2723
2724        // A&B&C <: D&E iff every part of the supertype is satisfied by some
2725        // part of the subtype — an intersection with MORE conjuncts is the
2726        // more specific (sub)type, so `Countable&ArrayAccess&Iterator` is a
2727        // subtype of `Countable&ArrayAccess`. Purely structural (each part's
2728        // own `is_subtype_structural` recurses, so e.g. two differently-named
2729        // interfaces only match when equal — same conservative stance as the
2730        // TClosure<:TClosure arm above for named types).
2731        (
2732            Atomic::TIntersection { parts: sub_parts },
2733            Atomic::TIntersection { parts: sup_parts },
2734        ) => sup_parts.iter().all(|sup_part| {
2735            sub_parts
2736                .iter()
2737                .any(|sub_part| sub_part.is_subtype_structural(sup_part))
2738        }),
2739        (Atomic::TIntersection { parts }, Atomic::TObject) => parts
2740            .iter()
2741            .any(|part| part.is_subtype_structural(&Type::single(Atomic::TObject))),
2742
2743        // List <: array  (list key is always int; int must satisfy the array's key type)
2744        (Atomic::TList { value }, Atomic::TArray { key, value: av }) => {
2745            Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2746        }
2747        (Atomic::TNonEmptyList { value }, Atomic::TArray { key, value: av }) => {
2748            Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2749        }
2750        (Atomic::TNonEmptyList { value }, Atomic::TNonEmptyArray { key, value: av }) => {
2751            Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2752        }
2753        (Atomic::TNonEmptyList { value }, Atomic::TList { value: lv }) => {
2754            value.is_subtype_structural(lv)
2755        }
2756        (Atomic::TNonEmptyList { value: v1 }, Atomic::TNonEmptyList { value: v2 }) => {
2757            v1.is_subtype_structural(v2)
2758        }
2759        // array<int, X> is accepted where list<X> or non-empty-list<X> expected
2760        (Atomic::TArray { key, value: av }, Atomic::TList { value: lv }) => {
2761            matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2762                && av.is_subtype_structural(lv)
2763        }
2764        (Atomic::TArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
2765            matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2766                && av.is_subtype_structural(lv)
2767        }
2768        (Atomic::TNonEmptyArray { key, value: av }, Atomic::TList { value: lv }) => {
2769            matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2770                && av.is_subtype_structural(lv)
2771        }
2772        (Atomic::TNonEmptyArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
2773            matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2774                && av.is_subtype_structural(lv)
2775        }
2776        // TList <: TList value covariance
2777        (Atomic::TList { value: v1 }, Atomic::TList { value: v2 }) => v1.is_subtype_structural(v2),
2778        (Atomic::TNonEmptyArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
2779            k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
2780        }
2781
2782        // array<A, B> <: array<C, D>  iff  A <: C && B <: D
2783        (Atomic::TArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
2784            k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
2785        }
2786
2787        // A keyed/shape array is a subtype of array<K, V> / non-empty-array<K, V>
2788        // when all property KEYS are subtypes of K. Value compatibility is checked
2789        // structurally only for scalar types; named-object values are deferred to
2790        // class-hierarchy checks in return_arrays_compatible (mir-analyzer).
2791        // Open shapes (is_open=true) may have extra unknown keys beyond `properties`:
2792        // those stay unchecked (permissive), but every KNOWN property must still
2793        // satisfy K/V regardless of openness — an open shape isn't a license to skip
2794        // checking the keys it does declare.
2795        (Atomic::TKeyedArray { properties, .. }, Atomic::TArray { key, value }) => {
2796            properties.iter().all(|(prop_key, prop)| {
2797                let key_atomic = match prop_key {
2798                    crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2799                    crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2800                };
2801                if !Type::single(key_atomic).is_subtype_structural(key) {
2802                    return false; // key mismatch — definitively incompatible
2803                }
2804                // Named-object values require class-hierarchy checks not available here.
2805                let has_named_obj = prop.ty.types.iter().any(|a| {
2806                    matches!(
2807                        a,
2808                        Atomic::TNamedObject { .. }
2809                            | Atomic::TSelf { .. }
2810                            | Atomic::TStaticObject { .. }
2811                            | Atomic::TClosure { .. }
2812                            | Atomic::TTemplateParam { .. }
2813                    )
2814                });
2815                has_named_obj || prop.ty.is_subtype_structural(value)
2816            })
2817        }
2818        (
2819            Atomic::TKeyedArray {
2820                properties,
2821                is_open,
2822                ..
2823            },
2824            Atomic::TNonEmptyArray { key, value },
2825        ) => {
2826            (*is_open || properties.iter().any(|(_, p)| !p.optional))
2827                && properties.iter().all(|(prop_key, prop)| {
2828                    let key_atomic = match prop_key {
2829                        crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2830                        crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2831                    };
2832                    if !Type::single(key_atomic).is_subtype_structural(key) {
2833                        return false;
2834                    }
2835                    let has_named_obj = prop.ty.types.iter().any(|a| {
2836                        matches!(
2837                            a,
2838                            Atomic::TNamedObject { .. }
2839                                | Atomic::TSelf { .. }
2840                                | Atomic::TStaticObject { .. }
2841                                | Atomic::TClosure { .. }
2842                                | Atomic::TTemplateParam { .. }
2843                        )
2844                    });
2845                    has_named_obj || prop.ty.is_subtype_structural(value)
2846                })
2847        }
2848
2849        // A list-shaped keyed array (is_list=true, all int keys) is a subtype of list<X>.
2850        (
2851            Atomic::TKeyedArray {
2852                properties,
2853                is_list,
2854                ..
2855            },
2856            Atomic::TList { value: lv },
2857        ) => *is_list && properties.values().all(|p| p.ty.is_subtype_structural(lv)),
2858        (
2859            Atomic::TKeyedArray {
2860                properties,
2861                is_list,
2862                ..
2863            },
2864            Atomic::TNonEmptyList { value: lv },
2865        ) => {
2866            *is_list
2867                && !properties.is_empty()
2868                && properties.values().all(|p| p.ty.is_subtype_structural(lv))
2869        }
2870
2871        // Two shapes: every sup key must be satisfied (present+compatible, or
2872        // absent-but-optional/sub-open), and sub may not have keys sup doesn't
2873        // declare unless sup itself is open. Named-object values are deferred
2874        // to class-hierarchy checks, same as the TArray/TList sup arms above.
2875        (
2876            Atomic::TKeyedArray {
2877                properties: sub_props,
2878                is_open: sub_open,
2879                is_list: sub_list,
2880            },
2881            Atomic::TKeyedArray {
2882                properties: sup_props,
2883                is_open: sup_open,
2884                is_list: sup_list,
2885            },
2886        ) => {
2887            // A list shape's keys run 0, 1, … in order; `[1 => 'x', 0 => 'y']` isn't one.
2888            if *sup_list
2889                && !*sub_list
2890                && sub_props
2891                    .keys()
2892                    .enumerate()
2893                    .any(|(i, k)| *k != crate::atomic::ArrayKey::Int(i as i64))
2894            {
2895                return false;
2896            }
2897            // Class-typed values are left to the hierarchy-aware checks, unless the value can't be an object.
2898            let value_fits = |sub: &Type, sup: &Type| {
2899                if sub.is_subtype_by_template_bounds(sup) {
2900                    return true;
2901                }
2902                let has_template = sup
2903                    .types
2904                    .iter()
2905                    .any(|a| matches!(a, Atomic::TTemplateParam { .. }));
2906                let has_class = sup.types.iter().any(|a| {
2907                    matches!(
2908                        a,
2909                        Atomic::TNamedObject { .. }
2910                            | Atomic::TSelf { .. }
2911                            | Atomic::TStaticObject { .. }
2912                            | Atomic::TClosure { .. }
2913                    )
2914                });
2915                has_template
2916                    || (has_class && !sub.types.iter().all(Atomic::is_definitely_non_object))
2917            };
2918            let keys_satisfied = sup_props
2919                .iter()
2920                .all(|(key, sup_prop)| match sub_props.get(key) {
2921                    Some(sub_prop) => {
2922                        // A key merely optional on the sub side may legally be
2923                        // absent at runtime, so it can't satisfy a sup key that
2924                        // requires it present.
2925                        if !sup_prop.optional && sub_prop.optional {
2926                            return false;
2927                        }
2928                        value_fits(&sub_prop.ty, &sup_prop.ty)
2929                    }
2930                    None => {
2931                        sup_prop.optional
2932                            || (*sub_open
2933                                && sub_props
2934                                    .remainder
2935                                    .as_ref()
2936                                    .is_none_or(|rest| value_fits(rest, &sup_prop.ty)))
2937                    }
2938                });
2939            let no_undeclared_extras = sub_props.iter().all(|(k, sub_prop)| {
2940                sup_props.contains_key(k)
2941                    || match &sup_props.remainder {
2942                        Some(rest) => value_fits(&sub_prop.ty, rest),
2943                        None => *sup_open,
2944                    }
2945            });
2946            keys_satisfied && no_undeclared_extras
2947        }
2948        // TKeyedArray (array shape) satisfies TIntersection iff it satisfies every
2949        // intersection part. This handles the Psalm idiom of using intersection types
2950        // for "shape plus extra keys allowed" patterns like:
2951        // @psalm-type Context = array<string,mixed> & array{actor:...,target?:...,outcome:...}
2952        // `associative-array` (an intersection with an open, empty, non-list shape) is never a list.
2953        (
2954            Atomic::TKeyedArray {
2955                properties,
2956                is_list: true,
2957                ..
2958            },
2959            Atomic::TIntersection { parts },
2960        ) if !properties.is_empty()
2961            && parts.iter().any(|part| {
2962                matches!(
2963                    part.types.as_slice(),
2964                    [Atomic::TKeyedArray { properties, is_open: true, is_list: false }]
2965                        if properties.is_empty()
2966                )
2967            }) =>
2968        {
2969            false
2970        }
2971        (
2972            Atomic::TKeyedArray {
2973                properties,
2974                is_open,
2975                ..
2976            },
2977            Atomic::TIntersection { parts },
2978        ) => parts.iter().all(|part| {
2979            part.types.iter().any(|part_atomic| match part_atomic {
2980                Atomic::TKeyedArray {
2981                    properties: sup_props,
2982                    is_open: sup_open,
2983                    ..
2984                } => {
2985                    let keys_satisfied =
2986                        sup_props
2987                            .iter()
2988                            .all(|(key, sup_prop)| match properties.get(key) {
2989                                Some(sub_prop) => {
2990                                    if !sup_prop.optional && sub_prop.optional {
2991                                        return false;
2992                                    }
2993                                    let has_named_obj = sup_prop.ty.types.iter().any(|a| {
2994                                        matches!(
2995                                            a,
2996                                            Atomic::TNamedObject { .. }
2997                                                | Atomic::TSelf { .. }
2998                                                | Atomic::TStaticObject { .. }
2999                                                | Atomic::TClosure { .. }
3000                                                | Atomic::TTemplateParam { .. }
3001                                        )
3002                                    });
3003                                    has_named_obj
3004                                        || sub_prop.ty.is_subtype_by_template_bounds(&sup_prop.ty)
3005                                        || bare_array_may_fit(&sub_prop.ty, &sup_prop.ty)
3006                                }
3007                                None => *is_open || sup_prop.optional,
3008                            });
3009                    let has_array_part = parts.iter().any(|part| {
3010                        part.types
3011                            .iter()
3012                            .any(|t| matches!(t, Atomic::TArray { .. }))
3013                    });
3014                    let has_keyed_array_part = parts.iter().any(|part| {
3015                        part.types
3016                            .iter()
3017                            .any(|t| matches!(t, Atomic::TKeyedArray { .. }))
3018                    });
3019                    let keys_allowed_by_some_part = if has_array_part {
3020                        true
3021                    } else if has_keyed_array_part {
3022                        properties.keys().all(|k| {
3023                            parts.iter().any(|part| {
3024                                part.types.iter().any(|t| {
3025                                    if let Atomic::TKeyedArray {
3026                                        properties: part_props,
3027                                        ..
3028                                    } = t
3029                                    {
3030                                        part_props.contains_key(k)
3031                                    } else {
3032                                        false
3033                                    }
3034                                })
3035                            })
3036                        })
3037                    } else {
3038                        true
3039                    };
3040                    let no_undeclared_extras = *sup_open || keys_allowed_by_some_part;
3041                    keys_satisfied && no_undeclared_extras
3042                }
3043                Atomic::TArray { key, value } => properties.iter().all(|(prop_key, prop)| {
3044                    let key_atomic = match prop_key {
3045                        crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
3046                        crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
3047                    };
3048                    if !Type::single(key_atomic).is_subtype_structural(key) {
3049                        return false;
3050                    }
3051                    let has_named_obj = prop.ty.types.iter().any(|a| {
3052                        matches!(
3053                            a,
3054                            Atomic::TNamedObject { .. }
3055                                | Atomic::TSelf { .. }
3056                                | Atomic::TStaticObject { .. }
3057                                | Atomic::TClosure { .. }
3058                                | Atomic::TTemplateParam { .. }
3059                        )
3060                    });
3061                    has_named_obj || prop.ty.is_subtype_structural(value)
3062                }),
3063                Atomic::TNamedObject { .. }
3064                | Atomic::TSelf { .. }
3065                | Atomic::TStaticObject { .. }
3066                | Atomic::TClosure { .. }
3067                | Atomic::TTemplateParam { .. } => true,
3068                _ => false,
3069            })
3070        }),
3071
3072        _ => false,
3073    }
3074}
3075
3076/// A bare `array` carries no key/value info, so it may hold any array-shaped `sup`.
3077fn bare_array_may_fit(sub: &Type, sup: &Type) -> bool {
3078    fn array_like(t: &Atomic) -> bool {
3079        match t {
3080            Atomic::TArray { .. }
3081            | Atomic::TNonEmptyArray { .. }
3082            | Atomic::TList { .. }
3083            | Atomic::TNonEmptyList { .. }
3084            | Atomic::TKeyedArray { .. } => true,
3085            Atomic::TIntersection { parts } => parts.iter().all(|p| p.types.iter().all(array_like)),
3086            _ => false,
3087        }
3088    }
3089    matches!(
3090        sub.types.as_slice(),
3091        [Atomic::TArray { key, value }]
3092            if value.is_mixed()
3093                && (key.is_mixed()
3094                    || matches!(key.types.as_slice(), [Atomic::TInt, Atomic::TString] | [Atomic::TString, Atomic::TInt]))
3095    ) && sup.types.iter().all(array_like)
3096}
3097
3098/// Whether each generic type-argument in `sub` is compatible with the
3099/// corresponding argument in `sup`. Arguments are invariant (require structural
3100/// equality) with one exception: an empty array literal (`array{}`) is accepted
3101/// against any array/list argument, so `new Box([])` — inferred as
3102/// `Box<array{}>` — satisfies a declared `Box<list<T>>` for any `T`.
3103fn type_params_compatible(sub: &[Type], sup: &[Type]) -> bool {
3104    if sub.len() != sup.len() {
3105        return false;
3106    }
3107    sub.iter()
3108        .zip(sup.iter())
3109        .all(|(a, b)| a == b || (is_empty_array_literal(a) && is_array_like(b)))
3110}
3111
3112/// True for a non-empty union whose atoms are all empty keyed arrays (`array{}`),
3113/// i.e. the type of an empty array literal `[]`.
3114fn is_empty_array_literal(t: &Type) -> bool {
3115    !t.types.is_empty()
3116        && t.types.iter().all(
3117            |atom| matches!(atom, Atomic::TKeyedArray { properties, .. } if properties.is_empty()),
3118        )
3119}
3120
3121/// True for a non-empty union whose atoms are all array/list types.
3122fn is_array_like(t: &Type) -> bool {
3123    !t.types.is_empty() && t.types.iter().all(|atom| atom.is_array())
3124}
3125
3126// ---------------------------------------------------------------------------
3127// Tests
3128// ---------------------------------------------------------------------------
3129
3130/// Accumulates a union with hash-based dedup of literal strings/ints, so large
3131/// literal sets build in linear time. Equivalent to repeated [`Type::add_type`].
3132pub struct UnionBuilder {
3133    ty: Type,
3134    strings: std::collections::HashSet<std::sync::Arc<str>>,
3135    ints: std::collections::HashSet<i64>,
3136    // No atom present can subsume a new literal (`mixed`, `string`, int ranges).
3137    literals_independent: bool,
3138}
3139
3140impl Default for UnionBuilder {
3141    fn default() -> Self {
3142        Self::new()
3143    }
3144}
3145
3146impl UnionBuilder {
3147    pub fn new() -> Self {
3148        Self {
3149            ty: Type::empty(),
3150            strings: Default::default(),
3151            ints: Default::default(),
3152            literals_independent: true,
3153        }
3154    }
3155
3156    pub fn is_empty(&self) -> bool {
3157        self.ty.is_empty()
3158    }
3159
3160    pub fn merge(&mut self, other: &Type) {
3161        for a in &other.types {
3162            self.add(a.clone());
3163        }
3164        self.ty.possibly_undefined |= other.possibly_undefined;
3165    }
3166
3167    pub fn add(&mut self, atomic: Atomic) {
3168        // A lone `never` is dropped by add_type once anything else arrives.
3169        let lone_never = matches!(self.ty.types.first(), Some(Atomic::TNever));
3170        if self.literals_independent && !lone_never {
3171            match &atomic {
3172                Atomic::TLiteralString(s) => {
3173                    if self.strings.insert(s.clone()) {
3174                        self.ty.types.push(atomic);
3175                    }
3176                    return;
3177                }
3178                Atomic::TLiteralInt(n) => {
3179                    if self.ints.insert(*n) {
3180                        self.ty.types.push(atomic);
3181                    }
3182                    return;
3183                }
3184                _ => {}
3185            }
3186        }
3187        let disturbs_literals = matches!(
3188            atomic,
3189            Atomic::TString | Atomic::TMixed | Atomic::TConditional { .. }
3190        ) || int_bounds(&atomic).is_some();
3191        self.ty.add_type(atomic);
3192        if disturbs_literals || lone_never {
3193            self.resync();
3194        }
3195    }
3196
3197    fn resync(&mut self) {
3198        self.strings.clear();
3199        self.ints.clear();
3200        self.literals_independent = true;
3201        for t in &self.ty.types {
3202            match t {
3203                Atomic::TLiteralString(s) => {
3204                    self.strings.insert(s.clone());
3205                }
3206                Atomic::TLiteralInt(n) => {
3207                    self.ints.insert(*n);
3208                }
3209                Atomic::TMixed | Atomic::TString => self.literals_independent = false,
3210                other if int_bounds(other).is_some() => self.literals_independent = false,
3211                _ => {}
3212            }
3213        }
3214    }
3215
3216    pub fn build(self) -> Type {
3217        self.ty
3218    }
3219}
3220
3221/// `list{class-string|object, non-empty-string}`: the `[class, method]` form of a callable.
3222fn callable_array() -> Atomic {
3223    let mut properties = KeyedProperties::with_capacity_and_hasher(2, Default::default());
3224    properties.insert(
3225        ArrayKey::Int(0),
3226        KeyedProperty {
3227            ty: Type::from_vec(vec![Atomic::TClassString(None), Atomic::TObject]),
3228            optional: false,
3229        },
3230    );
3231    properties.insert(
3232        ArrayKey::Int(1),
3233        KeyedProperty {
3234            ty: Type::single(Atomic::TNonEmptyString),
3235            optional: false,
3236        },
3237    );
3238    Atomic::TKeyedArray {
3239        properties: Arc::new(properties),
3240        is_open: false,
3241        is_list: true,
3242    }
3243}
3244
3245#[cfg(test)]
3246mod tests {
3247    use std::sync::Arc;
3248
3249    use super::*;
3250
3251    fn conditional(
3252        param_name: Option<Name>,
3253        subject: Type,
3254        if_true: Type,
3255        if_false: Type,
3256    ) -> Atomic {
3257        Atomic::TConditional {
3258            data: Box::new(crate::atomic::ConditionalData {
3259                param_name,
3260                subject,
3261                if_true,
3262                if_false,
3263            }),
3264        }
3265    }
3266
3267    #[test]
3268    fn single_is_single() {
3269        let u = Type::single(Atomic::TString);
3270        assert!(u.is_single());
3271        assert!(!u.is_nullable());
3272    }
3273
3274    #[test]
3275    fn nullable_has_null() {
3276        let u = Type::nullable(Atomic::TString);
3277        assert!(u.is_nullable());
3278        assert_eq!(u.types.len(), 2);
3279    }
3280
3281    #[test]
3282    fn add_type_deduplicates() {
3283        let mut u = Type::single(Atomic::TString);
3284        u.add_type(Atomic::TString);
3285        assert_eq!(u.types.len(), 1);
3286    }
3287
3288    #[test]
3289    fn array_key_is_int_string() {
3290        let k = Type::array_key();
3291        assert!(k.is_array_key());
3292        assert_eq!(k.types.len(), 2);
3293    }
3294
3295    #[test]
3296    fn is_array_key_false_for_plain_int() {
3297        assert!(!Type::int().is_array_key());
3298    }
3299
3300    #[test]
3301    fn is_array_key_false_for_mixed() {
3302        assert!(!Type::mixed().is_array_key());
3303    }
3304
3305    #[test]
3306    fn is_array_key_false_for_int_string_null() {
3307        let mut u = Type::array_key();
3308        u.add_type(Atomic::TNull);
3309        assert!(!u.is_array_key());
3310    }
3311
3312    #[test]
3313    fn add_type_literal_subsumed_by_base() {
3314        let mut u = Type::single(Atomic::TInt);
3315        u.add_type(Atomic::TLiteralInt(42));
3316        assert_eq!(u.types.len(), 1);
3317        assert!(matches!(u.types[0], Atomic::TInt));
3318    }
3319
3320    #[test]
3321    fn true_then_false_merges_to_bool() {
3322        let mut u = Type::single(Atomic::TTrue);
3323        u.add_type(Atomic::TFalse);
3324        assert_eq!(u.types.len(), 1);
3325        assert!(matches!(u.types[0], Atomic::TBool));
3326    }
3327
3328    #[test]
3329    fn false_then_true_merges_to_bool() {
3330        let mut u = Type::single(Atomic::TFalse);
3331        u.add_type(Atomic::TTrue);
3332        assert_eq!(u.types.len(), 1);
3333        assert!(matches!(u.types[0], Atomic::TBool));
3334    }
3335
3336    #[test]
3337    fn true_alone_stays_true() {
3338        let u = Type::single(Atomic::TTrue);
3339        assert_eq!(u.types.len(), 1);
3340        assert!(matches!(u.types[0], Atomic::TTrue));
3341    }
3342
3343    #[test]
3344    fn true_false_merge_preserves_other_union_members() {
3345        let mut u = Type::single(Atomic::TTrue);
3346        u.add_type(Atomic::TNull);
3347        u.add_type(Atomic::TFalse);
3348        assert_eq!(u.types.len(), 2);
3349        assert!(u.contains(|t| matches!(t, Atomic::TBool)));
3350        assert!(u.contains(|t| matches!(t, Atomic::TNull)));
3351    }
3352
3353    #[test]
3354    fn add_type_base_widens_literals() {
3355        let mut u = Type::single(Atomic::TLiteralInt(1));
3356        u.add_type(Atomic::TLiteralInt(2));
3357        u.add_type(Atomic::TInt);
3358        assert_eq!(u.types.len(), 1);
3359        assert!(matches!(u.types[0], Atomic::TInt));
3360    }
3361
3362    #[test]
3363    fn mixed_subsumes_everything() {
3364        let mut u = Type::single(Atomic::TString);
3365        u.add_type(Atomic::TMixed);
3366        assert_eq!(u.types.len(), 1);
3367        assert!(u.is_mixed());
3368    }
3369
3370    #[test]
3371    fn remove_null() {
3372        let u = Type::nullable(Atomic::TString);
3373        let narrowed = u.remove_null();
3374        assert!(!narrowed.is_nullable());
3375        assert_eq!(narrowed.types.len(), 1);
3376    }
3377
3378    #[test]
3379    fn narrow_to_truthy_removes_null_false() {
3380        let mut u = Type::empty();
3381        u.add_type(Atomic::TString);
3382        u.add_type(Atomic::TNull);
3383        u.add_type(Atomic::TFalse);
3384        let truthy = u.narrow_to_truthy();
3385        assert!(!truthy.is_nullable());
3386        assert!(!truthy.contains(|t| matches!(t, Atomic::TFalse)));
3387    }
3388
3389    #[test]
3390    fn merge_combines_types() {
3391        let a = Type::single(Atomic::TString);
3392        let b = Type::single(Atomic::TInt);
3393        let merged = Type::merge(&a, &b);
3394        assert_eq!(merged.types.len(), 2);
3395    }
3396
3397    #[test]
3398    fn intersect_keeps_narrower_side_not_self() {
3399        // int ∩ (1|2) must keep the narrower `1|2`, not the wider `int` —
3400        // this is exactly what a `match ($x) { 1, 2 => ... }` arm relies on
3401        // to narrow $x inside its body.
3402        let int_ty = Type::single(Atomic::TInt);
3403        let mut literals = Type::empty();
3404        literals.add_type(Atomic::TLiteralInt(1));
3405        literals.add_type(Atomic::TLiteralInt(2));
3406
3407        let narrowed = int_ty.intersect_with(&literals);
3408        assert_eq!(narrowed.types.len(), 2);
3409        assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(1))));
3410        assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(2))));
3411        assert!(!narrowed.contains(|t| matches!(t, Atomic::TInt)));
3412    }
3413
3414    #[test]
3415    fn subtype_literal_int_under_int() {
3416        let sub = Type::single(Atomic::TLiteralInt(5));
3417        let sup = Type::single(Atomic::TInt);
3418        assert!(sub.is_subtype_structural(&sup));
3419    }
3420
3421    #[test]
3422    fn subtype_never_is_bottom() {
3423        let never = Type::never();
3424        let string = Type::single(Atomic::TString);
3425        assert!(never.is_subtype_structural(&string));
3426    }
3427
3428    #[test]
3429    fn subtype_everything_under_mixed() {
3430        let string = Type::single(Atomic::TString);
3431        let mixed = Type::mixed();
3432        assert!(string.is_subtype_structural(&mixed));
3433    }
3434
3435    #[test]
3436    fn subtype_enum_case_under_own_enum() {
3437        let sub = Type::single(Atomic::TLiteralEnumCase {
3438            enum_fqcn: Name::new("RoundingMode"),
3439            case_name: Name::new("Unnecessary"),
3440        });
3441        let sup = Type::single(Atomic::TNamedObject {
3442            fqcn: Name::new("RoundingMode"),
3443            type_params: empty_type_params(),
3444        });
3445        assert!(sub.is_subtype_structural(&sup));
3446    }
3447
3448    #[test]
3449    fn enum_case_not_subtype_of_unrelated_enum() {
3450        let sub = Type::single(Atomic::TLiteralEnumCase {
3451            enum_fqcn: Name::new("RoundingMode"),
3452            case_name: Name::new("Unnecessary"),
3453        });
3454        let sup = Type::single(Atomic::TNamedObject {
3455            fqcn: Name::new("Suit"),
3456            type_params: empty_type_params(),
3457        });
3458        assert!(!sub.is_subtype_structural(&sup));
3459    }
3460
3461    #[test]
3462    fn subtype_enum_case_under_own_self_and_static() {
3463        let case = |enum_fqcn: &str| {
3464            Type::single(Atomic::TLiteralEnumCase {
3465                enum_fqcn: Name::new(enum_fqcn),
3466                case_name: Name::new("A"),
3467            })
3468        };
3469        let own = Type::single(Atomic::TSelf {
3470            fqcn: Name::new("Suit"),
3471        });
3472        let own_static = Type::single(Atomic::TStaticObject {
3473            fqcn: Name::new("Suit"),
3474        });
3475        assert!(case("Suit").is_subtype_structural(&own));
3476        assert!(case("Suit").is_subtype_structural(&own_static));
3477        assert!(!case("Other").is_subtype_structural(&own));
3478    }
3479
3480    #[test]
3481    fn subtype_enum_case_under_bare_object() {
3482        let sub = Type::single(Atomic::TLiteralEnumCase {
3483            enum_fqcn: Name::new("RoundingMode"),
3484            case_name: Name::new("Unnecessary"),
3485        });
3486        let sup = Type::single(Atomic::TObject);
3487        assert!(sub.is_subtype_structural(&sup));
3488    }
3489
3490    #[test]
3491    fn template_substitution() {
3492        let mut bindings = FxHashMap::default();
3493        bindings.insert(Name::new("T"), Type::single(Atomic::TString));
3494
3495        let tmpl = Type::single(Atomic::TTemplateParam {
3496            name: Name::new("T"),
3497            as_type: Box::new(Type::mixed()),
3498            defining_entity: Name::new("MyClass"),
3499        });
3500
3501        let resolved = tmpl.substitute_templates(&bindings);
3502        assert_eq!(resolved.types.len(), 1);
3503        assert!(matches!(resolved.types[0], Atomic::TString));
3504    }
3505
3506    #[test]
3507    fn intersection_is_object() {
3508        let parts = vec![
3509            Type::single(Atomic::TNamedObject {
3510                fqcn: Name::new("Iterator"),
3511                type_params: empty_type_params(),
3512            }),
3513            Type::single(Atomic::TNamedObject {
3514                fqcn: Name::new("Countable"),
3515                type_params: empty_type_params(),
3516            }),
3517        ];
3518        let atomic = Atomic::TIntersection {
3519            parts: vec_to_type_params(parts),
3520        };
3521        assert!(atomic.is_object());
3522        assert!(!atomic.can_be_falsy());
3523        assert!(atomic.can_be_truthy());
3524    }
3525
3526    #[test]
3527    fn intersection_display_two_parts() {
3528        let parts = vec![
3529            Type::single(Atomic::TNamedObject {
3530                fqcn: Name::new("Iterator"),
3531                type_params: empty_type_params(),
3532            }),
3533            Type::single(Atomic::TNamedObject {
3534                fqcn: Name::new("Countable"),
3535                type_params: empty_type_params(),
3536            }),
3537        ];
3538        let u = Type::single(Atomic::TIntersection {
3539            parts: vec_to_type_params(parts),
3540        });
3541        assert_eq!(format!("{u}"), "Iterator&Countable");
3542    }
3543
3544    #[test]
3545    fn intersection_display_three_parts() {
3546        let parts = vec![
3547            Type::single(Atomic::TNamedObject {
3548                fqcn: Name::new("A"),
3549                type_params: empty_type_params(),
3550            }),
3551            Type::single(Atomic::TNamedObject {
3552                fqcn: Name::new("B"),
3553                type_params: empty_type_params(),
3554            }),
3555            Type::single(Atomic::TNamedObject {
3556                fqcn: Name::new("C"),
3557                type_params: empty_type_params(),
3558            }),
3559        ];
3560        let u = Type::single(Atomic::TIntersection {
3561            parts: vec_to_type_params(parts),
3562        });
3563        assert_eq!(format!("{u}"), "A&B&C");
3564    }
3565
3566    #[test]
3567    fn intersection_in_nullable_union_display() {
3568        let intersection = Atomic::TIntersection {
3569            parts: vec_to_type_params(vec![
3570                Type::single(Atomic::TNamedObject {
3571                    fqcn: Name::new("Iterator"),
3572                    type_params: empty_type_params(),
3573                }),
3574                Type::single(Atomic::TNamedObject {
3575                    fqcn: Name::new("Countable"),
3576                    type_params: empty_type_params(),
3577                }),
3578            ]),
3579        };
3580        let mut u = Type::single(intersection);
3581        u.add_type(Atomic::TNull);
3582        assert!(u.is_nullable());
3583        assert!(u.contains(|t| matches!(t, Atomic::TIntersection { .. })));
3584    }
3585
3586    // --- substitute_templates coverage for previously-missing arms ----------
3587
3588    fn t_param(name: &str) -> Type {
3589        Type::single(Atomic::TTemplateParam {
3590            name: Name::new(name),
3591            as_type: Box::new(Type::mixed()),
3592            defining_entity: Name::new("Fn"),
3593        })
3594    }
3595
3596    fn bindings_t_string() -> FxHashMap<Name, Type> {
3597        let mut b = FxHashMap::default();
3598        b.insert(Name::new("T"), Type::single(Atomic::TString));
3599        b
3600    }
3601
3602    #[test]
3603    fn substitute_non_empty_array_key_and_value() {
3604        let ty = Type::single(Atomic::TNonEmptyArray {
3605            key: Box::new(t_param("T")),
3606            value: Box::new(t_param("T")),
3607        });
3608        let result = ty.substitute_templates(&bindings_t_string());
3609        assert_eq!(result.types.len(), 1);
3610        let Atomic::TNonEmptyArray { key, value } = &result.types[0] else {
3611            panic!("expected TNonEmptyArray");
3612        };
3613        assert!(matches!(key.types[0], Atomic::TString));
3614        assert!(matches!(value.types[0], Atomic::TString));
3615    }
3616
3617    #[test]
3618    fn substitute_non_empty_list_value() {
3619        let ty = Type::single(Atomic::TNonEmptyList {
3620            value: Box::new(t_param("T")),
3621        });
3622        let result = ty.substitute_templates(&bindings_t_string());
3623        let Atomic::TNonEmptyList { value } = &result.types[0] else {
3624            panic!("expected TNonEmptyList");
3625        };
3626        assert!(matches!(value.types[0], Atomic::TString));
3627    }
3628
3629    #[test]
3630    fn substitute_keyed_array_property_types() {
3631        use crate::atomic::{ArrayKey, KeyedProperty};
3632        let mut props = KeyedProperties::default();
3633        props.insert(
3634            ArrayKey::String(Arc::from("name")),
3635            KeyedProperty {
3636                ty: t_param("T"),
3637                optional: false,
3638            },
3639        );
3640        props.insert(
3641            ArrayKey::String(Arc::from("tag")),
3642            KeyedProperty {
3643                ty: t_param("T"),
3644                optional: true,
3645            },
3646        );
3647        let ty = Type::single(Atomic::TKeyedArray {
3648            properties: Arc::new(props),
3649            is_open: true,
3650            is_list: false,
3651        });
3652        let result = ty.substitute_templates(&bindings_t_string());
3653        let Atomic::TKeyedArray {
3654            properties,
3655            is_open,
3656            is_list,
3657        } = &result.types[0]
3658        else {
3659            panic!("expected TKeyedArray");
3660        };
3661        assert!(is_open);
3662        assert!(!is_list);
3663        assert!(matches!(
3664            properties[&ArrayKey::String(Arc::from("name"))].ty.types[0],
3665            Atomic::TString
3666        ));
3667        assert!(properties[&ArrayKey::String(Arc::from("tag"))].optional);
3668        assert!(matches!(
3669            properties[&ArrayKey::String(Arc::from("tag"))].ty.types[0],
3670            Atomic::TString
3671        ));
3672    }
3673
3674    #[test]
3675    fn substitute_callable_params_and_return() {
3676        use crate::atomic::FnParam;
3677        let ty = Type::single(Atomic::TCallable {
3678            params: Some(Box::new(vec![FnParam {
3679                name: Name::new("x"),
3680                ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3681                out_ty: None,
3682                default: None,
3683                is_variadic: false,
3684                is_byref: false,
3685                is_optional: false,
3686            }])),
3687            return_type: Some(Box::new(t_param("T"))),
3688            is_pure: false,
3689        });
3690        let result = ty.substitute_templates(&bindings_t_string());
3691        let Atomic::TCallable {
3692            params,
3693            return_type,
3694            ..
3695        } = &result.types[0]
3696        else {
3697            panic!("expected TCallable");
3698        };
3699        let param_ty = params.as_ref().unwrap()[0].ty.as_ref().unwrap();
3700        let param_union = param_ty.to_union();
3701        assert!(matches!(param_union.types[0], Atomic::TString));
3702        let ret = return_type.as_ref().unwrap();
3703        assert!(matches!(ret.types[0], Atomic::TString));
3704    }
3705
3706    #[test]
3707    fn substitute_callable_bare_no_panic() {
3708        // callable with no params/return — must not panic and must pass through unchanged
3709        let ty = Type::single(Atomic::TCallable {
3710            params: None,
3711            return_type: None,
3712            is_pure: false,
3713        });
3714        let result = ty.substitute_templates(&bindings_t_string());
3715        assert!(matches!(
3716            result.types[0],
3717            Atomic::TCallable {
3718                params: None,
3719                return_type: None,
3720                ..
3721            }
3722        ));
3723    }
3724
3725    #[test]
3726    fn substitute_closure_params_return_and_this() {
3727        use crate::atomic::FnParam;
3728        let ty = Type::single(Atomic::TClosure {
3729            data: Box::new(crate::atomic::ClosureData {
3730                params: Box::new([FnParam {
3731                    name: Name::new("a"),
3732                    ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3733                    out_ty: None,
3734                    default: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3735                    is_variadic: true,
3736                    is_byref: true,
3737                    is_optional: true,
3738                }]),
3739                return_type: t_param("T"),
3740                this_type: Some(t_param("T")),
3741                is_pure: false,
3742                is_static: false,
3743                rejects_surplus_args: false,
3744                is_impure: false,
3745            }),
3746        });
3747        let result = ty.substitute_templates(&bindings_t_string());
3748        let Atomic::TClosure { data } = &result.types[0] else {
3749            panic!("expected TClosure");
3750        };
3751        let (params, return_type, this_type) = (&data.params, &data.return_type, &data.this_type);
3752        let p = &params[0];
3753        let ty_union = p.ty.as_ref().unwrap().to_union();
3754        let default_union = p.default.as_ref().unwrap().to_union();
3755        assert!(matches!(ty_union.types[0], Atomic::TString));
3756        assert!(matches!(default_union.types[0], Atomic::TString));
3757        // flags preserved
3758        assert!(p.is_variadic);
3759        assert!(p.is_byref);
3760        assert!(p.is_optional);
3761        assert!(matches!(return_type.types[0], Atomic::TString));
3762        assert!(matches!(
3763            this_type.as_ref().unwrap().types[0],
3764            Atomic::TString
3765        ));
3766    }
3767
3768    #[test]
3769    fn substitute_conditional_all_branches() {
3770        let ty = Type::single(conditional(
3771            None,
3772            t_param("T"),
3773            t_param("T"),
3774            Type::single(Atomic::TInt),
3775        ));
3776        let result = ty.substitute_templates(&bindings_t_string());
3777        let Atomic::TConditional { data } = &result.types[0] else {
3778            panic!("expected TConditional");
3779        };
3780        let (subject, if_true, if_false) = (&data.subject, &data.if_true, &data.if_false);
3781        assert!(matches!(subject.types[0], Atomic::TString));
3782        assert!(matches!(if_true.types[0], Atomic::TString));
3783        assert!(matches!(if_false.types[0], Atomic::TInt));
3784    }
3785
3786    #[test]
3787    fn resolve_conditional_is_null_non_null_arg() {
3788        let ty = Type::single(conditional(
3789            Some(Name::new("x")),
3790            Type::single(Atomic::TNull),
3791            Type::single(Atomic::TInt),
3792            Type::single(Atomic::TString),
3793        ));
3794        let result = ty.resolve_conditional_returns(|name| {
3795            if name == "x" {
3796                Some(Type::single(Atomic::TString)) // definitely not null
3797            } else {
3798                None
3799            }
3800        });
3801        assert!(result.types.len() == 1);
3802        assert!(matches!(result.types[0], Atomic::TString));
3803    }
3804
3805    #[test]
3806    fn resolve_conditional_is_null_null_arg() {
3807        let ty = Type::single(conditional(
3808            Some(Name::new("x")),
3809            Type::single(Atomic::TNull),
3810            Type::single(Atomic::TInt),
3811            Type::single(Atomic::TString),
3812        ));
3813        let result = ty.resolve_conditional_returns(|name| {
3814            if name == "x" {
3815                Some(Type::single(Atomic::TNull)) // definitely null
3816            } else {
3817                None
3818            }
3819        });
3820        assert!(result.types.len() == 1);
3821        assert!(matches!(result.types[0], Atomic::TInt));
3822    }
3823
3824    #[test]
3825    fn resolve_conditional_is_null_nullable_arg_widens_to_branch_union() {
3826        let mut nullable_str = Type::single(Atomic::TString);
3827        nullable_str.add_type(Atomic::TNull);
3828        let ty = Type::single(conditional(
3829            Some(Name::new("x")),
3830            Type::single(Atomic::TNull),
3831            Type::single(Atomic::TInt),
3832            Type::single(Atomic::TString),
3833        ));
3834        let result = ty.resolve_conditional_returns(|name| {
3835            if name == "x" {
3836                Some(nullable_str.clone())
3837            } else {
3838                None
3839            }
3840        });
3841        // uncertain discriminator → widen to if_true | if_false
3842        assert_eq!(result.types.len(), 2);
3843        assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
3844        assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
3845    }
3846
3847    #[test]
3848    fn resolve_conditional_nested_widens_inner_branch() {
3849        // ($x is null ? int : ($x is string ? string : float))
3850        // When $x is unknown, should widen to int|string|float (no TConditional remaining).
3851        let inner = Type::single(conditional(
3852            Some(Name::new("x")),
3853            Type::single(Atomic::TString),
3854            Type::single(Atomic::TString),
3855            Type::single(Atomic::TFloat),
3856        ));
3857        let ty = Type::single(conditional(
3858            Some(Name::new("x")),
3859            Type::single(Atomic::TNull),
3860            Type::single(Atomic::TInt),
3861            inner,
3862        ));
3863        // unknown arg → widen both outer branches, inner conditional must also be widened
3864        let result = ty.resolve_conditional_returns(|_| None);
3865        assert!(
3866            result
3867                .types
3868                .iter()
3869                .all(|t| !matches!(t, Atomic::TConditional { .. })),
3870            "no TConditional should survive: {:?}",
3871            result.types
3872        );
3873        assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
3874        assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
3875        assert!(result.types.iter().any(|t| matches!(t, Atomic::TFloat)));
3876    }
3877
3878    #[test]
3879    fn resolve_conditional_nested_resolves_inner_branch() {
3880        // ($x is null ? int : ($x is string ? string : float))
3881        // When $x is definitely not null but unknown string-or-not → resolves outer to inner,
3882        // then inner must also be resolved.
3883        let inner = Type::single(conditional(
3884            Some(Name::new("x")),
3885            Type::single(Atomic::TString),
3886            Type::single(Atomic::TString),
3887            Type::single(Atomic::TFloat),
3888        ));
3889        let ty = Type::single(conditional(
3890            Some(Name::new("x")),
3891            Type::single(Atomic::TNull),
3892            Type::single(Atomic::TInt),
3893            inner,
3894        ));
3895        // $x = string → outer: not null → if_false (inner); inner: is string → if_true = string
3896        let result = ty.resolve_conditional_returns(|name| {
3897            if name == "x" {
3898                Some(Type::single(Atomic::TString))
3899            } else {
3900                None
3901            }
3902        });
3903        assert!(
3904            result
3905                .types
3906                .iter()
3907                .all(|t| !matches!(t, Atomic::TConditional { .. })),
3908            "no TConditional should survive: {:?}",
3909            result.types
3910        );
3911        assert_eq!(result.types.len(), 1);
3912        assert!(matches!(result.types[0], Atomic::TString));
3913    }
3914
3915    #[test]
3916    fn resolve_conditional_true_subject_bool_arg_widens() {
3917        // A `bool` argument carries the value classes `{true, false}`:
3918        // `false` is not contained in the `true` class, and `true`
3919        // overlaps it, so neither branch is ruled out.
3920        let ty = Type::single(conditional(
3921            Some(Name::new("x")),
3922            Type::single(Atomic::TTrue),
3923            Type::single(Atomic::TInt),
3924            Type::single(Atomic::TString),
3925        ));
3926        let result = ty.resolve_conditional_returns(|name| {
3927            if name == "x" {
3928                Some(Type::single(Atomic::TBool))
3929            } else {
3930                None
3931            }
3932        });
3933        assert_eq!(result.types.len(), 2);
3934        assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3935        assert!(result.contains(|t| matches!(t, Atomic::TString)));
3936    }
3937
3938    #[test]
3939    fn resolve_conditional_true_subject_mixed_arg_widens() {
3940        // `mixed` maps to the `Top` value class, which overlaps every
3941        // other class, so it can never rule a branch out.
3942        let ty = Type::single(conditional(
3943            Some(Name::new("x")),
3944            Type::single(Atomic::TTrue),
3945            Type::single(Atomic::TInt),
3946            Type::single(Atomic::TString),
3947        ));
3948        let result = ty.resolve_conditional_returns(|name| {
3949            if name == "x" {
3950                Some(Type::mixed())
3951            } else {
3952                None
3953            }
3954        });
3955        assert_eq!(result.types.len(), 2);
3956        assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3957        assert!(result.contains(|t| matches!(t, Atomic::TString)));
3958    }
3959
3960    #[test]
3961    fn resolve_conditional_true_subject_literal_args() {
3962        // Literals decide by value class: `false` is contained in
3963        // `{false}` and disjoint from `{true}`, and vice versa.
3964        let ty = Type::single(conditional(
3965            Some(Name::new("x")),
3966            Type::single(Atomic::TTrue),
3967            Type::single(Atomic::TInt),
3968            Type::single(Atomic::TString),
3969        ));
3970        let false_arg = ty.clone().resolve_conditional_returns(|name| {
3971            if name == "x" {
3972                Some(Type::single(Atomic::TFalse))
3973            } else {
3974                None
3975            }
3976        });
3977        assert_eq!(false_arg.types.len(), 1);
3978        assert!(matches!(false_arg.types[0], Atomic::TString));
3979
3980        let true_arg = ty.resolve_conditional_returns(|name| {
3981            if name == "x" {
3982                Some(Type::single(Atomic::TTrue))
3983            } else {
3984                None
3985            }
3986        });
3987        assert_eq!(true_arg.types.len(), 1);
3988        assert!(matches!(true_arg.types[0], Atomic::TInt));
3989    }
3990
3991    #[test]
3992    fn resolve_conditional_bool_subject_scalar_arg_widens() {
3993        // `scalar` carries all five scalar classes: `true`/`false`
3994        // overlap the `bool` subject, but `int`/`float`/`string` are
3995        // not contained in `{true, false}`, so neither branch commits.
3996        let ty = Type::single(conditional(
3997            Some(Name::new("x")),
3998            Type::single(Atomic::TBool),
3999            Type::single(Atomic::TInt),
4000            Type::single(Atomic::TString),
4001        ));
4002        let result = ty.resolve_conditional_returns(|name| {
4003            if name == "x" {
4004                Some(Type::single(Atomic::TScalar))
4005            } else {
4006                None
4007            }
4008        });
4009        assert_eq!(result.types.len(), 2);
4010        assert!(result.contains(|t| matches!(t, Atomic::TInt)));
4011        assert!(result.contains(|t| matches!(t, Atomic::TString)));
4012    }
4013
4014    #[test]
4015    fn resolve_conditional_string_subject_bool_arg_false_branch() {
4016        // Disjoint value classes still commit to the false branch: a
4017        // `bool` argument carries `{true, false}`, none of which is a
4018        // string, and strings are not bools.
4019        let ty = Type::single(conditional(
4020            Some(Name::new("x")),
4021            Type::single(Atomic::TString),
4022            Type::single(Atomic::TInt),
4023            Type::single(Atomic::TBool),
4024        ));
4025        let result = ty.resolve_conditional_returns(|name| {
4026            if name == "x" {
4027                Some(Type::single(Atomic::TBool))
4028            } else {
4029                None
4030            }
4031        });
4032        assert_eq!(result.types.len(), 1);
4033        assert!(matches!(result.types[0], Atomic::TBool));
4034    }
4035
4036    #[test]
4037    fn resolve_conditional_list_subject_bare_array_arg_widens() {
4038        // A bare `array` is the supertype of `list`, so it may or may
4039        // not be a list: both branches stay live.
4040        let ty = Type::single(conditional(
4041            Some(Name::new("x")),
4042            Type::single(Atomic::TList {
4043                value: Box::new(Type::mixed()),
4044            }),
4045            Type::single(Atomic::TInt),
4046            Type::single(Atomic::TString),
4047        ));
4048        let result = ty.resolve_conditional_returns(|name| {
4049            if name == "x" {
4050                Some(Type::single(Atomic::TArray {
4051                    key: Box::new(Type::mixed()),
4052                    value: Box::new(Type::mixed()),
4053                }))
4054            } else {
4055                None
4056            }
4057        });
4058        assert_eq!(result.types.len(), 2);
4059        assert!(result.contains(|t| matches!(t, Atomic::TInt)));
4060        assert!(result.contains(|t| matches!(t, Atomic::TString)));
4061    }
4062
4063    #[test]
4064    fn resolve_conditional_float_subject_int_literal_false_branch() {
4065        // A `float` subject is the `Float` class; an int literal is
4066        // `LitInt`, which is not a float, and floats are not ints.
4067        let ty = resolve_conditional_branch(
4068            &Type::single(Atomic::TFloat),
4069            &Type::single(Atomic::TLiteralInt(42)),
4070            &Type::single(Atomic::TInt),
4071            &Type::single(Atomic::TString),
4072        );
4073        assert!(matches!(
4074            ty.as_ref(),
4075            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4076        ));
4077    }
4078
4079    #[test]
4080    fn resolve_conditional_int_subject_float_literal_false_branch() {
4081        let ty = resolve_conditional_branch(
4082            &Type::single(Atomic::TInt),
4083            &Type::single(Atomic::TLiteralFloat(1, 0)),
4084            &Type::single(Atomic::TInt),
4085            &Type::single(Atomic::TString),
4086        );
4087        assert!(matches!(
4088            ty.as_ref(),
4089            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4090        ));
4091    }
4092
4093    #[test]
4094    fn resolve_conditional_float_subject_float_literal_then_branch() {
4095        let ty = resolve_conditional_branch(
4096            &Type::single(Atomic::TFloat),
4097            &Type::single(Atomic::TLiteralFloat(1, 5)),
4098            &Type::single(Atomic::TInt),
4099            &Type::single(Atomic::TString),
4100        );
4101        assert!(matches!(
4102            ty.as_ref(),
4103            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4104        ));
4105    }
4106
4107    #[test]
4108    fn resolve_conditional_int_subject_int_literal_then_branch() {
4109        let ty = resolve_conditional_branch(
4110            &Type::single(Atomic::TInt),
4111            &Type::single(Atomic::TLiteralInt(7)),
4112            &Type::single(Atomic::TInt),
4113            &Type::single(Atomic::TString),
4114        );
4115        assert!(matches!(
4116            ty.as_ref(),
4117            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4118        ));
4119    }
4120
4121    #[test]
4122    fn resolve_conditional_int_subject_float_arg_false_branch() {
4123        // A bare `float` argument is never an `int`: disjoint value
4124        // classes commit to the false branch.
4125        let ty = resolve_conditional_branch(
4126            &Type::single(Atomic::TInt),
4127            &Type::single(Atomic::TFloat),
4128            &Type::single(Atomic::TInt),
4129            &Type::single(Atomic::TString),
4130        );
4131        assert!(matches!(
4132            ty.as_ref(),
4133            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4134        ));
4135    }
4136
4137    #[test]
4138    fn resolve_conditional_array_subject_string_arg_false_branch() {
4139        let ty = resolve_conditional_branch(
4140            &Type::single(Atomic::TArray {
4141                key: Box::new(Type::mixed()),
4142                value: Box::new(Type::mixed()),
4143            }),
4144            &Type::single(Atomic::TString),
4145            &Type::single(Atomic::TInt),
4146            &Type::single(Atomic::TString),
4147        );
4148        assert!(matches!(
4149            ty.as_ref(),
4150            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4151        ));
4152    }
4153
4154    #[test]
4155    fn resolve_conditional_array_subject_bool_arg_false_branch() {
4156        let ty = resolve_conditional_branch(
4157            &Type::single(Atomic::TArray {
4158                key: Box::new(Type::mixed()),
4159                value: Box::new(Type::mixed()),
4160            }),
4161            &Type::single(Atomic::TBool),
4162            &Type::single(Atomic::TInt),
4163            &Type::single(Atomic::TString),
4164        );
4165        assert!(matches!(
4166            ty.as_ref(),
4167            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4168        ));
4169    }
4170
4171    #[test]
4172    fn resolve_conditional_array_subject_mixed_arg_widens() {
4173        // A `mixed` argument is `Top`: it overlaps `array`, so the then
4174        // branch is never ruled out, and it is not contained in `array`,
4175        // so the false branch is never ruled out either.
4176        let ty = resolve_conditional_branch(
4177            &Type::single(Atomic::TArray {
4178                key: Box::new(Type::mixed()),
4179                value: Box::new(Type::mixed()),
4180            }),
4181            &Type::mixed(),
4182            &Type::single(Atomic::TInt),
4183            &Type::single(Atomic::TString),
4184        );
4185        assert!(ty.is_none());
4186    }
4187
4188    #[test]
4189    fn resolve_conditional_array_subject_list_arg_then_branch() {
4190        // A `list` argument is an `array` (`List` is contained in
4191        // `Array`), so every argument class is in the subject's class.
4192        let ty = resolve_conditional_branch(
4193            &Type::single(Atomic::TArray {
4194                key: Box::new(Type::mixed()),
4195                value: Box::new(Type::mixed()),
4196            }),
4197            &Type::single(Atomic::TList {
4198                value: Box::new(Type::mixed()),
4199            }),
4200            &Type::single(Atomic::TInt),
4201            &Type::single(Atomic::TString),
4202        );
4203        assert!(matches!(
4204            ty.as_ref(),
4205            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4206        ));
4207    }
4208
4209    #[test]
4210    fn resolve_conditional_list_subject_keyed_list_arg_then_branch() {
4211        // A keyed array with `is_list` is a list at runtime.
4212        let ty = resolve_conditional_branch(
4213            &Type::single(Atomic::TList {
4214                value: Box::new(Type::mixed()),
4215            }),
4216            &Type::single(Atomic::TKeyedArray {
4217                properties: Arc::default(),
4218                is_open: false,
4219                is_list: true,
4220            }),
4221            &Type::single(Atomic::TInt),
4222            &Type::single(Atomic::TString),
4223        );
4224        assert!(matches!(
4225            ty.as_ref(),
4226            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4227        ));
4228    }
4229
4230    #[test]
4231    fn resolve_conditional_list_subject_list_string_union_widens() {
4232        // A `list|string` argument carries `{List, String}`: `List`
4233        // overlaps the `list` subject, `String` does not, so neither
4234        // branch is ruled out.
4235        let ty = resolve_conditional_branch(
4236            &Type::single(Atomic::TList {
4237                value: Box::new(Type::mixed()),
4238            }),
4239            &Type::from_vec(vec![
4240                Atomic::TList {
4241                    value: Box::new(Type::mixed()),
4242                },
4243                Atomic::TString,
4244            ]),
4245            &Type::single(Atomic::TInt),
4246            &Type::single(Atomic::TString),
4247        );
4248        assert!(ty.is_none());
4249    }
4250
4251    #[test]
4252    fn resolve_conditional_numeric_subject_widens() {
4253        // `numeric` is a refined subject (it admits numeric strings such
4254        // as `"123"`), so the value-class lattice cannot reduce it: the
4255        // branch stays undecidable even for a literal string argument.
4256        let ty = resolve_conditional_branch(
4257            &Type::single(Atomic::TNumeric),
4258            &Type::single(Atomic::TLiteralString("123".into())),
4259            &Type::single(Atomic::TInt),
4260            &Type::single(Atomic::TString),
4261        );
4262        assert!(ty.is_none());
4263    }
4264
4265    #[test]
4266    fn resolve_conditional_non_empty_string_subject_widens() {
4267        // A `non-empty-string` subject is refined (`""` is a string but
4268        // not non-empty), so even a bare string argument is undecidable.
4269        let ty = resolve_conditional_branch(
4270            &Type::single(Atomic::TNonEmptyString),
4271            &Type::single(Atomic::TString),
4272            &Type::single(Atomic::TInt),
4273            &Type::single(Atomic::TString),
4274        );
4275        assert!(ty.is_none());
4276    }
4277
4278    #[test]
4279    fn resolve_conditional_template_arg_widens() {
4280        // A template parameter has no value classes at all (opaque), so
4281        // it is undecidable against any subject.
4282        let ty = resolve_conditional_branch(
4283            &Type::single(Atomic::TString),
4284            &t_param("T"),
4285            &Type::single(Atomic::TInt),
4286            &Type::single(Atomic::TString),
4287        );
4288        assert!(ty.is_none());
4289    }
4290
4291    #[test]
4292    fn resolve_conditional_mixed_subject_bool_arg_then_branch() {
4293        // `mixed` is a decidable subject: every value class is contained
4294        // in `Top`, so a bool argument is always `mixed`.
4295        let ty = resolve_conditional_branch(
4296            &Type::single(Atomic::TMixed),
4297            &Type::single(Atomic::TBool),
4298            &Type::single(Atomic::TInt),
4299            &Type::single(Atomic::TString),
4300        );
4301        assert!(matches!(
4302            ty.as_ref(),
4303            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4304        ));
4305    }
4306
4307    #[test]
4308    fn resolve_conditional_scalar_subject_null_arg_false_branch() {
4309        // `null` is not a scalar value class: the argument is disjoint
4310        // from the subject, so the false branch is taken.
4311        let ty = resolve_conditional_branch(
4312            &Type::single(Atomic::TScalar),
4313            &Type::single(Atomic::TNull),
4314            &Type::single(Atomic::TInt),
4315            &Type::single(Atomic::TString),
4316        );
4317        assert!(matches!(
4318            ty.as_ref(),
4319            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4320        ));
4321    }
4322
4323    #[test]
4324    fn resolve_conditional_object_subject_named_arg_then_branch() {
4325        // A named class instance is an object at runtime.
4326        let ty = resolve_conditional_branch(
4327            &Type::single(Atomic::TObject),
4328            &Type::single(Atomic::TNamedObject {
4329                fqcn: Name::new("Foo"),
4330                type_params: empty_type_params(),
4331            }),
4332            &Type::single(Atomic::TInt),
4333            &Type::single(Atomic::TString),
4334        );
4335        assert!(matches!(
4336            ty.as_ref(),
4337            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4338        ));
4339    }
4340
4341    #[test]
4342    fn resolve_conditional_named_subject_other_class_widens() {
4343        // A named-object subject is refined (one specific class), so an
4344        // instance of another class is undecidable even though both are
4345        // objects.
4346        let ty = resolve_conditional_branch(
4347            &Type::single(Atomic::TNamedObject {
4348                fqcn: Name::new("Foo"),
4349                type_params: empty_type_params(),
4350            }),
4351            &Type::single(Atomic::TNamedObject {
4352                fqcn: Name::new("Bar"),
4353                type_params: empty_type_params(),
4354            }),
4355            &Type::single(Atomic::TInt),
4356            &Type::single(Atomic::TString),
4357        );
4358        assert!(ty.is_none());
4359    }
4360
4361    #[test]
4362    fn resolve_conditional_enum_case_subject_widens() {
4363        // An enum-case subject is refined: the value-class lattice cannot
4364        // reduce a specific enum case, so an int argument is undecidable.
4365        let ty = resolve_conditional_branch(
4366            &Type::single(Atomic::TLiteralEnumCase {
4367                enum_fqcn: Name::new("RoundingMode"),
4368                case_name: Name::new("Unnecessary"),
4369            }),
4370            &Type::single(Atomic::TInt),
4371            &Type::single(Atomic::TInt),
4372            &Type::single(Atomic::TString),
4373        );
4374        assert!(ty.is_none());
4375    }
4376
4377    #[test]
4378    fn resolve_conditional_null_subject_bool_arg_false_branch() {
4379        // `null` and bool are disjoint value classes.
4380        let ty = resolve_conditional_branch(
4381            &Type::single(Atomic::TNull),
4382            &Type::single(Atomic::TBool),
4383            &Type::single(Atomic::TInt),
4384            &Type::single(Atomic::TString),
4385        );
4386        assert!(matches!(
4387            ty.as_ref(),
4388            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4389        ));
4390    }
4391
4392    #[test]
4393    fn resolve_conditional_bool_subject_true_arg_then_branch() {
4394        // `true` is contained in `bool`'s `{true, false}` classes, so
4395        // the then branch is taken.
4396        let ty = resolve_conditional_branch(
4397            &Type::single(Atomic::TBool),
4398            &Type::single(Atomic::TTrue),
4399            &Type::single(Atomic::TInt),
4400            &Type::single(Atomic::TString),
4401        );
4402        assert!(matches!(
4403            ty.as_ref(),
4404            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4405        ));
4406    }
4407
4408    #[test]
4409    fn substitute_intersection_parts() {
4410        let ty = Type::single(Atomic::TIntersection {
4411            parts: vec_to_type_params(vec![
4412                Type::single(Atomic::TNamedObject {
4413                    fqcn: Name::new("Countable"),
4414                    type_params: empty_type_params(),
4415                }),
4416                t_param("T"),
4417            ]),
4418        });
4419        let result = ty.substitute_templates(&bindings_t_string());
4420        let Atomic::TIntersection { parts } = &result.types[0] else {
4421            panic!("expected TIntersection");
4422        };
4423        assert_eq!(parts.len(), 2);
4424        assert!(matches!(parts[0].types[0], Atomic::TNamedObject { .. }));
4425        assert!(matches!(parts[1].types[0], Atomic::TString));
4426    }
4427
4428    fn shape(props: &[(&str, Atomic, bool)], is_open: bool) -> Atomic {
4429        Atomic::TKeyedArray {
4430            properties: Arc::new(
4431                props
4432                    .iter()
4433                    .map(|(k, ty, optional)| {
4434                        (
4435                            ArrayKey::String(Arc::from(*k)),
4436                            KeyedProperty {
4437                                ty: Type::single(ty.clone()),
4438                                optional: *optional,
4439                            },
4440                        )
4441                    })
4442                    .collect(),
4443            ),
4444            is_open,
4445            is_list: false,
4446        }
4447    }
4448
4449    /// A closed shape `{a: int}` plus key `k{i}` for each bit set in `bits`.
4450    fn shape_with_bits(bits: u32, is_open: bool) -> Atomic {
4451        let names: Vec<String> = (0..5).map(|i| format!("k{i}")).collect();
4452        let mut props = vec![("a", Atomic::TInt, false)];
4453        props.extend(
4454            (0..5)
4455                .filter(|i| bits & (1 << i) != 0)
4456                .map(|i| (names[i].as_str(), Atomic::TString, false)),
4457        );
4458        shape(&props, is_open)
4459    }
4460
4461    fn keyed_count(ty: &Type) -> usize {
4462        ty.types
4463            .iter()
4464            .filter(|t| matches!(t, Atomic::TKeyedArray { .. }))
4465            .count()
4466    }
4467
4468    #[test]
4469    fn add_type_keeps_few_shapes_apart() {
4470        let mut ty = Type::empty();
4471        for bits in 0..MAX_KEYED_SHAPES as u32 {
4472            ty.add_type(shape_with_bits(bits, false));
4473        }
4474        assert_eq!(keyed_count(&ty), MAX_KEYED_SHAPES);
4475    }
4476
4477    #[test]
4478    fn add_type_folds_shapes_past_the_limit() {
4479        let mut ty = Type::empty();
4480        for bits in 0..32 {
4481            ty.add_type(shape_with_bits(bits, false));
4482        }
4483        assert!(keyed_count(&ty) <= MAX_KEYED_SHAPES);
4484        // Every key stays reachable; `a` stays required everywhere.
4485        for t in &ty.types {
4486            let Atomic::TKeyedArray { properties, .. } = t else {
4487                continue;
4488            };
4489            assert!(!properties[&ArrayKey::String(Arc::from("a"))].optional);
4490        }
4491        for i in 0..5 {
4492            let key = ArrayKey::String(Arc::from(format!("k{i}").as_str()));
4493            assert!(ty.types.iter().any(|t| matches!(
4494                t,
4495                Atomic::TKeyedArray { properties, .. } if properties.contains_key(&key)
4496            )));
4497        }
4498    }
4499
4500    #[test]
4501    fn add_type_folds_generic_arrays_past_the_limit() {
4502        let mut ty = Type::empty();
4503        for i in 0..32 {
4504            ty.add_type(Atomic::TArray {
4505                key: Box::new(Type::single(Atomic::TInt)),
4506                value: Box::new(Type::single(Atomic::TLiteralInt(i))),
4507            });
4508        }
4509        assert!(ty.types.len() <= MAX_GENERIC_ARRAYS);
4510        for i in 0..32 {
4511            assert!(ty.types.iter().any(|t| matches!(
4512                t,
4513                Atomic::TArray { value, .. } if value.types.contains(&Atomic::TLiteralInt(i))
4514            )));
4515        }
4516    }
4517
4518    #[test]
4519    fn add_type_widens_string_literals_past_the_limit() {
4520        let mut ty = Type::empty();
4521        for i in 0..MAX_LITERAL_STRINGS {
4522            ty.add_type(Atomic::TLiteralString(format!("s{i}").into()));
4523        }
4524        assert_eq!(ty.types.len(), MAX_LITERAL_STRINGS);
4525        ty.add_type(Atomic::TLiteralString("one more".into()));
4526        assert_eq!(ty.types.as_slice(), &[Atomic::TString]);
4527        ty.add_type(Atomic::TLiteralString("after".into()));
4528        assert_eq!(ty.types.as_slice(), &[Atomic::TString]);
4529    }
4530
4531    #[test]
4532    fn add_type_drops_generic_arrays_another_covers() {
4533        let list = |value: Atomic| Atomic::TList {
4534            value: Box::new(Type::single(value)),
4535        };
4536        let mut ty = Type::single(list(Atomic::TLiteralInt(0)));
4537        ty.add_type(list(Atomic::TInt));
4538        assert_eq!(ty.types.as_slice(), &[list(Atomic::TInt)]);
4539        ty.add_type(list(Atomic::TLiteralInt(1)));
4540        assert_eq!(ty.types.as_slice(), &[list(Atomic::TInt)]);
4541
4542        let mut opaque = Type::single(list(Atomic::TMixed));
4543        opaque.add_type(list(Atomic::TInt));
4544        assert_eq!(opaque.types.len(), 2);
4545
4546        let mut kinds = Type::single(Atomic::TNonEmptyList {
4547            value: Box::new(Type::single(Atomic::TInt)),
4548        });
4549        kinds.add_type(list(Atomic::TInt));
4550        assert_eq!(kinds.types.len(), 2);
4551    }
4552
4553    #[test]
4554    fn add_type_drops_shapes_another_covers() {
4555        let mut ty = Type::single(shape(&[("a", Atomic::TLiteralInt(1), false)], false));
4556        ty.add_type(shape(&[("a", Atomic::TInt, false)], false));
4557        assert_eq!(
4558            ty.types.as_slice(),
4559            &[shape(&[("a", Atomic::TInt, false)], false)]
4560        );
4561
4562        let kept = |a: Atomic, b: Atomic| {
4563            let mut ty = Type::single(a);
4564            ty.add_type(b);
4565            ty.types.len() == 2
4566        };
4567        let int_shape = shape(&[("a", Atomic::TLiteralInt(1), false)], false);
4568        assert!(kept(
4569            int_shape.clone(),
4570            shape(&[("a", Atomic::TFloat, false)], false)
4571        ));
4572        assert!(kept(
4573            int_shape.clone(),
4574            shape(&[("a", Atomic::TMixed, false)], false)
4575        ));
4576        assert!(kept(
4577            int_shape.clone(),
4578            shape(&[("a", Atomic::TInt, true)], false)
4579        ));
4580        assert!(kept(
4581            int_shape.clone(),
4582            shape(&[("a", Atomic::TInt, false)], true)
4583        ));
4584        assert!(kept(
4585            int_shape,
4586            shape(
4587                &[("a", Atomic::TInt, false), ("b", Atomic::TInt, false)],
4588                false
4589            )
4590        ));
4591    }
4592
4593    #[test]
4594    fn combine_keeps_emptiness_and_open_shape_soundness() {
4595        // `array{}` and `array{a: int}` differ in emptiness.
4596        assert!(combine_keyed_arrays(
4597            &shape(&[], false),
4598            &shape(&[("a", Atomic::TInt, false)], false)
4599        )
4600        .is_none());
4601        // Open and closed shapes don't mix.
4602        assert!(combine_keyed_arrays(
4603            &shape(&[("a", Atomic::TInt, false)], true),
4604            &shape(&[("a", Atomic::TInt, false)], false)
4605        )
4606        .is_none());
4607        // An open shape missing `k` already admits any `k`: drop it.
4608        assert_eq!(
4609            combine_keyed_arrays(
4610                &shape(&[("a", Atomic::TInt, false)], true),
4611                &shape(
4612                    &[("a", Atomic::TInt, false), ("k", Atomic::TString, false)],
4613                    true
4614                )
4615            ),
4616            Some(shape(&[("a", Atomic::TInt, false)], true))
4617        );
4618    }
4619
4620    #[test]
4621    fn substitute_no_template_params_identity() {
4622        let ty = Type::single(Atomic::TInt);
4623        let result = ty.substitute_templates(&bindings_t_string());
4624        assert!(matches!(result.types[0], Atomic::TInt));
4625    }
4626}