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}
63
64impl Type {
65 pub fn empty() -> Self {
68 Self {
69 types: SmallVec::new(),
70 possibly_undefined: false,
71 from_docblock: false,
72 falsy_stripped: false,
73 }
74 }
75
76 pub fn single(atomic: Atomic) -> Self {
77 let mut types = SmallVec::new();
78 types.push(atomic);
79 Self {
80 types,
81 possibly_undefined: false,
82 from_docblock: false,
83 falsy_stripped: false,
84 }
85 }
86
87 pub fn mixed() -> Self {
88 Self::single(Atomic::TMixed)
89 }
90
91 pub fn void() -> Self {
92 Self::single(Atomic::TVoid)
93 }
94
95 pub fn never() -> Self {
96 Self::single(Atomic::TNever)
97 }
98
99 pub fn null() -> Self {
100 Self::single(Atomic::TNull)
101 }
102
103 pub fn bool() -> Self {
104 Self::single(Atomic::TBool)
105 }
106
107 pub fn int() -> Self {
108 Self::single(Atomic::TInt)
109 }
110
111 pub fn float() -> Self {
112 Self::single(Atomic::TFloat)
113 }
114
115 pub fn string() -> Self {
116 Self::single(Atomic::TString)
117 }
118
119 pub fn array_key() -> Self {
122 let mut u = Self::single(Atomic::TInt);
123 u.add_type(Atomic::TString);
124 u
125 }
126
127 pub fn nullable(atomic: Atomic) -> Self {
129 if matches!(atomic, Atomic::TMixed) {
131 return Self::mixed();
132 }
133 let mut types = SmallVec::new();
134 types.push(atomic);
135 types.push(Atomic::TNull);
136 Self {
137 types,
138 possibly_undefined: false,
139 from_docblock: false,
140 falsy_stripped: false,
141 }
142 }
143
144 pub fn from_vec(atomics: Vec<Atomic>) -> Self {
146 let mut u = Self::empty();
147 for a in atomics {
148 u.add_type(a);
149 }
150 u
151 }
152
153 pub fn is_empty(&self) -> bool {
156 self.types.is_empty()
157 }
158
159 pub fn is_single(&self) -> bool {
160 self.types.len() == 1
161 }
162
163 pub fn is_nullable(&self) -> bool {
164 self.types.iter().any(|t| matches!(t, Atomic::TNull))
165 }
166
167 pub fn is_array_key(&self) -> bool {
172 self.types.len() == 2
173 && self.types.iter().any(|t| matches!(t, Atomic::TInt))
174 && self.types.iter().any(|t| matches!(t, Atomic::TString))
175 }
176
177 pub fn is_mixed(&self) -> bool {
178 self.types.iter().any(|t| match t {
179 Atomic::TMixed => true,
180 Atomic::TTemplateParam { as_type, .. } => as_type.is_mixed(),
181 _ => false,
182 })
183 }
184
185 pub fn is_mixed_not_template(&self) -> bool {
190 self.is_mixed()
191 && !self
192 .types
193 .iter()
194 .any(|t| matches!(t, Atomic::TTemplateParam { .. }))
195 }
196
197 pub fn is_never(&self) -> bool {
198 self.types.iter().all(|t| matches!(t, Atomic::TNever)) && !self.types.is_empty()
199 }
200
201 pub fn clone_validity(&self) -> CloneValidity {
204 if self.types.is_empty() {
205 return CloneValidity::Unknown;
206 }
207 let mut has_non_object = false;
208 let mut has_other = false; for t in &self.types {
210 match t {
211 Atomic::TTemplateParam { as_type, .. } => match as_type.clone_validity() {
212 CloneValidity::Invalid => has_non_object = true,
213 CloneValidity::PossiblyInvalid => {
214 has_non_object = true;
215 has_other = true;
216 }
217 CloneValidity::Cloneable | CloneValidity::Unknown => has_other = true,
218 },
219 other if other.is_definitely_non_object() => has_non_object = true,
220 _ => has_other = true,
221 }
222 }
223 match (has_non_object, has_other) {
224 (true, false) => CloneValidity::Invalid,
225 (true, true) => CloneValidity::PossiblyInvalid,
226 _ => CloneValidity::Cloneable,
227 }
228 }
229
230 pub fn is_void(&self) -> bool {
231 self.is_single() && matches!(self.types[0], Atomic::TVoid)
232 }
233
234 pub fn can_be_falsy(&self) -> bool {
235 self.types.iter().any(|t| t.can_be_falsy())
236 }
237
238 pub fn can_be_truthy(&self) -> bool {
239 self.types.iter().any(|t| t.can_be_truthy())
240 }
241
242 pub fn contains<F: Fn(&Atomic) -> bool>(&self, f: F) -> bool {
243 self.types.iter().any(f)
244 }
245
246 pub fn has_named_object(&self, fqcn: &str) -> bool {
247 self.types.iter().any(|t| match t {
248 Atomic::TNamedObject { fqcn: f, .. } => f.as_ref() == fqcn,
249 _ => false,
250 })
251 }
252
253 pub fn add_type(&mut self, atomic: Atomic) {
258 if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
260 return;
261 }
262
263 if matches!(atomic, Atomic::TMixed) {
265 self.types.clear();
266 self.types.push(Atomic::TMixed);
267 return;
268 }
269
270 let atomic = if let Atomic::TConditional { data } = &atomic {
273 let (if_true, if_false) = (&data.if_true, &data.if_false);
274 let mut simplified_true = Type::empty();
275 for t in &if_true.types {
276 simplified_true.add_type(t.clone());
277 }
278 let mut simplified_false = Type::empty();
279 for t in &if_false.types {
280 simplified_false.add_type(t.clone());
281 }
282 if simplified_true == simplified_false {
283 for t in simplified_true.types {
284 self.add_type(t);
285 }
286 return;
287 }
288 atomic
289 } else {
290 atomic
291 };
292
293 if self.types.contains(&atomic) {
295 return;
296 }
297
298 if let Atomic::TLiteralInt(_) = &atomic {
300 if self.types.iter().any(|t| matches!(t, Atomic::TInt)) {
301 return;
302 }
303 }
304 if let Atomic::TLiteralString(_) = &atomic {
306 if self.types.iter().any(|t| matches!(t, Atomic::TString)) {
307 return;
308 }
309 }
310 if matches!(atomic, Atomic::TTrue | Atomic::TFalse)
312 && self.types.iter().any(|t| matches!(t, Atomic::TBool))
313 {
314 return;
315 }
316 if matches!(atomic, Atomic::TTrue) && self.types.iter().any(|t| matches!(t, Atomic::TFalse))
319 {
320 self.types.retain(|t| !matches!(t, Atomic::TFalse));
321 self.types.push(Atomic::TBool);
322 return;
323 }
324 if matches!(atomic, Atomic::TFalse) && self.types.iter().any(|t| matches!(t, Atomic::TTrue))
325 {
326 self.types.retain(|t| !matches!(t, Atomic::TTrue));
327 self.types.push(Atomic::TBool);
328 return;
329 }
330 if matches!(atomic, Atomic::TInt) {
332 self.types.retain(|t| !matches!(t, Atomic::TLiteralInt(_)));
333 }
334 if matches!(atomic, Atomic::TString) {
336 self.types
337 .retain(|t| !matches!(t, Atomic::TLiteralString(_)));
338 }
339 if matches!(atomic, Atomic::TBool) {
341 self.types
342 .retain(|t| !matches!(t, Atomic::TTrue | Atomic::TFalse));
343 }
344
345 if matches!(atomic, Atomic::TNever) {
347 if !self.types.is_empty() {
348 return;
349 }
350 } else {
351 self.types.retain(|t| !matches!(t, Atomic::TNever));
352 }
353
354 if let Atomic::TKeyedArray {
360 properties,
361 is_open,
362 ..
363 } = &atomic
364 {
365 if properties.is_empty() && !is_open {
366 for existing in &self.types {
367 match existing {
368 Atomic::TArray { .. }
369 | Atomic::TNonEmptyArray { .. }
370 | Atomic::TList { .. }
371 | Atomic::TNonEmptyList { .. } => {
372 return; }
374 _ => {}
375 }
376 }
377 }
378 }
379
380 let is_generic_array_or_list = matches!(
383 &atomic,
384 Atomic::TArray { .. }
385 | Atomic::TNonEmptyArray { .. }
386 | Atomic::TList { .. }
387 | Atomic::TNonEmptyList { .. }
388 );
389 if is_generic_array_or_list {
390 self.types.retain(|t| {
391 if let Atomic::TKeyedArray {
392 properties,
393 is_open,
394 ..
395 } = t
396 {
397 !properties.is_empty() || *is_open
398 } else {
399 true
400 }
401 });
402 }
403
404 self.types.push(atomic);
405 }
406
407 pub fn remove_null(&self) -> Type {
411 self.filter(|t| !matches!(t, Atomic::TNull))
412 }
413
414 pub fn remove_false(&self) -> Type {
417 let mut result = self.filter(|t| !matches!(t, Atomic::TFalse | Atomic::TBool));
418 if self.types.iter().any(|t| matches!(t, Atomic::TBool)) {
419 result.add_type(Atomic::TTrue);
420 }
421 result
422 }
423
424 pub fn remove_true(&self) -> Type {
427 let mut result = self.filter(|t| !matches!(t, Atomic::TTrue | Atomic::TBool));
428 if self.types.iter().any(|t| matches!(t, Atomic::TBool)) {
429 result.add_type(Atomic::TFalse);
430 }
431 result
432 }
433
434 pub fn core_type(&self) -> Type {
436 self.remove_null().remove_false()
437 }
438
439 pub fn narrow_to_truthy(&self) -> Type {
441 if self.is_mixed_not_template() {
442 return Type::mixed();
443 }
444 let mut result = Type::empty();
445 result.from_docblock = self.from_docblock;
446 for t in &self.types {
447 match t {
448 Atomic::TTemplateParam { .. } => result.add_type(t.clone()),
452 Atomic::TLiteralInt(0)
454 | Atomic::TLiteralFloat(0, 0)
455 | Atomic::TNull
456 | Atomic::TFalse => {}
457 Atomic::TLiteralString(s) if s.as_ref() == "" || s.as_ref() == "0" => {}
458 Atomic::TBool => result.add_type(Atomic::TTrue),
460 Atomic::TArray { key, value } => result.add_type(Atomic::TNonEmptyArray {
462 key: key.clone(),
463 value: value.clone(),
464 }),
465 Atomic::TList { value } => result.add_type(Atomic::TNonEmptyList {
466 value: value.clone(),
467 }),
468 Atomic::TString => result.add_type(Atomic::TNonEmptyString),
472 Atomic::TNonNegativeInt => result.add_type(Atomic::TPositiveInt),
477 Atomic::TIntRange { min: Some(0), max } if max.is_none_or(|m| m >= 1) => {
478 let atom = if max.is_none() {
479 Atomic::TPositiveInt
480 } else {
481 Atomic::TIntRange {
482 min: Some(1),
483 max: *max,
484 }
485 };
486 result.add_type(atom);
487 }
488 Atomic::TIntRange { min, max: Some(0) } => {
490 let atom = match min {
491 None => Atomic::TNegativeInt,
492 Some(n) if *n <= -1 => Atomic::TIntRange {
493 min: *min,
494 max: Some(-1),
495 },
496 _ => continue, };
498 result.add_type(atom);
499 }
500 t if !t.can_be_truthy() => {}
502 _ => result.add_type(t.clone()),
503 }
504 }
505 result
506 }
507
508 pub fn narrow_to_falsy(&self) -> Type {
510 if self.is_mixed_not_template() {
511 return Type::from_vec(vec![
512 Atomic::TNull,
513 Atomic::TFalse,
514 Atomic::TLiteralInt(0),
515 Atomic::TLiteralString("".into()),
516 ]);
517 }
518 let mut result = Type::empty();
519 result.from_docblock = self.from_docblock;
520 for t in &self.types {
521 match t {
522 Atomic::TTemplateParam { .. } => result.add_type(t.clone()),
527 Atomic::TBool => result.add_type(Atomic::TFalse),
529 Atomic::TInt => result.add_type(Atomic::TLiteralInt(0)),
531 Atomic::TFloat => result.add_type(Atomic::TLiteralFloat(0, 0)),
533 Atomic::TString => {
535 result.add_type(Atomic::TLiteralString("".into()));
536 result.add_type(Atomic::TLiteralString("0".into()));
537 }
538 Atomic::TNumericString => result.add_type(Atomic::TLiteralString("0".into())),
540 Atomic::TNonNegativeInt => result.add_type(Atomic::TLiteralInt(0)),
542 Atomic::TIntRange {
544 min: Some(0),
545 max: Some(_) | None,
546 } => result.add_type(Atomic::TLiteralInt(0)),
547 Atomic::TIntRange { max: Some(0), .. } => result.add_type(Atomic::TLiteralInt(0)),
549 t if !t.can_be_falsy() => {} _ => result.add_type(t.clone()),
551 }
552 }
553 result
554 }
555
556 pub fn narrow_instanceof(&self, class: &str) -> Type {
562 let narrowed_ty = Atomic::TNamedObject {
563 fqcn: class.into(),
564 type_params: empty_type_params(),
565 };
566 let has_object = self.types.iter().any(|t| {
568 matches!(
569 t,
570 Atomic::TObject | Atomic::TNamedObject { .. } | Atomic::TMixed | Atomic::TNull )
572 });
573 if has_object || self.is_empty() {
574 Type::single(narrowed_ty)
575 } else {
576 Type::single(narrowed_ty)
579 }
580 }
581
582 pub fn narrow_to_string(&self) -> Type {
586 self.filter_replacing(
587 |t| t.is_string() || matches!(t, Atomic::TTemplateParam { .. }),
588 |t| matches!(t, Atomic::TMixed | Atomic::TScalar),
589 Atomic::TString,
590 )
591 }
592
593 pub fn narrow_to_int(&self) -> Type {
595 self.filter_replacing(
596 |t| t.is_int() || matches!(t, Atomic::TTemplateParam { .. }),
597 |t| matches!(t, Atomic::TMixed | Atomic::TScalar | Atomic::TNumeric),
598 Atomic::TInt,
599 )
600 }
601
602 pub fn narrow_to_float(&self) -> Type {
604 self.filter_replacing(
605 |t| {
606 matches!(
607 t,
608 Atomic::TFloat
609 | Atomic::TIntegralFloat
610 | Atomic::TLiteralFloat(..)
611 | Atomic::TTemplateParam { .. }
612 )
613 },
614 |t| matches!(t, Atomic::TMixed | Atomic::TScalar | Atomic::TNumeric),
615 Atomic::TFloat,
616 )
617 }
618
619 pub fn narrow_to_bool(&self) -> Type {
621 self.filter_replacing(
622 |t| {
623 matches!(
624 t,
625 Atomic::TBool | Atomic::TTrue | Atomic::TFalse | Atomic::TTemplateParam { .. }
626 )
627 },
628 |t| matches!(t, Atomic::TMixed | Atomic::TScalar),
629 Atomic::TBool,
630 )
631 }
632
633 pub fn narrow_to_null(&self) -> Type {
635 self.filter_replacing(
636 |t| matches!(t, Atomic::TNull | Atomic::TTemplateParam { .. }),
637 |t| matches!(t, Atomic::TMixed),
638 Atomic::TNull,
639 )
640 }
641
642 pub fn narrow_to_array(&self) -> Type {
644 self.filter_replacing(
645 |t| t.is_array() || matches!(t, Atomic::TTemplateParam { .. }),
646 |t| matches!(t, Atomic::TMixed),
647 Atomic::TArray {
648 key: Box::new(Type::mixed()),
649 value: Box::new(Type::mixed()),
650 },
651 )
652 }
653
654 pub fn narrow_to_non_empty_collection(&self) -> Type {
656 let mut out = Type::empty();
657 out.from_docblock = self.from_docblock;
658 for t in &self.types {
659 match t {
660 Atomic::TArray { key, value } => out.add_type(Atomic::TNonEmptyArray {
661 key: key.clone(),
662 value: value.clone(),
663 }),
664 Atomic::TList { value } => out.add_type(Atomic::TNonEmptyList {
665 value: value.clone(),
666 }),
667 _ => out.add_type(t.clone()),
668 }
669 }
670 out
671 }
672
673 pub fn narrow_to_empty_collection(&self) -> Type {
683 let mut out = Type::empty();
684 out.from_docblock = self.from_docblock;
685 for t in &self.types {
686 match t {
687 Atomic::TNonEmptyArray { .. } | Atomic::TNonEmptyList { .. } => {}
688 Atomic::TArray { .. } | Atomic::TList { .. } => {
689 out.add_type(Atomic::TKeyedArray {
690 properties: Box::default(),
691 is_open: false,
692 is_list: true,
693 });
694 }
695 _ => out.add_type(t.clone()),
696 }
697 }
698 out
699 }
700
701 pub fn narrow_to_list(&self) -> Type {
713 let mut out = Type::empty();
714 out.from_docblock = self.from_docblock;
715 for t in &self.types {
716 match t {
717 Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => out.add_type(t.clone()),
718 Atomic::TArray { key, value } if !key.narrow_to_int().is_empty() => {
724 out.add_type(Atomic::TList {
725 value: value.clone(),
726 });
727 }
728 Atomic::TNonEmptyArray { key, value } if !key.narrow_to_int().is_empty() => {
729 out.add_type(Atomic::TNonEmptyList {
730 value: value.clone(),
731 });
732 }
733 Atomic::TKeyedArray { is_list: true, .. } => out.add_type(t.clone()),
734 Atomic::TMixed => out.add_type(Atomic::TList {
735 value: Box::new(Type::mixed()),
736 }),
737 _ => {}
738 }
739 }
740 if out.is_empty() {
741 self.filter(|t| matches!(t, Atomic::TList { .. } | Atomic::TNonEmptyList { .. }))
742 } else {
743 out
744 }
745 }
746
747 pub fn narrow_to_object(&self) -> Type {
752 let mut out = Type::empty();
753 for t in &self.types {
754 if matches!(t, Atomic::TMixed) {
755 out.add_type(Atomic::TObject);
756 } else if t.is_object() || matches!(t, Atomic::TTemplateParam { .. }) {
757 out.add_type(t.clone());
758 }
759 }
760 if out.types.is_empty() {
761 self.filter(|t| t.is_object())
762 } else {
763 out
764 }
765 }
766
767 pub fn narrow_to_callable(&self) -> Type {
774 let narrowed = self.filter(|t| {
775 t.is_callable()
776 || t.is_string()
777 || t.is_array()
778 || t.is_object()
779 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
780 });
781 let mut result = Type::empty();
788 result.possibly_undefined = narrowed.possibly_undefined;
789 result.from_docblock = narrowed.from_docblock;
790 for atomic in narrowed.types {
791 if matches!(atomic, Atomic::TObject) {
792 result.add_type(Atomic::TCallable {
793 params: None,
794 return_type: None,
795 });
796 } else {
797 result.add_type(atomic);
798 }
799 }
800 result
801 }
802
803 pub fn narrow_to_scalar(&self) -> Type {
805 self.filter_replacing(
806 |t| {
807 t.is_string()
808 || t.is_int()
809 || matches!(
810 t,
811 Atomic::TFloat
812 | Atomic::TIntegralFloat
813 | Atomic::TLiteralFloat(..)
814 | Atomic::TBool
815 | Atomic::TTrue
816 | Atomic::TFalse
817 | Atomic::TScalar
818 | Atomic::TNumeric
819 | Atomic::TNumericString
820 | Atomic::TTemplateParam { .. }
821 )
822 },
823 |t| matches!(t, Atomic::TMixed),
824 Atomic::TScalar,
825 )
826 }
827
828 pub fn narrow_to_iterable(&self) -> Type {
831 self.filter(|t| {
832 t.is_array()
833 || t.is_object()
834 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
835 })
836 }
837
838 pub fn narrow_to_countable(&self) -> Type {
841 self.filter(|t| {
842 t.is_array()
843 || t.is_object()
844 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
845 })
846 }
847
848 pub fn narrow_to_resource(&self) -> Type {
852 self.filter(|t| matches!(t, Atomic::TMixed))
854 }
855
856 pub fn narrow_to_class_string(&self) -> Type {
861 let mut out = Type::empty();
862 out.from_docblock = self.from_docblock;
863 for t in &self.types {
864 match t {
865 Atomic::TClassString(_) => out.add_type(t.clone()),
866 _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
867 out.add_type(Atomic::TClassString(None));
868 }
869 _ => {}
870 }
871 }
872 out
873 }
874
875 pub fn narrow_to_interface_string(&self) -> Type {
880 let mut out = Type::empty();
881 out.from_docblock = self.from_docblock;
882 for t in &self.types {
883 match t {
884 Atomic::TInterfaceString(_) => out.add_type(t.clone()),
885 Atomic::TClassString(name) => {
889 out.add_type(Atomic::TInterfaceString(*name));
890 }
891 _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
892 out.add_type(Atomic::TInterfaceString(None));
893 }
894 _ => {}
895 }
896 }
897 out
898 }
899
900 pub fn merge(a: &Type, b: &Type) -> Type {
905 if b.types.is_empty() {
907 let mut result = a.clone();
908 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
909 return result;
910 }
911 if a.types.is_empty() {
913 let mut result = b.clone();
914 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
915 return result;
916 }
917 if a.types.len() == 1 && matches!(a.types[0], Atomic::TMixed) {
919 let mut result = a.clone();
920 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
921 return result;
922 }
923 if b.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
925 return Type {
926 types: smallvec::smallvec![Atomic::TMixed],
927 possibly_undefined: a.possibly_undefined || b.possibly_undefined,
928 from_docblock: a.from_docblock || b.from_docblock,
929 falsy_stripped: false,
930 };
931 }
932 let mut result = a.clone();
933 result.merge_with(b);
934 result
935 }
936
937 pub fn merge_with(&mut self, other: &Type) {
939 if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
940 self.possibly_undefined |= other.possibly_undefined;
941 return;
942 }
943 if other.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
944 self.types.clear();
945 self.types.push(Atomic::TMixed);
946 self.possibly_undefined |= other.possibly_undefined;
947 return;
948 }
949 for atomic in &other.types {
950 self.add_type(atomic.clone());
951 }
952 self.possibly_undefined |= other.possibly_undefined;
953 }
954
955 pub fn intersect_with(&self, other: &Type) -> Type {
959 if self.is_mixed() {
960 return other.clone();
961 }
962 if other.is_mixed() {
963 return self.clone();
964 }
965 let mut result = Type::empty();
973 for a in &self.types {
974 for b in &other.types {
975 if a == b {
976 result.add_type(a.clone());
977 } else if atomic_subtype(b, a) {
978 result.add_type(b.clone());
979 } else if atomic_subtype(a, b) {
980 result.add_type(a.clone());
981 }
982 }
983 }
984 if result.is_empty() {
985 Type::never()
986 } else {
987 result
988 }
989 }
990
991 pub fn substitute_templates(&self, bindings: &FxHashMap<Name, Type>) -> Type {
995 if bindings.is_empty() {
996 return self.clone();
997 }
998 if !self.types.iter().any(atomic_may_contain_templates) {
1001 return self.clone();
1002 }
1003 let mut result = Type::empty();
1004 result.possibly_undefined = self.possibly_undefined;
1005 result.from_docblock = self.from_docblock;
1006 for atomic in &self.types {
1007 match atomic {
1008 Atomic::TTemplateParam { name, .. } => {
1009 if let Some(resolved) = bindings.get(name) {
1010 for t in &resolved.types {
1011 result.add_type(t.clone());
1012 }
1013 } else {
1014 result.add_type(atomic.clone());
1015 }
1016 }
1017 Atomic::TArray { key, value } => {
1018 result.add_type(Atomic::TArray {
1019 key: Box::new(key.substitute_templates(bindings)),
1020 value: Box::new(value.substitute_templates(bindings)),
1021 });
1022 }
1023 Atomic::TList { value } => {
1024 result.add_type(Atomic::TList {
1025 value: Box::new(value.substitute_templates(bindings)),
1026 });
1027 }
1028 Atomic::TNonEmptyArray { key, value } => {
1029 result.add_type(Atomic::TNonEmptyArray {
1030 key: Box::new(key.substitute_templates(bindings)),
1031 value: Box::new(value.substitute_templates(bindings)),
1032 });
1033 }
1034 Atomic::TNonEmptyList { value } => {
1035 result.add_type(Atomic::TNonEmptyList {
1036 value: Box::new(value.substitute_templates(bindings)),
1037 });
1038 }
1039 Atomic::TKeyedArray {
1040 properties,
1041 is_open,
1042 is_list,
1043 } => {
1044 use crate::atomic::KeyedProperty;
1045 let new_props = properties
1046 .iter()
1047 .map(|(k, prop)| {
1048 (
1049 k.clone(),
1050 KeyedProperty {
1051 ty: prop.ty.substitute_templates(bindings),
1052 optional: prop.optional,
1053 },
1054 )
1055 })
1056 .collect();
1057 result.add_type(Atomic::TKeyedArray {
1058 properties: Box::new(new_props),
1059 is_open: *is_open,
1060 is_list: *is_list,
1061 });
1062 }
1063 Atomic::TCallable {
1064 params,
1065 return_type,
1066 } => {
1067 result.add_type(Atomic::TCallable {
1068 params: params.as_ref().map(|ps| {
1069 ps.iter()
1070 .map(|p| substitute_in_fn_param(p, bindings))
1071 .collect()
1072 }),
1073 return_type: return_type
1074 .as_ref()
1075 .map(|r| Box::new(r.substitute_templates(bindings))),
1076 });
1077 }
1078 Atomic::TClosure { data } => {
1079 result.add_type(Atomic::TClosure {
1080 data: Box::new(crate::atomic::ClosureData {
1081 params: data
1082 .params
1083 .iter()
1084 .map(|p| substitute_in_fn_param(p, bindings))
1085 .collect(),
1086 return_type: data.return_type.substitute_templates(bindings),
1087 this_type: data
1088 .this_type
1089 .as_ref()
1090 .map(|t| t.substitute_templates(bindings)),
1091 }),
1092 });
1093 }
1094 Atomic::TConditional { data } => {
1095 let param_name = &data.param_name;
1096 let new_subject = data.subject.substitute_templates(bindings);
1097 let new_if_true = data.if_true.substitute_templates(bindings);
1098 let new_if_false = data.if_false.substitute_templates(bindings);
1099
1100 let resolved = if let Some(name) = param_name {
1104 if let Some(bound) = bindings.get(name) {
1105 if new_subject.types.len() == 1 {
1106 resolve_conditional_branch(
1107 &new_subject.types[0],
1108 bound,
1109 &new_if_true,
1110 &new_if_false,
1111 )
1112 } else {
1113 None
1114 }
1115 } else {
1116 None
1117 }
1118 } else {
1119 None
1120 };
1121
1122 if let Some(branch) = resolved {
1123 for t in branch.types {
1124 result.add_type(t);
1125 }
1126 } else {
1127 result.add_type(Atomic::TConditional {
1128 data: Box::new(crate::atomic::ConditionalData {
1129 param_name: *param_name,
1130 subject: new_subject,
1131 if_true: new_if_true,
1132 if_false: new_if_false,
1133 }),
1134 });
1135 }
1136 }
1137 Atomic::TIntersection { parts } => {
1138 result.add_type(Atomic::TIntersection {
1139 parts: vec_to_type_params(
1140 parts
1141 .iter()
1142 .map(|p| p.substitute_templates(bindings))
1143 .collect(),
1144 ),
1145 });
1146 }
1147 Atomic::TNamedObject { fqcn, type_params } => {
1148 if type_params.is_empty() && !fqcn.contains('\\') {
1155 if let Some(resolved) = bindings.get(fqcn) {
1156 for t in &resolved.types {
1157 result.add_type(t.clone());
1158 }
1159 continue;
1160 }
1161 }
1162 let new_params: Vec<Type> = type_params
1163 .iter()
1164 .map(|p| p.substitute_templates(bindings))
1165 .collect();
1166 result.add_type(Atomic::TNamedObject {
1167 fqcn: *fqcn,
1168 type_params: vec_to_type_params(new_params),
1169 });
1170 }
1171 Atomic::TClassString(Some(param_name)) => {
1173 if let Some(resolved) = bindings.get(param_name) {
1174 for r_atomic in &resolved.types {
1175 let cls_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1176 Some(*fqcn)
1177 } else {
1178 None
1179 };
1180 result.add_type(Atomic::TClassString(cls_name));
1181 }
1182 } else {
1183 result.add_type(atomic.clone());
1184 }
1185 }
1186 Atomic::TInterfaceString(Some(param_name)) => {
1188 if let Some(resolved) = bindings.get(param_name) {
1189 for r_atomic in &resolved.types {
1190 let iface_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1191 Some(*fqcn)
1192 } else {
1193 None
1194 };
1195 result.add_type(Atomic::TInterfaceString(iface_name));
1196 }
1197 } else {
1198 result.add_type(atomic.clone());
1199 }
1200 }
1201 _ => {
1202 result.add_type(atomic.clone());
1203 }
1204 }
1205 }
1206 result
1207 }
1208
1209 pub fn resolve_conditional_returns<F>(self, lookup: F) -> Type
1215 where
1216 F: Fn(&str) -> Option<Type>,
1217 {
1218 self.resolve_conditional_inner(&lookup)
1219 }
1220
1221 fn resolve_conditional_inner<F>(self, lookup: &F) -> Type
1222 where
1223 F: Fn(&str) -> Option<Type>,
1224 {
1225 let mut result = Type::empty();
1226 for atomic in self.types {
1227 match atomic {
1228 Atomic::TConditional { ref data } => {
1229 let (param_name, subject, if_true, if_false) = (
1230 &data.param_name,
1231 &data.subject,
1232 &data.if_true,
1233 &data.if_false,
1234 );
1235 let resolved = if subject.types.len() == 1 {
1236 if let Some(name) = param_name {
1237 if let Some(arg_ty) = lookup(name.as_ref()) {
1238 resolve_conditional_branch(
1239 &subject.types[0],
1240 &arg_ty,
1241 if_true,
1242 if_false,
1243 )
1244 } else {
1245 None
1246 }
1247 } else {
1248 None
1249 }
1250 } else {
1251 None
1252 };
1253
1254 if let Some(branch) = resolved {
1255 for t in branch.resolve_conditional_inner(lookup).types {
1257 result.add_type(t);
1258 }
1259 } else {
1260 for t in if_true.clone().resolve_conditional_inner(lookup).types {
1263 result.add_type(t);
1264 }
1265 for t in if_false.clone().resolve_conditional_inner(lookup).types {
1266 result.add_type(t);
1267 }
1268 }
1269 }
1270 other => result.add_type(other),
1271 }
1272 }
1273 result
1274 }
1275
1276 pub fn is_subtype_structural(&self, other: &Type) -> bool {
1286 if other.is_mixed() {
1287 return true;
1288 }
1289 if self.is_never() {
1290 return true; }
1292 self.types
1293 .iter()
1294 .all(|a| other.types.iter().any(|b| atomic_subtype(a, b)))
1295 }
1296
1297 pub fn accepts_atomic_structural(&self, sub: &Atomic) -> bool {
1301 if self.is_mixed() {
1302 return true;
1303 }
1304 matches!(sub, Atomic::TNever) || self.types.iter().any(|b| atomic_subtype(sub, b))
1305 }
1306
1307 fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Type {
1310 let mut result = Type::empty();
1311 result.possibly_undefined = self.possibly_undefined;
1312 result.from_docblock = self.from_docblock;
1313 for atomic in &self.types {
1314 if f(atomic) {
1315 result.types.push(atomic.clone());
1316 }
1317 }
1318 result
1319 }
1320
1321 fn filter_replacing<K: Fn(&Atomic) -> bool, P: Fn(&Atomic) -> bool>(
1326 &self,
1327 keep: K,
1328 placeholder: P,
1329 replacement: Atomic,
1330 ) -> Type {
1331 let mut result = Type::empty();
1332 result.possibly_undefined = self.possibly_undefined;
1333 result.from_docblock = self.from_docblock;
1334 for atomic in &self.types {
1335 if keep(atomic) {
1336 result.add_type(atomic.clone());
1337 } else if placeholder(atomic) {
1338 result.add_type(replacement.clone());
1339 }
1340 }
1341 result
1342 }
1343
1344 pub fn possibly_undefined(mut self) -> Self {
1346 self.possibly_undefined = true;
1347 self
1348 }
1349
1350 pub fn from_docblock(mut self) -> Self {
1352 self.from_docblock = true;
1353 self
1354 }
1355
1356 pub fn falsy_stripped(mut self) -> Self {
1359 self.falsy_stripped = true;
1360 self
1361 }
1362}
1363
1364fn is_string_atomic(a: &Atomic) -> bool {
1369 matches!(
1370 a,
1371 Atomic::TString
1372 | Atomic::TNonEmptyString
1373 | Atomic::TLiteralString(_)
1374 | Atomic::TNumericString
1375 | Atomic::TClassString(_)
1376 | Atomic::TInterfaceString(_)
1377 | Atomic::TCallableString
1378 )
1379}
1380
1381fn is_array_atomic(a: &Atomic) -> bool {
1382 matches!(
1383 a,
1384 Atomic::TArray { .. }
1385 | Atomic::TNonEmptyArray { .. }
1386 | Atomic::TKeyedArray { .. }
1387 | Atomic::TList { .. }
1388 | Atomic::TNonEmptyList { .. }
1389 )
1390}
1391
1392fn is_list_atomic(a: &Atomic) -> bool {
1393 match a {
1394 Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => true,
1395 Atomic::TKeyedArray { is_list, .. } => *is_list,
1396 _ => false,
1397 }
1398}
1399
1400fn is_float_atomic(a: &Atomic) -> bool {
1401 matches!(
1402 a,
1403 Atomic::TFloat | Atomic::TIntegralFloat | Atomic::TLiteralFloat(..)
1404 )
1405}
1406
1407fn is_bool_atomic(a: &Atomic) -> bool {
1408 matches!(a, Atomic::TBool | Atomic::TTrue | Atomic::TFalse)
1409}
1410
1411fn resolve_conditional_branch(
1417 subject: &Atomic,
1418 arg_ty: &Type,
1419 if_true: &Type,
1420 if_false: &Type,
1421) -> Option<Type> {
1422 let predicate: fn(&Atomic) -> bool = match subject {
1423 Atomic::TNull => |a| matches!(a, Atomic::TNull),
1424 Atomic::TTrue => |a| matches!(a, Atomic::TTrue),
1425 Atomic::TFalse => |a| matches!(a, Atomic::TFalse),
1426 Atomic::TString => is_string_atomic,
1427 Atomic::TList { .. } => is_list_atomic,
1428 Atomic::TArray { .. } => is_array_atomic,
1429 Atomic::TInt => Atomic::is_int,
1430 Atomic::TFloat => is_float_atomic,
1431 Atomic::TBool => is_bool_atomic,
1432 _ => return None,
1433 };
1434
1435 if arg_ty.types.is_empty() {
1436 return None;
1437 }
1438 let all_match = arg_ty.types.iter().all(&predicate);
1439 let none_match = !arg_ty.types.iter().any(predicate);
1440 if all_match {
1441 Some(if_true.clone())
1442 } else if none_match {
1443 Some(if_false.clone())
1444 } else {
1445 None
1446 }
1447}
1448
1449fn atomic_may_contain_templates(atomic: &Atomic) -> bool {
1457 match atomic {
1458 Atomic::TNamedObject { fqcn, type_params } => {
1462 !type_params.is_empty() || !fqcn.contains('\\')
1463 }
1464 Atomic::TTemplateParam { .. }
1465 | Atomic::TArray { .. }
1466 | Atomic::TList { .. }
1467 | Atomic::TNonEmptyArray { .. }
1468 | Atomic::TNonEmptyList { .. }
1469 | Atomic::TKeyedArray { .. }
1470 | Atomic::TCallable { .. }
1471 | Atomic::TClosure { .. }
1472 | Atomic::TConditional { .. }
1473 | Atomic::TIntersection { .. }
1474 | Atomic::TClassString(Some(_))
1475 | Atomic::TInterfaceString(Some(_)) => true,
1476 _ => false,
1477 }
1478}
1479
1480fn substitute_in_fn_param(
1481 p: &crate::atomic::FnParam,
1482 bindings: &FxHashMap<Name, Type>,
1483) -> crate::atomic::FnParam {
1484 crate::atomic::FnParam {
1485 name: p.name,
1486 ty: p.ty.as_ref().map(|t| {
1487 let u = t.to_union();
1488 let substituted = u.substitute_templates(bindings);
1489 crate::compact::SimpleType::from_union(substituted)
1490 }),
1491 out_ty: p.out_ty.as_ref().map(|t| {
1492 let u = t.to_union();
1493 let substituted = u.substitute_templates(bindings);
1494 crate::compact::SimpleType::from_union(substituted)
1495 }),
1496 default: p.default.as_ref().map(|d| {
1497 let u = d.to_union();
1498 let substituted = u.substitute_templates(bindings);
1499 crate::compact::SimpleType::from_union(substituted)
1500 }),
1501 is_variadic: p.is_variadic,
1502 is_byref: p.is_byref,
1503 is_optional: p.is_optional,
1504 }
1505}
1506
1507pub fn atomic_subtype(sub: &Atomic, sup: &Atomic) -> bool {
1513 if sub == sup {
1514 return true;
1515 }
1516 match (sub, sup) {
1517 (Atomic::TNever, _) => true,
1519 (_, Atomic::TMixed) => true,
1521 (Atomic::TMixed, _) => true,
1522 (_, Atomic::TTemplateParam { as_type, .. }) => {
1527 as_type.is_mixed() || as_type.types.iter().any(|b| atomic_subtype(sub, b))
1528 }
1529
1530 (Atomic::TLiteralInt(_), Atomic::TInt) => true,
1532 (Atomic::TLiteralInt(_), Atomic::TNumeric) => true,
1533 (Atomic::TLiteralInt(_), Atomic::TScalar) => true,
1534 (Atomic::TLiteralInt(n), Atomic::TPositiveInt) => *n > 0,
1535 (Atomic::TLiteralInt(n), Atomic::TNonNegativeInt) => *n >= 0,
1536 (Atomic::TLiteralInt(n), Atomic::TNegativeInt) => *n < 0,
1537 (Atomic::TPositiveInt, Atomic::TInt) => true,
1538 (Atomic::TPositiveInt, Atomic::TNonNegativeInt) => true,
1539 (Atomic::TPositiveInt, Atomic::TNumeric) => true,
1540 (Atomic::TPositiveInt, Atomic::TScalar) => true,
1541 (Atomic::TNegativeInt, Atomic::TInt) => true,
1542 (Atomic::TNegativeInt, Atomic::TNumeric) => true,
1543 (Atomic::TNegativeInt, Atomic::TScalar) => true,
1544 (Atomic::TNonNegativeInt, Atomic::TInt) => true,
1545 (Atomic::TNonNegativeInt, Atomic::TNumeric) => true,
1546 (Atomic::TNonNegativeInt, Atomic::TScalar) => true,
1547 (Atomic::TIntRange { .. }, Atomic::TInt) => true,
1548 (Atomic::TIntRange { .. }, Atomic::TNumeric) => true,
1549 (Atomic::TIntRange { .. }, Atomic::TScalar) => true,
1550 (Atomic::TPositiveInt, Atomic::TIntRange { min, max }) => {
1552 max.is_none() && min.is_none_or(|m| m <= 1)
1553 }
1554 (Atomic::TNegativeInt, Atomic::TIntRange { min, max }) => {
1556 min.is_none() && max.is_none_or(|m| m >= -1)
1557 }
1558 (Atomic::TNonNegativeInt, Atomic::TIntRange { min, max }) => {
1560 max.is_none() && min.is_none_or(|m| m <= 0)
1561 }
1562 (Atomic::TIntRange { min: sub_min, .. }, Atomic::TPositiveInt) => {
1564 sub_min.is_some_and(|lo| lo >= 1)
1565 }
1566 (Atomic::TIntRange { min: sub_min, .. }, Atomic::TNonNegativeInt) => {
1567 sub_min.is_some_and(|lo| lo >= 0)
1568 }
1569 (Atomic::TIntRange { max: sub_max, .. }, Atomic::TNegativeInt) => {
1570 sub_max.is_some_and(|hi| hi <= -1)
1571 }
1572 (
1574 Atomic::TIntRange {
1575 min: sub_min,
1576 max: sub_max,
1577 },
1578 Atomic::TIntRange {
1579 min: sup_min,
1580 max: sup_max,
1581 },
1582 ) => {
1583 let lower_ok = match (sub_min, sup_min) {
1584 (_, None) => true,
1585 (None, Some(_)) => false,
1586 (Some(sl), Some(su)) => sl >= su,
1587 };
1588 let upper_ok = match (sub_max, sup_max) {
1589 (None, None) | (Some(_), None) => true,
1590 (None, Some(_)) => false,
1591 (Some(sl), Some(su)) => sl <= su,
1592 };
1593 lower_ok && upper_ok
1594 }
1595
1596 (Atomic::TLiteralFloat(..), Atomic::TFloat) => true,
1597 (Atomic::TLiteralFloat(..), Atomic::TNumeric) => true,
1598 (Atomic::TLiteralFloat(..), Atomic::TScalar) => true,
1599
1600 (Atomic::TLiteralString(s), Atomic::TString) => {
1601 let _ = s;
1602 true
1603 }
1604 (Atomic::TLiteralString(s), Atomic::TCallableString) => {
1605 let _ = s;
1606 true
1607 }
1608 (Atomic::TLiteralString(s), Atomic::TNonEmptyString) => !s.is_empty(),
1609 (Atomic::TLiteralString(s), Atomic::TNumericString) => s.parse::<f64>().is_ok(),
1610 (Atomic::TLiteralString(_), Atomic::TClassString(_)) => true,
1613 (Atomic::TLiteralString(_), Atomic::TInterfaceString(_)) => true,
1616 (Atomic::TLiteralString(_), Atomic::TScalar) => true,
1617 (Atomic::TNonEmptyString, Atomic::TString) => true,
1618 (Atomic::TCallableString, Atomic::TString) => true,
1619 (Atomic::TNumericString, Atomic::TNonEmptyString) => true,
1621 (Atomic::TNumericString, Atomic::TString) => true,
1622 (Atomic::TClassString(_), Atomic::TString) => true,
1623 (Atomic::TInterfaceString(_), Atomic::TString) => true,
1624 (Atomic::TInterfaceString(_), Atomic::TClassString(None)) => true,
1629 (Atomic::TInterfaceString(Some(a)), Atomic::TClassString(Some(b))) => a == b,
1630 (Atomic::TEnumString, Atomic::TString) => true,
1631 (Atomic::TTraitString, Atomic::TString) => true,
1632
1633 (Atomic::TTrue, Atomic::TBool) => true,
1634 (Atomic::TFalse, Atomic::TBool) => true,
1635
1636 (Atomic::TInt, Atomic::TNumeric) => true,
1637 (Atomic::TFloat, Atomic::TNumeric) => true,
1638 (Atomic::TIntegralFloat, Atomic::TNumeric) => true,
1639 (Atomic::TNumericString, Atomic::TNumeric) => true,
1640
1641 (Atomic::TInt, Atomic::TScalar) => true,
1642 (Atomic::TFloat, Atomic::TScalar) => true,
1643 (Atomic::TIntegralFloat, Atomic::TScalar) => true,
1644 (Atomic::TString, Atomic::TScalar) => true,
1645 (Atomic::TBool, Atomic::TScalar) => true,
1646 (Atomic::TNumeric, Atomic::TScalar) => true,
1647 (Atomic::TTrue, Atomic::TScalar) => true,
1648 (Atomic::TFalse, Atomic::TScalar) => true,
1649 (Atomic::TNonEmptyString, Atomic::TScalar) => true,
1653 (Atomic::TNumericString, Atomic::TScalar) => true,
1654 (Atomic::TCallableString, Atomic::TScalar) => true,
1655 (Atomic::TClassString(_), Atomic::TScalar) => true,
1656 (Atomic::TInterfaceString(_), Atomic::TScalar) => true,
1657 (Atomic::TEnumString, Atomic::TScalar) => true,
1658 (Atomic::TTraitString, Atomic::TScalar) => true,
1659
1660 (Atomic::TNamedObject { .. }, Atomic::TObject) => true,
1662 (Atomic::TStaticObject { .. }, Atomic::TObject) => true,
1663 (Atomic::TSelf { .. }, Atomic::TObject) => true,
1664 (Atomic::TSelf { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
1666 (Atomic::TStaticObject { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
1667 (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TSelf { fqcn: b }) => a == b,
1669 (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TStaticObject { fqcn: b }) => a == b,
1670 (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TNamedObject { fqcn, .. }) => {
1673 enum_fqcn == fqcn
1674 }
1675 (
1679 Atomic::TNamedObject {
1680 fqcn: sub_fqcn,
1681 type_params: sub_params,
1682 },
1683 Atomic::TNamedObject {
1684 fqcn: sup_fqcn,
1685 type_params: sup_params,
1686 },
1687 ) => {
1688 sub_fqcn == sup_fqcn
1689 && (sup_params.is_empty() || type_params_compatible(sub_params, sup_params))
1690 }
1691
1692 (Atomic::TIntegralFloat, Atomic::TFloat) => true,
1694
1695 (Atomic::TLiteralInt(_), Atomic::TFloat) => true,
1697 (Atomic::TPositiveInt, Atomic::TFloat) => true,
1698 (Atomic::TNegativeInt, Atomic::TFloat) => true,
1699 (Atomic::TNonNegativeInt, Atomic::TFloat) => true,
1700 (Atomic::TInt, Atomic::TFloat) => true,
1701 (Atomic::TIntRange { .. }, Atomic::TFloat) => true,
1702
1703 (Atomic::TLiteralInt(n), Atomic::TIntRange { min, max }) => {
1705 min.is_none_or(|lo| *n >= lo) && max.is_none_or(|hi| *n <= hi)
1706 }
1707
1708 (Atomic::TString, Atomic::TCallable { .. }) => true,
1710 (Atomic::TNonEmptyString, Atomic::TCallable { .. }) => true,
1711 (Atomic::TLiteralString(_), Atomic::TCallable { .. }) => true,
1712 (Atomic::TArray { .. }, Atomic::TCallable { .. }) => true,
1713 (Atomic::TNonEmptyArray { .. }, Atomic::TCallable { .. }) => true,
1714 (Atomic::TKeyedArray { .. }, Atomic::TCallable { .. }) => true,
1715
1716 (Atomic::TClosure { .. }, Atomic::TCallable { .. }) => true,
1718 (Atomic::TCallable { .. }, Atomic::TClosure { .. }) => true,
1720 (Atomic::TClosure { data: sub }, Atomic::TClosure { data: sup }) => {
1730 fn has_nominal_type(t: &Type) -> bool {
1731 t.types.iter().any(|a| {
1732 matches!(
1733 a,
1734 Atomic::TNamedObject { .. }
1735 | Atomic::TSelf { .. }
1736 | Atomic::TStaticObject { .. }
1737 | Atomic::TTemplateParam { .. }
1738 | Atomic::TClosure { .. }
1739 | Atomic::TCallable { .. }
1740 )
1741 })
1742 }
1743 let sub_required = sub
1744 .params
1745 .iter()
1746 .filter(|p| !p.is_optional && !p.is_variadic)
1747 .count();
1748 if sub_required > sup.params.len() {
1749 false
1750 } else {
1751 let params_ok = sup.params.iter().enumerate().all(|(i, sup_param)| {
1752 let Some(sub_param) = sub.params.get(i) else {
1753 return true;
1754 };
1755 if sub_param.is_optional || sub_param.is_variadic {
1756 return true;
1757 }
1758 let (Some(sub_ty), Some(sup_ty)) =
1759 (sub_param.ty.as_ref(), sup_param.ty.as_ref())
1760 else {
1761 return true;
1762 };
1763 let (sub_u, sup_u) = (sub_ty.to_union(), sup_ty.to_union());
1764 if has_nominal_type(&sub_u) || has_nominal_type(&sup_u) {
1765 return true;
1766 }
1767 sup_u.is_subtype_structural(&sub_u)
1770 });
1771 params_ok
1772 && (sub.return_type.is_mixed()
1773 || sup.return_type.is_mixed()
1774 || has_nominal_type(&sub.return_type)
1775 || has_nominal_type(&sup.return_type)
1776 || sub.return_type.is_subtype_structural(&sup.return_type))
1777 }
1778 }
1779 (Atomic::TCallable { .. }, Atomic::TCallable { .. }) => true,
1781 (Atomic::TClosure { .. }, Atomic::TNamedObject { fqcn, .. }) => {
1783 fqcn.as_ref().eq_ignore_ascii_case("closure")
1784 }
1785 (Atomic::TClosure { .. }, Atomic::TObject) => true,
1786 (Atomic::TNamedObject { fqcn, .. }, Atomic::TClosure { .. }) => {
1788 fqcn.as_ref().eq_ignore_ascii_case("closure")
1789 }
1790 (Atomic::TNamedObject { fqcn, .. }, Atomic::TCallable { .. }) => {
1792 fqcn.as_ref().eq_ignore_ascii_case("closure")
1793 }
1794
1795 (
1803 Atomic::TIntersection { parts: sub_parts },
1804 Atomic::TIntersection { parts: sup_parts },
1805 ) => sup_parts.iter().all(|sup_part| {
1806 sub_parts
1807 .iter()
1808 .any(|sub_part| sub_part.is_subtype_structural(sup_part))
1809 }),
1810
1811 (Atomic::TList { value }, Atomic::TArray { key, value: av }) => {
1813 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
1814 }
1815 (Atomic::TNonEmptyList { value }, Atomic::TArray { key, value: av }) => {
1816 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
1817 }
1818 (Atomic::TNonEmptyList { value }, Atomic::TNonEmptyArray { key, value: av }) => {
1819 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
1820 }
1821 (Atomic::TNonEmptyList { value }, Atomic::TList { value: lv }) => {
1822 value.is_subtype_structural(lv)
1823 }
1824 (Atomic::TArray { key, value: av }, Atomic::TList { value: lv }) => {
1826 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
1827 && av.is_subtype_structural(lv)
1828 }
1829 (Atomic::TArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
1830 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
1831 && av.is_subtype_structural(lv)
1832 }
1833 (Atomic::TNonEmptyArray { key, value: av }, Atomic::TList { value: lv }) => {
1834 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
1835 && av.is_subtype_structural(lv)
1836 }
1837 (Atomic::TNonEmptyArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
1838 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
1839 && av.is_subtype_structural(lv)
1840 }
1841 (Atomic::TList { value: v1 }, Atomic::TList { value: v2 }) => v1.is_subtype_structural(v2),
1843 (Atomic::TNonEmptyArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
1844 k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
1845 }
1846
1847 (Atomic::TArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
1849 k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
1850 }
1851
1852 (Atomic::TKeyedArray { properties, .. }, Atomic::TArray { key, value }) => {
1861 properties.iter().all(|(prop_key, prop)| {
1862 let key_atomic = match prop_key {
1863 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
1864 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
1865 };
1866 if !Type::single(key_atomic).is_subtype_structural(key) {
1867 return false; }
1869 let has_named_obj = prop.ty.types.iter().any(|a| {
1871 matches!(
1872 a,
1873 Atomic::TNamedObject { .. }
1874 | Atomic::TSelf { .. }
1875 | Atomic::TStaticObject { .. }
1876 | Atomic::TClosure { .. }
1877 | Atomic::TTemplateParam { .. }
1878 )
1879 });
1880 has_named_obj || prop.ty.is_subtype_structural(value)
1881 })
1882 }
1883 (
1884 Atomic::TKeyedArray {
1885 properties,
1886 is_open,
1887 ..
1888 },
1889 Atomic::TNonEmptyArray { key, value },
1890 ) => {
1891 (*is_open || properties.iter().any(|(_, p)| !p.optional))
1892 && properties.iter().all(|(prop_key, prop)| {
1893 let key_atomic = match prop_key {
1894 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
1895 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
1896 };
1897 if !Type::single(key_atomic).is_subtype_structural(key) {
1898 return false;
1899 }
1900 let has_named_obj = prop.ty.types.iter().any(|a| {
1901 matches!(
1902 a,
1903 Atomic::TNamedObject { .. }
1904 | Atomic::TSelf { .. }
1905 | Atomic::TStaticObject { .. }
1906 | Atomic::TClosure { .. }
1907 | Atomic::TTemplateParam { .. }
1908 )
1909 });
1910 has_named_obj || prop.ty.is_subtype_structural(value)
1911 })
1912 }
1913
1914 (
1916 Atomic::TKeyedArray {
1917 properties,
1918 is_list,
1919 ..
1920 },
1921 Atomic::TList { value: lv },
1922 ) => *is_list && properties.values().all(|p| p.ty.is_subtype_structural(lv)),
1923 (
1924 Atomic::TKeyedArray {
1925 properties,
1926 is_list,
1927 ..
1928 },
1929 Atomic::TNonEmptyList { value: lv },
1930 ) => {
1931 *is_list
1932 && !properties.is_empty()
1933 && properties.values().all(|p| p.ty.is_subtype_structural(lv))
1934 }
1935
1936 (
1941 Atomic::TKeyedArray {
1942 properties: sub_props,
1943 is_open: sub_open,
1944 ..
1945 },
1946 Atomic::TKeyedArray {
1947 properties: sup_props,
1948 is_open: sup_open,
1949 ..
1950 },
1951 ) => {
1952 let keys_satisfied = sup_props
1953 .iter()
1954 .all(|(key, sup_prop)| match sub_props.get(key) {
1955 Some(sub_prop) => {
1956 if !sup_prop.optional && sub_prop.optional {
1960 return false;
1961 }
1962 let has_named_obj = sup_prop.ty.types.iter().any(|a| {
1963 matches!(
1964 a,
1965 Atomic::TNamedObject { .. }
1966 | Atomic::TSelf { .. }
1967 | Atomic::TStaticObject { .. }
1968 | Atomic::TClosure { .. }
1969 | Atomic::TTemplateParam { .. }
1970 )
1971 });
1972 has_named_obj || sub_prop.ty.is_subtype_structural(&sup_prop.ty)
1973 }
1974 None => sup_prop.optional || *sub_open,
1975 });
1976 let no_undeclared_extras =
1977 *sup_open || sub_props.keys().all(|k| sup_props.contains_key(k));
1978 keys_satisfied && no_undeclared_extras
1979 }
1980
1981 _ => false,
1982 }
1983}
1984
1985fn type_params_compatible(sub: &[Type], sup: &[Type]) -> bool {
1991 if sub.len() != sup.len() {
1992 return false;
1993 }
1994 sub.iter()
1995 .zip(sup.iter())
1996 .all(|(a, b)| a == b || (is_empty_array_literal(a) && is_array_like(b)))
1997}
1998
1999fn is_empty_array_literal(t: &Type) -> bool {
2002 !t.types.is_empty()
2003 && t.types.iter().all(
2004 |atom| matches!(atom, Atomic::TKeyedArray { properties, .. } if properties.is_empty()),
2005 )
2006}
2007
2008fn is_array_like(t: &Type) -> bool {
2010 !t.types.is_empty() && t.types.iter().all(|atom| atom.is_array())
2011}
2012
2013#[cfg(test)]
2018mod tests {
2019 use std::sync::Arc;
2020
2021 use super::*;
2022
2023 fn conditional(
2024 param_name: Option<Name>,
2025 subject: Type,
2026 if_true: Type,
2027 if_false: Type,
2028 ) -> Atomic {
2029 Atomic::TConditional {
2030 data: Box::new(crate::atomic::ConditionalData {
2031 param_name,
2032 subject,
2033 if_true,
2034 if_false,
2035 }),
2036 }
2037 }
2038
2039 #[test]
2040 fn single_is_single() {
2041 let u = Type::single(Atomic::TString);
2042 assert!(u.is_single());
2043 assert!(!u.is_nullable());
2044 }
2045
2046 #[test]
2047 fn nullable_has_null() {
2048 let u = Type::nullable(Atomic::TString);
2049 assert!(u.is_nullable());
2050 assert_eq!(u.types.len(), 2);
2051 }
2052
2053 #[test]
2054 fn add_type_deduplicates() {
2055 let mut u = Type::single(Atomic::TString);
2056 u.add_type(Atomic::TString);
2057 assert_eq!(u.types.len(), 1);
2058 }
2059
2060 #[test]
2061 fn array_key_is_int_string() {
2062 let k = Type::array_key();
2063 assert!(k.is_array_key());
2064 assert_eq!(k.types.len(), 2);
2065 }
2066
2067 #[test]
2068 fn is_array_key_false_for_plain_int() {
2069 assert!(!Type::int().is_array_key());
2070 }
2071
2072 #[test]
2073 fn is_array_key_false_for_mixed() {
2074 assert!(!Type::mixed().is_array_key());
2075 }
2076
2077 #[test]
2078 fn is_array_key_false_for_int_string_null() {
2079 let mut u = Type::array_key();
2080 u.add_type(Atomic::TNull);
2081 assert!(!u.is_array_key());
2082 }
2083
2084 #[test]
2085 fn add_type_literal_subsumed_by_base() {
2086 let mut u = Type::single(Atomic::TInt);
2087 u.add_type(Atomic::TLiteralInt(42));
2088 assert_eq!(u.types.len(), 1);
2089 assert!(matches!(u.types[0], Atomic::TInt));
2090 }
2091
2092 #[test]
2093 fn true_then_false_merges_to_bool() {
2094 let mut u = Type::single(Atomic::TTrue);
2095 u.add_type(Atomic::TFalse);
2096 assert_eq!(u.types.len(), 1);
2097 assert!(matches!(u.types[0], Atomic::TBool));
2098 }
2099
2100 #[test]
2101 fn false_then_true_merges_to_bool() {
2102 let mut u = Type::single(Atomic::TFalse);
2103 u.add_type(Atomic::TTrue);
2104 assert_eq!(u.types.len(), 1);
2105 assert!(matches!(u.types[0], Atomic::TBool));
2106 }
2107
2108 #[test]
2109 fn true_alone_stays_true() {
2110 let u = Type::single(Atomic::TTrue);
2111 assert_eq!(u.types.len(), 1);
2112 assert!(matches!(u.types[0], Atomic::TTrue));
2113 }
2114
2115 #[test]
2116 fn true_false_merge_preserves_other_union_members() {
2117 let mut u = Type::single(Atomic::TTrue);
2118 u.add_type(Atomic::TNull);
2119 u.add_type(Atomic::TFalse);
2120 assert_eq!(u.types.len(), 2);
2121 assert!(u.contains(|t| matches!(t, Atomic::TBool)));
2122 assert!(u.contains(|t| matches!(t, Atomic::TNull)));
2123 }
2124
2125 #[test]
2126 fn add_type_base_widens_literals() {
2127 let mut u = Type::single(Atomic::TLiteralInt(1));
2128 u.add_type(Atomic::TLiteralInt(2));
2129 u.add_type(Atomic::TInt);
2130 assert_eq!(u.types.len(), 1);
2131 assert!(matches!(u.types[0], Atomic::TInt));
2132 }
2133
2134 #[test]
2135 fn mixed_subsumes_everything() {
2136 let mut u = Type::single(Atomic::TString);
2137 u.add_type(Atomic::TMixed);
2138 assert_eq!(u.types.len(), 1);
2139 assert!(u.is_mixed());
2140 }
2141
2142 #[test]
2143 fn remove_null() {
2144 let u = Type::nullable(Atomic::TString);
2145 let narrowed = u.remove_null();
2146 assert!(!narrowed.is_nullable());
2147 assert_eq!(narrowed.types.len(), 1);
2148 }
2149
2150 #[test]
2151 fn narrow_to_truthy_removes_null_false() {
2152 let mut u = Type::empty();
2153 u.add_type(Atomic::TString);
2154 u.add_type(Atomic::TNull);
2155 u.add_type(Atomic::TFalse);
2156 let truthy = u.narrow_to_truthy();
2157 assert!(!truthy.is_nullable());
2158 assert!(!truthy.contains(|t| matches!(t, Atomic::TFalse)));
2159 }
2160
2161 #[test]
2162 fn merge_combines_types() {
2163 let a = Type::single(Atomic::TString);
2164 let b = Type::single(Atomic::TInt);
2165 let merged = Type::merge(&a, &b);
2166 assert_eq!(merged.types.len(), 2);
2167 }
2168
2169 #[test]
2170 fn intersect_keeps_narrower_side_not_self() {
2171 let int_ty = Type::single(Atomic::TInt);
2175 let mut literals = Type::empty();
2176 literals.add_type(Atomic::TLiteralInt(1));
2177 literals.add_type(Atomic::TLiteralInt(2));
2178
2179 let narrowed = int_ty.intersect_with(&literals);
2180 assert_eq!(narrowed.types.len(), 2);
2181 assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(1))));
2182 assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(2))));
2183 assert!(!narrowed.contains(|t| matches!(t, Atomic::TInt)));
2184 }
2185
2186 #[test]
2187 fn subtype_literal_int_under_int() {
2188 let sub = Type::single(Atomic::TLiteralInt(5));
2189 let sup = Type::single(Atomic::TInt);
2190 assert!(sub.is_subtype_structural(&sup));
2191 }
2192
2193 #[test]
2194 fn subtype_never_is_bottom() {
2195 let never = Type::never();
2196 let string = Type::single(Atomic::TString);
2197 assert!(never.is_subtype_structural(&string));
2198 }
2199
2200 #[test]
2201 fn subtype_everything_under_mixed() {
2202 let string = Type::single(Atomic::TString);
2203 let mixed = Type::mixed();
2204 assert!(string.is_subtype_structural(&mixed));
2205 }
2206
2207 #[test]
2208 fn subtype_enum_case_under_own_enum() {
2209 let sub = Type::single(Atomic::TLiteralEnumCase {
2210 enum_fqcn: Name::new("RoundingMode"),
2211 case_name: Name::new("Unnecessary"),
2212 });
2213 let sup = Type::single(Atomic::TNamedObject {
2214 fqcn: Name::new("RoundingMode"),
2215 type_params: empty_type_params(),
2216 });
2217 assert!(sub.is_subtype_structural(&sup));
2218 }
2219
2220 #[test]
2221 fn enum_case_not_subtype_of_unrelated_enum() {
2222 let sub = Type::single(Atomic::TLiteralEnumCase {
2223 enum_fqcn: Name::new("RoundingMode"),
2224 case_name: Name::new("Unnecessary"),
2225 });
2226 let sup = Type::single(Atomic::TNamedObject {
2227 fqcn: Name::new("Suit"),
2228 type_params: empty_type_params(),
2229 });
2230 assert!(!sub.is_subtype_structural(&sup));
2231 }
2232
2233 #[test]
2234 fn template_substitution() {
2235 let mut bindings = FxHashMap::default();
2236 bindings.insert(Name::new("T"), Type::single(Atomic::TString));
2237
2238 let tmpl = Type::single(Atomic::TTemplateParam {
2239 name: Name::new("T"),
2240 as_type: Box::new(Type::mixed()),
2241 defining_entity: Name::new("MyClass"),
2242 });
2243
2244 let resolved = tmpl.substitute_templates(&bindings);
2245 assert_eq!(resolved.types.len(), 1);
2246 assert!(matches!(resolved.types[0], Atomic::TString));
2247 }
2248
2249 #[test]
2250 fn intersection_is_object() {
2251 let parts = vec![
2252 Type::single(Atomic::TNamedObject {
2253 fqcn: Name::new("Iterator"),
2254 type_params: empty_type_params(),
2255 }),
2256 Type::single(Atomic::TNamedObject {
2257 fqcn: Name::new("Countable"),
2258 type_params: empty_type_params(),
2259 }),
2260 ];
2261 let atomic = Atomic::TIntersection {
2262 parts: vec_to_type_params(parts),
2263 };
2264 assert!(atomic.is_object());
2265 assert!(!atomic.can_be_falsy());
2266 assert!(atomic.can_be_truthy());
2267 }
2268
2269 #[test]
2270 fn intersection_display_two_parts() {
2271 let parts = vec![
2272 Type::single(Atomic::TNamedObject {
2273 fqcn: Name::new("Iterator"),
2274 type_params: empty_type_params(),
2275 }),
2276 Type::single(Atomic::TNamedObject {
2277 fqcn: Name::new("Countable"),
2278 type_params: empty_type_params(),
2279 }),
2280 ];
2281 let u = Type::single(Atomic::TIntersection {
2282 parts: vec_to_type_params(parts),
2283 });
2284 assert_eq!(format!("{u}"), "Iterator&Countable");
2285 }
2286
2287 #[test]
2288 fn intersection_display_three_parts() {
2289 let parts = vec![
2290 Type::single(Atomic::TNamedObject {
2291 fqcn: Name::new("A"),
2292 type_params: empty_type_params(),
2293 }),
2294 Type::single(Atomic::TNamedObject {
2295 fqcn: Name::new("B"),
2296 type_params: empty_type_params(),
2297 }),
2298 Type::single(Atomic::TNamedObject {
2299 fqcn: Name::new("C"),
2300 type_params: empty_type_params(),
2301 }),
2302 ];
2303 let u = Type::single(Atomic::TIntersection {
2304 parts: vec_to_type_params(parts),
2305 });
2306 assert_eq!(format!("{u}"), "A&B&C");
2307 }
2308
2309 #[test]
2310 fn intersection_in_nullable_union_display() {
2311 let intersection = Atomic::TIntersection {
2312 parts: vec_to_type_params(vec![
2313 Type::single(Atomic::TNamedObject {
2314 fqcn: Name::new("Iterator"),
2315 type_params: empty_type_params(),
2316 }),
2317 Type::single(Atomic::TNamedObject {
2318 fqcn: Name::new("Countable"),
2319 type_params: empty_type_params(),
2320 }),
2321 ]),
2322 };
2323 let mut u = Type::single(intersection);
2324 u.add_type(Atomic::TNull);
2325 assert!(u.is_nullable());
2326 assert!(u.contains(|t| matches!(t, Atomic::TIntersection { .. })));
2327 }
2328
2329 fn t_param(name: &str) -> Type {
2332 Type::single(Atomic::TTemplateParam {
2333 name: Name::new(name),
2334 as_type: Box::new(Type::mixed()),
2335 defining_entity: Name::new("Fn"),
2336 })
2337 }
2338
2339 fn bindings_t_string() -> FxHashMap<Name, Type> {
2340 let mut b = FxHashMap::default();
2341 b.insert(Name::new("T"), Type::single(Atomic::TString));
2342 b
2343 }
2344
2345 #[test]
2346 fn substitute_non_empty_array_key_and_value() {
2347 let ty = Type::single(Atomic::TNonEmptyArray {
2348 key: Box::new(t_param("T")),
2349 value: Box::new(t_param("T")),
2350 });
2351 let result = ty.substitute_templates(&bindings_t_string());
2352 assert_eq!(result.types.len(), 1);
2353 let Atomic::TNonEmptyArray { key, value } = &result.types[0] else {
2354 panic!("expected TNonEmptyArray");
2355 };
2356 assert!(matches!(key.types[0], Atomic::TString));
2357 assert!(matches!(value.types[0], Atomic::TString));
2358 }
2359
2360 #[test]
2361 fn substitute_non_empty_list_value() {
2362 let ty = Type::single(Atomic::TNonEmptyList {
2363 value: Box::new(t_param("T")),
2364 });
2365 let result = ty.substitute_templates(&bindings_t_string());
2366 let Atomic::TNonEmptyList { value } = &result.types[0] else {
2367 panic!("expected TNonEmptyList");
2368 };
2369 assert!(matches!(value.types[0], Atomic::TString));
2370 }
2371
2372 #[test]
2373 fn substitute_keyed_array_property_types() {
2374 use crate::atomic::{ArrayKey, KeyedProperty};
2375 use indexmap::IndexMap;
2376 let mut props = IndexMap::new();
2377 props.insert(
2378 ArrayKey::String(Arc::from("name")),
2379 KeyedProperty {
2380 ty: t_param("T"),
2381 optional: false,
2382 },
2383 );
2384 props.insert(
2385 ArrayKey::String(Arc::from("tag")),
2386 KeyedProperty {
2387 ty: t_param("T"),
2388 optional: true,
2389 },
2390 );
2391 let ty = Type::single(Atomic::TKeyedArray {
2392 properties: Box::new(props),
2393 is_open: true,
2394 is_list: false,
2395 });
2396 let result = ty.substitute_templates(&bindings_t_string());
2397 let Atomic::TKeyedArray {
2398 properties,
2399 is_open,
2400 is_list,
2401 } = &result.types[0]
2402 else {
2403 panic!("expected TKeyedArray");
2404 };
2405 assert!(is_open);
2406 assert!(!is_list);
2407 assert!(matches!(
2408 properties[&ArrayKey::String(Arc::from("name"))].ty.types[0],
2409 Atomic::TString
2410 ));
2411 assert!(properties[&ArrayKey::String(Arc::from("tag"))].optional);
2412 assert!(matches!(
2413 properties[&ArrayKey::String(Arc::from("tag"))].ty.types[0],
2414 Atomic::TString
2415 ));
2416 }
2417
2418 #[test]
2419 fn substitute_callable_params_and_return() {
2420 use crate::atomic::FnParam;
2421 let ty = Type::single(Atomic::TCallable {
2422 params: Some(Box::new([FnParam {
2423 name: Name::new("x"),
2424 ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
2425 out_ty: None,
2426 default: None,
2427 is_variadic: false,
2428 is_byref: false,
2429 is_optional: false,
2430 }])),
2431 return_type: Some(Box::new(t_param("T"))),
2432 });
2433 let result = ty.substitute_templates(&bindings_t_string());
2434 let Atomic::TCallable {
2435 params,
2436 return_type,
2437 } = &result.types[0]
2438 else {
2439 panic!("expected TCallable");
2440 };
2441 let param_ty = params.as_ref().unwrap()[0].ty.as_ref().unwrap();
2442 let param_union = param_ty.to_union();
2443 assert!(matches!(param_union.types[0], Atomic::TString));
2444 let ret = return_type.as_ref().unwrap();
2445 assert!(matches!(ret.types[0], Atomic::TString));
2446 }
2447
2448 #[test]
2449 fn substitute_callable_bare_no_panic() {
2450 let ty = Type::single(Atomic::TCallable {
2452 params: None,
2453 return_type: None,
2454 });
2455 let result = ty.substitute_templates(&bindings_t_string());
2456 assert!(matches!(
2457 result.types[0],
2458 Atomic::TCallable {
2459 params: None,
2460 return_type: None
2461 }
2462 ));
2463 }
2464
2465 #[test]
2466 fn substitute_closure_params_return_and_this() {
2467 use crate::atomic::FnParam;
2468 let ty = Type::single(Atomic::TClosure {
2469 data: Box::new(crate::atomic::ClosureData {
2470 params: Box::new([FnParam {
2471 name: Name::new("a"),
2472 ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
2473 out_ty: None,
2474 default: Some(crate::compact::SimpleType::from_union(t_param("T"))),
2475 is_variadic: true,
2476 is_byref: true,
2477 is_optional: true,
2478 }]),
2479 return_type: t_param("T"),
2480 this_type: Some(t_param("T")),
2481 }),
2482 });
2483 let result = ty.substitute_templates(&bindings_t_string());
2484 let Atomic::TClosure { data } = &result.types[0] else {
2485 panic!("expected TClosure");
2486 };
2487 let (params, return_type, this_type) = (&data.params, &data.return_type, &data.this_type);
2488 let p = ¶ms[0];
2489 let ty_union = p.ty.as_ref().unwrap().to_union();
2490 let default_union = p.default.as_ref().unwrap().to_union();
2491 assert!(matches!(ty_union.types[0], Atomic::TString));
2492 assert!(matches!(default_union.types[0], Atomic::TString));
2493 assert!(p.is_variadic);
2495 assert!(p.is_byref);
2496 assert!(p.is_optional);
2497 assert!(matches!(return_type.types[0], Atomic::TString));
2498 assert!(matches!(
2499 this_type.as_ref().unwrap().types[0],
2500 Atomic::TString
2501 ));
2502 }
2503
2504 #[test]
2505 fn substitute_conditional_all_branches() {
2506 let ty = Type::single(conditional(
2507 None,
2508 t_param("T"),
2509 t_param("T"),
2510 Type::single(Atomic::TInt),
2511 ));
2512 let result = ty.substitute_templates(&bindings_t_string());
2513 let Atomic::TConditional { data } = &result.types[0] else {
2514 panic!("expected TConditional");
2515 };
2516 let (subject, if_true, if_false) = (&data.subject, &data.if_true, &data.if_false);
2517 assert!(matches!(subject.types[0], Atomic::TString));
2518 assert!(matches!(if_true.types[0], Atomic::TString));
2519 assert!(matches!(if_false.types[0], Atomic::TInt));
2520 }
2521
2522 #[test]
2523 fn resolve_conditional_is_null_non_null_arg() {
2524 let ty = Type::single(conditional(
2525 Some(Name::new("x")),
2526 Type::single(Atomic::TNull),
2527 Type::single(Atomic::TInt),
2528 Type::single(Atomic::TString),
2529 ));
2530 let result = ty.resolve_conditional_returns(|name| {
2531 if name == "x" {
2532 Some(Type::single(Atomic::TString)) } else {
2534 None
2535 }
2536 });
2537 assert!(result.types.len() == 1);
2538 assert!(matches!(result.types[0], Atomic::TString));
2539 }
2540
2541 #[test]
2542 fn resolve_conditional_is_null_null_arg() {
2543 let ty = Type::single(conditional(
2544 Some(Name::new("x")),
2545 Type::single(Atomic::TNull),
2546 Type::single(Atomic::TInt),
2547 Type::single(Atomic::TString),
2548 ));
2549 let result = ty.resolve_conditional_returns(|name| {
2550 if name == "x" {
2551 Some(Type::single(Atomic::TNull)) } else {
2553 None
2554 }
2555 });
2556 assert!(result.types.len() == 1);
2557 assert!(matches!(result.types[0], Atomic::TInt));
2558 }
2559
2560 #[test]
2561 fn resolve_conditional_is_null_nullable_arg_widens_to_branch_union() {
2562 let mut nullable_str = Type::single(Atomic::TString);
2563 nullable_str.add_type(Atomic::TNull);
2564 let ty = Type::single(conditional(
2565 Some(Name::new("x")),
2566 Type::single(Atomic::TNull),
2567 Type::single(Atomic::TInt),
2568 Type::single(Atomic::TString),
2569 ));
2570 let result = ty.resolve_conditional_returns(|name| {
2571 if name == "x" {
2572 Some(nullable_str.clone())
2573 } else {
2574 None
2575 }
2576 });
2577 assert_eq!(result.types.len(), 2);
2579 assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
2580 assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
2581 }
2582
2583 #[test]
2584 fn resolve_conditional_nested_widens_inner_branch() {
2585 let inner = Type::single(conditional(
2588 Some(Name::new("x")),
2589 Type::single(Atomic::TString),
2590 Type::single(Atomic::TString),
2591 Type::single(Atomic::TFloat),
2592 ));
2593 let ty = Type::single(conditional(
2594 Some(Name::new("x")),
2595 Type::single(Atomic::TNull),
2596 Type::single(Atomic::TInt),
2597 inner,
2598 ));
2599 let result = ty.resolve_conditional_returns(|_| None);
2601 assert!(
2602 result
2603 .types
2604 .iter()
2605 .all(|t| !matches!(t, Atomic::TConditional { .. })),
2606 "no TConditional should survive: {:?}",
2607 result.types
2608 );
2609 assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
2610 assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
2611 assert!(result.types.iter().any(|t| matches!(t, Atomic::TFloat)));
2612 }
2613
2614 #[test]
2615 fn resolve_conditional_nested_resolves_inner_branch() {
2616 let inner = Type::single(conditional(
2620 Some(Name::new("x")),
2621 Type::single(Atomic::TString),
2622 Type::single(Atomic::TString),
2623 Type::single(Atomic::TFloat),
2624 ));
2625 let ty = Type::single(conditional(
2626 Some(Name::new("x")),
2627 Type::single(Atomic::TNull),
2628 Type::single(Atomic::TInt),
2629 inner,
2630 ));
2631 let result = ty.resolve_conditional_returns(|name| {
2633 if name == "x" {
2634 Some(Type::single(Atomic::TString))
2635 } else {
2636 None
2637 }
2638 });
2639 assert!(
2640 result
2641 .types
2642 .iter()
2643 .all(|t| !matches!(t, Atomic::TConditional { .. })),
2644 "no TConditional should survive: {:?}",
2645 result.types
2646 );
2647 assert_eq!(result.types.len(), 1);
2648 assert!(matches!(result.types[0], Atomic::TString));
2649 }
2650
2651 #[test]
2652 fn substitute_intersection_parts() {
2653 let ty = Type::single(Atomic::TIntersection {
2654 parts: vec_to_type_params(vec![
2655 Type::single(Atomic::TNamedObject {
2656 fqcn: Name::new("Countable"),
2657 type_params: empty_type_params(),
2658 }),
2659 t_param("T"),
2660 ]),
2661 });
2662 let result = ty.substitute_templates(&bindings_t_string());
2663 let Atomic::TIntersection { parts } = &result.types[0] else {
2664 panic!("expected TIntersection");
2665 };
2666 assert_eq!(parts.len(), 2);
2667 assert!(matches!(parts[0].types[0], Atomic::TNamedObject { .. }));
2668 assert!(matches!(parts[1].types[0], Atomic::TString));
2669 }
2670
2671 #[test]
2672 fn substitute_no_template_params_identity() {
2673 let ty = Type::single(Atomic::TInt);
2674 let result = ty.substitute_templates(&bindings_t_string());
2675 assert!(matches!(result.types[0], Atomic::TInt));
2676 }
2677}