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