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