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