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