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#[derive(Clone, Copy, Debug)]
115pub enum TypeRef<'ty> {
116 Union(&'ty TUnion),
117 Atomic(&'ty TAtomic),
118}
119
120pub trait TType {
122 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 fn append_child_nodes<'types>(&'types self, _children: &mut Vec<TypeRef<'types>>) {}
131
132 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 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 fn can_be_intersected(&self) -> bool {
171 false
172 }
173
174 fn get_intersection_types(&self) -> Option<&[TAtomic]> {
176 None
177 }
178
179 fn get_intersection_types_mut(&mut self) -> Option<&mut Vec<TAtomic>> {
181 None
182 }
183
184 fn has_intersection_types(&self) -> bool {
186 false
187 }
188
189 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 fn is_complex(&self) -> bool {
208 false
209 }
210
211 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
227impl<'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#[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#[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#[inline]
457#[must_use]
458pub fn get_signum_result() -> TUnion {
459 TUnion::new(Cow::Borrowed(SIGNUM_RESULT_SLICE))
460}
461
462#[inline]
464#[must_use]
465pub fn get_one_int() -> TUnion {
466 TUnion::from_single(Cow::Borrowed(ONE_INT_ATOMIC))
467}
468
469#[inline]
471#[must_use]
472pub fn get_zero_int() -> TUnion {
473 TUnion::from_single(Cow::Borrowed(ZERO_INT_ATOMIC))
474}
475
476#[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#[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 (true, true, _, _) => NUMERIC_TRUTHY_STRING_ATOMIC,
567 (true, false, _, _) => NUMERIC_STRING_ATOMIC,
568 (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 (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#[must_use]
754pub fn get_callable_array() -> TAtomic {
755 TAtomic::Array(TArray::List(TList {
756 element_type: Arc::new(get_never()),
757 known_elements: Some(Arc::new(std::collections::BTreeMap::from([
758 (
759 0,
760 (
761 false,
762 TUnion::from_vec(vec![TAtomic::Object(TObject::Any), TAtomic::Scalar(TScalar::class_string())]),
763 ),
764 ),
765 (1, (false, get_non_empty_string())),
766 ]))),
767 known_count: None,
768 non_empty: true,
769 }))
770}
771
772#[inline]
773#[must_use]
774pub fn get_non_empty_string() -> TUnion {
775 TUnion::from_single(Cow::Borrowed(NON_EMPTY_STRING_ATOMIC))
776}
777
778#[inline]
779#[must_use]
780pub fn get_empty_string() -> TUnion {
781 TUnion::from_single(Cow::Borrowed(&EMPTY_STRING_ATOMIC))
782}
783
784#[inline]
785#[must_use]
786pub fn get_truthy_string() -> TUnion {
787 TUnion::from_single(Cow::Borrowed(TRUTHY_STRING_ATOMIC))
788}
789
790#[inline]
791#[must_use]
792pub fn get_unspecified_literal_string() -> TUnion {
793 TUnion::from_single(Cow::Borrowed(UNSPECIFIED_LITERAL_STRING_ATOMIC))
794}
795
796#[inline]
797#[must_use]
798pub fn get_non_empty_unspecified_literal_string() -> TUnion {
799 TUnion::from_single(Cow::Borrowed(NON_EMPTY_UNSPECIFIED_LITERAL_STRING_ATOMIC))
800}
801
802#[inline]
803#[must_use]
804pub fn get_scalar() -> TUnion {
805 TUnion::from_single(Cow::Borrowed(SCALAR_ATOMIC))
806}
807
808#[inline]
809#[must_use]
810pub fn get_nullable_scalar() -> TUnion {
811 TUnion::new(Cow::Borrowed(NULL_SCALAR_ATOMIC_SLICE))
812}
813
814#[inline]
815#[must_use]
816pub fn get_mixed_iterable() -> TUnion {
817 TUnion::from_single(Cow::Borrowed(&MIXED_ITERABLE_ATOMIC))
818}
819
820#[inline]
821#[must_use]
822pub fn get_empty_keyed_array() -> TUnion {
823 TUnion::from_single(Cow::Borrowed(&EMPTY_KEYED_ARRAY_ATOMIC))
824}
825
826#[inline]
829#[must_use]
830pub fn get_empty() -> TUnion {
831 TUnion::new(Cow::Borrowed(EMPTY_ATOMIC_SLICE.as_slice()))
832}
833
834#[inline]
837#[must_use]
838pub fn get_empty_scalar() -> TUnion {
839 TUnion::new(Cow::Borrowed(EMPTY_SCALAR_ATOMIC_SLICE.as_slice()))
840}
841
842#[inline]
843#[must_use]
844pub fn get_mixed_list() -> TUnion {
845 get_list(get_mixed())
846}
847
848#[inline]
849#[must_use]
850pub fn get_mixed_keyed_array() -> TUnion {
851 get_keyed_array(get_arraykey(), get_mixed())
852}
853
854#[inline]
855#[must_use]
856pub fn get_mixed_callable() -> TUnion {
857 TUnion::from_single(Cow::Borrowed(&MIXED_CALLABLE_ATOMIC))
858}
859
860#[inline]
861#[must_use]
862pub fn get_mixed_closure() -> TUnion {
863 TUnion::from_single(Cow::Borrowed(&MIXED_CLOSURE_ATOMIC))
864}
865
866#[inline]
867#[must_use]
868pub fn get_named_object(name: Word, type_resolution_context: Option<&TypeResolutionContext>) -> TUnion {
869 if let Some(type_resolution_context) = type_resolution_context
870 && let Some(defining_entities) = type_resolution_context.get_template_definition(name)
871 {
872 let first = &defining_entities[0];
873 return wrap_atomic(TAtomic::Scalar(TScalar::ClassLikeString(TClassLikeString::Generic {
874 kind: TClassLikeStringKind::Class,
875 parameter_name: name,
876 defining_entity: first.defining_entity,
877 constraint: Arc::new((*(first.constraint.get_single())).clone()),
878 })));
879 }
880
881 wrap_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(name))))
882}
883
884#[inline]
885#[must_use]
886pub fn get_list(element_type: TUnion) -> TUnion {
887 wrap_atomic(TAtomic::Array(TArray::List(TList::new(Arc::new(element_type)))))
888}
889
890#[inline]
891#[must_use]
892pub fn get_non_empty_list(element_type: TUnion) -> TUnion {
893 wrap_atomic(TAtomic::Array(TArray::List(TList::new_non_empty(Arc::new(element_type)))))
894}
895
896#[inline]
897#[must_use]
898pub fn get_keyed_array(key_parameter: TUnion, value_parameter: TUnion) -> TUnion {
899 wrap_atomic(TAtomic::Array(TArray::Keyed(TKeyedArray::new_with_parameters(
900 Arc::new(key_parameter),
901 Arc::new(value_parameter),
902 ))))
903}
904
905#[inline]
906#[must_use]
907pub fn add_optional_union_type(base_type: TUnion, maybe_type: Option<&TUnion>, codebase: &CodebaseMetadata) -> TUnion {
908 if let Some(type_2) = maybe_type {
909 add_union_type(base_type, type_2, codebase, combiner::CombinerOptions::default())
910 } else {
911 base_type
912 }
913}
914
915#[must_use]
917pub fn add_optional_union_type_rc(
918 base_type: &Rc<TUnion>,
919 maybe_type: Option<&TUnion>,
920 codebase: &CodebaseMetadata,
921) -> Rc<TUnion> {
922 match maybe_type {
923 Some(type_2) if base_type.as_ref() == type_2 => Rc::clone(base_type),
924 Some(type_2) => Rc::new(add_unequal_union_type_inner(
925 (**base_type).clone(),
926 type_2,
927 codebase,
928 combiner::CombinerOptions::default(),
929 false,
930 )),
931 None => Rc::clone(base_type),
932 }
933}
934
935#[inline]
936#[must_use]
937pub fn combine_optional_union_types(
938 type_1: Option<&TUnion>,
939 type_2: Option<&TUnion>,
940 codebase: &CodebaseMetadata,
941) -> TUnion {
942 match (type_1, type_2) {
943 (Some(type_1), Some(type_2)) => {
944 combine_union_types(type_1, type_2, codebase, combiner::CombinerOptions::default())
945 }
946 (Some(type_1), None) => type_1.clone(),
947 (None, Some(type_2)) => type_2.clone(),
948 (None, None) => get_mixed(),
949 }
950}
951
952#[inline]
954#[must_use]
955pub fn combine_union_types_rc(
956 type_1: &Rc<TUnion>,
957 type_2: &Rc<TUnion>,
958 codebase: &CodebaseMetadata,
959 options: combiner::CombinerOptions,
960) -> Rc<TUnion> {
961 if type_1 == type_2 {
962 return Rc::clone(type_1);
963 }
964
965 Rc::new(combine_unequal_union_types_inner(type_1, type_2, codebase, options, false))
966}
967
968#[inline]
970#[must_use]
971pub fn combine_owned_union_types_rc(
972 type_1: Rc<TUnion>,
973 type_2: &Rc<TUnion>,
974 codebase: &CodebaseMetadata,
975 options: combiner::CombinerOptions,
976) -> Rc<TUnion> {
977 if type_1 == *type_2 {
978 return type_1;
979 }
980
981 let combined = match Rc::try_unwrap(type_1) {
982 Ok(type_1) => combine_unequal_union_types_cow(Cow::Owned(type_1), type_2, codebase, options, false),
983 Err(type_1) => combine_unequal_union_types_inner(&type_1, type_2, codebase, options, false),
984 };
985
986 Rc::new(combined)
987}
988
989#[inline]
990#[must_use]
991pub fn combine_union_types(
992 type_1: &TUnion,
993 type_2: &TUnion,
994 codebase: &CodebaseMetadata,
995 options: combiner::CombinerOptions,
996) -> TUnion {
997 combine_union_types_inner(type_1, type_2, codebase, options, false)
998}
999
1000#[inline]
1001#[must_use]
1002pub fn combine_union_types_preserving_array_shapes(
1003 type_1: &TUnion,
1004 type_2: &TUnion,
1005 codebase: &CodebaseMetadata,
1006 options: combiner::CombinerOptions,
1007) -> TUnion {
1008 combine_union_types_inner(type_1, type_2, codebase, options, true)
1009}
1010
1011fn combine_union_types_inner(
1012 type_1: &TUnion,
1013 type_2: &TUnion,
1014 codebase: &CodebaseMetadata,
1015 options: combiner::CombinerOptions,
1016 preserve_array_shapes: bool,
1017) -> TUnion {
1018 if type_1 == type_2 {
1019 return type_1.clone();
1020 }
1021
1022 combine_unequal_union_types_inner(type_1, type_2, codebase, options, preserve_array_shapes)
1023}
1024
1025fn combine_unequal_union_types_inner(
1026 type_1: &TUnion,
1027 type_2: &TUnion,
1028 codebase: &CodebaseMetadata,
1029 options: combiner::CombinerOptions,
1030 preserve_array_shapes: bool,
1031) -> TUnion {
1032 combine_unequal_union_types_cow(Cow::Borrowed(type_1), type_2, codebase, options, preserve_array_shapes)
1033}
1034
1035fn combine_unequal_union_types_cow(
1036 type_1: Cow<'_, TUnion>,
1037 type_2: &TUnion,
1038 codebase: &CodebaseMetadata,
1039 options: combiner::CombinerOptions,
1040 preserve_array_shapes: bool,
1041) -> TUnion {
1042 let flags_1 = type_1.flags;
1043 let mut combined_type = if type_1.is_never() || type_1.is_never_template() {
1044 type_2.clone()
1045 } else if type_2.is_never() || type_2.is_never_template() {
1046 type_1.into_owned()
1047 } else if type_1.is_vanilla_mixed() && type_2.is_vanilla_mixed() {
1048 get_mixed()
1049 } else {
1050 let mut all_atomic_types = match type_1 {
1051 Cow::Borrowed(type_1) => type_1.types.to_vec(),
1052 Cow::Owned(type_1) => type_1.types.into_owned(),
1053 };
1054
1055 all_atomic_types.extend(type_2.types.iter().cloned());
1056
1057 let types = if preserve_array_shapes {
1058 combiner::combine_preserving_array_shapes(all_atomic_types, codebase, options)
1059 } else {
1060 combiner::combine(all_atomic_types, codebase, options)
1061 };
1062
1063 let mut result = TUnion::from_vec(types);
1064
1065 if flags_1.contains(UnionFlags::HAD_TEMPLATE) && type_2.had_template() {
1066 result.set_had_template(true);
1067 }
1068
1069 if flags_1.contains(UnionFlags::REFERENCE_FREE) && type_2.reference_free() {
1070 result.set_reference_free(true);
1071 }
1072
1073 result
1074 };
1075
1076 if flags_1.contains(UnionFlags::POSSIBLY_UNDEFINED) || type_2.possibly_undefined() {
1077 combined_type.set_possibly_undefined(true, None);
1078 }
1079
1080 if flags_1.contains(UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY) || type_2.possibly_undefined_from_try() {
1081 combined_type.set_possibly_undefined_from_try(true);
1082 }
1083
1084 if flags_1.contains(UnionFlags::IGNORE_FALSABLE_ISSUES) || type_2.ignore_falsable_issues() {
1085 combined_type.set_ignore_falsable_issues(true);
1086 }
1087
1088 combined_type
1089}
1090
1091#[inline]
1092#[must_use]
1093pub fn add_union_type(
1094 base_type: TUnion,
1095 other_type: &TUnion,
1096 codebase: &CodebaseMetadata,
1097 options: combiner::CombinerOptions,
1098) -> TUnion {
1099 add_union_type_inner(base_type, other_type, codebase, options, false)
1100}
1101
1102#[inline]
1103#[must_use]
1104pub fn add_union_type_preserving_array_shapes(
1105 base_type: TUnion,
1106 other_type: &TUnion,
1107 codebase: &CodebaseMetadata,
1108 options: combiner::CombinerOptions,
1109) -> TUnion {
1110 add_union_type_inner(base_type, other_type, codebase, options, true)
1111}
1112
1113fn add_union_type_inner(
1114 base_type: TUnion,
1115 other_type: &TUnion,
1116 codebase: &CodebaseMetadata,
1117 options: combiner::CombinerOptions,
1118 preserve_array_shapes: bool,
1119) -> TUnion {
1120 if &base_type == other_type {
1121 return base_type;
1122 }
1123
1124 add_unequal_union_type_inner(base_type, other_type, codebase, options, preserve_array_shapes)
1125}
1126
1127fn add_unequal_union_type_inner(
1128 base_type: TUnion,
1129 other_type: &TUnion,
1130 codebase: &CodebaseMetadata,
1131 options: combiner::CombinerOptions,
1132 preserve_array_shapes: bool,
1133) -> TUnion {
1134 let original_flags = base_type.flags;
1135 let mut base_type = if base_type.is_vanilla_mixed() && other_type.is_vanilla_mixed() {
1136 base_type
1137 } else {
1138 combine_unequal_union_types_cow(Cow::Owned(base_type), other_type, codebase, options, preserve_array_shapes)
1139 };
1140 base_type.flags = original_flags;
1141
1142 if !other_type.had_template() {
1143 base_type.set_had_template(false);
1144 }
1145
1146 if !other_type.reference_free() {
1147 base_type.set_reference_free(false);
1148 }
1149
1150 if other_type.possibly_undefined() {
1151 base_type.set_possibly_undefined(true, None);
1152 }
1153 if other_type.possibly_undefined_from_try() {
1154 base_type.set_possibly_undefined_from_try(true);
1155 }
1156 if other_type.ignore_falsable_issues() {
1157 base_type.set_ignore_falsable_issues(true);
1158 }
1159 if other_type.ignore_nullable_issues() {
1160 base_type.set_ignore_nullable_issues(true);
1161 }
1162
1163 base_type
1164}
1165
1166#[must_use]
1167pub fn intersect_union_types(type_1: &TUnion, type_2: &TUnion, codebase: &CodebaseMetadata) -> Option<TUnion> {
1168 if type_1 == type_2 {
1169 return Some(type_1.clone());
1170 }
1171
1172 if type_1.is_never() || type_2.is_never() {
1173 return Some(get_never());
1174 }
1175
1176 let mut intersection_performed = false;
1177
1178 if type_1.is_mixed() {
1179 if type_2.is_mixed() {
1180 return Some(get_mixed());
1181 }
1182
1183 return Some(type_2.clone());
1184 } else if type_2.is_mixed() {
1185 return Some(type_1.clone());
1186 }
1187
1188 let mut intersected_atomic_types = vec![];
1189 for type_1_atomic in type_1.types.iter() {
1190 for type_2_atomic in type_2.types.iter() {
1191 if let Some(intersection_atomic) =
1192 intersect_atomic_types(type_1_atomic, type_2_atomic, codebase, &mut intersection_performed)
1193 {
1194 intersected_atomic_types.push(intersection_atomic);
1195 }
1196 }
1197 }
1198
1199 let mut combined_type: Option<TUnion> = None;
1200 if !intersected_atomic_types.is_empty() {
1201 let combined_vec = combiner::combine(intersected_atomic_types, codebase, combiner::CombinerOptions::default());
1202 if !combined_vec.is_empty() {
1203 combined_type = Some(TUnion::from_vec(combined_vec));
1204 }
1205 }
1206
1207 if !intersection_performed {
1209 if union_comparator::is_contained_by(
1210 codebase,
1211 type_1,
1212 type_2,
1213 false,
1214 false,
1215 false,
1216 &mut ComparisonResult::default(),
1217 ) {
1218 combined_type = Some(type_1.clone());
1219 } else if union_comparator::is_contained_by(
1220 codebase,
1221 type_2,
1222 type_1,
1223 false,
1224 false,
1225 false,
1226 &mut ComparisonResult::default(),
1227 ) {
1228 combined_type = Some(type_2.clone());
1229 }
1230 }
1231
1232 if let Some(mut final_type) = combined_type {
1233 final_type.set_possibly_undefined(
1234 type_1.possibly_undefined() && type_2.possibly_undefined(),
1235 Some(type_1.possibly_undefined_from_try() && type_2.possibly_undefined_from_try()),
1236 );
1237 final_type.set_ignore_falsable_issues(type_1.ignore_falsable_issues() && type_2.ignore_falsable_issues());
1238 final_type.set_ignore_nullable_issues(type_1.ignore_nullable_issues() && type_2.ignore_nullable_issues());
1239
1240 return Some(final_type);
1241 }
1242
1243 None
1244}
1245
1246fn intersect_atomic_types(
1248 type_1: &TAtomic,
1249 type_2: &TAtomic,
1250 codebase: &CodebaseMetadata,
1251 intersection_performed: &mut bool,
1252) -> Option<TAtomic> {
1253 if type_1 == type_2 {
1254 *intersection_performed = true;
1255 return Some(type_1.clone());
1256 }
1257
1258 if let (TAtomic::Scalar(TScalar::Integer(t1_int)), TAtomic::Scalar(TScalar::Integer(t2_int))) = (type_1, type_2) {
1259 let (min1, max1) = t1_int.get_bounds();
1260 let (min2, max2) = t2_int.get_bounds();
1261
1262 let new_min = match (min1, min2) {
1263 (Some(m1), Some(m2)) => Some(m1.max(m2)),
1264 (Some(m), None) | (None, Some(m)) => Some(m),
1265 (None, None) => None,
1266 };
1267
1268 let new_max = match (max1, max2) {
1269 (Some(m1), Some(m2)) => Some(m1.min(m2)),
1270 (Some(m), None) | (None, Some(m)) => Some(m),
1271 (None, None) => None,
1272 };
1273
1274 let intersected_int = if let (Some(min), Some(max)) = (new_min, new_max) {
1275 if min > max {
1276 return None;
1277 }
1278
1279 if min == max { TInteger::Literal(min) } else { TInteger::Range(min, max) }
1280 } else if let Some(min) = new_min {
1281 TInteger::From(min)
1282 } else if let Some(max) = new_max {
1283 TInteger::To(max)
1284 } else {
1285 TInteger::Unspecified
1286 };
1287
1288 *intersection_performed = true;
1289 return Some(TAtomic::Scalar(TScalar::Integer(intersected_int)));
1290 }
1291
1292 let t1_union = TUnion::from_atomic(type_1.clone());
1293 let t2_union = TUnion::from_atomic(type_2.clone());
1294
1295 let mut narrower_type = None;
1296 let mut wider_type = None;
1297
1298 if union_comparator::is_contained_by(
1299 codebase,
1300 &t2_union,
1301 &t1_union,
1302 false,
1303 false,
1304 false,
1305 &mut ComparisonResult::default(),
1306 ) {
1307 narrower_type = Some(type_2);
1308 wider_type = Some(type_1);
1309 } else if union_comparator::is_contained_by(
1310 codebase,
1311 &t1_union,
1312 &t2_union,
1313 false,
1314 false,
1315 false,
1316 &mut ComparisonResult::default(),
1317 ) {
1318 narrower_type = Some(type_1);
1319 wider_type = Some(type_2);
1320 }
1321
1322 if let (Some(narrower), Some(wider)) = (narrower_type, wider_type) {
1323 *intersection_performed = true;
1324 let mut result = narrower.clone();
1325
1326 if narrower.can_be_intersected() && wider.can_be_intersected() {
1327 let mut wider_clone = wider.clone();
1328 if let Some(types) = wider_clone.get_intersection_types_mut() {
1329 types.clear();
1330 }
1331
1332 for part in
1333 std::iter::once(wider_clone).chain(wider.get_intersection_types().into_iter().flatten().cloned())
1334 {
1335 if part != *narrower && !result.get_intersection_types().is_some_and(|types| types.contains(&part)) {
1336 result.add_intersection_type(part);
1337 }
1338 }
1339 }
1340 return Some(result);
1341 }
1342
1343 if let (TAtomic::Array(left_array), TAtomic::Array(right_array)) = (type_1, type_2) {
1344 let array_has_known_shape = |array: &TArray| match array {
1345 TArray::List(list) => list.known_elements.is_some(),
1346 TArray::Keyed(keyed) => keyed.known_items.is_some(),
1347 };
1348
1349 if array_has_known_shape(left_array) || array_has_known_shape(right_array) {
1350 return None;
1351 }
1352
1353 let (left_key, left_value) = get_array_parameters(left_array, codebase);
1354 let (right_key, right_value) = get_array_parameters(right_array, codebase);
1355
1356 let key = intersect_union_types(&left_key, &right_key, codebase).unwrap_or_else(get_never);
1357 let value = intersect_union_types(&left_value, &right_value, codebase).unwrap_or_else(get_never);
1358
1359 let is_list = left_array.is_list() || right_array.is_list();
1360 let non_empty = left_array.is_non_empty() || right_array.is_non_empty();
1361
1362 if non_empty && (key.is_never() || value.is_never()) {
1363 return None;
1364 }
1365
1366 *intersection_performed = true;
1367 let array = if is_list {
1368 let mut list = TList::new(Arc::new(value));
1369 list.non_empty = non_empty;
1370 TArray::List(list)
1371 } else {
1372 TArray::Keyed(TKeyedArray::new_with_parameters(Arc::new(key), Arc::new(value)).with_non_empty(non_empty))
1373 };
1374
1375 return Some(TAtomic::Array(array));
1376 }
1377
1378 if let (TAtomic::Scalar(TScalar::String(s)), TAtomic::Scalar(TScalar::Numeric))
1379 | (TAtomic::Scalar(TScalar::Numeric), TAtomic::Scalar(TScalar::String(s))) = (type_1, type_2)
1380 {
1381 *intersection_performed = true;
1382 return Some(TAtomic::Scalar(TScalar::String(s.as_numeric(true))));
1383 }
1384
1385 if let (TAtomic::Scalar(TScalar::String(s1)), TAtomic::Scalar(TScalar::String(s2))) = (type_1, type_2) {
1386 if let (Some(v1), Some(v2)) = (&s1.get_known_literal_value(), &s2.get_known_literal_value())
1387 && v1 != v2
1388 {
1389 return None;
1390 }
1391
1392 let combined = TAtomic::Scalar(TScalar::String(TString {
1393 is_numeric: s1.is_numeric || s2.is_numeric,
1394 is_truthy: s1.is_truthy || s2.is_truthy,
1395 is_non_empty: s1.is_non_empty || s2.is_non_empty,
1396 is_callable: false,
1397 casing: match (s1.casing, s2.casing) {
1398 (TStringCasing::Lowercase, TStringCasing::Lowercase) => TStringCasing::Lowercase,
1399 (TStringCasing::Uppercase, TStringCasing::Uppercase) => TStringCasing::Uppercase,
1400 _ => TStringCasing::Unspecified,
1401 },
1402 literal: if s1.is_literal_origin() && s2.is_literal_origin() {
1403 Some(TStringLiteral::Unspecified)
1404 } else {
1405 None
1406 },
1407 }));
1408 *intersection_performed = true;
1409 return Some(combined);
1410 }
1411
1412 if type_1.can_be_intersected() && type_2.can_be_intersected() {
1413 if let (TAtomic::Object(TObject::Named(n1)), TAtomic::Object(TObject::Named(n2))) = (type_1, type_2)
1414 && let (Some(c1), Some(c2)) =
1415 (codebase.get_class_like(n1.name.as_bytes()), codebase.get_class_like(n2.name.as_bytes()))
1416 && !c1.kind.is_interface()
1417 && !c1.kind.is_trait()
1418 && !c2.kind.is_interface()
1419 && !c2.kind.is_trait()
1420 {
1421 return None;
1422 }
1423
1424 let mut result = type_1.clone();
1425 result.add_intersection_type(type_2.clone());
1426 if let Some(intersections) = type_2.get_intersection_types() {
1427 for i in intersections {
1428 result.add_intersection_type(i.clone());
1429 }
1430 }
1431
1432 *intersection_performed = true;
1433 return Some(result);
1434 }
1435
1436 None
1437}
1438
1439#[must_use]
1440pub fn get_iterable_parameters(atomic: &TAtomic, codebase: &CodebaseMetadata) -> Option<(TUnion, TUnion)> {
1441 let (mut key, mut value) = get_iterable_parameters_impl(atomic, codebase, &[])?;
1442 if let TAtomic::Object(object @ TObject::Named(_)) = atomic {
1443 let has_static = |union: &TUnion| {
1444 union.types.iter().any(
1445 |atomic| matches!(atomic, TAtomic::Object(TObject::Named(named)) if named.is_static || named.is_this),
1446 )
1447 };
1448
1449 if has_static(&key) || has_static(&value) {
1450 let options = TypeExpansionOptions {
1451 static_class_type: StaticClassType::Object(object.clone()),
1452 ..Default::default()
1453 };
1454 expander::expand_union(codebase, &mut key, &options);
1455 expander::expand_union(codebase, &mut value, &options);
1456 }
1457 }
1458
1459 Some((key, value))
1460}
1461
1462fn get_iterable_parameters_impl(
1463 atomic: &TAtomic,
1464 codebase: &CodebaseMetadata,
1465 visited_aggregates: &[Word],
1466) -> Option<(TUnion, TUnion)> {
1467 let mut parameters = get_primary_iterable_parameters(atomic, codebase, visited_aggregates);
1468 for intersection in atomic.get_intersection_types().unwrap_or_default() {
1469 let Some((key, value)) = get_iterable_parameters_impl(intersection, codebase, visited_aggregates) else {
1470 continue;
1471 };
1472
1473 parameters = Some(match parameters {
1474 Some((primary_key, primary_value)) => (
1475 intersect_read_types(&primary_key, &key, codebase),
1476 intersect_read_types(&primary_value, &value, codebase),
1477 ),
1478 None => (key, value),
1479 });
1480 }
1481
1482 parameters
1483}
1484
1485fn get_primary_iterable_parameters(
1486 atomic: &TAtomic,
1487 codebase: &CodebaseMetadata,
1488 visited_aggregates: &[Word],
1489) -> Option<(TUnion, TUnion)> {
1490 if atomic.is_generator()
1491 && let Some(generator_parameters) = atomic.get_generator_parameters()
1492 {
1493 let mut key_type = generator_parameters.0;
1494 let mut value_type = generator_parameters.1;
1495
1496 expander::expand_union(codebase, &mut key_type, &TypeExpansionOptions::default());
1497 expander::expand_union(codebase, &mut value_type, &TypeExpansionOptions::default());
1498
1499 return Some((key_type, value_type));
1500 }
1501
1502 'parameters: {
1503 match atomic {
1504 TAtomic::Iterable(iterable) => {
1505 let mut key_type = iterable.get_key_type().clone();
1506 let mut value_type = iterable.get_value_type().clone();
1507
1508 expander::expand_union(codebase, &mut key_type, &TypeExpansionOptions::default());
1509 expander::expand_union(codebase, &mut value_type, &TypeExpansionOptions::default());
1510
1511 Some((key_type, value_type))
1512 }
1513 TAtomic::Array(array_type) => {
1514 let (mut key_type, mut value_type) = get_array_parameters(array_type, codebase);
1515
1516 expander::expand_union(codebase, &mut key_type, &TypeExpansionOptions::default());
1517 expander::expand_union(codebase, &mut value_type, &TypeExpansionOptions::default());
1518
1519 Some((key_type, value_type))
1520 }
1521 TAtomic::Object(object) => {
1522 let name = object.get_name()?;
1523 let traversable = word("traversable");
1524 let iterator = word("iterator");
1525 let iterator_aggregate = word("iteratoraggregate");
1526
1527 let class_metadata = codebase.get_class_like(name.as_bytes())?;
1528 let is_iterator_interface = class_metadata.name == iterator
1529 || class_metadata.name == traversable
1530 || class_metadata.name == iterator_aggregate;
1531
1532 if !is_iterator_interface && !class_metadata.all_parent_interfaces.contains(&traversable) {
1533 break 'parameters None;
1534 }
1535
1536 let traversable_metadata = codebase.get_class_like(traversable.as_bytes())?;
1537 let key_template = traversable_metadata.template_types.get_index(0).map(|(name, _)| *name)?;
1538 let value_template = traversable_metadata.template_types.get_index(1).map(|(name, _)| *name)?;
1539
1540 let mut key_type = get_specialized_template_type(
1541 codebase,
1542 key_template,
1543 traversable,
1544 class_metadata,
1545 object.get_type_parameters(),
1546 )
1547 .unwrap_or_else(get_mixed);
1548
1549 let mut value_type = get_specialized_template_type(
1550 codebase,
1551 value_template,
1552 traversable,
1553 class_metadata,
1554 object.get_type_parameters(),
1555 )
1556 .unwrap_or_else(get_mixed);
1557
1558 resolve_unbound_generic_parameters(
1559 codebase,
1560 class_metadata,
1561 object.get_type_parameters(),
1562 &mut key_type,
1563 );
1564 resolve_unbound_generic_parameters(
1565 codebase,
1566 class_metadata,
1567 object.get_type_parameters(),
1568 &mut value_type,
1569 );
1570
1571 if is_iterator_interface || (!key_type.is_mixed() && !value_type.is_mixed()) {
1572 return Some((key_type, value_type));
1573 }
1574
1575 if class_metadata.all_parent_interfaces.contains(&iterator) {
1576 if key_type.is_mixed()
1577 && let Some(method_key) = get_iterator_method_return_type(
1578 codebase,
1579 class_metadata,
1580 object.get_type_parameters(),
1581 b"key",
1582 )
1583 && !method_key.is_mixed()
1584 {
1585 key_type = method_key;
1586 }
1587
1588 if value_type.is_mixed()
1589 && let Some(method_val) = get_iterator_method_return_type(
1590 codebase,
1591 class_metadata,
1592 object.get_type_parameters(),
1593 b"current",
1594 )
1595 && !method_val.is_mixed()
1596 {
1597 value_type = method_val;
1598 }
1599 } else if class_metadata.all_parent_interfaces.contains(&iterator_aggregate)
1600 && !visited_aggregates.contains(&class_metadata.name)
1601 && let Some(inner_iter) = get_iterator_method_return_type(
1602 codebase,
1603 class_metadata,
1604 object.get_type_parameters(),
1605 b"getiterator",
1606 )
1607 {
1608 let mut next_visited = Vec::with_capacity(visited_aggregates.len() + 1);
1609 next_visited.extend_from_slice(visited_aggregates);
1610 next_visited.push(class_metadata.name);
1611
1612 if let Some((inner_k, inner_v)) =
1613 inner_iter.types.iter().try_fold((get_never(), get_never()), |(key, value), atomic_inner| {
1614 let (inner_key, inner_value) =
1615 get_iterable_parameters_impl(atomic_inner, codebase, &next_visited)?;
1616
1617 Some((
1618 add_union_type(key, &inner_key, codebase, combiner::CombinerOptions::default()),
1619 add_union_type(value, &inner_value, codebase, combiner::CombinerOptions::default()),
1620 ))
1621 })
1622 {
1623 if key_type.is_mixed() && !inner_k.is_mixed() {
1624 key_type = inner_k;
1625 }
1626 if value_type.is_mixed() && !inner_v.is_mixed() {
1627 value_type = inner_v;
1628 }
1629 }
1630 }
1631
1632 Some((key_type, value_type))
1633 }
1634 _ => None,
1635 }
1636 }
1637}
1638
1639#[must_use]
1640pub fn get_array_parameters(array_type: &TArray, codebase: &CodebaseMetadata) -> (TUnion, TUnion) {
1641 match array_type {
1642 TArray::Keyed(keyed_data) => {
1643 let mut key_types = vec![];
1644 let mut value_param;
1645
1646 if let Some((key_param, value_p)) = &keyed_data.parameters {
1647 key_types.extend(key_param.types.iter().cloned());
1648 value_param = (**value_p).clone();
1649 } else {
1650 key_types.push(TAtomic::Never);
1651 value_param = get_never();
1652 }
1653
1654 if let Some(known_items) = &keyed_data.known_items {
1655 for (key, (_, item_type)) in known_items.iter() {
1656 key_types.push(key.to_atomic());
1657 value_param =
1658 add_union_type(value_param, item_type, codebase, combiner::CombinerOptions::default());
1659 }
1660 }
1661
1662 if key_types.is_empty() {
1663 key_types.push(TAtomic::Never);
1664 }
1665
1666 let combined_key_types = combiner::combine(key_types, codebase, combiner::CombinerOptions::default());
1667 let key_param_union = TUnion::from_vec(combined_key_types);
1668
1669 (key_param_union, value_param)
1670 }
1671 TArray::List(list_data) => {
1672 let mut key_types = vec![];
1673 let mut value_type = (*list_data.element_type).clone();
1674
1675 if let Some(known_elements) = &list_data.known_elements {
1676 for (key_idx, (_, element_type)) in known_elements.iter() {
1677 key_types.push(TAtomic::Scalar(TScalar::literal_int(*key_idx as i64)));
1678
1679 value_type =
1680 combine_union_types(element_type, &value_type, codebase, combiner::CombinerOptions::default());
1681 }
1682 }
1683
1684 if key_types.is_empty() || !value_type.is_never() {
1685 if value_type.is_never() {
1686 key_types.push(TAtomic::Never);
1687 } else {
1688 key_types.push(TAtomic::Scalar(TScalar::Integer(TInteger::non_negative())));
1689 }
1690 }
1691
1692 let key_type =
1693 TUnion::from_vec(combiner::combine(key_types, codebase, combiner::CombinerOptions::default()));
1694
1695 (key_type, value_type)
1696 }
1697 }
1698}
1699
1700#[must_use]
1701pub fn get_iterable_value_parameter(atomic: &TAtomic, codebase: &CodebaseMetadata) -> Option<TUnion> {
1702 if let TAtomic::Array(array) = atomic {
1703 return Some(get_array_value_parameter(array, codebase));
1704 }
1705
1706 get_iterable_value_parameter_impl(atomic, codebase, &[])
1707}
1708
1709fn get_iterable_value_parameter_impl(
1710 atomic: &TAtomic,
1711 codebase: &CodebaseMetadata,
1712 visited_aggregates: &[Word],
1713) -> Option<TUnion> {
1714 let mut value = get_primary_iterable_value_parameter(atomic, codebase, visited_aggregates);
1715 for intersection in atomic.get_intersection_types().unwrap_or_default() {
1716 let Some(intersection_value) = get_iterable_value_parameter_impl(intersection, codebase, visited_aggregates)
1717 else {
1718 continue;
1719 };
1720
1721 value = Some(match value {
1722 Some(primary) => intersect_read_types(&primary, &intersection_value, codebase),
1723 None => intersection_value,
1724 });
1725 }
1726
1727 value
1728}
1729
1730fn get_primary_iterable_value_parameter(
1731 atomic: &TAtomic,
1732 codebase: &CodebaseMetadata,
1733 visited_aggregates: &[Word],
1734) -> Option<TUnion> {
1735 if atomic.is_generator()
1736 && let Some(generator_parameters) = atomic.get_generator_parameters()
1737 {
1738 return Some(generator_parameters.1);
1739 }
1740
1741 match atomic {
1742 TAtomic::Iterable(iterable) => Some(iterable.get_value_type().clone()),
1743 TAtomic::Array(array_type) => Some(get_array_value_parameter(array_type, codebase)),
1744 TAtomic::Object(object) => {
1745 let name = object.get_name()?;
1746 let traversable = word("traversable");
1747
1748 let class_metadata = codebase.get_class_like(name.as_bytes())?;
1749 if !codebase.is_instance_of(class_metadata.name.as_bytes(), traversable.as_bytes()) {
1750 return None;
1751 }
1752
1753 let traversable_metadata = codebase.get_class_like(traversable.as_bytes())?;
1754 let value_template = traversable_metadata.template_types.get_index(1).map(|(name, _)| *name)?;
1755
1756 let mut value = get_specialized_template_type(
1757 codebase,
1758 value_template,
1759 traversable,
1760 class_metadata,
1761 object.get_type_parameters(),
1762 )?;
1763
1764 resolve_unbound_generic_parameters(codebase, class_metadata, object.get_type_parameters(), &mut value);
1765 if !value.is_mixed() {
1766 return Some(value);
1767 }
1768
1769 if class_metadata.all_parent_interfaces.contains(&word("iterator")) {
1770 return get_iterator_method_return_type(
1771 codebase,
1772 class_metadata,
1773 object.get_type_parameters(),
1774 b"current",
1775 )
1776 .or(Some(value));
1777 }
1778
1779 if class_metadata.all_parent_interfaces.contains(&word("iteratoraggregate"))
1780 && !visited_aggregates.contains(&class_metadata.name)
1781 && let Some(iterator) = get_iterator_method_return_type(
1782 codebase,
1783 class_metadata,
1784 object.get_type_parameters(),
1785 b"getiterator",
1786 )
1787 {
1788 let mut visited = Vec::with_capacity(visited_aggregates.len() + 1);
1789 visited.extend_from_slice(visited_aggregates);
1790 visited.push(class_metadata.name);
1791
1792 return iterator
1793 .types
1794 .iter()
1795 .try_fold(get_never(), |result, atomic| {
1796 let inner = get_iterable_value_parameter_impl(atomic, codebase, &visited)?;
1797
1798 Some(add_union_type(result, &inner, codebase, combiner::CombinerOptions::default()))
1799 })
1800 .or(Some(value));
1801 }
1802
1803 Some(value)
1804 }
1805 _ => None,
1806 }
1807}
1808
1809#[must_use]
1810pub fn get_array_value_parameter(array_type: &TArray, codebase: &CodebaseMetadata) -> TUnion {
1811 match array_type {
1812 TArray::Keyed(keyed_data) => {
1813 let mut value_param;
1814
1815 if let Some((_, value_p)) = &keyed_data.parameters {
1816 value_param = (**value_p).clone();
1817 } else {
1818 value_param = get_never();
1819 }
1820
1821 if let Some(known_items) = &keyed_data.known_items {
1822 for (_, item_type) in known_items.values() {
1823 value_param =
1824 combine_union_types(item_type, &value_param, codebase, combiner::CombinerOptions::default());
1825 }
1826 }
1827
1828 value_param
1829 }
1830 TArray::List(list_data) => {
1831 let mut value_param = (*list_data.element_type).clone();
1832
1833 if let Some(known_elements) = &list_data.known_elements {
1834 for (_, element_type) in known_elements.values() {
1835 value_param =
1836 combine_union_types(element_type, &value_param, codebase, combiner::CombinerOptions::default());
1837 }
1838 }
1839
1840 value_param
1841 }
1842 }
1843}
1844
1845#[must_use]
1850pub fn get_specialized_template_type(
1851 codebase: &CodebaseMetadata,
1852 template_name: Word,
1853 template_defining_class_id: Word,
1854 instantiated_class_metadata: &ClassLikeMetadata,
1855 instantiated_type_parameters: Option<&[TUnion]>,
1856) -> Option<TUnion> {
1857 let defining_class_metadata = codebase.get_class_like(template_defining_class_id.as_bytes())?;
1858
1859 if defining_class_metadata.name == instantiated_class_metadata.name {
1860 let index = instantiated_class_metadata.get_template_index_for_name(template_name)?;
1861
1862 let Some(instantiated_type_parameters) = instantiated_type_parameters else {
1863 let template = instantiated_class_metadata.get_template_type(template_name)?;
1864 let mut result = template.constraint.clone();
1865
1866 expander::expand_union(codebase, &mut result, &TypeExpansionOptions::default());
1867
1868 return Some(result);
1869 };
1870
1871 let mut result = instantiated_type_parameters.get(index).cloned()?;
1872
1873 expander::expand_union(codebase, &mut result, &TypeExpansionOptions::default());
1874
1875 return Some(result);
1876 }
1877
1878 let template = defining_class_metadata.get_template_type(template_name)?;
1879 let template_union = wrap_atomic(TAtomic::GenericParameter(TGenericParameter {
1880 parameter_name: template_name,
1881 defining_entity: template.defining_entity,
1882 constraint: Arc::new(template.constraint.clone()),
1883 intersection_types: None,
1884 }));
1885
1886 let mut template_result = TemplateResult::default();
1887 for (defining_class, template_parameters) in &instantiated_class_metadata.template_extended_parameters {
1888 for (parameter_name, parameter_type) in template_parameters {
1889 template_result.add_lower_bound(
1890 *parameter_name,
1891 GenericParent::ClassLike(*defining_class),
1892 parameter_type.clone(),
1893 );
1894 }
1895 }
1896
1897 let mut template_type = inferred_type_replacer::replace(&template_union, &template_result, codebase);
1898 if let Some(type_parameters) = instantiated_type_parameters {
1899 let mut template_result = TemplateResult::default();
1900 for (i, parameter_type) in type_parameters.iter().enumerate() {
1901 if let Some(parameter_name) = instantiated_class_metadata.get_template_name_for_index(i) {
1902 template_result.add_lower_bound(
1903 parameter_name,
1904 GenericParent::ClassLike(instantiated_class_metadata.name),
1905 parameter_type.clone(),
1906 );
1907 }
1908 }
1909
1910 if !template_result.lower_bounds.is_empty() {
1911 template_type = inferred_type_replacer::replace(&template_type, &template_result, codebase);
1912 }
1913 }
1914
1915 expander::expand_union(
1916 codebase,
1917 &mut template_type,
1918 &TypeExpansionOptions {
1919 static_class_type: StaticClassType::Name(instantiated_class_metadata.original_name),
1920 ..Default::default()
1921 },
1922 );
1923
1924 Some(template_type)
1925}
1926
1927fn resolve_unbound_generic_parameters(
1928 codebase: &CodebaseMetadata,
1929 class_metadata: &ClassLikeMetadata,
1930 type_parameters: Option<&[TUnion]>,
1931 union: &mut TUnion,
1932) {
1933 if !union.has_template_types() {
1934 return;
1935 }
1936
1937 let mut template_result = TemplateResult::default();
1938 for node in union.get_all_child_nodes() {
1939 if let TypeRef::Atomic(TAtomic::GenericParameter(parameter)) = node
1940 && is_unbound_class_template(class_metadata, type_parameters, parameter)
1941 {
1942 template_result.add_lower_bound(
1943 parameter.parameter_name,
1944 parameter.defining_entity,
1945 (*parameter.constraint).clone(),
1946 );
1947 }
1948 }
1949
1950 if !template_result.lower_bounds.is_empty() {
1951 *union = inferred_type_replacer::replace(union, &template_result, codebase);
1952 }
1953}
1954
1955fn is_unbound_class_template(
1956 class_metadata: &ClassLikeMetadata,
1957 type_parameters: Option<&[TUnion]>,
1958 parameter: &TGenericParameter,
1959) -> bool {
1960 let GenericParent::ClassLike(defining_class) = parameter.defining_entity else {
1961 return false;
1962 };
1963
1964 if defining_class == class_metadata.name {
1965 return type_parameters.is_none_or(|type_parameters| {
1966 class_metadata
1967 .get_template_index_for_name(parameter.parameter_name)
1968 .is_none_or(|index| index >= type_parameters.len())
1969 });
1970 }
1971
1972 (class_metadata.all_parent_classes.contains(&defining_class)
1973 || class_metadata.all_parent_interfaces.contains(&defining_class))
1974 && !class_metadata
1975 .template_extended_parameters
1976 .get(&defining_class)
1977 .is_some_and(|parameters| parameters.contains_key(¶meter.parameter_name))
1978}
1979
1980#[must_use]
1982pub fn get_iterator_method_return_type(
1983 codebase: &CodebaseMetadata,
1984 class_metadata: &ClassLikeMetadata,
1985 type_parameters: Option<&[TUnion]>,
1986 method_name: &[u8],
1987) -> Option<TUnion> {
1988 let method = codebase.get_declaring_method(class_metadata.name.as_bytes(), method_name)?;
1989 let return_type_meta = method.return_type_metadata.as_ref()?;
1990 let mut return_type = return_type_meta.type_union.clone();
1991
1992 if return_type.has_template_types() {
1993 let mut template_result = TemplateResult::default();
1994 for node in return_type.get_all_child_nodes() {
1995 if let TypeRef::Atomic(TAtomic::GenericParameter(parameter)) = node
1996 && let GenericParent::ClassLike(class_name) = parameter.defining_entity
1997 && let Some(template_type) = get_specialized_template_type(
1998 codebase,
1999 parameter.parameter_name,
2000 class_name,
2001 class_metadata,
2002 type_parameters,
2003 )
2004 {
2005 template_result.add_lower_bound(parameter.parameter_name, parameter.defining_entity, template_type);
2006 }
2007 }
2008
2009 if !template_result.lower_bounds.is_empty() {
2010 return_type = inferred_type_replacer::replace(&return_type, &template_result, codebase);
2011 }
2012
2013 resolve_unbound_generic_parameters(codebase, class_metadata, type_parameters, &mut return_type);
2014 }
2015
2016 let expansion_options = TypeExpansionOptions {
2017 self_class: Some(class_metadata.name),
2018 static_class_type: StaticClassType::Name(class_metadata.name),
2019 ..Default::default()
2020 };
2021 expander::expand_union(codebase, &mut return_type, &expansion_options);
2022 Some(return_type)
2023}
2024
2025#[cfg(test)]
2026mod tests {
2027 use std::rc::Rc;
2028
2029 use mago_word::word;
2030
2031 use crate::metadata::CodebaseMetadata;
2032 use crate::ttype::atomic::TAtomic;
2033 use crate::ttype::atomic::object::TObject;
2034 use crate::ttype::atomic::object::named::TNamedObject;
2035 use crate::ttype::combiner::CombinerOptions;
2036 use crate::ttype::flags::UnionFlags;
2037 use crate::ttype::union::TUnion;
2038
2039 use super::add_optional_union_type;
2040 use super::add_optional_union_type_rc;
2041 use super::combine_owned_union_types_rc;
2042 use super::combine_union_types;
2043 use super::combine_union_types_rc;
2044 use super::get_empty_keyed_array;
2045 use super::get_int;
2046 use super::get_list;
2047 use super::get_mixed;
2048 use super::get_never;
2049 use super::get_string;
2050 use super::intersect_union_types;
2051
2052 fn assert_exact(actual: &TUnion, expected: &TUnion) {
2053 assert_eq!(actual.types, expected.types);
2054 assert_eq!(actual.flags, expected.flags);
2055 }
2056
2057 #[test]
2058 fn rc_merges_keep_the_first_equal_union_and_all_its_flags() {
2059 let codebase = CodebaseMetadata::new();
2060 let ignored_flags = [
2061 UnionFlags::empty(),
2062 UnionFlags::POPULATED,
2063 UnionFlags::NULLSAFE_NULL,
2064 UnionFlags::POPULATED.union(UnionFlags::NULLSAFE_NULL),
2065 ];
2066 for first_flags in ignored_flags {
2067 for second_flags in ignored_flags {
2068 let mut first = get_int();
2069 let shared_flags = UnionFlags::HAD_TEMPLATE
2070 .union(UnionFlags::BY_REFERENCE)
2071 .union(UnionFlags::REFERENCE_FREE)
2072 .union(UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY)
2073 .union(UnionFlags::POSSIBLY_UNDEFINED)
2074 .union(UnionFlags::IGNORE_NULLABLE_ISSUES)
2075 .union(UnionFlags::IGNORE_FALSABLE_ISSUES)
2076 .union(UnionFlags::FROM_TEMPLATE_DEFAULT)
2077 .union(UnionFlags::FROM_UNSPECIFIED_TEMPLATE);
2078 first.flags = first_flags.union(shared_flags);
2079 let mut second = first.clone();
2080 second.flags = second_flags.union(shared_flags);
2081 let first = Rc::new(first);
2082 let second = Rc::new(second);
2083 assert!(!Rc::ptr_eq(&first, &second));
2084 assert_eq!(first, second);
2085
2086 let expected = combine_union_types(&first, &second, &codebase, CombinerOptions::default());
2087 let actual = combine_union_types_rc(&first, &second, &codebase, CombinerOptions::default());
2088 assert_exact(&actual, &expected);
2089 assert!(Rc::ptr_eq(&actual, &first));
2090
2091 let expected = add_optional_union_type((*first).clone(), Some(&second), &codebase);
2092 let actual = add_optional_union_type_rc(&first, Some(&second), &codebase);
2093 assert_exact(&actual, &expected);
2094 assert!(Rc::ptr_eq(&actual, &first));
2095 }
2096 }
2097 }
2098
2099 #[test]
2100 fn repeated_intersection_with_the_same_object_does_not_grow() {
2101 let codebase = CodebaseMetadata::new();
2102 let array_access = TUnion::from_atomic(TAtomic::Object(TObject::Named(TNamedObject::new(word("ArrayAccess")))));
2103 let mut narrowed = Some(array_access.clone());
2104 for _ in 0..3 {
2105 narrowed = narrowed.and_then(|narrowed| intersect_union_types(&narrowed, &array_access, &codebase));
2106 }
2107
2108 assert_eq!(narrowed.map(|narrowed| narrowed.types), Some(array_access.types));
2109 }
2110
2111 #[test]
2112 fn rc_merges_keep_identical_and_missing_optional_inputs() {
2113 let codebase = CodebaseMetadata::new();
2114 let first = Rc::new(get_int());
2115 assert!(Rc::ptr_eq(&combine_union_types_rc(&first, &first, &codebase, CombinerOptions::default()), &first));
2116 assert!(Rc::ptr_eq(&add_optional_union_type_rc(&first, Some(&first), &codebase), &first));
2117 assert!(Rc::ptr_eq(&add_optional_union_type_rc(&first, None, &codebase), &first));
2118 }
2119
2120 #[test]
2121 fn rc_merges_match_owned_results_for_unequal_unions() {
2122 let codebase = CodebaseMetadata::new();
2123 let first = Rc::new(get_int());
2124 for flag in [
2125 UnionFlags::HAD_TEMPLATE,
2126 UnionFlags::BY_REFERENCE,
2127 UnionFlags::REFERENCE_FREE,
2128 UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY,
2129 UnionFlags::POSSIBLY_UNDEFINED,
2130 UnionFlags::IGNORE_NULLABLE_ISSUES,
2131 UnionFlags::IGNORE_FALSABLE_ISSUES,
2132 UnionFlags::FROM_TEMPLATE_DEFAULT,
2133 UnionFlags::FROM_UNSPECIFIED_TEMPLATE,
2134 ] {
2135 for mut second in [get_int(), get_string()] {
2136 second.flags = flag.union(UnionFlags::POPULATED);
2137 let second = Rc::new(second);
2138 assert_ne!(first, second);
2139 assert_exact(
2140 &combine_union_types_rc(&first, &second, &codebase, CombinerOptions::default()),
2141 &combine_union_types(&first, &second, &codebase, CombinerOptions::default()),
2142 );
2143 assert_exact(
2144 &add_optional_union_type_rc(&first, Some(&second), &codebase),
2145 &add_optional_union_type((*first).clone(), Some(&second), &codebase),
2146 );
2147 }
2148 }
2149 }
2150
2151 #[test]
2152 fn consuming_rc_merges_match_borrowed_types_flags_and_shared_snapshots() {
2153 let codebase = CodebaseMetadata::new();
2154 let types = [get_int(), get_string(), get_never(), get_mixed(), get_empty_keyed_array(), get_list(get_int())];
2155 let flags = [
2156 UnionFlags::empty(),
2157 UnionFlags::HAD_TEMPLATE,
2158 UnionFlags::BY_REFERENCE,
2159 UnionFlags::REFERENCE_FREE,
2160 UnionFlags::POSSIBLY_UNDEFINED_FROM_TRY,
2161 UnionFlags::POSSIBLY_UNDEFINED,
2162 UnionFlags::IGNORE_NULLABLE_ISSUES,
2163 UnionFlags::IGNORE_FALSABLE_ISSUES,
2164 UnionFlags::FROM_TEMPLATE_DEFAULT,
2165 UnionFlags::FROM_UNSPECIFIED_TEMPLATE,
2166 UnionFlags::POPULATED,
2167 UnionFlags::NULLSAFE_NULL,
2168 ];
2169
2170 for first_type in &types {
2171 for second_type in &types {
2172 for first_flags in flags {
2173 for second_flags in flags {
2174 let mut first = first_type.clone();
2175 first.flags = first_flags;
2176 let mut second = second_type.clone();
2177 second.flags = second_flags;
2178 let second = Rc::new(second);
2179 let expected = combine_union_types(&first, &second, &codebase, CombinerOptions::default());
2180
2181 let shared = Rc::new(first.clone());
2182 let actual = combine_owned_union_types_rc(
2183 Rc::clone(&shared),
2184 &second,
2185 &codebase,
2186 CombinerOptions::default(),
2187 );
2188 assert_exact(&actual, &expected);
2189 assert_exact(&shared, &first);
2190
2191 let unique = Rc::new(first);
2192 let original_pointer = Rc::as_ptr(&unique);
2193 let equal = unique == second;
2194 let actual =
2195 combine_owned_union_types_rc(unique, &second, &codebase, CombinerOptions::default());
2196 assert_exact(&actual, &expected);
2197 if equal {
2198 assert!(std::ptr::eq(Rc::as_ptr(&actual), original_pointer));
2199 }
2200 }
2201 }
2202 }
2203 }
2204 }
2205}