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
1407fn is_string_atomic(a: &Atomic) -> bool {
1412 matches!(
1413 a,
1414 Atomic::TString
1415 | Atomic::TNonEmptyString
1416 | Atomic::TLiteralString(_)
1417 | Atomic::TNumericString
1418 | Atomic::TClassString(_)
1419 | Atomic::TInterfaceString(_)
1420 | Atomic::TCallableString
1421 )
1422}
1423
1424fn is_array_atomic(a: &Atomic) -> bool {
1425 matches!(
1426 a,
1427 Atomic::TArray { .. }
1428 | Atomic::TNonEmptyArray { .. }
1429 | Atomic::TKeyedArray { .. }
1430 | Atomic::TList { .. }
1431 | Atomic::TNonEmptyList { .. }
1432 )
1433}
1434
1435fn is_list_atomic(a: &Atomic) -> bool {
1436 match a {
1437 Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => true,
1438 Atomic::TKeyedArray { is_list, .. } => *is_list,
1439 _ => false,
1440 }
1441}
1442
1443fn is_float_atomic(a: &Atomic) -> bool {
1444 matches!(
1445 a,
1446 Atomic::TFloat | Atomic::TIntegralFloat | Atomic::TLiteralFloat(..)
1447 )
1448}
1449
1450fn is_bool_atomic(a: &Atomic) -> bool {
1451 matches!(a, Atomic::TBool | Atomic::TTrue | Atomic::TFalse)
1452}
1453
1454fn resolve_conditional_branch(
1460 subject: &Atomic,
1461 arg_ty: &Type,
1462 if_true: &Type,
1463 if_false: &Type,
1464) -> Option<Type> {
1465 let predicate: fn(&Atomic) -> bool = match subject {
1466 Atomic::TNull => |a| matches!(a, Atomic::TNull),
1467 Atomic::TTrue => |a| matches!(a, Atomic::TTrue),
1468 Atomic::TFalse => |a| matches!(a, Atomic::TFalse),
1469 Atomic::TString => is_string_atomic,
1470 Atomic::TList { .. } => is_list_atomic,
1471 Atomic::TArray { .. } => is_array_atomic,
1472 Atomic::TInt => Atomic::is_int,
1473 Atomic::TFloat => is_float_atomic,
1474 Atomic::TBool => is_bool_atomic,
1475 _ => return None,
1476 };
1477
1478 if arg_ty.types.is_empty() {
1479 return None;
1480 }
1481 let all_match = arg_ty.types.iter().all(&predicate);
1482 let none_match = !arg_ty.types.iter().any(predicate);
1483 if all_match {
1484 Some(if_true.clone())
1485 } else if none_match {
1486 Some(if_false.clone())
1487 } else {
1488 None
1489 }
1490}
1491
1492fn atomic_may_contain_templates(atomic: &Atomic) -> bool {
1500 match atomic {
1501 Atomic::TNamedObject { fqcn, type_params } => {
1505 !type_params.is_empty() || !fqcn.contains('\\')
1506 }
1507 Atomic::TTemplateParam { .. }
1508 | Atomic::TKeyOf { .. }
1509 | Atomic::TValueOf { .. }
1510 | Atomic::TArray { .. }
1511 | Atomic::TList { .. }
1512 | Atomic::TNonEmptyArray { .. }
1513 | Atomic::TNonEmptyList { .. }
1514 | Atomic::TKeyedArray { .. }
1515 | Atomic::TCallable { .. }
1516 | Atomic::TClosure { .. }
1517 | Atomic::TConditional { .. }
1518 | Atomic::TIntersection { .. }
1519 | Atomic::TClassString(Some(_))
1520 | Atomic::TInterfaceString(Some(_)) => true,
1521 _ => false,
1522 }
1523}
1524
1525fn eval_key_of_type(t: &Type) -> Option<Type> {
1526 let mut result = Type::empty();
1527 for atomic in &t.types {
1528 match atomic {
1529 Atomic::TArray { key, .. } | Atomic::TNonEmptyArray { key, .. } => {
1530 for k in &key.types {
1531 result.add_type(k.clone());
1532 }
1533 }
1534 Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => {
1535 result.add_type(Atomic::TInt);
1536 }
1537 Atomic::TKeyedArray { properties, .. } => {
1538 for key in properties.keys() {
1539 match key {
1540 crate::atomic::ArrayKey::Int(n) => result.add_type(Atomic::TLiteralInt(*n)),
1541 crate::atomic::ArrayKey::String(s) => {
1542 result.add_type(Atomic::TLiteralString(s.clone()))
1543 }
1544 }
1545 }
1546 }
1547 _ => return None,
1548 }
1549 }
1550 (!result.types.is_empty()).then_some(result)
1551}
1552
1553fn eval_value_of_type(t: &Type) -> Option<Type> {
1554 let mut result = Type::empty();
1555 for atomic in &t.types {
1556 match atomic {
1557 Atomic::TArray { value, .. }
1558 | Atomic::TNonEmptyArray { value, .. }
1559 | Atomic::TList { value }
1560 | Atomic::TNonEmptyList { value } => {
1561 result.merge_with(value);
1562 }
1563 Atomic::TKeyedArray { properties, .. } => {
1564 for prop in properties.values() {
1565 result.merge_with(&prop.ty);
1566 }
1567 }
1568 _ => return None,
1569 }
1570 }
1571 (!result.types.is_empty()).then_some(result)
1572}
1573
1574fn substitute_in_fn_param(
1575 p: &crate::atomic::FnParam,
1576 bindings: &FxHashMap<Name, Type>,
1577) -> crate::atomic::FnParam {
1578 crate::atomic::FnParam {
1579 name: p.name,
1580 ty: p.ty.as_ref().map(|t| {
1581 let u = t.to_union();
1582 let substituted = u.substitute_templates(bindings);
1583 crate::compact::SimpleType::from_union(substituted)
1584 }),
1585 out_ty: p.out_ty.as_ref().map(|t| {
1586 let u = t.to_union();
1587 let substituted = u.substitute_templates(bindings);
1588 crate::compact::SimpleType::from_union(substituted)
1589 }),
1590 default: p.default.as_ref().map(|d| {
1591 let u = d.to_union();
1592 let substituted = u.substitute_templates(bindings);
1593 crate::compact::SimpleType::from_union(substituted)
1594 }),
1595 is_variadic: p.is_variadic,
1596 is_byref: p.is_byref,
1597 is_optional: p.is_optional,
1598 }
1599}
1600
1601pub fn atomic_subtype(sub: &Atomic, sup: &Atomic) -> bool {
1607 if sub == sup {
1608 return true;
1609 }
1610 match (sub, sup) {
1611 (Atomic::TNever, _) => true,
1613 (_, Atomic::TMixed) => true,
1615 (Atomic::TMixed, _) => true,
1616 (_, Atomic::TTemplateParam { as_type, .. }) => {
1621 as_type.is_mixed() || as_type.types.iter().any(|b| atomic_subtype(sub, b))
1622 }
1623
1624 (Atomic::TLiteralInt(_), Atomic::TInt) => true,
1626 (Atomic::TLiteralInt(_), Atomic::TNumeric) => true,
1627 (Atomic::TLiteralInt(_), Atomic::TScalar) => true,
1628 (Atomic::TLiteralInt(n), Atomic::TPositiveInt) => *n > 0,
1629 (Atomic::TLiteralInt(n), Atomic::TNonNegativeInt) => *n >= 0,
1630 (Atomic::TLiteralInt(n), Atomic::TNegativeInt) => *n < 0,
1631 (Atomic::TPositiveInt, Atomic::TInt) => true,
1632 (Atomic::TPositiveInt, Atomic::TNonNegativeInt) => true,
1633 (Atomic::TPositiveInt, Atomic::TNumeric) => true,
1634 (Atomic::TPositiveInt, Atomic::TScalar) => true,
1635 (Atomic::TNegativeInt, Atomic::TInt) => true,
1636 (Atomic::TNegativeInt, Atomic::TNumeric) => true,
1637 (Atomic::TNegativeInt, Atomic::TScalar) => true,
1638 (Atomic::TNonNegativeInt, Atomic::TInt) => true,
1639 (Atomic::TNonNegativeInt, Atomic::TNumeric) => true,
1640 (Atomic::TNonNegativeInt, Atomic::TScalar) => true,
1641 (Atomic::TIntRange { .. }, Atomic::TInt) => true,
1642 (Atomic::TIntRange { .. }, Atomic::TNumeric) => true,
1643 (Atomic::TIntRange { .. }, Atomic::TScalar) => true,
1644 (Atomic::TPositiveInt, Atomic::TIntRange { min, max }) => {
1646 max.is_none() && min.is_none_or(|m| m <= 1)
1647 }
1648 (Atomic::TNegativeInt, Atomic::TIntRange { min, max }) => {
1650 min.is_none() && max.is_none_or(|m| m >= -1)
1651 }
1652 (Atomic::TNonNegativeInt, Atomic::TIntRange { min, max }) => {
1654 max.is_none() && min.is_none_or(|m| m <= 0)
1655 }
1656 (Atomic::TIntRange { min: sub_min, .. }, Atomic::TPositiveInt) => {
1658 sub_min.is_some_and(|lo| lo >= 1)
1659 }
1660 (Atomic::TIntRange { min: sub_min, .. }, Atomic::TNonNegativeInt) => {
1661 sub_min.is_some_and(|lo| lo >= 0)
1662 }
1663 (Atomic::TIntRange { max: sub_max, .. }, Atomic::TNegativeInt) => {
1664 sub_max.is_some_and(|hi| hi <= -1)
1665 }
1666 (
1668 Atomic::TIntRange {
1669 min: sub_min,
1670 max: sub_max,
1671 },
1672 Atomic::TIntRange {
1673 min: sup_min,
1674 max: sup_max,
1675 },
1676 ) => {
1677 let lower_ok = match (sub_min, sup_min) {
1678 (_, None) => true,
1679 (None, Some(_)) => false,
1680 (Some(sl), Some(su)) => sl >= su,
1681 };
1682 let upper_ok = match (sub_max, sup_max) {
1683 (None, None) | (Some(_), None) => true,
1684 (None, Some(_)) => false,
1685 (Some(sl), Some(su)) => sl <= su,
1686 };
1687 lower_ok && upper_ok
1688 }
1689
1690 (Atomic::TLiteralFloat(..), Atomic::TFloat) => true,
1691 (Atomic::TLiteralFloat(..), Atomic::TNumeric) => true,
1692 (Atomic::TLiteralFloat(..), Atomic::TScalar) => true,
1693
1694 (Atomic::TLiteralString(s), Atomic::TString) => {
1695 let _ = s;
1696 true
1697 }
1698 (Atomic::TLiteralString(s), Atomic::TCallableString) => {
1699 let _ = s;
1700 true
1701 }
1702 (Atomic::TLiteralString(s), Atomic::TNonEmptyString) => !s.is_empty(),
1703 (Atomic::TLiteralString(s), Atomic::TNumericString) => s.parse::<f64>().is_ok(),
1704 (Atomic::TLiteralString(_), Atomic::TClassString(_)) => true,
1707 (Atomic::TLiteralString(_), Atomic::TInterfaceString(_)) => true,
1710 (Atomic::TLiteralString(_), Atomic::TScalar) => true,
1711 (Atomic::TNonEmptyString, Atomic::TString) => true,
1712 (Atomic::TCallableString, Atomic::TString) => true,
1713 (Atomic::TNumericString, Atomic::TNonEmptyString) => true,
1715 (Atomic::TNumericString, Atomic::TString) => true,
1716 (Atomic::TClassString(_), Atomic::TNonEmptyString) => true,
1720 (Atomic::TInterfaceString(_), Atomic::TNonEmptyString) => true,
1721 (Atomic::TCallableString, Atomic::TNonEmptyString) => true,
1722 (Atomic::TEnumString, Atomic::TNonEmptyString) => true,
1723 (Atomic::TTraitString, Atomic::TNonEmptyString) => true,
1724 (Atomic::TClassString(_), Atomic::TString) => true,
1725 (Atomic::TInterfaceString(_), Atomic::TString) => true,
1726 (Atomic::TInterfaceString(_), Atomic::TClassString(None)) => true,
1731 (Atomic::TInterfaceString(Some(a)), Atomic::TClassString(Some(b))) => a == b,
1732 (Atomic::TEnumString, Atomic::TString) => true,
1733 (Atomic::TTraitString, Atomic::TString) => true,
1734
1735 (Atomic::TTrue, Atomic::TBool) => true,
1736 (Atomic::TFalse, Atomic::TBool) => true,
1737
1738 (Atomic::TInt, Atomic::TNumeric) => true,
1739 (Atomic::TFloat, Atomic::TNumeric) => true,
1740 (Atomic::TIntegralFloat, Atomic::TNumeric) => true,
1741 (Atomic::TNumericString, Atomic::TNumeric) => true,
1742
1743 (Atomic::TInt, Atomic::TScalar) => true,
1744 (Atomic::TFloat, Atomic::TScalar) => true,
1745 (Atomic::TIntegralFloat, Atomic::TScalar) => true,
1746 (Atomic::TString, Atomic::TScalar) => true,
1747 (Atomic::TBool, Atomic::TScalar) => true,
1748 (Atomic::TNumeric, Atomic::TScalar) => true,
1749 (Atomic::TTrue, Atomic::TScalar) => true,
1750 (Atomic::TFalse, Atomic::TScalar) => true,
1751 (Atomic::TNonEmptyString, Atomic::TScalar) => true,
1755 (Atomic::TNumericString, Atomic::TScalar) => true,
1756 (Atomic::TCallableString, Atomic::TScalar) => true,
1757 (Atomic::TClassString(_), Atomic::TScalar) => true,
1758 (Atomic::TInterfaceString(_), Atomic::TScalar) => true,
1759 (Atomic::TEnumString, Atomic::TScalar) => true,
1760 (Atomic::TTraitString, Atomic::TScalar) => true,
1761
1762 (Atomic::TNamedObject { .. }, Atomic::TObject) => true,
1764 (Atomic::TStaticObject { .. }, Atomic::TObject) => true,
1765 (Atomic::TSelf { .. }, Atomic::TObject) => true,
1766 (Atomic::TLiteralEnumCase { .. }, Atomic::TObject) => true,
1768 (Atomic::TSelf { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
1770 (Atomic::TStaticObject { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
1771 (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TSelf { fqcn: b }) => a == b,
1773 (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TStaticObject { fqcn: b }) => a == b,
1774 (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TNamedObject { fqcn, .. }) => {
1777 enum_fqcn == fqcn
1778 }
1779 (
1783 Atomic::TNamedObject {
1784 fqcn: sub_fqcn,
1785 type_params: sub_params,
1786 },
1787 Atomic::TNamedObject {
1788 fqcn: sup_fqcn,
1789 type_params: sup_params,
1790 },
1791 ) => {
1792 sub_fqcn == sup_fqcn
1793 && (sup_params.is_empty() || type_params_compatible(sub_params, sup_params))
1794 }
1795
1796 (Atomic::TIntegralFloat, Atomic::TFloat) => true,
1798
1799 (Atomic::TLiteralInt(_), Atomic::TFloat) => true,
1801 (Atomic::TPositiveInt, Atomic::TFloat) => true,
1802 (Atomic::TNegativeInt, Atomic::TFloat) => true,
1803 (Atomic::TNonNegativeInt, Atomic::TFloat) => true,
1804 (Atomic::TInt, Atomic::TFloat) => true,
1805 (Atomic::TIntRange { .. }, Atomic::TFloat) => true,
1806
1807 (Atomic::TLiteralInt(n), Atomic::TIntRange { min, max }) => {
1809 min.is_none_or(|lo| *n >= lo) && max.is_none_or(|hi| *n <= hi)
1810 }
1811
1812 (Atomic::TString, Atomic::TCallable { .. }) => true,
1814 (Atomic::TNonEmptyString, Atomic::TCallable { .. }) => true,
1815 (Atomic::TLiteralString(_), Atomic::TCallable { .. }) => true,
1816 (Atomic::TArray { .. }, Atomic::TCallable { .. }) => true,
1817 (Atomic::TNonEmptyArray { .. }, Atomic::TCallable { .. }) => true,
1818 (Atomic::TKeyedArray { .. }, Atomic::TCallable { .. }) => true,
1819
1820 (Atomic::TClosure { .. }, Atomic::TCallable { .. }) => true,
1822 (Atomic::TCallable { .. }, Atomic::TClosure { .. }) => true,
1824 (Atomic::TClosure { data: sub }, Atomic::TClosure { data: sup }) => {
1834 fn has_nominal_type(t: &Type) -> bool {
1835 t.types.iter().any(|a| {
1836 matches!(
1837 a,
1838 Atomic::TNamedObject { .. }
1839 | Atomic::TSelf { .. }
1840 | Atomic::TStaticObject { .. }
1841 | Atomic::TTemplateParam { .. }
1842 | Atomic::TClosure { .. }
1843 | Atomic::TCallable { .. }
1844 )
1845 })
1846 }
1847 let sub_required = sub
1848 .params
1849 .iter()
1850 .filter(|p| !p.is_optional && !p.is_variadic)
1851 .count();
1852 if sub_required > sup.params.len() {
1853 false
1854 } else {
1855 let params_ok = sup.params.iter().enumerate().all(|(i, sup_param)| {
1856 let Some(sub_param) = sub.params.get(i) else {
1857 return true;
1858 };
1859 if sub_param.is_optional || sub_param.is_variadic {
1860 return true;
1861 }
1862 let (Some(sub_ty), Some(sup_ty)) =
1863 (sub_param.ty.as_ref(), sup_param.ty.as_ref())
1864 else {
1865 return true;
1866 };
1867 let (sub_u, sup_u) = (sub_ty.to_union(), sup_ty.to_union());
1868 if has_nominal_type(&sub_u) || has_nominal_type(&sup_u) {
1869 return true;
1870 }
1871 sup_u.is_subtype_structural(&sub_u)
1874 });
1875 params_ok
1876 && (sub.return_type.is_mixed()
1877 || sup.return_type.is_mixed()
1878 || has_nominal_type(&sub.return_type)
1879 || has_nominal_type(&sup.return_type)
1880 || sub.return_type.is_subtype_structural(&sup.return_type))
1881 }
1882 }
1883 (Atomic::TCallable { .. }, Atomic::TCallable { .. }) => true,
1885 (Atomic::TClosure { .. }, Atomic::TNamedObject { fqcn, .. }) => {
1887 fqcn.as_ref().eq_ignore_ascii_case("closure")
1888 }
1889 (Atomic::TClosure { .. }, Atomic::TObject) => true,
1890 (Atomic::TNamedObject { fqcn, .. }, Atomic::TClosure { .. }) => {
1892 fqcn.as_ref().eq_ignore_ascii_case("closure")
1893 }
1894 (Atomic::TNamedObject { fqcn, .. }, Atomic::TCallable { .. }) => {
1896 fqcn.as_ref().eq_ignore_ascii_case("closure")
1897 }
1898
1899 (
1907 Atomic::TIntersection { parts: sub_parts },
1908 Atomic::TIntersection { parts: sup_parts },
1909 ) => sup_parts.iter().all(|sup_part| {
1910 sub_parts
1911 .iter()
1912 .any(|sub_part| sub_part.is_subtype_structural(sup_part))
1913 }),
1914
1915 (Atomic::TList { value }, Atomic::TArray { key, value: av }) => {
1917 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
1918 }
1919 (Atomic::TNonEmptyList { value }, Atomic::TArray { key, value: av }) => {
1920 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
1921 }
1922 (Atomic::TNonEmptyList { value }, Atomic::TNonEmptyArray { key, value: av }) => {
1923 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
1924 }
1925 (Atomic::TNonEmptyList { value }, Atomic::TList { value: lv }) => {
1926 value.is_subtype_structural(lv)
1927 }
1928 (Atomic::TArray { key, value: av }, Atomic::TList { value: lv }) => {
1930 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
1931 && av.is_subtype_structural(lv)
1932 }
1933 (Atomic::TArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
1934 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
1935 && av.is_subtype_structural(lv)
1936 }
1937 (Atomic::TNonEmptyArray { key, value: av }, Atomic::TList { value: lv }) => {
1938 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
1939 && av.is_subtype_structural(lv)
1940 }
1941 (Atomic::TNonEmptyArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
1942 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
1943 && av.is_subtype_structural(lv)
1944 }
1945 (Atomic::TList { value: v1 }, Atomic::TList { value: v2 }) => v1.is_subtype_structural(v2),
1947 (Atomic::TNonEmptyArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
1948 k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
1949 }
1950
1951 (Atomic::TArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
1953 k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
1954 }
1955
1956 (Atomic::TKeyedArray { properties, .. }, Atomic::TArray { key, value }) => {
1965 properties.iter().all(|(prop_key, prop)| {
1966 let key_atomic = match prop_key {
1967 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
1968 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
1969 };
1970 if !Type::single(key_atomic).is_subtype_structural(key) {
1971 return false; }
1973 let has_named_obj = prop.ty.types.iter().any(|a| {
1975 matches!(
1976 a,
1977 Atomic::TNamedObject { .. }
1978 | Atomic::TSelf { .. }
1979 | Atomic::TStaticObject { .. }
1980 | Atomic::TClosure { .. }
1981 | Atomic::TTemplateParam { .. }
1982 )
1983 });
1984 has_named_obj || prop.ty.is_subtype_structural(value)
1985 })
1986 }
1987 (
1988 Atomic::TKeyedArray {
1989 properties,
1990 is_open,
1991 ..
1992 },
1993 Atomic::TNonEmptyArray { key, value },
1994 ) => {
1995 (*is_open || properties.iter().any(|(_, p)| !p.optional))
1996 && properties.iter().all(|(prop_key, prop)| {
1997 let key_atomic = match prop_key {
1998 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
1999 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2000 };
2001 if !Type::single(key_atomic).is_subtype_structural(key) {
2002 return false;
2003 }
2004 let has_named_obj = prop.ty.types.iter().any(|a| {
2005 matches!(
2006 a,
2007 Atomic::TNamedObject { .. }
2008 | Atomic::TSelf { .. }
2009 | Atomic::TStaticObject { .. }
2010 | Atomic::TClosure { .. }
2011 | Atomic::TTemplateParam { .. }
2012 )
2013 });
2014 has_named_obj || prop.ty.is_subtype_structural(value)
2015 })
2016 }
2017
2018 (
2020 Atomic::TKeyedArray {
2021 properties,
2022 is_list,
2023 ..
2024 },
2025 Atomic::TList { value: lv },
2026 ) => *is_list && properties.values().all(|p| p.ty.is_subtype_structural(lv)),
2027 (
2028 Atomic::TKeyedArray {
2029 properties,
2030 is_list,
2031 ..
2032 },
2033 Atomic::TNonEmptyList { value: lv },
2034 ) => {
2035 *is_list
2036 && !properties.is_empty()
2037 && properties.values().all(|p| p.ty.is_subtype_structural(lv))
2038 }
2039
2040 (
2045 Atomic::TKeyedArray {
2046 properties: sub_props,
2047 is_open: sub_open,
2048 ..
2049 },
2050 Atomic::TKeyedArray {
2051 properties: sup_props,
2052 is_open: sup_open,
2053 ..
2054 },
2055 ) => {
2056 let keys_satisfied = sup_props
2057 .iter()
2058 .all(|(key, sup_prop)| match sub_props.get(key) {
2059 Some(sub_prop) => {
2060 if !sup_prop.optional && sub_prop.optional {
2064 return false;
2065 }
2066 let has_named_obj = sup_prop.ty.types.iter().any(|a| {
2067 matches!(
2068 a,
2069 Atomic::TNamedObject { .. }
2070 | Atomic::TSelf { .. }
2071 | Atomic::TStaticObject { .. }
2072 | Atomic::TClosure { .. }
2073 | Atomic::TTemplateParam { .. }
2074 )
2075 });
2076 has_named_obj || sub_prop.ty.is_subtype_structural(&sup_prop.ty)
2077 }
2078 None => sup_prop.optional || *sub_open,
2079 });
2080 let no_undeclared_extras =
2081 *sup_open || sub_props.keys().all(|k| sup_props.contains_key(k));
2082 keys_satisfied && no_undeclared_extras
2083 }
2084
2085 _ => false,
2086 }
2087}
2088
2089fn type_params_compatible(sub: &[Type], sup: &[Type]) -> bool {
2095 if sub.len() != sup.len() {
2096 return false;
2097 }
2098 sub.iter()
2099 .zip(sup.iter())
2100 .all(|(a, b)| a == b || (is_empty_array_literal(a) && is_array_like(b)))
2101}
2102
2103fn is_empty_array_literal(t: &Type) -> bool {
2106 !t.types.is_empty()
2107 && t.types.iter().all(
2108 |atom| matches!(atom, Atomic::TKeyedArray { properties, .. } if properties.is_empty()),
2109 )
2110}
2111
2112fn is_array_like(t: &Type) -> bool {
2114 !t.types.is_empty() && t.types.iter().all(|atom| atom.is_array())
2115}
2116
2117#[cfg(test)]
2122mod tests {
2123 use std::sync::Arc;
2124
2125 use super::*;
2126
2127 fn conditional(
2128 param_name: Option<Name>,
2129 subject: Type,
2130 if_true: Type,
2131 if_false: Type,
2132 ) -> Atomic {
2133 Atomic::TConditional {
2134 data: Box::new(crate::atomic::ConditionalData {
2135 param_name,
2136 subject,
2137 if_true,
2138 if_false,
2139 }),
2140 }
2141 }
2142
2143 #[test]
2144 fn single_is_single() {
2145 let u = Type::single(Atomic::TString);
2146 assert!(u.is_single());
2147 assert!(!u.is_nullable());
2148 }
2149
2150 #[test]
2151 fn nullable_has_null() {
2152 let u = Type::nullable(Atomic::TString);
2153 assert!(u.is_nullable());
2154 assert_eq!(u.types.len(), 2);
2155 }
2156
2157 #[test]
2158 fn add_type_deduplicates() {
2159 let mut u = Type::single(Atomic::TString);
2160 u.add_type(Atomic::TString);
2161 assert_eq!(u.types.len(), 1);
2162 }
2163
2164 #[test]
2165 fn array_key_is_int_string() {
2166 let k = Type::array_key();
2167 assert!(k.is_array_key());
2168 assert_eq!(k.types.len(), 2);
2169 }
2170
2171 #[test]
2172 fn is_array_key_false_for_plain_int() {
2173 assert!(!Type::int().is_array_key());
2174 }
2175
2176 #[test]
2177 fn is_array_key_false_for_mixed() {
2178 assert!(!Type::mixed().is_array_key());
2179 }
2180
2181 #[test]
2182 fn is_array_key_false_for_int_string_null() {
2183 let mut u = Type::array_key();
2184 u.add_type(Atomic::TNull);
2185 assert!(!u.is_array_key());
2186 }
2187
2188 #[test]
2189 fn add_type_literal_subsumed_by_base() {
2190 let mut u = Type::single(Atomic::TInt);
2191 u.add_type(Atomic::TLiteralInt(42));
2192 assert_eq!(u.types.len(), 1);
2193 assert!(matches!(u.types[0], Atomic::TInt));
2194 }
2195
2196 #[test]
2197 fn true_then_false_merges_to_bool() {
2198 let mut u = Type::single(Atomic::TTrue);
2199 u.add_type(Atomic::TFalse);
2200 assert_eq!(u.types.len(), 1);
2201 assert!(matches!(u.types[0], Atomic::TBool));
2202 }
2203
2204 #[test]
2205 fn false_then_true_merges_to_bool() {
2206 let mut u = Type::single(Atomic::TFalse);
2207 u.add_type(Atomic::TTrue);
2208 assert_eq!(u.types.len(), 1);
2209 assert!(matches!(u.types[0], Atomic::TBool));
2210 }
2211
2212 #[test]
2213 fn true_alone_stays_true() {
2214 let u = Type::single(Atomic::TTrue);
2215 assert_eq!(u.types.len(), 1);
2216 assert!(matches!(u.types[0], Atomic::TTrue));
2217 }
2218
2219 #[test]
2220 fn true_false_merge_preserves_other_union_members() {
2221 let mut u = Type::single(Atomic::TTrue);
2222 u.add_type(Atomic::TNull);
2223 u.add_type(Atomic::TFalse);
2224 assert_eq!(u.types.len(), 2);
2225 assert!(u.contains(|t| matches!(t, Atomic::TBool)));
2226 assert!(u.contains(|t| matches!(t, Atomic::TNull)));
2227 }
2228
2229 #[test]
2230 fn add_type_base_widens_literals() {
2231 let mut u = Type::single(Atomic::TLiteralInt(1));
2232 u.add_type(Atomic::TLiteralInt(2));
2233 u.add_type(Atomic::TInt);
2234 assert_eq!(u.types.len(), 1);
2235 assert!(matches!(u.types[0], Atomic::TInt));
2236 }
2237
2238 #[test]
2239 fn mixed_subsumes_everything() {
2240 let mut u = Type::single(Atomic::TString);
2241 u.add_type(Atomic::TMixed);
2242 assert_eq!(u.types.len(), 1);
2243 assert!(u.is_mixed());
2244 }
2245
2246 #[test]
2247 fn remove_null() {
2248 let u = Type::nullable(Atomic::TString);
2249 let narrowed = u.remove_null();
2250 assert!(!narrowed.is_nullable());
2251 assert_eq!(narrowed.types.len(), 1);
2252 }
2253
2254 #[test]
2255 fn narrow_to_truthy_removes_null_false() {
2256 let mut u = Type::empty();
2257 u.add_type(Atomic::TString);
2258 u.add_type(Atomic::TNull);
2259 u.add_type(Atomic::TFalse);
2260 let truthy = u.narrow_to_truthy();
2261 assert!(!truthy.is_nullable());
2262 assert!(!truthy.contains(|t| matches!(t, Atomic::TFalse)));
2263 }
2264
2265 #[test]
2266 fn merge_combines_types() {
2267 let a = Type::single(Atomic::TString);
2268 let b = Type::single(Atomic::TInt);
2269 let merged = Type::merge(&a, &b);
2270 assert_eq!(merged.types.len(), 2);
2271 }
2272
2273 #[test]
2274 fn intersect_keeps_narrower_side_not_self() {
2275 let int_ty = Type::single(Atomic::TInt);
2279 let mut literals = Type::empty();
2280 literals.add_type(Atomic::TLiteralInt(1));
2281 literals.add_type(Atomic::TLiteralInt(2));
2282
2283 let narrowed = int_ty.intersect_with(&literals);
2284 assert_eq!(narrowed.types.len(), 2);
2285 assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(1))));
2286 assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(2))));
2287 assert!(!narrowed.contains(|t| matches!(t, Atomic::TInt)));
2288 }
2289
2290 #[test]
2291 fn subtype_literal_int_under_int() {
2292 let sub = Type::single(Atomic::TLiteralInt(5));
2293 let sup = Type::single(Atomic::TInt);
2294 assert!(sub.is_subtype_structural(&sup));
2295 }
2296
2297 #[test]
2298 fn subtype_never_is_bottom() {
2299 let never = Type::never();
2300 let string = Type::single(Atomic::TString);
2301 assert!(never.is_subtype_structural(&string));
2302 }
2303
2304 #[test]
2305 fn subtype_everything_under_mixed() {
2306 let string = Type::single(Atomic::TString);
2307 let mixed = Type::mixed();
2308 assert!(string.is_subtype_structural(&mixed));
2309 }
2310
2311 #[test]
2312 fn subtype_enum_case_under_own_enum() {
2313 let sub = Type::single(Atomic::TLiteralEnumCase {
2314 enum_fqcn: Name::new("RoundingMode"),
2315 case_name: Name::new("Unnecessary"),
2316 });
2317 let sup = Type::single(Atomic::TNamedObject {
2318 fqcn: Name::new("RoundingMode"),
2319 type_params: empty_type_params(),
2320 });
2321 assert!(sub.is_subtype_structural(&sup));
2322 }
2323
2324 #[test]
2325 fn enum_case_not_subtype_of_unrelated_enum() {
2326 let sub = Type::single(Atomic::TLiteralEnumCase {
2327 enum_fqcn: Name::new("RoundingMode"),
2328 case_name: Name::new("Unnecessary"),
2329 });
2330 let sup = Type::single(Atomic::TNamedObject {
2331 fqcn: Name::new("Suit"),
2332 type_params: empty_type_params(),
2333 });
2334 assert!(!sub.is_subtype_structural(&sup));
2335 }
2336
2337 #[test]
2338 fn subtype_enum_case_under_bare_object() {
2339 let sub = Type::single(Atomic::TLiteralEnumCase {
2340 enum_fqcn: Name::new("RoundingMode"),
2341 case_name: Name::new("Unnecessary"),
2342 });
2343 let sup = Type::single(Atomic::TObject);
2344 assert!(sub.is_subtype_structural(&sup));
2345 }
2346
2347 #[test]
2348 fn template_substitution() {
2349 let mut bindings = FxHashMap::default();
2350 bindings.insert(Name::new("T"), Type::single(Atomic::TString));
2351
2352 let tmpl = Type::single(Atomic::TTemplateParam {
2353 name: Name::new("T"),
2354 as_type: Box::new(Type::mixed()),
2355 defining_entity: Name::new("MyClass"),
2356 });
2357
2358 let resolved = tmpl.substitute_templates(&bindings);
2359 assert_eq!(resolved.types.len(), 1);
2360 assert!(matches!(resolved.types[0], Atomic::TString));
2361 }
2362
2363 #[test]
2364 fn intersection_is_object() {
2365 let parts = vec![
2366 Type::single(Atomic::TNamedObject {
2367 fqcn: Name::new("Iterator"),
2368 type_params: empty_type_params(),
2369 }),
2370 Type::single(Atomic::TNamedObject {
2371 fqcn: Name::new("Countable"),
2372 type_params: empty_type_params(),
2373 }),
2374 ];
2375 let atomic = Atomic::TIntersection {
2376 parts: vec_to_type_params(parts),
2377 };
2378 assert!(atomic.is_object());
2379 assert!(!atomic.can_be_falsy());
2380 assert!(atomic.can_be_truthy());
2381 }
2382
2383 #[test]
2384 fn intersection_display_two_parts() {
2385 let parts = vec![
2386 Type::single(Atomic::TNamedObject {
2387 fqcn: Name::new("Iterator"),
2388 type_params: empty_type_params(),
2389 }),
2390 Type::single(Atomic::TNamedObject {
2391 fqcn: Name::new("Countable"),
2392 type_params: empty_type_params(),
2393 }),
2394 ];
2395 let u = Type::single(Atomic::TIntersection {
2396 parts: vec_to_type_params(parts),
2397 });
2398 assert_eq!(format!("{u}"), "Iterator&Countable");
2399 }
2400
2401 #[test]
2402 fn intersection_display_three_parts() {
2403 let parts = vec![
2404 Type::single(Atomic::TNamedObject {
2405 fqcn: Name::new("A"),
2406 type_params: empty_type_params(),
2407 }),
2408 Type::single(Atomic::TNamedObject {
2409 fqcn: Name::new("B"),
2410 type_params: empty_type_params(),
2411 }),
2412 Type::single(Atomic::TNamedObject {
2413 fqcn: Name::new("C"),
2414 type_params: empty_type_params(),
2415 }),
2416 ];
2417 let u = Type::single(Atomic::TIntersection {
2418 parts: vec_to_type_params(parts),
2419 });
2420 assert_eq!(format!("{u}"), "A&B&C");
2421 }
2422
2423 #[test]
2424 fn intersection_in_nullable_union_display() {
2425 let intersection = Atomic::TIntersection {
2426 parts: vec_to_type_params(vec![
2427 Type::single(Atomic::TNamedObject {
2428 fqcn: Name::new("Iterator"),
2429 type_params: empty_type_params(),
2430 }),
2431 Type::single(Atomic::TNamedObject {
2432 fqcn: Name::new("Countable"),
2433 type_params: empty_type_params(),
2434 }),
2435 ]),
2436 };
2437 let mut u = Type::single(intersection);
2438 u.add_type(Atomic::TNull);
2439 assert!(u.is_nullable());
2440 assert!(u.contains(|t| matches!(t, Atomic::TIntersection { .. })));
2441 }
2442
2443 fn t_param(name: &str) -> Type {
2446 Type::single(Atomic::TTemplateParam {
2447 name: Name::new(name),
2448 as_type: Box::new(Type::mixed()),
2449 defining_entity: Name::new("Fn"),
2450 })
2451 }
2452
2453 fn bindings_t_string() -> FxHashMap<Name, Type> {
2454 let mut b = FxHashMap::default();
2455 b.insert(Name::new("T"), Type::single(Atomic::TString));
2456 b
2457 }
2458
2459 #[test]
2460 fn substitute_non_empty_array_key_and_value() {
2461 let ty = Type::single(Atomic::TNonEmptyArray {
2462 key: Box::new(t_param("T")),
2463 value: Box::new(t_param("T")),
2464 });
2465 let result = ty.substitute_templates(&bindings_t_string());
2466 assert_eq!(result.types.len(), 1);
2467 let Atomic::TNonEmptyArray { key, value } = &result.types[0] else {
2468 panic!("expected TNonEmptyArray");
2469 };
2470 assert!(matches!(key.types[0], Atomic::TString));
2471 assert!(matches!(value.types[0], Atomic::TString));
2472 }
2473
2474 #[test]
2475 fn substitute_non_empty_list_value() {
2476 let ty = Type::single(Atomic::TNonEmptyList {
2477 value: Box::new(t_param("T")),
2478 });
2479 let result = ty.substitute_templates(&bindings_t_string());
2480 let Atomic::TNonEmptyList { value } = &result.types[0] else {
2481 panic!("expected TNonEmptyList");
2482 };
2483 assert!(matches!(value.types[0], Atomic::TString));
2484 }
2485
2486 #[test]
2487 fn substitute_keyed_array_property_types() {
2488 use crate::atomic::{ArrayKey, KeyedProperty};
2489 use indexmap::IndexMap;
2490 let mut props = IndexMap::new();
2491 props.insert(
2492 ArrayKey::String(Arc::from("name")),
2493 KeyedProperty {
2494 ty: t_param("T"),
2495 optional: false,
2496 },
2497 );
2498 props.insert(
2499 ArrayKey::String(Arc::from("tag")),
2500 KeyedProperty {
2501 ty: t_param("T"),
2502 optional: true,
2503 },
2504 );
2505 let ty = Type::single(Atomic::TKeyedArray {
2506 properties: Box::new(props),
2507 is_open: true,
2508 is_list: false,
2509 });
2510 let result = ty.substitute_templates(&bindings_t_string());
2511 let Atomic::TKeyedArray {
2512 properties,
2513 is_open,
2514 is_list,
2515 } = &result.types[0]
2516 else {
2517 panic!("expected TKeyedArray");
2518 };
2519 assert!(is_open);
2520 assert!(!is_list);
2521 assert!(matches!(
2522 properties[&ArrayKey::String(Arc::from("name"))].ty.types[0],
2523 Atomic::TString
2524 ));
2525 assert!(properties[&ArrayKey::String(Arc::from("tag"))].optional);
2526 assert!(matches!(
2527 properties[&ArrayKey::String(Arc::from("tag"))].ty.types[0],
2528 Atomic::TString
2529 ));
2530 }
2531
2532 #[test]
2533 fn substitute_callable_params_and_return() {
2534 use crate::atomic::FnParam;
2535 let ty = Type::single(Atomic::TCallable {
2536 params: Some(Box::new([FnParam {
2537 name: Name::new("x"),
2538 ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
2539 out_ty: None,
2540 default: None,
2541 is_variadic: false,
2542 is_byref: false,
2543 is_optional: false,
2544 }])),
2545 return_type: Some(Box::new(t_param("T"))),
2546 });
2547 let result = ty.substitute_templates(&bindings_t_string());
2548 let Atomic::TCallable {
2549 params,
2550 return_type,
2551 } = &result.types[0]
2552 else {
2553 panic!("expected TCallable");
2554 };
2555 let param_ty = params.as_ref().unwrap()[0].ty.as_ref().unwrap();
2556 let param_union = param_ty.to_union();
2557 assert!(matches!(param_union.types[0], Atomic::TString));
2558 let ret = return_type.as_ref().unwrap();
2559 assert!(matches!(ret.types[0], Atomic::TString));
2560 }
2561
2562 #[test]
2563 fn substitute_callable_bare_no_panic() {
2564 let ty = Type::single(Atomic::TCallable {
2566 params: None,
2567 return_type: None,
2568 });
2569 let result = ty.substitute_templates(&bindings_t_string());
2570 assert!(matches!(
2571 result.types[0],
2572 Atomic::TCallable {
2573 params: None,
2574 return_type: None
2575 }
2576 ));
2577 }
2578
2579 #[test]
2580 fn substitute_closure_params_return_and_this() {
2581 use crate::atomic::FnParam;
2582 let ty = Type::single(Atomic::TClosure {
2583 data: Box::new(crate::atomic::ClosureData {
2584 params: Box::new([FnParam {
2585 name: Name::new("a"),
2586 ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
2587 out_ty: None,
2588 default: Some(crate::compact::SimpleType::from_union(t_param("T"))),
2589 is_variadic: true,
2590 is_byref: true,
2591 is_optional: true,
2592 }]),
2593 return_type: t_param("T"),
2594 this_type: Some(t_param("T")),
2595 }),
2596 });
2597 let result = ty.substitute_templates(&bindings_t_string());
2598 let Atomic::TClosure { data } = &result.types[0] else {
2599 panic!("expected TClosure");
2600 };
2601 let (params, return_type, this_type) = (&data.params, &data.return_type, &data.this_type);
2602 let p = ¶ms[0];
2603 let ty_union = p.ty.as_ref().unwrap().to_union();
2604 let default_union = p.default.as_ref().unwrap().to_union();
2605 assert!(matches!(ty_union.types[0], Atomic::TString));
2606 assert!(matches!(default_union.types[0], Atomic::TString));
2607 assert!(p.is_variadic);
2609 assert!(p.is_byref);
2610 assert!(p.is_optional);
2611 assert!(matches!(return_type.types[0], Atomic::TString));
2612 assert!(matches!(
2613 this_type.as_ref().unwrap().types[0],
2614 Atomic::TString
2615 ));
2616 }
2617
2618 #[test]
2619 fn substitute_conditional_all_branches() {
2620 let ty = Type::single(conditional(
2621 None,
2622 t_param("T"),
2623 t_param("T"),
2624 Type::single(Atomic::TInt),
2625 ));
2626 let result = ty.substitute_templates(&bindings_t_string());
2627 let Atomic::TConditional { data } = &result.types[0] else {
2628 panic!("expected TConditional");
2629 };
2630 let (subject, if_true, if_false) = (&data.subject, &data.if_true, &data.if_false);
2631 assert!(matches!(subject.types[0], Atomic::TString));
2632 assert!(matches!(if_true.types[0], Atomic::TString));
2633 assert!(matches!(if_false.types[0], Atomic::TInt));
2634 }
2635
2636 #[test]
2637 fn resolve_conditional_is_null_non_null_arg() {
2638 let ty = Type::single(conditional(
2639 Some(Name::new("x")),
2640 Type::single(Atomic::TNull),
2641 Type::single(Atomic::TInt),
2642 Type::single(Atomic::TString),
2643 ));
2644 let result = ty.resolve_conditional_returns(|name| {
2645 if name == "x" {
2646 Some(Type::single(Atomic::TString)) } else {
2648 None
2649 }
2650 });
2651 assert!(result.types.len() == 1);
2652 assert!(matches!(result.types[0], Atomic::TString));
2653 }
2654
2655 #[test]
2656 fn resolve_conditional_is_null_null_arg() {
2657 let ty = Type::single(conditional(
2658 Some(Name::new("x")),
2659 Type::single(Atomic::TNull),
2660 Type::single(Atomic::TInt),
2661 Type::single(Atomic::TString),
2662 ));
2663 let result = ty.resolve_conditional_returns(|name| {
2664 if name == "x" {
2665 Some(Type::single(Atomic::TNull)) } else {
2667 None
2668 }
2669 });
2670 assert!(result.types.len() == 1);
2671 assert!(matches!(result.types[0], Atomic::TInt));
2672 }
2673
2674 #[test]
2675 fn resolve_conditional_is_null_nullable_arg_widens_to_branch_union() {
2676 let mut nullable_str = Type::single(Atomic::TString);
2677 nullable_str.add_type(Atomic::TNull);
2678 let ty = Type::single(conditional(
2679 Some(Name::new("x")),
2680 Type::single(Atomic::TNull),
2681 Type::single(Atomic::TInt),
2682 Type::single(Atomic::TString),
2683 ));
2684 let result = ty.resolve_conditional_returns(|name| {
2685 if name == "x" {
2686 Some(nullable_str.clone())
2687 } else {
2688 None
2689 }
2690 });
2691 assert_eq!(result.types.len(), 2);
2693 assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
2694 assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
2695 }
2696
2697 #[test]
2698 fn resolve_conditional_nested_widens_inner_branch() {
2699 let inner = Type::single(conditional(
2702 Some(Name::new("x")),
2703 Type::single(Atomic::TString),
2704 Type::single(Atomic::TString),
2705 Type::single(Atomic::TFloat),
2706 ));
2707 let ty = Type::single(conditional(
2708 Some(Name::new("x")),
2709 Type::single(Atomic::TNull),
2710 Type::single(Atomic::TInt),
2711 inner,
2712 ));
2713 let result = ty.resolve_conditional_returns(|_| None);
2715 assert!(
2716 result
2717 .types
2718 .iter()
2719 .all(|t| !matches!(t, Atomic::TConditional { .. })),
2720 "no TConditional should survive: {:?}",
2721 result.types
2722 );
2723 assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
2724 assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
2725 assert!(result.types.iter().any(|t| matches!(t, Atomic::TFloat)));
2726 }
2727
2728 #[test]
2729 fn resolve_conditional_nested_resolves_inner_branch() {
2730 let inner = Type::single(conditional(
2734 Some(Name::new("x")),
2735 Type::single(Atomic::TString),
2736 Type::single(Atomic::TString),
2737 Type::single(Atomic::TFloat),
2738 ));
2739 let ty = Type::single(conditional(
2740 Some(Name::new("x")),
2741 Type::single(Atomic::TNull),
2742 Type::single(Atomic::TInt),
2743 inner,
2744 ));
2745 let result = ty.resolve_conditional_returns(|name| {
2747 if name == "x" {
2748 Some(Type::single(Atomic::TString))
2749 } else {
2750 None
2751 }
2752 });
2753 assert!(
2754 result
2755 .types
2756 .iter()
2757 .all(|t| !matches!(t, Atomic::TConditional { .. })),
2758 "no TConditional should survive: {:?}",
2759 result.types
2760 );
2761 assert_eq!(result.types.len(), 1);
2762 assert!(matches!(result.types[0], Atomic::TString));
2763 }
2764
2765 #[test]
2766 fn substitute_intersection_parts() {
2767 let ty = Type::single(Atomic::TIntersection {
2768 parts: vec_to_type_params(vec![
2769 Type::single(Atomic::TNamedObject {
2770 fqcn: Name::new("Countable"),
2771 type_params: empty_type_params(),
2772 }),
2773 t_param("T"),
2774 ]),
2775 });
2776 let result = ty.substitute_templates(&bindings_t_string());
2777 let Atomic::TIntersection { parts } = &result.types[0] else {
2778 panic!("expected TIntersection");
2779 };
2780 assert_eq!(parts.len(), 2);
2781 assert!(matches!(parts[0].types[0], Atomic::TNamedObject { .. }));
2782 assert!(matches!(parts[1].types[0], Atomic::TString));
2783 }
2784
2785 #[test]
2786 fn substitute_no_template_params_identity() {
2787 let ty = Type::single(Atomic::TInt);
2788 let result = ty.substitute_templates(&bindings_t_string());
2789 assert!(matches!(result.types[0], Atomic::TInt));
2790 }
2791}