Skip to main content

mir_types/
union.rs

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