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