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