1use rustc_hash::FxHashMap;
2use serde::{Deserialize, Serialize};
3use smallvec::SmallVec;
4use std::sync::{Arc, OnceLock};
5
6use crate::atomic::Atomic;
7use crate::symbol::Name;
8
9pub fn empty_type_params() -> Arc<[Type]> {
13 static EMPTY: OnceLock<Arc<[Type]>> = OnceLock::new();
14 EMPTY.get_or_init(|| Arc::from([] as [Type; 0])).clone()
15}
16
17pub fn vec_to_type_params(v: Vec<Type>) -> Arc<[Type]> {
20 if v.is_empty() {
21 empty_type_params()
22 } else {
23 Arc::from(v)
24 }
25}
26
27pub type AtomicVec = SmallVec<[Atomic; 2]>;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum CloneValidity {
33 Cloneable,
35 Invalid,
37 PossiblyInvalid,
39 Unknown,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
48pub struct Type {
49 pub types: AtomicVec,
50 pub possibly_undefined: bool,
52 pub from_docblock: bool,
54 pub falsy_stripped: bool,
62 pub possibly_absent_offset: bool,
73}
74
75impl Type {
76 pub fn empty() -> Self {
79 Self {
80 types: SmallVec::new(),
81 possibly_undefined: false,
82 from_docblock: false,
83 falsy_stripped: false,
84 possibly_absent_offset: false,
85 }
86 }
87
88 pub fn single(atomic: Atomic) -> Self {
89 let mut types = SmallVec::new();
90 types.push(atomic);
91 Self {
92 types,
93 possibly_undefined: false,
94 from_docblock: false,
95 falsy_stripped: false,
96 possibly_absent_offset: false,
97 }
98 }
99
100 pub fn mixed() -> Self {
101 Self::single(Atomic::TMixed)
102 }
103
104 pub fn void() -> Self {
105 Self::single(Atomic::TVoid)
106 }
107
108 pub fn never() -> Self {
109 Self::single(Atomic::TNever)
110 }
111
112 pub fn null() -> Self {
113 Self::single(Atomic::TNull)
114 }
115
116 pub fn bool() -> Self {
117 Self::single(Atomic::TBool)
118 }
119
120 pub fn int() -> Self {
121 Self::single(Atomic::TInt)
122 }
123
124 pub fn float() -> Self {
125 Self::single(Atomic::TFloat)
126 }
127
128 pub fn string() -> Self {
129 Self::single(Atomic::TString)
130 }
131
132 pub fn array_key() -> Self {
135 let mut u = Self::single(Atomic::TInt);
136 u.add_type(Atomic::TString);
137 u
138 }
139
140 pub fn nullable(atomic: Atomic) -> Self {
142 if matches!(atomic, Atomic::TMixed) {
144 return Self::mixed();
145 }
146 let mut types = SmallVec::new();
147 types.push(atomic);
148 types.push(Atomic::TNull);
149 Self {
150 types,
151 possibly_undefined: false,
152 from_docblock: false,
153 falsy_stripped: false,
154 possibly_absent_offset: false,
155 }
156 }
157
158 pub fn from_vec(atomics: Vec<Atomic>) -> Self {
160 let mut u = Self::empty();
161 for a in atomics {
162 u.add_type(a);
163 }
164 u
165 }
166
167 pub fn is_empty(&self) -> bool {
170 self.types.is_empty()
171 }
172
173 pub fn is_single(&self) -> bool {
174 self.types.len() == 1
175 }
176
177 pub fn is_nullable(&self) -> bool {
178 self.types.iter().any(|t| matches!(t, Atomic::TNull))
179 }
180
181 pub fn is_array_key(&self) -> bool {
186 self.types.len() == 2
187 && self.types.iter().any(|t| matches!(t, Atomic::TInt))
188 && self.types.iter().any(|t| matches!(t, Atomic::TString))
189 }
190
191 pub fn is_mixed(&self) -> bool {
192 self.types.iter().any(|t| match t {
193 Atomic::TMixed => true,
194 Atomic::TTemplateParam { as_type, .. } => as_type.is_mixed(),
195 _ => false,
196 })
197 }
198
199 pub fn is_mixed_not_template(&self) -> bool {
204 self.is_mixed()
205 && !self
206 .types
207 .iter()
208 .any(|t| matches!(t, Atomic::TTemplateParam { .. }))
209 }
210
211 pub fn is_never(&self) -> bool {
212 self.types.iter().all(|t| matches!(t, Atomic::TNever)) && !self.types.is_empty()
213 }
214
215 pub fn clone_validity(&self) -> CloneValidity {
218 if self.types.is_empty() {
219 return CloneValidity::Unknown;
220 }
221 let mut has_non_object = false;
222 let mut has_other = false; for t in &self.types {
224 match t {
225 Atomic::TTemplateParam { as_type, .. } => match as_type.clone_validity() {
226 CloneValidity::Invalid => has_non_object = true,
227 CloneValidity::PossiblyInvalid => {
228 has_non_object = true;
229 has_other = true;
230 }
231 CloneValidity::Cloneable | CloneValidity::Unknown => has_other = true,
232 },
233 other if other.is_definitely_non_object() => has_non_object = true,
234 _ => has_other = true,
235 }
236 }
237 match (has_non_object, has_other) {
238 (true, false) => CloneValidity::Invalid,
239 (true, true) => CloneValidity::PossiblyInvalid,
240 _ => CloneValidity::Cloneable,
241 }
242 }
243
244 pub fn is_void(&self) -> bool {
245 self.is_single() && matches!(self.types[0], Atomic::TVoid)
246 }
247
248 pub fn can_be_falsy(&self) -> bool {
249 self.types.iter().any(|t| t.can_be_falsy())
250 }
251
252 pub fn can_be_truthy(&self) -> bool {
253 self.types.iter().any(|t| t.can_be_truthy())
254 }
255
256 pub fn contains<F: Fn(&Atomic) -> bool>(&self, f: F) -> bool {
257 self.types.iter().any(f)
258 }
259
260 pub fn has_named_object(&self, fqcn: &str) -> bool {
261 self.types.iter().any(|t| match t {
262 Atomic::TNamedObject { fqcn: f, .. } => f.as_ref() == fqcn,
263 _ => false,
264 })
265 }
266
267 pub fn add_type(&mut self, atomic: Atomic) {
272 if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
274 return;
275 }
276
277 if matches!(atomic, Atomic::TMixed) {
279 self.types.clear();
280 self.types.push(Atomic::TMixed);
281 return;
282 }
283
284 let atomic = if let Atomic::TConditional { data } = &atomic {
287 let (if_true, if_false) = (&data.if_true, &data.if_false);
288 let mut simplified_true = Type::empty();
289 for t in &if_true.types {
290 simplified_true.add_type(t.clone());
291 }
292 let mut simplified_false = Type::empty();
293 for t in &if_false.types {
294 simplified_false.add_type(t.clone());
295 }
296 if simplified_true == simplified_false {
297 for t in simplified_true.types {
298 self.add_type(t);
299 }
300 return;
301 }
302 atomic
303 } else {
304 atomic
305 };
306
307 if self.types.contains(&atomic) {
309 return;
310 }
311
312 if let Atomic::TLiteralInt(_) = &atomic {
314 if self.types.iter().any(|t| matches!(t, Atomic::TInt)) {
315 return;
316 }
317 }
318 if let Atomic::TLiteralString(_) = &atomic {
320 if self.types.iter().any(|t| matches!(t, Atomic::TString)) {
321 return;
322 }
323 }
324 if matches!(atomic, Atomic::TTrue | Atomic::TFalse)
326 && self.types.iter().any(|t| matches!(t, Atomic::TBool))
327 {
328 return;
329 }
330 if matches!(atomic, Atomic::TTrue) && self.types.iter().any(|t| matches!(t, Atomic::TFalse))
333 {
334 self.types.retain(|t| !matches!(t, Atomic::TFalse));
335 self.types.push(Atomic::TBool);
336 return;
337 }
338 if matches!(atomic, Atomic::TFalse) && self.types.iter().any(|t| matches!(t, Atomic::TTrue))
339 {
340 self.types.retain(|t| !matches!(t, Atomic::TTrue));
341 self.types.push(Atomic::TBool);
342 return;
343 }
344 if matches!(atomic, Atomic::TInt) {
346 self.types.retain(|t| !matches!(t, Atomic::TLiteralInt(_)));
347 }
348 if matches!(atomic, Atomic::TString) {
350 self.types
351 .retain(|t| !matches!(t, Atomic::TLiteralString(_)));
352 }
353 if matches!(atomic, Atomic::TBool) {
355 self.types
356 .retain(|t| !matches!(t, Atomic::TTrue | Atomic::TFalse));
357 }
358
359 if matches!(atomic, Atomic::TNever) {
361 if !self.types.is_empty() {
362 return;
363 }
364 } else {
365 self.types.retain(|t| !matches!(t, Atomic::TNever));
366 }
367
368 if let Atomic::TKeyedArray {
374 properties,
375 is_open,
376 ..
377 } = &atomic
378 {
379 if properties.is_empty() && !is_open {
380 for existing in &self.types {
381 match existing {
382 Atomic::TArray { .. }
383 | Atomic::TNonEmptyArray { .. }
384 | Atomic::TList { .. }
385 | Atomic::TNonEmptyList { .. } => {
386 return; }
388 _ => {}
389 }
390 }
391 }
392 }
393
394 let is_generic_array_or_list = matches!(
397 &atomic,
398 Atomic::TArray { .. }
399 | Atomic::TNonEmptyArray { .. }
400 | Atomic::TList { .. }
401 | Atomic::TNonEmptyList { .. }
402 );
403 if is_generic_array_or_list {
404 self.types.retain(|t| {
405 if let Atomic::TKeyedArray {
406 properties,
407 is_open,
408 ..
409 } = t
410 {
411 !properties.is_empty() || *is_open
412 } else {
413 true
414 }
415 });
416 }
417
418 self.types.push(atomic);
419 }
420
421 pub fn remove_null(&self) -> Type {
425 self.filter(|t| !matches!(t, Atomic::TNull))
426 }
427
428 pub fn remove_false(&self) -> Type {
431 let mut result = self.filter(|t| !matches!(t, Atomic::TFalse | Atomic::TBool));
432 if self.types.iter().any(|t| matches!(t, Atomic::TBool)) {
433 result.add_type(Atomic::TTrue);
434 }
435 result
436 }
437
438 pub fn remove_true(&self) -> Type {
441 let mut result = self.filter(|t| !matches!(t, Atomic::TTrue | Atomic::TBool));
442 if self.types.iter().any(|t| matches!(t, Atomic::TBool)) {
443 result.add_type(Atomic::TFalse);
444 }
445 result
446 }
447
448 pub fn core_type(&self) -> Type {
450 self.remove_null().remove_false()
451 }
452
453 pub fn narrow_to_truthy(&self) -> Type {
455 if self.is_mixed_not_template() {
456 return Type::mixed();
457 }
458 let mut result = Type::empty();
459 result.from_docblock = self.from_docblock;
460 for t in &self.types {
461 match t {
462 Atomic::TTemplateParam { .. } => result.add_type(t.clone()),
466 Atomic::TLiteralInt(0)
468 | Atomic::TLiteralFloat(0, 0)
469 | Atomic::TNull
470 | Atomic::TFalse => {}
471 Atomic::TLiteralString(s) if s.as_ref() == "" || s.as_ref() == "0" => {}
472 Atomic::TBool => result.add_type(Atomic::TTrue),
474 Atomic::TArray { key, value } => result.add_type(Atomic::TNonEmptyArray {
476 key: key.clone(),
477 value: value.clone(),
478 }),
479 Atomic::TList { value } => result.add_type(Atomic::TNonEmptyList {
480 value: value.clone(),
481 }),
482 Atomic::TString => result.add_type(Atomic::TNonEmptyString),
486 Atomic::TNonNegativeInt => result.add_type(Atomic::TPositiveInt),
491 Atomic::TIntRange { min: Some(0), max } if max.is_none_or(|m| m >= 1) => {
492 let atom = if max.is_none() {
493 Atomic::TPositiveInt
494 } else {
495 Atomic::TIntRange {
496 min: Some(1),
497 max: *max,
498 }
499 };
500 result.add_type(atom);
501 }
502 Atomic::TIntRange { min, max: Some(0) } => {
504 let atom = match min {
505 None => Atomic::TNegativeInt,
506 Some(n) if *n <= -1 => Atomic::TIntRange {
507 min: *min,
508 max: Some(-1),
509 },
510 _ => continue, };
512 result.add_type(atom);
513 }
514 t if !t.can_be_truthy() => {}
516 _ => result.add_type(t.clone()),
517 }
518 }
519 result
520 }
521
522 pub fn narrow_to_falsy(&self) -> Type {
524 if self.is_mixed_not_template() {
525 return Type::from_vec(vec![
526 Atomic::TNull,
527 Atomic::TFalse,
528 Atomic::TLiteralInt(0),
529 Atomic::TLiteralString("".into()),
530 ]);
531 }
532 let mut result = Type::empty();
533 result.from_docblock = self.from_docblock;
534 for t in &self.types {
535 match t {
536 Atomic::TTemplateParam { .. } => result.add_type(t.clone()),
541 Atomic::TBool => result.add_type(Atomic::TFalse),
543 Atomic::TInt => result.add_type(Atomic::TLiteralInt(0)),
545 Atomic::TFloat => result.add_type(Atomic::TLiteralFloat(0, 0)),
547 Atomic::TString => {
549 result.add_type(Atomic::TLiteralString("".into()));
550 result.add_type(Atomic::TLiteralString("0".into()));
551 }
552 Atomic::TNumericString => result.add_type(Atomic::TLiteralString("0".into())),
554 Atomic::TNonNegativeInt => result.add_type(Atomic::TLiteralInt(0)),
556 Atomic::TIntRange {
558 min: Some(0),
559 max: Some(_) | None,
560 } => result.add_type(Atomic::TLiteralInt(0)),
561 Atomic::TIntRange { max: Some(0), .. } => result.add_type(Atomic::TLiteralInt(0)),
563 t if !t.can_be_falsy() => {} _ => result.add_type(t.clone()),
565 }
566 }
567 result
568 }
569
570 pub fn narrow_instanceof(&self, class: &str) -> Type {
576 let narrowed_ty = Atomic::TNamedObject {
577 fqcn: class.into(),
578 type_params: empty_type_params(),
579 };
580 let has_object = self.types.iter().any(|t| {
582 matches!(
583 t,
584 Atomic::TObject | Atomic::TNamedObject { .. } | Atomic::TMixed | Atomic::TNull )
586 });
587 if has_object || self.is_empty() {
588 Type::single(narrowed_ty)
589 } else {
590 Type::single(narrowed_ty)
593 }
594 }
595
596 pub fn narrow_to_string(&self) -> Type {
600 self.filter_replacing(
601 |t| t.is_string() || matches!(t, Atomic::TTemplateParam { .. }),
602 |t| matches!(t, Atomic::TMixed | Atomic::TScalar),
603 Atomic::TString,
604 )
605 }
606
607 pub fn narrow_to_int(&self) -> Type {
609 self.filter_replacing(
610 |t| t.is_int() || matches!(t, Atomic::TTemplateParam { .. }),
611 |t| matches!(t, Atomic::TMixed | Atomic::TScalar | Atomic::TNumeric),
612 Atomic::TInt,
613 )
614 }
615
616 pub fn narrow_to_float(&self) -> Type {
618 self.filter_replacing(
619 |t| {
620 matches!(
621 t,
622 Atomic::TFloat
623 | Atomic::TIntegralFloat
624 | Atomic::TLiteralFloat(..)
625 | Atomic::TTemplateParam { .. }
626 )
627 },
628 |t| matches!(t, Atomic::TMixed | Atomic::TScalar | Atomic::TNumeric),
629 Atomic::TFloat,
630 )
631 }
632
633 pub fn narrow_to_bool(&self) -> Type {
635 self.filter_replacing(
636 |t| {
637 matches!(
638 t,
639 Atomic::TBool | Atomic::TTrue | Atomic::TFalse | Atomic::TTemplateParam { .. }
640 )
641 },
642 |t| matches!(t, Atomic::TMixed | Atomic::TScalar),
643 Atomic::TBool,
644 )
645 }
646
647 pub fn narrow_to_null(&self) -> Type {
649 self.filter_replacing(
650 |t| matches!(t, Atomic::TNull | Atomic::TTemplateParam { .. }),
651 |t| matches!(t, Atomic::TMixed),
652 Atomic::TNull,
653 )
654 }
655
656 pub fn narrow_to_array(&self) -> Type {
658 self.filter_replacing(
659 |t| t.is_array() || matches!(t, Atomic::TTemplateParam { .. }),
660 |t| matches!(t, Atomic::TMixed),
661 Atomic::TArray {
662 key: Box::new(Type::mixed()),
663 value: Box::new(Type::mixed()),
664 },
665 )
666 }
667
668 pub fn narrow_to_non_empty_collection(&self) -> Type {
670 let mut out = Type::empty();
671 out.from_docblock = self.from_docblock;
672 for t in &self.types {
673 match t {
674 Atomic::TArray { key, value } => out.add_type(Atomic::TNonEmptyArray {
675 key: key.clone(),
676 value: value.clone(),
677 }),
678 Atomic::TList { value } => out.add_type(Atomic::TNonEmptyList {
679 value: value.clone(),
680 }),
681 _ => out.add_type(t.clone()),
682 }
683 }
684 out
685 }
686
687 pub fn narrow_to_empty_collection(&self) -> Type {
697 let mut out = Type::empty();
698 out.from_docblock = self.from_docblock;
699 for t in &self.types {
700 match t {
701 Atomic::TNonEmptyArray { .. } | Atomic::TNonEmptyList { .. } => {}
702 Atomic::TArray { .. } | Atomic::TList { .. } => {
703 out.add_type(Atomic::TKeyedArray {
704 properties: Box::default(),
705 is_open: false,
706 is_list: true,
707 });
708 }
709 _ => out.add_type(t.clone()),
710 }
711 }
712 out
713 }
714
715 pub fn narrow_to_list(&self) -> Type {
727 let mut out = Type::empty();
728 out.from_docblock = self.from_docblock;
729 for t in &self.types {
730 match t {
731 Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => out.add_type(t.clone()),
732 Atomic::TArray { key, value } if !key.narrow_to_int().is_empty() => {
738 out.add_type(Atomic::TList {
739 value: value.clone(),
740 });
741 }
742 Atomic::TNonEmptyArray { key, value } if !key.narrow_to_int().is_empty() => {
743 out.add_type(Atomic::TNonEmptyList {
744 value: value.clone(),
745 });
746 }
747 Atomic::TKeyedArray { is_list: true, .. } => out.add_type(t.clone()),
748 Atomic::TMixed => out.add_type(Atomic::TList {
749 value: Box::new(Type::mixed()),
750 }),
751 _ => {}
752 }
753 }
754 if out.is_empty() {
755 self.filter(|t| matches!(t, Atomic::TList { .. } | Atomic::TNonEmptyList { .. }))
756 } else {
757 out
758 }
759 }
760
761 pub fn narrow_to_object(&self) -> Type {
766 let mut out = Type::empty();
767 for t in &self.types {
768 if matches!(t, Atomic::TMixed) {
769 out.add_type(Atomic::TObject);
770 } else if t.is_object() || matches!(t, Atomic::TTemplateParam { .. }) {
771 out.add_type(t.clone());
772 }
773 }
774 if out.types.is_empty() {
775 self.filter(|t| t.is_object())
776 } else {
777 out
778 }
779 }
780
781 pub fn narrow_to_callable(&self) -> Type {
788 let narrowed = self.filter(|t| {
789 t.is_callable()
790 || t.is_string()
791 || t.is_array()
792 || t.is_object()
793 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
794 });
795 let mut result = Type::empty();
802 result.possibly_undefined = narrowed.possibly_undefined;
803 result.from_docblock = narrowed.from_docblock;
804 for atomic in narrowed.types {
805 if matches!(atomic, Atomic::TObject) {
806 result.add_type(Atomic::TCallable {
807 params: None,
808 return_type: None,
809 });
810 } else {
811 result.add_type(atomic);
812 }
813 }
814 result
815 }
816
817 pub fn narrow_to_scalar(&self) -> Type {
819 self.filter_replacing(
820 |t| {
821 t.is_string()
822 || t.is_int()
823 || matches!(
824 t,
825 Atomic::TFloat
826 | Atomic::TIntegralFloat
827 | Atomic::TLiteralFloat(..)
828 | Atomic::TBool
829 | Atomic::TTrue
830 | Atomic::TFalse
831 | Atomic::TScalar
832 | Atomic::TNumeric
833 | Atomic::TNumericString
834 | Atomic::TTemplateParam { .. }
835 )
836 },
837 |t| matches!(t, Atomic::TMixed),
838 Atomic::TScalar,
839 )
840 }
841
842 pub fn narrow_to_iterable(&self) -> Type {
845 self.filter(|t| {
846 t.is_array()
847 || t.is_object()
848 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
849 })
850 }
851
852 pub fn narrow_to_countable(&self) -> Type {
855 self.filter(|t| {
856 t.is_array()
857 || t.is_object()
858 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
859 })
860 }
861
862 pub fn narrow_to_resource(&self) -> Type {
866 self.filter(|t| matches!(t, Atomic::TMixed))
868 }
869
870 pub fn narrow_to_class_string(&self) -> Type {
875 let mut out = Type::empty();
876 out.from_docblock = self.from_docblock;
877 for t in &self.types {
878 match t {
879 Atomic::TClassString(_) => out.add_type(t.clone()),
880 _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
881 out.add_type(Atomic::TClassString(None));
882 }
883 _ => {}
884 }
885 }
886 out
887 }
888
889 pub fn narrow_to_interface_string(&self) -> Type {
894 let mut out = Type::empty();
895 out.from_docblock = self.from_docblock;
896 for t in &self.types {
897 match t {
898 Atomic::TInterfaceString(_) => out.add_type(t.clone()),
899 Atomic::TClassString(name) => {
903 out.add_type(Atomic::TInterfaceString(*name));
904 }
905 _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
906 out.add_type(Atomic::TInterfaceString(None));
907 }
908 _ => {}
909 }
910 }
911 out
912 }
913
914 pub fn merge(a: &Type, b: &Type) -> Type {
919 if b.types.is_empty() {
921 let mut result = a.clone();
922 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
923 return result;
924 }
925 if a.types.is_empty() {
927 let mut result = b.clone();
928 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
929 return result;
930 }
931 if a.types.len() == 1 && matches!(a.types[0], Atomic::TMixed) {
933 let mut result = a.clone();
934 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
935 return result;
936 }
937 if b.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
939 return Type {
940 types: smallvec::smallvec![Atomic::TMixed],
941 possibly_undefined: a.possibly_undefined || b.possibly_undefined,
942 from_docblock: a.from_docblock || b.from_docblock,
943 falsy_stripped: false,
944 possibly_absent_offset: false,
945 };
946 }
947 let mut result = a.clone();
948 result.merge_with(b);
949 result
950 }
951
952 pub fn merge_with(&mut self, other: &Type) {
954 if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
955 self.possibly_undefined |= other.possibly_undefined;
956 return;
957 }
958 if other.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
959 self.types.clear();
960 self.types.push(Atomic::TMixed);
961 self.possibly_undefined |= other.possibly_undefined;
962 return;
963 }
964 for atomic in &other.types {
965 self.add_type(atomic.clone());
966 }
967 self.possibly_undefined |= other.possibly_undefined;
968 }
969
970 pub fn intersect_with(&self, other: &Type) -> Type {
974 if self.is_mixed() {
975 return other.clone();
976 }
977 if other.is_mixed() {
978 return self.clone();
979 }
980 let mut result = Type::empty();
988 for a in &self.types {
989 for b in &other.types {
990 if a == b {
991 result.add_type(a.clone());
992 } else if atomic_subtype(b, a) {
993 result.add_type(b.clone());
994 } else if atomic_subtype(a, b) {
995 result.add_type(a.clone());
996 }
997 }
998 }
999 if result.is_empty() {
1000 Type::never()
1001 } else {
1002 result
1003 }
1004 }
1005
1006 pub fn substitute_templates(&self, bindings: &FxHashMap<Name, Type>) -> Type {
1010 if bindings.is_empty() {
1011 return self.clone();
1012 }
1013 if !self.types.iter().any(atomic_may_contain_templates) {
1016 return self.clone();
1017 }
1018 let mut result = Type::empty();
1019 result.possibly_undefined = self.possibly_undefined;
1020 result.from_docblock = self.from_docblock;
1021 for atomic in &self.types {
1022 match atomic {
1023 Atomic::TTemplateParam { name, .. } => {
1024 if let Some(resolved) = bindings.get(name) {
1025 for t in &resolved.types {
1026 result.add_type(t.clone());
1027 }
1028 } else {
1029 result.add_type(atomic.clone());
1030 }
1031 }
1032 Atomic::TArray { key, value } => {
1033 result.add_type(Atomic::TArray {
1034 key: Box::new(key.substitute_templates(bindings)),
1035 value: Box::new(value.substitute_templates(bindings)),
1036 });
1037 }
1038 Atomic::TList { value } => {
1039 result.add_type(Atomic::TList {
1040 value: Box::new(value.substitute_templates(bindings)),
1041 });
1042 }
1043 Atomic::TNonEmptyArray { key, value } => {
1044 result.add_type(Atomic::TNonEmptyArray {
1045 key: Box::new(key.substitute_templates(bindings)),
1046 value: Box::new(value.substitute_templates(bindings)),
1047 });
1048 }
1049 Atomic::TNonEmptyList { value } => {
1050 result.add_type(Atomic::TNonEmptyList {
1051 value: Box::new(value.substitute_templates(bindings)),
1052 });
1053 }
1054 Atomic::TKeyedArray {
1055 properties,
1056 is_open,
1057 is_list,
1058 } => {
1059 use crate::atomic::KeyedProperty;
1060 let new_props = properties
1061 .iter()
1062 .map(|(k, prop)| {
1063 (
1064 k.clone(),
1065 KeyedProperty {
1066 ty: prop.ty.substitute_templates(bindings),
1067 optional: prop.optional,
1068 },
1069 )
1070 })
1071 .collect();
1072 result.add_type(Atomic::TKeyedArray {
1073 properties: Box::new(new_props),
1074 is_open: *is_open,
1075 is_list: *is_list,
1076 });
1077 }
1078 Atomic::TCallable {
1079 params,
1080 return_type,
1081 } => {
1082 result.add_type(Atomic::TCallable {
1083 params: params.as_ref().map(|ps| {
1084 ps.iter()
1085 .map(|p| substitute_in_fn_param(p, bindings))
1086 .collect()
1087 }),
1088 return_type: return_type
1089 .as_ref()
1090 .map(|r| Box::new(r.substitute_templates(bindings))),
1091 });
1092 }
1093 Atomic::TClosure { data } => {
1094 result.add_type(Atomic::TClosure {
1095 data: Box::new(crate::atomic::ClosureData {
1096 params: data
1097 .params
1098 .iter()
1099 .map(|p| substitute_in_fn_param(p, bindings))
1100 .collect(),
1101 return_type: data.return_type.substitute_templates(bindings),
1102 this_type: data
1103 .this_type
1104 .as_ref()
1105 .map(|t| t.substitute_templates(bindings)),
1106 }),
1107 });
1108 }
1109 Atomic::TConditional { data } => {
1110 let param_name = &data.param_name;
1111 let new_subject = data.subject.substitute_templates(bindings);
1112 let new_if_true = data.if_true.substitute_templates(bindings);
1113 let new_if_false = data.if_false.substitute_templates(bindings);
1114
1115 let resolved = if let Some(name) = param_name {
1119 if let Some(bound) = bindings.get(name) {
1120 if new_subject.types.len() == 1 {
1121 resolve_conditional_branch(
1122 &new_subject.types[0],
1123 bound,
1124 &new_if_true,
1125 &new_if_false,
1126 )
1127 } else {
1128 None
1129 }
1130 } else {
1131 None
1132 }
1133 } else {
1134 None
1135 };
1136
1137 if let Some(branch) = resolved {
1138 for t in branch.types {
1139 result.add_type(t);
1140 }
1141 } else {
1142 result.add_type(Atomic::TConditional {
1143 data: Box::new(crate::atomic::ConditionalData {
1144 param_name: *param_name,
1145 subject: new_subject,
1146 if_true: new_if_true,
1147 if_false: new_if_false,
1148 }),
1149 });
1150 }
1151 }
1152 Atomic::TKeyOf { target } => {
1153 let new_target = target.substitute_templates(bindings);
1154 if let Some(resolved) = eval_key_of_type(&new_target) {
1155 result.merge_with(&resolved);
1156 } else {
1157 result.add_type(Atomic::TKeyOf {
1158 target: Box::new(new_target),
1159 });
1160 }
1161 }
1162 Atomic::TValueOf { target } => {
1163 let new_target = target.substitute_templates(bindings);
1164 if let Some(resolved) = eval_value_of_type(&new_target) {
1165 result.merge_with(&resolved);
1166 } else {
1167 result.add_type(Atomic::TValueOf {
1168 target: Box::new(new_target),
1169 });
1170 }
1171 }
1172 Atomic::TIntersection { parts } => {
1173 result.add_type(Atomic::TIntersection {
1174 parts: vec_to_type_params(
1175 parts
1176 .iter()
1177 .map(|p| p.substitute_templates(bindings))
1178 .collect(),
1179 ),
1180 });
1181 }
1182 Atomic::TNamedObject { fqcn, type_params } => {
1183 if type_params.is_empty() && !fqcn.contains('\\') {
1190 if let Some(resolved) = bindings.get(fqcn) {
1191 for t in &resolved.types {
1192 result.add_type(t.clone());
1193 }
1194 continue;
1195 }
1196 }
1197 let new_params: Vec<Type> = type_params
1198 .iter()
1199 .map(|p| p.substitute_templates(bindings))
1200 .collect();
1201 result.add_type(Atomic::TNamedObject {
1202 fqcn: *fqcn,
1203 type_params: vec_to_type_params(new_params),
1204 });
1205 }
1206 Atomic::TClassString(Some(param_name)) => {
1208 if let Some(resolved) = bindings.get(param_name) {
1209 for r_atomic in &resolved.types {
1210 let cls_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1211 Some(*fqcn)
1212 } else {
1213 None
1214 };
1215 result.add_type(Atomic::TClassString(cls_name));
1216 }
1217 } else {
1218 result.add_type(atomic.clone());
1219 }
1220 }
1221 Atomic::TInterfaceString(Some(param_name)) => {
1223 if let Some(resolved) = bindings.get(param_name) {
1224 for r_atomic in &resolved.types {
1225 let iface_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1226 Some(*fqcn)
1227 } else {
1228 None
1229 };
1230 result.add_type(Atomic::TInterfaceString(iface_name));
1231 }
1232 } else {
1233 result.add_type(atomic.clone());
1234 }
1235 }
1236 _ => {
1237 result.add_type(atomic.clone());
1238 }
1239 }
1240 }
1241 result
1242 }
1243
1244 pub fn resolve_conditional_returns<F>(self, lookup: F) -> Type
1250 where
1251 F: Fn(&str) -> Option<Type>,
1252 {
1253 self.resolve_conditional_inner(&lookup)
1254 }
1255
1256 fn resolve_conditional_inner<F>(self, lookup: &F) -> Type
1257 where
1258 F: Fn(&str) -> Option<Type>,
1259 {
1260 let mut result = Type::empty();
1261 for atomic in self.types {
1262 match atomic {
1263 Atomic::TConditional { ref data } => {
1264 let (param_name, subject, if_true, if_false) = (
1265 &data.param_name,
1266 &data.subject,
1267 &data.if_true,
1268 &data.if_false,
1269 );
1270 let resolved = if subject.types.len() == 1 {
1271 if let Some(name) = param_name {
1272 if let Some(arg_ty) = lookup(name.as_ref()) {
1273 resolve_conditional_branch(
1274 &subject.types[0],
1275 &arg_ty,
1276 if_true,
1277 if_false,
1278 )
1279 } else {
1280 None
1281 }
1282 } else {
1283 None
1284 }
1285 } else {
1286 None
1287 };
1288
1289 if let Some(branch) = resolved {
1290 for t in branch.resolve_conditional_inner(lookup).types {
1292 result.add_type(t);
1293 }
1294 } else {
1295 for t in if_true.clone().resolve_conditional_inner(lookup).types {
1298 result.add_type(t);
1299 }
1300 for t in if_false.clone().resolve_conditional_inner(lookup).types {
1301 result.add_type(t);
1302 }
1303 }
1304 }
1305 other => result.add_type(other),
1306 }
1307 }
1308 result
1309 }
1310
1311 pub fn is_subtype_structural(&self, other: &Type) -> bool {
1321 if other.is_mixed() {
1322 return true;
1323 }
1324 if self.is_never() {
1325 return true; }
1327 self.types
1328 .iter()
1329 .all(|a| other.types.iter().any(|b| atomic_subtype(a, b)))
1330 }
1331
1332 pub fn accepts_atomic_structural(&self, sub: &Atomic) -> bool {
1336 if self.is_mixed() {
1337 return true;
1338 }
1339 matches!(sub, Atomic::TNever) || self.types.iter().any(|b| atomic_subtype(sub, b))
1340 }
1341
1342 fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Type {
1345 let mut result = Type::empty();
1346 result.possibly_undefined = self.possibly_undefined;
1347 result.from_docblock = self.from_docblock;
1348 for atomic in &self.types {
1349 if f(atomic) {
1350 result.types.push(atomic.clone());
1351 }
1352 }
1353 result
1354 }
1355
1356 fn filter_replacing<K: Fn(&Atomic) -> bool, P: Fn(&Atomic) -> bool>(
1361 &self,
1362 keep: K,
1363 placeholder: P,
1364 replacement: Atomic,
1365 ) -> Type {
1366 let mut result = Type::empty();
1367 result.possibly_undefined = self.possibly_undefined;
1368 result.from_docblock = self.from_docblock;
1369 for atomic in &self.types {
1370 if keep(atomic) {
1371 result.add_type(atomic.clone());
1372 } else if placeholder(atomic) {
1373 result.add_type(replacement.clone());
1374 }
1375 }
1376 result
1377 }
1378
1379 pub fn possibly_undefined(mut self) -> Self {
1381 self.possibly_undefined = true;
1382 self
1383 }
1384
1385 pub fn from_docblock(mut self) -> Self {
1387 self.from_docblock = true;
1388 self
1389 }
1390
1391 pub fn falsy_stripped(mut self) -> Self {
1394 self.falsy_stripped = true;
1395 self
1396 }
1397
1398 pub fn possibly_absent_offset(mut self) -> Self {
1402 self.possibly_absent_offset = true;
1403 self
1404 }
1405}
1406
1407#[derive(Clone, PartialEq, Eq, Debug)]
1421enum ValueClass {
1422 Int,
1423 Float,
1424 True,
1425 False,
1426 String,
1427 Array,
1428 List,
1430 Object,
1431 Null,
1432 Top,
1435 LitInt(i64),
1438 LitFloat(i64, i64),
1440 LitString(Arc<str>),
1442}
1443
1444impl ValueClass {
1445 fn includes(&self, b: &Self) -> bool {
1450 self == b
1451 || matches!(
1452 (self, b),
1453 (Self::Top, _)
1454 | (Self::Int, Self::LitInt(_))
1455 | (Self::Float, Self::LitFloat(..))
1456 | (Self::String, Self::LitString(_))
1457 | (Self::Array, Self::List)
1458 )
1459 }
1460}
1461
1462fn value_classes(a: &Atomic) -> Vec<ValueClass> {
1468 use ValueClass::*;
1469 match a {
1470 Atomic::TInt
1473 | Atomic::TIntRange { .. }
1474 | Atomic::TPositiveInt
1475 | Atomic::TNegativeInt
1476 | Atomic::TNonNegativeInt => vec![Int],
1477 Atomic::TLiteralInt(v) => vec![LitInt(*v)],
1478 Atomic::TFloat | Atomic::TIntegralFloat => vec![Float],
1480 Atomic::TLiteralFloat(int_bits, frac_bits) => {
1481 vec![LitFloat(*int_bits, *frac_bits)]
1482 }
1483 Atomic::TBool => vec![True, False],
1485 Atomic::TTrue => vec![True],
1486 Atomic::TFalse => vec![False],
1487 Atomic::TString
1489 | Atomic::TNonEmptyString
1490 | Atomic::TNumericString
1491 | Atomic::TClassString(_)
1492 | Atomic::TInterfaceString(_)
1493 | Atomic::TEnumString
1494 | Atomic::TTraitString
1495 | Atomic::TCallableString => vec![String],
1496 Atomic::TLiteralString(s) => vec![LitString(s.clone())],
1497 Atomic::TArray { .. }
1499 | Atomic::TNonEmptyArray { .. }
1500 | Atomic::TKeyedArray { is_list: false, .. } => vec![Array],
1501 Atomic::TList { .. }
1502 | Atomic::TNonEmptyList { .. }
1503 | Atomic::TKeyedArray { is_list: true, .. } => vec![List],
1504 Atomic::TObject
1506 | Atomic::TNamedObject { .. }
1507 | Atomic::TStaticObject { .. }
1508 | Atomic::TSelf { .. }
1509 | Atomic::TParent { .. }
1510 | Atomic::TClosure { .. }
1511 | Atomic::TLiteralEnumCase { .. } => vec![Object],
1512 Atomic::TNull => vec![Null],
1515 Atomic::TVoid => vec![Top],
1516 Atomic::TMixed => vec![Top],
1518 Atomic::TScalar => vec![Int, Float, True, False, String],
1519 Atomic::TNumeric => vec![Int, Float],
1522 Atomic::TCallable { .. }
1524 | Atomic::TNever
1525 | Atomic::TTemplateParam { .. }
1526 | Atomic::TKeyOf { .. }
1527 | Atomic::TValueOf { .. }
1528 | Atomic::TConditional { .. }
1529 | Atomic::TIntersection { .. } => Vec::new(),
1530 }
1531}
1532
1533fn subject_is_decidable(subject: &Atomic) -> bool {
1541 matches!(
1542 subject,
1543 Atomic::TNull
1544 | Atomic::TTrue
1545 | Atomic::TFalse
1546 | Atomic::TBool
1547 | Atomic::TString
1548 | Atomic::TInt
1549 | Atomic::TFloat
1550 | Atomic::TArray { .. }
1551 | Atomic::TList { .. }
1552 | Atomic::TObject
1553 | Atomic::TMixed
1554 | Atomic::TScalar
1555 )
1556}
1557
1558fn resolve_conditional_branch(
1580 subject: &Atomic,
1581 arg_ty: &Type,
1582 if_true: &Type,
1583 if_false: &Type,
1584) -> Option<Type> {
1585 if !subject_is_decidable(subject) {
1586 return None;
1587 }
1588 if arg_ty.types.is_empty() {
1589 return None;
1590 }
1591 let subject_classes = value_classes(subject);
1592 let arg_classes: Vec<ValueClass> = arg_ty.types.iter().flat_map(value_classes).collect();
1593 if arg_classes.is_empty() {
1594 return None;
1596 }
1597 let all_match = arg_classes
1598 .iter()
1599 .all(|c| subject_classes.iter().any(|s| s.includes(c)));
1600 let any_overlap = arg_classes.iter().any(|c| {
1601 subject_classes
1602 .iter()
1603 .any(|s| s.includes(c) || c.includes(s))
1604 });
1605 if all_match {
1606 Some(if_true.clone())
1607 } else if !any_overlap {
1608 Some(if_false.clone())
1609 } else {
1610 None
1611 }
1612}
1613
1614fn atomic_may_contain_templates(atomic: &Atomic) -> bool {
1622 match atomic {
1623 Atomic::TNamedObject { fqcn, type_params } => {
1627 !type_params.is_empty() || !fqcn.contains('\\')
1628 }
1629 Atomic::TTemplateParam { .. }
1630 | Atomic::TKeyOf { .. }
1631 | Atomic::TValueOf { .. }
1632 | Atomic::TArray { .. }
1633 | Atomic::TList { .. }
1634 | Atomic::TNonEmptyArray { .. }
1635 | Atomic::TNonEmptyList { .. }
1636 | Atomic::TKeyedArray { .. }
1637 | Atomic::TCallable { .. }
1638 | Atomic::TClosure { .. }
1639 | Atomic::TConditional { .. }
1640 | Atomic::TIntersection { .. }
1641 | Atomic::TClassString(Some(_))
1642 | Atomic::TInterfaceString(Some(_)) => true,
1643 _ => false,
1644 }
1645}
1646
1647fn eval_key_of_type(t: &Type) -> Option<Type> {
1648 let mut result = Type::empty();
1649 for atomic in &t.types {
1650 match atomic {
1651 Atomic::TArray { key, .. } | Atomic::TNonEmptyArray { key, .. } => {
1652 for k in &key.types {
1653 result.add_type(k.clone());
1654 }
1655 }
1656 Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => {
1657 result.add_type(Atomic::TInt);
1658 }
1659 Atomic::TKeyedArray { properties, .. } => {
1660 for key in properties.keys() {
1661 match key {
1662 crate::atomic::ArrayKey::Int(n) => result.add_type(Atomic::TLiteralInt(*n)),
1663 crate::atomic::ArrayKey::String(s) => {
1664 result.add_type(Atomic::TLiteralString(s.clone()))
1665 }
1666 }
1667 }
1668 }
1669 _ => return None,
1670 }
1671 }
1672 (!result.types.is_empty()).then_some(result)
1673}
1674
1675fn eval_value_of_type(t: &Type) -> Option<Type> {
1676 let mut result = Type::empty();
1677 for atomic in &t.types {
1678 match atomic {
1679 Atomic::TArray { value, .. }
1680 | Atomic::TNonEmptyArray { value, .. }
1681 | Atomic::TList { value }
1682 | Atomic::TNonEmptyList { value } => {
1683 result.merge_with(value);
1684 }
1685 Atomic::TKeyedArray { properties, .. } => {
1686 for prop in properties.values() {
1687 result.merge_with(&prop.ty);
1688 }
1689 }
1690 _ => return None,
1691 }
1692 }
1693 (!result.types.is_empty()).then_some(result)
1694}
1695
1696fn substitute_in_fn_param(
1697 p: &crate::atomic::FnParam,
1698 bindings: &FxHashMap<Name, Type>,
1699) -> crate::atomic::FnParam {
1700 crate::atomic::FnParam {
1701 name: p.name,
1702 ty: p.ty.as_ref().map(|t| {
1703 let u = t.to_union();
1704 let substituted = u.substitute_templates(bindings);
1705 crate::compact::SimpleType::from_union(substituted)
1706 }),
1707 out_ty: p.out_ty.as_ref().map(|t| {
1708 let u = t.to_union();
1709 let substituted = u.substitute_templates(bindings);
1710 crate::compact::SimpleType::from_union(substituted)
1711 }),
1712 default: p.default.as_ref().map(|d| {
1713 let u = d.to_union();
1714 let substituted = u.substitute_templates(bindings);
1715 crate::compact::SimpleType::from_union(substituted)
1716 }),
1717 is_variadic: p.is_variadic,
1718 is_byref: p.is_byref,
1719 is_optional: p.is_optional,
1720 }
1721}
1722
1723pub fn atomic_subtype(sub: &Atomic, sup: &Atomic) -> bool {
1729 if sub == sup {
1730 return true;
1731 }
1732 match (sub, sup) {
1733 (Atomic::TNever, _) => true,
1735 (_, Atomic::TMixed) => true,
1737 (Atomic::TMixed, _) => true,
1738 (_, Atomic::TTemplateParam { as_type, .. }) => {
1743 as_type.is_mixed() || as_type.types.iter().any(|b| atomic_subtype(sub, b))
1744 }
1745
1746 (Atomic::TLiteralInt(_), Atomic::TInt) => true,
1748 (Atomic::TLiteralInt(_), Atomic::TNumeric) => true,
1749 (Atomic::TLiteralInt(_), Atomic::TScalar) => true,
1750 (Atomic::TLiteralInt(n), Atomic::TPositiveInt) => *n > 0,
1751 (Atomic::TLiteralInt(n), Atomic::TNonNegativeInt) => *n >= 0,
1752 (Atomic::TLiteralInt(n), Atomic::TNegativeInt) => *n < 0,
1753 (Atomic::TPositiveInt, Atomic::TInt) => true,
1754 (Atomic::TPositiveInt, Atomic::TNonNegativeInt) => true,
1755 (Atomic::TPositiveInt, Atomic::TNumeric) => true,
1756 (Atomic::TPositiveInt, Atomic::TScalar) => true,
1757 (Atomic::TNegativeInt, Atomic::TInt) => true,
1758 (Atomic::TNegativeInt, Atomic::TNumeric) => true,
1759 (Atomic::TNegativeInt, Atomic::TScalar) => true,
1760 (Atomic::TNonNegativeInt, Atomic::TInt) => true,
1761 (Atomic::TNonNegativeInt, Atomic::TNumeric) => true,
1762 (Atomic::TNonNegativeInt, Atomic::TScalar) => true,
1763 (Atomic::TIntRange { .. }, Atomic::TInt) => true,
1764 (Atomic::TIntRange { .. }, Atomic::TNumeric) => true,
1765 (Atomic::TIntRange { .. }, Atomic::TScalar) => true,
1766 (Atomic::TPositiveInt, Atomic::TIntRange { min, max }) => {
1768 max.is_none() && min.is_none_or(|m| m <= 1)
1769 }
1770 (Atomic::TNegativeInt, Atomic::TIntRange { min, max }) => {
1772 min.is_none() && max.is_none_or(|m| m >= -1)
1773 }
1774 (Atomic::TNonNegativeInt, Atomic::TIntRange { min, max }) => {
1776 max.is_none() && min.is_none_or(|m| m <= 0)
1777 }
1778 (Atomic::TIntRange { min: sub_min, .. }, Atomic::TPositiveInt) => {
1780 sub_min.is_some_and(|lo| lo >= 1)
1781 }
1782 (Atomic::TIntRange { min: sub_min, .. }, Atomic::TNonNegativeInt) => {
1783 sub_min.is_some_and(|lo| lo >= 0)
1784 }
1785 (Atomic::TIntRange { max: sub_max, .. }, Atomic::TNegativeInt) => {
1786 sub_max.is_some_and(|hi| hi <= -1)
1787 }
1788 (
1790 Atomic::TIntRange {
1791 min: sub_min,
1792 max: sub_max,
1793 },
1794 Atomic::TIntRange {
1795 min: sup_min,
1796 max: sup_max,
1797 },
1798 ) => {
1799 let lower_ok = match (sub_min, sup_min) {
1800 (_, None) => true,
1801 (None, Some(_)) => false,
1802 (Some(sl), Some(su)) => sl >= su,
1803 };
1804 let upper_ok = match (sub_max, sup_max) {
1805 (None, None) | (Some(_), None) => true,
1806 (None, Some(_)) => false,
1807 (Some(sl), Some(su)) => sl <= su,
1808 };
1809 lower_ok && upper_ok
1810 }
1811
1812 (Atomic::TLiteralFloat(..), Atomic::TFloat) => true,
1813 (Atomic::TLiteralFloat(..), Atomic::TNumeric) => true,
1814 (Atomic::TLiteralFloat(..), Atomic::TScalar) => true,
1815
1816 (Atomic::TLiteralString(s), Atomic::TString) => {
1817 let _ = s;
1818 true
1819 }
1820 (Atomic::TLiteralString(s), Atomic::TCallableString) => {
1821 let _ = s;
1822 true
1823 }
1824 (Atomic::TLiteralString(s), Atomic::TNonEmptyString) => !s.is_empty(),
1825 (Atomic::TLiteralString(s), Atomic::TNumericString) => s.parse::<f64>().is_ok(),
1826 (Atomic::TLiteralString(_), Atomic::TClassString(_)) => true,
1829 (Atomic::TLiteralString(_), Atomic::TInterfaceString(_)) => true,
1832 (Atomic::TLiteralString(_), Atomic::TScalar) => true,
1833 (Atomic::TNonEmptyString, Atomic::TString) => true,
1834 (Atomic::TCallableString, Atomic::TString) => true,
1835 (Atomic::TNumericString, Atomic::TNonEmptyString) => true,
1837 (Atomic::TNumericString, Atomic::TString) => true,
1838 (Atomic::TClassString(_), Atomic::TNonEmptyString) => true,
1842 (Atomic::TInterfaceString(_), Atomic::TNonEmptyString) => true,
1843 (Atomic::TCallableString, Atomic::TNonEmptyString) => true,
1844 (Atomic::TEnumString, Atomic::TNonEmptyString) => true,
1845 (Atomic::TTraitString, Atomic::TNonEmptyString) => true,
1846 (Atomic::TClassString(_), Atomic::TString) => true,
1847 (Atomic::TInterfaceString(_), Atomic::TString) => true,
1848 (Atomic::TInterfaceString(_), Atomic::TClassString(None)) => true,
1853 (Atomic::TInterfaceString(Some(a)), Atomic::TClassString(Some(b))) => a == b,
1854 (Atomic::TEnumString, Atomic::TString) => true,
1855 (Atomic::TTraitString, Atomic::TString) => true,
1856
1857 (Atomic::TTrue, Atomic::TBool) => true,
1858 (Atomic::TFalse, Atomic::TBool) => true,
1859
1860 (Atomic::TInt, Atomic::TNumeric) => true,
1861 (Atomic::TFloat, Atomic::TNumeric) => true,
1862 (Atomic::TIntegralFloat, Atomic::TNumeric) => true,
1863 (Atomic::TNumericString, Atomic::TNumeric) => true,
1864
1865 (Atomic::TInt, Atomic::TScalar) => true,
1866 (Atomic::TFloat, Atomic::TScalar) => true,
1867 (Atomic::TIntegralFloat, Atomic::TScalar) => true,
1868 (Atomic::TString, Atomic::TScalar) => true,
1869 (Atomic::TBool, Atomic::TScalar) => true,
1870 (Atomic::TNumeric, Atomic::TScalar) => true,
1871 (Atomic::TTrue, Atomic::TScalar) => true,
1872 (Atomic::TFalse, Atomic::TScalar) => true,
1873 (Atomic::TNonEmptyString, Atomic::TScalar) => true,
1877 (Atomic::TNumericString, Atomic::TScalar) => true,
1878 (Atomic::TCallableString, Atomic::TScalar) => true,
1879 (Atomic::TClassString(_), Atomic::TScalar) => true,
1880 (Atomic::TInterfaceString(_), Atomic::TScalar) => true,
1881 (Atomic::TEnumString, Atomic::TScalar) => true,
1882 (Atomic::TTraitString, Atomic::TScalar) => true,
1883
1884 (Atomic::TNamedObject { .. }, Atomic::TObject) => true,
1886 (Atomic::TStaticObject { .. }, Atomic::TObject) => true,
1887 (Atomic::TSelf { .. }, Atomic::TObject) => true,
1888 (Atomic::TLiteralEnumCase { .. }, Atomic::TObject) => true,
1890 (Atomic::TSelf { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
1892 (Atomic::TStaticObject { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
1893 (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TSelf { fqcn: b }) => a == b,
1895 (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TStaticObject { fqcn: b }) => a == b,
1896 (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TNamedObject { fqcn, .. }) => {
1899 enum_fqcn == fqcn
1900 }
1901 (
1905 Atomic::TNamedObject {
1906 fqcn: sub_fqcn,
1907 type_params: sub_params,
1908 },
1909 Atomic::TNamedObject {
1910 fqcn: sup_fqcn,
1911 type_params: sup_params,
1912 },
1913 ) => {
1914 sub_fqcn == sup_fqcn
1915 && (sup_params.is_empty() || type_params_compatible(sub_params, sup_params))
1916 }
1917
1918 (Atomic::TIntegralFloat, Atomic::TFloat) => true,
1920
1921 (Atomic::TLiteralInt(_), Atomic::TFloat) => true,
1923 (Atomic::TPositiveInt, Atomic::TFloat) => true,
1924 (Atomic::TNegativeInt, Atomic::TFloat) => true,
1925 (Atomic::TNonNegativeInt, Atomic::TFloat) => true,
1926 (Atomic::TInt, Atomic::TFloat) => true,
1927 (Atomic::TIntRange { .. }, Atomic::TFloat) => true,
1928
1929 (Atomic::TLiteralInt(n), Atomic::TIntRange { min, max }) => {
1931 min.is_none_or(|lo| *n >= lo) && max.is_none_or(|hi| *n <= hi)
1932 }
1933
1934 (Atomic::TString, Atomic::TCallable { .. }) => true,
1936 (Atomic::TNonEmptyString, Atomic::TCallable { .. }) => true,
1937 (Atomic::TLiteralString(_), Atomic::TCallable { .. }) => true,
1938 (Atomic::TArray { .. }, Atomic::TCallable { .. }) => true,
1939 (Atomic::TNonEmptyArray { .. }, Atomic::TCallable { .. }) => true,
1940 (Atomic::TKeyedArray { .. }, Atomic::TCallable { .. }) => true,
1941
1942 (Atomic::TClosure { .. }, Atomic::TCallable { .. }) => true,
1944 (Atomic::TCallable { .. }, Atomic::TClosure { .. }) => true,
1946 (Atomic::TClosure { data: sub }, Atomic::TClosure { data: sup }) => {
1956 fn has_nominal_type(t: &Type) -> bool {
1957 t.types.iter().any(|a| {
1958 matches!(
1959 a,
1960 Atomic::TNamedObject { .. }
1961 | Atomic::TSelf { .. }
1962 | Atomic::TStaticObject { .. }
1963 | Atomic::TTemplateParam { .. }
1964 | Atomic::TClosure { .. }
1965 | Atomic::TCallable { .. }
1966 )
1967 })
1968 }
1969 let sub_required = sub
1970 .params
1971 .iter()
1972 .filter(|p| !p.is_optional && !p.is_variadic)
1973 .count();
1974 if sub_required > sup.params.len() {
1975 false
1976 } else {
1977 let params_ok = sup.params.iter().enumerate().all(|(i, sup_param)| {
1978 let Some(sub_param) = sub.params.get(i) else {
1979 return true;
1980 };
1981 if sub_param.is_optional || sub_param.is_variadic {
1982 return true;
1983 }
1984 let (Some(sub_ty), Some(sup_ty)) =
1985 (sub_param.ty.as_ref(), sup_param.ty.as_ref())
1986 else {
1987 return true;
1988 };
1989 let (sub_u, sup_u) = (sub_ty.to_union(), sup_ty.to_union());
1990 if has_nominal_type(&sub_u) || has_nominal_type(&sup_u) {
1991 return true;
1992 }
1993 sup_u.is_subtype_structural(&sub_u)
1996 });
1997 params_ok
1998 && (sub.return_type.is_mixed()
1999 || sup.return_type.is_mixed()
2000 || has_nominal_type(&sub.return_type)
2001 || has_nominal_type(&sup.return_type)
2002 || sub.return_type.is_subtype_structural(&sup.return_type))
2003 }
2004 }
2005 (Atomic::TCallable { .. }, Atomic::TCallable { .. }) => true,
2007 (Atomic::TClosure { .. }, Atomic::TNamedObject { fqcn, .. }) => {
2009 fqcn.as_ref().eq_ignore_ascii_case("closure")
2010 }
2011 (Atomic::TClosure { .. }, Atomic::TObject) => true,
2012 (Atomic::TNamedObject { fqcn, .. }, Atomic::TClosure { .. }) => {
2014 fqcn.as_ref().eq_ignore_ascii_case("closure")
2015 }
2016 (Atomic::TNamedObject { fqcn, .. }, Atomic::TCallable { .. }) => {
2018 fqcn.as_ref().eq_ignore_ascii_case("closure")
2019 }
2020
2021 (
2029 Atomic::TIntersection { parts: sub_parts },
2030 Atomic::TIntersection { parts: sup_parts },
2031 ) => sup_parts.iter().all(|sup_part| {
2032 sub_parts
2033 .iter()
2034 .any(|sub_part| sub_part.is_subtype_structural(sup_part))
2035 }),
2036
2037 (Atomic::TList { value }, Atomic::TArray { key, value: av }) => {
2039 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2040 }
2041 (Atomic::TNonEmptyList { value }, Atomic::TArray { key, value: av }) => {
2042 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2043 }
2044 (Atomic::TNonEmptyList { value }, Atomic::TNonEmptyArray { key, value: av }) => {
2045 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2046 }
2047 (Atomic::TNonEmptyList { value }, Atomic::TList { value: lv }) => {
2048 value.is_subtype_structural(lv)
2049 }
2050 (Atomic::TArray { key, value: av }, Atomic::TList { value: lv }) => {
2052 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2053 && av.is_subtype_structural(lv)
2054 }
2055 (Atomic::TArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
2056 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2057 && av.is_subtype_structural(lv)
2058 }
2059 (Atomic::TNonEmptyArray { key, value: av }, Atomic::TList { value: lv }) => {
2060 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2061 && av.is_subtype_structural(lv)
2062 }
2063 (Atomic::TNonEmptyArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
2064 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2065 && av.is_subtype_structural(lv)
2066 }
2067 (Atomic::TList { value: v1 }, Atomic::TList { value: v2 }) => v1.is_subtype_structural(v2),
2069 (Atomic::TNonEmptyArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
2070 k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
2071 }
2072
2073 (Atomic::TArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
2075 k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
2076 }
2077
2078 (Atomic::TKeyedArray { properties, .. }, Atomic::TArray { key, value }) => {
2087 properties.iter().all(|(prop_key, prop)| {
2088 let key_atomic = match prop_key {
2089 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2090 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2091 };
2092 if !Type::single(key_atomic).is_subtype_structural(key) {
2093 return false; }
2095 let has_named_obj = prop.ty.types.iter().any(|a| {
2097 matches!(
2098 a,
2099 Atomic::TNamedObject { .. }
2100 | Atomic::TSelf { .. }
2101 | Atomic::TStaticObject { .. }
2102 | Atomic::TClosure { .. }
2103 | Atomic::TTemplateParam { .. }
2104 )
2105 });
2106 has_named_obj || prop.ty.is_subtype_structural(value)
2107 })
2108 }
2109 (
2110 Atomic::TKeyedArray {
2111 properties,
2112 is_open,
2113 ..
2114 },
2115 Atomic::TNonEmptyArray { key, value },
2116 ) => {
2117 (*is_open || properties.iter().any(|(_, p)| !p.optional))
2118 && properties.iter().all(|(prop_key, prop)| {
2119 let key_atomic = match prop_key {
2120 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2121 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2122 };
2123 if !Type::single(key_atomic).is_subtype_structural(key) {
2124 return false;
2125 }
2126 let has_named_obj = prop.ty.types.iter().any(|a| {
2127 matches!(
2128 a,
2129 Atomic::TNamedObject { .. }
2130 | Atomic::TSelf { .. }
2131 | Atomic::TStaticObject { .. }
2132 | Atomic::TClosure { .. }
2133 | Atomic::TTemplateParam { .. }
2134 )
2135 });
2136 has_named_obj || prop.ty.is_subtype_structural(value)
2137 })
2138 }
2139
2140 (
2142 Atomic::TKeyedArray {
2143 properties,
2144 is_list,
2145 ..
2146 },
2147 Atomic::TList { value: lv },
2148 ) => *is_list && properties.values().all(|p| p.ty.is_subtype_structural(lv)),
2149 (
2150 Atomic::TKeyedArray {
2151 properties,
2152 is_list,
2153 ..
2154 },
2155 Atomic::TNonEmptyList { value: lv },
2156 ) => {
2157 *is_list
2158 && !properties.is_empty()
2159 && properties.values().all(|p| p.ty.is_subtype_structural(lv))
2160 }
2161
2162 (
2167 Atomic::TKeyedArray {
2168 properties: sub_props,
2169 is_open: sub_open,
2170 ..
2171 },
2172 Atomic::TKeyedArray {
2173 properties: sup_props,
2174 is_open: sup_open,
2175 ..
2176 },
2177 ) => {
2178 let keys_satisfied = sup_props
2179 .iter()
2180 .all(|(key, sup_prop)| match sub_props.get(key) {
2181 Some(sub_prop) => {
2182 if !sup_prop.optional && sub_prop.optional {
2186 return false;
2187 }
2188 let has_named_obj = sup_prop.ty.types.iter().any(|a| {
2189 matches!(
2190 a,
2191 Atomic::TNamedObject { .. }
2192 | Atomic::TSelf { .. }
2193 | Atomic::TStaticObject { .. }
2194 | Atomic::TClosure { .. }
2195 | Atomic::TTemplateParam { .. }
2196 )
2197 });
2198 has_named_obj || sub_prop.ty.is_subtype_structural(&sup_prop.ty)
2199 }
2200 None => sup_prop.optional || *sub_open,
2201 });
2202 let no_undeclared_extras =
2203 *sup_open || sub_props.keys().all(|k| sup_props.contains_key(k));
2204 keys_satisfied && no_undeclared_extras
2205 }
2206
2207 _ => false,
2208 }
2209}
2210
2211fn type_params_compatible(sub: &[Type], sup: &[Type]) -> bool {
2217 if sub.len() != sup.len() {
2218 return false;
2219 }
2220 sub.iter()
2221 .zip(sup.iter())
2222 .all(|(a, b)| a == b || (is_empty_array_literal(a) && is_array_like(b)))
2223}
2224
2225fn is_empty_array_literal(t: &Type) -> bool {
2228 !t.types.is_empty()
2229 && t.types.iter().all(
2230 |atom| matches!(atom, Atomic::TKeyedArray { properties, .. } if properties.is_empty()),
2231 )
2232}
2233
2234fn is_array_like(t: &Type) -> bool {
2236 !t.types.is_empty() && t.types.iter().all(|atom| atom.is_array())
2237}
2238
2239#[cfg(test)]
2244mod tests {
2245 use std::sync::Arc;
2246
2247 use super::*;
2248
2249 fn conditional(
2250 param_name: Option<Name>,
2251 subject: Type,
2252 if_true: Type,
2253 if_false: Type,
2254 ) -> Atomic {
2255 Atomic::TConditional {
2256 data: Box::new(crate::atomic::ConditionalData {
2257 param_name,
2258 subject,
2259 if_true,
2260 if_false,
2261 }),
2262 }
2263 }
2264
2265 #[test]
2266 fn single_is_single() {
2267 let u = Type::single(Atomic::TString);
2268 assert!(u.is_single());
2269 assert!(!u.is_nullable());
2270 }
2271
2272 #[test]
2273 fn nullable_has_null() {
2274 let u = Type::nullable(Atomic::TString);
2275 assert!(u.is_nullable());
2276 assert_eq!(u.types.len(), 2);
2277 }
2278
2279 #[test]
2280 fn add_type_deduplicates() {
2281 let mut u = Type::single(Atomic::TString);
2282 u.add_type(Atomic::TString);
2283 assert_eq!(u.types.len(), 1);
2284 }
2285
2286 #[test]
2287 fn array_key_is_int_string() {
2288 let k = Type::array_key();
2289 assert!(k.is_array_key());
2290 assert_eq!(k.types.len(), 2);
2291 }
2292
2293 #[test]
2294 fn is_array_key_false_for_plain_int() {
2295 assert!(!Type::int().is_array_key());
2296 }
2297
2298 #[test]
2299 fn is_array_key_false_for_mixed() {
2300 assert!(!Type::mixed().is_array_key());
2301 }
2302
2303 #[test]
2304 fn is_array_key_false_for_int_string_null() {
2305 let mut u = Type::array_key();
2306 u.add_type(Atomic::TNull);
2307 assert!(!u.is_array_key());
2308 }
2309
2310 #[test]
2311 fn add_type_literal_subsumed_by_base() {
2312 let mut u = Type::single(Atomic::TInt);
2313 u.add_type(Atomic::TLiteralInt(42));
2314 assert_eq!(u.types.len(), 1);
2315 assert!(matches!(u.types[0], Atomic::TInt));
2316 }
2317
2318 #[test]
2319 fn true_then_false_merges_to_bool() {
2320 let mut u = Type::single(Atomic::TTrue);
2321 u.add_type(Atomic::TFalse);
2322 assert_eq!(u.types.len(), 1);
2323 assert!(matches!(u.types[0], Atomic::TBool));
2324 }
2325
2326 #[test]
2327 fn false_then_true_merges_to_bool() {
2328 let mut u = Type::single(Atomic::TFalse);
2329 u.add_type(Atomic::TTrue);
2330 assert_eq!(u.types.len(), 1);
2331 assert!(matches!(u.types[0], Atomic::TBool));
2332 }
2333
2334 #[test]
2335 fn true_alone_stays_true() {
2336 let u = Type::single(Atomic::TTrue);
2337 assert_eq!(u.types.len(), 1);
2338 assert!(matches!(u.types[0], Atomic::TTrue));
2339 }
2340
2341 #[test]
2342 fn true_false_merge_preserves_other_union_members() {
2343 let mut u = Type::single(Atomic::TTrue);
2344 u.add_type(Atomic::TNull);
2345 u.add_type(Atomic::TFalse);
2346 assert_eq!(u.types.len(), 2);
2347 assert!(u.contains(|t| matches!(t, Atomic::TBool)));
2348 assert!(u.contains(|t| matches!(t, Atomic::TNull)));
2349 }
2350
2351 #[test]
2352 fn add_type_base_widens_literals() {
2353 let mut u = Type::single(Atomic::TLiteralInt(1));
2354 u.add_type(Atomic::TLiteralInt(2));
2355 u.add_type(Atomic::TInt);
2356 assert_eq!(u.types.len(), 1);
2357 assert!(matches!(u.types[0], Atomic::TInt));
2358 }
2359
2360 #[test]
2361 fn mixed_subsumes_everything() {
2362 let mut u = Type::single(Atomic::TString);
2363 u.add_type(Atomic::TMixed);
2364 assert_eq!(u.types.len(), 1);
2365 assert!(u.is_mixed());
2366 }
2367
2368 #[test]
2369 fn remove_null() {
2370 let u = Type::nullable(Atomic::TString);
2371 let narrowed = u.remove_null();
2372 assert!(!narrowed.is_nullable());
2373 assert_eq!(narrowed.types.len(), 1);
2374 }
2375
2376 #[test]
2377 fn narrow_to_truthy_removes_null_false() {
2378 let mut u = Type::empty();
2379 u.add_type(Atomic::TString);
2380 u.add_type(Atomic::TNull);
2381 u.add_type(Atomic::TFalse);
2382 let truthy = u.narrow_to_truthy();
2383 assert!(!truthy.is_nullable());
2384 assert!(!truthy.contains(|t| matches!(t, Atomic::TFalse)));
2385 }
2386
2387 #[test]
2388 fn merge_combines_types() {
2389 let a = Type::single(Atomic::TString);
2390 let b = Type::single(Atomic::TInt);
2391 let merged = Type::merge(&a, &b);
2392 assert_eq!(merged.types.len(), 2);
2393 }
2394
2395 #[test]
2396 fn intersect_keeps_narrower_side_not_self() {
2397 let int_ty = Type::single(Atomic::TInt);
2401 let mut literals = Type::empty();
2402 literals.add_type(Atomic::TLiteralInt(1));
2403 literals.add_type(Atomic::TLiteralInt(2));
2404
2405 let narrowed = int_ty.intersect_with(&literals);
2406 assert_eq!(narrowed.types.len(), 2);
2407 assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(1))));
2408 assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(2))));
2409 assert!(!narrowed.contains(|t| matches!(t, Atomic::TInt)));
2410 }
2411
2412 #[test]
2413 fn subtype_literal_int_under_int() {
2414 let sub = Type::single(Atomic::TLiteralInt(5));
2415 let sup = Type::single(Atomic::TInt);
2416 assert!(sub.is_subtype_structural(&sup));
2417 }
2418
2419 #[test]
2420 fn subtype_never_is_bottom() {
2421 let never = Type::never();
2422 let string = Type::single(Atomic::TString);
2423 assert!(never.is_subtype_structural(&string));
2424 }
2425
2426 #[test]
2427 fn subtype_everything_under_mixed() {
2428 let string = Type::single(Atomic::TString);
2429 let mixed = Type::mixed();
2430 assert!(string.is_subtype_structural(&mixed));
2431 }
2432
2433 #[test]
2434 fn subtype_enum_case_under_own_enum() {
2435 let sub = Type::single(Atomic::TLiteralEnumCase {
2436 enum_fqcn: Name::new("RoundingMode"),
2437 case_name: Name::new("Unnecessary"),
2438 });
2439 let sup = Type::single(Atomic::TNamedObject {
2440 fqcn: Name::new("RoundingMode"),
2441 type_params: empty_type_params(),
2442 });
2443 assert!(sub.is_subtype_structural(&sup));
2444 }
2445
2446 #[test]
2447 fn enum_case_not_subtype_of_unrelated_enum() {
2448 let sub = Type::single(Atomic::TLiteralEnumCase {
2449 enum_fqcn: Name::new("RoundingMode"),
2450 case_name: Name::new("Unnecessary"),
2451 });
2452 let sup = Type::single(Atomic::TNamedObject {
2453 fqcn: Name::new("Suit"),
2454 type_params: empty_type_params(),
2455 });
2456 assert!(!sub.is_subtype_structural(&sup));
2457 }
2458
2459 #[test]
2460 fn subtype_enum_case_under_bare_object() {
2461 let sub = Type::single(Atomic::TLiteralEnumCase {
2462 enum_fqcn: Name::new("RoundingMode"),
2463 case_name: Name::new("Unnecessary"),
2464 });
2465 let sup = Type::single(Atomic::TObject);
2466 assert!(sub.is_subtype_structural(&sup));
2467 }
2468
2469 #[test]
2470 fn template_substitution() {
2471 let mut bindings = FxHashMap::default();
2472 bindings.insert(Name::new("T"), Type::single(Atomic::TString));
2473
2474 let tmpl = Type::single(Atomic::TTemplateParam {
2475 name: Name::new("T"),
2476 as_type: Box::new(Type::mixed()),
2477 defining_entity: Name::new("MyClass"),
2478 });
2479
2480 let resolved = tmpl.substitute_templates(&bindings);
2481 assert_eq!(resolved.types.len(), 1);
2482 assert!(matches!(resolved.types[0], Atomic::TString));
2483 }
2484
2485 #[test]
2486 fn intersection_is_object() {
2487 let parts = vec![
2488 Type::single(Atomic::TNamedObject {
2489 fqcn: Name::new("Iterator"),
2490 type_params: empty_type_params(),
2491 }),
2492 Type::single(Atomic::TNamedObject {
2493 fqcn: Name::new("Countable"),
2494 type_params: empty_type_params(),
2495 }),
2496 ];
2497 let atomic = Atomic::TIntersection {
2498 parts: vec_to_type_params(parts),
2499 };
2500 assert!(atomic.is_object());
2501 assert!(!atomic.can_be_falsy());
2502 assert!(atomic.can_be_truthy());
2503 }
2504
2505 #[test]
2506 fn intersection_display_two_parts() {
2507 let parts = vec![
2508 Type::single(Atomic::TNamedObject {
2509 fqcn: Name::new("Iterator"),
2510 type_params: empty_type_params(),
2511 }),
2512 Type::single(Atomic::TNamedObject {
2513 fqcn: Name::new("Countable"),
2514 type_params: empty_type_params(),
2515 }),
2516 ];
2517 let u = Type::single(Atomic::TIntersection {
2518 parts: vec_to_type_params(parts),
2519 });
2520 assert_eq!(format!("{u}"), "Iterator&Countable");
2521 }
2522
2523 #[test]
2524 fn intersection_display_three_parts() {
2525 let parts = vec![
2526 Type::single(Atomic::TNamedObject {
2527 fqcn: Name::new("A"),
2528 type_params: empty_type_params(),
2529 }),
2530 Type::single(Atomic::TNamedObject {
2531 fqcn: Name::new("B"),
2532 type_params: empty_type_params(),
2533 }),
2534 Type::single(Atomic::TNamedObject {
2535 fqcn: Name::new("C"),
2536 type_params: empty_type_params(),
2537 }),
2538 ];
2539 let u = Type::single(Atomic::TIntersection {
2540 parts: vec_to_type_params(parts),
2541 });
2542 assert_eq!(format!("{u}"), "A&B&C");
2543 }
2544
2545 #[test]
2546 fn intersection_in_nullable_union_display() {
2547 let intersection = Atomic::TIntersection {
2548 parts: vec_to_type_params(vec![
2549 Type::single(Atomic::TNamedObject {
2550 fqcn: Name::new("Iterator"),
2551 type_params: empty_type_params(),
2552 }),
2553 Type::single(Atomic::TNamedObject {
2554 fqcn: Name::new("Countable"),
2555 type_params: empty_type_params(),
2556 }),
2557 ]),
2558 };
2559 let mut u = Type::single(intersection);
2560 u.add_type(Atomic::TNull);
2561 assert!(u.is_nullable());
2562 assert!(u.contains(|t| matches!(t, Atomic::TIntersection { .. })));
2563 }
2564
2565 fn t_param(name: &str) -> Type {
2568 Type::single(Atomic::TTemplateParam {
2569 name: Name::new(name),
2570 as_type: Box::new(Type::mixed()),
2571 defining_entity: Name::new("Fn"),
2572 })
2573 }
2574
2575 fn bindings_t_string() -> FxHashMap<Name, Type> {
2576 let mut b = FxHashMap::default();
2577 b.insert(Name::new("T"), Type::single(Atomic::TString));
2578 b
2579 }
2580
2581 #[test]
2582 fn substitute_non_empty_array_key_and_value() {
2583 let ty = Type::single(Atomic::TNonEmptyArray {
2584 key: Box::new(t_param("T")),
2585 value: Box::new(t_param("T")),
2586 });
2587 let result = ty.substitute_templates(&bindings_t_string());
2588 assert_eq!(result.types.len(), 1);
2589 let Atomic::TNonEmptyArray { key, value } = &result.types[0] else {
2590 panic!("expected TNonEmptyArray");
2591 };
2592 assert!(matches!(key.types[0], Atomic::TString));
2593 assert!(matches!(value.types[0], Atomic::TString));
2594 }
2595
2596 #[test]
2597 fn substitute_non_empty_list_value() {
2598 let ty = Type::single(Atomic::TNonEmptyList {
2599 value: Box::new(t_param("T")),
2600 });
2601 let result = ty.substitute_templates(&bindings_t_string());
2602 let Atomic::TNonEmptyList { value } = &result.types[0] else {
2603 panic!("expected TNonEmptyList");
2604 };
2605 assert!(matches!(value.types[0], Atomic::TString));
2606 }
2607
2608 #[test]
2609 fn substitute_keyed_array_property_types() {
2610 use crate::atomic::{ArrayKey, KeyedProperty};
2611 use indexmap::IndexMap;
2612 let mut props = IndexMap::new();
2613 props.insert(
2614 ArrayKey::String(Arc::from("name")),
2615 KeyedProperty {
2616 ty: t_param("T"),
2617 optional: false,
2618 },
2619 );
2620 props.insert(
2621 ArrayKey::String(Arc::from("tag")),
2622 KeyedProperty {
2623 ty: t_param("T"),
2624 optional: true,
2625 },
2626 );
2627 let ty = Type::single(Atomic::TKeyedArray {
2628 properties: Box::new(props),
2629 is_open: true,
2630 is_list: false,
2631 });
2632 let result = ty.substitute_templates(&bindings_t_string());
2633 let Atomic::TKeyedArray {
2634 properties,
2635 is_open,
2636 is_list,
2637 } = &result.types[0]
2638 else {
2639 panic!("expected TKeyedArray");
2640 };
2641 assert!(is_open);
2642 assert!(!is_list);
2643 assert!(matches!(
2644 properties[&ArrayKey::String(Arc::from("name"))].ty.types[0],
2645 Atomic::TString
2646 ));
2647 assert!(properties[&ArrayKey::String(Arc::from("tag"))].optional);
2648 assert!(matches!(
2649 properties[&ArrayKey::String(Arc::from("tag"))].ty.types[0],
2650 Atomic::TString
2651 ));
2652 }
2653
2654 #[test]
2655 fn substitute_callable_params_and_return() {
2656 use crate::atomic::FnParam;
2657 let ty = Type::single(Atomic::TCallable {
2658 params: Some(Box::new([FnParam {
2659 name: Name::new("x"),
2660 ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
2661 out_ty: None,
2662 default: None,
2663 is_variadic: false,
2664 is_byref: false,
2665 is_optional: false,
2666 }])),
2667 return_type: Some(Box::new(t_param("T"))),
2668 });
2669 let result = ty.substitute_templates(&bindings_t_string());
2670 let Atomic::TCallable {
2671 params,
2672 return_type,
2673 } = &result.types[0]
2674 else {
2675 panic!("expected TCallable");
2676 };
2677 let param_ty = params.as_ref().unwrap()[0].ty.as_ref().unwrap();
2678 let param_union = param_ty.to_union();
2679 assert!(matches!(param_union.types[0], Atomic::TString));
2680 let ret = return_type.as_ref().unwrap();
2681 assert!(matches!(ret.types[0], Atomic::TString));
2682 }
2683
2684 #[test]
2685 fn substitute_callable_bare_no_panic() {
2686 let ty = Type::single(Atomic::TCallable {
2688 params: None,
2689 return_type: None,
2690 });
2691 let result = ty.substitute_templates(&bindings_t_string());
2692 assert!(matches!(
2693 result.types[0],
2694 Atomic::TCallable {
2695 params: None,
2696 return_type: None
2697 }
2698 ));
2699 }
2700
2701 #[test]
2702 fn substitute_closure_params_return_and_this() {
2703 use crate::atomic::FnParam;
2704 let ty = Type::single(Atomic::TClosure {
2705 data: Box::new(crate::atomic::ClosureData {
2706 params: Box::new([FnParam {
2707 name: Name::new("a"),
2708 ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
2709 out_ty: None,
2710 default: Some(crate::compact::SimpleType::from_union(t_param("T"))),
2711 is_variadic: true,
2712 is_byref: true,
2713 is_optional: true,
2714 }]),
2715 return_type: t_param("T"),
2716 this_type: Some(t_param("T")),
2717 }),
2718 });
2719 let result = ty.substitute_templates(&bindings_t_string());
2720 let Atomic::TClosure { data } = &result.types[0] else {
2721 panic!("expected TClosure");
2722 };
2723 let (params, return_type, this_type) = (&data.params, &data.return_type, &data.this_type);
2724 let p = ¶ms[0];
2725 let ty_union = p.ty.as_ref().unwrap().to_union();
2726 let default_union = p.default.as_ref().unwrap().to_union();
2727 assert!(matches!(ty_union.types[0], Atomic::TString));
2728 assert!(matches!(default_union.types[0], Atomic::TString));
2729 assert!(p.is_variadic);
2731 assert!(p.is_byref);
2732 assert!(p.is_optional);
2733 assert!(matches!(return_type.types[0], Atomic::TString));
2734 assert!(matches!(
2735 this_type.as_ref().unwrap().types[0],
2736 Atomic::TString
2737 ));
2738 }
2739
2740 #[test]
2741 fn substitute_conditional_all_branches() {
2742 let ty = Type::single(conditional(
2743 None,
2744 t_param("T"),
2745 t_param("T"),
2746 Type::single(Atomic::TInt),
2747 ));
2748 let result = ty.substitute_templates(&bindings_t_string());
2749 let Atomic::TConditional { data } = &result.types[0] else {
2750 panic!("expected TConditional");
2751 };
2752 let (subject, if_true, if_false) = (&data.subject, &data.if_true, &data.if_false);
2753 assert!(matches!(subject.types[0], Atomic::TString));
2754 assert!(matches!(if_true.types[0], Atomic::TString));
2755 assert!(matches!(if_false.types[0], Atomic::TInt));
2756 }
2757
2758 #[test]
2759 fn resolve_conditional_is_null_non_null_arg() {
2760 let ty = Type::single(conditional(
2761 Some(Name::new("x")),
2762 Type::single(Atomic::TNull),
2763 Type::single(Atomic::TInt),
2764 Type::single(Atomic::TString),
2765 ));
2766 let result = ty.resolve_conditional_returns(|name| {
2767 if name == "x" {
2768 Some(Type::single(Atomic::TString)) } else {
2770 None
2771 }
2772 });
2773 assert!(result.types.len() == 1);
2774 assert!(matches!(result.types[0], Atomic::TString));
2775 }
2776
2777 #[test]
2778 fn resolve_conditional_is_null_null_arg() {
2779 let ty = Type::single(conditional(
2780 Some(Name::new("x")),
2781 Type::single(Atomic::TNull),
2782 Type::single(Atomic::TInt),
2783 Type::single(Atomic::TString),
2784 ));
2785 let result = ty.resolve_conditional_returns(|name| {
2786 if name == "x" {
2787 Some(Type::single(Atomic::TNull)) } else {
2789 None
2790 }
2791 });
2792 assert!(result.types.len() == 1);
2793 assert!(matches!(result.types[0], Atomic::TInt));
2794 }
2795
2796 #[test]
2797 fn resolve_conditional_is_null_nullable_arg_widens_to_branch_union() {
2798 let mut nullable_str = Type::single(Atomic::TString);
2799 nullable_str.add_type(Atomic::TNull);
2800 let ty = Type::single(conditional(
2801 Some(Name::new("x")),
2802 Type::single(Atomic::TNull),
2803 Type::single(Atomic::TInt),
2804 Type::single(Atomic::TString),
2805 ));
2806 let result = ty.resolve_conditional_returns(|name| {
2807 if name == "x" {
2808 Some(nullable_str.clone())
2809 } else {
2810 None
2811 }
2812 });
2813 assert_eq!(result.types.len(), 2);
2815 assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
2816 assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
2817 }
2818
2819 #[test]
2820 fn resolve_conditional_nested_widens_inner_branch() {
2821 let inner = Type::single(conditional(
2824 Some(Name::new("x")),
2825 Type::single(Atomic::TString),
2826 Type::single(Atomic::TString),
2827 Type::single(Atomic::TFloat),
2828 ));
2829 let ty = Type::single(conditional(
2830 Some(Name::new("x")),
2831 Type::single(Atomic::TNull),
2832 Type::single(Atomic::TInt),
2833 inner,
2834 ));
2835 let result = ty.resolve_conditional_returns(|_| None);
2837 assert!(
2838 result
2839 .types
2840 .iter()
2841 .all(|t| !matches!(t, Atomic::TConditional { .. })),
2842 "no TConditional should survive: {:?}",
2843 result.types
2844 );
2845 assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
2846 assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
2847 assert!(result.types.iter().any(|t| matches!(t, Atomic::TFloat)));
2848 }
2849
2850 #[test]
2851 fn resolve_conditional_nested_resolves_inner_branch() {
2852 let inner = Type::single(conditional(
2856 Some(Name::new("x")),
2857 Type::single(Atomic::TString),
2858 Type::single(Atomic::TString),
2859 Type::single(Atomic::TFloat),
2860 ));
2861 let ty = Type::single(conditional(
2862 Some(Name::new("x")),
2863 Type::single(Atomic::TNull),
2864 Type::single(Atomic::TInt),
2865 inner,
2866 ));
2867 let result = ty.resolve_conditional_returns(|name| {
2869 if name == "x" {
2870 Some(Type::single(Atomic::TString))
2871 } else {
2872 None
2873 }
2874 });
2875 assert!(
2876 result
2877 .types
2878 .iter()
2879 .all(|t| !matches!(t, Atomic::TConditional { .. })),
2880 "no TConditional should survive: {:?}",
2881 result.types
2882 );
2883 assert_eq!(result.types.len(), 1);
2884 assert!(matches!(result.types[0], Atomic::TString));
2885 }
2886
2887 #[test]
2888 fn resolve_conditional_true_subject_bool_arg_widens() {
2889 let ty = Type::single(conditional(
2893 Some(Name::new("x")),
2894 Type::single(Atomic::TTrue),
2895 Type::single(Atomic::TInt),
2896 Type::single(Atomic::TString),
2897 ));
2898 let result = ty.resolve_conditional_returns(|name| {
2899 if name == "x" {
2900 Some(Type::single(Atomic::TBool))
2901 } else {
2902 None
2903 }
2904 });
2905 assert_eq!(result.types.len(), 2);
2906 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
2907 assert!(result.contains(|t| matches!(t, Atomic::TString)));
2908 }
2909
2910 #[test]
2911 fn resolve_conditional_true_subject_mixed_arg_widens() {
2912 let ty = Type::single(conditional(
2915 Some(Name::new("x")),
2916 Type::single(Atomic::TTrue),
2917 Type::single(Atomic::TInt),
2918 Type::single(Atomic::TString),
2919 ));
2920 let result = ty.resolve_conditional_returns(|name| {
2921 if name == "x" {
2922 Some(Type::mixed())
2923 } else {
2924 None
2925 }
2926 });
2927 assert_eq!(result.types.len(), 2);
2928 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
2929 assert!(result.contains(|t| matches!(t, Atomic::TString)));
2930 }
2931
2932 #[test]
2933 fn resolve_conditional_true_subject_literal_args() {
2934 let ty = Type::single(conditional(
2937 Some(Name::new("x")),
2938 Type::single(Atomic::TTrue),
2939 Type::single(Atomic::TInt),
2940 Type::single(Atomic::TString),
2941 ));
2942 let false_arg = ty.clone().resolve_conditional_returns(|name| {
2943 if name == "x" {
2944 Some(Type::single(Atomic::TFalse))
2945 } else {
2946 None
2947 }
2948 });
2949 assert_eq!(false_arg.types.len(), 1);
2950 assert!(matches!(false_arg.types[0], Atomic::TString));
2951
2952 let true_arg = ty.resolve_conditional_returns(|name| {
2953 if name == "x" {
2954 Some(Type::single(Atomic::TTrue))
2955 } else {
2956 None
2957 }
2958 });
2959 assert_eq!(true_arg.types.len(), 1);
2960 assert!(matches!(true_arg.types[0], Atomic::TInt));
2961 }
2962
2963 #[test]
2964 fn resolve_conditional_bool_subject_scalar_arg_widens() {
2965 let ty = Type::single(conditional(
2969 Some(Name::new("x")),
2970 Type::single(Atomic::TBool),
2971 Type::single(Atomic::TInt),
2972 Type::single(Atomic::TString),
2973 ));
2974 let result = ty.resolve_conditional_returns(|name| {
2975 if name == "x" {
2976 Some(Type::single(Atomic::TScalar))
2977 } else {
2978 None
2979 }
2980 });
2981 assert_eq!(result.types.len(), 2);
2982 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
2983 assert!(result.contains(|t| matches!(t, Atomic::TString)));
2984 }
2985
2986 #[test]
2987 fn resolve_conditional_string_subject_bool_arg_false_branch() {
2988 let ty = Type::single(conditional(
2992 Some(Name::new("x")),
2993 Type::single(Atomic::TString),
2994 Type::single(Atomic::TInt),
2995 Type::single(Atomic::TBool),
2996 ));
2997 let result = ty.resolve_conditional_returns(|name| {
2998 if name == "x" {
2999 Some(Type::single(Atomic::TBool))
3000 } else {
3001 None
3002 }
3003 });
3004 assert_eq!(result.types.len(), 1);
3005 assert!(matches!(result.types[0], Atomic::TBool));
3006 }
3007
3008 #[test]
3009 fn resolve_conditional_list_subject_bare_array_arg_widens() {
3010 let ty = Type::single(conditional(
3013 Some(Name::new("x")),
3014 Type::single(Atomic::TList {
3015 value: Box::new(Type::mixed()),
3016 }),
3017 Type::single(Atomic::TInt),
3018 Type::single(Atomic::TString),
3019 ));
3020 let result = ty.resolve_conditional_returns(|name| {
3021 if name == "x" {
3022 Some(Type::single(Atomic::TArray {
3023 key: Box::new(Type::mixed()),
3024 value: Box::new(Type::mixed()),
3025 }))
3026 } else {
3027 None
3028 }
3029 });
3030 assert_eq!(result.types.len(), 2);
3031 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3032 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3033 }
3034
3035 #[test]
3036 fn resolve_conditional_float_subject_int_literal_false_branch() {
3037 let ty = resolve_conditional_branch(
3040 &Atomic::TFloat,
3041 &Type::single(Atomic::TLiteralInt(42)),
3042 &Type::single(Atomic::TInt),
3043 &Type::single(Atomic::TString),
3044 );
3045 assert!(matches!(
3046 ty.as_ref(),
3047 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3048 ));
3049 }
3050
3051 #[test]
3052 fn resolve_conditional_int_subject_float_literal_false_branch() {
3053 let ty = resolve_conditional_branch(
3054 &Atomic::TInt,
3055 &Type::single(Atomic::TLiteralFloat(1, 0)),
3056 &Type::single(Atomic::TInt),
3057 &Type::single(Atomic::TString),
3058 );
3059 assert!(matches!(
3060 ty.as_ref(),
3061 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3062 ));
3063 }
3064
3065 #[test]
3066 fn resolve_conditional_float_subject_float_literal_then_branch() {
3067 let ty = resolve_conditional_branch(
3068 &Atomic::TFloat,
3069 &Type::single(Atomic::TLiteralFloat(1, 5)),
3070 &Type::single(Atomic::TInt),
3071 &Type::single(Atomic::TString),
3072 );
3073 assert!(matches!(
3074 ty.as_ref(),
3075 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3076 ));
3077 }
3078
3079 #[test]
3080 fn resolve_conditional_int_subject_int_literal_then_branch() {
3081 let ty = resolve_conditional_branch(
3082 &Atomic::TInt,
3083 &Type::single(Atomic::TLiteralInt(7)),
3084 &Type::single(Atomic::TInt),
3085 &Type::single(Atomic::TString),
3086 );
3087 assert!(matches!(
3088 ty.as_ref(),
3089 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3090 ));
3091 }
3092
3093 #[test]
3094 fn resolve_conditional_int_subject_float_arg_false_branch() {
3095 let ty = resolve_conditional_branch(
3098 &Atomic::TInt,
3099 &Type::single(Atomic::TFloat),
3100 &Type::single(Atomic::TInt),
3101 &Type::single(Atomic::TString),
3102 );
3103 assert!(matches!(
3104 ty.as_ref(),
3105 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3106 ));
3107 }
3108
3109 #[test]
3110 fn resolve_conditional_array_subject_string_arg_false_branch() {
3111 let ty = resolve_conditional_branch(
3112 &Atomic::TArray {
3113 key: Box::new(Type::mixed()),
3114 value: Box::new(Type::mixed()),
3115 },
3116 &Type::single(Atomic::TString),
3117 &Type::single(Atomic::TInt),
3118 &Type::single(Atomic::TString),
3119 );
3120 assert!(matches!(
3121 ty.as_ref(),
3122 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3123 ));
3124 }
3125
3126 #[test]
3127 fn resolve_conditional_array_subject_bool_arg_false_branch() {
3128 let ty = resolve_conditional_branch(
3129 &Atomic::TArray {
3130 key: Box::new(Type::mixed()),
3131 value: Box::new(Type::mixed()),
3132 },
3133 &Type::single(Atomic::TBool),
3134 &Type::single(Atomic::TInt),
3135 &Type::single(Atomic::TString),
3136 );
3137 assert!(matches!(
3138 ty.as_ref(),
3139 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3140 ));
3141 }
3142
3143 #[test]
3144 fn resolve_conditional_array_subject_mixed_arg_widens() {
3145 let ty = resolve_conditional_branch(
3149 &Atomic::TArray {
3150 key: Box::new(Type::mixed()),
3151 value: Box::new(Type::mixed()),
3152 },
3153 &Type::mixed(),
3154 &Type::single(Atomic::TInt),
3155 &Type::single(Atomic::TString),
3156 );
3157 assert!(ty.is_none());
3158 }
3159
3160 #[test]
3161 fn resolve_conditional_array_subject_list_arg_then_branch() {
3162 let ty = resolve_conditional_branch(
3165 &Atomic::TArray {
3166 key: Box::new(Type::mixed()),
3167 value: Box::new(Type::mixed()),
3168 },
3169 &Type::single(Atomic::TList {
3170 value: Box::new(Type::mixed()),
3171 }),
3172 &Type::single(Atomic::TInt),
3173 &Type::single(Atomic::TString),
3174 );
3175 assert!(matches!(
3176 ty.as_ref(),
3177 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3178 ));
3179 }
3180
3181 #[test]
3182 fn resolve_conditional_list_subject_keyed_list_arg_then_branch() {
3183 let ty = resolve_conditional_branch(
3185 &Atomic::TList {
3186 value: Box::new(Type::mixed()),
3187 },
3188 &Type::single(Atomic::TKeyedArray {
3189 properties: Box::default(),
3190 is_open: false,
3191 is_list: true,
3192 }),
3193 &Type::single(Atomic::TInt),
3194 &Type::single(Atomic::TString),
3195 );
3196 assert!(matches!(
3197 ty.as_ref(),
3198 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3199 ));
3200 }
3201
3202 #[test]
3203 fn resolve_conditional_list_subject_list_string_union_widens() {
3204 let ty = resolve_conditional_branch(
3208 &Atomic::TList {
3209 value: Box::new(Type::mixed()),
3210 },
3211 &Type::from_vec(vec![
3212 Atomic::TList {
3213 value: Box::new(Type::mixed()),
3214 },
3215 Atomic::TString,
3216 ]),
3217 &Type::single(Atomic::TInt),
3218 &Type::single(Atomic::TString),
3219 );
3220 assert!(ty.is_none());
3221 }
3222
3223 #[test]
3224 fn resolve_conditional_numeric_subject_widens() {
3225 let ty = resolve_conditional_branch(
3229 &Atomic::TNumeric,
3230 &Type::single(Atomic::TLiteralString("123".into())),
3231 &Type::single(Atomic::TInt),
3232 &Type::single(Atomic::TString),
3233 );
3234 assert!(ty.is_none());
3235 }
3236
3237 #[test]
3238 fn resolve_conditional_non_empty_string_subject_widens() {
3239 let ty = resolve_conditional_branch(
3242 &Atomic::TNonEmptyString,
3243 &Type::single(Atomic::TString),
3244 &Type::single(Atomic::TInt),
3245 &Type::single(Atomic::TString),
3246 );
3247 assert!(ty.is_none());
3248 }
3249
3250 #[test]
3251 fn resolve_conditional_template_arg_widens() {
3252 let ty = resolve_conditional_branch(
3255 &Atomic::TString,
3256 &t_param("T"),
3257 &Type::single(Atomic::TInt),
3258 &Type::single(Atomic::TString),
3259 );
3260 assert!(ty.is_none());
3261 }
3262
3263 #[test]
3264 fn resolve_conditional_mixed_subject_bool_arg_then_branch() {
3265 let ty = resolve_conditional_branch(
3268 &Atomic::TMixed,
3269 &Type::single(Atomic::TBool),
3270 &Type::single(Atomic::TInt),
3271 &Type::single(Atomic::TString),
3272 );
3273 assert!(matches!(
3274 ty.as_ref(),
3275 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3276 ));
3277 }
3278
3279 #[test]
3280 fn resolve_conditional_scalar_subject_null_arg_false_branch() {
3281 let ty = resolve_conditional_branch(
3284 &Atomic::TScalar,
3285 &Type::single(Atomic::TNull),
3286 &Type::single(Atomic::TInt),
3287 &Type::single(Atomic::TString),
3288 );
3289 assert!(matches!(
3290 ty.as_ref(),
3291 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3292 ));
3293 }
3294
3295 #[test]
3296 fn resolve_conditional_object_subject_named_arg_then_branch() {
3297 let ty = resolve_conditional_branch(
3299 &Atomic::TObject,
3300 &Type::single(Atomic::TNamedObject {
3301 fqcn: Name::new("Foo"),
3302 type_params: empty_type_params(),
3303 }),
3304 &Type::single(Atomic::TInt),
3305 &Type::single(Atomic::TString),
3306 );
3307 assert!(matches!(
3308 ty.as_ref(),
3309 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3310 ));
3311 }
3312
3313 #[test]
3314 fn resolve_conditional_named_subject_other_class_widens() {
3315 let ty = resolve_conditional_branch(
3319 &Atomic::TNamedObject {
3320 fqcn: Name::new("Foo"),
3321 type_params: empty_type_params(),
3322 },
3323 &Type::single(Atomic::TNamedObject {
3324 fqcn: Name::new("Bar"),
3325 type_params: empty_type_params(),
3326 }),
3327 &Type::single(Atomic::TInt),
3328 &Type::single(Atomic::TString),
3329 );
3330 assert!(ty.is_none());
3331 }
3332
3333 #[test]
3334 fn resolve_conditional_enum_case_subject_widens() {
3335 let ty = resolve_conditional_branch(
3338 &Atomic::TLiteralEnumCase {
3339 enum_fqcn: Name::new("RoundingMode"),
3340 case_name: Name::new("Unnecessary"),
3341 },
3342 &Type::single(Atomic::TInt),
3343 &Type::single(Atomic::TInt),
3344 &Type::single(Atomic::TString),
3345 );
3346 assert!(ty.is_none());
3347 }
3348
3349 #[test]
3350 fn resolve_conditional_null_subject_bool_arg_false_branch() {
3351 let ty = resolve_conditional_branch(
3353 &Atomic::TNull,
3354 &Type::single(Atomic::TBool),
3355 &Type::single(Atomic::TInt),
3356 &Type::single(Atomic::TString),
3357 );
3358 assert!(matches!(
3359 ty.as_ref(),
3360 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3361 ));
3362 }
3363
3364 #[test]
3365 fn resolve_conditional_bool_subject_true_arg_then_branch() {
3366 let ty = resolve_conditional_branch(
3369 &Atomic::TBool,
3370 &Type::single(Atomic::TTrue),
3371 &Type::single(Atomic::TInt),
3372 &Type::single(Atomic::TString),
3373 );
3374 assert!(matches!(
3375 ty.as_ref(),
3376 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3377 ));
3378 }
3379
3380 #[test]
3381 fn substitute_intersection_parts() {
3382 let ty = Type::single(Atomic::TIntersection {
3383 parts: vec_to_type_params(vec![
3384 Type::single(Atomic::TNamedObject {
3385 fqcn: Name::new("Countable"),
3386 type_params: empty_type_params(),
3387 }),
3388 t_param("T"),
3389 ]),
3390 });
3391 let result = ty.substitute_templates(&bindings_t_string());
3392 let Atomic::TIntersection { parts } = &result.types[0] else {
3393 panic!("expected TIntersection");
3394 };
3395 assert_eq!(parts.len(), 2);
3396 assert!(matches!(parts[0].types[0], Atomic::TNamedObject { .. }));
3397 assert!(matches!(parts[1].types[0], Atomic::TString));
3398 }
3399
3400 #[test]
3401 fn substitute_no_template_params_identity() {
3402 let ty = Type::single(Atomic::TInt);
3403 let result = ty.substitute_templates(&bindings_t_string());
3404 assert!(matches!(result.types[0], Atomic::TInt));
3405 }
3406}