Skip to main content

mir_types/
union.rs

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