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