Skip to main content

mago_codex/ttype/
mod.rs

1use std::borrow::Cow;
2use std::rc::Rc;
3use std::sync::Arc;
4
5use mago_word::Word;
6use mago_word::word;
7
8use crate::metadata::CodebaseMetadata;
9use crate::metadata::class_like::ClassLikeMetadata;
10use crate::misc::GenericParent;
11use crate::ttype::atomic::TAtomic;
12use crate::ttype::atomic::array::TArray;
13use crate::ttype::atomic::array::keyed::TKeyedArray;
14use crate::ttype::atomic::array::list::TList;
15use crate::ttype::atomic::generic::TGenericParameter;
16use crate::ttype::atomic::object::TObject;
17use crate::ttype::atomic::object::named::TNamedObject;
18use crate::ttype::atomic::scalar::TScalar;
19use crate::ttype::atomic::scalar::class_like_string::TClassLikeString;
20use crate::ttype::atomic::scalar::class_like_string::TClassLikeStringKind;
21use crate::ttype::atomic::scalar::int::TInteger;
22use crate::ttype::atomic::scalar::string::TString;
23use crate::ttype::atomic::scalar::string::TStringCasing;
24use crate::ttype::atomic::scalar::string::TStringLiteral;
25use crate::ttype::comparator::ComparisonResult;
26use crate::ttype::comparator::union_comparator;
27use crate::ttype::expander::StaticClassType;
28use crate::ttype::expander::TypeExpansionOptions;
29use crate::ttype::flags::UnionFlags;
30use crate::ttype::resolution::TypeResolutionContext;
31use crate::ttype::shared::ARRAYKEY_ATOMIC;
32use crate::ttype::shared::BOOL_ATOMIC;
33use crate::ttype::shared::CALLABLE_STRING_ATOMIC;
34use crate::ttype::shared::CLASS_STRING_ATOMIC;
35use crate::ttype::shared::CLOSED_RESOURCE_ATOMIC;
36use crate::ttype::shared::EMPTY_ATOMIC_SLICE;
37use crate::ttype::shared::EMPTY_KEYED_ARRAY_ATOMIC;
38use crate::ttype::shared::EMPTY_SCALAR_ATOMIC_SLICE;
39use crate::ttype::shared::EMPTY_STRING_ATOMIC;
40use crate::ttype::shared::FALSE_ATOMIC;
41use crate::ttype::shared::FLOAT_ATOMIC;
42use crate::ttype::shared::INT_ATOMIC;
43use crate::ttype::shared::INT_FLOAT_ATOMIC_SLICE;
44use crate::ttype::shared::INT_STRING_ATOMIC_SLICE;
45use crate::ttype::shared::ISSET_FROM_LOOP_MIXED_ATOMIC;
46use crate::ttype::shared::LOWERCASE_CALLABLE_STRING_ATOMIC;
47use crate::ttype::shared::LOWERCASE_STRING_ATOMIC;
48use crate::ttype::shared::MINUS_ONE_INT_ATOMIC;
49use crate::ttype::shared::MIXED_ATOMIC;
50use crate::ttype::shared::MIXED_CALLABLE_ATOMIC;
51use crate::ttype::shared::MIXED_CLOSURE_ATOMIC;
52use crate::ttype::shared::MIXED_ITERABLE_ATOMIC;
53use crate::ttype::shared::NEGATIVE_INT_ATOMIC;
54use crate::ttype::shared::NEVER_ATOMIC;
55use crate::ttype::shared::NON_EMPTY_LOWERCASE_STRING_ATOMIC;
56use crate::ttype::shared::NON_EMPTY_STRING_ATOMIC;
57use crate::ttype::shared::NON_EMPTY_UNSPECIFIED_LITERAL_STRING_ATOMIC;
58use crate::ttype::shared::NON_EMPTY_UPPERCASE_STRING_ATOMIC;
59use crate::ttype::shared::NON_NEGATIVE_INT_ATOMIC;
60use crate::ttype::shared::NON_POSITIVE_INT_ATOMIC;
61use crate::ttype::shared::NULL_ATOMIC;
62use crate::ttype::shared::NULL_FLOAT_ATOMIC_SLICE;
63use crate::ttype::shared::NULL_INT_ATOMIC_SLICE;
64use crate::ttype::shared::NULL_OBJECT_ATOMIC_SLICE;
65use crate::ttype::shared::NULL_SCALAR_ATOMIC_SLICE;
66use crate::ttype::shared::NULL_STRING_ATOMIC_SLICE;
67use crate::ttype::shared::NUMERIC_ATOMIC;
68use crate::ttype::shared::NUMERIC_STRING_ATOMIC;
69use crate::ttype::shared::NUMERIC_TRUTHY_STRING_ATOMIC;
70use crate::ttype::shared::OBJECT_ATOMIC;
71use crate::ttype::shared::ONE_INT_ATOMIC;
72use crate::ttype::shared::OPEN_RESOURCE_ATOMIC;
73use crate::ttype::shared::PLACEHOLDER_ATOMIC;
74use crate::ttype::shared::POSITIVE_INT_ATOMIC;
75use crate::ttype::shared::RESOURCE_ATOMIC;
76use crate::ttype::shared::SCALAR_ATOMIC;
77use crate::ttype::shared::SIGNUM_RESULT_SLICE;
78use crate::ttype::shared::STRING_ATOMIC;
79use crate::ttype::shared::TRUE_ATOMIC;
80use crate::ttype::shared::TRUTHY_LOWERCASE_STRING_ATOMIC;
81use crate::ttype::shared::TRUTHY_MIXED_ATOMIC;
82use crate::ttype::shared::TRUTHY_STRING_ATOMIC;
83use crate::ttype::shared::TRUTHY_UPPERCASE_STRING_ATOMIC;
84use crate::ttype::shared::UNSPECIFIED_LITERAL_FLOAT_ATOMIC;
85use crate::ttype::shared::UNSPECIFIED_LITERAL_INT_ATOMIC;
86use crate::ttype::shared::UNSPECIFIED_LITERAL_STRING_ATOMIC;
87use crate::ttype::shared::UPPERCASE_CALLABLE_STRING_ATOMIC;
88use crate::ttype::shared::UPPERCASE_STRING_ATOMIC;
89use crate::ttype::shared::VOID_ATOMIC;
90use crate::ttype::shared::ZERO_INT_ATOMIC;
91use crate::ttype::template::TemplateResult;
92use crate::ttype::template::inferred_type_replacer;
93use crate::ttype::union::TUnion;
94
95pub mod atomic;
96pub mod builder;
97pub mod cast;
98pub mod combination;
99pub mod combiner;
100pub mod comparator;
101pub mod display;
102pub mod error;
103pub mod expander;
104pub mod flags;
105pub mod resolution;
106pub mod shared;
107pub mod template;
108pub mod union;
109
110/// A reference to a type in the type system, which can be either a union or an atomic type.
111#[derive(Clone, Copy, Debug)]
112pub enum TypeRef<'ty> {
113    Union(&'ty TUnion),
114    Atomic(&'ty TAtomic),
115}
116
117/// A trait to be implemented by all types in the type system.
118pub trait TType {
119    /// Returns a vector of child type nodes that this type contains.
120    fn get_child_nodes(&self) -> Vec<TypeRef<'_>> {
121        let mut children = Vec::new();
122        self.append_child_nodes(&mut children);
123        children
124    }
125
126    /// Appends direct children without allocating a separate vector.
127    fn append_child_nodes<'types>(&'types self, _children: &mut Vec<TypeRef<'types>>) {}
128
129    /// Returns a vector of all child type nodes, including nested ones.
130    fn get_all_child_nodes(&self) -> Vec<TypeRef<'_>> {
131        let mut child_nodes = self.get_child_nodes();
132        let mut all_child_nodes = Vec::with_capacity(16);
133
134        while let Some(child_node) = child_nodes.pop() {
135            match child_node {
136                TypeRef::Union(union) => union.append_child_nodes(&mut child_nodes),
137                TypeRef::Atomic(atomic) => atomic.append_child_nodes(&mut child_nodes),
138            }
139            all_child_nodes.push(child_node);
140        }
141
142        all_child_nodes
143    }
144
145    /// Checks child type nodes in depth-first order, stopping at the first match.
146    fn any_child_node(&self, mut predicate: impl FnMut(TypeRef<'_>) -> bool) -> bool
147    where
148        Self: Sized,
149    {
150        let mut child_nodes = self.get_child_nodes();
151
152        while let Some(child_node) = child_nodes.pop() {
153            if predicate(child_node) {
154                return true;
155            }
156
157            match child_node {
158                TypeRef::Union(union) => union.append_child_nodes(&mut child_nodes),
159                TypeRef::Atomic(atomic) => atomic.append_child_nodes(&mut child_nodes),
160            }
161        }
162
163        false
164    }
165
166    /// Checks if this type can have intersection types (`&B&S`).
167    fn can_be_intersected(&self) -> bool {
168        false
169    }
170
171    /// Returns a slice of the additional intersection types (`&B&S`), if any. Contains boxed atomic types.
172    fn get_intersection_types(&self) -> Option<&[TAtomic]> {
173        None
174    }
175
176    /// Returns a mutable slice of the additional intersection types (`&B&S`), if any. Contains boxed atomic types.
177    fn get_intersection_types_mut(&mut self) -> Option<&mut Vec<TAtomic>> {
178        None
179    }
180
181    /// Checks if this type has intersection types.
182    fn has_intersection_types(&self) -> bool {
183        false
184    }
185
186    /// Adds an intersection type to this type.
187    ///
188    /// Returns `true` if the intersection type was added successfully,
189    ///  or `false` if this type does not support intersection types.
190    fn add_intersection_type(&mut self, _intersection_type: TAtomic) -> bool {
191        false
192    }
193
194    fn needs_population(&self) -> bool {
195        false
196    }
197
198    fn is_expandable(&self) -> bool {
199        false
200    }
201
202    /// Returns true if this type has complex structure that benefits from
203    /// multiline formatting when used as a generic parameter.
204    fn is_complex(&self) -> bool {
205        false
206    }
207
208    /// Return a human-readable atom for this type, which is
209    /// suitable for use in error messages or debugging.
210    ///
211    /// The resulting identifier must be unique for the type,
212    /// but it does not have to be globally unique.
213    fn get_id(&self) -> Word;
214
215    fn get_pretty_id(&self) -> Word {
216        self.get_pretty_id_with_indent(0)
217    }
218
219    fn get_pretty_id_with_indent(&self, _indent: usize) -> Word {
220        self.get_id()
221    }
222}
223
224/// Implements the `TType` trait for `TypeRef`.
225impl<'ty> TType for TypeRef<'ty> {
226    fn get_child_nodes(&self) -> Vec<TypeRef<'ty>> {
227        match self {
228            TypeRef::Union(ttype) => ttype.get_child_nodes(),
229            TypeRef::Atomic(ttype) => ttype.get_child_nodes(),
230        }
231    }
232
233    fn append_child_nodes<'types>(&'types self, children: &mut Vec<TypeRef<'types>>) {
234        match self {
235            TypeRef::Union(ttype) => ttype.append_child_nodes(children),
236            TypeRef::Atomic(ttype) => ttype.append_child_nodes(children),
237        }
238    }
239
240    fn can_be_intersected(&self) -> bool {
241        match self {
242            TypeRef::Union(ttype) => ttype.can_be_intersected(),
243            TypeRef::Atomic(ttype) => ttype.can_be_intersected(),
244        }
245    }
246
247    fn get_intersection_types(&self) -> Option<&[TAtomic]> {
248        match self {
249            TypeRef::Union(ttype) => ttype.get_intersection_types(),
250            TypeRef::Atomic(ttype) => ttype.get_intersection_types(),
251        }
252    }
253
254    fn has_intersection_types(&self) -> bool {
255        match self {
256            TypeRef::Union(ttype) => ttype.has_intersection_types(),
257            TypeRef::Atomic(ttype) => ttype.has_intersection_types(),
258        }
259    }
260
261    fn needs_population(&self) -> bool {
262        match self {
263            TypeRef::Union(ttype) => ttype.needs_population(),
264            TypeRef::Atomic(ttype) => ttype.needs_population(),
265        }
266    }
267
268    fn is_expandable(&self) -> bool {
269        match self {
270            TypeRef::Union(ttype) => ttype.is_expandable(),
271            TypeRef::Atomic(ttype) => ttype.is_expandable(),
272        }
273    }
274
275    fn is_complex(&self) -> bool {
276        match self {
277            TypeRef::Union(ttype) => ttype.is_complex(),
278            TypeRef::Atomic(ttype) => ttype.is_complex(),
279        }
280    }
281
282    fn get_id(&self) -> Word {
283        match self {
284            TypeRef::Union(ttype) => ttype.get_id(),
285            TypeRef::Atomic(ttype) => ttype.get_id(),
286        }
287    }
288
289    fn get_pretty_id_with_indent(&self, indent: usize) -> Word {
290        match self {
291            TypeRef::Union(ttype) => ttype.get_pretty_id_with_indent(indent),
292            TypeRef::Atomic(ttype) => ttype.get_pretty_id_with_indent(indent),
293        }
294    }
295}
296
297impl<'ty> From<&'ty TUnion> for TypeRef<'ty> {
298    fn from(reference: &'ty TUnion) -> Self {
299        TypeRef::Union(reference)
300    }
301}
302
303impl<'ty> From<&'ty TAtomic> for TypeRef<'ty> {
304    fn from(reference: &'ty TAtomic) -> Self {
305        TypeRef::Atomic(reference)
306    }
307}
308
309/// Creates a `TUnion` from a `TInteger`, using a canonical static type where possible.
310///
311/// This function is a key optimization point. It checks if the provided `TInteger`
312/// matches a common, reusable form (like "any integer" or "a positive integer").
313/// If it does, it returns a zero-allocation `TUnion` that borrows a static,
314/// shared instance.
315///
316/// For specific literal values or ranges that do not have a canonical static
317/// representation, it falls back to creating a new, owned `TUnion`, which
318/// involves a heap allocation.
319#[must_use]
320pub fn get_union_from_integer(integer: &TInteger) -> TUnion {
321    if integer.is_unspecified() {
322        return get_int();
323    }
324
325    if integer.is_positive() {
326        return get_positive_int();
327    }
328
329    if integer.is_negative() {
330        return get_negative_int();
331    }
332
333    if integer.is_non_negative() {
334        return get_non_negative_int();
335    }
336
337    if integer.is_non_positive() {
338        return get_non_positive_int();
339    }
340
341    TUnion::from_single(Cow::Owned(TAtomic::Scalar(TScalar::Integer(*integer))))
342}
343
344#[inline]
345#[must_use]
346pub fn wrap_atomic(tinner: TAtomic) -> TUnion {
347    TUnion::from_single(Cow::Owned(tinner))
348}
349
350#[inline]
351#[must_use]
352pub fn get_int() -> TUnion {
353    TUnion::from_single(Cow::Borrowed(INT_ATOMIC))
354}
355
356#[inline]
357#[must_use]
358pub fn get_positive_int() -> TUnion {
359    TUnion::from_single(Cow::Borrowed(POSITIVE_INT_ATOMIC))
360}
361
362#[inline]
363#[must_use]
364pub fn get_negative_int() -> TUnion {
365    TUnion::from_single(Cow::Borrowed(NEGATIVE_INT_ATOMIC))
366}
367
368#[inline]
369#[must_use]
370pub fn get_non_positive_int() -> TUnion {
371    TUnion::from_single(Cow::Borrowed(NON_POSITIVE_INT_ATOMIC))
372}
373
374#[inline]
375#[must_use]
376pub fn get_non_negative_int() -> TUnion {
377    TUnion::from_single(Cow::Borrowed(NON_NEGATIVE_INT_ATOMIC))
378}
379
380#[inline]
381#[must_use]
382pub fn get_non_zero_int() -> TUnion {
383    TUnion::from_vec(vec![
384        TAtomic::Scalar(TScalar::Integer(TInteger::negative())),
385        TAtomic::Scalar(TScalar::Integer(TInteger::positive())),
386    ])
387}
388
389#[inline]
390#[must_use]
391pub fn get_unspecified_literal_int() -> TUnion {
392    TUnion::from_single(Cow::Borrowed(UNSPECIFIED_LITERAL_INT_ATOMIC))
393}
394
395#[inline]
396#[must_use]
397pub fn get_unspecified_literal_float() -> TUnion {
398    TUnion::from_single(Cow::Borrowed(UNSPECIFIED_LITERAL_FLOAT_ATOMIC))
399}
400
401#[inline]
402#[must_use]
403pub fn get_int_range(from: Option<i64>, to: Option<i64>) -> TUnion {
404    let atomic = match (from, to) {
405        (Some(from), Some(to)) => TAtomic::Scalar(TScalar::Integer(TInteger::Range(from, to))),
406        (Some(from), None) => {
407            if 0 == from {
408                return get_non_negative_int();
409            }
410
411            if 1 == from {
412                return get_positive_int();
413            }
414
415            TAtomic::Scalar(TScalar::Integer(TInteger::From(from)))
416        }
417        (None, Some(to)) => {
418            if 0 == to {
419                return get_non_positive_int();
420            }
421
422            if -1 == to {
423                return get_negative_int();
424            }
425
426            TAtomic::Scalar(TScalar::Integer(TInteger::To(to)))
427        }
428        (None, None) => return get_int(),
429    };
430
431    TUnion::from_single(Cow::Owned(atomic))
432}
433
434/// Returns a zero-allocation `TUnion` for the type `-1|0|1`.
435#[inline]
436#[must_use]
437pub fn get_signum_result() -> TUnion {
438    TUnion::new(Cow::Borrowed(SIGNUM_RESULT_SLICE))
439}
440
441/// Returns a zero-allocation `TUnion` for the integer literal `1`.
442#[inline]
443#[must_use]
444pub fn get_one_int() -> TUnion {
445    TUnion::from_single(Cow::Borrowed(ONE_INT_ATOMIC))
446}
447
448/// Returns a zero-allocation `TUnion` for the integer literal `0`.
449#[inline]
450#[must_use]
451pub fn get_zero_int() -> TUnion {
452    TUnion::from_single(Cow::Borrowed(ZERO_INT_ATOMIC))
453}
454
455/// Returns a zero-allocation `TUnion` for the integer literal `-1`.
456#[inline]
457#[must_use]
458pub fn get_minus_one_int() -> TUnion {
459    TUnion::from_single(Cow::Borrowed(MINUS_ONE_INT_ATOMIC))
460}
461
462#[inline]
463#[must_use]
464pub fn get_literal_int(value: i64) -> TUnion {
465    if value == 0 {
466        return get_zero_int();
467    }
468
469    if value == 1 {
470        return get_one_int();
471    }
472
473    if value == -1 {
474        return get_minus_one_int();
475    }
476
477    TUnion::from_single(Cow::Owned(TAtomic::Scalar(TScalar::literal_int(value))))
478}
479
480#[inline]
481#[must_use]
482pub fn get_int_or_float() -> TUnion {
483    TUnion::new(Cow::Borrowed(INT_FLOAT_ATOMIC_SLICE))
484}
485
486#[inline]
487#[must_use]
488pub fn get_int_or_string() -> TUnion {
489    TUnion::new(Cow::Borrowed(INT_STRING_ATOMIC_SLICE))
490}
491
492#[inline]
493#[must_use]
494pub fn get_nullable_int() -> TUnion {
495    TUnion::new(Cow::Borrowed(NULL_INT_ATOMIC_SLICE))
496}
497
498#[inline]
499#[must_use]
500pub fn get_nullable_float() -> TUnion {
501    TUnion::new(Cow::Borrowed(NULL_FLOAT_ATOMIC_SLICE))
502}
503
504#[inline]
505#[must_use]
506pub fn get_nullable_object() -> TUnion {
507    TUnion::new(Cow::Borrowed(NULL_OBJECT_ATOMIC_SLICE))
508}
509
510#[inline]
511#[must_use]
512pub fn get_nullable_string() -> TUnion {
513    TUnion::new(Cow::Borrowed(NULL_STRING_ATOMIC_SLICE))
514}
515
516#[inline]
517#[must_use]
518pub fn get_string() -> TUnion {
519    TUnion::from_single(Cow::Borrowed(STRING_ATOMIC))
520}
521
522/// Returns a zero-allocation `TUnion` for a `string` with the specified properties.
523///
524/// This function maps all possible boolean property combinations to a canonical,
525/// static `TAtomic` instance, avoiding heap allocations for common string types.
526#[must_use]
527#[allow(clippy::fn_params_excessive_bools)]
528pub fn get_string_with_props(
529    is_numeric: bool,
530    is_truthy: bool,
531    is_non_empty: bool,
532    is_callable: bool,
533    casing: TStringCasing,
534) -> TUnion {
535    if is_callable {
536        return match casing {
537            TStringCasing::Lowercase => TUnion::from_single(Cow::Borrowed(LOWERCASE_CALLABLE_STRING_ATOMIC)),
538            TStringCasing::Uppercase => TUnion::from_single(Cow::Borrowed(UPPERCASE_CALLABLE_STRING_ATOMIC)),
539            TStringCasing::Unspecified => TUnion::from_single(Cow::Borrowed(CALLABLE_STRING_ATOMIC)),
540        };
541    }
542
543    let atomic_ref = match (is_numeric, is_truthy, is_non_empty, casing) {
544        // is_numeric = true
545        (true, true, _, _) => NUMERIC_TRUTHY_STRING_ATOMIC,
546        (true, false, _, _) => NUMERIC_STRING_ATOMIC,
547        // is_numeric = false, is_truthy = true
548        (false, true, _, TStringCasing::Unspecified) => TRUTHY_STRING_ATOMIC,
549        (false, true, _, TStringCasing::Uppercase) => TRUTHY_UPPERCASE_STRING_ATOMIC,
550        (false, true, _, TStringCasing::Lowercase) => TRUTHY_LOWERCASE_STRING_ATOMIC,
551        // is_numeric = false, is_truthy = false
552        (false, false, false, TStringCasing::Unspecified) => STRING_ATOMIC,
553        (false, false, false, TStringCasing::Uppercase) => UPPERCASE_STRING_ATOMIC,
554        (false, false, false, TStringCasing::Lowercase) => LOWERCASE_STRING_ATOMIC,
555        (false, false, true, TStringCasing::Unspecified) => NON_EMPTY_STRING_ATOMIC,
556        (false, false, true, TStringCasing::Uppercase) => NON_EMPTY_UPPERCASE_STRING_ATOMIC,
557        (false, false, true, TStringCasing::Lowercase) => NON_EMPTY_LOWERCASE_STRING_ATOMIC,
558    };
559
560    TUnion::from_single(Cow::Borrowed(atomic_ref))
561}
562
563#[inline]
564#[must_use]
565pub fn get_class_string() -> TUnion {
566    TUnion::from_single(Cow::Borrowed(CLASS_STRING_ATOMIC))
567}
568
569#[inline]
570#[must_use]
571pub fn get_literal_string(value: Word) -> TUnion {
572    TUnion::from_single(Cow::Owned(TAtomic::Scalar(TScalar::literal_string(value))))
573}
574
575#[inline]
576#[must_use]
577pub fn get_float() -> TUnion {
578    TUnion::from_single(Cow::Borrowed(FLOAT_ATOMIC))
579}
580
581#[inline]
582#[must_use]
583pub fn get_literal_float(v: f64) -> TUnion {
584    TUnion::from_single(Cow::Owned(TAtomic::Scalar(TScalar::literal_float(v))))
585}
586
587#[inline]
588#[must_use]
589pub fn get_mixed() -> TUnion {
590    TUnion::from_single(Cow::Borrowed(MIXED_ATOMIC))
591}
592
593#[inline]
594#[must_use]
595pub fn get_truthy_mixed() -> TUnion {
596    TUnion::from_single(Cow::Borrowed(TRUTHY_MIXED_ATOMIC))
597}
598
599#[inline]
600#[must_use]
601pub fn get_isset_from_mixed_mixed() -> TUnion {
602    TUnion::from_single(Cow::Borrowed(ISSET_FROM_LOOP_MIXED_ATOMIC))
603}
604
605#[must_use]
606pub fn get_mixed_maybe_from_loop(from_loop_isset: bool) -> TUnion {
607    if from_loop_isset { get_isset_from_mixed_mixed() } else { get_mixed() }
608}
609
610#[inline]
611#[must_use]
612pub fn get_never() -> TUnion {
613    TUnion::from_single(Cow::Borrowed(NEVER_ATOMIC))
614}
615
616#[inline]
617#[must_use]
618pub fn get_resource() -> TUnion {
619    TUnion::from_single(Cow::Borrowed(RESOURCE_ATOMIC))
620}
621
622#[inline]
623#[must_use]
624pub fn get_closed_resource() -> TUnion {
625    TUnion::from_single(Cow::Borrowed(CLOSED_RESOURCE_ATOMIC))
626}
627
628#[inline]
629#[must_use]
630pub fn get_open_resource() -> TUnion {
631    TUnion::from_single(Cow::Borrowed(OPEN_RESOURCE_ATOMIC))
632}
633
634#[inline]
635#[must_use]
636pub fn get_placeholder() -> TUnion {
637    TUnion::from_single(Cow::Borrowed(PLACEHOLDER_ATOMIC))
638}
639
640#[inline]
641#[must_use]
642pub fn get_void() -> TUnion {
643    TUnion::from_single(Cow::Borrowed(VOID_ATOMIC))
644}
645
646#[inline]
647#[must_use]
648pub fn get_null() -> TUnion {
649    TUnion::from_single(Cow::Borrowed(NULL_ATOMIC))
650}
651
652#[inline]
653#[must_use]
654pub fn get_undefined_null() -> TUnion {
655    let mut null = TUnion::from_single(Cow::Borrowed(NULL_ATOMIC));
656    null.set_possibly_undefined(true, None);
657    null
658}
659
660#[inline]
661#[must_use]
662pub fn get_arraykey() -> TUnion {
663    TUnion::from_single(Cow::Borrowed(ARRAYKEY_ATOMIC))
664}
665
666#[inline]
667#[must_use]
668pub fn get_bool() -> TUnion {
669    TUnion::from_single(Cow::Borrowed(BOOL_ATOMIC))
670}
671
672#[inline]
673#[must_use]
674pub fn get_false() -> TUnion {
675    TUnion::from_single(Cow::Borrowed(FALSE_ATOMIC))
676}
677
678#[inline]
679#[must_use]
680pub fn get_true() -> TUnion {
681    TUnion::from_single(Cow::Borrowed(TRUE_ATOMIC))
682}
683
684#[inline]
685#[must_use]
686pub fn get_object() -> TUnion {
687    TUnion::from_single(Cow::Borrowed(OBJECT_ATOMIC))
688}
689
690#[inline]
691#[must_use]
692pub fn get_numeric() -> TUnion {
693    TUnion::from_single(Cow::Borrowed(NUMERIC_ATOMIC))
694}
695
696#[inline]
697#[must_use]
698pub fn get_callable_string() -> TUnion {
699    TUnion::from_single(Cow::Borrowed(CALLABLE_STRING_ATOMIC))
700}
701
702#[must_use]
703pub fn get_numeric_string() -> TUnion {
704    TUnion::from_single(Cow::Borrowed(NUMERIC_STRING_ATOMIC))
705}
706
707#[inline]
708#[must_use]
709pub fn get_lowercase_string() -> TUnion {
710    TUnion::from_single(Cow::Borrowed(LOWERCASE_STRING_ATOMIC))
711}
712
713#[inline]
714#[must_use]
715pub fn get_non_empty_lowercase_string() -> TUnion {
716    TUnion::from_single(Cow::Borrowed(NON_EMPTY_LOWERCASE_STRING_ATOMIC))
717}
718
719#[inline]
720#[must_use]
721pub fn get_uppercase_string() -> TUnion {
722    TUnion::from_single(Cow::Borrowed(UPPERCASE_STRING_ATOMIC))
723}
724
725#[inline]
726#[must_use]
727pub fn get_non_empty_uppercase_string() -> TUnion {
728    TUnion::from_single(Cow::Borrowed(NON_EMPTY_UPPERCASE_STRING_ATOMIC))
729}
730
731#[inline]
732#[must_use]
733pub fn get_non_empty_string() -> TUnion {
734    TUnion::from_single(Cow::Borrowed(NON_EMPTY_STRING_ATOMIC))
735}
736
737#[inline]
738#[must_use]
739pub fn get_empty_string() -> TUnion {
740    TUnion::from_single(Cow::Borrowed(&EMPTY_STRING_ATOMIC))
741}
742
743#[inline]
744#[must_use]
745pub fn get_truthy_string() -> TUnion {
746    TUnion::from_single(Cow::Borrowed(TRUTHY_STRING_ATOMIC))
747}
748
749#[inline]
750#[must_use]
751pub fn get_unspecified_literal_string() -> TUnion {
752    TUnion::from_single(Cow::Borrowed(UNSPECIFIED_LITERAL_STRING_ATOMIC))
753}
754
755#[inline]
756#[must_use]
757pub fn get_non_empty_unspecified_literal_string() -> TUnion {
758    TUnion::from_single(Cow::Borrowed(NON_EMPTY_UNSPECIFIED_LITERAL_STRING_ATOMIC))
759}
760
761#[inline]
762#[must_use]
763pub fn get_scalar() -> TUnion {
764    TUnion::from_single(Cow::Borrowed(SCALAR_ATOMIC))
765}
766
767#[inline]
768#[must_use]
769pub fn get_nullable_scalar() -> TUnion {
770    TUnion::new(Cow::Borrowed(NULL_SCALAR_ATOMIC_SLICE))
771}
772
773#[inline]
774#[must_use]
775pub fn get_mixed_iterable() -> TUnion {
776    TUnion::from_single(Cow::Borrowed(&MIXED_ITERABLE_ATOMIC))
777}
778
779#[inline]
780#[must_use]
781pub fn get_empty_keyed_array() -> TUnion {
782    TUnion::from_single(Cow::Borrowed(&EMPTY_KEYED_ARRAY_ATOMIC))
783}
784
785/// The `empty` type: every value for which PHP's `empty()` returns true,
786/// i.e. `null|0|0.0|'0'|''|false|array{}`.
787#[inline]
788#[must_use]
789pub fn get_empty() -> TUnion {
790    TUnion::new(Cow::Borrowed(EMPTY_ATOMIC_SLICE.as_slice()))
791}
792
793/// The `empty-scalar` type: every scalar for which PHP's `empty()` returns
794/// true, i.e. `0|0.0|'0'|''|false`.
795#[inline]
796#[must_use]
797pub fn get_empty_scalar() -> TUnion {
798    TUnion::new(Cow::Borrowed(EMPTY_SCALAR_ATOMIC_SLICE.as_slice()))
799}
800
801#[inline]
802#[must_use]
803pub fn get_mixed_list() -> TUnion {
804    get_list(get_mixed())
805}
806
807#[inline]
808#[must_use]
809pub fn get_mixed_keyed_array() -> TUnion {
810    get_keyed_array(get_arraykey(), get_mixed())
811}
812
813#[inline]
814#[must_use]
815pub fn get_mixed_callable() -> TUnion {
816    TUnion::from_single(Cow::Borrowed(&MIXED_CALLABLE_ATOMIC))
817}
818
819#[inline]
820#[must_use]
821pub fn get_mixed_closure() -> TUnion {
822    TUnion::from_single(Cow::Borrowed(&MIXED_CLOSURE_ATOMIC))
823}
824
825#[inline]
826#[must_use]
827pub fn get_named_object(name: Word, type_resolution_context: Option<&TypeResolutionContext>) -> TUnion {
828    if let Some(type_resolution_context) = type_resolution_context
829        && let Some(defining_entities) = type_resolution_context.get_template_definition(name)
830    {
831        let first = &defining_entities[0];
832        return wrap_atomic(TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::Generic {
833            kind: TClassLikeStringKind::Class,
834            parameter_name: name,
835            defining_entity: first.defining_entity,
836            constraint: Arc::new((*(first.constraint.get_single())).clone()),
837        })));
838    }
839
840    wrap_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(name))))
841}
842
843#[inline]
844#[must_use]
845pub fn get_list(element_type: TUnion) -> TUnion {
846    wrap_atomic(TAtomic::Array(TArray::List(TList::new(Arc::new(element_type)))))
847}
848
849#[inline]
850#[must_use]
851pub fn get_non_empty_list(element_type: TUnion) -> TUnion {
852    wrap_atomic(TAtomic::Array(TArray::List(TList::new_non_empty(Arc::new(element_type)))))
853}
854
855#[inline]
856#[must_use]
857pub fn get_keyed_array(key_parameter: TUnion, value_parameter: TUnion) -> TUnion {
858    wrap_atomic(TAtomic::Array(TArray::Keyed(TKeyedArray::new_with_parameters(
859        Arc::new(key_parameter),
860        Arc::new(value_parameter),
861    ))))
862}
863
864#[inline]
865#[must_use]
866pub fn add_optional_union_type(base_type: TUnion, maybe_type: Option<&TUnion>, codebase: &CodebaseMetadata) -> TUnion {
867    if let Some(type_2) = maybe_type {
868        add_union_type(base_type, type_2, codebase, combiner::CombinerOptions::default())
869    } else {
870        base_type
871    }
872}
873
874/// Reference-counted variant of [`add_optional_union_type`].
875#[must_use]
876pub fn add_optional_union_type_rc(
877    base_type: &Rc<TUnion>,
878    maybe_type: Option<&TUnion>,
879    codebase: &CodebaseMetadata,
880) -> Rc<TUnion> {
881    match maybe_type {
882        Some(type_2) if base_type.as_ref() == type_2 => Rc::clone(base_type),
883        Some(type_2) => Rc::new(add_unequal_union_type_inner(
884            (**base_type).clone(),
885            type_2,
886            codebase,
887            combiner::CombinerOptions::default(),
888            false,
889        )),
890        None => Rc::clone(base_type),
891    }
892}
893
894#[inline]
895#[must_use]
896pub fn combine_optional_union_types(
897    type_1: Option<&TUnion>,
898    type_2: Option<&TUnion>,
899    codebase: &CodebaseMetadata,
900) -> TUnion {
901    match (type_1, type_2) {
902        (Some(type_1), Some(type_2)) => {
903            combine_union_types(type_1, type_2, codebase, combiner::CombinerOptions::default())
904        }
905        (Some(type_1), None) => type_1.clone(),
906        (None, Some(type_2)) => type_2.clone(),
907        (None, None) => get_mixed(),
908    }
909}
910
911/// Reference-counted variant of [`combine_union_types`].
912#[inline]
913#[must_use]
914pub fn combine_union_types_rc(
915    type_1: &Rc<TUnion>,
916    type_2: &Rc<TUnion>,
917    codebase: &CodebaseMetadata,
918    options: combiner::CombinerOptions,
919) -> Rc<TUnion> {
920    if type_1 == type_2 {
921        return Rc::clone(type_1);
922    }
923
924    Rc::new(combine_unequal_union_types_inner(type_1, type_2, codebase, options, false))
925}
926
927/// Combines types, moving the first union's atoms when it has one owner.
928#[inline]
929#[must_use]
930pub fn combine_owned_union_types_rc(
931    type_1: Rc<TUnion>,
932    type_2: &Rc<TUnion>,
933    codebase: &CodebaseMetadata,
934    options: combiner::CombinerOptions,
935) -> Rc<TUnion> {
936    if type_1 == *type_2 {
937        return type_1;
938    }
939
940    let combined = match Rc::try_unwrap(type_1) {
941        Ok(type_1) => combine_unequal_union_types_cow(Cow::Owned(type_1), type_2, codebase, options, false),
942        Err(type_1) => combine_unequal_union_types_inner(&type_1, type_2, codebase, options, false),
943    };
944
945    Rc::new(combined)
946}
947
948#[inline]
949#[must_use]
950pub fn combine_union_types(
951    type_1: &TUnion,
952    type_2: &TUnion,
953    codebase: &CodebaseMetadata,
954    options: combiner::CombinerOptions,
955) -> TUnion {
956    combine_union_types_inner(type_1, type_2, codebase, options, false)
957}
958
959#[inline]
960#[must_use]
961pub fn combine_union_types_preserving_array_shapes(
962    type_1: &TUnion,
963    type_2: &TUnion,
964    codebase: &CodebaseMetadata,
965    options: combiner::CombinerOptions,
966) -> TUnion {
967    combine_union_types_inner(type_1, type_2, codebase, options, true)
968}
969
970fn combine_union_types_inner(
971    type_1: &TUnion,
972    type_2: &TUnion,
973    codebase: &CodebaseMetadata,
974    options: combiner::CombinerOptions,
975    preserve_array_shapes: bool,
976) -> TUnion {
977    if type_1 == type_2 {
978        return type_1.clone();
979    }
980
981    combine_unequal_union_types_inner(type_1, type_2, codebase, options, preserve_array_shapes)
982}
983
984fn combine_unequal_union_types_inner(
985    type_1: &TUnion,
986    type_2: &TUnion,
987    codebase: &CodebaseMetadata,
988    options: combiner::CombinerOptions,
989    preserve_array_shapes: bool,
990) -> TUnion {
991    combine_unequal_union_types_cow(Cow::Borrowed(type_1), type_2, codebase, options, preserve_array_shapes)
992}
993
994fn combine_unequal_union_types_cow(
995    type_1: Cow<'_, TUnion>,
996    type_2: &TUnion,
997    codebase: &CodebaseMetadata,
998    options: combiner::CombinerOptions,
999    preserve_array_shapes: bool,
1000) -> TUnion {
1001    let flags_1 = type_1.flags;
1002    let mut combined_type = if type_1.is_never() || type_1.is_never_template() {
1003        type_2.clone()
1004    } else if type_2.is_never() || type_2.is_never_template() {
1005        type_1.into_owned()
1006    } else if type_1.is_vanilla_mixed() && type_2.is_vanilla_mixed() {
1007        get_mixed()
1008    } else {
1009        let mut all_atomic_types = match type_1 {
1010            Cow::Borrowed(type_1) => type_1.types.to_vec(),
1011            Cow::Owned(type_1) => type_1.types.into_owned(),
1012        };
1013
1014        all_atomic_types.extend(type_2.types.iter().cloned());
1015
1016        let types = if preserve_array_shapes {
1017            combiner::combine_preserving_array_shapes(all_atomic_types, codebase, options)
1018        } else {
1019            combiner::combine(all_atomic_types, codebase, options)
1020        };
1021
1022        let mut result = TUnion::from_vec(types);
1023
1024        if flags_1.contains(UnionFlags::HAD_TEMPLATE) && type_2.had_template() {
1025            result.set_had_template(true);
1026        }
1027
1028        if flags_1.contains(UnionFlags::REFERENCE_FREE) && type_2.reference_free() {
1029            result.set_reference_free(true);
1030        }
1031
1032        result
1033    };
1034
1035    if flags_1.contains(UnionFlags::POSSIBLY_UNDEFINED) || type_2.possibly_undefined() {
1036        combined_type.set_possibly_undefined(true, None);
1037    }
1038
1039    if flags_1.contains(UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY) || type_2.possibly_undefined_from_try() {
1040        combined_type.set_possibly_undefined_from_try(true);
1041    }
1042
1043    if flags_1.contains(UnionFlags::IGNORE_FALSABLE_ISSUES) || type_2.ignore_falsable_issues() {
1044        combined_type.set_ignore_falsable_issues(true);
1045    }
1046
1047    combined_type
1048}
1049
1050#[inline]
1051#[must_use]
1052pub fn add_union_type(
1053    base_type: TUnion,
1054    other_type: &TUnion,
1055    codebase: &CodebaseMetadata,
1056    options: combiner::CombinerOptions,
1057) -> TUnion {
1058    add_union_type_inner(base_type, other_type, codebase, options, false)
1059}
1060
1061#[inline]
1062#[must_use]
1063pub fn add_union_type_preserving_array_shapes(
1064    base_type: TUnion,
1065    other_type: &TUnion,
1066    codebase: &CodebaseMetadata,
1067    options: combiner::CombinerOptions,
1068) -> TUnion {
1069    add_union_type_inner(base_type, other_type, codebase, options, true)
1070}
1071
1072fn add_union_type_inner(
1073    base_type: TUnion,
1074    other_type: &TUnion,
1075    codebase: &CodebaseMetadata,
1076    options: combiner::CombinerOptions,
1077    preserve_array_shapes: bool,
1078) -> TUnion {
1079    if &base_type == other_type {
1080        return base_type;
1081    }
1082
1083    add_unequal_union_type_inner(base_type, other_type, codebase, options, preserve_array_shapes)
1084}
1085
1086fn add_unequal_union_type_inner(
1087    base_type: TUnion,
1088    other_type: &TUnion,
1089    codebase: &CodebaseMetadata,
1090    options: combiner::CombinerOptions,
1091    preserve_array_shapes: bool,
1092) -> TUnion {
1093    let original_flags = base_type.flags;
1094    let mut base_type = if base_type.is_vanilla_mixed() && other_type.is_vanilla_mixed() {
1095        base_type
1096    } else {
1097        combine_unequal_union_types_cow(Cow::Owned(base_type), other_type, codebase, options, preserve_array_shapes)
1098    };
1099    base_type.flags = original_flags;
1100
1101    if !other_type.had_template() {
1102        base_type.set_had_template(false);
1103    }
1104
1105    if !other_type.reference_free() {
1106        base_type.set_reference_free(false);
1107    }
1108
1109    if other_type.possibly_undefined() {
1110        base_type.set_possibly_undefined(true, None);
1111    }
1112    if other_type.possibly_undefined_from_try() {
1113        base_type.set_possibly_undefined_from_try(true);
1114    }
1115    if other_type.ignore_falsable_issues() {
1116        base_type.set_ignore_falsable_issues(true);
1117    }
1118    if other_type.ignore_nullable_issues() {
1119        base_type.set_ignore_nullable_issues(true);
1120    }
1121
1122    base_type
1123}
1124
1125#[must_use]
1126pub fn intersect_union_types(type_1: &TUnion, type_2: &TUnion, codebase: &CodebaseMetadata) -> Option<TUnion> {
1127    if type_1 == type_2 {
1128        return Some(type_1.clone());
1129    }
1130
1131    if type_1.is_never() || type_2.is_never() {
1132        return Some(get_never());
1133    }
1134
1135    let mut intersection_performed = false;
1136
1137    if type_1.is_mixed() {
1138        if type_2.is_mixed() {
1139            return Some(get_mixed());
1140        }
1141
1142        return Some(type_2.clone());
1143    } else if type_2.is_mixed() {
1144        return Some(type_1.clone());
1145    }
1146
1147    let mut intersected_atomic_types = vec![];
1148    for type_1_atomic in type_1.types.iter() {
1149        for type_2_atomic in type_2.types.iter() {
1150            if let Some(intersection_atomic) =
1151                intersect_atomic_types(type_1_atomic, type_2_atomic, codebase, &mut intersection_performed)
1152            {
1153                intersected_atomic_types.push(intersection_atomic);
1154            }
1155        }
1156    }
1157
1158    let mut combined_type: Option<TUnion> = None;
1159    if !intersected_atomic_types.is_empty() {
1160        let combined_vec = combiner::combine(intersected_atomic_types, codebase, combiner::CombinerOptions::default());
1161        if !combined_vec.is_empty() {
1162            combined_type = Some(TUnion::from_vec(combined_vec));
1163        }
1164    }
1165
1166    // If atomic-level intersection didn't yield a result, check for subtyping at the union level.
1167    if !intersection_performed {
1168        if union_comparator::is_contained_by(
1169            codebase,
1170            type_1,
1171            type_2,
1172            false,
1173            false,
1174            false,
1175            &mut ComparisonResult::default(),
1176        ) {
1177            combined_type = Some(type_1.clone());
1178        } else if union_comparator::is_contained_by(
1179            codebase,
1180            type_2,
1181            type_1,
1182            false,
1183            false,
1184            false,
1185            &mut ComparisonResult::default(),
1186        ) {
1187            combined_type = Some(type_2.clone());
1188        }
1189    }
1190
1191    if let Some(mut final_type) = combined_type {
1192        final_type.set_possibly_undefined(
1193            type_1.possibly_undefined() && type_2.possibly_undefined(),
1194            Some(type_1.possibly_undefined_from_try() && type_2.possibly_undefined_from_try()),
1195        );
1196        final_type.set_ignore_falsable_issues(type_1.ignore_falsable_issues() && type_2.ignore_falsable_issues());
1197        final_type.set_ignore_nullable_issues(type_1.ignore_nullable_issues() && type_2.ignore_nullable_issues());
1198
1199        return Some(final_type);
1200    }
1201
1202    None
1203}
1204
1205/// This is the core logic used by `intersect_union_types`.
1206fn intersect_atomic_types(
1207    type_1: &TAtomic,
1208    type_2: &TAtomic,
1209    codebase: &CodebaseMetadata,
1210    intersection_performed: &mut bool,
1211) -> Option<TAtomic> {
1212    if let (TAtomic::Scalar(TScalar::Integer(t1_int)), TAtomic::Scalar(TScalar::Integer(t2_int))) = (type_1, type_2) {
1213        let (min1, max1) = t1_int.get_bounds();
1214        let (min2, max2) = t2_int.get_bounds();
1215
1216        let new_min = match (min1, min2) {
1217            (Some(m1), Some(m2)) => Some(m1.max(m2)),
1218            (Some(m), None) | (None, Some(m)) => Some(m),
1219            (None, None) => None,
1220        };
1221
1222        let new_max = match (max1, max2) {
1223            (Some(m1), Some(m2)) => Some(m1.min(m2)),
1224            (Some(m), None) | (None, Some(m)) => Some(m),
1225            (None, None) => None,
1226        };
1227
1228        let intersected_int = if let (Some(min), Some(max)) = (new_min, new_max) {
1229            if min > max {
1230                return None;
1231            }
1232
1233            if min == max { TInteger::Literal(min) } else { TInteger::Range(min, max) }
1234        } else if let Some(min) = new_min {
1235            TInteger::From(min)
1236        } else if let Some(max) = new_max {
1237            TInteger::To(max)
1238        } else {
1239            TInteger::Unspecified
1240        };
1241
1242        *intersection_performed = true;
1243        return Some(TAtomic::Scalar(TScalar::Integer(intersected_int)));
1244    }
1245
1246    let t1_union = TUnion::from_atomic(type_1.clone());
1247    let t2_union = TUnion::from_atomic(type_2.clone());
1248
1249    let mut narrower_type = None;
1250    let mut wider_type = None;
1251
1252    if union_comparator::is_contained_by(
1253        codebase,
1254        &t2_union,
1255        &t1_union,
1256        false,
1257        false,
1258        false,
1259        &mut ComparisonResult::default(),
1260    ) {
1261        narrower_type = Some(type_2);
1262        wider_type = Some(type_1);
1263    } else if union_comparator::is_contained_by(
1264        codebase,
1265        &t1_union,
1266        &t2_union,
1267        false,
1268        false,
1269        false,
1270        &mut ComparisonResult::default(),
1271    ) {
1272        narrower_type = Some(type_1);
1273        wider_type = Some(type_2);
1274    }
1275
1276    if let (Some(narrower), Some(wider)) = (narrower_type, wider_type) {
1277        *intersection_performed = true;
1278        let mut result = narrower.clone();
1279
1280        if narrower.can_be_intersected() && wider.can_be_intersected() {
1281            let mut wider_clone = wider.clone();
1282            if let Some(types) = wider_clone.get_intersection_types_mut() {
1283                types.clear();
1284            }
1285
1286            result.add_intersection_type(wider_clone);
1287            if let Some(wider_intersections) = wider.get_intersection_types() {
1288                for i_type in wider_intersections {
1289                    result.add_intersection_type(i_type.clone());
1290                }
1291            }
1292        }
1293        return Some(result);
1294    }
1295
1296    if let (TAtomic::Array(left_array), TAtomic::Array(right_array)) = (type_1, type_2) {
1297        let array_has_known_shape = |array: &TArray| match array {
1298            TArray::List(list) => list.known_elements.is_some(),
1299            TArray::Keyed(keyed) => keyed.known_items.is_some(),
1300        };
1301
1302        if array_has_known_shape(left_array) || array_has_known_shape(right_array) {
1303            return None;
1304        }
1305
1306        let (left_key, left_value) = get_array_parameters(left_array, codebase);
1307        let (right_key, right_value) = get_array_parameters(right_array, codebase);
1308
1309        let key = intersect_union_types(&left_key, &right_key, codebase).unwrap_or_else(get_never);
1310        let value = intersect_union_types(&left_value, &right_value, codebase).unwrap_or_else(get_never);
1311
1312        let is_list = left_array.is_list() || right_array.is_list();
1313        let non_empty = left_array.is_non_empty() || right_array.is_non_empty();
1314
1315        if non_empty && (key.is_never() || value.is_never()) {
1316            return None;
1317        }
1318
1319        *intersection_performed = true;
1320        let array = if is_list {
1321            let mut list = TList::new(Arc::new(value));
1322            list.non_empty = non_empty;
1323            TArray::List(list)
1324        } else {
1325            TArray::Keyed(TKeyedArray::new_with_parameters(Arc::new(key), Arc::new(value)).with_non_empty(non_empty))
1326        };
1327
1328        return Some(TAtomic::Array(array));
1329    }
1330
1331    if let (TAtomic::Scalar(TScalar::String(s)), TAtomic::Scalar(TScalar::Numeric))
1332    | (TAtomic::Scalar(TScalar::Numeric), TAtomic::Scalar(TScalar::String(s))) = (type_1, type_2)
1333    {
1334        *intersection_performed = true;
1335        return Some(TAtomic::Scalar(TScalar::String(s.as_numeric(true))));
1336    }
1337
1338    if let (TAtomic::Scalar(TScalar::String(s1)), TAtomic::Scalar(TScalar::String(s2))) = (type_1, type_2) {
1339        if let (Some(v1), Some(v2)) = (&s1.get_known_literal_value(), &s2.get_known_literal_value())
1340            && v1 != v2
1341        {
1342            return None;
1343        }
1344
1345        let combined = TAtomic::Scalar(TScalar::String(TString {
1346            is_numeric: s1.is_numeric || s2.is_numeric,
1347            is_truthy: s1.is_truthy || s2.is_truthy,
1348            is_non_empty: s1.is_non_empty || s2.is_non_empty,
1349            is_callable: false,
1350            casing: match (s1.casing, s2.casing) {
1351                (TStringCasing::Lowercase, TStringCasing::Lowercase) => TStringCasing::Lowercase,
1352                (TStringCasing::Uppercase, TStringCasing::Uppercase) => TStringCasing::Uppercase,
1353                _ => TStringCasing::Unspecified,
1354            },
1355            literal: if s1.is_literal_origin() && s2.is_literal_origin() {
1356                Some(TStringLiteral::Unspecified)
1357            } else {
1358                None
1359            },
1360        }));
1361        *intersection_performed = true;
1362        return Some(combined);
1363    }
1364
1365    if type_1.can_be_intersected() && type_2.can_be_intersected() {
1366        if let (TAtomic::Object(TObject::Named(n1)), TAtomic::Object(TObject::Named(n2))) = (type_1, type_2)
1367            && let (Some(c1), Some(c2)) =
1368                (codebase.get_class_like(n1.name.as_bytes()), codebase.get_class_like(n2.name.as_bytes()))
1369            && !c1.kind.is_interface()
1370            && !c1.kind.is_trait()
1371            && !c2.kind.is_interface()
1372            && !c2.kind.is_trait()
1373        {
1374            return None;
1375        }
1376
1377        let mut result = type_1.clone();
1378        result.add_intersection_type(type_2.clone());
1379        if let Some(intersections) = type_2.get_intersection_types() {
1380            for i in intersections {
1381                result.add_intersection_type(i.clone());
1382            }
1383        }
1384
1385        *intersection_performed = true;
1386        return Some(result);
1387    }
1388
1389    None
1390}
1391
1392#[must_use]
1393pub fn get_iterable_parameters(atomic: &TAtomic, codebase: &CodebaseMetadata) -> Option<(TUnion, TUnion)> {
1394    get_iterable_parameters_impl(atomic, codebase, &[])
1395}
1396
1397fn get_iterable_parameters_impl(
1398    atomic: &TAtomic,
1399    codebase: &CodebaseMetadata,
1400    visited_aggregates: &[Word],
1401) -> Option<(TUnion, TUnion)> {
1402    if let Some(generator_parameters) = atomic.get_generator_parameters() {
1403        let mut key_type = generator_parameters.0;
1404        let mut value_type = generator_parameters.1;
1405
1406        expander::expand_union(codebase, &mut key_type, &TypeExpansionOptions::default());
1407        expander::expand_union(codebase, &mut value_type, &TypeExpansionOptions::default());
1408
1409        return Some((key_type, value_type));
1410    }
1411
1412    let parameters =
1413        'parameters: {
1414            match atomic {
1415                TAtomic::Iterable(iterable) => {
1416                    let mut key_type = iterable.get_key_type().clone();
1417                    let mut value_type = iterable.get_value_type().clone();
1418
1419                    expander::expand_union(codebase, &mut key_type, &TypeExpansionOptions::default());
1420                    expander::expand_union(codebase, &mut value_type, &TypeExpansionOptions::default());
1421
1422                    Some((key_type, value_type))
1423                }
1424                TAtomic::Array(array_type) => {
1425                    let (mut key_type, mut value_type) = get_array_parameters(array_type, codebase);
1426
1427                    expander::expand_union(codebase, &mut key_type, &TypeExpansionOptions::default());
1428                    expander::expand_union(codebase, &mut value_type, &TypeExpansionOptions::default());
1429
1430                    Some((key_type, value_type))
1431                }
1432                TAtomic::Object(object) => {
1433                    let name = object.get_name()?;
1434                    let traversable = word("traversable");
1435                    let iterator = word("iterator");
1436                    let iterator_aggregate = word("iteratoraggregate");
1437
1438                    let class_metadata = codebase.get_class_like(name.as_bytes())?;
1439                    let is_iterator_interface = class_metadata.name == iterator
1440                        || class_metadata.name == traversable
1441                        || class_metadata.name == iterator_aggregate;
1442
1443                    if !is_iterator_interface && !class_metadata.all_parent_interfaces.contains(&traversable) {
1444                        break 'parameters None;
1445                    }
1446
1447                    let traversable_metadata = codebase.get_class_like(traversable.as_bytes())?;
1448                    let key_template = traversable_metadata.template_types.get_index(0).map(|(name, _)| *name)?;
1449                    let value_template = traversable_metadata.template_types.get_index(1).map(|(name, _)| *name)?;
1450
1451                    let mut key_type = get_specialized_template_type(
1452                        codebase,
1453                        key_template,
1454                        traversable,
1455                        class_metadata,
1456                        object.get_type_parameters(),
1457                    )
1458                    .unwrap_or_else(get_mixed);
1459
1460                    let mut value_type = get_specialized_template_type(
1461                        codebase,
1462                        value_template,
1463                        traversable,
1464                        class_metadata,
1465                        object.get_type_parameters(),
1466                    )
1467                    .unwrap_or_else(get_mixed);
1468
1469                    resolve_unbound_generic_parameters(codebase, &mut key_type);
1470                    resolve_unbound_generic_parameters(codebase, &mut value_type);
1471
1472                    if is_iterator_interface || (!key_type.is_mixed() && !value_type.is_mixed()) {
1473                        return Some((key_type, value_type));
1474                    }
1475
1476                    if class_metadata.all_parent_interfaces.contains(&iterator) {
1477                        if key_type.is_mixed()
1478                            && let Some(method_key) = get_iterator_method_return_type(
1479                                codebase,
1480                                class_metadata,
1481                                object.get_type_parameters(),
1482                                b"key",
1483                            )
1484                            && !method_key.is_mixed()
1485                        {
1486                            key_type = method_key;
1487                        }
1488
1489                        if value_type.is_mixed()
1490                            && let Some(method_val) = get_iterator_method_return_type(
1491                                codebase,
1492                                class_metadata,
1493                                object.get_type_parameters(),
1494                                b"current",
1495                            )
1496                            && !method_val.is_mixed()
1497                        {
1498                            value_type = method_val;
1499                        }
1500                    } else if class_metadata.all_parent_interfaces.contains(&iterator_aggregate)
1501                        && !visited_aggregates.contains(&class_metadata.name)
1502                        && let Some(inner_iter) = get_iterator_method_return_type(
1503                            codebase,
1504                            class_metadata,
1505                            object.get_type_parameters(),
1506                            b"getiterator",
1507                        )
1508                    {
1509                        let mut next_visited = Vec::with_capacity(visited_aggregates.len() + 1);
1510                        next_visited.extend_from_slice(visited_aggregates);
1511                        next_visited.push(class_metadata.name);
1512
1513                        if let Some((inner_k, inner_v)) = inner_iter.types.iter().find_map(|atomic_inner| {
1514                            get_iterable_parameters_impl(atomic_inner, codebase, &next_visited)
1515                        }) {
1516                            if key_type.is_mixed() && !inner_k.is_mixed() {
1517                                key_type = inner_k;
1518                            }
1519                            if value_type.is_mixed() && !inner_v.is_mixed() {
1520                                value_type = inner_v;
1521                            }
1522                        }
1523                    }
1524
1525                    Some((key_type, value_type))
1526                }
1527                _ => None,
1528            }
1529        };
1530
1531    if let Some((key_type, value_type)) = parameters {
1532        return Some((key_type, value_type));
1533    }
1534
1535    if let Some(intersection_types) = atomic.get_intersection_types() {
1536        for intersection_type in intersection_types {
1537            if let Some((key_type, value_type)) =
1538                get_iterable_parameters_impl(intersection_type, codebase, visited_aggregates)
1539            {
1540                return Some((key_type, value_type));
1541            }
1542        }
1543    }
1544
1545    None
1546}
1547
1548#[must_use]
1549pub fn get_array_parameters(array_type: &TArray, codebase: &CodebaseMetadata) -> (TUnion, TUnion) {
1550    match array_type {
1551        TArray::Keyed(keyed_data) => {
1552            let mut key_types = vec![];
1553            let mut value_param;
1554
1555            if let Some((key_param, value_p)) = &keyed_data.parameters {
1556                key_types.extend(key_param.types.iter().cloned());
1557                value_param = (**value_p).clone();
1558            } else {
1559                key_types.push(TAtomic::Never);
1560                value_param = get_never();
1561            }
1562
1563            if let Some(known_items) = &keyed_data.known_items {
1564                for (key, (_, item_type)) in known_items.iter() {
1565                    key_types.push(key.to_atomic());
1566                    value_param =
1567                        add_union_type(value_param, item_type, codebase, combiner::CombinerOptions::default());
1568                }
1569            }
1570
1571            if key_types.is_empty() {
1572                key_types.push(TAtomic::Never);
1573            }
1574
1575            let combined_key_types = combiner::combine(key_types, codebase, combiner::CombinerOptions::default());
1576            let key_param_union = TUnion::from_vec(combined_key_types);
1577
1578            (key_param_union, value_param)
1579        }
1580        TArray::List(list_data) => {
1581            let mut key_types = vec![];
1582            let mut value_type = (*list_data.element_type).clone();
1583
1584            if let Some(known_elements) = &list_data.known_elements {
1585                for (key_idx, (_, element_type)) in known_elements.iter() {
1586                    key_types.push(TAtomic::Scalar(TScalar::literal_int(*key_idx as i64)));
1587
1588                    value_type =
1589                        combine_union_types(element_type, &value_type, codebase, combiner::CombinerOptions::default());
1590                }
1591            }
1592
1593            if key_types.is_empty() || !value_type.is_never() {
1594                if value_type.is_never() {
1595                    key_types.push(TAtomic::Never);
1596                } else {
1597                    key_types.push(TAtomic::Scalar(TScalar::Integer(TInteger::non_negative())));
1598                }
1599            }
1600
1601            let key_type =
1602                TUnion::from_vec(combiner::combine(key_types, codebase, combiner::CombinerOptions::default()));
1603
1604            (key_type, value_type)
1605        }
1606    }
1607}
1608
1609#[must_use]
1610pub fn get_iterable_value_parameter(atomic: &TAtomic, codebase: &CodebaseMetadata) -> Option<TUnion> {
1611    if let Some(generator_parameters) = atomic.get_generator_parameters() {
1612        return Some(generator_parameters.1);
1613    }
1614
1615    let parameter = match atomic {
1616        TAtomic::Iterable(iterable) => Some(iterable.get_value_type().clone()),
1617        TAtomic::Array(array_type) => Some(get_array_value_parameter(array_type, codebase)),
1618        TAtomic::Object(object) => {
1619            let name = object.get_name()?;
1620            let traversable = word("traversable");
1621
1622            let class_metadata = codebase.get_class_like(name.as_bytes())?;
1623            if !codebase.is_instance_of(class_metadata.name.as_bytes(), traversable.as_bytes()) {
1624                return None;
1625            }
1626
1627            let traversable_metadata = codebase.get_class_like(traversable.as_bytes())?;
1628            let value_template = traversable_metadata.template_types.get_index(1).map(|(name, _)| *name)?;
1629
1630            get_specialized_template_type(
1631                codebase,
1632                value_template,
1633                traversable,
1634                class_metadata,
1635                object.get_type_parameters(),
1636            )
1637        }
1638        _ => None,
1639    };
1640
1641    if let Some(value_param) = parameter {
1642        return Some(value_param);
1643    }
1644
1645    if let Some(intersection_types) = atomic.get_intersection_types() {
1646        for intersection_type in intersection_types {
1647            if let Some(value_param) = get_iterable_value_parameter(intersection_type, codebase) {
1648                return Some(value_param);
1649            }
1650        }
1651    }
1652
1653    None
1654}
1655
1656#[must_use]
1657pub fn get_array_value_parameter(array_type: &TArray, codebase: &CodebaseMetadata) -> TUnion {
1658    match array_type {
1659        TArray::Keyed(keyed_data) => {
1660            let mut value_param;
1661
1662            if let Some((_, value_p)) = &keyed_data.parameters {
1663                value_param = (**value_p).clone();
1664            } else {
1665                value_param = get_never();
1666            }
1667
1668            if let Some(known_items) = &keyed_data.known_items {
1669                for (_, item_type) in known_items.values() {
1670                    value_param =
1671                        combine_union_types(item_type, &value_param, codebase, combiner::CombinerOptions::default());
1672                }
1673            }
1674
1675            value_param
1676        }
1677        TArray::List(list_data) => {
1678            let mut value_param = (*list_data.element_type).clone();
1679
1680            if let Some(known_elements) = &list_data.known_elements {
1681                for (_, element_type) in known_elements.values() {
1682                    value_param =
1683                        combine_union_types(element_type, &value_param, codebase, combiner::CombinerOptions::default());
1684                }
1685            }
1686
1687            value_param
1688        }
1689    }
1690}
1691
1692/// Resolves a generic template from an ancestor class in the context of a descendant class.
1693///
1694/// This function correctly traverses the pre-calculated inheritance map to determine the
1695/// concrete type of a template parameter.
1696#[must_use]
1697pub fn get_specialized_template_type(
1698    codebase: &CodebaseMetadata,
1699    template_name: Word,
1700    template_defining_class_id: Word,
1701    instantiated_class_metadata: &ClassLikeMetadata,
1702    instantiated_type_parameters: Option<&[TUnion]>,
1703) -> Option<TUnion> {
1704    let defining_class_metadata = codebase.get_class_like(template_defining_class_id.as_bytes())?;
1705
1706    if defining_class_metadata.name == instantiated_class_metadata.name {
1707        let index = instantiated_class_metadata.get_template_index_for_name(template_name)?;
1708
1709        let Some(instantiated_type_parameters) = instantiated_type_parameters else {
1710            let template = instantiated_class_metadata.get_template_type(template_name)?;
1711            let mut result = template.constraint.clone();
1712
1713            expander::expand_union(codebase, &mut result, &TypeExpansionOptions::default());
1714
1715            return Some(result);
1716        };
1717
1718        let mut result = instantiated_type_parameters.get(index).cloned()?;
1719
1720        expander::expand_union(codebase, &mut result, &TypeExpansionOptions::default());
1721
1722        return Some(result);
1723    }
1724
1725    let template = defining_class_metadata.get_template_type(template_name)?;
1726    let template_union = wrap_atomic(TAtomic::GenericParameter(TGenericParameter {
1727        parameter_name: template_name,
1728        defining_entity: template.defining_entity,
1729        constraint: Arc::new(template.constraint.clone()),
1730        intersection_types: None,
1731    }));
1732
1733    let mut template_result = TemplateResult::default();
1734    for (defining_class, template_parameters) in &instantiated_class_metadata.template_extended_parameters {
1735        for (parameter_name, parameter_type) in template_parameters {
1736            template_result.add_lower_bound(
1737                *parameter_name,
1738                GenericParent::ClassLike(*defining_class),
1739                parameter_type.clone(),
1740            );
1741        }
1742    }
1743
1744    let mut template_type = inferred_type_replacer::replace(&template_union, &template_result, codebase);
1745    if let Some(type_parameters) = instantiated_type_parameters {
1746        let mut template_result = TemplateResult::default();
1747        for (i, parameter_type) in type_parameters.iter().enumerate() {
1748            if let Some(parameter_name) = instantiated_class_metadata.get_template_name_for_index(i) {
1749                template_result.add_lower_bound(
1750                    parameter_name,
1751                    GenericParent::ClassLike(instantiated_class_metadata.name),
1752                    parameter_type.clone(),
1753                );
1754            }
1755        }
1756
1757        if !template_result.lower_bounds.is_empty() {
1758            template_type = inferred_type_replacer::replace(&template_type, &template_result, codebase);
1759        }
1760    }
1761
1762    expander::expand_union(codebase, &mut template_type, &TypeExpansionOptions::default());
1763
1764    Some(template_type)
1765}
1766
1767fn resolve_unbound_generic_parameters(codebase: &CodebaseMetadata, union: &mut TUnion) {
1768    if !union.has_template_types() {
1769        return;
1770    }
1771
1772    let mut template_result = TemplateResult::default();
1773    for node in union.get_all_child_nodes() {
1774        if let TypeRef::Atomic(TAtomic::GenericParameter(parameter)) = node {
1775            template_result.add_lower_bound(
1776                parameter.parameter_name,
1777                parameter.defining_entity,
1778                (*parameter.constraint).clone(),
1779            );
1780        }
1781    }
1782
1783    if !template_result.lower_bounds.is_empty() {
1784        *union = inferred_type_replacer::replace(union, &template_result, codebase);
1785    }
1786}
1787
1788fn get_iterator_method_return_type(
1789    codebase: &CodebaseMetadata,
1790    class_metadata: &ClassLikeMetadata,
1791    type_parameters: Option<&[TUnion]>,
1792    method_name: &[u8],
1793) -> Option<TUnion> {
1794    let method = codebase.get_declaring_method(class_metadata.name.as_bytes(), method_name)?;
1795    let return_type_meta = method.return_type_metadata.as_ref()?;
1796    let mut return_type = return_type_meta.type_union.clone();
1797
1798    if return_type.has_template_types() {
1799        let mut template_result = TemplateResult::default();
1800        for node in return_type.get_all_child_nodes() {
1801            if let TypeRef::Atomic(TAtomic::GenericParameter(parameter)) = node
1802                && let GenericParent::ClassLike(class_name) = parameter.defining_entity
1803                && let Some(template_type) = get_specialized_template_type(
1804                    codebase,
1805                    parameter.parameter_name,
1806                    class_name,
1807                    class_metadata,
1808                    type_parameters,
1809                )
1810            {
1811                template_result.add_lower_bound(parameter.parameter_name, parameter.defining_entity, template_type);
1812            }
1813        }
1814
1815        if !template_result.lower_bounds.is_empty() {
1816            return_type = inferred_type_replacer::replace(&return_type, &template_result, codebase);
1817        }
1818
1819        resolve_unbound_generic_parameters(codebase, &mut return_type);
1820    }
1821
1822    let expansion_options = TypeExpansionOptions {
1823        self_class: Some(class_metadata.name),
1824        static_class_type: StaticClassType::Name(class_metadata.name),
1825        ..Default::default()
1826    };
1827    expander::expand_union(codebase, &mut return_type, &expansion_options);
1828    Some(return_type)
1829}
1830
1831#[cfg(test)]
1832mod tests {
1833    use std::rc::Rc;
1834
1835    use crate::metadata::CodebaseMetadata;
1836    use crate::ttype::combiner::CombinerOptions;
1837    use crate::ttype::flags::UnionFlags;
1838    use crate::ttype::union::TUnion;
1839
1840    use super::add_optional_union_type;
1841    use super::add_optional_union_type_rc;
1842    use super::combine_owned_union_types_rc;
1843    use super::combine_union_types;
1844    use super::combine_union_types_rc;
1845    use super::get_empty_keyed_array;
1846    use super::get_int;
1847    use super::get_list;
1848    use super::get_mixed;
1849    use super::get_never;
1850    use super::get_string;
1851
1852    fn assert_exact(actual: &TUnion, expected: &TUnion) {
1853        assert_eq!(actual.types, expected.types);
1854        assert_eq!(actual.flags, expected.flags);
1855    }
1856
1857    #[test]
1858    fn rc_merges_keep_the_first_equal_union_and_all_its_flags() {
1859        let codebase = CodebaseMetadata::new();
1860        let ignored_flags = [
1861            UnionFlags::empty(),
1862            UnionFlags::POPULATED,
1863            UnionFlags::NULLSAFE_NULL,
1864            UnionFlags::POPULATED.union(UnionFlags::NULLSAFE_NULL),
1865        ];
1866        for first_flags in ignored_flags {
1867            for second_flags in ignored_flags {
1868                let mut first = get_int();
1869                let shared_flags = UnionFlags::HAD_TEMPLATE
1870                    .union(UnionFlags::BY_REFERENCE)
1871                    .union(UnionFlags::REFERENCE_FREE)
1872                    .union(UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY)
1873                    .union(UnionFlags::POSSIBLY_UNDEFINED)
1874                    .union(UnionFlags::IGNORE_NULLABLE_ISSUES)
1875                    .union(UnionFlags::IGNORE_FALSABLE_ISSUES)
1876                    .union(UnionFlags::FROM_TEMPLATE_DEFAULT)
1877                    .union(UnionFlags::FROM_UNSPECIFIED_TEMPLATE);
1878                first.flags = first_flags.union(shared_flags);
1879                let mut second = first.clone();
1880                second.flags = second_flags.union(shared_flags);
1881                let first = Rc::new(first);
1882                let second = Rc::new(second);
1883                assert!(!Rc::ptr_eq(&first, &second));
1884                assert_eq!(first, second);
1885
1886                let expected = combine_union_types(&first, &second, &codebase, CombinerOptions::default());
1887                let actual = combine_union_types_rc(&first, &second, &codebase, CombinerOptions::default());
1888                assert_exact(&actual, &expected);
1889                assert!(Rc::ptr_eq(&actual, &first));
1890
1891                let expected = add_optional_union_type((*first).clone(), Some(&second), &codebase);
1892                let actual = add_optional_union_type_rc(&first, Some(&second), &codebase);
1893                assert_exact(&actual, &expected);
1894                assert!(Rc::ptr_eq(&actual, &first));
1895            }
1896        }
1897    }
1898
1899    #[test]
1900    fn rc_merges_keep_identical_and_missing_optional_inputs() {
1901        let codebase = CodebaseMetadata::new();
1902        let first = Rc::new(get_int());
1903        assert!(Rc::ptr_eq(&combine_union_types_rc(&first, &first, &codebase, CombinerOptions::default()), &first));
1904        assert!(Rc::ptr_eq(&add_optional_union_type_rc(&first, Some(&first), &codebase), &first));
1905        assert!(Rc::ptr_eq(&add_optional_union_type_rc(&first, None, &codebase), &first));
1906    }
1907
1908    #[test]
1909    fn rc_merges_match_owned_results_for_unequal_unions() {
1910        let codebase = CodebaseMetadata::new();
1911        let first = Rc::new(get_int());
1912        for flag in [
1913            UnionFlags::HAD_TEMPLATE,
1914            UnionFlags::BY_REFERENCE,
1915            UnionFlags::REFERENCE_FREE,
1916            UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY,
1917            UnionFlags::POSSIBLY_UNDEFINED,
1918            UnionFlags::IGNORE_NULLABLE_ISSUES,
1919            UnionFlags::IGNORE_FALSABLE_ISSUES,
1920            UnionFlags::FROM_TEMPLATE_DEFAULT,
1921            UnionFlags::FROM_UNSPECIFIED_TEMPLATE,
1922        ] {
1923            for mut second in [get_int(), get_string()] {
1924                second.flags = flag.union(UnionFlags::POPULATED);
1925                let second = Rc::new(second);
1926                assert_ne!(first, second);
1927                assert_exact(
1928                    &combine_union_types_rc(&first, &second, &codebase, CombinerOptions::default()),
1929                    &combine_union_types(&first, &second, &codebase, CombinerOptions::default()),
1930                );
1931                assert_exact(
1932                    &add_optional_union_type_rc(&first, Some(&second), &codebase),
1933                    &add_optional_union_type((*first).clone(), Some(&second), &codebase),
1934                );
1935            }
1936        }
1937    }
1938
1939    #[test]
1940    fn consuming_rc_merges_match_borrowed_types_flags_and_shared_snapshots() {
1941        let codebase = CodebaseMetadata::new();
1942        let types = [get_int(), get_string(), get_never(), get_mixed(), get_empty_keyed_array(), get_list(get_int())];
1943        let flags = [
1944            UnionFlags::empty(),
1945            UnionFlags::HAD_TEMPLATE,
1946            UnionFlags::BY_REFERENCE,
1947            UnionFlags::REFERENCE_FREE,
1948            UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY,
1949            UnionFlags::POSSIBLY_UNDEFINED,
1950            UnionFlags::IGNORE_NULLABLE_ISSUES,
1951            UnionFlags::IGNORE_FALSABLE_ISSUES,
1952            UnionFlags::FROM_TEMPLATE_DEFAULT,
1953            UnionFlags::FROM_UNSPECIFIED_TEMPLATE,
1954            UnionFlags::POPULATED,
1955            UnionFlags::NULLSAFE_NULL,
1956        ];
1957
1958        for first_type in &types {
1959            for second_type in &types {
1960                for first_flags in flags {
1961                    for second_flags in flags {
1962                        let mut first = first_type.clone();
1963                        first.flags = first_flags;
1964                        let mut second = second_type.clone();
1965                        second.flags = second_flags;
1966                        let second = Rc::new(second);
1967                        let expected = combine_union_types(&first, &second, &codebase, CombinerOptions::default());
1968
1969                        let shared = Rc::new(first.clone());
1970                        let actual = combine_owned_union_types_rc(
1971                            Rc::clone(&shared),
1972                            &second,
1973                            &codebase,
1974                            CombinerOptions::default(),
1975                        );
1976                        assert_exact(&actual, &expected);
1977                        assert_exact(&shared, &first);
1978
1979                        let unique = Rc::new(first);
1980                        let original_pointer = Rc::as_ptr(&unique);
1981                        let equal = unique == second;
1982                        let actual =
1983                            combine_owned_union_types_rc(unique, &second, &codebase, CombinerOptions::default());
1984                        assert_exact(&actual, &expected);
1985                        if equal {
1986                            assert!(std::ptr::eq(Rc::as_ptr(&actual), original_pointer));
1987                        }
1988                    }
1989                }
1990            }
1991        }
1992    }
1993}