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::Atomic;
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
75impl Type {
76    // --- Constructors -------------------------------------------------------
77
78    pub fn empty() -> Self {
79        Self {
80            types: SmallVec::new(),
81            possibly_undefined: false,
82            from_docblock: false,
83            falsy_stripped: false,
84            possibly_absent_offset: false,
85        }
86    }
87
88    pub fn single(atomic: Atomic) -> Self {
89        let mut types = SmallVec::new();
90        types.push(atomic);
91        Self {
92            types,
93            possibly_undefined: false,
94            from_docblock: false,
95            falsy_stripped: false,
96            possibly_absent_offset: false,
97        }
98    }
99
100    pub fn mixed() -> Self {
101        Self::single(Atomic::TMixed)
102    }
103
104    pub fn void() -> Self {
105        Self::single(Atomic::TVoid)
106    }
107
108    pub fn never() -> Self {
109        Self::single(Atomic::TNever)
110    }
111
112    pub fn null() -> Self {
113        Self::single(Atomic::TNull)
114    }
115
116    pub fn bool() -> Self {
117        Self::single(Atomic::TBool)
118    }
119
120    pub fn int() -> Self {
121        Self::single(Atomic::TInt)
122    }
123
124    pub fn float() -> Self {
125        Self::single(Atomic::TFloat)
126    }
127
128    pub fn string() -> Self {
129        Self::single(Atomic::TString)
130    }
131
132    /// `int|string` — the canonical PHP array-key type, used as the default
133    /// key type when a docblock/inferred array has no more specific key.
134    pub fn array_key() -> Self {
135        let mut u = Self::single(Atomic::TInt);
136        u.add_type(Atomic::TString);
137        u
138    }
139
140    /// `T|null`
141    pub fn nullable(atomic: Atomic) -> Self {
142        // `mixed|null` = `mixed` — null is already included in mixed.
143        if matches!(atomic, Atomic::TMixed) {
144            return Self::mixed();
145        }
146        let mut types = SmallVec::new();
147        types.push(atomic);
148        types.push(Atomic::TNull);
149        Self {
150            types,
151            possibly_undefined: false,
152            from_docblock: false,
153            falsy_stripped: false,
154            possibly_absent_offset: false,
155        }
156    }
157
158    /// Build a union from multiple atomics, de-duplicating on the fly.
159    pub fn from_vec(atomics: Vec<Atomic>) -> Self {
160        let mut u = Self::empty();
161        for a in atomics {
162            u.add_type(a);
163        }
164        u
165    }
166
167    // --- Introspection -------------------------------------------------------
168
169    pub fn is_empty(&self) -> bool {
170        self.types.is_empty()
171    }
172
173    pub fn is_single(&self) -> bool {
174        self.types.len() == 1
175    }
176
177    pub fn is_nullable(&self) -> bool {
178        self.types.iter().any(|t| matches!(t, Atomic::TNull))
179    }
180
181    /// True when this is exactly `int|string` — the array-key domain, which
182    /// is already the maximal set of legal PHP array keys and so should be
183    /// treated like a "default"/unconstrained key, same as `mixed` would be
184    /// for a non-key type parameter.
185    pub fn is_array_key(&self) -> bool {
186        self.types.len() == 2
187            && self.types.iter().any(|t| matches!(t, Atomic::TInt))
188            && self.types.iter().any(|t| matches!(t, Atomic::TString))
189    }
190
191    pub fn is_mixed(&self) -> bool {
192        self.types.iter().any(|t| match t {
193            Atomic::TMixed => true,
194            Atomic::TTemplateParam { as_type, .. } => as_type.is_mixed(),
195            _ => false,
196        })
197    }
198
199    /// True only when the type contains `TMixed` atoms and no `TTemplateParam` atoms.
200    /// Unlike [`is_mixed`], this does not treat an unconstrained template parameter as
201    /// "mixed" — a `T` placeholder is an intentionally parameterised type that will be
202    /// instantiated at the call site, so it must not trigger `MixedAssignment` warnings.
203    pub fn is_mixed_not_template(&self) -> bool {
204        self.is_mixed()
205            && !self
206                .types
207                .iter()
208                .any(|t| matches!(t, Atomic::TTemplateParam { .. }))
209    }
210
211    pub fn is_never(&self) -> bool {
212        self.types.iter().all(|t| matches!(t, Atomic::TNever)) && !self.types.is_empty()
213    }
214
215    /// Classify this type for `clone` validity. Recurses into template-param
216    /// bounds (like [`Type::is_mixed`]). Callers handle `mixed` separately.
217    pub fn clone_validity(&self) -> CloneValidity {
218        if self.types.is_empty() {
219            return CloneValidity::Unknown;
220        }
221        let mut has_non_object = false;
222        let mut has_other = false; // object or ambiguous (callable, mixed, conditional, …)
223        for t in &self.types {
224            match t {
225                Atomic::TTemplateParam { as_type, .. } => match as_type.clone_validity() {
226                    CloneValidity::Invalid => has_non_object = true,
227                    CloneValidity::PossiblyInvalid => {
228                        has_non_object = true;
229                        has_other = true;
230                    }
231                    CloneValidity::Cloneable | CloneValidity::Unknown => has_other = true,
232                },
233                other if other.is_definitely_non_object() => has_non_object = true,
234                _ => has_other = true,
235            }
236        }
237        match (has_non_object, has_other) {
238            (true, false) => CloneValidity::Invalid,
239            (true, true) => CloneValidity::PossiblyInvalid,
240            _ => CloneValidity::Cloneable,
241        }
242    }
243
244    pub fn is_void(&self) -> bool {
245        self.is_single() && matches!(self.types[0], Atomic::TVoid)
246    }
247
248    pub fn can_be_falsy(&self) -> bool {
249        self.types.iter().any(|t| t.can_be_falsy())
250    }
251
252    pub fn can_be_truthy(&self) -> bool {
253        self.types.iter().any(|t| t.can_be_truthy())
254    }
255
256    pub fn contains<F: Fn(&Atomic) -> bool>(&self, f: F) -> bool {
257        self.types.iter().any(f)
258    }
259
260    pub fn has_named_object(&self, fqcn: &str) -> bool {
261        self.types.iter().any(|t| match t {
262            Atomic::TNamedObject { fqcn: f, .. } => f.as_ref() == fqcn,
263            _ => false,
264        })
265    }
266
267    // --- Mutation ------------------------------------------------------------
268
269    /// Add an atomic to this union, skipping duplicates.
270    /// Subsumption rules: anything ⊆ TMixed; TLiteralInt ⊆ TInt; etc.
271    pub fn add_type(&mut self, atomic: Atomic) {
272        // If we already have TMixed, nothing to add.
273        if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
274            return;
275        }
276
277        // Adding TMixed subsumes everything.
278        if matches!(atomic, Atomic::TMixed) {
279            self.types.clear();
280            self.types.push(Atomic::TMixed);
281            return;
282        }
283
284        // Simplify trivial conditional types: (X is ? T : T) → T
285        // Recursively simplify branches first so nested trivial conditionals collapse.
286        let atomic = if let Atomic::TConditional { data } = &atomic {
287            let (if_true, if_false) = (&data.if_true, &data.if_false);
288            let mut simplified_true = Type::empty();
289            for t in &if_true.types {
290                simplified_true.add_type(t.clone());
291            }
292            let mut simplified_false = Type::empty();
293            for t in &if_false.types {
294                simplified_false.add_type(t.clone());
295            }
296            if simplified_true == simplified_false {
297                for t in simplified_true.types {
298                    self.add_type(t);
299                }
300                return;
301            }
302            atomic
303        } else {
304            atomic
305        };
306
307        // Avoid exact duplicates.
308        if self.types.contains(&atomic) {
309            return;
310        }
311
312        // TLiteralInt(n) is subsumed by TInt.
313        if let Atomic::TLiteralInt(_) = &atomic {
314            if self.types.iter().any(|t| matches!(t, Atomic::TInt)) {
315                return;
316            }
317        }
318        // TLiteralString(s) is subsumed by TString.
319        if let Atomic::TLiteralString(_) = &atomic {
320            if self.types.iter().any(|t| matches!(t, Atomic::TString)) {
321                return;
322            }
323        }
324        // TTrue / TFalse are subsumed by TBool.
325        if matches!(atomic, Atomic::TTrue | Atomic::TFalse)
326            && self.types.iter().any(|t| matches!(t, Atomic::TBool))
327        {
328            return;
329        }
330        // TTrue and TFalse together are exactly TBool — merge rather than
331        // keeping both literals once both are present.
332        if matches!(atomic, Atomic::TTrue) && self.types.iter().any(|t| matches!(t, Atomic::TFalse))
333        {
334            self.types.retain(|t| !matches!(t, Atomic::TFalse));
335            self.types.push(Atomic::TBool);
336            return;
337        }
338        if matches!(atomic, Atomic::TFalse) && self.types.iter().any(|t| matches!(t, Atomic::TTrue))
339        {
340            self.types.retain(|t| !matches!(t, Atomic::TTrue));
341            self.types.push(Atomic::TBool);
342            return;
343        }
344        // Adding TInt widens away all TLiteralInt variants.
345        if matches!(atomic, Atomic::TInt) {
346            self.types.retain(|t| !matches!(t, Atomic::TLiteralInt(_)));
347        }
348        // Adding TString widens away all TLiteralString variants.
349        if matches!(atomic, Atomic::TString) {
350            self.types
351                .retain(|t| !matches!(t, Atomic::TLiteralString(_)));
352        }
353        // Adding TBool widens away TTrue/TFalse.
354        if matches!(atomic, Atomic::TBool) {
355            self.types
356                .retain(|t| !matches!(t, Atomic::TTrue | Atomic::TFalse));
357        }
358
359        // TNever is the bottom type: T | never = T.
360        if matches!(atomic, Atomic::TNever) {
361            if !self.types.is_empty() {
362                return;
363            }
364        } else {
365            self.types.retain(|t| !matches!(t, Atomic::TNever));
366        }
367
368        // Closed empty keyed array (array{}) is a subtype of any generic array or
369        // list. Remove it if we already have a generic array<K,V> or list<V>. An
370        // OPEN empty shape (array{...}) carries real information — it may hold
371        // unknown, possibly non-list, extra keys at runtime — so it's not
372        // subsumed and must not be dropped.
373        if let Atomic::TKeyedArray {
374            properties,
375            is_open,
376            ..
377        } = &atomic
378        {
379            if properties.is_empty() && !is_open {
380                for existing in &self.types {
381                    match existing {
382                        Atomic::TArray { .. }
383                        | Atomic::TNonEmptyArray { .. }
384                        | Atomic::TList { .. }
385                        | Atomic::TNonEmptyList { .. } => {
386                            return; // Don't add empty array, it's subsumed
387                        }
388                        _ => {}
389                    }
390                }
391            }
392        }
393
394        // When adding a generic array or list, remove any CLOSED empty keyed
395        // arrays since they're subtypes (same reasoning as above, mirrored).
396        let is_generic_array_or_list = matches!(
397            &atomic,
398            Atomic::TArray { .. }
399                | Atomic::TNonEmptyArray { .. }
400                | Atomic::TList { .. }
401                | Atomic::TNonEmptyList { .. }
402        );
403        if is_generic_array_or_list {
404            self.types.retain(|t| {
405                if let Atomic::TKeyedArray {
406                    properties,
407                    is_open,
408                    ..
409                } = t
410                {
411                    !properties.is_empty() || *is_open
412                } else {
413                    true
414                }
415            });
416        }
417
418        self.types.push(atomic);
419    }
420
421    // --- Narrowing -----------------------------------------------------------
422
423    /// Remove `null` from the union (e.g. after a null check).
424    pub fn remove_null(&self) -> Type {
425        self.filter(|t| !matches!(t, Atomic::TNull))
426    }
427
428    /// Remove `false` from the union.
429    /// `TFalse` is dropped; `TBool` becomes `TTrue` since `bool - false = true`.
430    pub fn remove_false(&self) -> Type {
431        let mut result = self.filter(|t| !matches!(t, Atomic::TFalse | Atomic::TBool));
432        if self.types.iter().any(|t| matches!(t, Atomic::TBool)) {
433            result.add_type(Atomic::TTrue);
434        }
435        result
436    }
437
438    /// Remove `true` from the union.
439    /// `TTrue` is dropped; `TBool` becomes `TFalse` since `bool - true = false`.
440    pub fn remove_true(&self) -> Type {
441        let mut result = self.filter(|t| !matches!(t, Atomic::TTrue | Atomic::TBool));
442        if self.types.iter().any(|t| matches!(t, Atomic::TBool)) {
443            result.add_type(Atomic::TFalse);
444        }
445        result
446    }
447
448    /// Remove both `null` and `false` from the union (core type without nullable/falsy variants).
449    pub fn core_type(&self) -> Type {
450        self.remove_null().remove_false()
451    }
452
453    /// Keep only truthy atomics (e.g. after `if ($x)`).
454    pub fn narrow_to_truthy(&self) -> Type {
455        if self.is_mixed_not_template() {
456            return Type::mixed();
457        }
458        let mut result = Type::empty();
459        result.from_docblock = self.from_docblock;
460        for t in &self.types {
461            match t {
462                // An unconstrained/bounded template could resolve to anything at
463                // runtime, truthy or falsy — preserve it rather than dropping or
464                // widening it, the same way narrow_to_string/_int/etc. already do.
465                Atomic::TTemplateParam { .. } => result.add_type(t.clone()),
466                // Always-falsy — exclude entirely.
467                Atomic::TLiteralInt(0)
468                | Atomic::TLiteralFloat(0, 0)
469                | Atomic::TNull
470                | Atomic::TFalse => {}
471                Atomic::TLiteralString(s) if s.as_ref() == "" || s.as_ref() == "0" => {}
472                // bool contains both true (truthy) and false (falsy); truthy branch is true.
473                Atomic::TBool => result.add_type(Atomic::TTrue),
474                // array/list: empty ↔ falsy; truthy branch is non-empty-array/list.
475                Atomic::TArray { key, value } => result.add_type(Atomic::TNonEmptyArray {
476                    key: key.clone(),
477                    value: value.clone(),
478                }),
479                Atomic::TList { value } => result.add_type(Atomic::TNonEmptyList {
480                    value: value.clone(),
481                }),
482                // string: only "" and "0" are falsy; truthy branch is non-empty-string.
483                // non-empty-string still includes "0" (which is falsy) but that is the
484                // standard approximation used by Psalm and other analyzers.
485                Atomic::TString => result.add_type(Atomic::TNonEmptyString),
486                // numeric-string: "0" is the only falsy value; non-zero numerics are truthy.
487                // No named "non-zero numeric-string" type exists; keep as-is conservatively.
488                // int<0, max> only has 0 as its falsy value; truthy branch is int<1, max>.
489                // (int<0, 0> is handled by the can_be_truthy() false guard below.)
490                Atomic::TNonNegativeInt => result.add_type(Atomic::TPositiveInt),
491                Atomic::TIntRange { min: Some(0), max } if max.is_none_or(|m| m >= 1) => {
492                    let atom = if max.is_none() {
493                        Atomic::TPositiveInt
494                    } else {
495                        Atomic::TIntRange {
496                            min: Some(1),
497                            max: *max,
498                        }
499                    };
500                    result.add_type(atom);
501                }
502                // int<min, 0>: 0 is the only falsy value; truthy branch excludes it → int<min, -1>.
503                Atomic::TIntRange { min, max: Some(0) } => {
504                    let atom = match min {
505                        None => Atomic::TNegativeInt,
506                        Some(n) if *n <= -1 => Atomic::TIntRange {
507                            min: *min,
508                            max: Some(-1),
509                        },
510                        _ => continue, // min >= 0 with max == 0 → range is {0} — can_be_truthy() handles this
511                    };
512                    result.add_type(atom);
513                }
514                // Anything else that can never be truthy — drop.
515                t if !t.can_be_truthy() => {}
516                _ => result.add_type(t.clone()),
517            }
518        }
519        result
520    }
521
522    /// Keep only falsy atomics (e.g. after `if (!$x)`).
523    pub fn narrow_to_falsy(&self) -> Type {
524        if self.is_mixed_not_template() {
525            return Type::from_vec(vec![
526                Atomic::TNull,
527                Atomic::TFalse,
528                Atomic::TLiteralInt(0),
529                Atomic::TLiteralString("".into()),
530            ]);
531        }
532        let mut result = Type::empty();
533        result.from_docblock = self.from_docblock;
534        for t in &self.types {
535            match t {
536                // An unconstrained/bounded template could resolve to anything at
537                // runtime, truthy or falsy — preserve it rather than dropping it
538                // (its own `can_be_falsy()` conservatively defaults to `false`,
539                // which would otherwise wrongly exclude it here).
540                Atomic::TTemplateParam { .. } => result.add_type(t.clone()),
541                // bool: only false is falsy; falsy branch is false.
542                Atomic::TBool => result.add_type(Atomic::TFalse),
543                // int: only 0 is falsy.
544                Atomic::TInt => result.add_type(Atomic::TLiteralInt(0)),
545                // float: only 0.0 is falsy.
546                Atomic::TFloat => result.add_type(Atomic::TLiteralFloat(0, 0)),
547                // string: only "" and "0" are falsy.
548                Atomic::TString => {
549                    result.add_type(Atomic::TLiteralString("".into()));
550                    result.add_type(Atomic::TLiteralString("0".into()));
551                }
552                // numeric-string: only "0" is a falsy numeric string.
553                Atomic::TNumericString => result.add_type(Atomic::TLiteralString("0".into())),
554                // non-negative-int: only 0 is falsy.
555                Atomic::TNonNegativeInt => result.add_type(Atomic::TLiteralInt(0)),
556                // int<0, hi>: only 0 is falsy.
557                Atomic::TIntRange {
558                    min: Some(0),
559                    max: Some(_) | None,
560                } => result.add_type(Atomic::TLiteralInt(0)),
561                // int<min, 0>: only 0 is falsy.
562                Atomic::TIntRange { max: Some(0), .. } => result.add_type(Atomic::TLiteralInt(0)),
563                t if !t.can_be_falsy() => {} // always truthy — exclude
564                _ => result.add_type(t.clone()),
565            }
566        }
567        result
568    }
569
570    /// Narrow this type as if `$x instanceof ClassName` is true.
571    ///
572    /// The instanceof check guarantees the value IS an instance of `class`, so we
573    /// replace any object / mixed constituents with the specific named object.  Scalar
574    /// constituents are dropped (they can never satisfy instanceof).
575    pub fn narrow_instanceof(&self, class: &str) -> Type {
576        let narrowed_ty = Atomic::TNamedObject {
577            fqcn: class.into(),
578            type_params: empty_type_params(),
579        };
580        // If any constituent is an object-like type, the result is the specific class.
581        let has_object = self.types.iter().any(|t| {
582            matches!(
583                t,
584                Atomic::TObject | Atomic::TNamedObject { .. } | Atomic::TMixed | Atomic::TNull // null fails instanceof, but mixed/object may include null
585            )
586        });
587        if has_object || self.is_empty() {
588            Type::single(narrowed_ty)
589        } else {
590            // Pure scalars — instanceof is always false here, but return the class
591            // defensively so callers don't see an empty union.
592            Type::single(narrowed_ty)
593        }
594    }
595
596    /// Narrow as if `is_string($x)` is true. `mixed`/`scalar` become a concrete
597    /// `string` (rather than staying `mixed`) so downstream string-only
598    /// operations see a usable type instead of reporting `Mixed*`.
599    pub fn narrow_to_string(&self) -> Type {
600        self.filter_replacing(
601            |t| t.is_string() || matches!(t, Atomic::TTemplateParam { .. }),
602            |t| matches!(t, Atomic::TMixed | Atomic::TScalar),
603            Atomic::TString,
604        )
605    }
606
607    /// Narrow as if `is_int($x)` is true.
608    pub fn narrow_to_int(&self) -> Type {
609        self.filter_replacing(
610            |t| t.is_int() || matches!(t, Atomic::TTemplateParam { .. }),
611            |t| matches!(t, Atomic::TMixed | Atomic::TScalar | Atomic::TNumeric),
612            Atomic::TInt,
613        )
614    }
615
616    /// Narrow as if `is_float($x)` is true.
617    pub fn narrow_to_float(&self) -> Type {
618        self.filter_replacing(
619            |t| {
620                matches!(
621                    t,
622                    Atomic::TFloat
623                        | Atomic::TIntegralFloat
624                        | Atomic::TLiteralFloat(..)
625                        | Atomic::TTemplateParam { .. }
626                )
627            },
628            |t| matches!(t, Atomic::TMixed | Atomic::TScalar | Atomic::TNumeric),
629            Atomic::TFloat,
630        )
631    }
632
633    /// Narrow as if `is_bool($x)` is true.
634    pub fn narrow_to_bool(&self) -> Type {
635        self.filter_replacing(
636            |t| {
637                matches!(
638                    t,
639                    Atomic::TBool | Atomic::TTrue | Atomic::TFalse | Atomic::TTemplateParam { .. }
640                )
641            },
642            |t| matches!(t, Atomic::TMixed | Atomic::TScalar),
643            Atomic::TBool,
644        )
645    }
646
647    /// Narrow as if `is_null($x)` is true.
648    pub fn narrow_to_null(&self) -> Type {
649        self.filter_replacing(
650            |t| matches!(t, Atomic::TNull | Atomic::TTemplateParam { .. }),
651            |t| matches!(t, Atomic::TMixed),
652            Atomic::TNull,
653        )
654    }
655
656    /// Narrow as if `is_array($x)` is true.
657    pub fn narrow_to_array(&self) -> Type {
658        self.filter_replacing(
659            |t| t.is_array() || matches!(t, Atomic::TTemplateParam { .. }),
660            |t| matches!(t, Atomic::TMixed),
661            Atomic::TArray {
662                key: Box::new(Type::mixed()),
663                value: Box::new(Type::mixed()),
664            },
665        )
666    }
667
668    /// Narrow array/list types to their non-empty variants (for `count() > 0` etc.).
669    pub fn narrow_to_non_empty_collection(&self) -> Type {
670        let mut out = Type::empty();
671        out.from_docblock = self.from_docblock;
672        for t in &self.types {
673            match t {
674                Atomic::TArray { key, value } => out.add_type(Atomic::TNonEmptyArray {
675                    key: key.clone(),
676                    value: value.clone(),
677                }),
678                Atomic::TList { value } => out.add_type(Atomic::TNonEmptyList {
679                    value: value.clone(),
680                }),
681                _ => out.add_type(t.clone()),
682            }
683        }
684        out
685    }
686
687    /// Narrow array/list types when proven empty (e.g. `array_key_first($x) === null`,
688    /// `$arr === []`). Drops the non-empty variants outright — they can never
689    /// be empty — and narrows a plain `array`/`list` down to the same closed,
690    /// zero-property `TKeyedArray` an empty `[]` literal itself types as, so
691    /// e.g. `$values[0]` on a proven-empty branch is flagged as a
692    /// `NonExistentArrayOffset` instead of silently keeping the pre-narrow
693    /// element type. `TKeyedArray` atoms are left unchanged — narrowing an
694    /// already-shaped array to "empty" when it may declare required
695    /// properties is a separate, more nuanced case.
696    pub fn narrow_to_empty_collection(&self) -> Type {
697        let mut out = Type::empty();
698        out.from_docblock = self.from_docblock;
699        for t in &self.types {
700            match t {
701                Atomic::TNonEmptyArray { .. } | Atomic::TNonEmptyList { .. } => {}
702                Atomic::TArray { .. } | Atomic::TList { .. } => {
703                    out.add_type(Atomic::TKeyedArray {
704                        properties: Box::default(),
705                        is_open: false,
706                        is_list: true,
707                    });
708                }
709                _ => out.add_type(t.clone()),
710            }
711        }
712        out
713    }
714
715    /// Narrow as if `array_is_list($x)` is true.
716    /// Lists have sequential integer keys starting from 0, so:
717    /// - `list<T>` / `non-empty-list<T>` are kept unchanged.
718    /// - `array<int, T>` is narrowed to `list<T>` (could be sequential).
719    /// - `non-empty-array<int, T>` is narrowed to `non-empty-list<T>`.
720    /// - `TKeyedArray` (shape) is kept only when its own `is_list` flag is
721    ///   already true — that flag is precise (set from the actual literal's
722    ///   keys, or an explicit `list{...}` docblock), not a hint, so a
723    ///   string-keyed or non-contiguous shape is correctly excluded.
724    /// - `mixed` becomes `list<mixed>` (array_is_list implies array).
725    /// - All other types (string-keyed arrays, non-arrays) are dropped.
726    pub fn narrow_to_list(&self) -> Type {
727        let mut out = Type::empty();
728        out.from_docblock = self.from_docblock;
729        for t in &self.types {
730            match t {
731                Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => out.add_type(t.clone()),
732                // Guard on "key admits int" rather than "key is exactly TInt" —
733                // `is_array($mixed)` narrows an unknown key to `Type::mixed()`,
734                // which is a list candidate (the runtime shape is still unknown),
735                // unlike a key statically known to exclude int entirely (e.g. a
736                // docblock-declared `array<string, T>`), which must stay excluded.
737                Atomic::TArray { key, value } if !key.narrow_to_int().is_empty() => {
738                    out.add_type(Atomic::TList {
739                        value: value.clone(),
740                    });
741                }
742                Atomic::TNonEmptyArray { key, value } if !key.narrow_to_int().is_empty() => {
743                    out.add_type(Atomic::TNonEmptyList {
744                        value: value.clone(),
745                    });
746                }
747                Atomic::TKeyedArray { is_list: true, .. } => out.add_type(t.clone()),
748                Atomic::TMixed => out.add_type(Atomic::TList {
749                    value: Box::new(Type::mixed()),
750                }),
751                _ => {}
752            }
753        }
754        if out.is_empty() {
755            self.filter(|t| matches!(t, Atomic::TList { .. } | Atomic::TNonEmptyList { .. }))
756        } else {
757            out
758        }
759    }
760
761    /// Narrow as if `is_object($x)` is true. A `mixed` becomes a concrete bare
762    /// `object` (rather than staying `mixed`) so downstream object-only
763    /// operations — `clone`, `instanceof`, method calls — see an object type
764    /// instead of reporting `Mixed*`.
765    pub fn narrow_to_object(&self) -> Type {
766        let mut out = Type::empty();
767        for t in &self.types {
768            if matches!(t, Atomic::TMixed) {
769                out.add_type(Atomic::TObject);
770            } else if t.is_object() || matches!(t, Atomic::TTemplateParam { .. }) {
771                out.add_type(t.clone());
772            }
773        }
774        if out.types.is_empty() {
775            self.filter(|t| t.is_object())
776        } else {
777            out
778        }
779    }
780
781    /// Narrow as if `is_callable($x)` is true.
782    ///
783    /// PHP accepts closures, TCallable, strings (function names), arrays
784    /// (['Class', 'method'] or [$obj, 'method']), and objects with __invoke.
785    /// Keep all of these; only drop atoms that are definitely not callable
786    /// (scalars, null, bool, etc.).
787    pub fn narrow_to_callable(&self) -> Type {
788        let narrowed = self.filter(|t| {
789            t.is_callable()
790                || t.is_string()
791                || t.is_array()
792                || t.is_object()
793                || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
794        });
795        // A bare `object` carries no known `__invoke` signature to compare
796        // against a `callable`-typed target, so it stayed an object rather
797        // than satisfying one — represent it as a generic callable instead,
798        // matching what `is_callable()` actually proved. A `TNamedObject`
799        // keeps its own class (its real `__invoke`, if any, is more precise
800        // than a generic callable).
801        let mut result = Type::empty();
802        result.possibly_undefined = narrowed.possibly_undefined;
803        result.from_docblock = narrowed.from_docblock;
804        for atomic in narrowed.types {
805            if matches!(atomic, Atomic::TObject) {
806                result.add_type(Atomic::TCallable {
807                    params: None,
808                    return_type: None,
809                });
810            } else {
811                result.add_type(atomic);
812            }
813        }
814        result
815    }
816
817    /// Narrow as if `is_scalar($x)` is true (int | string | float | bool).
818    pub fn narrow_to_scalar(&self) -> Type {
819        self.filter_replacing(
820            |t| {
821                t.is_string()
822                    || t.is_int()
823                    || matches!(
824                        t,
825                        Atomic::TFloat
826                            | Atomic::TIntegralFloat
827                            | Atomic::TLiteralFloat(..)
828                            | Atomic::TBool
829                            | Atomic::TTrue
830                            | Atomic::TFalse
831                            | Atomic::TScalar
832                            | Atomic::TNumeric
833                            | Atomic::TNumericString
834                            | Atomic::TTemplateParam { .. }
835                    )
836            },
837            |t| matches!(t, Atomic::TMixed),
838            Atomic::TScalar,
839        )
840    }
841
842    /// Narrow as if `is_iterable($x)` is true (array | Traversable).
843    /// For simplicity, this narrows to arrays or objects (can't easily verify interfaces).
844    pub fn narrow_to_iterable(&self) -> Type {
845        self.filter(|t| {
846            t.is_array()
847                || t.is_object()
848                || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
849        })
850    }
851
852    /// Narrow as if `is_countable($x)` is true (array | Countable).
853    /// For simplicity, this narrows to arrays or objects (can't easily verify Countable interface).
854    pub fn narrow_to_countable(&self) -> Type {
855        self.filter(|t| {
856            t.is_array()
857                || t.is_object()
858                || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
859        })
860    }
861
862    /// Narrow as if `is_resource($x)` is true.
863    /// Note: No TResource atomic type exists in the type system; this is a no-op.
864    /// Resources are declining in modern PHP and not actively tracked.
865    pub fn narrow_to_resource(&self) -> Type {
866        // No resource type in the system; just return mixed (allows any type)
867        self.filter(|t| matches!(t, Atomic::TMixed))
868    }
869
870    /// Narrow as if `class_exists($x)` returned true for a string variable.
871    /// String atoms become `class-string`; existing class-string atoms pass through;
872    /// mixed/scalar becomes `class-string`. Non-string atoms are dropped (returning
873    /// empty so the caller can mark the branch as diverging).
874    pub fn narrow_to_class_string(&self) -> Type {
875        let mut out = Type::empty();
876        out.from_docblock = self.from_docblock;
877        for t in &self.types {
878            match t {
879                Atomic::TClassString(_) => out.add_type(t.clone()),
880                _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
881                    out.add_type(Atomic::TClassString(None));
882                }
883                _ => {}
884            }
885        }
886        out
887    }
888
889    /// Narrow as if `interface_exists($x)` returned true for a string variable.
890    /// String atoms become `interface-string`; existing interface-string atoms pass
891    /// through; mixed/scalar becomes `interface-string`. Non-string atoms are dropped
892    /// (returning empty so the caller can mark the branch as diverging).
893    pub fn narrow_to_interface_string(&self) -> Type {
894        let mut out = Type::empty();
895        out.from_docblock = self.from_docblock;
896        for t in &self.types {
897            match t {
898                Atomic::TInterfaceString(_) => out.add_type(t.clone()),
899                // A known class-string keeps its name — every interface-string is
900                // also a valid class-string, so `interface_exists()` returning true
901                // narrows the atom without losing which class it names.
902                Atomic::TClassString(name) => {
903                    out.add_type(Atomic::TInterfaceString(*name));
904                }
905                _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
906                    out.add_type(Atomic::TInterfaceString(None));
907                }
908                _ => {}
909            }
910        }
911        out
912    }
913
914    // --- Merge (branch join) ------------------------------------------------
915
916    /// Merge two unions at a branch join point (e.g. after if/else).
917    /// The result is the union of all types in both.
918    pub fn merge(a: &Type, b: &Type) -> Type {
919        // Fast path: b is empty — nothing to add.
920        if b.types.is_empty() {
921            let mut result = a.clone();
922            result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
923            return result;
924        }
925        // Fast path: a is empty — clone b.
926        if a.types.is_empty() {
927            let mut result = b.clone();
928            result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
929            return result;
930        }
931        // Fast path: a is already mixed — b cannot widen it further.
932        if a.types.len() == 1 && matches!(a.types[0], Atomic::TMixed) {
933            let mut result = a.clone();
934            result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
935            return result;
936        }
937        // Fast path: b contains mixed — result collapses to mixed.
938        if b.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
939            return Type {
940                types: smallvec::smallvec![Atomic::TMixed],
941                possibly_undefined: a.possibly_undefined || b.possibly_undefined,
942                from_docblock: a.from_docblock || b.from_docblock,
943                falsy_stripped: false,
944                possibly_absent_offset: false,
945            };
946        }
947        let mut result = a.clone();
948        result.merge_with(b);
949        result
950    }
951
952    /// Merge `other` into `self` in-place (avoids cloning `self`).
953    pub fn merge_with(&mut self, other: &Type) {
954        if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
955            self.possibly_undefined |= other.possibly_undefined;
956            return;
957        }
958        if other.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
959            self.types.clear();
960            self.types.push(Atomic::TMixed);
961            self.possibly_undefined |= other.possibly_undefined;
962            return;
963        }
964        for atomic in &other.types {
965            self.add_type(atomic.clone());
966        }
967        self.possibly_undefined |= other.possibly_undefined;
968    }
969
970    /// Intersect with another union: keep only types present in `other`, widening
971    /// where `self` contains `mixed` (which is compatible with everything).
972    /// Used for match-arm subject narrowing.
973    pub fn intersect_with(&self, other: &Type) -> Type {
974        if self.is_mixed() {
975            return other.clone();
976        }
977        if other.is_mixed() {
978            return self.clone();
979        }
980        // Keep the more specific of each overlapping (self, other) atomic
981        // pair — e.g. intersecting `int` with `1|2` must keep `1|2` (the
982        // narrower side), not `int` (self's own, wider atomic): the whole
983        // point of narrowing a variable against a match/switch arm's
984        // literal conditions is to end up with the literal, not the bare
985        // declared type it already had. Every matching pair is kept (not
986        // just the first), so `int ∩ (1|2)` keeps both `1` and `2`.
987        let mut result = Type::empty();
988        for a in &self.types {
989            for b in &other.types {
990                if a == b {
991                    result.add_type(a.clone());
992                } else if atomic_subtype(b, a) {
993                    result.add_type(b.clone());
994                } else if atomic_subtype(a, b) {
995                    result.add_type(a.clone());
996                }
997            }
998        }
999        if result.is_empty() {
1000            Type::never()
1001        } else {
1002            result
1003        }
1004    }
1005
1006    // --- Template substitution ----------------------------------------------
1007
1008    /// Replace template param references with their resolved types.
1009    pub fn substitute_templates(&self, bindings: &FxHashMap<Name, Type>) -> Type {
1010        if bindings.is_empty() {
1011            return self.clone();
1012        }
1013        // Most argument/return types are plain scalars or resolved objects
1014        // with nothing to substitute — skip the rebuild entirely.
1015        if !self.types.iter().any(atomic_may_contain_templates) {
1016            return self.clone();
1017        }
1018        let mut result = Type::empty();
1019        result.possibly_undefined = self.possibly_undefined;
1020        result.from_docblock = self.from_docblock;
1021        for atomic in &self.types {
1022            match atomic {
1023                Atomic::TTemplateParam { name, .. } => {
1024                    if let Some(resolved) = bindings.get(name) {
1025                        for t in &resolved.types {
1026                            result.add_type(t.clone());
1027                        }
1028                    } else {
1029                        result.add_type(atomic.clone());
1030                    }
1031                }
1032                Atomic::TArray { key, value } => {
1033                    result.add_type(Atomic::TArray {
1034                        key: Box::new(key.substitute_templates(bindings)),
1035                        value: Box::new(value.substitute_templates(bindings)),
1036                    });
1037                }
1038                Atomic::TList { value } => {
1039                    result.add_type(Atomic::TList {
1040                        value: Box::new(value.substitute_templates(bindings)),
1041                    });
1042                }
1043                Atomic::TNonEmptyArray { key, value } => {
1044                    result.add_type(Atomic::TNonEmptyArray {
1045                        key: Box::new(key.substitute_templates(bindings)),
1046                        value: Box::new(value.substitute_templates(bindings)),
1047                    });
1048                }
1049                Atomic::TNonEmptyList { value } => {
1050                    result.add_type(Atomic::TNonEmptyList {
1051                        value: Box::new(value.substitute_templates(bindings)),
1052                    });
1053                }
1054                Atomic::TKeyedArray {
1055                    properties,
1056                    is_open,
1057                    is_list,
1058                } => {
1059                    use crate::atomic::KeyedProperty;
1060                    let new_props = properties
1061                        .iter()
1062                        .map(|(k, prop)| {
1063                            (
1064                                k.clone(),
1065                                KeyedProperty {
1066                                    ty: prop.ty.substitute_templates(bindings),
1067                                    optional: prop.optional,
1068                                },
1069                            )
1070                        })
1071                        .collect();
1072                    result.add_type(Atomic::TKeyedArray {
1073                        properties: Box::new(new_props),
1074                        is_open: *is_open,
1075                        is_list: *is_list,
1076                    });
1077                }
1078                Atomic::TCallable {
1079                    params,
1080                    return_type,
1081                } => {
1082                    result.add_type(Atomic::TCallable {
1083                        params: params.as_ref().map(|ps| {
1084                            ps.iter()
1085                                .map(|p| substitute_in_fn_param(p, bindings))
1086                                .collect()
1087                        }),
1088                        return_type: return_type
1089                            .as_ref()
1090                            .map(|r| Box::new(r.substitute_templates(bindings))),
1091                    });
1092                }
1093                Atomic::TClosure { data } => {
1094                    result.add_type(Atomic::TClosure {
1095                        data: Box::new(crate::atomic::ClosureData {
1096                            params: data
1097                                .params
1098                                .iter()
1099                                .map(|p| substitute_in_fn_param(p, bindings))
1100                                .collect(),
1101                            return_type: data.return_type.substitute_templates(bindings),
1102                            this_type: data
1103                                .this_type
1104                                .as_ref()
1105                                .map(|t| t.substitute_templates(bindings)),
1106                        }),
1107                    });
1108                }
1109                Atomic::TConditional { data } => {
1110                    let param_name = &data.param_name;
1111                    let new_subject = data.subject.substitute_templates(bindings);
1112                    let new_if_true = data.if_true.substitute_templates(bindings);
1113                    let new_if_false = data.if_false.substitute_templates(bindings);
1114
1115                    // If param_name names a template that is bound in this substitution,
1116                    // resolve the conditional immediately using the same predicate logic as
1117                    // `resolve_conditional_returns` for the $param form.
1118                    let resolved = if let Some(name) = param_name {
1119                        if let Some(bound) = bindings.get(name) {
1120                            if new_subject.types.len() == 1 {
1121                                resolve_conditional_branch(
1122                                    &new_subject.types[0],
1123                                    bound,
1124                                    &new_if_true,
1125                                    &new_if_false,
1126                                )
1127                            } else {
1128                                None
1129                            }
1130                        } else {
1131                            None
1132                        }
1133                    } else {
1134                        None
1135                    };
1136
1137                    if let Some(branch) = resolved {
1138                        for t in branch.types {
1139                            result.add_type(t);
1140                        }
1141                    } else {
1142                        result.add_type(Atomic::TConditional {
1143                            data: Box::new(crate::atomic::ConditionalData {
1144                                param_name: *param_name,
1145                                subject: new_subject,
1146                                if_true: new_if_true,
1147                                if_false: new_if_false,
1148                            }),
1149                        });
1150                    }
1151                }
1152                Atomic::TKeyOf { target } => {
1153                    let new_target = target.substitute_templates(bindings);
1154                    if let Some(resolved) = eval_key_of_type(&new_target) {
1155                        result.merge_with(&resolved);
1156                    } else {
1157                        result.add_type(Atomic::TKeyOf {
1158                            target: Box::new(new_target),
1159                        });
1160                    }
1161                }
1162                Atomic::TValueOf { target } => {
1163                    let new_target = target.substitute_templates(bindings);
1164                    if let Some(resolved) = eval_value_of_type(&new_target) {
1165                        result.merge_with(&resolved);
1166                    } else {
1167                        result.add_type(Atomic::TValueOf {
1168                            target: Box::new(new_target),
1169                        });
1170                    }
1171                }
1172                Atomic::TIntersection { parts } => {
1173                    result.add_type(Atomic::TIntersection {
1174                        parts: vec_to_type_params(
1175                            parts
1176                                .iter()
1177                                .map(|p| p.substitute_templates(bindings))
1178                                .collect(),
1179                        ),
1180                    });
1181                }
1182                Atomic::TNamedObject { fqcn, type_params } => {
1183                    // TODO: the docblock parser emits TNamedObject { fqcn: "T" } for bare @return T
1184                    // annotations instead of TTemplateParam, because it lacks template context at
1185                    // parse time. This block works around that by treating bare unqualified names
1186                    // as template param references when they appear in the binding map. Proper fix:
1187                    // make the docblock parser template-aware so it emits TTemplateParam directly.
1188                    // See issue #26 for context.
1189                    if type_params.is_empty() && !fqcn.contains('\\') {
1190                        if let Some(resolved) = bindings.get(fqcn) {
1191                            for t in &resolved.types {
1192                                result.add_type(t.clone());
1193                            }
1194                            continue;
1195                        }
1196                    }
1197                    let new_params: Vec<Type> = type_params
1198                        .iter()
1199                        .map(|p| p.substitute_templates(bindings))
1200                        .collect();
1201                    result.add_type(Atomic::TNamedObject {
1202                        fqcn: *fqcn,
1203                        type_params: vec_to_type_params(new_params),
1204                    });
1205                }
1206                // class-string<T> → substitute T from bindings
1207                Atomic::TClassString(Some(param_name)) => {
1208                    if let Some(resolved) = bindings.get(param_name) {
1209                        for r_atomic in &resolved.types {
1210                            let cls_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1211                                Some(*fqcn)
1212                            } else {
1213                                None
1214                            };
1215                            result.add_type(Atomic::TClassString(cls_name));
1216                        }
1217                    } else {
1218                        result.add_type(atomic.clone());
1219                    }
1220                }
1221                // interface-string<T> → substitute T from bindings
1222                Atomic::TInterfaceString(Some(param_name)) => {
1223                    if let Some(resolved) = bindings.get(param_name) {
1224                        for r_atomic in &resolved.types {
1225                            let iface_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1226                                Some(*fqcn)
1227                            } else {
1228                                None
1229                            };
1230                            result.add_type(Atomic::TInterfaceString(iface_name));
1231                        }
1232                    } else {
1233                        result.add_type(atomic.clone());
1234                    }
1235                }
1236                _ => {
1237                    result.add_type(atomic.clone());
1238                }
1239            }
1240        }
1241        result
1242    }
1243
1244    /// Resolves `TConditional` atoms whose discriminator is known at the call site.
1245    ///
1246    /// `lookup(param_name)` returns the call-site argument type for the named parameter,
1247    /// or `None` if the argument is not available. Handles `is null`, `is string`, and
1248    /// `is array` conditions; other condition types pass through unchanged.
1249    pub fn resolve_conditional_returns<F>(self, lookup: F) -> Type
1250    where
1251        F: Fn(&str) -> Option<Type>,
1252    {
1253        self.resolve_conditional_inner(&lookup)
1254    }
1255
1256    fn resolve_conditional_inner<F>(self, lookup: &F) -> Type
1257    where
1258        F: Fn(&str) -> Option<Type>,
1259    {
1260        let mut result = Type::empty();
1261        for atomic in self.types {
1262            match atomic {
1263                Atomic::TConditional { ref data } => {
1264                    let (param_name, subject, if_true, if_false) = (
1265                        &data.param_name,
1266                        &data.subject,
1267                        &data.if_true,
1268                        &data.if_false,
1269                    );
1270                    let resolved = if subject.types.len() == 1 {
1271                        if let Some(name) = param_name {
1272                            if let Some(arg_ty) = lookup(name.as_ref()) {
1273                                resolve_conditional_branch(
1274                                    &subject.types[0],
1275                                    &arg_ty,
1276                                    if_true,
1277                                    if_false,
1278                                )
1279                            } else {
1280                                None
1281                            }
1282                        } else {
1283                            None
1284                        }
1285                    } else {
1286                        None
1287                    };
1288
1289                    if let Some(branch) = resolved {
1290                        // Recursively resolve nested conditionals in the selected branch.
1291                        for t in branch.resolve_conditional_inner(lookup).types {
1292                            result.add_type(t);
1293                        }
1294                    } else {
1295                        // Cannot resolve at this call site: widen to the union of both branches.
1296                        // Recursively resolve nested conditionals in each branch.
1297                        for t in if_true.clone().resolve_conditional_inner(lookup).types {
1298                            result.add_type(t);
1299                        }
1300                        for t in if_false.clone().resolve_conditional_inner(lookup).types {
1301                            result.add_type(t);
1302                        }
1303                    }
1304                }
1305                other => result.add_type(other),
1306            }
1307        }
1308        result
1309    }
1310
1311    // --- Subtype check -------------------------------------------------------
1312
1313    /// Returns true if every atomic in `self` is a subtype of some atomic in `other`,
1314    /// using **only structural rules** — no `extends` / `implements` walk.
1315    ///
1316    /// Two distinct user-defined classes are never related here, even when one
1317    /// extends the other. Within `mir-analyzer`, when a `db` is in scope,
1318    /// prefer `crate::subtype::is_subtype(db, sub, sup)` which layers
1319    /// inheritance resolution on top of this check.
1320    pub fn is_subtype_structural(&self, other: &Type) -> bool {
1321        if other.is_mixed() {
1322            return true;
1323        }
1324        if self.is_never() {
1325            return true; // never <: everything
1326        }
1327        self.types
1328            .iter()
1329            .all(|a| other.types.iter().any(|b| atomic_subtype(a, b)))
1330    }
1331
1332    /// `sub <: self`, structurally, for a single atomic — equivalent to
1333    /// `Type::single(sub.clone()).is_subtype_structural(self)` without the
1334    /// clone and the temporary single-atomic union.
1335    pub fn accepts_atomic_structural(&self, sub: &Atomic) -> bool {
1336        if self.is_mixed() {
1337            return true;
1338        }
1339        matches!(sub, Atomic::TNever) || self.types.iter().any(|b| atomic_subtype(sub, b))
1340    }
1341
1342    // --- Utilities ----------------------------------------------------------
1343
1344    fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Type {
1345        let mut result = Type::empty();
1346        result.possibly_undefined = self.possibly_undefined;
1347        result.from_docblock = self.from_docblock;
1348        for atomic in &self.types {
1349            if f(atomic) {
1350                result.types.push(atomic.clone());
1351            }
1352        }
1353        result
1354    }
1355
1356    /// Like `filter`, but atoms matching `placeholder` are substituted with
1357    /// `replacement` instead of passing through unchanged. Used so narrowing
1358    /// an unrefined `mixed`/`scalar`/`numeric` value (e.g. via `is_int($x)`)
1359    /// yields the concrete narrowed type instead of staying `mixed`.
1360    fn filter_replacing<K: Fn(&Atomic) -> bool, P: Fn(&Atomic) -> bool>(
1361        &self,
1362        keep: K,
1363        placeholder: P,
1364        replacement: Atomic,
1365    ) -> Type {
1366        let mut result = Type::empty();
1367        result.possibly_undefined = self.possibly_undefined;
1368        result.from_docblock = self.from_docblock;
1369        for atomic in &self.types {
1370            if keep(atomic) {
1371                result.add_type(atomic.clone());
1372            } else if placeholder(atomic) {
1373                result.add_type(replacement.clone());
1374            }
1375        }
1376        result
1377    }
1378
1379    /// Mark this union as possibly-undefined and return it.
1380    pub fn possibly_undefined(mut self) -> Self {
1381        self.possibly_undefined = true;
1382        self
1383    }
1384
1385    /// Mark this union as coming from a docblock annotation.
1386    pub fn from_docblock(mut self) -> Self {
1387        self.from_docblock = true;
1388        self
1389    }
1390
1391    /// Mark this union as having had a `false`/`null` failure variant stripped
1392    /// for flow purposes (see the field doc on [`Type::falsy_stripped`]).
1393    pub fn falsy_stripped(mut self) -> Self {
1394        self.falsy_stripped = true;
1395        self
1396    }
1397
1398    /// Mark this union as read from a generic array/list offset whose key
1399    /// presence isn't statically provable (see the field doc on
1400    /// [`Type::possibly_absent_offset`]).
1401    pub fn possibly_absent_offset(mut self) -> Self {
1402        self.possibly_absent_offset = true;
1403        self
1404    }
1405}
1406
1407// ---------------------------------------------------------------------------
1408// Conditional return resolution helpers
1409// ---------------------------------------------------------------------------
1410
1411fn is_string_atomic(a: &Atomic) -> bool {
1412    matches!(
1413        a,
1414        Atomic::TString
1415            | Atomic::TNonEmptyString
1416            | Atomic::TLiteralString(_)
1417            | Atomic::TNumericString
1418            | Atomic::TClassString(_)
1419            | Atomic::TInterfaceString(_)
1420            | Atomic::TCallableString
1421    )
1422}
1423
1424fn is_array_atomic(a: &Atomic) -> bool {
1425    matches!(
1426        a,
1427        Atomic::TArray { .. }
1428            | Atomic::TNonEmptyArray { .. }
1429            | Atomic::TKeyedArray { .. }
1430            | Atomic::TList { .. }
1431            | Atomic::TNonEmptyList { .. }
1432    )
1433}
1434
1435fn is_list_atomic(a: &Atomic) -> bool {
1436    match a {
1437        Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => true,
1438        Atomic::TKeyedArray { is_list, .. } => *is_list,
1439        _ => false,
1440    }
1441}
1442
1443fn is_float_atomic(a: &Atomic) -> bool {
1444    matches!(
1445        a,
1446        Atomic::TFloat | Atomic::TIntegralFloat | Atomic::TLiteralFloat(..)
1447    )
1448}
1449
1450fn is_bool_atomic(a: &Atomic) -> bool {
1451    matches!(a, Atomic::TBool | Atomic::TTrue | Atomic::TFalse)
1452}
1453
1454/// Resolve one branch of a conditional return type given the subject discriminant
1455/// atomic and the actual argument type at the call site.
1456///
1457/// Returns `Some(branch)` when the branch can be determined statically, or `None`
1458/// to signal that the caller should widen to the union of both branches.
1459fn resolve_conditional_branch(
1460    subject: &Atomic,
1461    arg_ty: &Type,
1462    if_true: &Type,
1463    if_false: &Type,
1464) -> Option<Type> {
1465    let predicate: fn(&Atomic) -> bool = match subject {
1466        Atomic::TNull => |a| matches!(a, Atomic::TNull),
1467        Atomic::TTrue => |a| matches!(a, Atomic::TTrue),
1468        Atomic::TFalse => |a| matches!(a, Atomic::TFalse),
1469        Atomic::TString => is_string_atomic,
1470        Atomic::TList { .. } => is_list_atomic,
1471        Atomic::TArray { .. } => is_array_atomic,
1472        Atomic::TInt => Atomic::is_int,
1473        Atomic::TFloat => is_float_atomic,
1474        Atomic::TBool => is_bool_atomic,
1475        _ => return None,
1476    };
1477
1478    if arg_ty.types.is_empty() {
1479        return None;
1480    }
1481    let all_match = arg_ty.types.iter().all(&predicate);
1482    let none_match = !arg_ty.types.iter().any(predicate);
1483    if all_match {
1484        Some(if_true.clone())
1485    } else if none_match {
1486        Some(if_false.clone())
1487    } else {
1488        None
1489    }
1490}
1491
1492// ---------------------------------------------------------------------------
1493// Template substitution helpers
1494// ---------------------------------------------------------------------------
1495
1496/// Whether `substitute_templates` could change this atomic: it is either a
1497/// template reference itself or a container/callable that may hold one.
1498/// Mirrors the substituting arms of that function's match — keep in sync.
1499fn atomic_may_contain_templates(atomic: &Atomic) -> bool {
1500    match atomic {
1501        // Bare unqualified names double as template refs (docblock parser
1502        // workaround, see substitute_templates); qualified names only matter
1503        // when they carry generic params.
1504        Atomic::TNamedObject { fqcn, type_params } => {
1505            !type_params.is_empty() || !fqcn.contains('\\')
1506        }
1507        Atomic::TTemplateParam { .. }
1508        | Atomic::TKeyOf { .. }
1509        | Atomic::TValueOf { .. }
1510        | Atomic::TArray { .. }
1511        | Atomic::TList { .. }
1512        | Atomic::TNonEmptyArray { .. }
1513        | Atomic::TNonEmptyList { .. }
1514        | Atomic::TKeyedArray { .. }
1515        | Atomic::TCallable { .. }
1516        | Atomic::TClosure { .. }
1517        | Atomic::TConditional { .. }
1518        | Atomic::TIntersection { .. }
1519        | Atomic::TClassString(Some(_))
1520        | Atomic::TInterfaceString(Some(_)) => true,
1521        _ => false,
1522    }
1523}
1524
1525fn eval_key_of_type(t: &Type) -> Option<Type> {
1526    let mut result = Type::empty();
1527    for atomic in &t.types {
1528        match atomic {
1529            Atomic::TArray { key, .. } | Atomic::TNonEmptyArray { key, .. } => {
1530                for k in &key.types {
1531                    result.add_type(k.clone());
1532                }
1533            }
1534            Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => {
1535                result.add_type(Atomic::TInt);
1536            }
1537            Atomic::TKeyedArray { properties, .. } => {
1538                for key in properties.keys() {
1539                    match key {
1540                        crate::atomic::ArrayKey::Int(n) => result.add_type(Atomic::TLiteralInt(*n)),
1541                        crate::atomic::ArrayKey::String(s) => {
1542                            result.add_type(Atomic::TLiteralString(s.clone()))
1543                        }
1544                    }
1545                }
1546            }
1547            _ => return None,
1548        }
1549    }
1550    (!result.types.is_empty()).then_some(result)
1551}
1552
1553fn eval_value_of_type(t: &Type) -> Option<Type> {
1554    let mut result = Type::empty();
1555    for atomic in &t.types {
1556        match atomic {
1557            Atomic::TArray { value, .. }
1558            | Atomic::TNonEmptyArray { value, .. }
1559            | Atomic::TList { value }
1560            | Atomic::TNonEmptyList { value } => {
1561                result.merge_with(value);
1562            }
1563            Atomic::TKeyedArray { properties, .. } => {
1564                for prop in properties.values() {
1565                    result.merge_with(&prop.ty);
1566                }
1567            }
1568            _ => return None,
1569        }
1570    }
1571    (!result.types.is_empty()).then_some(result)
1572}
1573
1574fn substitute_in_fn_param(
1575    p: &crate::atomic::FnParam,
1576    bindings: &FxHashMap<Name, Type>,
1577) -> crate::atomic::FnParam {
1578    crate::atomic::FnParam {
1579        name: p.name,
1580        ty: p.ty.as_ref().map(|t| {
1581            let u = t.to_union();
1582            let substituted = u.substitute_templates(bindings);
1583            crate::compact::SimpleType::from_union(substituted)
1584        }),
1585        out_ty: p.out_ty.as_ref().map(|t| {
1586            let u = t.to_union();
1587            let substituted = u.substitute_templates(bindings);
1588            crate::compact::SimpleType::from_union(substituted)
1589        }),
1590        default: p.default.as_ref().map(|d| {
1591            let u = d.to_union();
1592            let substituted = u.substitute_templates(bindings);
1593            crate::compact::SimpleType::from_union(substituted)
1594        }),
1595        is_variadic: p.is_variadic,
1596        is_byref: p.is_byref,
1597        is_optional: p.is_optional,
1598    }
1599}
1600
1601// ---------------------------------------------------------------------------
1602// Atomic subtype (no codebase — structural check only)
1603// ---------------------------------------------------------------------------
1604
1605/// Structural `sub <: sup` for a single atomic pair, without hierarchy resolution.
1606pub fn atomic_subtype(sub: &Atomic, sup: &Atomic) -> bool {
1607    if sub == sup {
1608        return true;
1609    }
1610    match (sub, sup) {
1611        // Bottom type
1612        (Atomic::TNever, _) => true,
1613        // Top types — anything goes in both directions for mixed
1614        (_, Atomic::TMixed) => true,
1615        (Atomic::TMixed, _) => true,
1616        // Template param in supertype position: any value satisfies an unconstrained
1617        // template (as_type = mixed), or a constrained one if it satisfies the bound.
1618        // This handles union bounds like `T of string|list<I>|array<K, V>` where
1619        // I/K/V are free template params — any type satisfies them structurally.
1620        (_, Atomic::TTemplateParam { as_type, .. }) => {
1621            as_type.is_mixed() || as_type.types.iter().any(|b| atomic_subtype(sub, b))
1622        }
1623
1624        // Scalars
1625        (Atomic::TLiteralInt(_), Atomic::TInt) => true,
1626        (Atomic::TLiteralInt(_), Atomic::TNumeric) => true,
1627        (Atomic::TLiteralInt(_), Atomic::TScalar) => true,
1628        (Atomic::TLiteralInt(n), Atomic::TPositiveInt) => *n > 0,
1629        (Atomic::TLiteralInt(n), Atomic::TNonNegativeInt) => *n >= 0,
1630        (Atomic::TLiteralInt(n), Atomic::TNegativeInt) => *n < 0,
1631        (Atomic::TPositiveInt, Atomic::TInt) => true,
1632        (Atomic::TPositiveInt, Atomic::TNonNegativeInt) => true,
1633        (Atomic::TPositiveInt, Atomic::TNumeric) => true,
1634        (Atomic::TPositiveInt, Atomic::TScalar) => true,
1635        (Atomic::TNegativeInt, Atomic::TInt) => true,
1636        (Atomic::TNegativeInt, Atomic::TNumeric) => true,
1637        (Atomic::TNegativeInt, Atomic::TScalar) => true,
1638        (Atomic::TNonNegativeInt, Atomic::TInt) => true,
1639        (Atomic::TNonNegativeInt, Atomic::TNumeric) => true,
1640        (Atomic::TNonNegativeInt, Atomic::TScalar) => true,
1641        (Atomic::TIntRange { .. }, Atomic::TInt) => true,
1642        (Atomic::TIntRange { .. }, Atomic::TNumeric) => true,
1643        (Atomic::TIntRange { .. }, Atomic::TScalar) => true,
1644        // positive-int is int<1, ∞>: subtype of int<sup_min, ∞> when sup_min <= 1
1645        (Atomic::TPositiveInt, Atomic::TIntRange { min, max }) => {
1646            max.is_none() && min.is_none_or(|m| m <= 1)
1647        }
1648        // negative-int is int<-∞, -1>: subtype of int<-∞, sup_max> when sup_max >= -1
1649        (Atomic::TNegativeInt, Atomic::TIntRange { min, max }) => {
1650            min.is_none() && max.is_none_or(|m| m >= -1)
1651        }
1652        // non-negative-int is int<0, ∞>: subtype of int<sup_min, ∞> when sup_min <= 0
1653        (Atomic::TNonNegativeInt, Atomic::TIntRange { min, max }) => {
1654            max.is_none() && min.is_none_or(|m| m <= 0)
1655        }
1656        // A bounded int range is a subtype of a named int subtype when every value fits
1657        (Atomic::TIntRange { min: sub_min, .. }, Atomic::TPositiveInt) => {
1658            sub_min.is_some_and(|lo| lo >= 1)
1659        }
1660        (Atomic::TIntRange { min: sub_min, .. }, Atomic::TNonNegativeInt) => {
1661            sub_min.is_some_and(|lo| lo >= 0)
1662        }
1663        (Atomic::TIntRange { max: sub_max, .. }, Atomic::TNegativeInt) => {
1664            sub_max.is_some_and(|hi| hi <= -1)
1665        }
1666        // int<sub_min, sub_max> <: int<sup_min, sup_max> when ranges nest
1667        (
1668            Atomic::TIntRange {
1669                min: sub_min,
1670                max: sub_max,
1671            },
1672            Atomic::TIntRange {
1673                min: sup_min,
1674                max: sup_max,
1675            },
1676        ) => {
1677            let lower_ok = match (sub_min, sup_min) {
1678                (_, None) => true,
1679                (None, Some(_)) => false,
1680                (Some(sl), Some(su)) => sl >= su,
1681            };
1682            let upper_ok = match (sub_max, sup_max) {
1683                (None, None) | (Some(_), None) => true,
1684                (None, Some(_)) => false,
1685                (Some(sl), Some(su)) => sl <= su,
1686            };
1687            lower_ok && upper_ok
1688        }
1689
1690        (Atomic::TLiteralFloat(..), Atomic::TFloat) => true,
1691        (Atomic::TLiteralFloat(..), Atomic::TNumeric) => true,
1692        (Atomic::TLiteralFloat(..), Atomic::TScalar) => true,
1693
1694        (Atomic::TLiteralString(s), Atomic::TString) => {
1695            let _ = s;
1696            true
1697        }
1698        (Atomic::TLiteralString(s), Atomic::TCallableString) => {
1699            let _ = s;
1700            true
1701        }
1702        (Atomic::TLiteralString(s), Atomic::TNonEmptyString) => !s.is_empty(),
1703        (Atomic::TLiteralString(s), Atomic::TNumericString) => s.parse::<f64>().is_ok(),
1704        // A literal string is type-compatible with class-string; validate_class_string_argument
1705        // separately checks whether the string names a real class (UndefinedClass).
1706        (Atomic::TLiteralString(_), Atomic::TClassString(_)) => true,
1707        // Same, for interface-string; validate_interface_string_argument checks existence
1708        // and that the name actually resolves to an interface.
1709        (Atomic::TLiteralString(_), Atomic::TInterfaceString(_)) => true,
1710        (Atomic::TLiteralString(_), Atomic::TScalar) => true,
1711        (Atomic::TNonEmptyString, Atomic::TString) => true,
1712        (Atomic::TCallableString, Atomic::TString) => true,
1713        // numeric-string is always non-empty (e.g. "42", "-1", "0.5") — "" is not numeric.
1714        (Atomic::TNumericString, Atomic::TNonEmptyString) => true,
1715        (Atomic::TNumericString, Atomic::TString) => true,
1716        // A class/interface/callable/enum/trait name can never be the empty
1717        // string in real PHP — every one of these string-subtype atoms is
1718        // always non-empty, same reasoning as numeric-string above.
1719        (Atomic::TClassString(_), Atomic::TNonEmptyString) => true,
1720        (Atomic::TInterfaceString(_), Atomic::TNonEmptyString) => true,
1721        (Atomic::TCallableString, Atomic::TNonEmptyString) => true,
1722        (Atomic::TEnumString, Atomic::TNonEmptyString) => true,
1723        (Atomic::TTraitString, Atomic::TNonEmptyString) => true,
1724        (Atomic::TClassString(_), Atomic::TString) => true,
1725        (Atomic::TInterfaceString(_), Atomic::TString) => true,
1726        // Every interface-string is a valid class-string: PHP doesn't distinguish
1727        // the two at runtime — both are just strings naming a class-like symbol.
1728        // Instantiability (`new $x()`) is guarded separately, since an interface
1729        // name can never be `new`-ed even though it satisfies class-string.
1730        (Atomic::TInterfaceString(_), Atomic::TClassString(None)) => true,
1731        (Atomic::TInterfaceString(Some(a)), Atomic::TClassString(Some(b))) => a == b,
1732        (Atomic::TEnumString, Atomic::TString) => true,
1733        (Atomic::TTraitString, Atomic::TString) => true,
1734
1735        (Atomic::TTrue, Atomic::TBool) => true,
1736        (Atomic::TFalse, Atomic::TBool) => true,
1737
1738        (Atomic::TInt, Atomic::TNumeric) => true,
1739        (Atomic::TFloat, Atomic::TNumeric) => true,
1740        (Atomic::TIntegralFloat, Atomic::TNumeric) => true,
1741        (Atomic::TNumericString, Atomic::TNumeric) => true,
1742
1743        (Atomic::TInt, Atomic::TScalar) => true,
1744        (Atomic::TFloat, Atomic::TScalar) => true,
1745        (Atomic::TIntegralFloat, Atomic::TScalar) => true,
1746        (Atomic::TString, Atomic::TScalar) => true,
1747        (Atomic::TBool, Atomic::TScalar) => true,
1748        (Atomic::TNumeric, Atomic::TScalar) => true,
1749        (Atomic::TTrue, Atomic::TScalar) => true,
1750        (Atomic::TFalse, Atomic::TScalar) => true,
1751        // Every refined string atom is, at runtime, still just a `string` —
1752        // and therefore a `scalar` — same as the already-covered TLiteralString
1753        // and int-family refinements just above/below.
1754        (Atomic::TNonEmptyString, Atomic::TScalar) => true,
1755        (Atomic::TNumericString, Atomic::TScalar) => true,
1756        (Atomic::TCallableString, Atomic::TScalar) => true,
1757        (Atomic::TClassString(_), Atomic::TScalar) => true,
1758        (Atomic::TInterfaceString(_), Atomic::TScalar) => true,
1759        (Atomic::TEnumString, Atomic::TScalar) => true,
1760        (Atomic::TTraitString, Atomic::TScalar) => true,
1761
1762        // Object hierarchy (structural, no codebase)
1763        (Atomic::TNamedObject { .. }, Atomic::TObject) => true,
1764        (Atomic::TStaticObject { .. }, Atomic::TObject) => true,
1765        (Atomic::TSelf { .. }, Atomic::TObject) => true,
1766        // An enum-case literal is, at runtime, an object.
1767        (Atomic::TLiteralEnumCase { .. }, Atomic::TObject) => true,
1768        // self(X) and static(X) satisfy TNamedObject(X) with same FQCN
1769        (Atomic::TSelf { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
1770        (Atomic::TStaticObject { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
1771        // TNamedObject(X) satisfies self(X) / static(X) with same FQCN
1772        (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TSelf { fqcn: b }) => a == b,
1773        (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TStaticObject { fqcn: b }) => a == b,
1774        // An enum-case literal satisfies its own bare enum type (enums are
1775        // represented as TNamedObject).
1776        (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TNamedObject { fqcn, .. }) => {
1777            enum_fqcn == fqcn
1778        }
1779        // Bare generic property accepts parameterized value: Box accepts Box<string>.
1780        // The reverse is NOT true — bare Box value does not satisfy Box<string> property
1781        // (invariant check). Only sup being bare (empty type_params) is the wildcard.
1782        (
1783            Atomic::TNamedObject {
1784                fqcn: sub_fqcn,
1785                type_params: sub_params,
1786            },
1787            Atomic::TNamedObject {
1788                fqcn: sup_fqcn,
1789                type_params: sup_params,
1790            },
1791        ) => {
1792            sub_fqcn == sup_fqcn
1793                && (sup_params.is_empty() || type_params_compatible(sub_params, sup_params))
1794        }
1795
1796        // TIntegralFloat is a subtype of float (all integral floats are floats)
1797        (Atomic::TIntegralFloat, Atomic::TFloat) => true,
1798
1799        // Literal int widens to float in PHP
1800        (Atomic::TLiteralInt(_), Atomic::TFloat) => true,
1801        (Atomic::TPositiveInt, Atomic::TFloat) => true,
1802        (Atomic::TNegativeInt, Atomic::TFloat) => true,
1803        (Atomic::TNonNegativeInt, Atomic::TFloat) => true,
1804        (Atomic::TInt, Atomic::TFloat) => true,
1805        (Atomic::TIntRange { .. }, Atomic::TFloat) => true,
1806
1807        // Literal int satisfies an int range only when the value is within bounds
1808        (Atomic::TLiteralInt(n), Atomic::TIntRange { min, max }) => {
1809            min.is_none_or(|lo| *n >= lo) && max.is_none_or(|hi| *n <= hi)
1810        }
1811
1812        // PHP callables: string and array are valid callable values
1813        (Atomic::TString, Atomic::TCallable { .. }) => true,
1814        (Atomic::TNonEmptyString, Atomic::TCallable { .. }) => true,
1815        (Atomic::TLiteralString(_), Atomic::TCallable { .. }) => true,
1816        (Atomic::TArray { .. }, Atomic::TCallable { .. }) => true,
1817        (Atomic::TNonEmptyArray { .. }, Atomic::TCallable { .. }) => true,
1818        (Atomic::TKeyedArray { .. }, Atomic::TCallable { .. }) => true,
1819
1820        // Closure <: callable, typed Closure <: Closure
1821        (Atomic::TClosure { .. }, Atomic::TCallable { .. }) => true,
1822        // callable <: Closure: callable is wider but not flagged at default error level
1823        (Atomic::TCallable { .. }, Atomic::TClosure { .. }) => true,
1824        // TClosure <: TClosure: check arity, per-parameter contravariance, and
1825        // return covariance for scalar/array-shaped types, where a purely
1826        // structural check is reliable. A named-class (or nested-callable)
1827        // param/return is skipped rather than checked — this checker has no
1828        // database access to walk `extends`/`implements`, so it can't safely
1829        // tell a real Liskov violation apart from a legitimate subclass/
1830        // superclass substitution; treating it as compatible avoids false
1831        // positives on that far more common case at the cost of missing the
1832        // narrower nominal-variance violation.
1833        (Atomic::TClosure { data: sub }, Atomic::TClosure { data: sup }) => {
1834            fn has_nominal_type(t: &Type) -> bool {
1835                t.types.iter().any(|a| {
1836                    matches!(
1837                        a,
1838                        Atomic::TNamedObject { .. }
1839                            | Atomic::TSelf { .. }
1840                            | Atomic::TStaticObject { .. }
1841                            | Atomic::TTemplateParam { .. }
1842                            | Atomic::TClosure { .. }
1843                            | Atomic::TCallable { .. }
1844                    )
1845                })
1846            }
1847            let sub_required = sub
1848                .params
1849                .iter()
1850                .filter(|p| !p.is_optional && !p.is_variadic)
1851                .count();
1852            if sub_required > sup.params.len() {
1853                false
1854            } else {
1855                let params_ok = sup.params.iter().enumerate().all(|(i, sup_param)| {
1856                    let Some(sub_param) = sub.params.get(i) else {
1857                        return true;
1858                    };
1859                    if sub_param.is_optional || sub_param.is_variadic {
1860                        return true;
1861                    }
1862                    let (Some(sub_ty), Some(sup_ty)) =
1863                        (sub_param.ty.as_ref(), sup_param.ty.as_ref())
1864                    else {
1865                        return true;
1866                    };
1867                    let (sub_u, sup_u) = (sub_ty.to_union(), sup_ty.to_union());
1868                    if has_nominal_type(&sub_u) || has_nominal_type(&sup_u) {
1869                        return true;
1870                    }
1871                    // Contravariance: whatever `sup` promises to pass must be
1872                    // acceptable to `sub`'s declared parameter type.
1873                    sup_u.is_subtype_structural(&sub_u)
1874                });
1875                params_ok
1876                    && (sub.return_type.is_mixed()
1877                        || sup.return_type.is_mixed()
1878                        || has_nominal_type(&sub.return_type)
1879                        || has_nominal_type(&sup.return_type)
1880                        || sub.return_type.is_subtype_structural(&sup.return_type))
1881            }
1882        }
1883        // callable <: callable (trivial)
1884        (Atomic::TCallable { .. }, Atomic::TCallable { .. }) => true,
1885        // TClosure satisfies `Closure` named object or `object`
1886        (Atomic::TClosure { .. }, Atomic::TNamedObject { fqcn, .. }) => {
1887            fqcn.as_ref().eq_ignore_ascii_case("closure")
1888        }
1889        (Atomic::TClosure { .. }, Atomic::TObject) => true,
1890        // bare `Closure` (named object without signature) satisfies any typed Closure(): T
1891        (Atomic::TNamedObject { fqcn, .. }, Atomic::TClosure { .. }) => {
1892            fqcn.as_ref().eq_ignore_ascii_case("closure")
1893        }
1894        // `Closure` named-object satisfies `callable`
1895        (Atomic::TNamedObject { fqcn, .. }, Atomic::TCallable { .. }) => {
1896            fqcn.as_ref().eq_ignore_ascii_case("closure")
1897        }
1898
1899        // A&B&C <: D&E iff every part of the supertype is satisfied by some
1900        // part of the subtype — an intersection with MORE conjuncts is the
1901        // more specific (sub)type, so `Countable&ArrayAccess&Iterator` is a
1902        // subtype of `Countable&ArrayAccess`. Purely structural (each part's
1903        // own `is_subtype_structural` recurses, so e.g. two differently-named
1904        // interfaces only match when equal — same conservative stance as the
1905        // TClosure<:TClosure arm above for named types).
1906        (
1907            Atomic::TIntersection { parts: sub_parts },
1908            Atomic::TIntersection { parts: sup_parts },
1909        ) => sup_parts.iter().all(|sup_part| {
1910            sub_parts
1911                .iter()
1912                .any(|sub_part| sub_part.is_subtype_structural(sup_part))
1913        }),
1914
1915        // List <: array  (list key is always int; int must satisfy the array's key type)
1916        (Atomic::TList { value }, Atomic::TArray { key, value: av }) => {
1917            Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
1918        }
1919        (Atomic::TNonEmptyList { value }, Atomic::TArray { key, value: av }) => {
1920            Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
1921        }
1922        (Atomic::TNonEmptyList { value }, Atomic::TNonEmptyArray { key, value: av }) => {
1923            Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
1924        }
1925        (Atomic::TNonEmptyList { value }, Atomic::TList { value: lv }) => {
1926            value.is_subtype_structural(lv)
1927        }
1928        // array<int, X> is accepted where list<X> or non-empty-list<X> expected
1929        (Atomic::TArray { key, value: av }, Atomic::TList { value: lv }) => {
1930            matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
1931                && av.is_subtype_structural(lv)
1932        }
1933        (Atomic::TArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
1934            matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
1935                && av.is_subtype_structural(lv)
1936        }
1937        (Atomic::TNonEmptyArray { key, value: av }, Atomic::TList { value: lv }) => {
1938            matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
1939                && av.is_subtype_structural(lv)
1940        }
1941        (Atomic::TNonEmptyArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
1942            matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
1943                && av.is_subtype_structural(lv)
1944        }
1945        // TList <: TList value covariance
1946        (Atomic::TList { value: v1 }, Atomic::TList { value: v2 }) => v1.is_subtype_structural(v2),
1947        (Atomic::TNonEmptyArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
1948            k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
1949        }
1950
1951        // array<A, B> <: array<C, D>  iff  A <: C && B <: D
1952        (Atomic::TArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
1953            k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
1954        }
1955
1956        // A keyed/shape array is a subtype of array<K, V> / non-empty-array<K, V>
1957        // when all property KEYS are subtypes of K. Value compatibility is checked
1958        // structurally only for scalar types; named-object values are deferred to
1959        // class-hierarchy checks in return_arrays_compatible (mir-analyzer).
1960        // Open shapes (is_open=true) may have extra unknown keys beyond `properties`:
1961        // those stay unchecked (permissive), but every KNOWN property must still
1962        // satisfy K/V regardless of openness — an open shape isn't a license to skip
1963        // checking the keys it does declare.
1964        (Atomic::TKeyedArray { properties, .. }, Atomic::TArray { key, value }) => {
1965            properties.iter().all(|(prop_key, prop)| {
1966                let key_atomic = match prop_key {
1967                    crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
1968                    crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
1969                };
1970                if !Type::single(key_atomic).is_subtype_structural(key) {
1971                    return false; // key mismatch — definitively incompatible
1972                }
1973                // Named-object values require class-hierarchy checks not available here.
1974                let has_named_obj = prop.ty.types.iter().any(|a| {
1975                    matches!(
1976                        a,
1977                        Atomic::TNamedObject { .. }
1978                            | Atomic::TSelf { .. }
1979                            | Atomic::TStaticObject { .. }
1980                            | Atomic::TClosure { .. }
1981                            | Atomic::TTemplateParam { .. }
1982                    )
1983                });
1984                has_named_obj || prop.ty.is_subtype_structural(value)
1985            })
1986        }
1987        (
1988            Atomic::TKeyedArray {
1989                properties,
1990                is_open,
1991                ..
1992            },
1993            Atomic::TNonEmptyArray { key, value },
1994        ) => {
1995            (*is_open || properties.iter().any(|(_, p)| !p.optional))
1996                && properties.iter().all(|(prop_key, prop)| {
1997                    let key_atomic = match prop_key {
1998                        crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
1999                        crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2000                    };
2001                    if !Type::single(key_atomic).is_subtype_structural(key) {
2002                        return false;
2003                    }
2004                    let has_named_obj = prop.ty.types.iter().any(|a| {
2005                        matches!(
2006                            a,
2007                            Atomic::TNamedObject { .. }
2008                                | Atomic::TSelf { .. }
2009                                | Atomic::TStaticObject { .. }
2010                                | Atomic::TClosure { .. }
2011                                | Atomic::TTemplateParam { .. }
2012                        )
2013                    });
2014                    has_named_obj || prop.ty.is_subtype_structural(value)
2015                })
2016        }
2017
2018        // A list-shaped keyed array (is_list=true, all int keys) is a subtype of list<X>.
2019        (
2020            Atomic::TKeyedArray {
2021                properties,
2022                is_list,
2023                ..
2024            },
2025            Atomic::TList { value: lv },
2026        ) => *is_list && properties.values().all(|p| p.ty.is_subtype_structural(lv)),
2027        (
2028            Atomic::TKeyedArray {
2029                properties,
2030                is_list,
2031                ..
2032            },
2033            Atomic::TNonEmptyList { value: lv },
2034        ) => {
2035            *is_list
2036                && !properties.is_empty()
2037                && properties.values().all(|p| p.ty.is_subtype_structural(lv))
2038        }
2039
2040        // Two shapes: every sup key must be satisfied (present+compatible, or
2041        // absent-but-optional/sub-open), and sub may not have keys sup doesn't
2042        // declare unless sup itself is open. Named-object values are deferred
2043        // to class-hierarchy checks, same as the TArray/TList sup arms above.
2044        (
2045            Atomic::TKeyedArray {
2046                properties: sub_props,
2047                is_open: sub_open,
2048                ..
2049            },
2050            Atomic::TKeyedArray {
2051                properties: sup_props,
2052                is_open: sup_open,
2053                ..
2054            },
2055        ) => {
2056            let keys_satisfied = sup_props
2057                .iter()
2058                .all(|(key, sup_prop)| match sub_props.get(key) {
2059                    Some(sub_prop) => {
2060                        // A key merely optional on the sub side may legally be
2061                        // absent at runtime, so it can't satisfy a sup key that
2062                        // requires it present.
2063                        if !sup_prop.optional && sub_prop.optional {
2064                            return false;
2065                        }
2066                        let has_named_obj = sup_prop.ty.types.iter().any(|a| {
2067                            matches!(
2068                                a,
2069                                Atomic::TNamedObject { .. }
2070                                    | Atomic::TSelf { .. }
2071                                    | Atomic::TStaticObject { .. }
2072                                    | Atomic::TClosure { .. }
2073                                    | Atomic::TTemplateParam { .. }
2074                            )
2075                        });
2076                        has_named_obj || sub_prop.ty.is_subtype_structural(&sup_prop.ty)
2077                    }
2078                    None => sup_prop.optional || *sub_open,
2079                });
2080            let no_undeclared_extras =
2081                *sup_open || sub_props.keys().all(|k| sup_props.contains_key(k));
2082            keys_satisfied && no_undeclared_extras
2083        }
2084
2085        _ => false,
2086    }
2087}
2088
2089/// Whether each generic type-argument in `sub` is compatible with the
2090/// corresponding argument in `sup`. Arguments are invariant (require structural
2091/// equality) with one exception: an empty array literal (`array{}`) is accepted
2092/// against any array/list argument, so `new Box([])` — inferred as
2093/// `Box<array{}>` — satisfies a declared `Box<list<T>>` for any `T`.
2094fn type_params_compatible(sub: &[Type], sup: &[Type]) -> bool {
2095    if sub.len() != sup.len() {
2096        return false;
2097    }
2098    sub.iter()
2099        .zip(sup.iter())
2100        .all(|(a, b)| a == b || (is_empty_array_literal(a) && is_array_like(b)))
2101}
2102
2103/// True for a non-empty union whose atoms are all empty keyed arrays (`array{}`),
2104/// i.e. the type of an empty array literal `[]`.
2105fn is_empty_array_literal(t: &Type) -> bool {
2106    !t.types.is_empty()
2107        && t.types.iter().all(
2108            |atom| matches!(atom, Atomic::TKeyedArray { properties, .. } if properties.is_empty()),
2109        )
2110}
2111
2112/// True for a non-empty union whose atoms are all array/list types.
2113fn is_array_like(t: &Type) -> bool {
2114    !t.types.is_empty() && t.types.iter().all(|atom| atom.is_array())
2115}
2116
2117// ---------------------------------------------------------------------------
2118// Tests
2119// ---------------------------------------------------------------------------
2120
2121#[cfg(test)]
2122mod tests {
2123    use std::sync::Arc;
2124
2125    use super::*;
2126
2127    fn conditional(
2128        param_name: Option<Name>,
2129        subject: Type,
2130        if_true: Type,
2131        if_false: Type,
2132    ) -> Atomic {
2133        Atomic::TConditional {
2134            data: Box::new(crate::atomic::ConditionalData {
2135                param_name,
2136                subject,
2137                if_true,
2138                if_false,
2139            }),
2140        }
2141    }
2142
2143    #[test]
2144    fn single_is_single() {
2145        let u = Type::single(Atomic::TString);
2146        assert!(u.is_single());
2147        assert!(!u.is_nullable());
2148    }
2149
2150    #[test]
2151    fn nullable_has_null() {
2152        let u = Type::nullable(Atomic::TString);
2153        assert!(u.is_nullable());
2154        assert_eq!(u.types.len(), 2);
2155    }
2156
2157    #[test]
2158    fn add_type_deduplicates() {
2159        let mut u = Type::single(Atomic::TString);
2160        u.add_type(Atomic::TString);
2161        assert_eq!(u.types.len(), 1);
2162    }
2163
2164    #[test]
2165    fn array_key_is_int_string() {
2166        let k = Type::array_key();
2167        assert!(k.is_array_key());
2168        assert_eq!(k.types.len(), 2);
2169    }
2170
2171    #[test]
2172    fn is_array_key_false_for_plain_int() {
2173        assert!(!Type::int().is_array_key());
2174    }
2175
2176    #[test]
2177    fn is_array_key_false_for_mixed() {
2178        assert!(!Type::mixed().is_array_key());
2179    }
2180
2181    #[test]
2182    fn is_array_key_false_for_int_string_null() {
2183        let mut u = Type::array_key();
2184        u.add_type(Atomic::TNull);
2185        assert!(!u.is_array_key());
2186    }
2187
2188    #[test]
2189    fn add_type_literal_subsumed_by_base() {
2190        let mut u = Type::single(Atomic::TInt);
2191        u.add_type(Atomic::TLiteralInt(42));
2192        assert_eq!(u.types.len(), 1);
2193        assert!(matches!(u.types[0], Atomic::TInt));
2194    }
2195
2196    #[test]
2197    fn true_then_false_merges_to_bool() {
2198        let mut u = Type::single(Atomic::TTrue);
2199        u.add_type(Atomic::TFalse);
2200        assert_eq!(u.types.len(), 1);
2201        assert!(matches!(u.types[0], Atomic::TBool));
2202    }
2203
2204    #[test]
2205    fn false_then_true_merges_to_bool() {
2206        let mut u = Type::single(Atomic::TFalse);
2207        u.add_type(Atomic::TTrue);
2208        assert_eq!(u.types.len(), 1);
2209        assert!(matches!(u.types[0], Atomic::TBool));
2210    }
2211
2212    #[test]
2213    fn true_alone_stays_true() {
2214        let u = Type::single(Atomic::TTrue);
2215        assert_eq!(u.types.len(), 1);
2216        assert!(matches!(u.types[0], Atomic::TTrue));
2217    }
2218
2219    #[test]
2220    fn true_false_merge_preserves_other_union_members() {
2221        let mut u = Type::single(Atomic::TTrue);
2222        u.add_type(Atomic::TNull);
2223        u.add_type(Atomic::TFalse);
2224        assert_eq!(u.types.len(), 2);
2225        assert!(u.contains(|t| matches!(t, Atomic::TBool)));
2226        assert!(u.contains(|t| matches!(t, Atomic::TNull)));
2227    }
2228
2229    #[test]
2230    fn add_type_base_widens_literals() {
2231        let mut u = Type::single(Atomic::TLiteralInt(1));
2232        u.add_type(Atomic::TLiteralInt(2));
2233        u.add_type(Atomic::TInt);
2234        assert_eq!(u.types.len(), 1);
2235        assert!(matches!(u.types[0], Atomic::TInt));
2236    }
2237
2238    #[test]
2239    fn mixed_subsumes_everything() {
2240        let mut u = Type::single(Atomic::TString);
2241        u.add_type(Atomic::TMixed);
2242        assert_eq!(u.types.len(), 1);
2243        assert!(u.is_mixed());
2244    }
2245
2246    #[test]
2247    fn remove_null() {
2248        let u = Type::nullable(Atomic::TString);
2249        let narrowed = u.remove_null();
2250        assert!(!narrowed.is_nullable());
2251        assert_eq!(narrowed.types.len(), 1);
2252    }
2253
2254    #[test]
2255    fn narrow_to_truthy_removes_null_false() {
2256        let mut u = Type::empty();
2257        u.add_type(Atomic::TString);
2258        u.add_type(Atomic::TNull);
2259        u.add_type(Atomic::TFalse);
2260        let truthy = u.narrow_to_truthy();
2261        assert!(!truthy.is_nullable());
2262        assert!(!truthy.contains(|t| matches!(t, Atomic::TFalse)));
2263    }
2264
2265    #[test]
2266    fn merge_combines_types() {
2267        let a = Type::single(Atomic::TString);
2268        let b = Type::single(Atomic::TInt);
2269        let merged = Type::merge(&a, &b);
2270        assert_eq!(merged.types.len(), 2);
2271    }
2272
2273    #[test]
2274    fn intersect_keeps_narrower_side_not_self() {
2275        // int ∩ (1|2) must keep the narrower `1|2`, not the wider `int` —
2276        // this is exactly what a `match ($x) { 1, 2 => ... }` arm relies on
2277        // to narrow $x inside its body.
2278        let int_ty = Type::single(Atomic::TInt);
2279        let mut literals = Type::empty();
2280        literals.add_type(Atomic::TLiteralInt(1));
2281        literals.add_type(Atomic::TLiteralInt(2));
2282
2283        let narrowed = int_ty.intersect_with(&literals);
2284        assert_eq!(narrowed.types.len(), 2);
2285        assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(1))));
2286        assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(2))));
2287        assert!(!narrowed.contains(|t| matches!(t, Atomic::TInt)));
2288    }
2289
2290    #[test]
2291    fn subtype_literal_int_under_int() {
2292        let sub = Type::single(Atomic::TLiteralInt(5));
2293        let sup = Type::single(Atomic::TInt);
2294        assert!(sub.is_subtype_structural(&sup));
2295    }
2296
2297    #[test]
2298    fn subtype_never_is_bottom() {
2299        let never = Type::never();
2300        let string = Type::single(Atomic::TString);
2301        assert!(never.is_subtype_structural(&string));
2302    }
2303
2304    #[test]
2305    fn subtype_everything_under_mixed() {
2306        let string = Type::single(Atomic::TString);
2307        let mixed = Type::mixed();
2308        assert!(string.is_subtype_structural(&mixed));
2309    }
2310
2311    #[test]
2312    fn subtype_enum_case_under_own_enum() {
2313        let sub = Type::single(Atomic::TLiteralEnumCase {
2314            enum_fqcn: Name::new("RoundingMode"),
2315            case_name: Name::new("Unnecessary"),
2316        });
2317        let sup = Type::single(Atomic::TNamedObject {
2318            fqcn: Name::new("RoundingMode"),
2319            type_params: empty_type_params(),
2320        });
2321        assert!(sub.is_subtype_structural(&sup));
2322    }
2323
2324    #[test]
2325    fn enum_case_not_subtype_of_unrelated_enum() {
2326        let sub = Type::single(Atomic::TLiteralEnumCase {
2327            enum_fqcn: Name::new("RoundingMode"),
2328            case_name: Name::new("Unnecessary"),
2329        });
2330        let sup = Type::single(Atomic::TNamedObject {
2331            fqcn: Name::new("Suit"),
2332            type_params: empty_type_params(),
2333        });
2334        assert!(!sub.is_subtype_structural(&sup));
2335    }
2336
2337    #[test]
2338    fn subtype_enum_case_under_bare_object() {
2339        let sub = Type::single(Atomic::TLiteralEnumCase {
2340            enum_fqcn: Name::new("RoundingMode"),
2341            case_name: Name::new("Unnecessary"),
2342        });
2343        let sup = Type::single(Atomic::TObject);
2344        assert!(sub.is_subtype_structural(&sup));
2345    }
2346
2347    #[test]
2348    fn template_substitution() {
2349        let mut bindings = FxHashMap::default();
2350        bindings.insert(Name::new("T"), Type::single(Atomic::TString));
2351
2352        let tmpl = Type::single(Atomic::TTemplateParam {
2353            name: Name::new("T"),
2354            as_type: Box::new(Type::mixed()),
2355            defining_entity: Name::new("MyClass"),
2356        });
2357
2358        let resolved = tmpl.substitute_templates(&bindings);
2359        assert_eq!(resolved.types.len(), 1);
2360        assert!(matches!(resolved.types[0], Atomic::TString));
2361    }
2362
2363    #[test]
2364    fn intersection_is_object() {
2365        let parts = vec![
2366            Type::single(Atomic::TNamedObject {
2367                fqcn: Name::new("Iterator"),
2368                type_params: empty_type_params(),
2369            }),
2370            Type::single(Atomic::TNamedObject {
2371                fqcn: Name::new("Countable"),
2372                type_params: empty_type_params(),
2373            }),
2374        ];
2375        let atomic = Atomic::TIntersection {
2376            parts: vec_to_type_params(parts),
2377        };
2378        assert!(atomic.is_object());
2379        assert!(!atomic.can_be_falsy());
2380        assert!(atomic.can_be_truthy());
2381    }
2382
2383    #[test]
2384    fn intersection_display_two_parts() {
2385        let parts = vec![
2386            Type::single(Atomic::TNamedObject {
2387                fqcn: Name::new("Iterator"),
2388                type_params: empty_type_params(),
2389            }),
2390            Type::single(Atomic::TNamedObject {
2391                fqcn: Name::new("Countable"),
2392                type_params: empty_type_params(),
2393            }),
2394        ];
2395        let u = Type::single(Atomic::TIntersection {
2396            parts: vec_to_type_params(parts),
2397        });
2398        assert_eq!(format!("{u}"), "Iterator&Countable");
2399    }
2400
2401    #[test]
2402    fn intersection_display_three_parts() {
2403        let parts = vec![
2404            Type::single(Atomic::TNamedObject {
2405                fqcn: Name::new("A"),
2406                type_params: empty_type_params(),
2407            }),
2408            Type::single(Atomic::TNamedObject {
2409                fqcn: Name::new("B"),
2410                type_params: empty_type_params(),
2411            }),
2412            Type::single(Atomic::TNamedObject {
2413                fqcn: Name::new("C"),
2414                type_params: empty_type_params(),
2415            }),
2416        ];
2417        let u = Type::single(Atomic::TIntersection {
2418            parts: vec_to_type_params(parts),
2419        });
2420        assert_eq!(format!("{u}"), "A&B&C");
2421    }
2422
2423    #[test]
2424    fn intersection_in_nullable_union_display() {
2425        let intersection = Atomic::TIntersection {
2426            parts: vec_to_type_params(vec![
2427                Type::single(Atomic::TNamedObject {
2428                    fqcn: Name::new("Iterator"),
2429                    type_params: empty_type_params(),
2430                }),
2431                Type::single(Atomic::TNamedObject {
2432                    fqcn: Name::new("Countable"),
2433                    type_params: empty_type_params(),
2434                }),
2435            ]),
2436        };
2437        let mut u = Type::single(intersection);
2438        u.add_type(Atomic::TNull);
2439        assert!(u.is_nullable());
2440        assert!(u.contains(|t| matches!(t, Atomic::TIntersection { .. })));
2441    }
2442
2443    // --- substitute_templates coverage for previously-missing arms ----------
2444
2445    fn t_param(name: &str) -> Type {
2446        Type::single(Atomic::TTemplateParam {
2447            name: Name::new(name),
2448            as_type: Box::new(Type::mixed()),
2449            defining_entity: Name::new("Fn"),
2450        })
2451    }
2452
2453    fn bindings_t_string() -> FxHashMap<Name, Type> {
2454        let mut b = FxHashMap::default();
2455        b.insert(Name::new("T"), Type::single(Atomic::TString));
2456        b
2457    }
2458
2459    #[test]
2460    fn substitute_non_empty_array_key_and_value() {
2461        let ty = Type::single(Atomic::TNonEmptyArray {
2462            key: Box::new(t_param("T")),
2463            value: Box::new(t_param("T")),
2464        });
2465        let result = ty.substitute_templates(&bindings_t_string());
2466        assert_eq!(result.types.len(), 1);
2467        let Atomic::TNonEmptyArray { key, value } = &result.types[0] else {
2468            panic!("expected TNonEmptyArray");
2469        };
2470        assert!(matches!(key.types[0], Atomic::TString));
2471        assert!(matches!(value.types[0], Atomic::TString));
2472    }
2473
2474    #[test]
2475    fn substitute_non_empty_list_value() {
2476        let ty = Type::single(Atomic::TNonEmptyList {
2477            value: Box::new(t_param("T")),
2478        });
2479        let result = ty.substitute_templates(&bindings_t_string());
2480        let Atomic::TNonEmptyList { value } = &result.types[0] else {
2481            panic!("expected TNonEmptyList");
2482        };
2483        assert!(matches!(value.types[0], Atomic::TString));
2484    }
2485
2486    #[test]
2487    fn substitute_keyed_array_property_types() {
2488        use crate::atomic::{ArrayKey, KeyedProperty};
2489        use indexmap::IndexMap;
2490        let mut props = IndexMap::new();
2491        props.insert(
2492            ArrayKey::String(Arc::from("name")),
2493            KeyedProperty {
2494                ty: t_param("T"),
2495                optional: false,
2496            },
2497        );
2498        props.insert(
2499            ArrayKey::String(Arc::from("tag")),
2500            KeyedProperty {
2501                ty: t_param("T"),
2502                optional: true,
2503            },
2504        );
2505        let ty = Type::single(Atomic::TKeyedArray {
2506            properties: Box::new(props),
2507            is_open: true,
2508            is_list: false,
2509        });
2510        let result = ty.substitute_templates(&bindings_t_string());
2511        let Atomic::TKeyedArray {
2512            properties,
2513            is_open,
2514            is_list,
2515        } = &result.types[0]
2516        else {
2517            panic!("expected TKeyedArray");
2518        };
2519        assert!(is_open);
2520        assert!(!is_list);
2521        assert!(matches!(
2522            properties[&ArrayKey::String(Arc::from("name"))].ty.types[0],
2523            Atomic::TString
2524        ));
2525        assert!(properties[&ArrayKey::String(Arc::from("tag"))].optional);
2526        assert!(matches!(
2527            properties[&ArrayKey::String(Arc::from("tag"))].ty.types[0],
2528            Atomic::TString
2529        ));
2530    }
2531
2532    #[test]
2533    fn substitute_callable_params_and_return() {
2534        use crate::atomic::FnParam;
2535        let ty = Type::single(Atomic::TCallable {
2536            params: Some(Box::new([FnParam {
2537                name: Name::new("x"),
2538                ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
2539                out_ty: None,
2540                default: None,
2541                is_variadic: false,
2542                is_byref: false,
2543                is_optional: false,
2544            }])),
2545            return_type: Some(Box::new(t_param("T"))),
2546        });
2547        let result = ty.substitute_templates(&bindings_t_string());
2548        let Atomic::TCallable {
2549            params,
2550            return_type,
2551        } = &result.types[0]
2552        else {
2553            panic!("expected TCallable");
2554        };
2555        let param_ty = params.as_ref().unwrap()[0].ty.as_ref().unwrap();
2556        let param_union = param_ty.to_union();
2557        assert!(matches!(param_union.types[0], Atomic::TString));
2558        let ret = return_type.as_ref().unwrap();
2559        assert!(matches!(ret.types[0], Atomic::TString));
2560    }
2561
2562    #[test]
2563    fn substitute_callable_bare_no_panic() {
2564        // callable with no params/return — must not panic and must pass through unchanged
2565        let ty = Type::single(Atomic::TCallable {
2566            params: None,
2567            return_type: None,
2568        });
2569        let result = ty.substitute_templates(&bindings_t_string());
2570        assert!(matches!(
2571            result.types[0],
2572            Atomic::TCallable {
2573                params: None,
2574                return_type: None
2575            }
2576        ));
2577    }
2578
2579    #[test]
2580    fn substitute_closure_params_return_and_this() {
2581        use crate::atomic::FnParam;
2582        let ty = Type::single(Atomic::TClosure {
2583            data: Box::new(crate::atomic::ClosureData {
2584                params: Box::new([FnParam {
2585                    name: Name::new("a"),
2586                    ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
2587                    out_ty: None,
2588                    default: Some(crate::compact::SimpleType::from_union(t_param("T"))),
2589                    is_variadic: true,
2590                    is_byref: true,
2591                    is_optional: true,
2592                }]),
2593                return_type: t_param("T"),
2594                this_type: Some(t_param("T")),
2595            }),
2596        });
2597        let result = ty.substitute_templates(&bindings_t_string());
2598        let Atomic::TClosure { data } = &result.types[0] else {
2599            panic!("expected TClosure");
2600        };
2601        let (params, return_type, this_type) = (&data.params, &data.return_type, &data.this_type);
2602        let p = &params[0];
2603        let ty_union = p.ty.as_ref().unwrap().to_union();
2604        let default_union = p.default.as_ref().unwrap().to_union();
2605        assert!(matches!(ty_union.types[0], Atomic::TString));
2606        assert!(matches!(default_union.types[0], Atomic::TString));
2607        // flags preserved
2608        assert!(p.is_variadic);
2609        assert!(p.is_byref);
2610        assert!(p.is_optional);
2611        assert!(matches!(return_type.types[0], Atomic::TString));
2612        assert!(matches!(
2613            this_type.as_ref().unwrap().types[0],
2614            Atomic::TString
2615        ));
2616    }
2617
2618    #[test]
2619    fn substitute_conditional_all_branches() {
2620        let ty = Type::single(conditional(
2621            None,
2622            t_param("T"),
2623            t_param("T"),
2624            Type::single(Atomic::TInt),
2625        ));
2626        let result = ty.substitute_templates(&bindings_t_string());
2627        let Atomic::TConditional { data } = &result.types[0] else {
2628            panic!("expected TConditional");
2629        };
2630        let (subject, if_true, if_false) = (&data.subject, &data.if_true, &data.if_false);
2631        assert!(matches!(subject.types[0], Atomic::TString));
2632        assert!(matches!(if_true.types[0], Atomic::TString));
2633        assert!(matches!(if_false.types[0], Atomic::TInt));
2634    }
2635
2636    #[test]
2637    fn resolve_conditional_is_null_non_null_arg() {
2638        let ty = Type::single(conditional(
2639            Some(Name::new("x")),
2640            Type::single(Atomic::TNull),
2641            Type::single(Atomic::TInt),
2642            Type::single(Atomic::TString),
2643        ));
2644        let result = ty.resolve_conditional_returns(|name| {
2645            if name == "x" {
2646                Some(Type::single(Atomic::TString)) // definitely not null
2647            } else {
2648                None
2649            }
2650        });
2651        assert!(result.types.len() == 1);
2652        assert!(matches!(result.types[0], Atomic::TString));
2653    }
2654
2655    #[test]
2656    fn resolve_conditional_is_null_null_arg() {
2657        let ty = Type::single(conditional(
2658            Some(Name::new("x")),
2659            Type::single(Atomic::TNull),
2660            Type::single(Atomic::TInt),
2661            Type::single(Atomic::TString),
2662        ));
2663        let result = ty.resolve_conditional_returns(|name| {
2664            if name == "x" {
2665                Some(Type::single(Atomic::TNull)) // definitely null
2666            } else {
2667                None
2668            }
2669        });
2670        assert!(result.types.len() == 1);
2671        assert!(matches!(result.types[0], Atomic::TInt));
2672    }
2673
2674    #[test]
2675    fn resolve_conditional_is_null_nullable_arg_widens_to_branch_union() {
2676        let mut nullable_str = Type::single(Atomic::TString);
2677        nullable_str.add_type(Atomic::TNull);
2678        let ty = Type::single(conditional(
2679            Some(Name::new("x")),
2680            Type::single(Atomic::TNull),
2681            Type::single(Atomic::TInt),
2682            Type::single(Atomic::TString),
2683        ));
2684        let result = ty.resolve_conditional_returns(|name| {
2685            if name == "x" {
2686                Some(nullable_str.clone())
2687            } else {
2688                None
2689            }
2690        });
2691        // uncertain discriminator → widen to if_true | if_false
2692        assert_eq!(result.types.len(), 2);
2693        assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
2694        assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
2695    }
2696
2697    #[test]
2698    fn resolve_conditional_nested_widens_inner_branch() {
2699        // ($x is null ? int : ($x is string ? string : float))
2700        // When $x is unknown, should widen to int|string|float (no TConditional remaining).
2701        let inner = Type::single(conditional(
2702            Some(Name::new("x")),
2703            Type::single(Atomic::TString),
2704            Type::single(Atomic::TString),
2705            Type::single(Atomic::TFloat),
2706        ));
2707        let ty = Type::single(conditional(
2708            Some(Name::new("x")),
2709            Type::single(Atomic::TNull),
2710            Type::single(Atomic::TInt),
2711            inner,
2712        ));
2713        // unknown arg → widen both outer branches, inner conditional must also be widened
2714        let result = ty.resolve_conditional_returns(|_| None);
2715        assert!(
2716            result
2717                .types
2718                .iter()
2719                .all(|t| !matches!(t, Atomic::TConditional { .. })),
2720            "no TConditional should survive: {:?}",
2721            result.types
2722        );
2723        assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
2724        assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
2725        assert!(result.types.iter().any(|t| matches!(t, Atomic::TFloat)));
2726    }
2727
2728    #[test]
2729    fn resolve_conditional_nested_resolves_inner_branch() {
2730        // ($x is null ? int : ($x is string ? string : float))
2731        // When $x is definitely not null but unknown string-or-not → resolves outer to inner,
2732        // then inner must also be resolved.
2733        let inner = Type::single(conditional(
2734            Some(Name::new("x")),
2735            Type::single(Atomic::TString),
2736            Type::single(Atomic::TString),
2737            Type::single(Atomic::TFloat),
2738        ));
2739        let ty = Type::single(conditional(
2740            Some(Name::new("x")),
2741            Type::single(Atomic::TNull),
2742            Type::single(Atomic::TInt),
2743            inner,
2744        ));
2745        // $x = string → outer: not null → if_false (inner); inner: is string → if_true = string
2746        let result = ty.resolve_conditional_returns(|name| {
2747            if name == "x" {
2748                Some(Type::single(Atomic::TString))
2749            } else {
2750                None
2751            }
2752        });
2753        assert!(
2754            result
2755                .types
2756                .iter()
2757                .all(|t| !matches!(t, Atomic::TConditional { .. })),
2758            "no TConditional should survive: {:?}",
2759            result.types
2760        );
2761        assert_eq!(result.types.len(), 1);
2762        assert!(matches!(result.types[0], Atomic::TString));
2763    }
2764
2765    #[test]
2766    fn substitute_intersection_parts() {
2767        let ty = Type::single(Atomic::TIntersection {
2768            parts: vec_to_type_params(vec![
2769                Type::single(Atomic::TNamedObject {
2770                    fqcn: Name::new("Countable"),
2771                    type_params: empty_type_params(),
2772                }),
2773                t_param("T"),
2774            ]),
2775        });
2776        let result = ty.substitute_templates(&bindings_t_string());
2777        let Atomic::TIntersection { parts } = &result.types[0] else {
2778            panic!("expected TIntersection");
2779        };
2780        assert_eq!(parts.len(), 2);
2781        assert!(matches!(parts[0].types[0], Atomic::TNamedObject { .. }));
2782        assert!(matches!(parts[1].types[0], Atomic::TString));
2783    }
2784
2785    #[test]
2786    fn substitute_no_template_params_identity() {
2787        let ty = Type::single(Atomic::TInt);
2788        let result = ty.substitute_templates(&bindings_t_string());
2789        assert!(matches!(result.types[0], Atomic::TInt));
2790    }
2791}