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    /// Note: No TResource atomic type exists in the type system; this is a no-op.
1228    /// Resources are declining in modern PHP and not actively tracked.
1229    pub fn narrow_to_resource(&self) -> Type {
1230        // No resource type in the system; just return mixed (allows any type)
1231        self.filter(|t| matches!(t, Atomic::TMixed))
1232    }
1233
1234    /// Narrow as if `class_exists($x)` returned true for a string variable.
1235    /// String atoms become `class-string`; existing class-string atoms pass through;
1236    /// mixed/scalar becomes `class-string`. Non-string atoms are dropped (returning
1237    /// empty so the caller can mark the branch as diverging).
1238    pub fn narrow_to_class_string(&self) -> Type {
1239        let mut out = Type::empty();
1240        out.from_docblock = self.from_docblock;
1241        for t in &self.types {
1242            match t {
1243                Atomic::TClassString(_) => out.add_type(t.clone()),
1244                _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
1245                    out.add_type(Atomic::TClassString(None));
1246                }
1247                _ => {}
1248            }
1249        }
1250        out
1251    }
1252
1253    /// Narrow as if `interface_exists($x)` returned true for a string variable.
1254    /// String atoms become `interface-string`; existing interface-string atoms pass
1255    /// through; mixed/scalar becomes `interface-string`. Non-string atoms are dropped
1256    /// (returning empty so the caller can mark the branch as diverging).
1257    pub fn narrow_to_interface_string(&self) -> Type {
1258        let mut out = Type::empty();
1259        out.from_docblock = self.from_docblock;
1260        for t in &self.types {
1261            match t {
1262                Atomic::TInterfaceString(_) => out.add_type(t.clone()),
1263                // A known class-string keeps its name — every interface-string is
1264                // also a valid class-string, so `interface_exists()` returning true
1265                // narrows the atom without losing which class it names.
1266                Atomic::TClassString(name) => {
1267                    out.add_type(Atomic::TInterfaceString(*name));
1268                }
1269                _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
1270                    out.add_type(Atomic::TInterfaceString(None));
1271                }
1272                _ => {}
1273            }
1274        }
1275        out
1276    }
1277
1278    // --- Merge (branch join) ------------------------------------------------
1279
1280    /// Merge two unions at a branch join point (e.g. after if/else).
1281    /// The result is the union of all types in both.
1282    pub fn merge(a: &Type, b: &Type) -> Type {
1283        // Fast path: b is empty — nothing to add.
1284        if b.types.is_empty() {
1285            let mut result = a.clone();
1286            result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1287            return result;
1288        }
1289        // Fast path: a is empty — clone b.
1290        if a.types.is_empty() {
1291            let mut result = b.clone();
1292            result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1293            return result;
1294        }
1295        // Fast path: a is already mixed — b cannot widen it further.
1296        if a.types.len() == 1 && matches!(a.types[0], Atomic::TMixed) {
1297            let mut result = a.clone();
1298            result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1299            return result;
1300        }
1301        // Fast path: b contains mixed — result collapses to mixed.
1302        if b.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1303            return Type {
1304                types: smallvec::smallvec![Atomic::TMixed],
1305                possibly_undefined: a.possibly_undefined || b.possibly_undefined,
1306                from_docblock: a.from_docblock || b.from_docblock,
1307                falsy_stripped: false,
1308                possibly_absent_offset: false,
1309            };
1310        }
1311        let mut result = a.clone();
1312        result.merge_with(b);
1313        result
1314    }
1315
1316    /// Merge `other` into `self` in-place (avoids cloning `self`).
1317    pub fn merge_with(&mut self, other: &Type) {
1318        if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1319            self.possibly_undefined |= other.possibly_undefined;
1320            return;
1321        }
1322        if other.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1323            self.types.clear();
1324            self.types.push(Atomic::TMixed);
1325            self.possibly_undefined |= other.possibly_undefined;
1326            return;
1327        }
1328        for atomic in &other.types {
1329            // `add_type` may rewrite a conditional, so only plain atomics short-circuit.
1330            if matches!(atomic, Atomic::TConditional { .. }) {
1331                self.add_type(atomic.clone());
1332            } else if !self.types.contains(atomic)
1333                && !self.types.iter().any(|t| matches!(t, Atomic::TMixed))
1334            {
1335                self.add_absent_type(atomic.clone());
1336            }
1337        }
1338        self.possibly_undefined |= other.possibly_undefined;
1339    }
1340
1341    /// Intersect with another union: keep only types present in `other`, widening
1342    /// where `self` contains `mixed` (which is compatible with everything).
1343    /// Used for match-arm subject narrowing.
1344    pub fn intersect_with(&self, other: &Type) -> Type {
1345        if self.is_mixed() {
1346            return other.clone();
1347        }
1348        if other.is_mixed() {
1349            return self.clone();
1350        }
1351        // Keep the more specific of each overlapping (self, other) atomic
1352        // pair — e.g. intersecting `int` with `1|2` must keep `1|2` (the
1353        // narrower side), not `int` (self's own, wider atomic): the whole
1354        // point of narrowing a variable against a match/switch arm's
1355        // literal conditions is to end up with the literal, not the bare
1356        // declared type it already had. Every matching pair is kept (not
1357        // just the first), so `int ∩ (1|2)` keeps both `1` and `2`.
1358        let mut result = Type::empty();
1359        for a in &self.types {
1360            for b in &other.types {
1361                if a == b {
1362                    result.add_type(a.clone());
1363                } else if atomic_subtype(b, a) {
1364                    result.add_type(b.clone());
1365                } else if atomic_subtype(a, b) {
1366                    result.add_type(a.clone());
1367                }
1368            }
1369        }
1370        if result.is_empty() {
1371            Type::never()
1372        } else {
1373            result
1374        }
1375    }
1376
1377    // --- Template substitution ----------------------------------------------
1378
1379    /// Replace template param references with their resolved types.
1380    pub fn substitute_templates(&self, bindings: &FxHashMap<Name, Type>) -> Type {
1381        if bindings.is_empty() {
1382            return self.clone();
1383        }
1384        // Most argument/return types are plain scalars or resolved objects
1385        // with nothing to substitute — skip the rebuild entirely.
1386        if !self.types.iter().any(atomic_may_contain_templates) {
1387            return self.clone();
1388        }
1389        let mut result = Type::empty();
1390        result.possibly_undefined = self.possibly_undefined;
1391        result.from_docblock = self.from_docblock;
1392        for atomic in &self.types {
1393            match atomic {
1394                Atomic::TTemplateParam { name, .. } => {
1395                    if let Some(resolved) = bindings.get(name) {
1396                        for t in &resolved.types {
1397                            result.add_type(t.clone());
1398                        }
1399                    } else {
1400                        result.add_type(atomic.clone());
1401                    }
1402                }
1403                Atomic::TArray { key, value } => {
1404                    result.add_type(Atomic::TArray {
1405                        key: Box::new(key.substitute_templates(bindings)),
1406                        value: Box::new(value.substitute_templates(bindings)),
1407                    });
1408                }
1409                Atomic::TList { value } => {
1410                    result.add_type(Atomic::TList {
1411                        value: Box::new(value.substitute_templates(bindings)),
1412                    });
1413                }
1414                Atomic::TNonEmptyArray { key, value } => {
1415                    result.add_type(Atomic::TNonEmptyArray {
1416                        key: Box::new(key.substitute_templates(bindings)),
1417                        value: Box::new(value.substitute_templates(bindings)),
1418                    });
1419                }
1420                Atomic::TNonEmptyList { value } => {
1421                    result.add_type(Atomic::TNonEmptyList {
1422                        value: Box::new(value.substitute_templates(bindings)),
1423                    });
1424                }
1425                Atomic::TKeyedArray {
1426                    properties,
1427                    is_open,
1428                    is_list,
1429                } => {
1430                    use crate::atomic::KeyedProperty;
1431                    let new_props = properties
1432                        .iter()
1433                        .map(|(k, prop)| {
1434                            (
1435                                k.clone(),
1436                                KeyedProperty {
1437                                    ty: prop.ty.substitute_templates(bindings),
1438                                    optional: prop.optional,
1439                                },
1440                            )
1441                        })
1442                        .collect();
1443                    result.add_type(Atomic::TKeyedArray {
1444                        properties: Arc::new(new_props),
1445                        is_open: *is_open,
1446                        is_list: *is_list,
1447                    });
1448                }
1449                Atomic::TCallable {
1450                    params,
1451                    return_type,
1452                    is_pure,
1453                } => {
1454                    result.add_type(Atomic::TCallable {
1455                        params: params.as_ref().map(|ps| {
1456                            Box::new(
1457                                ps.iter()
1458                                    .map(|p| substitute_in_fn_param(p, bindings))
1459                                    .collect(),
1460                            )
1461                        }),
1462                        return_type: return_type
1463                            .as_ref()
1464                            .map(|r| Box::new(r.substitute_templates(bindings))),
1465                        is_pure: *is_pure,
1466                    });
1467                }
1468                Atomic::TClosure { data } => {
1469                    result.add_type(Atomic::TClosure {
1470                        data: Box::new(crate::atomic::ClosureData {
1471                            params: data
1472                                .params
1473                                .iter()
1474                                .map(|p| substitute_in_fn_param(p, bindings))
1475                                .collect(),
1476                            return_type: data.return_type.substitute_templates(bindings),
1477                            this_type: data
1478                                .this_type
1479                                .as_ref()
1480                                .map(|t| t.substitute_templates(bindings)),
1481                            is_pure: data.is_pure,
1482                            is_static: data.is_static,
1483                            rejects_surplus_args: data.rejects_surplus_args,
1484                        }),
1485                    });
1486                }
1487                Atomic::TConditional { data } => {
1488                    let param_name = &data.param_name;
1489                    let new_subject = data.subject.substitute_templates(bindings);
1490                    let new_if_true = data.if_true.substitute_templates(bindings);
1491                    let new_if_false = data.if_false.substitute_templates(bindings);
1492
1493                    // If param_name names a template that is bound in this substitution,
1494                    // resolve the conditional immediately using the same predicate logic as
1495                    // `resolve_conditional_returns` for the $param form.
1496                    let resolved = if let Some(name) = param_name {
1497                        if let Some(bound) = bindings.get(name) {
1498                            resolve_conditional_branch(
1499                                &new_subject,
1500                                bound,
1501                                &new_if_true,
1502                                &new_if_false,
1503                            )
1504                        } else {
1505                            None
1506                        }
1507                    } else {
1508                        None
1509                    };
1510
1511                    if let Some(branch) = resolved {
1512                        for t in branch.types {
1513                            result.add_type(t);
1514                        }
1515                    } else {
1516                        result.add_type(Atomic::TConditional {
1517                            data: Box::new(crate::atomic::ConditionalData {
1518                                param_name: *param_name,
1519                                subject: new_subject,
1520                                if_true: new_if_true,
1521                                if_false: new_if_false,
1522                            }),
1523                        });
1524                    }
1525                }
1526                Atomic::TKeyOf { target } => {
1527                    let new_target = target.substitute_templates(bindings);
1528                    if let Some(resolved) = eval_key_of_type(&new_target) {
1529                        result.merge_with(&resolved);
1530                    } else {
1531                        result.add_type(Atomic::TKeyOf {
1532                            target: Box::new(new_target),
1533                        });
1534                    }
1535                }
1536                Atomic::TValueOf { target } => {
1537                    let new_target = target.substitute_templates(bindings);
1538                    if let Some(resolved) = eval_value_of_type(&new_target) {
1539                        result.merge_with(&resolved);
1540                    } else {
1541                        result.add_type(Atomic::TValueOf {
1542                            target: Box::new(new_target),
1543                        });
1544                    }
1545                }
1546                Atomic::TIntersection { parts } => {
1547                    result.add_type(Atomic::TIntersection {
1548                        parts: vec_to_type_params(
1549                            parts
1550                                .iter()
1551                                .map(|p| p.substitute_templates(bindings))
1552                                .collect(),
1553                        ),
1554                    });
1555                }
1556                Atomic::TNamedObject { fqcn, type_params } => {
1557                    // See issue #26 for context.
1558                    if type_params.is_empty() && !fqcn.contains('\\') {
1559                        if let Some(resolved) = bindings.get(fqcn) {
1560                            for t in &resolved.types {
1561                                result.add_type(t.clone());
1562                            }
1563                            continue;
1564                        }
1565                    }
1566                    let new_params: Vec<Type> = type_params
1567                        .iter()
1568                        .map(|p| p.substitute_templates(bindings))
1569                        .collect();
1570                    result.add_type(Atomic::TNamedObject {
1571                        fqcn: *fqcn,
1572                        type_params: vec_to_type_params(new_params),
1573                    });
1574                }
1575                // class-string<T> → substitute T from bindings
1576                Atomic::TClassString(Some(param_name)) => {
1577                    if let Some(resolved) = bindings.get(param_name) {
1578                        for r_atomic in &resolved.types {
1579                            let cls_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1580                                Some(*fqcn)
1581                            } else {
1582                                None
1583                            };
1584                            result.add_type(Atomic::TClassString(cls_name));
1585                        }
1586                    } else {
1587                        result.add_type(atomic.clone());
1588                    }
1589                }
1590                // interface-string<T> → substitute T from bindings
1591                Atomic::TInterfaceString(Some(param_name)) => {
1592                    if let Some(resolved) = bindings.get(param_name) {
1593                        for r_atomic in &resolved.types {
1594                            let iface_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1595                                Some(*fqcn)
1596                            } else {
1597                                None
1598                            };
1599                            result.add_type(Atomic::TInterfaceString(iface_name));
1600                        }
1601                    } else {
1602                        result.add_type(atomic.clone());
1603                    }
1604                }
1605                _ => {
1606                    result.add_type(atomic.clone());
1607                }
1608            }
1609        }
1610        result
1611    }
1612
1613    /// Resolves `TConditional` atoms whose discriminator is known at the call site.
1614    ///
1615    /// `lookup(param_name)` returns the call-site argument type for the named parameter,
1616    /// or `None` if the argument is not available. Handles `is null`, `is string`, and
1617    /// `is array` conditions; other condition types pass through unchanged.
1618    pub fn resolve_conditional_returns<F>(self, lookup: F) -> Type
1619    where
1620        F: Fn(&str) -> Option<Type>,
1621    {
1622        self.resolve_conditional_inner(&lookup)
1623    }
1624
1625    fn resolve_conditional_inner<F>(self, lookup: &F) -> Type
1626    where
1627        F: Fn(&str) -> Option<Type>,
1628    {
1629        let mut result = Type::empty();
1630        for atomic in self.types {
1631            match atomic {
1632                Atomic::TConditional { ref data } => {
1633                    let (param_name, subject, if_true, if_false) = (
1634                        &data.param_name,
1635                        &data.subject,
1636                        &data.if_true,
1637                        &data.if_false,
1638                    );
1639                    let resolved =
1640                        param_name
1641                            .and_then(|name| lookup(name.as_ref()))
1642                            .and_then(|arg_ty| {
1643                                resolve_conditional_branch(subject, &arg_ty, if_true, if_false)
1644                            });
1645
1646                    if let Some(branch) = resolved {
1647                        // Recursively resolve nested conditionals in the selected branch.
1648                        for t in branch.resolve_conditional_inner(lookup).types {
1649                            result.add_type(t);
1650                        }
1651                    } else {
1652                        // Cannot resolve at this call site: widen to the union of both branches.
1653                        // Recursively resolve nested conditionals in each branch.
1654                        for t in if_true.clone().resolve_conditional_inner(lookup).types {
1655                            result.add_type(t);
1656                        }
1657                        for t in if_false.clone().resolve_conditional_inner(lookup).types {
1658                            result.add_type(t);
1659                        }
1660                    }
1661                }
1662                other => result.add_type(other),
1663            }
1664        }
1665        result
1666    }
1667
1668    // --- Subtype check -------------------------------------------------------
1669
1670    /// Returns true if every atomic in `self` is a subtype of some atomic in `other`,
1671    /// using **only structural rules** — no `extends` / `implements` walk.
1672    ///
1673    /// Two distinct user-defined classes are never related here, even when one
1674    /// extends the other. Within `mir-analyzer`, when a `db` is in scope,
1675    /// prefer `crate::subtype::is_subtype(db, sub, sup)` which layers
1676    /// inheritance resolution on top of this check.
1677    pub fn is_subtype_structural(&self, other: &Type) -> bool {
1678        if other.is_mixed() {
1679            return true;
1680        }
1681        if self.is_never() {
1682            return true; // never <: everything
1683        }
1684        self.types.iter().all(|a| {
1685            let fits = |a: &Atomic| other.types.iter().any(|b| atomic_subtype(a, b));
1686            fits(a) || composite_parts(a).is_some_and(|parts| parts.iter().all(fits))
1687        })
1688    }
1689
1690    /// Like `is_subtype_structural`, but a template atom is judged by its bound
1691    /// (an unbound one is `mixed` and fits anything).
1692    pub fn is_subtype_by_template_bounds(&self, other: &Type) -> bool {
1693        self.is_subtype_structural(other)
1694            || self.types.iter().all(|a| match a {
1695                Atomic::TTemplateParam { as_type, .. } => {
1696                    as_type.is_subtype_by_template_bounds(other)
1697                }
1698                _ => other.accepts_atomic_structural(a),
1699            })
1700    }
1701
1702    /// `sub <: self`, structurally, for a single atomic — equivalent to
1703    /// `Type::single(sub.clone()).is_subtype_structural(self)` without the
1704    /// clone and the temporary single-atomic union.
1705    pub fn accepts_atomic_structural(&self, sub: &Atomic) -> bool {
1706        if self.is_mixed() {
1707            return true;
1708        }
1709        matches!(sub, Atomic::TNever) || self.types.iter().any(|b| atomic_subtype(sub, b))
1710    }
1711
1712    // --- Utilities ----------------------------------------------------------
1713
1714    fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Type {
1715        let mut result = Type::empty();
1716        result.possibly_undefined = self.possibly_undefined;
1717        result.from_docblock = self.from_docblock;
1718        for atomic in &self.types {
1719            if f(atomic) {
1720                result.types.push(atomic.clone());
1721            }
1722        }
1723        result
1724    }
1725
1726    /// Like `filter`, but atoms matching `placeholder` are substituted with
1727    /// `replacement` instead of passing through unchanged. Used so narrowing
1728    /// an unrefined `mixed`/`scalar`/`numeric` value (e.g. via `is_int($x)`)
1729    /// yields the concrete narrowed type instead of staying `mixed`.
1730    fn filter_replacing<K: Fn(&Atomic) -> bool, P: Fn(&Atomic) -> bool>(
1731        &self,
1732        keep: K,
1733        placeholder: P,
1734        replacement: Atomic,
1735    ) -> Type {
1736        let mut result = Type::empty();
1737        result.possibly_undefined = self.possibly_undefined;
1738        result.from_docblock = self.from_docblock;
1739        for atomic in &self.types {
1740            if keep(atomic) {
1741                result.add_type(atomic.clone());
1742            } else if placeholder(atomic) {
1743                result.add_type(replacement.clone());
1744            }
1745        }
1746        result
1747    }
1748
1749    /// Mark this union as possibly-undefined and return it.
1750    pub fn possibly_undefined(mut self) -> Self {
1751        self.possibly_undefined = true;
1752        self
1753    }
1754
1755    /// Mark this union as coming from a docblock annotation.
1756    pub fn from_docblock(mut self) -> Self {
1757        self.from_docblock = true;
1758        self
1759    }
1760
1761    /// Mark this union as having had a `false`/`null` failure variant stripped
1762    /// for flow purposes (see the field doc on [`Type::falsy_stripped`]).
1763    pub fn falsy_stripped(mut self) -> Self {
1764        self.falsy_stripped = true;
1765        self
1766    }
1767
1768    /// Mark this union as read from a generic array/list offset whose key
1769    /// presence isn't statically provable (see the field doc on
1770    /// [`Type::possibly_absent_offset`]).
1771    pub fn possibly_absent_offset(mut self) -> Self {
1772        self.possibly_absent_offset = true;
1773        self
1774    }
1775}
1776
1777// ---------------------------------------------------------------------------
1778// Conditional return resolution helpers
1779// ---------------------------------------------------------------------------
1780
1781/// Coarse value class of a runtime value.
1782///
1783/// One atom may hold several classes (a `bool` may hold `true` *or*
1784/// `false`; a `scalar` argument is one of the five scalar classes).
1785/// Literal refinements stay precise only where they matter: `int`/`float`
1786/// literals get their own class so that `int` and `float` literals decide
1787/// against each other's subjects; string literals collapse to
1788/// [`ValueClass::String`] (refined string kinds never feed a conditional
1789/// subject and would only cost match precision).
1790#[derive(Clone, PartialEq, Eq, Debug)]
1791enum ValueClass {
1792    Int,
1793    Float,
1794    True,
1795    False,
1796    String,
1797    Array,
1798    /// `list`-shaped arrays (sequential integer keys) — a refinement of [`Array`].
1799    List,
1800    Object,
1801    Null,
1802    /// `mixed`/`void` — a value of every class; it overlaps every other
1803    /// class, so a `mixed` argument rules out no branch.
1804    Top,
1805    /// Literal `int` — precise against `int`/`float` subjects: an `int`
1806    /// literal is not a float, a float literal is not an int.
1807    LitInt(i64),
1808    /// Literal `float` — the bit decomposition mirrors [`Atomic::TLiteralFloat`].
1809    LitFloat(i64, i64),
1810    /// A specific `string` literal.
1811    LitString(Arc<str>),
1812    /// `class-string` and its kin — a refinement of [`String`].
1813    ClassString,
1814}
1815
1816impl ValueClass {
1817    /// Whether a value of class `b` is necessarily a value of class `a`, i.e.
1818    /// whether the class lattice (`int` literal <: `int` <: `scalar`;
1819    /// `list` <: `array`; `true`/`false` <: `bool`; `mixed` <: everything)
1820    /// places `b` beneath `a`.
1821    fn includes(&self, b: &Self) -> bool {
1822        self == b
1823            || matches!(
1824                (self, b),
1825                (Self::Top, _)
1826                    | (Self::Int, Self::LitInt(_))
1827                    | (Self::Float, Self::LitFloat(..))
1828                    | (Self::String, Self::LitString(_))
1829                    | (Self::String, Self::ClassString)
1830                    | (Self::Array, Self::List)
1831            )
1832    }
1833
1834    /// Whether some value is of both classes. A string literal may name a class.
1835    fn overlaps(&self, b: &Self) -> bool {
1836        self.includes(b)
1837            || b.includes(self)
1838            || matches!(
1839                (self, b),
1840                (Self::ClassString, Self::LitString(_)) | (Self::LitString(_), Self::ClassString)
1841            )
1842    }
1843}
1844
1845/// The value classes an atom may hold.
1846///
1847/// Meta-types map to every class they may hold (`TBool` holds `true` *and*
1848/// `false`); opaque/deferred atoms (`TTemplateParam`, `TKeyOf`, …) map to
1849/// none — an argument of such a type rules out no branch.
1850fn value_classes(a: &Atomic) -> Vec<ValueClass> {
1851    use ValueClass::*;
1852    match a {
1853        // Integers (range bounds are not modeled: a subject `int` is a
1854        // family question).
1855        Atomic::TInt
1856        | Atomic::TIntRange { .. }
1857        | Atomic::TPositiveInt
1858        | Atomic::TNegativeInt
1859        | Atomic::TNonNegativeInt => vec![Int],
1860        Atomic::TLiteralInt(v) => vec![LitInt(*v)],
1861        // Floats.
1862        Atomic::TFloat | Atomic::TIntegralFloat => vec![Float],
1863        Atomic::TLiteralFloat(int_bits, frac_bits) => {
1864            vec![LitFloat(*int_bits, *frac_bits)]
1865        }
1866        // Bools.
1867        Atomic::TBool => vec![True, False],
1868        Atomic::TTrue => vec![True],
1869        Atomic::TFalse => vec![False],
1870        // Strings — every refined string kind maps to one class.
1871        Atomic::TString
1872        | Atomic::TNonEmptyString
1873        | Atomic::TNumericString
1874        | Atomic::TCallableString => vec![String],
1875        Atomic::TClassString(_)
1876        | Atomic::TInterfaceString(_)
1877        | Atomic::TEnumString
1878        | Atomic::TTraitString => vec![ClassString],
1879        Atomic::TLiteralString(s) => vec![LitString(s.clone())],
1880        // Arrays — `list` is a refinement of `array`.
1881        Atomic::TArray { .. }
1882        | Atomic::TNonEmptyArray { .. }
1883        | Atomic::TKeyedArray { is_list: false, .. } => vec![Array],
1884        Atomic::TList { .. }
1885        | Atomic::TNonEmptyList { .. }
1886        | Atomic::TKeyedArray { is_list: true, .. } => vec![List],
1887        // Objects — a specific class instance is an object at runtime.
1888        Atomic::TObject
1889        | Atomic::TObjectShape { .. }
1890        | Atomic::TNamedObject { .. }
1891        | Atomic::TStaticObject { .. }
1892        | Atomic::TSelf { .. }
1893        | Atomic::TParent { .. }
1894        | Atomic::TClosure { .. }
1895        | Atomic::TLiteralEnumCase { .. } => vec![Object],
1896        // Null. `void` maps to `Top` (a `void`-typed value is unknown; treating
1897        // it as "everything" keeps any branch it feeds undecidable).
1898        Atomic::TNull => vec![Null],
1899        Atomic::TVoid => vec![Top],
1900        // Everything / scalars.
1901        Atomic::TMixed => vec![Top],
1902        Atomic::TScalar => vec![Int, Float, True, False, String],
1903        // `numeric` may hold `int` or `float` values (a numeric *string*
1904        // can never be the discriminant of an `is numeric` subject).
1905        Atomic::TNumeric => vec![Int, Float],
1906        // Opaque / deferred — rules out no branch.
1907        Atomic::TCallable { .. }
1908        | Atomic::TNever
1909        | Atomic::TTemplateParam { .. }
1910        | Atomic::TKeyOf { .. }
1911        | Atomic::TValueOf { .. }
1912        | Atomic::TConditional { .. }
1913        | Atomic::TIntersection { .. } => Vec::new(),
1914    }
1915}
1916
1917/// Whether a conditional discriminant subject can be decided by value class.
1918///
1919/// Only the bare family kinds and scalar literals qualify. A refined subject (a named object, a
1920/// shape, a non-empty list, an enum case, …) carries value-level constraints
1921/// the class lattice cannot express — an argument that is *some* object is
1922/// not necessarily *that* class — so refined subjects stay undecidable, the
1923/// same behavior as the pre-class predicate (which had no arm for them).
1924fn subject_is_decidable(subject: &Atomic) -> bool {
1925    matches!(
1926        subject,
1927        Atomic::TNull
1928            | Atomic::TTrue
1929            | Atomic::TFalse
1930            | Atomic::TBool
1931            | Atomic::TString
1932            | Atomic::TClassString(None)
1933            | Atomic::TInt
1934            | Atomic::TFloat
1935            | Atomic::TLiteralString(_)
1936            | Atomic::TLiteralInt(_)
1937            | Atomic::TLiteralFloat(..)
1938            | Atomic::TArray { .. }
1939            | Atomic::TList { .. }
1940            | Atomic::TObject
1941            | Atomic::TObjectShape { .. }
1942            | Atomic::TMixed
1943            | Atomic::TScalar
1944    )
1945}
1946
1947/// Resolve one branch of a conditional return type given the subject
1948/// discriminant and the actual argument type at the call site.
1949///
1950/// Returns `Some(branch)` when the branch can be determined statically, or
1951/// `None` to signal that the caller should widen to the union of both
1952/// branches.
1953///
1954/// Decision rule (value-class semantics): the discriminant and the argument
1955/// are compared *only on value classes* — the value sets the runtime type
1956/// system uses for narrowing. Class containment is the same lattice the
1957/// subtype relation uses for these kinds (`true` ⊆ `bool` ⊆ `scalar`,
1958/// `list` ⊆ `array`, `int`/`float` literals distinct, `mixed` ⊆ everything),
1959/// so a subject kind and an argument kind are related iff some contained
1960/// class relates them.
1961///
1962/// The true branch commits when every argument class is contained in some
1963/// subject class (every value the argument can hold is a subject value); the
1964/// false branch commits when every argument class is disjoint from every
1965/// subject class (no value the argument can hold is a subject value).
1966/// Otherwise the branch is undecidable and the caller widens to the union of
1967/// both branches.
1968fn resolve_conditional_branch(
1969    subject: &Type,
1970    arg_ty: &Type,
1971    if_true: &Type,
1972    if_false: &Type,
1973) -> Option<Type> {
1974    if arg_ty.types.is_empty() {
1975        return None;
1976    }
1977    // `T is void`: only `void` itself matches; a known non-void value never does.
1978    if let [Atomic::TVoid] = subject.types.as_slice() {
1979        return match arg_ty.types.as_slice() {
1980            [Atomic::TVoid] => Some(if_true.clone()),
1981            types
1982                if types.iter().all(|a| {
1983                    !matches!(a, Atomic::TVoid | Atomic::TMixed | Atomic::TNull)
1984                        && !value_classes(a).is_empty()
1985                }) =>
1986            {
1987                Some(if_false.clone())
1988            }
1989            _ => None,
1990        };
1991    }
1992    if subject.types.is_empty() || !subject.types.iter().all(subject_is_decidable) {
1993        return None;
1994    }
1995    let subject_classes: Vec<ValueClass> = subject.types.iter().flat_map(value_classes).collect();
1996    let arg_classes: Vec<ValueClass> = arg_ty.types.iter().flat_map(value_classes).collect();
1997    if arg_classes.is_empty() {
1998        // Opaque argument (template, `key-of`, …) — no branch is ruled out.
1999        return None;
2000    }
2001    let all_match = arg_classes
2002        .iter()
2003        .all(|c| subject_classes.iter().any(|s| s.includes(c)));
2004    let any_overlap = arg_classes
2005        .iter()
2006        .any(|c| subject_classes.iter().any(|s| s.overlaps(c)));
2007    if all_match {
2008        Some(if_true.clone())
2009    } else if !any_overlap {
2010        Some(if_false.clone())
2011    } else {
2012        None
2013    }
2014}
2015
2016// ---------------------------------------------------------------------------
2017// Template substitution helpers
2018// ---------------------------------------------------------------------------
2019
2020/// Whether `substitute_templates` could change this atomic: it is either a
2021/// template reference itself or a container/callable that may hold one.
2022/// Mirrors the substituting arms of that function's match — keep in sync.
2023fn atomic_may_contain_templates(atomic: &Atomic) -> bool {
2024    match atomic {
2025        // Bare unqualified names double as template refs (docblock parser
2026        // workaround, see substitute_templates); qualified names only matter
2027        // when they carry generic params.
2028        Atomic::TNamedObject { fqcn, type_params } => {
2029            !type_params.is_empty() || !fqcn.contains('\\')
2030        }
2031        Atomic::TTemplateParam { .. }
2032        | Atomic::TKeyOf { .. }
2033        | Atomic::TValueOf { .. }
2034        | Atomic::TArray { .. }
2035        | Atomic::TList { .. }
2036        | Atomic::TNonEmptyArray { .. }
2037        | Atomic::TNonEmptyList { .. }
2038        | Atomic::TKeyedArray { .. }
2039        | Atomic::TCallable { .. }
2040        | Atomic::TClosure { .. }
2041        | Atomic::TConditional { .. }
2042        | Atomic::TIntersection { .. }
2043        | Atomic::TClassString(Some(_))
2044        | Atomic::TInterfaceString(Some(_)) => true,
2045        _ => false,
2046    }
2047}
2048
2049pub fn eval_key_of_type(t: &Type) -> Option<Type> {
2050    let mut result = Type::empty();
2051    for atomic in &t.types {
2052        match atomic {
2053            Atomic::TArray { key, .. } | Atomic::TNonEmptyArray { key, .. } => {
2054                for k in &key.types {
2055                    result.add_type(k.clone());
2056                }
2057            }
2058            Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => {
2059                result.add_type(Atomic::TInt);
2060            }
2061            Atomic::TKeyedArray { properties, .. } => {
2062                for key in properties.keys() {
2063                    match key {
2064                        crate::atomic::ArrayKey::Int(n) => result.add_type(Atomic::TLiteralInt(*n)),
2065                        crate::atomic::ArrayKey::String(s) => {
2066                            result.add_type(Atomic::TLiteralString(s.clone()))
2067                        }
2068                    }
2069                }
2070            }
2071            _ => return None,
2072        }
2073    }
2074    (!result.types.is_empty()).then_some(result)
2075}
2076
2077pub fn eval_value_of_type(t: &Type) -> Option<Type> {
2078    let mut result = Type::empty();
2079    for atomic in &t.types {
2080        match atomic {
2081            Atomic::TArray { value, .. }
2082            | Atomic::TNonEmptyArray { value, .. }
2083            | Atomic::TList { value }
2084            | Atomic::TNonEmptyList { value } => {
2085                result.merge_with(value);
2086            }
2087            Atomic::TKeyedArray { properties, .. } => {
2088                for prop in properties.values() {
2089                    result.merge_with(&prop.ty);
2090                }
2091            }
2092            _ => return None,
2093        }
2094    }
2095    (!result.types.is_empty()).then_some(result)
2096}
2097
2098fn substitute_in_fn_param(
2099    p: &crate::atomic::FnParam,
2100    bindings: &FxHashMap<Name, Type>,
2101) -> crate::atomic::FnParam {
2102    crate::atomic::FnParam {
2103        name: p.name,
2104        ty: p.ty.as_ref().map(|t| {
2105            let u = t.to_union();
2106            let substituted = u.substitute_templates(bindings);
2107            crate::compact::SimpleType::from_union(substituted)
2108        }),
2109        out_ty: p.out_ty.as_ref().map(|t| {
2110            let u = t.to_union();
2111            let substituted = u.substitute_templates(bindings);
2112            crate::compact::SimpleType::from_union(substituted)
2113        }),
2114        default: p.default.as_ref().map(|d| {
2115            let u = d.to_union();
2116            let substituted = u.substitute_templates(bindings);
2117            crate::compact::SimpleType::from_union(substituted)
2118        }),
2119        is_variadic: p.is_variadic,
2120        is_byref: p.is_byref,
2121        is_optional: p.is_optional,
2122    }
2123}
2124
2125// ---------------------------------------------------------------------------
2126// Atomic subtype (no codebase — structural check only)
2127// ---------------------------------------------------------------------------
2128
2129/// Atomics that are exactly a union of other atomics, so a union spelling out
2130/// every part (e.g. `string|int|float|bool`) accepts them.
2131fn composite_parts(atomic: &Atomic) -> Option<&'static [Atomic]> {
2132    match atomic {
2133        Atomic::TScalar => Some(&[Atomic::TInt, Atomic::TFloat, Atomic::TString, Atomic::TBool]),
2134        Atomic::TNumeric => Some(&[Atomic::TInt, Atomic::TFloat, Atomic::TNumericString]),
2135        _ => None,
2136    }
2137}
2138
2139fn object_shape_subtype(have: &KeyedProperties, want: &KeyedProperties) -> bool {
2140    want.iter().all(|(name, wanted)| match have.get(name) {
2141        Some(had) => (wanted.optional || !had.optional) && had.ty.is_subtype_structural(&wanted.ty),
2142        None => wanted.optional,
2143    })
2144}
2145
2146/// Structural `sub <: sup` for a single atomic pair, without hierarchy resolution.
2147pub fn atomic_subtype(sub: &Atomic, sup: &Atomic) -> bool {
2148    if sub == sup {
2149        return true;
2150    }
2151    match (sub, sup) {
2152        (Atomic::TObjectShape { properties: have }, Atomic::TObjectShape { properties: want }) => {
2153            return object_shape_subtype(have, want);
2154        }
2155        (Atomic::TObjectShape { .. }, _) => return atomic_subtype(&Atomic::TObject, sup),
2156        // Without the codebase a class's properties are unknown, so any object may satisfy a shape.
2157        (_, Atomic::TObjectShape { .. }) => return atomic_subtype(sub, &Atomic::TObject),
2158        _ => {}
2159    }
2160    match (sub, sup) {
2161        // Bottom type
2162        (Atomic::TNever, _) => true,
2163        // Top types — anything goes in both directions for mixed
2164        (_, Atomic::TMixed) => true,
2165        (Atomic::TMixed, _) => true,
2166        // Template param in supertype position: any value satisfies an unconstrained
2167        // template (as_type = mixed), or a constrained one if it satisfies the bound.
2168        // This handles union bounds like `T of string|list<I>|array<K, V>` where
2169        // I/K/V are free template params — any type satisfies them structurally.
2170        (_, Atomic::TTemplateParam { as_type, .. }) => {
2171            as_type.is_mixed() || as_type.types.iter().any(|b| atomic_subtype(sub, b))
2172        }
2173
2174        // Scalars
2175        (Atomic::TLiteralInt(_), Atomic::TInt) => true,
2176        (Atomic::TLiteralInt(_), Atomic::TNumeric) => true,
2177        (Atomic::TLiteralInt(_), Atomic::TScalar) => true,
2178        (Atomic::TLiteralInt(n), Atomic::TPositiveInt) => *n > 0,
2179        (Atomic::TLiteralInt(n), Atomic::TNonNegativeInt) => *n >= 0,
2180        (Atomic::TLiteralInt(n), Atomic::TNegativeInt) => *n < 0,
2181        (Atomic::TPositiveInt, Atomic::TInt) => true,
2182        (Atomic::TPositiveInt, Atomic::TNonNegativeInt) => true,
2183        (Atomic::TPositiveInt, Atomic::TNumeric) => true,
2184        (Atomic::TPositiveInt, Atomic::TScalar) => true,
2185        (Atomic::TNegativeInt, Atomic::TInt) => true,
2186        (Atomic::TNegativeInt, Atomic::TNumeric) => true,
2187        (Atomic::TNegativeInt, Atomic::TScalar) => true,
2188        (Atomic::TNonNegativeInt, Atomic::TInt) => true,
2189        (Atomic::TNonNegativeInt, Atomic::TNumeric) => true,
2190        (Atomic::TNonNegativeInt, Atomic::TScalar) => true,
2191        (Atomic::TIntRange { .. }, Atomic::TInt) => true,
2192        (Atomic::TIntRange { .. }, Atomic::TNumeric) => true,
2193        (Atomic::TIntRange { .. }, Atomic::TScalar) => true,
2194        // positive-int is int<1, ∞>: subtype of int<sup_min, ∞> when sup_min <= 1
2195        (Atomic::TPositiveInt, Atomic::TIntRange { min, max }) => {
2196            max.is_none() && min.is_none_or(|m| m <= 1)
2197        }
2198        // negative-int is int<-∞, -1>: subtype of int<-∞, sup_max> when sup_max >= -1
2199        (Atomic::TNegativeInt, Atomic::TIntRange { min, max }) => {
2200            min.is_none() && max.is_none_or(|m| m >= -1)
2201        }
2202        // non-negative-int is int<0, ∞>: subtype of int<sup_min, ∞> when sup_min <= 0
2203        (Atomic::TNonNegativeInt, Atomic::TIntRange { min, max }) => {
2204            max.is_none() && min.is_none_or(|m| m <= 0)
2205        }
2206        // A bounded int range is a subtype of a named int subtype when every value fits
2207        (Atomic::TIntRange { min: sub_min, .. }, Atomic::TPositiveInt) => {
2208            sub_min.is_some_and(|lo| lo >= 1)
2209        }
2210        (Atomic::TIntRange { min: sub_min, .. }, Atomic::TNonNegativeInt) => {
2211            sub_min.is_some_and(|lo| lo >= 0)
2212        }
2213        (Atomic::TIntRange { max: sub_max, .. }, Atomic::TNegativeInt) => {
2214            sub_max.is_some_and(|hi| hi <= -1)
2215        }
2216        // int<sub_min, sub_max> <: int<sup_min, sup_max> when ranges nest
2217        (
2218            Atomic::TIntRange {
2219                min: sub_min,
2220                max: sub_max,
2221            },
2222            Atomic::TIntRange {
2223                min: sup_min,
2224                max: sup_max,
2225            },
2226        ) => {
2227            let lower_ok = match (sub_min, sup_min) {
2228                (_, None) => true,
2229                (None, Some(_)) => false,
2230                (Some(sl), Some(su)) => sl >= su,
2231            };
2232            let upper_ok = match (sub_max, sup_max) {
2233                (None, None) | (Some(_), None) => true,
2234                (None, Some(_)) => false,
2235                (Some(sl), Some(su)) => sl <= su,
2236            };
2237            lower_ok && upper_ok
2238        }
2239
2240        (Atomic::TLiteralFloat(..), Atomic::TFloat) => true,
2241        (Atomic::TLiteralFloat(..), Atomic::TNumeric) => true,
2242        (Atomic::TLiteralFloat(..), Atomic::TScalar) => true,
2243
2244        (Atomic::TLiteralString(s), Atomic::TString) => {
2245            let _ = s;
2246            true
2247        }
2248        (Atomic::TLiteralString(s), Atomic::TCallableString) => {
2249            let _ = s;
2250            true
2251        }
2252        (Atomic::TLiteralString(s), Atomic::TNonEmptyString) => !s.is_empty(),
2253        (Atomic::TLiteralString(s), Atomic::TNumericString) => s.parse::<f64>().is_ok(),
2254        // A literal string is type-compatible with class-string; validate_class_string_argument
2255        // separately checks whether the string names a real class (UndefinedClass).
2256        (Atomic::TLiteralString(_), Atomic::TClassString(_)) => true,
2257        // Same, for interface-string; validate_interface_string_argument checks existence
2258        // and that the name actually resolves to an interface.
2259        (Atomic::TLiteralString(_), Atomic::TInterfaceString(_)) => true,
2260        (Atomic::TLiteralString(_), Atomic::TScalar) => true,
2261        (Atomic::TNonEmptyString, Atomic::TString) => true,
2262        (Atomic::TCallableString, Atomic::TString) => true,
2263        // numeric-string is always non-empty (e.g. "42", "-1", "0.5") — "" is not numeric.
2264        (Atomic::TNumericString, Atomic::TNonEmptyString) => true,
2265        (Atomic::TNumericString, Atomic::TString) => true,
2266        // A class/interface/callable/enum/trait name can never be the empty
2267        // string in real PHP — every one of these string-subtype atoms is
2268        // always non-empty, same reasoning as numeric-string above.
2269        (Atomic::TClassString(_), Atomic::TNonEmptyString) => true,
2270        (Atomic::TInterfaceString(_), Atomic::TNonEmptyString) => true,
2271        (Atomic::TCallableString, Atomic::TNonEmptyString) => true,
2272        (Atomic::TEnumString, Atomic::TNonEmptyString) => true,
2273        (Atomic::TTraitString, Atomic::TNonEmptyString) => true,
2274        (Atomic::TClassString(_), Atomic::TString) => true,
2275        (Atomic::TInterfaceString(_), Atomic::TString) => true,
2276        // Every interface-string is a valid class-string: PHP doesn't distinguish
2277        // the two at runtime — both are just strings naming a class-like symbol.
2278        // Instantiability (`new $x()`) is guarded separately, since an interface
2279        // name can never be `new`-ed even though it satisfies class-string.
2280        (Atomic::TInterfaceString(_), Atomic::TClassString(None)) => true,
2281        (Atomic::TClassString(Some(_)), Atomic::TClassString(None)) => true,
2282        (Atomic::TInterfaceString(Some(a)), Atomic::TClassString(Some(b))) => a == b,
2283        (Atomic::TEnumString, Atomic::TString) => true,
2284        (Atomic::TTraitString, Atomic::TString) => true,
2285
2286        (Atomic::TTrue, Atomic::TBool) => true,
2287        (Atomic::TFalse, Atomic::TBool) => true,
2288
2289        (Atomic::TInt, Atomic::TNumeric) => true,
2290        (Atomic::TFloat, Atomic::TNumeric) => true,
2291        (Atomic::TIntegralFloat, Atomic::TNumeric) => true,
2292        (Atomic::TNumericString, Atomic::TNumeric) => true,
2293
2294        (Atomic::TInt, Atomic::TScalar) => true,
2295        (Atomic::TFloat, Atomic::TScalar) => true,
2296        (Atomic::TIntegralFloat, Atomic::TScalar) => true,
2297        (Atomic::TString, Atomic::TScalar) => true,
2298        (Atomic::TBool, Atomic::TScalar) => true,
2299        (Atomic::TNumeric, Atomic::TScalar) => true,
2300        (Atomic::TTrue, Atomic::TScalar) => true,
2301        (Atomic::TFalse, Atomic::TScalar) => true,
2302        // Every refined string atom is, at runtime, still just a `string` —
2303        // and therefore a `scalar` — same as the already-covered TLiteralString
2304        // and int-family refinements just above/below.
2305        (Atomic::TNonEmptyString, Atomic::TScalar) => true,
2306        (Atomic::TNumericString, Atomic::TScalar) => true,
2307        (Atomic::TCallableString, Atomic::TScalar) => true,
2308        (Atomic::TClassString(_), Atomic::TScalar) => true,
2309        (Atomic::TInterfaceString(_), Atomic::TScalar) => true,
2310        (Atomic::TEnumString, Atomic::TScalar) => true,
2311        (Atomic::TTraitString, Atomic::TScalar) => true,
2312
2313        // Object hierarchy (structural, no codebase)
2314        (Atomic::TNamedObject { .. }, Atomic::TObject) => true,
2315        (Atomic::TStaticObject { .. }, Atomic::TObject) => true,
2316        (Atomic::TSelf { .. }, Atomic::TObject) => true,
2317        // An enum-case literal is, at runtime, an object.
2318        (Atomic::TLiteralEnumCase { .. }, Atomic::TObject) => true,
2319        // self(X) and static(X) satisfy TNamedObject(X) with same FQCN
2320        (Atomic::TSelf { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
2321        (Atomic::TStaticObject { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
2322        // TNamedObject(X) satisfies self(X) / static(X) with same FQCN
2323        (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TSelf { fqcn: b }) => a == b,
2324        (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TStaticObject { fqcn: b }) => a == b,
2325        // An enum-case literal satisfies its own bare enum type (enums are
2326        // represented as TNamedObject).
2327        (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TNamedObject { fqcn, .. }) => {
2328            enum_fqcn == fqcn
2329        }
2330        (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TSelf { fqcn })
2331        | (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TStaticObject { fqcn }) => {
2332            enum_fqcn == fqcn
2333        }
2334        // Bare generic property accepts parameterized value: Box accepts Box<string>.
2335        // The reverse is NOT true — bare Box value does not satisfy Box<string> property
2336        // (invariant check). Only sup being bare (empty type_params) is the wildcard.
2337        (
2338            Atomic::TNamedObject {
2339                fqcn: sub_fqcn,
2340                type_params: sub_params,
2341            },
2342            Atomic::TNamedObject {
2343                fqcn: sup_fqcn,
2344                type_params: sup_params,
2345            },
2346        ) => {
2347            sub_fqcn == sup_fqcn
2348                && (sup_params.is_empty() || type_params_compatible(sub_params, sup_params))
2349        }
2350
2351        // TIntegralFloat is a subtype of float (all integral floats are floats)
2352        (Atomic::TIntegralFloat, Atomic::TFloat) => true,
2353
2354        // Literal int widens to float in PHP
2355        (Atomic::TLiteralInt(_), Atomic::TFloat) => true,
2356        (Atomic::TPositiveInt, Atomic::TFloat) => true,
2357        (Atomic::TNegativeInt, Atomic::TFloat) => true,
2358        (Atomic::TNonNegativeInt, Atomic::TFloat) => true,
2359        (Atomic::TInt, Atomic::TFloat) => true,
2360        (Atomic::TIntRange { .. }, Atomic::TFloat) => true,
2361
2362        // Literal int satisfies an int range only when the value is within bounds
2363        (Atomic::TLiteralInt(n), Atomic::TIntRange { min, max }) => {
2364            min.is_none_or(|lo| *n >= lo) && max.is_none_or(|hi| *n <= hi)
2365        }
2366
2367        // PHP callables: string and array are valid callable values
2368        (Atomic::TString, Atomic::TCallable { .. }) => true,
2369        (Atomic::TCallableString, Atomic::TCallable { .. }) => true,
2370        (Atomic::TNonEmptyString, Atomic::TCallable { .. }) => true,
2371        (Atomic::TLiteralString(_), Atomic::TCallable { .. }) => true,
2372        (Atomic::TArray { .. }, Atomic::TCallable { .. }) => true,
2373        (Atomic::TNonEmptyArray { .. }, Atomic::TCallable { .. }) => true,
2374        (Atomic::TKeyedArray { .. }, Atomic::TCallable { .. }) => true,
2375
2376        // Closure <: callable, typed Closure <: Closure
2377        (Atomic::TClosure { .. }, Atomic::TCallable { .. }) => true,
2378        // callable <: Closure: callable is wider but not flagged at default error level
2379        (Atomic::TCallable { .. }, Atomic::TClosure { .. }) => true,
2380        // TClosure <: TClosure: check arity, per-parameter contravariance, and
2381        // return covariance for scalar/array-shaped types, where a purely
2382        // structural check is reliable. A named-class (or nested-callable)
2383        // param/return is skipped rather than checked — this checker has no
2384        // database access to walk `extends`/`implements`, so it can't safely
2385        // tell a real Liskov violation apart from a legitimate subclass/
2386        // superclass substitution; treating it as compatible avoids false
2387        // positives on that far more common case at the cost of missing the
2388        // narrower nominal-variance violation.
2389        (Atomic::TClosure { data: sub }, Atomic::TClosure { data: sup }) => {
2390            fn has_nominal_type(t: &Type) -> bool {
2391                t.types.iter().any(|a| {
2392                    matches!(
2393                        a,
2394                        Atomic::TNamedObject { .. }
2395                            | Atomic::TSelf { .. }
2396                            | Atomic::TStaticObject { .. }
2397                            | Atomic::TTemplateParam { .. }
2398                            | Atomic::TClosure { .. }
2399                            | Atomic::TCallable { .. }
2400                    )
2401                })
2402            }
2403            let sub_required = sub
2404                .params
2405                .iter()
2406                .filter(|p| !p.is_optional && !p.is_variadic)
2407                .count();
2408            if sub_required > sup.params.len() {
2409                false
2410            } else {
2411                let params_ok = sup.params.iter().enumerate().all(|(i, sup_param)| {
2412                    let Some(sub_param) = sub.params.get(i) else {
2413                        return true;
2414                    };
2415                    if sub_param.is_optional || sub_param.is_variadic {
2416                        return true;
2417                    }
2418                    let (Some(sub_ty), Some(sup_ty)) =
2419                        (sub_param.ty.as_ref(), sup_param.ty.as_ref())
2420                    else {
2421                        return true;
2422                    };
2423                    let (sub_u, sup_u) = (sub_ty.to_union(), sup_ty.to_union());
2424                    if has_nominal_type(&sub_u) || has_nominal_type(&sup_u) {
2425                        return true;
2426                    }
2427                    // Contravariance: whatever `sup` promises to pass must be
2428                    // acceptable to `sub`'s declared parameter type.
2429                    sup_u.is_subtype_structural(&sub_u)
2430                });
2431                params_ok
2432                    && (sub.return_type.is_mixed()
2433                        || sup.return_type.is_mixed()
2434                        // A void callback discards its return value, so any
2435                        // return type satisfies it — PHP places no
2436                        // constraint on what an implementation returns here.
2437                        || sup.return_type.is_void()
2438                        || has_nominal_type(&sub.return_type)
2439                        || has_nominal_type(&sup.return_type)
2440                        || sub.return_type.is_subtype_structural(&sup.return_type))
2441            }
2442        }
2443        // callable <: callable (trivial)
2444        (Atomic::TCallable { .. }, Atomic::TCallable { .. }) => true,
2445        // TClosure satisfies `Closure` named object or `object`
2446        (Atomic::TClosure { .. }, Atomic::TNamedObject { fqcn, .. }) => {
2447            fqcn.as_ref().eq_ignore_ascii_case("closure")
2448        }
2449        (Atomic::TClosure { .. }, Atomic::TObject) => true,
2450        // bare `Closure` (named object without signature) satisfies any typed Closure(): T
2451        (Atomic::TNamedObject { fqcn, .. }, Atomic::TClosure { .. }) => {
2452            fqcn.as_ref().eq_ignore_ascii_case("closure")
2453        }
2454        // `Closure` named-object satisfies `callable`
2455        (Atomic::TNamedObject { fqcn, .. }, Atomic::TCallable { .. }) => {
2456            fqcn.as_ref().eq_ignore_ascii_case("closure")
2457        }
2458
2459        // A&B&C <: D&E iff every part of the supertype is satisfied by some
2460        // part of the subtype — an intersection with MORE conjuncts is the
2461        // more specific (sub)type, so `Countable&ArrayAccess&Iterator` is a
2462        // subtype of `Countable&ArrayAccess`. Purely structural (each part's
2463        // own `is_subtype_structural` recurses, so e.g. two differently-named
2464        // interfaces only match when equal — same conservative stance as the
2465        // TClosure<:TClosure arm above for named types).
2466        (
2467            Atomic::TIntersection { parts: sub_parts },
2468            Atomic::TIntersection { parts: sup_parts },
2469        ) => sup_parts.iter().all(|sup_part| {
2470            sub_parts
2471                .iter()
2472                .any(|sub_part| sub_part.is_subtype_structural(sup_part))
2473        }),
2474        (Atomic::TIntersection { parts }, Atomic::TObject) => parts
2475            .iter()
2476            .any(|part| part.is_subtype_structural(&Type::single(Atomic::TObject))),
2477
2478        // List <: array  (list key is always int; int must satisfy the array's key type)
2479        (Atomic::TList { value }, Atomic::TArray { key, value: av }) => {
2480            Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2481        }
2482        (Atomic::TNonEmptyList { value }, Atomic::TArray { key, value: av }) => {
2483            Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2484        }
2485        (Atomic::TNonEmptyList { value }, Atomic::TNonEmptyArray { key, value: av }) => {
2486            Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2487        }
2488        (Atomic::TNonEmptyList { value }, Atomic::TList { value: lv }) => {
2489            value.is_subtype_structural(lv)
2490        }
2491        (Atomic::TNonEmptyList { value: v1 }, Atomic::TNonEmptyList { value: v2 }) => {
2492            v1.is_subtype_structural(v2)
2493        }
2494        // array<int, X> is accepted where list<X> or non-empty-list<X> expected
2495        (Atomic::TArray { key, value: av }, Atomic::TList { value: lv }) => {
2496            matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2497                && av.is_subtype_structural(lv)
2498        }
2499        (Atomic::TArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
2500            matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2501                && av.is_subtype_structural(lv)
2502        }
2503        (Atomic::TNonEmptyArray { key, value: av }, Atomic::TList { value: lv }) => {
2504            matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2505                && av.is_subtype_structural(lv)
2506        }
2507        (Atomic::TNonEmptyArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
2508            matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2509                && av.is_subtype_structural(lv)
2510        }
2511        // TList <: TList value covariance
2512        (Atomic::TList { value: v1 }, Atomic::TList { value: v2 }) => v1.is_subtype_structural(v2),
2513        (Atomic::TNonEmptyArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
2514            k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
2515        }
2516
2517        // array<A, B> <: array<C, D>  iff  A <: C && B <: D
2518        (Atomic::TArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
2519            k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
2520        }
2521
2522        // A keyed/shape array is a subtype of array<K, V> / non-empty-array<K, V>
2523        // when all property KEYS are subtypes of K. Value compatibility is checked
2524        // structurally only for scalar types; named-object values are deferred to
2525        // class-hierarchy checks in return_arrays_compatible (mir-analyzer).
2526        // Open shapes (is_open=true) may have extra unknown keys beyond `properties`:
2527        // those stay unchecked (permissive), but every KNOWN property must still
2528        // satisfy K/V regardless of openness — an open shape isn't a license to skip
2529        // checking the keys it does declare.
2530        (Atomic::TKeyedArray { properties, .. }, Atomic::TArray { key, value }) => {
2531            properties.iter().all(|(prop_key, prop)| {
2532                let key_atomic = match prop_key {
2533                    crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2534                    crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2535                };
2536                if !Type::single(key_atomic).is_subtype_structural(key) {
2537                    return false; // key mismatch — definitively incompatible
2538                }
2539                // Named-object values require class-hierarchy checks not available here.
2540                let has_named_obj = prop.ty.types.iter().any(|a| {
2541                    matches!(
2542                        a,
2543                        Atomic::TNamedObject { .. }
2544                            | Atomic::TSelf { .. }
2545                            | Atomic::TStaticObject { .. }
2546                            | Atomic::TClosure { .. }
2547                            | Atomic::TTemplateParam { .. }
2548                    )
2549                });
2550                has_named_obj || prop.ty.is_subtype_structural(value)
2551            })
2552        }
2553        (
2554            Atomic::TKeyedArray {
2555                properties,
2556                is_open,
2557                ..
2558            },
2559            Atomic::TNonEmptyArray { key, value },
2560        ) => {
2561            (*is_open || properties.iter().any(|(_, p)| !p.optional))
2562                && properties.iter().all(|(prop_key, prop)| {
2563                    let key_atomic = match prop_key {
2564                        crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2565                        crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2566                    };
2567                    if !Type::single(key_atomic).is_subtype_structural(key) {
2568                        return false;
2569                    }
2570                    let has_named_obj = prop.ty.types.iter().any(|a| {
2571                        matches!(
2572                            a,
2573                            Atomic::TNamedObject { .. }
2574                                | Atomic::TSelf { .. }
2575                                | Atomic::TStaticObject { .. }
2576                                | Atomic::TClosure { .. }
2577                                | Atomic::TTemplateParam { .. }
2578                        )
2579                    });
2580                    has_named_obj || prop.ty.is_subtype_structural(value)
2581                })
2582        }
2583
2584        // A list-shaped keyed array (is_list=true, all int keys) is a subtype of list<X>.
2585        (
2586            Atomic::TKeyedArray {
2587                properties,
2588                is_list,
2589                ..
2590            },
2591            Atomic::TList { value: lv },
2592        ) => *is_list && properties.values().all(|p| p.ty.is_subtype_structural(lv)),
2593        (
2594            Atomic::TKeyedArray {
2595                properties,
2596                is_list,
2597                ..
2598            },
2599            Atomic::TNonEmptyList { value: lv },
2600        ) => {
2601            *is_list
2602                && !properties.is_empty()
2603                && properties.values().all(|p| p.ty.is_subtype_structural(lv))
2604        }
2605
2606        // Two shapes: every sup key must be satisfied (present+compatible, or
2607        // absent-but-optional/sub-open), and sub may not have keys sup doesn't
2608        // declare unless sup itself is open. Named-object values are deferred
2609        // to class-hierarchy checks, same as the TArray/TList sup arms above.
2610        (
2611            Atomic::TKeyedArray {
2612                properties: sub_props,
2613                is_open: sub_open,
2614                ..
2615            },
2616            Atomic::TKeyedArray {
2617                properties: sup_props,
2618                is_open: sup_open,
2619                ..
2620            },
2621        ) => {
2622            let keys_satisfied = sup_props
2623                .iter()
2624                .all(|(key, sup_prop)| match sub_props.get(key) {
2625                    Some(sub_prop) => {
2626                        // A key merely optional on the sub side may legally be
2627                        // absent at runtime, so it can't satisfy a sup key that
2628                        // requires it present.
2629                        if !sup_prop.optional && sub_prop.optional {
2630                            return false;
2631                        }
2632                        let has_named_obj = sup_prop.ty.types.iter().any(|a| {
2633                            matches!(
2634                                a,
2635                                Atomic::TNamedObject { .. }
2636                                    | Atomic::TSelf { .. }
2637                                    | Atomic::TStaticObject { .. }
2638                                    | Atomic::TClosure { .. }
2639                                    | Atomic::TTemplateParam { .. }
2640                            )
2641                        });
2642                        has_named_obj || sub_prop.ty.is_subtype_by_template_bounds(&sup_prop.ty)
2643                    }
2644                    None => sup_prop.optional || *sub_open,
2645                });
2646            let no_undeclared_extras =
2647                *sup_open || sub_props.keys().all(|k| sup_props.contains_key(k));
2648            keys_satisfied && no_undeclared_extras
2649        }
2650        // TKeyedArray (array shape) satisfies TIntersection iff it satisfies every
2651        // intersection part. This handles the Psalm idiom of using intersection types
2652        // for "shape plus extra keys allowed" patterns like:
2653        // @psalm-type Context = array<string,mixed> & array{actor:...,target?:...,outcome:...}
2654        (
2655            Atomic::TKeyedArray {
2656                properties,
2657                is_open,
2658                ..
2659            },
2660            Atomic::TIntersection { parts },
2661        ) => parts.iter().all(|part| {
2662            part.types.iter().any(|part_atomic| match part_atomic {
2663                Atomic::TKeyedArray {
2664                    properties: sup_props,
2665                    is_open: sup_open,
2666                    ..
2667                } => {
2668                    let keys_satisfied =
2669                        sup_props
2670                            .iter()
2671                            .all(|(key, sup_prop)| match properties.get(key) {
2672                                Some(sub_prop) => {
2673                                    if !sup_prop.optional && sub_prop.optional {
2674                                        return false;
2675                                    }
2676                                    let has_named_obj = sup_prop.ty.types.iter().any(|a| {
2677                                        matches!(
2678                                            a,
2679                                            Atomic::TNamedObject { .. }
2680                                                | Atomic::TSelf { .. }
2681                                                | Atomic::TStaticObject { .. }
2682                                                | Atomic::TClosure { .. }
2683                                                | Atomic::TTemplateParam { .. }
2684                                        )
2685                                    });
2686                                    has_named_obj
2687                                        || sub_prop.ty.is_subtype_by_template_bounds(&sup_prop.ty)
2688                                        || bare_array_may_fit(&sub_prop.ty, &sup_prop.ty)
2689                                }
2690                                None => *is_open || sup_prop.optional,
2691                            });
2692                    let has_array_part = parts.iter().any(|part| {
2693                        part.types
2694                            .iter()
2695                            .any(|t| matches!(t, Atomic::TArray { .. }))
2696                    });
2697                    let has_keyed_array_part = parts.iter().any(|part| {
2698                        part.types
2699                            .iter()
2700                            .any(|t| matches!(t, Atomic::TKeyedArray { .. }))
2701                    });
2702                    let keys_allowed_by_some_part = if has_array_part {
2703                        true
2704                    } else if has_keyed_array_part {
2705                        properties.keys().all(|k| {
2706                            parts.iter().any(|part| {
2707                                part.types.iter().any(|t| {
2708                                    if let Atomic::TKeyedArray {
2709                                        properties: part_props,
2710                                        ..
2711                                    } = t
2712                                    {
2713                                        part_props.contains_key(k)
2714                                    } else {
2715                                        false
2716                                    }
2717                                })
2718                            })
2719                        })
2720                    } else {
2721                        true
2722                    };
2723                    let no_undeclared_extras = *sup_open || keys_allowed_by_some_part;
2724                    keys_satisfied && no_undeclared_extras
2725                }
2726                Atomic::TArray { key, value } => properties.iter().all(|(prop_key, prop)| {
2727                    let key_atomic = match prop_key {
2728                        crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2729                        crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2730                    };
2731                    if !Type::single(key_atomic).is_subtype_structural(key) {
2732                        return false;
2733                    }
2734                    let has_named_obj = prop.ty.types.iter().any(|a| {
2735                        matches!(
2736                            a,
2737                            Atomic::TNamedObject { .. }
2738                                | Atomic::TSelf { .. }
2739                                | Atomic::TStaticObject { .. }
2740                                | Atomic::TClosure { .. }
2741                                | Atomic::TTemplateParam { .. }
2742                        )
2743                    });
2744                    has_named_obj || prop.ty.is_subtype_structural(value)
2745                }),
2746                Atomic::TNamedObject { .. }
2747                | Atomic::TSelf { .. }
2748                | Atomic::TStaticObject { .. }
2749                | Atomic::TClosure { .. }
2750                | Atomic::TTemplateParam { .. } => true,
2751                _ => false,
2752            })
2753        }),
2754
2755        _ => false,
2756    }
2757}
2758
2759/// A bare `array` carries no key/value info, so it may hold any array-shaped `sup`.
2760fn bare_array_may_fit(sub: &Type, sup: &Type) -> bool {
2761    fn array_like(t: &Atomic) -> bool {
2762        match t {
2763            Atomic::TArray { .. }
2764            | Atomic::TNonEmptyArray { .. }
2765            | Atomic::TList { .. }
2766            | Atomic::TNonEmptyList { .. }
2767            | Atomic::TKeyedArray { .. } => true,
2768            Atomic::TIntersection { parts } => parts.iter().all(|p| p.types.iter().all(array_like)),
2769            _ => false,
2770        }
2771    }
2772    matches!(
2773        sub.types.as_slice(),
2774        [Atomic::TArray { key, value }]
2775            if value.is_mixed()
2776                && (key.is_mixed()
2777                    || matches!(key.types.as_slice(), [Atomic::TInt, Atomic::TString] | [Atomic::TString, Atomic::TInt]))
2778    ) && sup.types.iter().all(array_like)
2779}
2780
2781/// Whether each generic type-argument in `sub` is compatible with the
2782/// corresponding argument in `sup`. Arguments are invariant (require structural
2783/// equality) with one exception: an empty array literal (`array{}`) is accepted
2784/// against any array/list argument, so `new Box([])` — inferred as
2785/// `Box<array{}>` — satisfies a declared `Box<list<T>>` for any `T`.
2786fn type_params_compatible(sub: &[Type], sup: &[Type]) -> bool {
2787    if sub.len() != sup.len() {
2788        return false;
2789    }
2790    sub.iter()
2791        .zip(sup.iter())
2792        .all(|(a, b)| a == b || (is_empty_array_literal(a) && is_array_like(b)))
2793}
2794
2795/// True for a non-empty union whose atoms are all empty keyed arrays (`array{}`),
2796/// i.e. the type of an empty array literal `[]`.
2797fn is_empty_array_literal(t: &Type) -> bool {
2798    !t.types.is_empty()
2799        && t.types.iter().all(
2800            |atom| matches!(atom, Atomic::TKeyedArray { properties, .. } if properties.is_empty()),
2801        )
2802}
2803
2804/// True for a non-empty union whose atoms are all array/list types.
2805fn is_array_like(t: &Type) -> bool {
2806    !t.types.is_empty() && t.types.iter().all(|atom| atom.is_array())
2807}
2808
2809// ---------------------------------------------------------------------------
2810// Tests
2811// ---------------------------------------------------------------------------
2812
2813/// Accumulates a union with hash-based dedup of literal strings/ints, so large
2814/// literal sets build in linear time. Equivalent to repeated [`Type::add_type`].
2815pub struct UnionBuilder {
2816    ty: Type,
2817    strings: std::collections::HashSet<std::sync::Arc<str>>,
2818    ints: std::collections::HashSet<i64>,
2819    // No atom present can subsume a new literal (`mixed`, `string`, int ranges).
2820    literals_independent: bool,
2821}
2822
2823impl Default for UnionBuilder {
2824    fn default() -> Self {
2825        Self::new()
2826    }
2827}
2828
2829impl UnionBuilder {
2830    pub fn new() -> Self {
2831        Self {
2832            ty: Type::empty(),
2833            strings: Default::default(),
2834            ints: Default::default(),
2835            literals_independent: true,
2836        }
2837    }
2838
2839    pub fn is_empty(&self) -> bool {
2840        self.ty.is_empty()
2841    }
2842
2843    pub fn merge(&mut self, other: &Type) {
2844        for a in &other.types {
2845            self.add(a.clone());
2846        }
2847        self.ty.possibly_undefined |= other.possibly_undefined;
2848    }
2849
2850    pub fn add(&mut self, atomic: Atomic) {
2851        // A lone `never` is dropped by add_type once anything else arrives.
2852        let lone_never = matches!(self.ty.types.first(), Some(Atomic::TNever));
2853        if self.literals_independent && !lone_never {
2854            match &atomic {
2855                Atomic::TLiteralString(s) => {
2856                    if self.strings.insert(s.clone()) {
2857                        self.ty.types.push(atomic);
2858                    }
2859                    return;
2860                }
2861                Atomic::TLiteralInt(n) => {
2862                    if self.ints.insert(*n) {
2863                        self.ty.types.push(atomic);
2864                    }
2865                    return;
2866                }
2867                _ => {}
2868            }
2869        }
2870        let disturbs_literals = matches!(
2871            atomic,
2872            Atomic::TString | Atomic::TMixed | Atomic::TConditional { .. }
2873        ) || int_bounds(&atomic).is_some();
2874        self.ty.add_type(atomic);
2875        if disturbs_literals || lone_never {
2876            self.resync();
2877        }
2878    }
2879
2880    fn resync(&mut self) {
2881        self.strings.clear();
2882        self.ints.clear();
2883        self.literals_independent = true;
2884        for t in &self.ty.types {
2885            match t {
2886                Atomic::TLiteralString(s) => {
2887                    self.strings.insert(s.clone());
2888                }
2889                Atomic::TLiteralInt(n) => {
2890                    self.ints.insert(*n);
2891                }
2892                Atomic::TMixed | Atomic::TString => self.literals_independent = false,
2893                other if int_bounds(other).is_some() => self.literals_independent = false,
2894                _ => {}
2895            }
2896        }
2897    }
2898
2899    pub fn build(self) -> Type {
2900        self.ty
2901    }
2902}
2903
2904/// `list{class-string|object, non-empty-string}`: the `[class, method]` form of a callable.
2905fn callable_array() -> Atomic {
2906    let mut properties = KeyedProperties::with_capacity_and_hasher(2, Default::default());
2907    properties.insert(
2908        ArrayKey::Int(0),
2909        KeyedProperty {
2910            ty: Type::from_vec(vec![Atomic::TClassString(None), Atomic::TObject]),
2911            optional: false,
2912        },
2913    );
2914    properties.insert(
2915        ArrayKey::Int(1),
2916        KeyedProperty {
2917            ty: Type::single(Atomic::TNonEmptyString),
2918            optional: false,
2919        },
2920    );
2921    Atomic::TKeyedArray {
2922        properties: Arc::new(properties),
2923        is_open: false,
2924        is_list: true,
2925    }
2926}
2927
2928#[cfg(test)]
2929mod tests {
2930    use std::sync::Arc;
2931
2932    use super::*;
2933
2934    fn conditional(
2935        param_name: Option<Name>,
2936        subject: Type,
2937        if_true: Type,
2938        if_false: Type,
2939    ) -> Atomic {
2940        Atomic::TConditional {
2941            data: Box::new(crate::atomic::ConditionalData {
2942                param_name,
2943                subject,
2944                if_true,
2945                if_false,
2946            }),
2947        }
2948    }
2949
2950    #[test]
2951    fn single_is_single() {
2952        let u = Type::single(Atomic::TString);
2953        assert!(u.is_single());
2954        assert!(!u.is_nullable());
2955    }
2956
2957    #[test]
2958    fn nullable_has_null() {
2959        let u = Type::nullable(Atomic::TString);
2960        assert!(u.is_nullable());
2961        assert_eq!(u.types.len(), 2);
2962    }
2963
2964    #[test]
2965    fn add_type_deduplicates() {
2966        let mut u = Type::single(Atomic::TString);
2967        u.add_type(Atomic::TString);
2968        assert_eq!(u.types.len(), 1);
2969    }
2970
2971    #[test]
2972    fn array_key_is_int_string() {
2973        let k = Type::array_key();
2974        assert!(k.is_array_key());
2975        assert_eq!(k.types.len(), 2);
2976    }
2977
2978    #[test]
2979    fn is_array_key_false_for_plain_int() {
2980        assert!(!Type::int().is_array_key());
2981    }
2982
2983    #[test]
2984    fn is_array_key_false_for_mixed() {
2985        assert!(!Type::mixed().is_array_key());
2986    }
2987
2988    #[test]
2989    fn is_array_key_false_for_int_string_null() {
2990        let mut u = Type::array_key();
2991        u.add_type(Atomic::TNull);
2992        assert!(!u.is_array_key());
2993    }
2994
2995    #[test]
2996    fn add_type_literal_subsumed_by_base() {
2997        let mut u = Type::single(Atomic::TInt);
2998        u.add_type(Atomic::TLiteralInt(42));
2999        assert_eq!(u.types.len(), 1);
3000        assert!(matches!(u.types[0], Atomic::TInt));
3001    }
3002
3003    #[test]
3004    fn true_then_false_merges_to_bool() {
3005        let mut u = Type::single(Atomic::TTrue);
3006        u.add_type(Atomic::TFalse);
3007        assert_eq!(u.types.len(), 1);
3008        assert!(matches!(u.types[0], Atomic::TBool));
3009    }
3010
3011    #[test]
3012    fn false_then_true_merges_to_bool() {
3013        let mut u = Type::single(Atomic::TFalse);
3014        u.add_type(Atomic::TTrue);
3015        assert_eq!(u.types.len(), 1);
3016        assert!(matches!(u.types[0], Atomic::TBool));
3017    }
3018
3019    #[test]
3020    fn true_alone_stays_true() {
3021        let u = Type::single(Atomic::TTrue);
3022        assert_eq!(u.types.len(), 1);
3023        assert!(matches!(u.types[0], Atomic::TTrue));
3024    }
3025
3026    #[test]
3027    fn true_false_merge_preserves_other_union_members() {
3028        let mut u = Type::single(Atomic::TTrue);
3029        u.add_type(Atomic::TNull);
3030        u.add_type(Atomic::TFalse);
3031        assert_eq!(u.types.len(), 2);
3032        assert!(u.contains(|t| matches!(t, Atomic::TBool)));
3033        assert!(u.contains(|t| matches!(t, Atomic::TNull)));
3034    }
3035
3036    #[test]
3037    fn add_type_base_widens_literals() {
3038        let mut u = Type::single(Atomic::TLiteralInt(1));
3039        u.add_type(Atomic::TLiteralInt(2));
3040        u.add_type(Atomic::TInt);
3041        assert_eq!(u.types.len(), 1);
3042        assert!(matches!(u.types[0], Atomic::TInt));
3043    }
3044
3045    #[test]
3046    fn mixed_subsumes_everything() {
3047        let mut u = Type::single(Atomic::TString);
3048        u.add_type(Atomic::TMixed);
3049        assert_eq!(u.types.len(), 1);
3050        assert!(u.is_mixed());
3051    }
3052
3053    #[test]
3054    fn remove_null() {
3055        let u = Type::nullable(Atomic::TString);
3056        let narrowed = u.remove_null();
3057        assert!(!narrowed.is_nullable());
3058        assert_eq!(narrowed.types.len(), 1);
3059    }
3060
3061    #[test]
3062    fn narrow_to_truthy_removes_null_false() {
3063        let mut u = Type::empty();
3064        u.add_type(Atomic::TString);
3065        u.add_type(Atomic::TNull);
3066        u.add_type(Atomic::TFalse);
3067        let truthy = u.narrow_to_truthy();
3068        assert!(!truthy.is_nullable());
3069        assert!(!truthy.contains(|t| matches!(t, Atomic::TFalse)));
3070    }
3071
3072    #[test]
3073    fn merge_combines_types() {
3074        let a = Type::single(Atomic::TString);
3075        let b = Type::single(Atomic::TInt);
3076        let merged = Type::merge(&a, &b);
3077        assert_eq!(merged.types.len(), 2);
3078    }
3079
3080    #[test]
3081    fn intersect_keeps_narrower_side_not_self() {
3082        // int ∩ (1|2) must keep the narrower `1|2`, not the wider `int` —
3083        // this is exactly what a `match ($x) { 1, 2 => ... }` arm relies on
3084        // to narrow $x inside its body.
3085        let int_ty = Type::single(Atomic::TInt);
3086        let mut literals = Type::empty();
3087        literals.add_type(Atomic::TLiteralInt(1));
3088        literals.add_type(Atomic::TLiteralInt(2));
3089
3090        let narrowed = int_ty.intersect_with(&literals);
3091        assert_eq!(narrowed.types.len(), 2);
3092        assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(1))));
3093        assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(2))));
3094        assert!(!narrowed.contains(|t| matches!(t, Atomic::TInt)));
3095    }
3096
3097    #[test]
3098    fn subtype_literal_int_under_int() {
3099        let sub = Type::single(Atomic::TLiteralInt(5));
3100        let sup = Type::single(Atomic::TInt);
3101        assert!(sub.is_subtype_structural(&sup));
3102    }
3103
3104    #[test]
3105    fn subtype_never_is_bottom() {
3106        let never = Type::never();
3107        let string = Type::single(Atomic::TString);
3108        assert!(never.is_subtype_structural(&string));
3109    }
3110
3111    #[test]
3112    fn subtype_everything_under_mixed() {
3113        let string = Type::single(Atomic::TString);
3114        let mixed = Type::mixed();
3115        assert!(string.is_subtype_structural(&mixed));
3116    }
3117
3118    #[test]
3119    fn subtype_enum_case_under_own_enum() {
3120        let sub = Type::single(Atomic::TLiteralEnumCase {
3121            enum_fqcn: Name::new("RoundingMode"),
3122            case_name: Name::new("Unnecessary"),
3123        });
3124        let sup = Type::single(Atomic::TNamedObject {
3125            fqcn: Name::new("RoundingMode"),
3126            type_params: empty_type_params(),
3127        });
3128        assert!(sub.is_subtype_structural(&sup));
3129    }
3130
3131    #[test]
3132    fn enum_case_not_subtype_of_unrelated_enum() {
3133        let sub = Type::single(Atomic::TLiteralEnumCase {
3134            enum_fqcn: Name::new("RoundingMode"),
3135            case_name: Name::new("Unnecessary"),
3136        });
3137        let sup = Type::single(Atomic::TNamedObject {
3138            fqcn: Name::new("Suit"),
3139            type_params: empty_type_params(),
3140        });
3141        assert!(!sub.is_subtype_structural(&sup));
3142    }
3143
3144    #[test]
3145    fn subtype_enum_case_under_own_self_and_static() {
3146        let case = |enum_fqcn: &str| {
3147            Type::single(Atomic::TLiteralEnumCase {
3148                enum_fqcn: Name::new(enum_fqcn),
3149                case_name: Name::new("A"),
3150            })
3151        };
3152        let own = Type::single(Atomic::TSelf {
3153            fqcn: Name::new("Suit"),
3154        });
3155        let own_static = Type::single(Atomic::TStaticObject {
3156            fqcn: Name::new("Suit"),
3157        });
3158        assert!(case("Suit").is_subtype_structural(&own));
3159        assert!(case("Suit").is_subtype_structural(&own_static));
3160        assert!(!case("Other").is_subtype_structural(&own));
3161    }
3162
3163    #[test]
3164    fn subtype_enum_case_under_bare_object() {
3165        let sub = Type::single(Atomic::TLiteralEnumCase {
3166            enum_fqcn: Name::new("RoundingMode"),
3167            case_name: Name::new("Unnecessary"),
3168        });
3169        let sup = Type::single(Atomic::TObject);
3170        assert!(sub.is_subtype_structural(&sup));
3171    }
3172
3173    #[test]
3174    fn template_substitution() {
3175        let mut bindings = FxHashMap::default();
3176        bindings.insert(Name::new("T"), Type::single(Atomic::TString));
3177
3178        let tmpl = Type::single(Atomic::TTemplateParam {
3179            name: Name::new("T"),
3180            as_type: Box::new(Type::mixed()),
3181            defining_entity: Name::new("MyClass"),
3182        });
3183
3184        let resolved = tmpl.substitute_templates(&bindings);
3185        assert_eq!(resolved.types.len(), 1);
3186        assert!(matches!(resolved.types[0], Atomic::TString));
3187    }
3188
3189    #[test]
3190    fn intersection_is_object() {
3191        let parts = vec![
3192            Type::single(Atomic::TNamedObject {
3193                fqcn: Name::new("Iterator"),
3194                type_params: empty_type_params(),
3195            }),
3196            Type::single(Atomic::TNamedObject {
3197                fqcn: Name::new("Countable"),
3198                type_params: empty_type_params(),
3199            }),
3200        ];
3201        let atomic = Atomic::TIntersection {
3202            parts: vec_to_type_params(parts),
3203        };
3204        assert!(atomic.is_object());
3205        assert!(!atomic.can_be_falsy());
3206        assert!(atomic.can_be_truthy());
3207    }
3208
3209    #[test]
3210    fn intersection_display_two_parts() {
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 u = Type::single(Atomic::TIntersection {
3222            parts: vec_to_type_params(parts),
3223        });
3224        assert_eq!(format!("{u}"), "Iterator&Countable");
3225    }
3226
3227    #[test]
3228    fn intersection_display_three_parts() {
3229        let parts = vec![
3230            Type::single(Atomic::TNamedObject {
3231                fqcn: Name::new("A"),
3232                type_params: empty_type_params(),
3233            }),
3234            Type::single(Atomic::TNamedObject {
3235                fqcn: Name::new("B"),
3236                type_params: empty_type_params(),
3237            }),
3238            Type::single(Atomic::TNamedObject {
3239                fqcn: Name::new("C"),
3240                type_params: empty_type_params(),
3241            }),
3242        ];
3243        let u = Type::single(Atomic::TIntersection {
3244            parts: vec_to_type_params(parts),
3245        });
3246        assert_eq!(format!("{u}"), "A&B&C");
3247    }
3248
3249    #[test]
3250    fn intersection_in_nullable_union_display() {
3251        let intersection = Atomic::TIntersection {
3252            parts: vec_to_type_params(vec![
3253                Type::single(Atomic::TNamedObject {
3254                    fqcn: Name::new("Iterator"),
3255                    type_params: empty_type_params(),
3256                }),
3257                Type::single(Atomic::TNamedObject {
3258                    fqcn: Name::new("Countable"),
3259                    type_params: empty_type_params(),
3260                }),
3261            ]),
3262        };
3263        let mut u = Type::single(intersection);
3264        u.add_type(Atomic::TNull);
3265        assert!(u.is_nullable());
3266        assert!(u.contains(|t| matches!(t, Atomic::TIntersection { .. })));
3267    }
3268
3269    // --- substitute_templates coverage for previously-missing arms ----------
3270
3271    fn t_param(name: &str) -> Type {
3272        Type::single(Atomic::TTemplateParam {
3273            name: Name::new(name),
3274            as_type: Box::new(Type::mixed()),
3275            defining_entity: Name::new("Fn"),
3276        })
3277    }
3278
3279    fn bindings_t_string() -> FxHashMap<Name, Type> {
3280        let mut b = FxHashMap::default();
3281        b.insert(Name::new("T"), Type::single(Atomic::TString));
3282        b
3283    }
3284
3285    #[test]
3286    fn substitute_non_empty_array_key_and_value() {
3287        let ty = Type::single(Atomic::TNonEmptyArray {
3288            key: Box::new(t_param("T")),
3289            value: Box::new(t_param("T")),
3290        });
3291        let result = ty.substitute_templates(&bindings_t_string());
3292        assert_eq!(result.types.len(), 1);
3293        let Atomic::TNonEmptyArray { key, value } = &result.types[0] else {
3294            panic!("expected TNonEmptyArray");
3295        };
3296        assert!(matches!(key.types[0], Atomic::TString));
3297        assert!(matches!(value.types[0], Atomic::TString));
3298    }
3299
3300    #[test]
3301    fn substitute_non_empty_list_value() {
3302        let ty = Type::single(Atomic::TNonEmptyList {
3303            value: Box::new(t_param("T")),
3304        });
3305        let result = ty.substitute_templates(&bindings_t_string());
3306        let Atomic::TNonEmptyList { value } = &result.types[0] else {
3307            panic!("expected TNonEmptyList");
3308        };
3309        assert!(matches!(value.types[0], Atomic::TString));
3310    }
3311
3312    #[test]
3313    fn substitute_keyed_array_property_types() {
3314        use crate::atomic::{ArrayKey, KeyedProperty};
3315        let mut props = KeyedProperties::default();
3316        props.insert(
3317            ArrayKey::String(Arc::from("name")),
3318            KeyedProperty {
3319                ty: t_param("T"),
3320                optional: false,
3321            },
3322        );
3323        props.insert(
3324            ArrayKey::String(Arc::from("tag")),
3325            KeyedProperty {
3326                ty: t_param("T"),
3327                optional: true,
3328            },
3329        );
3330        let ty = Type::single(Atomic::TKeyedArray {
3331            properties: Arc::new(props),
3332            is_open: true,
3333            is_list: false,
3334        });
3335        let result = ty.substitute_templates(&bindings_t_string());
3336        let Atomic::TKeyedArray {
3337            properties,
3338            is_open,
3339            is_list,
3340        } = &result.types[0]
3341        else {
3342            panic!("expected TKeyedArray");
3343        };
3344        assert!(is_open);
3345        assert!(!is_list);
3346        assert!(matches!(
3347            properties[&ArrayKey::String(Arc::from("name"))].ty.types[0],
3348            Atomic::TString
3349        ));
3350        assert!(properties[&ArrayKey::String(Arc::from("tag"))].optional);
3351        assert!(matches!(
3352            properties[&ArrayKey::String(Arc::from("tag"))].ty.types[0],
3353            Atomic::TString
3354        ));
3355    }
3356
3357    #[test]
3358    fn substitute_callable_params_and_return() {
3359        use crate::atomic::FnParam;
3360        let ty = Type::single(Atomic::TCallable {
3361            params: Some(Box::new(vec![FnParam {
3362                name: Name::new("x"),
3363                ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3364                out_ty: None,
3365                default: None,
3366                is_variadic: false,
3367                is_byref: false,
3368                is_optional: false,
3369            }])),
3370            return_type: Some(Box::new(t_param("T"))),
3371            is_pure: false,
3372        });
3373        let result = ty.substitute_templates(&bindings_t_string());
3374        let Atomic::TCallable {
3375            params,
3376            return_type,
3377            ..
3378        } = &result.types[0]
3379        else {
3380            panic!("expected TCallable");
3381        };
3382        let param_ty = params.as_ref().unwrap()[0].ty.as_ref().unwrap();
3383        let param_union = param_ty.to_union();
3384        assert!(matches!(param_union.types[0], Atomic::TString));
3385        let ret = return_type.as_ref().unwrap();
3386        assert!(matches!(ret.types[0], Atomic::TString));
3387    }
3388
3389    #[test]
3390    fn substitute_callable_bare_no_panic() {
3391        // callable with no params/return — must not panic and must pass through unchanged
3392        let ty = Type::single(Atomic::TCallable {
3393            params: None,
3394            return_type: None,
3395            is_pure: false,
3396        });
3397        let result = ty.substitute_templates(&bindings_t_string());
3398        assert!(matches!(
3399            result.types[0],
3400            Atomic::TCallable {
3401                params: None,
3402                return_type: None,
3403                ..
3404            }
3405        ));
3406    }
3407
3408    #[test]
3409    fn substitute_closure_params_return_and_this() {
3410        use crate::atomic::FnParam;
3411        let ty = Type::single(Atomic::TClosure {
3412            data: Box::new(crate::atomic::ClosureData {
3413                params: Box::new([FnParam {
3414                    name: Name::new("a"),
3415                    ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3416                    out_ty: None,
3417                    default: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3418                    is_variadic: true,
3419                    is_byref: true,
3420                    is_optional: true,
3421                }]),
3422                return_type: t_param("T"),
3423                this_type: Some(t_param("T")),
3424                is_pure: false,
3425                is_static: false,
3426                rejects_surplus_args: false,
3427            }),
3428        });
3429        let result = ty.substitute_templates(&bindings_t_string());
3430        let Atomic::TClosure { data } = &result.types[0] else {
3431            panic!("expected TClosure");
3432        };
3433        let (params, return_type, this_type) = (&data.params, &data.return_type, &data.this_type);
3434        let p = &params[0];
3435        let ty_union = p.ty.as_ref().unwrap().to_union();
3436        let default_union = p.default.as_ref().unwrap().to_union();
3437        assert!(matches!(ty_union.types[0], Atomic::TString));
3438        assert!(matches!(default_union.types[0], Atomic::TString));
3439        // flags preserved
3440        assert!(p.is_variadic);
3441        assert!(p.is_byref);
3442        assert!(p.is_optional);
3443        assert!(matches!(return_type.types[0], Atomic::TString));
3444        assert!(matches!(
3445            this_type.as_ref().unwrap().types[0],
3446            Atomic::TString
3447        ));
3448    }
3449
3450    #[test]
3451    fn substitute_conditional_all_branches() {
3452        let ty = Type::single(conditional(
3453            None,
3454            t_param("T"),
3455            t_param("T"),
3456            Type::single(Atomic::TInt),
3457        ));
3458        let result = ty.substitute_templates(&bindings_t_string());
3459        let Atomic::TConditional { data } = &result.types[0] else {
3460            panic!("expected TConditional");
3461        };
3462        let (subject, if_true, if_false) = (&data.subject, &data.if_true, &data.if_false);
3463        assert!(matches!(subject.types[0], Atomic::TString));
3464        assert!(matches!(if_true.types[0], Atomic::TString));
3465        assert!(matches!(if_false.types[0], Atomic::TInt));
3466    }
3467
3468    #[test]
3469    fn resolve_conditional_is_null_non_null_arg() {
3470        let ty = Type::single(conditional(
3471            Some(Name::new("x")),
3472            Type::single(Atomic::TNull),
3473            Type::single(Atomic::TInt),
3474            Type::single(Atomic::TString),
3475        ));
3476        let result = ty.resolve_conditional_returns(|name| {
3477            if name == "x" {
3478                Some(Type::single(Atomic::TString)) // definitely not null
3479            } else {
3480                None
3481            }
3482        });
3483        assert!(result.types.len() == 1);
3484        assert!(matches!(result.types[0], Atomic::TString));
3485    }
3486
3487    #[test]
3488    fn resolve_conditional_is_null_null_arg() {
3489        let ty = Type::single(conditional(
3490            Some(Name::new("x")),
3491            Type::single(Atomic::TNull),
3492            Type::single(Atomic::TInt),
3493            Type::single(Atomic::TString),
3494        ));
3495        let result = ty.resolve_conditional_returns(|name| {
3496            if name == "x" {
3497                Some(Type::single(Atomic::TNull)) // definitely null
3498            } else {
3499                None
3500            }
3501        });
3502        assert!(result.types.len() == 1);
3503        assert!(matches!(result.types[0], Atomic::TInt));
3504    }
3505
3506    #[test]
3507    fn resolve_conditional_is_null_nullable_arg_widens_to_branch_union() {
3508        let mut nullable_str = Type::single(Atomic::TString);
3509        nullable_str.add_type(Atomic::TNull);
3510        let ty = Type::single(conditional(
3511            Some(Name::new("x")),
3512            Type::single(Atomic::TNull),
3513            Type::single(Atomic::TInt),
3514            Type::single(Atomic::TString),
3515        ));
3516        let result = ty.resolve_conditional_returns(|name| {
3517            if name == "x" {
3518                Some(nullable_str.clone())
3519            } else {
3520                None
3521            }
3522        });
3523        // uncertain discriminator → widen to if_true | if_false
3524        assert_eq!(result.types.len(), 2);
3525        assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
3526        assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
3527    }
3528
3529    #[test]
3530    fn resolve_conditional_nested_widens_inner_branch() {
3531        // ($x is null ? int : ($x is string ? string : float))
3532        // When $x is unknown, should widen to int|string|float (no TConditional remaining).
3533        let inner = Type::single(conditional(
3534            Some(Name::new("x")),
3535            Type::single(Atomic::TString),
3536            Type::single(Atomic::TString),
3537            Type::single(Atomic::TFloat),
3538        ));
3539        let ty = Type::single(conditional(
3540            Some(Name::new("x")),
3541            Type::single(Atomic::TNull),
3542            Type::single(Atomic::TInt),
3543            inner,
3544        ));
3545        // unknown arg → widen both outer branches, inner conditional must also be widened
3546        let result = ty.resolve_conditional_returns(|_| None);
3547        assert!(
3548            result
3549                .types
3550                .iter()
3551                .all(|t| !matches!(t, Atomic::TConditional { .. })),
3552            "no TConditional should survive: {:?}",
3553            result.types
3554        );
3555        assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
3556        assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
3557        assert!(result.types.iter().any(|t| matches!(t, Atomic::TFloat)));
3558    }
3559
3560    #[test]
3561    fn resolve_conditional_nested_resolves_inner_branch() {
3562        // ($x is null ? int : ($x is string ? string : float))
3563        // When $x is definitely not null but unknown string-or-not → resolves outer to inner,
3564        // then inner must also be resolved.
3565        let inner = Type::single(conditional(
3566            Some(Name::new("x")),
3567            Type::single(Atomic::TString),
3568            Type::single(Atomic::TString),
3569            Type::single(Atomic::TFloat),
3570        ));
3571        let ty = Type::single(conditional(
3572            Some(Name::new("x")),
3573            Type::single(Atomic::TNull),
3574            Type::single(Atomic::TInt),
3575            inner,
3576        ));
3577        // $x = string → outer: not null → if_false (inner); inner: is string → if_true = string
3578        let result = ty.resolve_conditional_returns(|name| {
3579            if name == "x" {
3580                Some(Type::single(Atomic::TString))
3581            } else {
3582                None
3583            }
3584        });
3585        assert!(
3586            result
3587                .types
3588                .iter()
3589                .all(|t| !matches!(t, Atomic::TConditional { .. })),
3590            "no TConditional should survive: {:?}",
3591            result.types
3592        );
3593        assert_eq!(result.types.len(), 1);
3594        assert!(matches!(result.types[0], Atomic::TString));
3595    }
3596
3597    #[test]
3598    fn resolve_conditional_true_subject_bool_arg_widens() {
3599        // A `bool` argument carries the value classes `{true, false}`:
3600        // `false` is not contained in the `true` class, and `true`
3601        // overlaps it, so neither branch is ruled out.
3602        let ty = Type::single(conditional(
3603            Some(Name::new("x")),
3604            Type::single(Atomic::TTrue),
3605            Type::single(Atomic::TInt),
3606            Type::single(Atomic::TString),
3607        ));
3608        let result = ty.resolve_conditional_returns(|name| {
3609            if name == "x" {
3610                Some(Type::single(Atomic::TBool))
3611            } else {
3612                None
3613            }
3614        });
3615        assert_eq!(result.types.len(), 2);
3616        assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3617        assert!(result.contains(|t| matches!(t, Atomic::TString)));
3618    }
3619
3620    #[test]
3621    fn resolve_conditional_true_subject_mixed_arg_widens() {
3622        // `mixed` maps to the `Top` value class, which overlaps every
3623        // other class, so it can never rule a branch out.
3624        let ty = Type::single(conditional(
3625            Some(Name::new("x")),
3626            Type::single(Atomic::TTrue),
3627            Type::single(Atomic::TInt),
3628            Type::single(Atomic::TString),
3629        ));
3630        let result = ty.resolve_conditional_returns(|name| {
3631            if name == "x" {
3632                Some(Type::mixed())
3633            } else {
3634                None
3635            }
3636        });
3637        assert_eq!(result.types.len(), 2);
3638        assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3639        assert!(result.contains(|t| matches!(t, Atomic::TString)));
3640    }
3641
3642    #[test]
3643    fn resolve_conditional_true_subject_literal_args() {
3644        // Literals decide by value class: `false` is contained in
3645        // `{false}` and disjoint from `{true}`, and vice versa.
3646        let ty = Type::single(conditional(
3647            Some(Name::new("x")),
3648            Type::single(Atomic::TTrue),
3649            Type::single(Atomic::TInt),
3650            Type::single(Atomic::TString),
3651        ));
3652        let false_arg = ty.clone().resolve_conditional_returns(|name| {
3653            if name == "x" {
3654                Some(Type::single(Atomic::TFalse))
3655            } else {
3656                None
3657            }
3658        });
3659        assert_eq!(false_arg.types.len(), 1);
3660        assert!(matches!(false_arg.types[0], Atomic::TString));
3661
3662        let true_arg = ty.resolve_conditional_returns(|name| {
3663            if name == "x" {
3664                Some(Type::single(Atomic::TTrue))
3665            } else {
3666                None
3667            }
3668        });
3669        assert_eq!(true_arg.types.len(), 1);
3670        assert!(matches!(true_arg.types[0], Atomic::TInt));
3671    }
3672
3673    #[test]
3674    fn resolve_conditional_bool_subject_scalar_arg_widens() {
3675        // `scalar` carries all five scalar classes: `true`/`false`
3676        // overlap the `bool` subject, but `int`/`float`/`string` are
3677        // not contained in `{true, false}`, so neither branch commits.
3678        let ty = Type::single(conditional(
3679            Some(Name::new("x")),
3680            Type::single(Atomic::TBool),
3681            Type::single(Atomic::TInt),
3682            Type::single(Atomic::TString),
3683        ));
3684        let result = ty.resolve_conditional_returns(|name| {
3685            if name == "x" {
3686                Some(Type::single(Atomic::TScalar))
3687            } else {
3688                None
3689            }
3690        });
3691        assert_eq!(result.types.len(), 2);
3692        assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3693        assert!(result.contains(|t| matches!(t, Atomic::TString)));
3694    }
3695
3696    #[test]
3697    fn resolve_conditional_string_subject_bool_arg_false_branch() {
3698        // Disjoint value classes still commit to the false branch: a
3699        // `bool` argument carries `{true, false}`, none of which is a
3700        // string, and strings are not bools.
3701        let ty = Type::single(conditional(
3702            Some(Name::new("x")),
3703            Type::single(Atomic::TString),
3704            Type::single(Atomic::TInt),
3705            Type::single(Atomic::TBool),
3706        ));
3707        let result = ty.resolve_conditional_returns(|name| {
3708            if name == "x" {
3709                Some(Type::single(Atomic::TBool))
3710            } else {
3711                None
3712            }
3713        });
3714        assert_eq!(result.types.len(), 1);
3715        assert!(matches!(result.types[0], Atomic::TBool));
3716    }
3717
3718    #[test]
3719    fn resolve_conditional_list_subject_bare_array_arg_widens() {
3720        // A bare `array` is the supertype of `list`, so it may or may
3721        // not be a list: both branches stay live.
3722        let ty = Type::single(conditional(
3723            Some(Name::new("x")),
3724            Type::single(Atomic::TList {
3725                value: Box::new(Type::mixed()),
3726            }),
3727            Type::single(Atomic::TInt),
3728            Type::single(Atomic::TString),
3729        ));
3730        let result = ty.resolve_conditional_returns(|name| {
3731            if name == "x" {
3732                Some(Type::single(Atomic::TArray {
3733                    key: Box::new(Type::mixed()),
3734                    value: Box::new(Type::mixed()),
3735                }))
3736            } else {
3737                None
3738            }
3739        });
3740        assert_eq!(result.types.len(), 2);
3741        assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3742        assert!(result.contains(|t| matches!(t, Atomic::TString)));
3743    }
3744
3745    #[test]
3746    fn resolve_conditional_float_subject_int_literal_false_branch() {
3747        // A `float` subject is the `Float` class; an int literal is
3748        // `LitInt`, which is not a float, and floats are not ints.
3749        let ty = resolve_conditional_branch(
3750            &Type::single(Atomic::TFloat),
3751            &Type::single(Atomic::TLiteralInt(42)),
3752            &Type::single(Atomic::TInt),
3753            &Type::single(Atomic::TString),
3754        );
3755        assert!(matches!(
3756            ty.as_ref(),
3757            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3758        ));
3759    }
3760
3761    #[test]
3762    fn resolve_conditional_int_subject_float_literal_false_branch() {
3763        let ty = resolve_conditional_branch(
3764            &Type::single(Atomic::TInt),
3765            &Type::single(Atomic::TLiteralFloat(1, 0)),
3766            &Type::single(Atomic::TInt),
3767            &Type::single(Atomic::TString),
3768        );
3769        assert!(matches!(
3770            ty.as_ref(),
3771            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3772        ));
3773    }
3774
3775    #[test]
3776    fn resolve_conditional_float_subject_float_literal_then_branch() {
3777        let ty = resolve_conditional_branch(
3778            &Type::single(Atomic::TFloat),
3779            &Type::single(Atomic::TLiteralFloat(1, 5)),
3780            &Type::single(Atomic::TInt),
3781            &Type::single(Atomic::TString),
3782        );
3783        assert!(matches!(
3784            ty.as_ref(),
3785            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3786        ));
3787    }
3788
3789    #[test]
3790    fn resolve_conditional_int_subject_int_literal_then_branch() {
3791        let ty = resolve_conditional_branch(
3792            &Type::single(Atomic::TInt),
3793            &Type::single(Atomic::TLiteralInt(7)),
3794            &Type::single(Atomic::TInt),
3795            &Type::single(Atomic::TString),
3796        );
3797        assert!(matches!(
3798            ty.as_ref(),
3799            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3800        ));
3801    }
3802
3803    #[test]
3804    fn resolve_conditional_int_subject_float_arg_false_branch() {
3805        // A bare `float` argument is never an `int`: disjoint value
3806        // classes commit to the false branch.
3807        let ty = resolve_conditional_branch(
3808            &Type::single(Atomic::TInt),
3809            &Type::single(Atomic::TFloat),
3810            &Type::single(Atomic::TInt),
3811            &Type::single(Atomic::TString),
3812        );
3813        assert!(matches!(
3814            ty.as_ref(),
3815            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3816        ));
3817    }
3818
3819    #[test]
3820    fn resolve_conditional_array_subject_string_arg_false_branch() {
3821        let ty = resolve_conditional_branch(
3822            &Type::single(Atomic::TArray {
3823                key: Box::new(Type::mixed()),
3824                value: Box::new(Type::mixed()),
3825            }),
3826            &Type::single(Atomic::TString),
3827            &Type::single(Atomic::TInt),
3828            &Type::single(Atomic::TString),
3829        );
3830        assert!(matches!(
3831            ty.as_ref(),
3832            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3833        ));
3834    }
3835
3836    #[test]
3837    fn resolve_conditional_array_subject_bool_arg_false_branch() {
3838        let ty = resolve_conditional_branch(
3839            &Type::single(Atomic::TArray {
3840                key: Box::new(Type::mixed()),
3841                value: Box::new(Type::mixed()),
3842            }),
3843            &Type::single(Atomic::TBool),
3844            &Type::single(Atomic::TInt),
3845            &Type::single(Atomic::TString),
3846        );
3847        assert!(matches!(
3848            ty.as_ref(),
3849            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3850        ));
3851    }
3852
3853    #[test]
3854    fn resolve_conditional_array_subject_mixed_arg_widens() {
3855        // A `mixed` argument is `Top`: it overlaps `array`, so the then
3856        // branch is never ruled out, and it is not contained in `array`,
3857        // so the false branch is never ruled out either.
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::mixed(),
3864            &Type::single(Atomic::TInt),
3865            &Type::single(Atomic::TString),
3866        );
3867        assert!(ty.is_none());
3868    }
3869
3870    #[test]
3871    fn resolve_conditional_array_subject_list_arg_then_branch() {
3872        // A `list` argument is an `array` (`List` is contained in
3873        // `Array`), so every argument class is in the subject's class.
3874        let ty = resolve_conditional_branch(
3875            &Type::single(Atomic::TArray {
3876                key: Box::new(Type::mixed()),
3877                value: Box::new(Type::mixed()),
3878            }),
3879            &Type::single(Atomic::TList {
3880                value: Box::new(Type::mixed()),
3881            }),
3882            &Type::single(Atomic::TInt),
3883            &Type::single(Atomic::TString),
3884        );
3885        assert!(matches!(
3886            ty.as_ref(),
3887            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3888        ));
3889    }
3890
3891    #[test]
3892    fn resolve_conditional_list_subject_keyed_list_arg_then_branch() {
3893        // A keyed array with `is_list` is a list at runtime.
3894        let ty = resolve_conditional_branch(
3895            &Type::single(Atomic::TList {
3896                value: Box::new(Type::mixed()),
3897            }),
3898            &Type::single(Atomic::TKeyedArray {
3899                properties: Arc::default(),
3900                is_open: false,
3901                is_list: true,
3902            }),
3903            &Type::single(Atomic::TInt),
3904            &Type::single(Atomic::TString),
3905        );
3906        assert!(matches!(
3907            ty.as_ref(),
3908            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3909        ));
3910    }
3911
3912    #[test]
3913    fn resolve_conditional_list_subject_list_string_union_widens() {
3914        // A `list|string` argument carries `{List, String}`: `List`
3915        // overlaps the `list` subject, `String` does not, so neither
3916        // branch is ruled out.
3917        let ty = resolve_conditional_branch(
3918            &Type::single(Atomic::TList {
3919                value: Box::new(Type::mixed()),
3920            }),
3921            &Type::from_vec(vec![
3922                Atomic::TList {
3923                    value: Box::new(Type::mixed()),
3924                },
3925                Atomic::TString,
3926            ]),
3927            &Type::single(Atomic::TInt),
3928            &Type::single(Atomic::TString),
3929        );
3930        assert!(ty.is_none());
3931    }
3932
3933    #[test]
3934    fn resolve_conditional_numeric_subject_widens() {
3935        // `numeric` is a refined subject (it admits numeric strings such
3936        // as `"123"`), so the value-class lattice cannot reduce it: the
3937        // branch stays undecidable even for a literal string argument.
3938        let ty = resolve_conditional_branch(
3939            &Type::single(Atomic::TNumeric),
3940            &Type::single(Atomic::TLiteralString("123".into())),
3941            &Type::single(Atomic::TInt),
3942            &Type::single(Atomic::TString),
3943        );
3944        assert!(ty.is_none());
3945    }
3946
3947    #[test]
3948    fn resolve_conditional_non_empty_string_subject_widens() {
3949        // A `non-empty-string` subject is refined (`""` is a string but
3950        // not non-empty), so even a bare string argument is undecidable.
3951        let ty = resolve_conditional_branch(
3952            &Type::single(Atomic::TNonEmptyString),
3953            &Type::single(Atomic::TString),
3954            &Type::single(Atomic::TInt),
3955            &Type::single(Atomic::TString),
3956        );
3957        assert!(ty.is_none());
3958    }
3959
3960    #[test]
3961    fn resolve_conditional_template_arg_widens() {
3962        // A template parameter has no value classes at all (opaque), so
3963        // it is undecidable against any subject.
3964        let ty = resolve_conditional_branch(
3965            &Type::single(Atomic::TString),
3966            &t_param("T"),
3967            &Type::single(Atomic::TInt),
3968            &Type::single(Atomic::TString),
3969        );
3970        assert!(ty.is_none());
3971    }
3972
3973    #[test]
3974    fn resolve_conditional_mixed_subject_bool_arg_then_branch() {
3975        // `mixed` is a decidable subject: every value class is contained
3976        // in `Top`, so a bool argument is always `mixed`.
3977        let ty = resolve_conditional_branch(
3978            &Type::single(Atomic::TMixed),
3979            &Type::single(Atomic::TBool),
3980            &Type::single(Atomic::TInt),
3981            &Type::single(Atomic::TString),
3982        );
3983        assert!(matches!(
3984            ty.as_ref(),
3985            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3986        ));
3987    }
3988
3989    #[test]
3990    fn resolve_conditional_scalar_subject_null_arg_false_branch() {
3991        // `null` is not a scalar value class: the argument is disjoint
3992        // from the subject, so the false branch is taken.
3993        let ty = resolve_conditional_branch(
3994            &Type::single(Atomic::TScalar),
3995            &Type::single(Atomic::TNull),
3996            &Type::single(Atomic::TInt),
3997            &Type::single(Atomic::TString),
3998        );
3999        assert!(matches!(
4000            ty.as_ref(),
4001            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4002        ));
4003    }
4004
4005    #[test]
4006    fn resolve_conditional_object_subject_named_arg_then_branch() {
4007        // A named class instance is an object at runtime.
4008        let ty = resolve_conditional_branch(
4009            &Type::single(Atomic::TObject),
4010            &Type::single(Atomic::TNamedObject {
4011                fqcn: Name::new("Foo"),
4012                type_params: empty_type_params(),
4013            }),
4014            &Type::single(Atomic::TInt),
4015            &Type::single(Atomic::TString),
4016        );
4017        assert!(matches!(
4018            ty.as_ref(),
4019            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4020        ));
4021    }
4022
4023    #[test]
4024    fn resolve_conditional_named_subject_other_class_widens() {
4025        // A named-object subject is refined (one specific class), so an
4026        // instance of another class is undecidable even though both are
4027        // objects.
4028        let ty = resolve_conditional_branch(
4029            &Type::single(Atomic::TNamedObject {
4030                fqcn: Name::new("Foo"),
4031                type_params: empty_type_params(),
4032            }),
4033            &Type::single(Atomic::TNamedObject {
4034                fqcn: Name::new("Bar"),
4035                type_params: empty_type_params(),
4036            }),
4037            &Type::single(Atomic::TInt),
4038            &Type::single(Atomic::TString),
4039        );
4040        assert!(ty.is_none());
4041    }
4042
4043    #[test]
4044    fn resolve_conditional_enum_case_subject_widens() {
4045        // An enum-case subject is refined: the value-class lattice cannot
4046        // reduce a specific enum case, so an int argument is undecidable.
4047        let ty = resolve_conditional_branch(
4048            &Type::single(Atomic::TLiteralEnumCase {
4049                enum_fqcn: Name::new("RoundingMode"),
4050                case_name: Name::new("Unnecessary"),
4051            }),
4052            &Type::single(Atomic::TInt),
4053            &Type::single(Atomic::TInt),
4054            &Type::single(Atomic::TString),
4055        );
4056        assert!(ty.is_none());
4057    }
4058
4059    #[test]
4060    fn resolve_conditional_null_subject_bool_arg_false_branch() {
4061        // `null` and bool are disjoint value classes.
4062        let ty = resolve_conditional_branch(
4063            &Type::single(Atomic::TNull),
4064            &Type::single(Atomic::TBool),
4065            &Type::single(Atomic::TInt),
4066            &Type::single(Atomic::TString),
4067        );
4068        assert!(matches!(
4069            ty.as_ref(),
4070            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4071        ));
4072    }
4073
4074    #[test]
4075    fn resolve_conditional_bool_subject_true_arg_then_branch() {
4076        // `true` is contained in `bool`'s `{true, false}` classes, so
4077        // the then branch is taken.
4078        let ty = resolve_conditional_branch(
4079            &Type::single(Atomic::TBool),
4080            &Type::single(Atomic::TTrue),
4081            &Type::single(Atomic::TInt),
4082            &Type::single(Atomic::TString),
4083        );
4084        assert!(matches!(
4085            ty.as_ref(),
4086            Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4087        ));
4088    }
4089
4090    #[test]
4091    fn substitute_intersection_parts() {
4092        let ty = Type::single(Atomic::TIntersection {
4093            parts: vec_to_type_params(vec![
4094                Type::single(Atomic::TNamedObject {
4095                    fqcn: Name::new("Countable"),
4096                    type_params: empty_type_params(),
4097                }),
4098                t_param("T"),
4099            ]),
4100        });
4101        let result = ty.substitute_templates(&bindings_t_string());
4102        let Atomic::TIntersection { parts } = &result.types[0] else {
4103            panic!("expected TIntersection");
4104        };
4105        assert_eq!(parts.len(), 2);
4106        assert!(matches!(parts[0].types[0], Atomic::TNamedObject { .. }));
4107        assert!(matches!(parts[1].types[0], Atomic::TString));
4108    }
4109
4110    fn shape(props: &[(&str, Atomic, bool)], is_open: bool) -> Atomic {
4111        Atomic::TKeyedArray {
4112            properties: Arc::new(
4113                props
4114                    .iter()
4115                    .map(|(k, ty, optional)| {
4116                        (
4117                            ArrayKey::String(Arc::from(*k)),
4118                            KeyedProperty {
4119                                ty: Type::single(ty.clone()),
4120                                optional: *optional,
4121                            },
4122                        )
4123                    })
4124                    .collect(),
4125            ),
4126            is_open,
4127            is_list: false,
4128        }
4129    }
4130
4131    /// A closed shape `{a: int}` plus key `k{i}` for each bit set in `bits`.
4132    fn shape_with_bits(bits: u32, is_open: bool) -> Atomic {
4133        let names: Vec<String> = (0..5).map(|i| format!("k{i}")).collect();
4134        let mut props = vec![("a", Atomic::TInt, false)];
4135        props.extend(
4136            (0..5)
4137                .filter(|i| bits & (1 << i) != 0)
4138                .map(|i| (names[i].as_str(), Atomic::TString, false)),
4139        );
4140        shape(&props, is_open)
4141    }
4142
4143    fn keyed_count(ty: &Type) -> usize {
4144        ty.types
4145            .iter()
4146            .filter(|t| matches!(t, Atomic::TKeyedArray { .. }))
4147            .count()
4148    }
4149
4150    #[test]
4151    fn add_type_keeps_few_shapes_apart() {
4152        let mut ty = Type::empty();
4153        for bits in 0..MAX_KEYED_SHAPES as u32 {
4154            ty.add_type(shape_with_bits(bits, false));
4155        }
4156        assert_eq!(keyed_count(&ty), MAX_KEYED_SHAPES);
4157    }
4158
4159    #[test]
4160    fn add_type_folds_shapes_past_the_limit() {
4161        let mut ty = Type::empty();
4162        for bits in 0..32 {
4163            ty.add_type(shape_with_bits(bits, false));
4164        }
4165        assert!(keyed_count(&ty) <= MAX_KEYED_SHAPES);
4166        // Every key stays reachable; `a` stays required everywhere.
4167        for t in &ty.types {
4168            let Atomic::TKeyedArray { properties, .. } = t else {
4169                continue;
4170            };
4171            assert!(!properties[&ArrayKey::String(Arc::from("a"))].optional);
4172        }
4173        for i in 0..5 {
4174            let key = ArrayKey::String(Arc::from(format!("k{i}").as_str()));
4175            assert!(ty.types.iter().any(|t| matches!(
4176                t,
4177                Atomic::TKeyedArray { properties, .. } if properties.contains_key(&key)
4178            )));
4179        }
4180    }
4181
4182    #[test]
4183    fn add_type_folds_generic_arrays_past_the_limit() {
4184        let mut ty = Type::empty();
4185        for i in 0..32 {
4186            ty.add_type(Atomic::TArray {
4187                key: Box::new(Type::single(Atomic::TInt)),
4188                value: Box::new(Type::single(Atomic::TLiteralInt(i))),
4189            });
4190        }
4191        assert!(ty.types.len() <= MAX_GENERIC_ARRAYS);
4192        for i in 0..32 {
4193            assert!(ty.types.iter().any(|t| matches!(
4194                t,
4195                Atomic::TArray { value, .. } if value.types.contains(&Atomic::TLiteralInt(i))
4196            )));
4197        }
4198    }
4199
4200    #[test]
4201    fn add_type_widens_string_literals_past_the_limit() {
4202        let mut ty = Type::empty();
4203        for i in 0..MAX_LITERAL_STRINGS {
4204            ty.add_type(Atomic::TLiteralString(format!("s{i}").into()));
4205        }
4206        assert_eq!(ty.types.len(), MAX_LITERAL_STRINGS);
4207        ty.add_type(Atomic::TLiteralString("one more".into()));
4208        assert_eq!(ty.types.as_slice(), &[Atomic::TString]);
4209        ty.add_type(Atomic::TLiteralString("after".into()));
4210        assert_eq!(ty.types.as_slice(), &[Atomic::TString]);
4211    }
4212
4213    #[test]
4214    fn add_type_drops_generic_arrays_another_covers() {
4215        let list = |value: Atomic| Atomic::TList {
4216            value: Box::new(Type::single(value)),
4217        };
4218        let mut ty = Type::single(list(Atomic::TLiteralInt(0)));
4219        ty.add_type(list(Atomic::TInt));
4220        assert_eq!(ty.types.as_slice(), &[list(Atomic::TInt)]);
4221        ty.add_type(list(Atomic::TLiteralInt(1)));
4222        assert_eq!(ty.types.as_slice(), &[list(Atomic::TInt)]);
4223
4224        let mut opaque = Type::single(list(Atomic::TMixed));
4225        opaque.add_type(list(Atomic::TInt));
4226        assert_eq!(opaque.types.len(), 2);
4227
4228        let mut kinds = Type::single(Atomic::TNonEmptyList {
4229            value: Box::new(Type::single(Atomic::TInt)),
4230        });
4231        kinds.add_type(list(Atomic::TInt));
4232        assert_eq!(kinds.types.len(), 2);
4233    }
4234
4235    #[test]
4236    fn combine_keeps_emptiness_and_open_shape_soundness() {
4237        // `array{}` and `array{a: int}` differ in emptiness.
4238        assert!(combine_keyed_arrays(
4239            &shape(&[], false),
4240            &shape(&[("a", Atomic::TInt, false)], false)
4241        )
4242        .is_none());
4243        // Open and closed shapes don't mix.
4244        assert!(combine_keyed_arrays(
4245            &shape(&[("a", Atomic::TInt, false)], true),
4246            &shape(&[("a", Atomic::TInt, false)], false)
4247        )
4248        .is_none());
4249        // An open shape missing `k` already admits any `k`: drop it.
4250        assert_eq!(
4251            combine_keyed_arrays(
4252                &shape(&[("a", Atomic::TInt, false)], true),
4253                &shape(
4254                    &[("a", Atomic::TInt, false), ("k", Atomic::TString, false)],
4255                    true
4256                )
4257            ),
4258            Some(shape(&[("a", Atomic::TInt, false)], true))
4259        );
4260    }
4261
4262    #[test]
4263    fn substitute_no_template_params_identity() {
4264        let ty = Type::single(Atomic::TInt);
4265        let result = ty.substitute_templates(&bindings_t_string());
4266        assert!(matches!(result.types[0], Atomic::TInt));
4267    }
4268}