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(
1470                        codebase,
1471                        class_metadata,
1472                        object.get_type_parameters(),
1473                        &mut key_type,
1474                    );
1475                    resolve_unbound_generic_parameters(
1476                        codebase,
1477                        class_metadata,
1478                        object.get_type_parameters(),
1479                        &mut value_type,
1480                    );
1481
1482                    if is_iterator_interface || (!key_type.is_mixed() && !value_type.is_mixed()) {
1483                        return Some((key_type, value_type));
1484                    }
1485
1486                    if class_metadata.all_parent_interfaces.contains(&iterator) {
1487                        if key_type.is_mixed()
1488                            && let Some(method_key) = get_iterator_method_return_type(
1489                                codebase,
1490                                class_metadata,
1491                                object.get_type_parameters(),
1492                                b"key",
1493                            )
1494                            && !method_key.is_mixed()
1495                        {
1496                            key_type = method_key;
1497                        }
1498
1499                        if value_type.is_mixed()
1500                            && let Some(method_val) = get_iterator_method_return_type(
1501                                codebase,
1502                                class_metadata,
1503                                object.get_type_parameters(),
1504                                b"current",
1505                            )
1506                            && !method_val.is_mixed()
1507                        {
1508                            value_type = method_val;
1509                        }
1510                    } else if class_metadata.all_parent_interfaces.contains(&iterator_aggregate)
1511                        && !visited_aggregates.contains(&class_metadata.name)
1512                        && let Some(inner_iter) = get_iterator_method_return_type(
1513                            codebase,
1514                            class_metadata,
1515                            object.get_type_parameters(),
1516                            b"getiterator",
1517                        )
1518                    {
1519                        let mut next_visited = Vec::with_capacity(visited_aggregates.len() + 1);
1520                        next_visited.extend_from_slice(visited_aggregates);
1521                        next_visited.push(class_metadata.name);
1522
1523                        if let Some((inner_k, inner_v)) = inner_iter.types.iter().find_map(|atomic_inner| {
1524                            get_iterable_parameters_impl(atomic_inner, codebase, &next_visited)
1525                        }) {
1526                            if key_type.is_mixed() && !inner_k.is_mixed() {
1527                                key_type = inner_k;
1528                            }
1529                            if value_type.is_mixed() && !inner_v.is_mixed() {
1530                                value_type = inner_v;
1531                            }
1532                        }
1533                    }
1534
1535                    Some((key_type, value_type))
1536                }
1537                _ => None,
1538            }
1539        };
1540
1541    if let Some((key_type, value_type)) = parameters {
1542        return Some((key_type, value_type));
1543    }
1544
1545    if let Some(intersection_types) = atomic.get_intersection_types() {
1546        for intersection_type in intersection_types {
1547            if let Some((key_type, value_type)) =
1548                get_iterable_parameters_impl(intersection_type, codebase, visited_aggregates)
1549            {
1550                return Some((key_type, value_type));
1551            }
1552        }
1553    }
1554
1555    None
1556}
1557
1558#[must_use]
1559pub fn get_array_parameters(array_type: &TArray, codebase: &CodebaseMetadata) -> (TUnion, TUnion) {
1560    match array_type {
1561        TArray::Keyed(keyed_data) => {
1562            let mut key_types = vec![];
1563            let mut value_param;
1564
1565            if let Some((key_param, value_p)) = &keyed_data.parameters {
1566                key_types.extend(key_param.types.iter().cloned());
1567                value_param = (**value_p).clone();
1568            } else {
1569                key_types.push(TAtomic::Never);
1570                value_param = get_never();
1571            }
1572
1573            if let Some(known_items) = &keyed_data.known_items {
1574                for (key, (_, item_type)) in known_items.iter() {
1575                    key_types.push(key.to_atomic());
1576                    value_param =
1577                        add_union_type(value_param, item_type, codebase, combiner::CombinerOptions::default());
1578                }
1579            }
1580
1581            if key_types.is_empty() {
1582                key_types.push(TAtomic::Never);
1583            }
1584
1585            let combined_key_types = combiner::combine(key_types, codebase, combiner::CombinerOptions::default());
1586            let key_param_union = TUnion::from_vec(combined_key_types);
1587
1588            (key_param_union, value_param)
1589        }
1590        TArray::List(list_data) => {
1591            let mut key_types = vec![];
1592            let mut value_type = (*list_data.element_type).clone();
1593
1594            if let Some(known_elements) = &list_data.known_elements {
1595                for (key_idx, (_, element_type)) in known_elements.iter() {
1596                    key_types.push(TAtomic::Scalar(TScalar::literal_int(*key_idx as i64)));
1597
1598                    value_type =
1599                        combine_union_types(element_type, &value_type, codebase, combiner::CombinerOptions::default());
1600                }
1601            }
1602
1603            if key_types.is_empty() || !value_type.is_never() {
1604                if value_type.is_never() {
1605                    key_types.push(TAtomic::Never);
1606                } else {
1607                    key_types.push(TAtomic::Scalar(TScalar::Integer(TInteger::non_negative())));
1608                }
1609            }
1610
1611            let key_type =
1612                TUnion::from_vec(combiner::combine(key_types, codebase, combiner::CombinerOptions::default()));
1613
1614            (key_type, value_type)
1615        }
1616    }
1617}
1618
1619#[must_use]
1620pub fn get_iterable_value_parameter(atomic: &TAtomic, codebase: &CodebaseMetadata) -> Option<TUnion> {
1621    if let Some(generator_parameters) = atomic.get_generator_parameters() {
1622        return Some(generator_parameters.1);
1623    }
1624
1625    let parameter = match atomic {
1626        TAtomic::Iterable(iterable) => Some(iterable.get_value_type().clone()),
1627        TAtomic::Array(array_type) => Some(get_array_value_parameter(array_type, codebase)),
1628        TAtomic::Object(object) => {
1629            let name = object.get_name()?;
1630            let traversable = word("traversable");
1631
1632            let class_metadata = codebase.get_class_like(name.as_bytes())?;
1633            if !codebase.is_instance_of(class_metadata.name.as_bytes(), traversable.as_bytes()) {
1634                return None;
1635            }
1636
1637            let traversable_metadata = codebase.get_class_like(traversable.as_bytes())?;
1638            let value_template = traversable_metadata.template_types.get_index(1).map(|(name, _)| *name)?;
1639
1640            get_specialized_template_type(
1641                codebase,
1642                value_template,
1643                traversable,
1644                class_metadata,
1645                object.get_type_parameters(),
1646            )
1647        }
1648        _ => None,
1649    };
1650
1651    if let Some(value_param) = parameter {
1652        return Some(value_param);
1653    }
1654
1655    if let Some(intersection_types) = atomic.get_intersection_types() {
1656        for intersection_type in intersection_types {
1657            if let Some(value_param) = get_iterable_value_parameter(intersection_type, codebase) {
1658                return Some(value_param);
1659            }
1660        }
1661    }
1662
1663    None
1664}
1665
1666#[must_use]
1667pub fn get_array_value_parameter(array_type: &TArray, codebase: &CodebaseMetadata) -> TUnion {
1668    match array_type {
1669        TArray::Keyed(keyed_data) => {
1670            let mut value_param;
1671
1672            if let Some((_, value_p)) = &keyed_data.parameters {
1673                value_param = (**value_p).clone();
1674            } else {
1675                value_param = get_never();
1676            }
1677
1678            if let Some(known_items) = &keyed_data.known_items {
1679                for (_, item_type) in known_items.values() {
1680                    value_param =
1681                        combine_union_types(item_type, &value_param, codebase, combiner::CombinerOptions::default());
1682                }
1683            }
1684
1685            value_param
1686        }
1687        TArray::List(list_data) => {
1688            let mut value_param = (*list_data.element_type).clone();
1689
1690            if let Some(known_elements) = &list_data.known_elements {
1691                for (_, element_type) in known_elements.values() {
1692                    value_param =
1693                        combine_union_types(element_type, &value_param, codebase, combiner::CombinerOptions::default());
1694                }
1695            }
1696
1697            value_param
1698        }
1699    }
1700}
1701
1702/// Resolves a generic template from an ancestor class in the context of a descendant class.
1703///
1704/// This function correctly traverses the pre-calculated inheritance map to determine the
1705/// concrete type of a template parameter.
1706#[must_use]
1707pub fn get_specialized_template_type(
1708    codebase: &CodebaseMetadata,
1709    template_name: Word,
1710    template_defining_class_id: Word,
1711    instantiated_class_metadata: &ClassLikeMetadata,
1712    instantiated_type_parameters: Option<&[TUnion]>,
1713) -> Option<TUnion> {
1714    let defining_class_metadata = codebase.get_class_like(template_defining_class_id.as_bytes())?;
1715
1716    if defining_class_metadata.name == instantiated_class_metadata.name {
1717        let index = instantiated_class_metadata.get_template_index_for_name(template_name)?;
1718
1719        let Some(instantiated_type_parameters) = instantiated_type_parameters else {
1720            let template = instantiated_class_metadata.get_template_type(template_name)?;
1721            let mut result = template.constraint.clone();
1722
1723            expander::expand_union(codebase, &mut result, &TypeExpansionOptions::default());
1724
1725            return Some(result);
1726        };
1727
1728        let mut result = instantiated_type_parameters.get(index).cloned()?;
1729
1730        expander::expand_union(codebase, &mut result, &TypeExpansionOptions::default());
1731
1732        return Some(result);
1733    }
1734
1735    let template = defining_class_metadata.get_template_type(template_name)?;
1736    let template_union = wrap_atomic(TAtomic::GenericParameter(TGenericParameter {
1737        parameter_name: template_name,
1738        defining_entity: template.defining_entity,
1739        constraint: Arc::new(template.constraint.clone()),
1740        intersection_types: None,
1741    }));
1742
1743    let mut template_result = TemplateResult::default();
1744    for (defining_class, template_parameters) in &instantiated_class_metadata.template_extended_parameters {
1745        for (parameter_name, parameter_type) in template_parameters {
1746            template_result.add_lower_bound(
1747                *parameter_name,
1748                GenericParent::ClassLike(*defining_class),
1749                parameter_type.clone(),
1750            );
1751        }
1752    }
1753
1754    let mut template_type = inferred_type_replacer::replace(&template_union, &template_result, codebase);
1755    if let Some(type_parameters) = instantiated_type_parameters {
1756        let mut template_result = TemplateResult::default();
1757        for (i, parameter_type) in type_parameters.iter().enumerate() {
1758            if let Some(parameter_name) = instantiated_class_metadata.get_template_name_for_index(i) {
1759                template_result.add_lower_bound(
1760                    parameter_name,
1761                    GenericParent::ClassLike(instantiated_class_metadata.name),
1762                    parameter_type.clone(),
1763                );
1764            }
1765        }
1766
1767        if !template_result.lower_bounds.is_empty() {
1768            template_type = inferred_type_replacer::replace(&template_type, &template_result, codebase);
1769        }
1770    }
1771
1772    expander::expand_union(codebase, &mut template_type, &TypeExpansionOptions::default());
1773
1774    Some(template_type)
1775}
1776
1777fn resolve_unbound_generic_parameters(
1778    codebase: &CodebaseMetadata,
1779    class_metadata: &ClassLikeMetadata,
1780    type_parameters: Option<&[TUnion]>,
1781    union: &mut TUnion,
1782) {
1783    if !union.has_template_types() {
1784        return;
1785    }
1786
1787    let mut template_result = TemplateResult::default();
1788    for node in union.get_all_child_nodes() {
1789        if let TypeRef::Atomic(TAtomic::GenericParameter(parameter)) = node
1790            && is_unbound_class_template(class_metadata, type_parameters, parameter)
1791        {
1792            template_result.add_lower_bound(
1793                parameter.parameter_name,
1794                parameter.defining_entity,
1795                (*parameter.constraint).clone(),
1796            );
1797        }
1798    }
1799
1800    if !template_result.lower_bounds.is_empty() {
1801        *union = inferred_type_replacer::replace(union, &template_result, codebase);
1802    }
1803}
1804
1805fn is_unbound_class_template(
1806    class_metadata: &ClassLikeMetadata,
1807    type_parameters: Option<&[TUnion]>,
1808    parameter: &TGenericParameter,
1809) -> bool {
1810    let GenericParent::ClassLike(defining_class) = parameter.defining_entity else {
1811        return false;
1812    };
1813
1814    if defining_class == class_metadata.name {
1815        return type_parameters.is_none_or(|type_parameters| {
1816            class_metadata
1817                .get_template_index_for_name(parameter.parameter_name)
1818                .is_none_or(|index| index >= type_parameters.len())
1819        });
1820    }
1821
1822    (class_metadata.all_parent_classes.contains(&defining_class)
1823        || class_metadata.all_parent_interfaces.contains(&defining_class))
1824        && !class_metadata
1825            .template_extended_parameters
1826            .get(&defining_class)
1827            .is_some_and(|parameters| parameters.contains_key(&parameter.parameter_name))
1828}
1829
1830fn get_iterator_method_return_type(
1831    codebase: &CodebaseMetadata,
1832    class_metadata: &ClassLikeMetadata,
1833    type_parameters: Option<&[TUnion]>,
1834    method_name: &[u8],
1835) -> Option<TUnion> {
1836    let method = codebase.get_declaring_method(class_metadata.name.as_bytes(), method_name)?;
1837    let return_type_meta = method.return_type_metadata.as_ref()?;
1838    let mut return_type = return_type_meta.type_union.clone();
1839
1840    if return_type.has_template_types() {
1841        let mut template_result = TemplateResult::default();
1842        for node in return_type.get_all_child_nodes() {
1843            if let TypeRef::Atomic(TAtomic::GenericParameter(parameter)) = node
1844                && let GenericParent::ClassLike(class_name) = parameter.defining_entity
1845                && let Some(template_type) = get_specialized_template_type(
1846                    codebase,
1847                    parameter.parameter_name,
1848                    class_name,
1849                    class_metadata,
1850                    type_parameters,
1851                )
1852            {
1853                template_result.add_lower_bound(parameter.parameter_name, parameter.defining_entity, template_type);
1854            }
1855        }
1856
1857        if !template_result.lower_bounds.is_empty() {
1858            return_type = inferred_type_replacer::replace(&return_type, &template_result, codebase);
1859        }
1860
1861        resolve_unbound_generic_parameters(codebase, class_metadata, type_parameters, &mut return_type);
1862    }
1863
1864    let expansion_options = TypeExpansionOptions {
1865        self_class: Some(class_metadata.name),
1866        static_class_type: StaticClassType::Name(class_metadata.name),
1867        ..Default::default()
1868    };
1869    expander::expand_union(codebase, &mut return_type, &expansion_options);
1870    Some(return_type)
1871}
1872
1873#[cfg(test)]
1874mod tests {
1875    use std::rc::Rc;
1876
1877    use crate::metadata::CodebaseMetadata;
1878    use crate::ttype::combiner::CombinerOptions;
1879    use crate::ttype::flags::UnionFlags;
1880    use crate::ttype::union::TUnion;
1881
1882    use super::add_optional_union_type;
1883    use super::add_optional_union_type_rc;
1884    use super::combine_owned_union_types_rc;
1885    use super::combine_union_types;
1886    use super::combine_union_types_rc;
1887    use super::get_empty_keyed_array;
1888    use super::get_int;
1889    use super::get_list;
1890    use super::get_mixed;
1891    use super::get_never;
1892    use super::get_string;
1893
1894    fn assert_exact(actual: &TUnion, expected: &TUnion) {
1895        assert_eq!(actual.types, expected.types);
1896        assert_eq!(actual.flags, expected.flags);
1897    }
1898
1899    #[test]
1900    fn rc_merges_keep_the_first_equal_union_and_all_its_flags() {
1901        let codebase = CodebaseMetadata::new();
1902        let ignored_flags = [
1903            UnionFlags::empty(),
1904            UnionFlags::POPULATED,
1905            UnionFlags::NULLSAFE_NULL,
1906            UnionFlags::POPULATED.union(UnionFlags::NULLSAFE_NULL),
1907        ];
1908        for first_flags in ignored_flags {
1909            for second_flags in ignored_flags {
1910                let mut first = get_int();
1911                let shared_flags = UnionFlags::HAD_TEMPLATE
1912                    .union(UnionFlags::BY_REFERENCE)
1913                    .union(UnionFlags::REFERENCE_FREE)
1914                    .union(UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY)
1915                    .union(UnionFlags::POSSIBLY_UNDEFINED)
1916                    .union(UnionFlags::IGNORE_NULLABLE_ISSUES)
1917                    .union(UnionFlags::IGNORE_FALSABLE_ISSUES)
1918                    .union(UnionFlags::FROM_TEMPLATE_DEFAULT)
1919                    .union(UnionFlags::FROM_UNSPECIFIED_TEMPLATE);
1920                first.flags = first_flags.union(shared_flags);
1921                let mut second = first.clone();
1922                second.flags = second_flags.union(shared_flags);
1923                let first = Rc::new(first);
1924                let second = Rc::new(second);
1925                assert!(!Rc::ptr_eq(&first, &second));
1926                assert_eq!(first, second);
1927
1928                let expected = combine_union_types(&first, &second, &codebase, CombinerOptions::default());
1929                let actual = combine_union_types_rc(&first, &second, &codebase, CombinerOptions::default());
1930                assert_exact(&actual, &expected);
1931                assert!(Rc::ptr_eq(&actual, &first));
1932
1933                let expected = add_optional_union_type((*first).clone(), Some(&second), &codebase);
1934                let actual = add_optional_union_type_rc(&first, Some(&second), &codebase);
1935                assert_exact(&actual, &expected);
1936                assert!(Rc::ptr_eq(&actual, &first));
1937            }
1938        }
1939    }
1940
1941    #[test]
1942    fn rc_merges_keep_identical_and_missing_optional_inputs() {
1943        let codebase = CodebaseMetadata::new();
1944        let first = Rc::new(get_int());
1945        assert!(Rc::ptr_eq(&combine_union_types_rc(&first, &first, &codebase, CombinerOptions::default()), &first));
1946        assert!(Rc::ptr_eq(&add_optional_union_type_rc(&first, Some(&first), &codebase), &first));
1947        assert!(Rc::ptr_eq(&add_optional_union_type_rc(&first, None, &codebase), &first));
1948    }
1949
1950    #[test]
1951    fn rc_merges_match_owned_results_for_unequal_unions() {
1952        let codebase = CodebaseMetadata::new();
1953        let first = Rc::new(get_int());
1954        for flag in [
1955            UnionFlags::HAD_TEMPLATE,
1956            UnionFlags::BY_REFERENCE,
1957            UnionFlags::REFERENCE_FREE,
1958            UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY,
1959            UnionFlags::POSSIBLY_UNDEFINED,
1960            UnionFlags::IGNORE_NULLABLE_ISSUES,
1961            UnionFlags::IGNORE_FALSABLE_ISSUES,
1962            UnionFlags::FROM_TEMPLATE_DEFAULT,
1963            UnionFlags::FROM_UNSPECIFIED_TEMPLATE,
1964        ] {
1965            for mut second in [get_int(), get_string()] {
1966                second.flags = flag.union(UnionFlags::POPULATED);
1967                let second = Rc::new(second);
1968                assert_ne!(first, second);
1969                assert_exact(
1970                    &combine_union_types_rc(&first, &second, &codebase, CombinerOptions::default()),
1971                    &combine_union_types(&first, &second, &codebase, CombinerOptions::default()),
1972                );
1973                assert_exact(
1974                    &add_optional_union_type_rc(&first, Some(&second), &codebase),
1975                    &add_optional_union_type((*first).clone(), Some(&second), &codebase),
1976                );
1977            }
1978        }
1979    }
1980
1981    #[test]
1982    fn consuming_rc_merges_match_borrowed_types_flags_and_shared_snapshots() {
1983        let codebase = CodebaseMetadata::new();
1984        let types = [get_int(), get_string(), get_never(), get_mixed(), get_empty_keyed_array(), get_list(get_int())];
1985        let flags = [
1986            UnionFlags::empty(),
1987            UnionFlags::HAD_TEMPLATE,
1988            UnionFlags::BY_REFERENCE,
1989            UnionFlags::REFERENCE_FREE,
1990            UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY,
1991            UnionFlags::POSSIBLY_UNDEFINED,
1992            UnionFlags::IGNORE_NULLABLE_ISSUES,
1993            UnionFlags::IGNORE_FALSABLE_ISSUES,
1994            UnionFlags::FROM_TEMPLATE_DEFAULT,
1995            UnionFlags::FROM_UNSPECIFIED_TEMPLATE,
1996            UnionFlags::POPULATED,
1997            UnionFlags::NULLSAFE_NULL,
1998        ];
1999
2000        for first_type in &types {
2001            for second_type in &types {
2002                for first_flags in flags {
2003                    for second_flags in flags {
2004                        let mut first = first_type.clone();
2005                        first.flags = first_flags;
2006                        let mut second = second_type.clone();
2007                        second.flags = second_flags;
2008                        let second = Rc::new(second);
2009                        let expected = combine_union_types(&first, &second, &codebase, CombinerOptions::default());
2010
2011                        let shared = Rc::new(first.clone());
2012                        let actual = combine_owned_union_types_rc(
2013                            Rc::clone(&shared),
2014                            &second,
2015                            &codebase,
2016                            CombinerOptions::default(),
2017                        );
2018                        assert_exact(&actual, &expected);
2019                        assert_exact(&shared, &first);
2020
2021                        let unique = Rc::new(first);
2022                        let original_pointer = Rc::as_ptr(&unique);
2023                        let equal = unique == second;
2024                        let actual =
2025                            combine_owned_union_types_rc(unique, &second, &codebase, CombinerOptions::default());
2026                        assert_exact(&actual, &expected);
2027                        if equal {
2028                            assert!(std::ptr::eq(Rc::as_ptr(&actual), original_pointer));
2029                        }
2030                    }
2031                }
2032            }
2033        }
2034    }
2035}