1use rustc_hash::FxHashMap;
2use serde::{Deserialize, Serialize};
3use smallvec::SmallVec;
4use std::sync::{Arc, OnceLock};
5
6use crate::atomic::{ArrayKey, Atomic, KeyedProperties, KeyedProperty};
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
75type IntBounds = (Option<i64>, Option<i64>);
76
77fn int_bounds(a: &Atomic) -> Option<IntBounds> {
79 match a {
80 Atomic::TInt => Some((None, None)),
81 Atomic::TLiteralInt(n) => Some((Some(*n), Some(*n))),
82 Atomic::TPositiveInt => Some((Some(1), None)),
83 Atomic::TNonNegativeInt => Some((Some(0), None)),
84 Atomic::TNegativeInt => Some((None, Some(-1))),
85 Atomic::TIntRange { min, max } => Some((*min, *max)),
86 _ => None,
87 }
88}
89
90fn bounds_contain(outer: IntBounds, inner: IntBounds) -> bool {
91 let lo_ok = match (outer.0, inner.0) {
92 (None, _) => true,
93 (Some(o), Some(i)) => o <= i,
94 (Some(_), None) => false,
95 };
96 let hi_ok = match (outer.1, inner.1) {
97 (None, _) => true,
98 (Some(o), Some(i)) => o >= i,
99 (Some(_), None) => false,
100 };
101 lo_ok && hi_ok
102}
103
104const MAX_KEYED_SHAPES: usize = 8;
111
112const MAX_GENERIC_ARRAYS: usize = 8;
115
116fn combine_generic_arrays(a: &Atomic, b: &Atomic) -> Option<Atomic> {
118 let union = |x: &Type, y: &Type| {
119 let mut t = x.clone();
120 t.merge_with(y);
121 Box::new(t)
122 };
123 Some(match (a, b) {
124 (Atomic::TArray { key: ka, value: va }, Atomic::TArray { key: kb, value: vb }) => {
125 Atomic::TArray {
126 key: union(ka, kb),
127 value: union(va, vb),
128 }
129 }
130 (
131 Atomic::TNonEmptyArray { key: ka, value: va },
132 Atomic::TNonEmptyArray { key: kb, value: vb },
133 ) => Atomic::TNonEmptyArray {
134 key: union(ka, kb),
135 value: union(va, vb),
136 },
137 (Atomic::TList { value: va }, Atomic::TList { value: vb }) => Atomic::TList {
138 value: union(va, vb),
139 },
140 (Atomic::TNonEmptyList { value: va }, Atomic::TNonEmptyList { value: vb }) => {
141 Atomic::TNonEmptyList {
142 value: union(va, vb),
143 }
144 }
145 _ => return None,
146 })
147}
148
149fn combine_keyed_arrays(a: &Atomic, b: &Atomic) -> Option<Atomic> {
154 let (
155 Atomic::TKeyedArray {
156 properties: pa,
157 is_open: oa,
158 is_list: la,
159 },
160 Atomic::TKeyedArray {
161 properties: pb,
162 is_open: ob,
163 is_list: lb,
164 },
165 ) = (a, b)
166 else {
167 return None;
168 };
169 let non_empty = |p: &KeyedProperties| p.values().any(|v| !v.optional);
170 if oa != ob || la != lb || non_empty(pa) != non_empty(pb) {
171 return None;
172 }
173 let mut properties =
174 KeyedProperties::with_capacity_and_hasher(pa.len().max(pb.len()), Default::default());
175 for (key, x) in pa.iter() {
176 let prop = match pb.get(key) {
177 Some(y) => {
178 let mut ty = x.ty.clone();
179 ty.merge_with(&y.ty);
180 KeyedProperty {
181 ty,
182 optional: x.optional || y.optional,
183 }
184 }
185 None if *oa => continue,
188 None => KeyedProperty {
189 ty: x.ty.clone(),
190 optional: true,
191 },
192 };
193 properties.insert(key.clone(), prop);
194 }
195 if !*oa {
196 for (key, y) in pb.iter() {
197 if !pa.contains_key(key) {
198 properties.insert(
199 key.clone(),
200 KeyedProperty {
201 ty: y.ty.clone(),
202 optional: true,
203 },
204 );
205 }
206 }
207 }
208 Some(Atomic::TKeyedArray {
209 properties: Arc::new(properties),
210 is_open: *oa,
211 is_list: *la,
212 })
213}
214
215impl Type {
216 pub fn empty() -> Self {
219 Self {
220 types: SmallVec::new(),
221 possibly_undefined: false,
222 from_docblock: false,
223 falsy_stripped: false,
224 possibly_absent_offset: false,
225 }
226 }
227
228 pub fn single(atomic: Atomic) -> Self {
229 let mut types = SmallVec::new();
230 types.push(atomic);
231 Self {
232 types,
233 possibly_undefined: false,
234 from_docblock: false,
235 falsy_stripped: false,
236 possibly_absent_offset: false,
237 }
238 }
239
240 pub fn mixed() -> Self {
241 Self::single(Atomic::TMixed)
242 }
243
244 pub fn void() -> Self {
245 Self::single(Atomic::TVoid)
246 }
247
248 pub fn never() -> Self {
249 Self::single(Atomic::TNever)
250 }
251
252 pub fn null() -> Self {
253 Self::single(Atomic::TNull)
254 }
255
256 pub fn bool() -> Self {
257 Self::single(Atomic::TBool)
258 }
259
260 pub fn int() -> Self {
261 Self::single(Atomic::TInt)
262 }
263
264 pub fn float() -> Self {
265 Self::single(Atomic::TFloat)
266 }
267
268 pub fn string() -> Self {
269 Self::single(Atomic::TString)
270 }
271
272 pub fn array_key() -> Self {
275 let mut u = Self::single(Atomic::TInt);
276 u.add_type(Atomic::TString);
277 u
278 }
279
280 pub fn nullable(atomic: Atomic) -> Self {
282 if matches!(atomic, Atomic::TMixed) {
284 return Self::mixed();
285 }
286 let mut types = SmallVec::new();
287 types.push(atomic);
288 types.push(Atomic::TNull);
289 Self {
290 types,
291 possibly_undefined: false,
292 from_docblock: false,
293 falsy_stripped: false,
294 possibly_absent_offset: false,
295 }
296 }
297
298 pub fn from_vec(atomics: Vec<Atomic>) -> Self {
300 let mut u = Self::empty();
301 for a in atomics {
302 u.add_type(a);
303 }
304 u
305 }
306
307 pub fn is_empty(&self) -> bool {
310 self.types.is_empty()
311 }
312
313 pub fn is_single(&self) -> bool {
314 self.types.len() == 1
315 }
316
317 pub fn is_nullable(&self) -> bool {
318 self.types.iter().any(|t| matches!(t, Atomic::TNull))
319 }
320
321 pub fn is_array_key(&self) -> bool {
326 self.types.len() == 2
327 && self.types.iter().any(|t| matches!(t, Atomic::TInt))
328 && self.types.iter().any(|t| matches!(t, Atomic::TString))
329 }
330
331 pub fn is_mixed(&self) -> bool {
332 self.types.iter().any(|t| match t {
333 Atomic::TMixed => true,
334 Atomic::TTemplateParam { as_type, .. } => as_type.is_mixed(),
335 _ => false,
336 })
337 }
338
339 pub fn is_mixed_not_template(&self) -> bool {
344 self.is_mixed()
345 && !self
346 .types
347 .iter()
348 .any(|t| matches!(t, Atomic::TTemplateParam { .. }))
349 }
350
351 pub fn is_never(&self) -> bool {
352 self.types.iter().all(|t| matches!(t, Atomic::TNever)) && !self.types.is_empty()
353 }
354
355 pub fn clone_validity(&self) -> CloneValidity {
358 if self.types.is_empty() {
359 return CloneValidity::Unknown;
360 }
361 let mut has_non_object = false;
362 let mut has_other = false; for t in &self.types {
364 match t {
365 Atomic::TTemplateParam { as_type, .. } => match as_type.clone_validity() {
366 CloneValidity::Invalid => has_non_object = true,
367 CloneValidity::PossiblyInvalid => {
368 has_non_object = true;
369 has_other = true;
370 }
371 CloneValidity::Cloneable | CloneValidity::Unknown => has_other = true,
372 },
373 other if other.is_definitely_non_object() => has_non_object = true,
374 _ => has_other = true,
375 }
376 }
377 match (has_non_object, has_other) {
378 (true, false) => CloneValidity::Invalid,
379 (true, true) => CloneValidity::PossiblyInvalid,
380 _ => CloneValidity::Cloneable,
381 }
382 }
383
384 pub fn is_void(&self) -> bool {
385 self.is_single() && matches!(self.types[0], Atomic::TVoid)
386 }
387
388 pub fn can_be_falsy(&self) -> bool {
389 self.types.iter().any(|t| t.can_be_falsy())
390 }
391
392 pub fn can_be_truthy(&self) -> bool {
393 self.types.iter().any(|t| t.can_be_truthy())
394 }
395
396 pub fn contains<F: Fn(&Atomic) -> bool>(&self, f: F) -> bool {
397 self.types.iter().any(f)
398 }
399
400 pub fn has_named_object(&self, fqcn: &str) -> bool {
401 self.types.iter().any(|t| match t {
402 Atomic::TNamedObject { fqcn: f, .. } => f.as_ref() == fqcn,
403 _ => false,
404 })
405 }
406
407 pub fn add_type(&mut self, atomic: Atomic) {
412 if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
414 return;
415 }
416
417 if matches!(atomic, Atomic::TMixed) {
419 self.types.clear();
420 self.types.push(Atomic::TMixed);
421 return;
422 }
423
424 let atomic = if let Atomic::TConditional { data } = &atomic {
427 let (if_true, if_false) = (&data.if_true, &data.if_false);
428 let mut simplified_true = Type::empty();
429 for t in &if_true.types {
430 simplified_true.add_type(t.clone());
431 }
432 let mut simplified_false = Type::empty();
433 for t in &if_false.types {
434 simplified_false.add_type(t.clone());
435 }
436 if simplified_true == simplified_false {
437 for t in simplified_true.types {
438 self.add_type(t);
439 }
440 return;
441 }
442 atomic
443 } else {
444 atomic
445 };
446
447 if self.types.contains(&atomic) {
448 return;
449 }
450 self.add_absent_type(atomic);
451 }
452
453 fn add_absent_type(&mut self, atomic: Atomic) {
455 let mut atomic = atomic;
458 if matches!(atomic, Atomic::TKeyedArray { .. })
459 && self
460 .types
461 .iter()
462 .filter(|t| matches!(t, Atomic::TKeyedArray { .. }))
463 .count()
464 >= MAX_KEYED_SHAPES
465 {
466 if let Some((idx, combined)) = self
467 .types
468 .iter()
469 .enumerate()
470 .find_map(|(i, t)| combine_keyed_arrays(t, &atomic).map(|c| (i, c)))
471 {
472 self.types.remove(idx);
473 if self.types.contains(&combined) {
474 return;
475 }
476 atomic = combined;
477 }
478 }
479
480 if matches!(
481 atomic,
482 Atomic::TArray { .. }
483 | Atomic::TNonEmptyArray { .. }
484 | Atomic::TList { .. }
485 | Atomic::TNonEmptyList { .. }
486 ) && self
487 .types
488 .iter()
489 .filter(|t| std::mem::discriminant(*t) == std::mem::discriminant(&atomic))
490 .count()
491 >= MAX_GENERIC_ARRAYS
492 {
493 if let Some((idx, combined)) = self
494 .types
495 .iter()
496 .enumerate()
497 .find_map(|(i, t)| combine_generic_arrays(t, &atomic).map(|c| (i, c)))
498 {
499 self.types.remove(idx);
500 if self.types.contains(&combined) {
501 return;
502 }
503 atomic = combined;
504 }
505 }
506
507 if let Some(new_bounds) = int_bounds(&atomic) {
510 if self
511 .types
512 .iter()
513 .any(|t| int_bounds(t).is_some_and(|b| bounds_contain(b, new_bounds)))
514 {
515 return;
516 }
517 self.types
518 .retain(|t| !int_bounds(t).is_some_and(|b| bounds_contain(new_bounds, b)));
519 }
520 if let Atomic::TLiteralString(_) = &atomic {
522 if self.types.iter().any(|t| matches!(t, Atomic::TString)) {
523 return;
524 }
525 }
526 if matches!(atomic, Atomic::TNonEmptyString)
528 && self.types.iter().any(|t| matches!(t, Atomic::TString))
529 {
530 return;
531 }
532 if matches!(atomic, Atomic::TTrue | Atomic::TFalse)
534 && self.types.iter().any(|t| matches!(t, Atomic::TBool))
535 {
536 return;
537 }
538 if matches!(atomic, Atomic::TTrue) && self.types.iter().any(|t| matches!(t, Atomic::TFalse))
541 {
542 self.types.retain(|t| !matches!(t, Atomic::TFalse));
543 self.types.push(Atomic::TBool);
544 return;
545 }
546 if matches!(atomic, Atomic::TFalse) && self.types.iter().any(|t| matches!(t, Atomic::TTrue))
547 {
548 self.types.retain(|t| !matches!(t, Atomic::TTrue));
549 self.types.push(Atomic::TBool);
550 return;
551 }
552 if matches!(atomic, Atomic::TString) {
554 self.types
555 .retain(|t| !matches!(t, Atomic::TLiteralString(_) | Atomic::TNonEmptyString));
556 }
557 if matches!(atomic, Atomic::TBool) {
559 self.types
560 .retain(|t| !matches!(t, Atomic::TTrue | Atomic::TFalse));
561 }
562
563 if matches!(atomic, Atomic::TNever) {
565 if !self.types.is_empty() {
566 return;
567 }
568 } else {
569 self.types.retain(|t| !matches!(t, Atomic::TNever));
570 }
571
572 if let Atomic::TKeyedArray {
578 properties,
579 is_open,
580 ..
581 } = &atomic
582 {
583 if properties.is_empty() && !is_open {
584 for existing in &self.types {
585 match existing {
586 Atomic::TArray { .. }
587 | Atomic::TNonEmptyArray { .. }
588 | Atomic::TList { .. }
589 | Atomic::TNonEmptyList { .. } => {
590 return; }
592 _ => {}
593 }
594 }
595 }
596 }
597
598 let is_generic_array_or_list = matches!(
601 &atomic,
602 Atomic::TArray { .. }
603 | Atomic::TNonEmptyArray { .. }
604 | Atomic::TList { .. }
605 | Atomic::TNonEmptyList { .. }
606 );
607 if is_generic_array_or_list {
608 self.types.retain(|t| {
609 if let Atomic::TKeyedArray {
610 properties,
611 is_open,
612 ..
613 } = t
614 {
615 !properties.is_empty() || *is_open
616 } else {
617 true
618 }
619 });
620 }
621
622 self.types.push(atomic);
623 }
624
625 pub fn remove_null(&self) -> Type {
629 self.filter(|t| !matches!(t, Atomic::TNull))
630 }
631
632 pub fn remove_false(&self) -> Type {
635 let mut result = self.filter(|t| !matches!(t, Atomic::TFalse | Atomic::TBool));
636 if self.types.iter().any(|t| matches!(t, Atomic::TBool)) {
637 result.add_type(Atomic::TTrue);
638 }
639 result
640 }
641
642 pub fn remove_true(&self) -> Type {
645 let mut result = self.filter(|t| !matches!(t, Atomic::TTrue | Atomic::TBool));
646 if self.types.iter().any(|t| matches!(t, Atomic::TBool)) {
647 result.add_type(Atomic::TFalse);
648 }
649 result
650 }
651
652 pub fn core_type(&self) -> Type {
654 self.remove_null().remove_false()
655 }
656
657 pub fn narrow_to_truthy(&self) -> Type {
659 if self.is_mixed_not_template() {
660 return Type::mixed();
661 }
662 let mut result = Type::empty();
663 result.from_docblock = self.from_docblock;
664 for t in &self.types {
665 match t {
666 Atomic::TTemplateParam { .. } => result.add_type(t.clone()),
670 Atomic::TLiteralInt(0)
672 | Atomic::TLiteralFloat(0, 0)
673 | Atomic::TNull
674 | Atomic::TFalse => {}
675 Atomic::TLiteralString(s) if s.as_ref() == "" || s.as_ref() == "0" => {}
676 Atomic::TBool => result.add_type(Atomic::TTrue),
678 Atomic::TArray { key, value } => result.add_type(Atomic::TNonEmptyArray {
680 key: key.clone(),
681 value: value.clone(),
682 }),
683 Atomic::TList { value } => result.add_type(Atomic::TNonEmptyList {
684 value: value.clone(),
685 }),
686 Atomic::TString => result.add_type(Atomic::TNonEmptyString),
690 Atomic::TNonNegativeInt => result.add_type(Atomic::TPositiveInt),
695 Atomic::TIntRange { min: Some(0), max } if max.is_none_or(|m| m >= 1) => {
696 let atom = if max.is_none() {
697 Atomic::TPositiveInt
698 } else {
699 Atomic::TIntRange {
700 min: Some(1),
701 max: *max,
702 }
703 };
704 result.add_type(atom);
705 }
706 Atomic::TIntRange { min, max: Some(0) } => {
708 let atom = match min {
709 None => Atomic::TNegativeInt,
710 Some(n) if *n <= -1 => Atomic::TIntRange {
711 min: *min,
712 max: Some(-1),
713 },
714 _ => continue, };
716 result.add_type(atom);
717 }
718 t if !t.can_be_truthy() => {}
720 _ => result.add_type(t.clone()),
721 }
722 }
723 result
724 }
725
726 pub fn narrow_to_falsy(&self) -> Type {
728 if self.is_mixed_not_template() {
729 return Type::from_vec(vec![
730 Atomic::TNull,
731 Atomic::TFalse,
732 Atomic::TLiteralInt(0),
733 Atomic::TLiteralString("".into()),
734 ]);
735 }
736 let mut result = Type::empty();
737 result.from_docblock = self.from_docblock;
738 for t in &self.types {
739 match t {
740 Atomic::TTemplateParam { .. } => result.add_type(t.clone()),
745 Atomic::TBool => result.add_type(Atomic::TFalse),
747 Atomic::TInt => result.add_type(Atomic::TLiteralInt(0)),
749 Atomic::TFloat => result.add_type(Atomic::TLiteralFloat(0, 0)),
751 Atomic::TString => {
753 result.add_type(Atomic::TLiteralString("".into()));
754 result.add_type(Atomic::TLiteralString("0".into()));
755 }
756 Atomic::TNumericString => result.add_type(Atomic::TLiteralString("0".into())),
758 Atomic::TNonNegativeInt => result.add_type(Atomic::TLiteralInt(0)),
760 Atomic::TIntRange {
762 min: Some(0),
763 max: Some(_) | None,
764 } => result.add_type(Atomic::TLiteralInt(0)),
765 Atomic::TIntRange { max: Some(0), .. } => result.add_type(Atomic::TLiteralInt(0)),
767 t if !t.can_be_falsy() => {} _ => result.add_type(t.clone()),
769 }
770 }
771 result
772 }
773
774 pub fn narrow_instanceof(&self, class: &str) -> Type {
780 let narrowed_ty = Atomic::TNamedObject {
781 fqcn: class.into(),
782 type_params: empty_type_params(),
783 };
784 let has_object = self.types.iter().any(|t| {
786 matches!(
787 t,
788 Atomic::TObject
789 | Atomic::TObjectShape { .. }
790 | Atomic::TNamedObject { .. }
791 | Atomic::TMixed
792 | Atomic::TNull )
794 });
795 if has_object || self.is_empty() {
796 Type::single(narrowed_ty)
797 } else {
798 Type::single(narrowed_ty)
801 }
802 }
803
804 pub fn narrow_to_string(&self) -> Type {
808 self.filter_replacing(
809 |t| t.is_string() || matches!(t, Atomic::TTemplateParam { .. }),
810 |t| matches!(t, Atomic::TMixed | Atomic::TScalar),
811 Atomic::TString,
812 )
813 .with_callable_form(self, Atomic::TCallableString)
814 }
815
816 pub fn narrow_to_int(&self) -> Type {
818 self.filter_replacing(
819 |t| t.is_int() || matches!(t, Atomic::TTemplateParam { .. }),
820 |t| matches!(t, Atomic::TMixed | Atomic::TScalar | Atomic::TNumeric),
821 Atomic::TInt,
822 )
823 }
824
825 pub fn narrow_to_float(&self) -> Type {
827 self.filter_replacing(
828 |t| {
829 matches!(
830 t,
831 Atomic::TFloat
832 | Atomic::TIntegralFloat
833 | Atomic::TLiteralFloat(..)
834 | Atomic::TTemplateParam { .. }
835 )
836 },
837 |t| matches!(t, Atomic::TMixed | Atomic::TScalar | Atomic::TNumeric),
838 Atomic::TFloat,
839 )
840 }
841
842 pub fn narrow_to_bool(&self) -> Type {
844 self.filter_replacing(
845 |t| {
846 matches!(
847 t,
848 Atomic::TBool | Atomic::TTrue | Atomic::TFalse | Atomic::TTemplateParam { .. }
849 )
850 },
851 |t| matches!(t, Atomic::TMixed | Atomic::TScalar),
852 Atomic::TBool,
853 )
854 }
855
856 pub fn narrow_to_null(&self) -> Type {
858 self.filter_replacing(
859 |t| matches!(t, Atomic::TNull | Atomic::TTemplateParam { .. }),
860 |t| matches!(t, Atomic::TMixed),
861 Atomic::TNull,
862 )
863 }
864
865 pub fn narrow_to_array(&self) -> Type {
867 self.filter_replacing(
868 |t| t.is_array() || matches!(t, Atomic::TTemplateParam { .. }),
869 |t| matches!(t, Atomic::TMixed),
870 Atomic::TArray {
871 key: Box::new(Type::mixed()),
872 value: Box::new(Type::mixed()),
873 },
874 )
875 .with_callable_form(self, callable_array())
876 }
877
878 pub fn widen_nested_non_empty(&self) -> Type {
881 fn relax_all(ty: &Type) -> Type {
882 map_atoms(ty, |a| match a {
883 Atomic::TNonEmptyList { value } => Atomic::TList {
884 value: Box::new(relax_all(value)),
885 },
886 Atomic::TNonEmptyArray { key, value } => Atomic::TArray {
887 key: key.clone(),
888 value: Box::new(relax_all(value)),
889 },
890 other => map_values(other, relax_all),
891 })
892 }
893 fn map_values(atomic: &Atomic, f: fn(&Type) -> Type) -> Atomic {
894 match atomic {
895 Atomic::TArray { key, value } => Atomic::TArray {
896 key: key.clone(),
897 value: Box::new(f(value)),
898 },
899 Atomic::TList { value } => Atomic::TList {
900 value: Box::new(f(value)),
901 },
902 Atomic::TNonEmptyArray { key, value } => Atomic::TNonEmptyArray {
903 key: key.clone(),
904 value: Box::new(f(value)),
905 },
906 Atomic::TNonEmptyList { value } => Atomic::TNonEmptyList {
907 value: Box::new(f(value)),
908 },
909 Atomic::TKeyedArray {
910 properties,
911 is_open,
912 is_list,
913 } => Atomic::TKeyedArray {
914 properties: Arc::new(
915 properties
916 .iter()
917 .map(|(k, p)| {
918 (
919 k.clone(),
920 crate::atomic::KeyedProperty {
921 ty: f(&p.ty),
922 optional: p.optional,
923 },
924 )
925 })
926 .collect(),
927 ),
928 is_open: *is_open,
929 is_list: *is_list,
930 },
931 other => other.clone(),
932 }
933 }
934 fn map_atoms(ty: &Type, f: impl Fn(&Atomic) -> Atomic) -> Type {
935 let mut result = Type::empty();
936 result.possibly_undefined = ty.possibly_undefined;
937 result.from_docblock = ty.from_docblock;
938 for atomic in &ty.types {
939 result.add_type(f(atomic));
940 }
941 result
942 }
943 map_atoms(self, |a| map_values(a, relax_all))
944 }
945
946 pub fn narrow_to_non_empty_collection(&self) -> Type {
949 let mut out = Type::empty();
950 out.from_docblock = self.from_docblock;
951 for t in &self.types {
952 match t {
953 Atomic::TArray { key, value } => out.add_type(Atomic::TNonEmptyArray {
954 key: key.clone(),
955 value: value.clone(),
956 }),
957 Atomic::TList { value } => out.add_type(Atomic::TNonEmptyList {
958 value: value.clone(),
959 }),
960 Atomic::TKeyedArray {
961 properties,
962 is_open: false,
963 ..
964 } if properties.is_empty() => {}
965 _ => out.add_type(t.clone()),
966 }
967 }
968 out
969 }
970
971 pub fn narrow_to_empty_collection(&self) -> Type {
981 let mut out = Type::empty();
982 out.from_docblock = self.from_docblock;
983 for t in &self.types {
984 match t {
985 Atomic::TNonEmptyArray { .. } | Atomic::TNonEmptyList { .. } => {}
986 Atomic::TArray { .. } | Atomic::TList { .. } => {
987 out.add_type(Atomic::TKeyedArray {
988 properties: Arc::default(),
989 is_open: false,
990 is_list: true,
991 });
992 }
993 _ => out.add_type(t.clone()),
994 }
995 }
996 out
997 }
998
999 pub fn narrow_to_list(&self) -> Type {
1011 let mut out = Type::empty();
1012 out.from_docblock = self.from_docblock;
1013 for t in &self.types {
1014 match t {
1015 Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => out.add_type(t.clone()),
1016 Atomic::TArray { key, value } if !key.narrow_to_int().is_empty() => {
1022 out.add_type(Atomic::TList {
1023 value: value.clone(),
1024 });
1025 }
1026 Atomic::TNonEmptyArray { key, value } if !key.narrow_to_int().is_empty() => {
1027 out.add_type(Atomic::TNonEmptyList {
1028 value: value.clone(),
1029 });
1030 }
1031 Atomic::TKeyedArray { is_list: true, .. } => out.add_type(t.clone()),
1032 Atomic::TMixed => out.add_type(Atomic::TList {
1033 value: Box::new(Type::mixed()),
1034 }),
1035 _ => {}
1036 }
1037 }
1038 if out.is_empty() {
1039 self.filter(|t| matches!(t, Atomic::TList { .. } | Atomic::TNonEmptyList { .. }))
1040 } else {
1041 out
1042 }
1043 }
1044
1045 pub fn narrow_to_object(&self) -> Type {
1050 let mut out = Type::empty();
1051 for t in &self.types {
1052 if matches!(t, Atomic::TMixed) {
1053 out.add_type(Atomic::TObject);
1054 } else if t.is_object() || matches!(t, Atomic::TTemplateParam { .. }) {
1055 out.add_type(t.clone());
1056 }
1057 }
1058 if out.types.is_empty() {
1059 self.filter(|t| t.is_object())
1060 .with_callable_form(self, Atomic::TObject)
1061 } else {
1062 out.with_callable_form(self, Atomic::TObject)
1063 }
1064 }
1065
1066 fn with_callable_form(mut self, source: &Type, form: Atomic) -> Type {
1069 if source
1070 .types
1071 .iter()
1072 .any(|t| matches!(t, Atomic::TCallable { .. }))
1073 {
1074 self.add_type(form);
1075 }
1076 self
1077 }
1078
1079 pub fn narrow_to_not_callable(&self) -> Type {
1082 let callable_array = callable_array();
1083 self.filter(|t| {
1084 !t.is_callable()
1085 && *t != callable_array
1086 && !matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.eq_ignore_ascii_case("Closure"))
1087 })
1088 }
1089
1090 pub fn narrow_to_callable(&self) -> Type {
1097 let narrowed = self.filter(|t| {
1098 t.is_callable()
1099 || t.is_string()
1100 || t.is_array()
1101 || t.is_object()
1102 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1103 });
1104 let mut result = Type::empty();
1111 result.possibly_undefined = narrowed.possibly_undefined;
1112 result.from_docblock = narrowed.from_docblock;
1113 for atomic in narrowed.types {
1114 if matches!(atomic, Atomic::TObject | Atomic::TObjectShape { .. }) {
1115 result.add_type(Atomic::TCallable {
1116 params: None,
1117 return_type: None,
1118 is_pure: false,
1119 });
1120 } else {
1121 result.add_type(atomic);
1122 }
1123 }
1124 result
1125 }
1126
1127 pub fn narrow_to_scalar(&self) -> Type {
1129 self.filter_replacing(
1130 |t| {
1131 t.is_string()
1132 || t.is_int()
1133 || matches!(
1134 t,
1135 Atomic::TFloat
1136 | Atomic::TIntegralFloat
1137 | Atomic::TLiteralFloat(..)
1138 | Atomic::TBool
1139 | Atomic::TTrue
1140 | Atomic::TFalse
1141 | Atomic::TScalar
1142 | Atomic::TNumeric
1143 | Atomic::TNumericString
1144 | Atomic::TTemplateParam { .. }
1145 )
1146 },
1147 |t| matches!(t, Atomic::TMixed),
1148 Atomic::TScalar,
1149 )
1150 }
1151
1152 pub fn narrow_to_iterable(&self) -> Type {
1155 self.filter(|t| {
1156 t.is_array()
1157 || t.is_object()
1158 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1159 })
1160 }
1161
1162 pub fn narrow_to_countable(&self) -> Type {
1165 self.filter(|t| {
1166 t.is_array()
1167 || t.is_object()
1168 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1169 })
1170 }
1171
1172 pub fn narrow_to_resource(&self) -> Type {
1176 self.filter(|t| matches!(t, Atomic::TMixed))
1178 }
1179
1180 pub fn narrow_to_class_string(&self) -> Type {
1185 let mut out = Type::empty();
1186 out.from_docblock = self.from_docblock;
1187 for t in &self.types {
1188 match t {
1189 Atomic::TClassString(_) => out.add_type(t.clone()),
1190 _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
1191 out.add_type(Atomic::TClassString(None));
1192 }
1193 _ => {}
1194 }
1195 }
1196 out
1197 }
1198
1199 pub fn narrow_to_interface_string(&self) -> Type {
1204 let mut out = Type::empty();
1205 out.from_docblock = self.from_docblock;
1206 for t in &self.types {
1207 match t {
1208 Atomic::TInterfaceString(_) => out.add_type(t.clone()),
1209 Atomic::TClassString(name) => {
1213 out.add_type(Atomic::TInterfaceString(*name));
1214 }
1215 _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
1216 out.add_type(Atomic::TInterfaceString(None));
1217 }
1218 _ => {}
1219 }
1220 }
1221 out
1222 }
1223
1224 pub fn merge(a: &Type, b: &Type) -> Type {
1229 if b.types.is_empty() {
1231 let mut result = a.clone();
1232 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1233 return result;
1234 }
1235 if a.types.is_empty() {
1237 let mut result = b.clone();
1238 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1239 return result;
1240 }
1241 if a.types.len() == 1 && matches!(a.types[0], Atomic::TMixed) {
1243 let mut result = a.clone();
1244 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1245 return result;
1246 }
1247 if b.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1249 return Type {
1250 types: smallvec::smallvec![Atomic::TMixed],
1251 possibly_undefined: a.possibly_undefined || b.possibly_undefined,
1252 from_docblock: a.from_docblock || b.from_docblock,
1253 falsy_stripped: false,
1254 possibly_absent_offset: false,
1255 };
1256 }
1257 let mut result = a.clone();
1258 result.merge_with(b);
1259 result
1260 }
1261
1262 pub fn merge_with(&mut self, other: &Type) {
1264 if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1265 self.possibly_undefined |= other.possibly_undefined;
1266 return;
1267 }
1268 if other.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1269 self.types.clear();
1270 self.types.push(Atomic::TMixed);
1271 self.possibly_undefined |= other.possibly_undefined;
1272 return;
1273 }
1274 for atomic in &other.types {
1275 if matches!(atomic, Atomic::TConditional { .. }) {
1277 self.add_type(atomic.clone());
1278 } else if !self.types.contains(atomic)
1279 && !self.types.iter().any(|t| matches!(t, Atomic::TMixed))
1280 {
1281 self.add_absent_type(atomic.clone());
1282 }
1283 }
1284 self.possibly_undefined |= other.possibly_undefined;
1285 }
1286
1287 pub fn intersect_with(&self, other: &Type) -> Type {
1291 if self.is_mixed() {
1292 return other.clone();
1293 }
1294 if other.is_mixed() {
1295 return self.clone();
1296 }
1297 let mut result = Type::empty();
1305 for a in &self.types {
1306 for b in &other.types {
1307 if a == b {
1308 result.add_type(a.clone());
1309 } else if atomic_subtype(b, a) {
1310 result.add_type(b.clone());
1311 } else if atomic_subtype(a, b) {
1312 result.add_type(a.clone());
1313 }
1314 }
1315 }
1316 if result.is_empty() {
1317 Type::never()
1318 } else {
1319 result
1320 }
1321 }
1322
1323 pub fn substitute_templates(&self, bindings: &FxHashMap<Name, Type>) -> Type {
1327 if bindings.is_empty() {
1328 return self.clone();
1329 }
1330 if !self.types.iter().any(atomic_may_contain_templates) {
1333 return self.clone();
1334 }
1335 let mut result = Type::empty();
1336 result.possibly_undefined = self.possibly_undefined;
1337 result.from_docblock = self.from_docblock;
1338 for atomic in &self.types {
1339 match atomic {
1340 Atomic::TTemplateParam { name, .. } => {
1341 if let Some(resolved) = bindings.get(name) {
1342 for t in &resolved.types {
1343 result.add_type(t.clone());
1344 }
1345 } else {
1346 result.add_type(atomic.clone());
1347 }
1348 }
1349 Atomic::TArray { key, value } => {
1350 result.add_type(Atomic::TArray {
1351 key: Box::new(key.substitute_templates(bindings)),
1352 value: Box::new(value.substitute_templates(bindings)),
1353 });
1354 }
1355 Atomic::TList { value } => {
1356 result.add_type(Atomic::TList {
1357 value: Box::new(value.substitute_templates(bindings)),
1358 });
1359 }
1360 Atomic::TNonEmptyArray { key, value } => {
1361 result.add_type(Atomic::TNonEmptyArray {
1362 key: Box::new(key.substitute_templates(bindings)),
1363 value: Box::new(value.substitute_templates(bindings)),
1364 });
1365 }
1366 Atomic::TNonEmptyList { value } => {
1367 result.add_type(Atomic::TNonEmptyList {
1368 value: Box::new(value.substitute_templates(bindings)),
1369 });
1370 }
1371 Atomic::TKeyedArray {
1372 properties,
1373 is_open,
1374 is_list,
1375 } => {
1376 use crate::atomic::KeyedProperty;
1377 let new_props = properties
1378 .iter()
1379 .map(|(k, prop)| {
1380 (
1381 k.clone(),
1382 KeyedProperty {
1383 ty: prop.ty.substitute_templates(bindings),
1384 optional: prop.optional,
1385 },
1386 )
1387 })
1388 .collect();
1389 result.add_type(Atomic::TKeyedArray {
1390 properties: Arc::new(new_props),
1391 is_open: *is_open,
1392 is_list: *is_list,
1393 });
1394 }
1395 Atomic::TCallable {
1396 params,
1397 return_type,
1398 is_pure,
1399 } => {
1400 result.add_type(Atomic::TCallable {
1401 params: params.as_ref().map(|ps| {
1402 Box::new(
1403 ps.iter()
1404 .map(|p| substitute_in_fn_param(p, bindings))
1405 .collect(),
1406 )
1407 }),
1408 return_type: return_type
1409 .as_ref()
1410 .map(|r| Box::new(r.substitute_templates(bindings))),
1411 is_pure: *is_pure,
1412 });
1413 }
1414 Atomic::TClosure { data } => {
1415 result.add_type(Atomic::TClosure {
1416 data: Box::new(crate::atomic::ClosureData {
1417 params: data
1418 .params
1419 .iter()
1420 .map(|p| substitute_in_fn_param(p, bindings))
1421 .collect(),
1422 return_type: data.return_type.substitute_templates(bindings),
1423 this_type: data
1424 .this_type
1425 .as_ref()
1426 .map(|t| t.substitute_templates(bindings)),
1427 is_pure: data.is_pure,
1428 is_static: data.is_static,
1429 rejects_surplus_args: data.rejects_surplus_args,
1430 }),
1431 });
1432 }
1433 Atomic::TConditional { data } => {
1434 let param_name = &data.param_name;
1435 let new_subject = data.subject.substitute_templates(bindings);
1436 let new_if_true = data.if_true.substitute_templates(bindings);
1437 let new_if_false = data.if_false.substitute_templates(bindings);
1438
1439 let resolved = if let Some(name) = param_name {
1443 if let Some(bound) = bindings.get(name) {
1444 resolve_conditional_branch(
1445 &new_subject,
1446 bound,
1447 &new_if_true,
1448 &new_if_false,
1449 )
1450 } else {
1451 None
1452 }
1453 } else {
1454 None
1455 };
1456
1457 if let Some(branch) = resolved {
1458 for t in branch.types {
1459 result.add_type(t);
1460 }
1461 } else {
1462 result.add_type(Atomic::TConditional {
1463 data: Box::new(crate::atomic::ConditionalData {
1464 param_name: *param_name,
1465 subject: new_subject,
1466 if_true: new_if_true,
1467 if_false: new_if_false,
1468 }),
1469 });
1470 }
1471 }
1472 Atomic::TKeyOf { target } => {
1473 let new_target = target.substitute_templates(bindings);
1474 if let Some(resolved) = eval_key_of_type(&new_target) {
1475 result.merge_with(&resolved);
1476 } else {
1477 result.add_type(Atomic::TKeyOf {
1478 target: Box::new(new_target),
1479 });
1480 }
1481 }
1482 Atomic::TValueOf { target } => {
1483 let new_target = target.substitute_templates(bindings);
1484 if let Some(resolved) = eval_value_of_type(&new_target) {
1485 result.merge_with(&resolved);
1486 } else {
1487 result.add_type(Atomic::TValueOf {
1488 target: Box::new(new_target),
1489 });
1490 }
1491 }
1492 Atomic::TIntersection { parts } => {
1493 result.add_type(Atomic::TIntersection {
1494 parts: vec_to_type_params(
1495 parts
1496 .iter()
1497 .map(|p| p.substitute_templates(bindings))
1498 .collect(),
1499 ),
1500 });
1501 }
1502 Atomic::TNamedObject { fqcn, type_params } => {
1503 if type_params.is_empty() && !fqcn.contains('\\') {
1505 if let Some(resolved) = bindings.get(fqcn) {
1506 for t in &resolved.types {
1507 result.add_type(t.clone());
1508 }
1509 continue;
1510 }
1511 }
1512 let new_params: Vec<Type> = type_params
1513 .iter()
1514 .map(|p| p.substitute_templates(bindings))
1515 .collect();
1516 result.add_type(Atomic::TNamedObject {
1517 fqcn: *fqcn,
1518 type_params: vec_to_type_params(new_params),
1519 });
1520 }
1521 Atomic::TClassString(Some(param_name)) => {
1523 if let Some(resolved) = bindings.get(param_name) {
1524 for r_atomic in &resolved.types {
1525 let cls_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1526 Some(*fqcn)
1527 } else {
1528 None
1529 };
1530 result.add_type(Atomic::TClassString(cls_name));
1531 }
1532 } else {
1533 result.add_type(atomic.clone());
1534 }
1535 }
1536 Atomic::TInterfaceString(Some(param_name)) => {
1538 if let Some(resolved) = bindings.get(param_name) {
1539 for r_atomic in &resolved.types {
1540 let iface_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1541 Some(*fqcn)
1542 } else {
1543 None
1544 };
1545 result.add_type(Atomic::TInterfaceString(iface_name));
1546 }
1547 } else {
1548 result.add_type(atomic.clone());
1549 }
1550 }
1551 _ => {
1552 result.add_type(atomic.clone());
1553 }
1554 }
1555 }
1556 result
1557 }
1558
1559 pub fn resolve_conditional_returns<F>(self, lookup: F) -> Type
1565 where
1566 F: Fn(&str) -> Option<Type>,
1567 {
1568 self.resolve_conditional_inner(&lookup)
1569 }
1570
1571 fn resolve_conditional_inner<F>(self, lookup: &F) -> Type
1572 where
1573 F: Fn(&str) -> Option<Type>,
1574 {
1575 let mut result = Type::empty();
1576 for atomic in self.types {
1577 match atomic {
1578 Atomic::TConditional { ref data } => {
1579 let (param_name, subject, if_true, if_false) = (
1580 &data.param_name,
1581 &data.subject,
1582 &data.if_true,
1583 &data.if_false,
1584 );
1585 let resolved =
1586 param_name
1587 .and_then(|name| lookup(name.as_ref()))
1588 .and_then(|arg_ty| {
1589 resolve_conditional_branch(subject, &arg_ty, if_true, if_false)
1590 });
1591
1592 if let Some(branch) = resolved {
1593 for t in branch.resolve_conditional_inner(lookup).types {
1595 result.add_type(t);
1596 }
1597 } else {
1598 for t in if_true.clone().resolve_conditional_inner(lookup).types {
1601 result.add_type(t);
1602 }
1603 for t in if_false.clone().resolve_conditional_inner(lookup).types {
1604 result.add_type(t);
1605 }
1606 }
1607 }
1608 other => result.add_type(other),
1609 }
1610 }
1611 result
1612 }
1613
1614 pub fn is_subtype_structural(&self, other: &Type) -> bool {
1624 if other.is_mixed() {
1625 return true;
1626 }
1627 if self.is_never() {
1628 return true; }
1630 self.types.iter().all(|a| {
1631 let fits = |a: &Atomic| other.types.iter().any(|b| atomic_subtype(a, b));
1632 fits(a) || composite_parts(a).is_some_and(|parts| parts.iter().all(fits))
1633 })
1634 }
1635
1636 pub fn is_subtype_by_template_bounds(&self, other: &Type) -> bool {
1639 self.is_subtype_structural(other)
1640 || self.types.iter().all(|a| match a {
1641 Atomic::TTemplateParam { as_type, .. } => {
1642 as_type.is_subtype_by_template_bounds(other)
1643 }
1644 _ => other.accepts_atomic_structural(a),
1645 })
1646 }
1647
1648 pub fn accepts_atomic_structural(&self, sub: &Atomic) -> bool {
1652 if self.is_mixed() {
1653 return true;
1654 }
1655 matches!(sub, Atomic::TNever) || self.types.iter().any(|b| atomic_subtype(sub, b))
1656 }
1657
1658 fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Type {
1661 let mut result = Type::empty();
1662 result.possibly_undefined = self.possibly_undefined;
1663 result.from_docblock = self.from_docblock;
1664 for atomic in &self.types {
1665 if f(atomic) {
1666 result.types.push(atomic.clone());
1667 }
1668 }
1669 result
1670 }
1671
1672 fn filter_replacing<K: Fn(&Atomic) -> bool, P: Fn(&Atomic) -> bool>(
1677 &self,
1678 keep: K,
1679 placeholder: P,
1680 replacement: Atomic,
1681 ) -> Type {
1682 let mut result = Type::empty();
1683 result.possibly_undefined = self.possibly_undefined;
1684 result.from_docblock = self.from_docblock;
1685 for atomic in &self.types {
1686 if keep(atomic) {
1687 result.add_type(atomic.clone());
1688 } else if placeholder(atomic) {
1689 result.add_type(replacement.clone());
1690 }
1691 }
1692 result
1693 }
1694
1695 pub fn possibly_undefined(mut self) -> Self {
1697 self.possibly_undefined = true;
1698 self
1699 }
1700
1701 pub fn from_docblock(mut self) -> Self {
1703 self.from_docblock = true;
1704 self
1705 }
1706
1707 pub fn falsy_stripped(mut self) -> Self {
1710 self.falsy_stripped = true;
1711 self
1712 }
1713
1714 pub fn possibly_absent_offset(mut self) -> Self {
1718 self.possibly_absent_offset = true;
1719 self
1720 }
1721}
1722
1723#[derive(Clone, PartialEq, Eq, Debug)]
1737enum ValueClass {
1738 Int,
1739 Float,
1740 True,
1741 False,
1742 String,
1743 Array,
1744 List,
1746 Object,
1747 Null,
1748 Top,
1751 LitInt(i64),
1754 LitFloat(i64, i64),
1756 LitString(Arc<str>),
1758 ClassString,
1760}
1761
1762impl ValueClass {
1763 fn includes(&self, b: &Self) -> bool {
1768 self == b
1769 || matches!(
1770 (self, b),
1771 (Self::Top, _)
1772 | (Self::Int, Self::LitInt(_))
1773 | (Self::Float, Self::LitFloat(..))
1774 | (Self::String, Self::LitString(_))
1775 | (Self::String, Self::ClassString)
1776 | (Self::Array, Self::List)
1777 )
1778 }
1779
1780 fn overlaps(&self, b: &Self) -> bool {
1782 self.includes(b)
1783 || b.includes(self)
1784 || matches!(
1785 (self, b),
1786 (Self::ClassString, Self::LitString(_)) | (Self::LitString(_), Self::ClassString)
1787 )
1788 }
1789}
1790
1791fn value_classes(a: &Atomic) -> Vec<ValueClass> {
1797 use ValueClass::*;
1798 match a {
1799 Atomic::TInt
1802 | Atomic::TIntRange { .. }
1803 | Atomic::TPositiveInt
1804 | Atomic::TNegativeInt
1805 | Atomic::TNonNegativeInt => vec![Int],
1806 Atomic::TLiteralInt(v) => vec![LitInt(*v)],
1807 Atomic::TFloat | Atomic::TIntegralFloat => vec![Float],
1809 Atomic::TLiteralFloat(int_bits, frac_bits) => {
1810 vec![LitFloat(*int_bits, *frac_bits)]
1811 }
1812 Atomic::TBool => vec![True, False],
1814 Atomic::TTrue => vec![True],
1815 Atomic::TFalse => vec![False],
1816 Atomic::TString
1818 | Atomic::TNonEmptyString
1819 | Atomic::TNumericString
1820 | Atomic::TCallableString => vec![String],
1821 Atomic::TClassString(_)
1822 | Atomic::TInterfaceString(_)
1823 | Atomic::TEnumString
1824 | Atomic::TTraitString => vec![ClassString],
1825 Atomic::TLiteralString(s) => vec![LitString(s.clone())],
1826 Atomic::TArray { .. }
1828 | Atomic::TNonEmptyArray { .. }
1829 | Atomic::TKeyedArray { is_list: false, .. } => vec![Array],
1830 Atomic::TList { .. }
1831 | Atomic::TNonEmptyList { .. }
1832 | Atomic::TKeyedArray { is_list: true, .. } => vec![List],
1833 Atomic::TObject
1835 | Atomic::TObjectShape { .. }
1836 | Atomic::TNamedObject { .. }
1837 | Atomic::TStaticObject { .. }
1838 | Atomic::TSelf { .. }
1839 | Atomic::TParent { .. }
1840 | Atomic::TClosure { .. }
1841 | Atomic::TLiteralEnumCase { .. } => vec![Object],
1842 Atomic::TNull => vec![Null],
1845 Atomic::TVoid => vec![Top],
1846 Atomic::TMixed => vec![Top],
1848 Atomic::TScalar => vec![Int, Float, True, False, String],
1849 Atomic::TNumeric => vec![Int, Float],
1852 Atomic::TCallable { .. }
1854 | Atomic::TNever
1855 | Atomic::TTemplateParam { .. }
1856 | Atomic::TKeyOf { .. }
1857 | Atomic::TValueOf { .. }
1858 | Atomic::TConditional { .. }
1859 | Atomic::TIntersection { .. } => Vec::new(),
1860 }
1861}
1862
1863fn subject_is_decidable(subject: &Atomic) -> bool {
1871 matches!(
1872 subject,
1873 Atomic::TNull
1874 | Atomic::TTrue
1875 | Atomic::TFalse
1876 | Atomic::TBool
1877 | Atomic::TString
1878 | Atomic::TClassString(None)
1879 | Atomic::TInt
1880 | Atomic::TFloat
1881 | Atomic::TLiteralString(_)
1882 | Atomic::TLiteralInt(_)
1883 | Atomic::TLiteralFloat(..)
1884 | Atomic::TArray { .. }
1885 | Atomic::TList { .. }
1886 | Atomic::TObject
1887 | Atomic::TObjectShape { .. }
1888 | Atomic::TMixed
1889 | Atomic::TScalar
1890 )
1891}
1892
1893fn resolve_conditional_branch(
1915 subject: &Type,
1916 arg_ty: &Type,
1917 if_true: &Type,
1918 if_false: &Type,
1919) -> Option<Type> {
1920 if subject.types.is_empty() || !subject.types.iter().all(subject_is_decidable) {
1921 return None;
1922 }
1923 if arg_ty.types.is_empty() {
1924 return None;
1925 }
1926 let subject_classes: Vec<ValueClass> = subject.types.iter().flat_map(value_classes).collect();
1927 let arg_classes: Vec<ValueClass> = arg_ty.types.iter().flat_map(value_classes).collect();
1928 if arg_classes.is_empty() {
1929 return None;
1931 }
1932 let all_match = arg_classes
1933 .iter()
1934 .all(|c| subject_classes.iter().any(|s| s.includes(c)));
1935 let any_overlap = arg_classes
1936 .iter()
1937 .any(|c| subject_classes.iter().any(|s| s.overlaps(c)));
1938 if all_match {
1939 Some(if_true.clone())
1940 } else if !any_overlap {
1941 Some(if_false.clone())
1942 } else {
1943 None
1944 }
1945}
1946
1947fn atomic_may_contain_templates(atomic: &Atomic) -> bool {
1955 match atomic {
1956 Atomic::TNamedObject { fqcn, type_params } => {
1960 !type_params.is_empty() || !fqcn.contains('\\')
1961 }
1962 Atomic::TTemplateParam { .. }
1963 | Atomic::TKeyOf { .. }
1964 | Atomic::TValueOf { .. }
1965 | Atomic::TArray { .. }
1966 | Atomic::TList { .. }
1967 | Atomic::TNonEmptyArray { .. }
1968 | Atomic::TNonEmptyList { .. }
1969 | Atomic::TKeyedArray { .. }
1970 | Atomic::TCallable { .. }
1971 | Atomic::TClosure { .. }
1972 | Atomic::TConditional { .. }
1973 | Atomic::TIntersection { .. }
1974 | Atomic::TClassString(Some(_))
1975 | Atomic::TInterfaceString(Some(_)) => true,
1976 _ => false,
1977 }
1978}
1979
1980pub fn eval_key_of_type(t: &Type) -> Option<Type> {
1981 let mut result = Type::empty();
1982 for atomic in &t.types {
1983 match atomic {
1984 Atomic::TArray { key, .. } | Atomic::TNonEmptyArray { key, .. } => {
1985 for k in &key.types {
1986 result.add_type(k.clone());
1987 }
1988 }
1989 Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => {
1990 result.add_type(Atomic::TInt);
1991 }
1992 Atomic::TKeyedArray { properties, .. } => {
1993 for key in properties.keys() {
1994 match key {
1995 crate::atomic::ArrayKey::Int(n) => result.add_type(Atomic::TLiteralInt(*n)),
1996 crate::atomic::ArrayKey::String(s) => {
1997 result.add_type(Atomic::TLiteralString(s.clone()))
1998 }
1999 }
2000 }
2001 }
2002 _ => return None,
2003 }
2004 }
2005 (!result.types.is_empty()).then_some(result)
2006}
2007
2008pub fn eval_value_of_type(t: &Type) -> Option<Type> {
2009 let mut result = Type::empty();
2010 for atomic in &t.types {
2011 match atomic {
2012 Atomic::TArray { value, .. }
2013 | Atomic::TNonEmptyArray { value, .. }
2014 | Atomic::TList { value }
2015 | Atomic::TNonEmptyList { value } => {
2016 result.merge_with(value);
2017 }
2018 Atomic::TKeyedArray { properties, .. } => {
2019 for prop in properties.values() {
2020 result.merge_with(&prop.ty);
2021 }
2022 }
2023 _ => return None,
2024 }
2025 }
2026 (!result.types.is_empty()).then_some(result)
2027}
2028
2029fn substitute_in_fn_param(
2030 p: &crate::atomic::FnParam,
2031 bindings: &FxHashMap<Name, Type>,
2032) -> crate::atomic::FnParam {
2033 crate::atomic::FnParam {
2034 name: p.name,
2035 ty: p.ty.as_ref().map(|t| {
2036 let u = t.to_union();
2037 let substituted = u.substitute_templates(bindings);
2038 crate::compact::SimpleType::from_union(substituted)
2039 }),
2040 out_ty: p.out_ty.as_ref().map(|t| {
2041 let u = t.to_union();
2042 let substituted = u.substitute_templates(bindings);
2043 crate::compact::SimpleType::from_union(substituted)
2044 }),
2045 default: p.default.as_ref().map(|d| {
2046 let u = d.to_union();
2047 let substituted = u.substitute_templates(bindings);
2048 crate::compact::SimpleType::from_union(substituted)
2049 }),
2050 is_variadic: p.is_variadic,
2051 is_byref: p.is_byref,
2052 is_optional: p.is_optional,
2053 }
2054}
2055
2056fn composite_parts(atomic: &Atomic) -> Option<&'static [Atomic]> {
2063 match atomic {
2064 Atomic::TScalar => Some(&[Atomic::TInt, Atomic::TFloat, Atomic::TString, Atomic::TBool]),
2065 Atomic::TNumeric => Some(&[Atomic::TInt, Atomic::TFloat, Atomic::TNumericString]),
2066 _ => None,
2067 }
2068}
2069
2070fn object_shape_subtype(have: &KeyedProperties, want: &KeyedProperties) -> bool {
2071 want.iter().all(|(name, wanted)| match have.get(name) {
2072 Some(had) => (wanted.optional || !had.optional) && had.ty.is_subtype_structural(&wanted.ty),
2073 None => wanted.optional,
2074 })
2075}
2076
2077pub fn atomic_subtype(sub: &Atomic, sup: &Atomic) -> bool {
2079 if sub == sup {
2080 return true;
2081 }
2082 match (sub, sup) {
2083 (Atomic::TObjectShape { properties: have }, Atomic::TObjectShape { properties: want }) => {
2084 return object_shape_subtype(have, want);
2085 }
2086 (Atomic::TObjectShape { .. }, _) => return atomic_subtype(&Atomic::TObject, sup),
2087 (_, Atomic::TObjectShape { .. }) => return atomic_subtype(sub, &Atomic::TObject),
2089 _ => {}
2090 }
2091 match (sub, sup) {
2092 (Atomic::TNever, _) => true,
2094 (_, Atomic::TMixed) => true,
2096 (Atomic::TMixed, _) => true,
2097 (_, Atomic::TTemplateParam { as_type, .. }) => {
2102 as_type.is_mixed() || as_type.types.iter().any(|b| atomic_subtype(sub, b))
2103 }
2104
2105 (Atomic::TLiteralInt(_), Atomic::TInt) => true,
2107 (Atomic::TLiteralInt(_), Atomic::TNumeric) => true,
2108 (Atomic::TLiteralInt(_), Atomic::TScalar) => true,
2109 (Atomic::TLiteralInt(n), Atomic::TPositiveInt) => *n > 0,
2110 (Atomic::TLiteralInt(n), Atomic::TNonNegativeInt) => *n >= 0,
2111 (Atomic::TLiteralInt(n), Atomic::TNegativeInt) => *n < 0,
2112 (Atomic::TPositiveInt, Atomic::TInt) => true,
2113 (Atomic::TPositiveInt, Atomic::TNonNegativeInt) => true,
2114 (Atomic::TPositiveInt, Atomic::TNumeric) => true,
2115 (Atomic::TPositiveInt, Atomic::TScalar) => true,
2116 (Atomic::TNegativeInt, Atomic::TInt) => true,
2117 (Atomic::TNegativeInt, Atomic::TNumeric) => true,
2118 (Atomic::TNegativeInt, Atomic::TScalar) => true,
2119 (Atomic::TNonNegativeInt, Atomic::TInt) => true,
2120 (Atomic::TNonNegativeInt, Atomic::TNumeric) => true,
2121 (Atomic::TNonNegativeInt, Atomic::TScalar) => true,
2122 (Atomic::TIntRange { .. }, Atomic::TInt) => true,
2123 (Atomic::TIntRange { .. }, Atomic::TNumeric) => true,
2124 (Atomic::TIntRange { .. }, Atomic::TScalar) => true,
2125 (Atomic::TPositiveInt, Atomic::TIntRange { min, max }) => {
2127 max.is_none() && min.is_none_or(|m| m <= 1)
2128 }
2129 (Atomic::TNegativeInt, Atomic::TIntRange { min, max }) => {
2131 min.is_none() && max.is_none_or(|m| m >= -1)
2132 }
2133 (Atomic::TNonNegativeInt, Atomic::TIntRange { min, max }) => {
2135 max.is_none() && min.is_none_or(|m| m <= 0)
2136 }
2137 (Atomic::TIntRange { min: sub_min, .. }, Atomic::TPositiveInt) => {
2139 sub_min.is_some_and(|lo| lo >= 1)
2140 }
2141 (Atomic::TIntRange { min: sub_min, .. }, Atomic::TNonNegativeInt) => {
2142 sub_min.is_some_and(|lo| lo >= 0)
2143 }
2144 (Atomic::TIntRange { max: sub_max, .. }, Atomic::TNegativeInt) => {
2145 sub_max.is_some_and(|hi| hi <= -1)
2146 }
2147 (
2149 Atomic::TIntRange {
2150 min: sub_min,
2151 max: sub_max,
2152 },
2153 Atomic::TIntRange {
2154 min: sup_min,
2155 max: sup_max,
2156 },
2157 ) => {
2158 let lower_ok = match (sub_min, sup_min) {
2159 (_, None) => true,
2160 (None, Some(_)) => false,
2161 (Some(sl), Some(su)) => sl >= su,
2162 };
2163 let upper_ok = match (sub_max, sup_max) {
2164 (None, None) | (Some(_), None) => true,
2165 (None, Some(_)) => false,
2166 (Some(sl), Some(su)) => sl <= su,
2167 };
2168 lower_ok && upper_ok
2169 }
2170
2171 (Atomic::TLiteralFloat(..), Atomic::TFloat) => true,
2172 (Atomic::TLiteralFloat(..), Atomic::TNumeric) => true,
2173 (Atomic::TLiteralFloat(..), Atomic::TScalar) => true,
2174
2175 (Atomic::TLiteralString(s), Atomic::TString) => {
2176 let _ = s;
2177 true
2178 }
2179 (Atomic::TLiteralString(s), Atomic::TCallableString) => {
2180 let _ = s;
2181 true
2182 }
2183 (Atomic::TLiteralString(s), Atomic::TNonEmptyString) => !s.is_empty(),
2184 (Atomic::TLiteralString(s), Atomic::TNumericString) => s.parse::<f64>().is_ok(),
2185 (Atomic::TLiteralString(_), Atomic::TClassString(_)) => true,
2188 (Atomic::TLiteralString(_), Atomic::TInterfaceString(_)) => true,
2191 (Atomic::TLiteralString(_), Atomic::TScalar) => true,
2192 (Atomic::TNonEmptyString, Atomic::TString) => true,
2193 (Atomic::TCallableString, Atomic::TString) => true,
2194 (Atomic::TNumericString, Atomic::TNonEmptyString) => true,
2196 (Atomic::TNumericString, Atomic::TString) => true,
2197 (Atomic::TClassString(_), Atomic::TNonEmptyString) => true,
2201 (Atomic::TInterfaceString(_), Atomic::TNonEmptyString) => true,
2202 (Atomic::TCallableString, Atomic::TNonEmptyString) => true,
2203 (Atomic::TEnumString, Atomic::TNonEmptyString) => true,
2204 (Atomic::TTraitString, Atomic::TNonEmptyString) => true,
2205 (Atomic::TClassString(_), Atomic::TString) => true,
2206 (Atomic::TInterfaceString(_), Atomic::TString) => true,
2207 (Atomic::TInterfaceString(_), Atomic::TClassString(None)) => true,
2212 (Atomic::TClassString(Some(_)), Atomic::TClassString(None)) => true,
2213 (Atomic::TInterfaceString(Some(a)), Atomic::TClassString(Some(b))) => a == b,
2214 (Atomic::TEnumString, Atomic::TString) => true,
2215 (Atomic::TTraitString, Atomic::TString) => true,
2216
2217 (Atomic::TTrue, Atomic::TBool) => true,
2218 (Atomic::TFalse, Atomic::TBool) => true,
2219
2220 (Atomic::TInt, Atomic::TNumeric) => true,
2221 (Atomic::TFloat, Atomic::TNumeric) => true,
2222 (Atomic::TIntegralFloat, Atomic::TNumeric) => true,
2223 (Atomic::TNumericString, Atomic::TNumeric) => true,
2224
2225 (Atomic::TInt, Atomic::TScalar) => true,
2226 (Atomic::TFloat, Atomic::TScalar) => true,
2227 (Atomic::TIntegralFloat, Atomic::TScalar) => true,
2228 (Atomic::TString, Atomic::TScalar) => true,
2229 (Atomic::TBool, Atomic::TScalar) => true,
2230 (Atomic::TNumeric, Atomic::TScalar) => true,
2231 (Atomic::TTrue, Atomic::TScalar) => true,
2232 (Atomic::TFalse, Atomic::TScalar) => true,
2233 (Atomic::TNonEmptyString, Atomic::TScalar) => true,
2237 (Atomic::TNumericString, Atomic::TScalar) => true,
2238 (Atomic::TCallableString, Atomic::TScalar) => true,
2239 (Atomic::TClassString(_), Atomic::TScalar) => true,
2240 (Atomic::TInterfaceString(_), Atomic::TScalar) => true,
2241 (Atomic::TEnumString, Atomic::TScalar) => true,
2242 (Atomic::TTraitString, Atomic::TScalar) => true,
2243
2244 (Atomic::TNamedObject { .. }, Atomic::TObject) => true,
2246 (Atomic::TStaticObject { .. }, Atomic::TObject) => true,
2247 (Atomic::TSelf { .. }, Atomic::TObject) => true,
2248 (Atomic::TLiteralEnumCase { .. }, Atomic::TObject) => true,
2250 (Atomic::TSelf { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
2252 (Atomic::TStaticObject { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
2253 (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TSelf { fqcn: b }) => a == b,
2255 (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TStaticObject { fqcn: b }) => a == b,
2256 (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TNamedObject { fqcn, .. }) => {
2259 enum_fqcn == fqcn
2260 }
2261 (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TSelf { fqcn })
2262 | (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TStaticObject { fqcn }) => {
2263 enum_fqcn == fqcn
2264 }
2265 (
2269 Atomic::TNamedObject {
2270 fqcn: sub_fqcn,
2271 type_params: sub_params,
2272 },
2273 Atomic::TNamedObject {
2274 fqcn: sup_fqcn,
2275 type_params: sup_params,
2276 },
2277 ) => {
2278 sub_fqcn == sup_fqcn
2279 && (sup_params.is_empty() || type_params_compatible(sub_params, sup_params))
2280 }
2281
2282 (Atomic::TIntegralFloat, Atomic::TFloat) => true,
2284
2285 (Atomic::TLiteralInt(_), Atomic::TFloat) => true,
2287 (Atomic::TPositiveInt, Atomic::TFloat) => true,
2288 (Atomic::TNegativeInt, Atomic::TFloat) => true,
2289 (Atomic::TNonNegativeInt, Atomic::TFloat) => true,
2290 (Atomic::TInt, Atomic::TFloat) => true,
2291 (Atomic::TIntRange { .. }, Atomic::TFloat) => true,
2292
2293 (Atomic::TLiteralInt(n), Atomic::TIntRange { min, max }) => {
2295 min.is_none_or(|lo| *n >= lo) && max.is_none_or(|hi| *n <= hi)
2296 }
2297
2298 (Atomic::TString, Atomic::TCallable { .. }) => true,
2300 (Atomic::TCallableString, Atomic::TCallable { .. }) => true,
2301 (Atomic::TNonEmptyString, Atomic::TCallable { .. }) => true,
2302 (Atomic::TLiteralString(_), Atomic::TCallable { .. }) => true,
2303 (Atomic::TArray { .. }, Atomic::TCallable { .. }) => true,
2304 (Atomic::TNonEmptyArray { .. }, Atomic::TCallable { .. }) => true,
2305 (Atomic::TKeyedArray { .. }, Atomic::TCallable { .. }) => true,
2306
2307 (Atomic::TClosure { .. }, Atomic::TCallable { .. }) => true,
2309 (Atomic::TCallable { .. }, Atomic::TClosure { .. }) => true,
2311 (Atomic::TClosure { data: sub }, Atomic::TClosure { data: sup }) => {
2321 fn has_nominal_type(t: &Type) -> bool {
2322 t.types.iter().any(|a| {
2323 matches!(
2324 a,
2325 Atomic::TNamedObject { .. }
2326 | Atomic::TSelf { .. }
2327 | Atomic::TStaticObject { .. }
2328 | Atomic::TTemplateParam { .. }
2329 | Atomic::TClosure { .. }
2330 | Atomic::TCallable { .. }
2331 )
2332 })
2333 }
2334 let sub_required = sub
2335 .params
2336 .iter()
2337 .filter(|p| !p.is_optional && !p.is_variadic)
2338 .count();
2339 if sub_required > sup.params.len() {
2340 false
2341 } else {
2342 let params_ok = sup.params.iter().enumerate().all(|(i, sup_param)| {
2343 let Some(sub_param) = sub.params.get(i) else {
2344 return true;
2345 };
2346 if sub_param.is_optional || sub_param.is_variadic {
2347 return true;
2348 }
2349 let (Some(sub_ty), Some(sup_ty)) =
2350 (sub_param.ty.as_ref(), sup_param.ty.as_ref())
2351 else {
2352 return true;
2353 };
2354 let (sub_u, sup_u) = (sub_ty.to_union(), sup_ty.to_union());
2355 if has_nominal_type(&sub_u) || has_nominal_type(&sup_u) {
2356 return true;
2357 }
2358 sup_u.is_subtype_structural(&sub_u)
2361 });
2362 params_ok
2363 && (sub.return_type.is_mixed()
2364 || sup.return_type.is_mixed()
2365 || sup.return_type.is_void()
2369 || has_nominal_type(&sub.return_type)
2370 || has_nominal_type(&sup.return_type)
2371 || sub.return_type.is_subtype_structural(&sup.return_type))
2372 }
2373 }
2374 (Atomic::TCallable { .. }, Atomic::TCallable { .. }) => true,
2376 (Atomic::TClosure { .. }, Atomic::TNamedObject { fqcn, .. }) => {
2378 fqcn.as_ref().eq_ignore_ascii_case("closure")
2379 }
2380 (Atomic::TClosure { .. }, Atomic::TObject) => true,
2381 (Atomic::TNamedObject { fqcn, .. }, Atomic::TClosure { .. }) => {
2383 fqcn.as_ref().eq_ignore_ascii_case("closure")
2384 }
2385 (Atomic::TNamedObject { fqcn, .. }, Atomic::TCallable { .. }) => {
2387 fqcn.as_ref().eq_ignore_ascii_case("closure")
2388 }
2389
2390 (
2398 Atomic::TIntersection { parts: sub_parts },
2399 Atomic::TIntersection { parts: sup_parts },
2400 ) => sup_parts.iter().all(|sup_part| {
2401 sub_parts
2402 .iter()
2403 .any(|sub_part| sub_part.is_subtype_structural(sup_part))
2404 }),
2405 (Atomic::TIntersection { parts }, Atomic::TObject) => parts
2406 .iter()
2407 .any(|part| part.is_subtype_structural(&Type::single(Atomic::TObject))),
2408
2409 (Atomic::TList { value }, Atomic::TArray { key, value: av }) => {
2411 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2412 }
2413 (Atomic::TNonEmptyList { value }, Atomic::TArray { key, value: av }) => {
2414 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2415 }
2416 (Atomic::TNonEmptyList { value }, Atomic::TNonEmptyArray { key, value: av }) => {
2417 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2418 }
2419 (Atomic::TNonEmptyList { value }, Atomic::TList { value: lv }) => {
2420 value.is_subtype_structural(lv)
2421 }
2422 (Atomic::TNonEmptyList { value: v1 }, Atomic::TNonEmptyList { value: v2 }) => {
2423 v1.is_subtype_structural(v2)
2424 }
2425 (Atomic::TArray { key, value: av }, Atomic::TList { value: lv }) => {
2427 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2428 && av.is_subtype_structural(lv)
2429 }
2430 (Atomic::TArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
2431 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2432 && av.is_subtype_structural(lv)
2433 }
2434 (Atomic::TNonEmptyArray { key, value: av }, Atomic::TList { value: lv }) => {
2435 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2436 && av.is_subtype_structural(lv)
2437 }
2438 (Atomic::TNonEmptyArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
2439 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2440 && av.is_subtype_structural(lv)
2441 }
2442 (Atomic::TList { value: v1 }, Atomic::TList { value: v2 }) => v1.is_subtype_structural(v2),
2444 (Atomic::TNonEmptyArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
2445 k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
2446 }
2447
2448 (Atomic::TArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
2450 k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
2451 }
2452
2453 (Atomic::TKeyedArray { properties, .. }, Atomic::TArray { key, value }) => {
2462 properties.iter().all(|(prop_key, prop)| {
2463 let key_atomic = match prop_key {
2464 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2465 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2466 };
2467 if !Type::single(key_atomic).is_subtype_structural(key) {
2468 return false; }
2470 let has_named_obj = prop.ty.types.iter().any(|a| {
2472 matches!(
2473 a,
2474 Atomic::TNamedObject { .. }
2475 | Atomic::TSelf { .. }
2476 | Atomic::TStaticObject { .. }
2477 | Atomic::TClosure { .. }
2478 | Atomic::TTemplateParam { .. }
2479 )
2480 });
2481 has_named_obj || prop.ty.is_subtype_structural(value)
2482 })
2483 }
2484 (
2485 Atomic::TKeyedArray {
2486 properties,
2487 is_open,
2488 ..
2489 },
2490 Atomic::TNonEmptyArray { key, value },
2491 ) => {
2492 (*is_open || properties.iter().any(|(_, p)| !p.optional))
2493 && properties.iter().all(|(prop_key, prop)| {
2494 let key_atomic = match prop_key {
2495 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2496 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2497 };
2498 if !Type::single(key_atomic).is_subtype_structural(key) {
2499 return false;
2500 }
2501 let has_named_obj = prop.ty.types.iter().any(|a| {
2502 matches!(
2503 a,
2504 Atomic::TNamedObject { .. }
2505 | Atomic::TSelf { .. }
2506 | Atomic::TStaticObject { .. }
2507 | Atomic::TClosure { .. }
2508 | Atomic::TTemplateParam { .. }
2509 )
2510 });
2511 has_named_obj || prop.ty.is_subtype_structural(value)
2512 })
2513 }
2514
2515 (
2517 Atomic::TKeyedArray {
2518 properties,
2519 is_list,
2520 ..
2521 },
2522 Atomic::TList { value: lv },
2523 ) => *is_list && properties.values().all(|p| p.ty.is_subtype_structural(lv)),
2524 (
2525 Atomic::TKeyedArray {
2526 properties,
2527 is_list,
2528 ..
2529 },
2530 Atomic::TNonEmptyList { value: lv },
2531 ) => {
2532 *is_list
2533 && !properties.is_empty()
2534 && properties.values().all(|p| p.ty.is_subtype_structural(lv))
2535 }
2536
2537 (
2542 Atomic::TKeyedArray {
2543 properties: sub_props,
2544 is_open: sub_open,
2545 ..
2546 },
2547 Atomic::TKeyedArray {
2548 properties: sup_props,
2549 is_open: sup_open,
2550 ..
2551 },
2552 ) => {
2553 let keys_satisfied = sup_props
2554 .iter()
2555 .all(|(key, sup_prop)| match sub_props.get(key) {
2556 Some(sub_prop) => {
2557 if !sup_prop.optional && sub_prop.optional {
2561 return false;
2562 }
2563 let has_named_obj = sup_prop.ty.types.iter().any(|a| {
2564 matches!(
2565 a,
2566 Atomic::TNamedObject { .. }
2567 | Atomic::TSelf { .. }
2568 | Atomic::TStaticObject { .. }
2569 | Atomic::TClosure { .. }
2570 | Atomic::TTemplateParam { .. }
2571 )
2572 });
2573 has_named_obj || sub_prop.ty.is_subtype_by_template_bounds(&sup_prop.ty)
2574 }
2575 None => sup_prop.optional || *sub_open,
2576 });
2577 let no_undeclared_extras =
2578 *sup_open || sub_props.keys().all(|k| sup_props.contains_key(k));
2579 keys_satisfied && no_undeclared_extras
2580 }
2581 (
2586 Atomic::TKeyedArray {
2587 properties,
2588 is_open,
2589 ..
2590 },
2591 Atomic::TIntersection { parts },
2592 ) => parts.iter().all(|part| {
2593 part.types.iter().any(|part_atomic| match part_atomic {
2594 Atomic::TKeyedArray {
2595 properties: sup_props,
2596 is_open: sup_open,
2597 ..
2598 } => {
2599 let keys_satisfied =
2600 sup_props
2601 .iter()
2602 .all(|(key, sup_prop)| match properties.get(key) {
2603 Some(sub_prop) => {
2604 if !sup_prop.optional && sub_prop.optional {
2605 return false;
2606 }
2607 let has_named_obj = sup_prop.ty.types.iter().any(|a| {
2608 matches!(
2609 a,
2610 Atomic::TNamedObject { .. }
2611 | Atomic::TSelf { .. }
2612 | Atomic::TStaticObject { .. }
2613 | Atomic::TClosure { .. }
2614 | Atomic::TTemplateParam { .. }
2615 )
2616 });
2617 has_named_obj
2618 || sub_prop.ty.is_subtype_by_template_bounds(&sup_prop.ty)
2619 || bare_array_may_fit(&sub_prop.ty, &sup_prop.ty)
2620 }
2621 None => *is_open || sup_prop.optional,
2622 });
2623 let has_array_part = parts.iter().any(|part| {
2624 part.types
2625 .iter()
2626 .any(|t| matches!(t, Atomic::TArray { .. }))
2627 });
2628 let has_keyed_array_part = parts.iter().any(|part| {
2629 part.types
2630 .iter()
2631 .any(|t| matches!(t, Atomic::TKeyedArray { .. }))
2632 });
2633 let keys_allowed_by_some_part = if has_array_part {
2634 true
2635 } else if has_keyed_array_part {
2636 properties.keys().all(|k| {
2637 parts.iter().any(|part| {
2638 part.types.iter().any(|t| {
2639 if let Atomic::TKeyedArray {
2640 properties: part_props,
2641 ..
2642 } = t
2643 {
2644 part_props.contains_key(k)
2645 } else {
2646 false
2647 }
2648 })
2649 })
2650 })
2651 } else {
2652 true
2653 };
2654 let no_undeclared_extras = *sup_open || keys_allowed_by_some_part;
2655 keys_satisfied && no_undeclared_extras
2656 }
2657 Atomic::TArray { key, value } => properties.iter().all(|(prop_key, prop)| {
2658 let key_atomic = match prop_key {
2659 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2660 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2661 };
2662 if !Type::single(key_atomic).is_subtype_structural(key) {
2663 return false;
2664 }
2665 let has_named_obj = prop.ty.types.iter().any(|a| {
2666 matches!(
2667 a,
2668 Atomic::TNamedObject { .. }
2669 | Atomic::TSelf { .. }
2670 | Atomic::TStaticObject { .. }
2671 | Atomic::TClosure { .. }
2672 | Atomic::TTemplateParam { .. }
2673 )
2674 });
2675 has_named_obj || prop.ty.is_subtype_structural(value)
2676 }),
2677 Atomic::TNamedObject { .. }
2678 | Atomic::TSelf { .. }
2679 | Atomic::TStaticObject { .. }
2680 | Atomic::TClosure { .. }
2681 | Atomic::TTemplateParam { .. } => true,
2682 _ => false,
2683 })
2684 }),
2685
2686 _ => false,
2687 }
2688}
2689
2690fn bare_array_may_fit(sub: &Type, sup: &Type) -> bool {
2692 fn array_like(t: &Atomic) -> bool {
2693 match t {
2694 Atomic::TArray { .. }
2695 | Atomic::TNonEmptyArray { .. }
2696 | Atomic::TList { .. }
2697 | Atomic::TNonEmptyList { .. }
2698 | Atomic::TKeyedArray { .. } => true,
2699 Atomic::TIntersection { parts } => parts.iter().all(|p| p.types.iter().all(array_like)),
2700 _ => false,
2701 }
2702 }
2703 matches!(
2704 sub.types.as_slice(),
2705 [Atomic::TArray { key, value }]
2706 if value.is_mixed()
2707 && (key.is_mixed()
2708 || matches!(key.types.as_slice(), [Atomic::TInt, Atomic::TString] | [Atomic::TString, Atomic::TInt]))
2709 ) && sup.types.iter().all(array_like)
2710}
2711
2712fn type_params_compatible(sub: &[Type], sup: &[Type]) -> bool {
2718 if sub.len() != sup.len() {
2719 return false;
2720 }
2721 sub.iter()
2722 .zip(sup.iter())
2723 .all(|(a, b)| a == b || (is_empty_array_literal(a) && is_array_like(b)))
2724}
2725
2726fn is_empty_array_literal(t: &Type) -> bool {
2729 !t.types.is_empty()
2730 && t.types.iter().all(
2731 |atom| matches!(atom, Atomic::TKeyedArray { properties, .. } if properties.is_empty()),
2732 )
2733}
2734
2735fn is_array_like(t: &Type) -> bool {
2737 !t.types.is_empty() && t.types.iter().all(|atom| atom.is_array())
2738}
2739
2740pub struct UnionBuilder {
2747 ty: Type,
2748 strings: std::collections::HashSet<std::sync::Arc<str>>,
2749 ints: std::collections::HashSet<i64>,
2750 literals_independent: bool,
2752}
2753
2754impl Default for UnionBuilder {
2755 fn default() -> Self {
2756 Self::new()
2757 }
2758}
2759
2760impl UnionBuilder {
2761 pub fn new() -> Self {
2762 Self {
2763 ty: Type::empty(),
2764 strings: Default::default(),
2765 ints: Default::default(),
2766 literals_independent: true,
2767 }
2768 }
2769
2770 pub fn is_empty(&self) -> bool {
2771 self.ty.is_empty()
2772 }
2773
2774 pub fn merge(&mut self, other: &Type) {
2775 for a in &other.types {
2776 self.add(a.clone());
2777 }
2778 self.ty.possibly_undefined |= other.possibly_undefined;
2779 }
2780
2781 pub fn add(&mut self, atomic: Atomic) {
2782 let lone_never = matches!(self.ty.types.first(), Some(Atomic::TNever));
2784 if self.literals_independent && !lone_never {
2785 match &atomic {
2786 Atomic::TLiteralString(s) => {
2787 if self.strings.insert(s.clone()) {
2788 self.ty.types.push(atomic);
2789 }
2790 return;
2791 }
2792 Atomic::TLiteralInt(n) => {
2793 if self.ints.insert(*n) {
2794 self.ty.types.push(atomic);
2795 }
2796 return;
2797 }
2798 _ => {}
2799 }
2800 }
2801 let disturbs_literals = matches!(
2802 atomic,
2803 Atomic::TString | Atomic::TMixed | Atomic::TConditional { .. }
2804 ) || int_bounds(&atomic).is_some();
2805 self.ty.add_type(atomic);
2806 if disturbs_literals || lone_never {
2807 self.resync();
2808 }
2809 }
2810
2811 fn resync(&mut self) {
2812 self.strings.clear();
2813 self.ints.clear();
2814 self.literals_independent = true;
2815 for t in &self.ty.types {
2816 match t {
2817 Atomic::TLiteralString(s) => {
2818 self.strings.insert(s.clone());
2819 }
2820 Atomic::TLiteralInt(n) => {
2821 self.ints.insert(*n);
2822 }
2823 Atomic::TMixed | Atomic::TString => self.literals_independent = false,
2824 other if int_bounds(other).is_some() => self.literals_independent = false,
2825 _ => {}
2826 }
2827 }
2828 }
2829
2830 pub fn build(self) -> Type {
2831 self.ty
2832 }
2833}
2834
2835fn callable_array() -> Atomic {
2837 let mut properties = KeyedProperties::with_capacity_and_hasher(2, Default::default());
2838 properties.insert(
2839 ArrayKey::Int(0),
2840 KeyedProperty {
2841 ty: Type::from_vec(vec![Atomic::TClassString(None), Atomic::TObject]),
2842 optional: false,
2843 },
2844 );
2845 properties.insert(
2846 ArrayKey::Int(1),
2847 KeyedProperty {
2848 ty: Type::single(Atomic::TNonEmptyString),
2849 optional: false,
2850 },
2851 );
2852 Atomic::TKeyedArray {
2853 properties: Arc::new(properties),
2854 is_open: false,
2855 is_list: true,
2856 }
2857}
2858
2859#[cfg(test)]
2860mod tests {
2861 use std::sync::Arc;
2862
2863 use super::*;
2864
2865 fn conditional(
2866 param_name: Option<Name>,
2867 subject: Type,
2868 if_true: Type,
2869 if_false: Type,
2870 ) -> Atomic {
2871 Atomic::TConditional {
2872 data: Box::new(crate::atomic::ConditionalData {
2873 param_name,
2874 subject,
2875 if_true,
2876 if_false,
2877 }),
2878 }
2879 }
2880
2881 #[test]
2882 fn single_is_single() {
2883 let u = Type::single(Atomic::TString);
2884 assert!(u.is_single());
2885 assert!(!u.is_nullable());
2886 }
2887
2888 #[test]
2889 fn nullable_has_null() {
2890 let u = Type::nullable(Atomic::TString);
2891 assert!(u.is_nullable());
2892 assert_eq!(u.types.len(), 2);
2893 }
2894
2895 #[test]
2896 fn add_type_deduplicates() {
2897 let mut u = Type::single(Atomic::TString);
2898 u.add_type(Atomic::TString);
2899 assert_eq!(u.types.len(), 1);
2900 }
2901
2902 #[test]
2903 fn array_key_is_int_string() {
2904 let k = Type::array_key();
2905 assert!(k.is_array_key());
2906 assert_eq!(k.types.len(), 2);
2907 }
2908
2909 #[test]
2910 fn is_array_key_false_for_plain_int() {
2911 assert!(!Type::int().is_array_key());
2912 }
2913
2914 #[test]
2915 fn is_array_key_false_for_mixed() {
2916 assert!(!Type::mixed().is_array_key());
2917 }
2918
2919 #[test]
2920 fn is_array_key_false_for_int_string_null() {
2921 let mut u = Type::array_key();
2922 u.add_type(Atomic::TNull);
2923 assert!(!u.is_array_key());
2924 }
2925
2926 #[test]
2927 fn add_type_literal_subsumed_by_base() {
2928 let mut u = Type::single(Atomic::TInt);
2929 u.add_type(Atomic::TLiteralInt(42));
2930 assert_eq!(u.types.len(), 1);
2931 assert!(matches!(u.types[0], Atomic::TInt));
2932 }
2933
2934 #[test]
2935 fn true_then_false_merges_to_bool() {
2936 let mut u = Type::single(Atomic::TTrue);
2937 u.add_type(Atomic::TFalse);
2938 assert_eq!(u.types.len(), 1);
2939 assert!(matches!(u.types[0], Atomic::TBool));
2940 }
2941
2942 #[test]
2943 fn false_then_true_merges_to_bool() {
2944 let mut u = Type::single(Atomic::TFalse);
2945 u.add_type(Atomic::TTrue);
2946 assert_eq!(u.types.len(), 1);
2947 assert!(matches!(u.types[0], Atomic::TBool));
2948 }
2949
2950 #[test]
2951 fn true_alone_stays_true() {
2952 let u = Type::single(Atomic::TTrue);
2953 assert_eq!(u.types.len(), 1);
2954 assert!(matches!(u.types[0], Atomic::TTrue));
2955 }
2956
2957 #[test]
2958 fn true_false_merge_preserves_other_union_members() {
2959 let mut u = Type::single(Atomic::TTrue);
2960 u.add_type(Atomic::TNull);
2961 u.add_type(Atomic::TFalse);
2962 assert_eq!(u.types.len(), 2);
2963 assert!(u.contains(|t| matches!(t, Atomic::TBool)));
2964 assert!(u.contains(|t| matches!(t, Atomic::TNull)));
2965 }
2966
2967 #[test]
2968 fn add_type_base_widens_literals() {
2969 let mut u = Type::single(Atomic::TLiteralInt(1));
2970 u.add_type(Atomic::TLiteralInt(2));
2971 u.add_type(Atomic::TInt);
2972 assert_eq!(u.types.len(), 1);
2973 assert!(matches!(u.types[0], Atomic::TInt));
2974 }
2975
2976 #[test]
2977 fn mixed_subsumes_everything() {
2978 let mut u = Type::single(Atomic::TString);
2979 u.add_type(Atomic::TMixed);
2980 assert_eq!(u.types.len(), 1);
2981 assert!(u.is_mixed());
2982 }
2983
2984 #[test]
2985 fn remove_null() {
2986 let u = Type::nullable(Atomic::TString);
2987 let narrowed = u.remove_null();
2988 assert!(!narrowed.is_nullable());
2989 assert_eq!(narrowed.types.len(), 1);
2990 }
2991
2992 #[test]
2993 fn narrow_to_truthy_removes_null_false() {
2994 let mut u = Type::empty();
2995 u.add_type(Atomic::TString);
2996 u.add_type(Atomic::TNull);
2997 u.add_type(Atomic::TFalse);
2998 let truthy = u.narrow_to_truthy();
2999 assert!(!truthy.is_nullable());
3000 assert!(!truthy.contains(|t| matches!(t, Atomic::TFalse)));
3001 }
3002
3003 #[test]
3004 fn merge_combines_types() {
3005 let a = Type::single(Atomic::TString);
3006 let b = Type::single(Atomic::TInt);
3007 let merged = Type::merge(&a, &b);
3008 assert_eq!(merged.types.len(), 2);
3009 }
3010
3011 #[test]
3012 fn intersect_keeps_narrower_side_not_self() {
3013 let int_ty = Type::single(Atomic::TInt);
3017 let mut literals = Type::empty();
3018 literals.add_type(Atomic::TLiteralInt(1));
3019 literals.add_type(Atomic::TLiteralInt(2));
3020
3021 let narrowed = int_ty.intersect_with(&literals);
3022 assert_eq!(narrowed.types.len(), 2);
3023 assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(1))));
3024 assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(2))));
3025 assert!(!narrowed.contains(|t| matches!(t, Atomic::TInt)));
3026 }
3027
3028 #[test]
3029 fn subtype_literal_int_under_int() {
3030 let sub = Type::single(Atomic::TLiteralInt(5));
3031 let sup = Type::single(Atomic::TInt);
3032 assert!(sub.is_subtype_structural(&sup));
3033 }
3034
3035 #[test]
3036 fn subtype_never_is_bottom() {
3037 let never = Type::never();
3038 let string = Type::single(Atomic::TString);
3039 assert!(never.is_subtype_structural(&string));
3040 }
3041
3042 #[test]
3043 fn subtype_everything_under_mixed() {
3044 let string = Type::single(Atomic::TString);
3045 let mixed = Type::mixed();
3046 assert!(string.is_subtype_structural(&mixed));
3047 }
3048
3049 #[test]
3050 fn subtype_enum_case_under_own_enum() {
3051 let sub = Type::single(Atomic::TLiteralEnumCase {
3052 enum_fqcn: Name::new("RoundingMode"),
3053 case_name: Name::new("Unnecessary"),
3054 });
3055 let sup = Type::single(Atomic::TNamedObject {
3056 fqcn: Name::new("RoundingMode"),
3057 type_params: empty_type_params(),
3058 });
3059 assert!(sub.is_subtype_structural(&sup));
3060 }
3061
3062 #[test]
3063 fn enum_case_not_subtype_of_unrelated_enum() {
3064 let sub = Type::single(Atomic::TLiteralEnumCase {
3065 enum_fqcn: Name::new("RoundingMode"),
3066 case_name: Name::new("Unnecessary"),
3067 });
3068 let sup = Type::single(Atomic::TNamedObject {
3069 fqcn: Name::new("Suit"),
3070 type_params: empty_type_params(),
3071 });
3072 assert!(!sub.is_subtype_structural(&sup));
3073 }
3074
3075 #[test]
3076 fn subtype_enum_case_under_own_self_and_static() {
3077 let case = |enum_fqcn: &str| {
3078 Type::single(Atomic::TLiteralEnumCase {
3079 enum_fqcn: Name::new(enum_fqcn),
3080 case_name: Name::new("A"),
3081 })
3082 };
3083 let own = Type::single(Atomic::TSelf {
3084 fqcn: Name::new("Suit"),
3085 });
3086 let own_static = Type::single(Atomic::TStaticObject {
3087 fqcn: Name::new("Suit"),
3088 });
3089 assert!(case("Suit").is_subtype_structural(&own));
3090 assert!(case("Suit").is_subtype_structural(&own_static));
3091 assert!(!case("Other").is_subtype_structural(&own));
3092 }
3093
3094 #[test]
3095 fn subtype_enum_case_under_bare_object() {
3096 let sub = Type::single(Atomic::TLiteralEnumCase {
3097 enum_fqcn: Name::new("RoundingMode"),
3098 case_name: Name::new("Unnecessary"),
3099 });
3100 let sup = Type::single(Atomic::TObject);
3101 assert!(sub.is_subtype_structural(&sup));
3102 }
3103
3104 #[test]
3105 fn template_substitution() {
3106 let mut bindings = FxHashMap::default();
3107 bindings.insert(Name::new("T"), Type::single(Atomic::TString));
3108
3109 let tmpl = Type::single(Atomic::TTemplateParam {
3110 name: Name::new("T"),
3111 as_type: Box::new(Type::mixed()),
3112 defining_entity: Name::new("MyClass"),
3113 });
3114
3115 let resolved = tmpl.substitute_templates(&bindings);
3116 assert_eq!(resolved.types.len(), 1);
3117 assert!(matches!(resolved.types[0], Atomic::TString));
3118 }
3119
3120 #[test]
3121 fn intersection_is_object() {
3122 let parts = vec![
3123 Type::single(Atomic::TNamedObject {
3124 fqcn: Name::new("Iterator"),
3125 type_params: empty_type_params(),
3126 }),
3127 Type::single(Atomic::TNamedObject {
3128 fqcn: Name::new("Countable"),
3129 type_params: empty_type_params(),
3130 }),
3131 ];
3132 let atomic = Atomic::TIntersection {
3133 parts: vec_to_type_params(parts),
3134 };
3135 assert!(atomic.is_object());
3136 assert!(!atomic.can_be_falsy());
3137 assert!(atomic.can_be_truthy());
3138 }
3139
3140 #[test]
3141 fn intersection_display_two_parts() {
3142 let parts = vec![
3143 Type::single(Atomic::TNamedObject {
3144 fqcn: Name::new("Iterator"),
3145 type_params: empty_type_params(),
3146 }),
3147 Type::single(Atomic::TNamedObject {
3148 fqcn: Name::new("Countable"),
3149 type_params: empty_type_params(),
3150 }),
3151 ];
3152 let u = Type::single(Atomic::TIntersection {
3153 parts: vec_to_type_params(parts),
3154 });
3155 assert_eq!(format!("{u}"), "Iterator&Countable");
3156 }
3157
3158 #[test]
3159 fn intersection_display_three_parts() {
3160 let parts = vec![
3161 Type::single(Atomic::TNamedObject {
3162 fqcn: Name::new("A"),
3163 type_params: empty_type_params(),
3164 }),
3165 Type::single(Atomic::TNamedObject {
3166 fqcn: Name::new("B"),
3167 type_params: empty_type_params(),
3168 }),
3169 Type::single(Atomic::TNamedObject {
3170 fqcn: Name::new("C"),
3171 type_params: empty_type_params(),
3172 }),
3173 ];
3174 let u = Type::single(Atomic::TIntersection {
3175 parts: vec_to_type_params(parts),
3176 });
3177 assert_eq!(format!("{u}"), "A&B&C");
3178 }
3179
3180 #[test]
3181 fn intersection_in_nullable_union_display() {
3182 let intersection = Atomic::TIntersection {
3183 parts: vec_to_type_params(vec![
3184 Type::single(Atomic::TNamedObject {
3185 fqcn: Name::new("Iterator"),
3186 type_params: empty_type_params(),
3187 }),
3188 Type::single(Atomic::TNamedObject {
3189 fqcn: Name::new("Countable"),
3190 type_params: empty_type_params(),
3191 }),
3192 ]),
3193 };
3194 let mut u = Type::single(intersection);
3195 u.add_type(Atomic::TNull);
3196 assert!(u.is_nullable());
3197 assert!(u.contains(|t| matches!(t, Atomic::TIntersection { .. })));
3198 }
3199
3200 fn t_param(name: &str) -> Type {
3203 Type::single(Atomic::TTemplateParam {
3204 name: Name::new(name),
3205 as_type: Box::new(Type::mixed()),
3206 defining_entity: Name::new("Fn"),
3207 })
3208 }
3209
3210 fn bindings_t_string() -> FxHashMap<Name, Type> {
3211 let mut b = FxHashMap::default();
3212 b.insert(Name::new("T"), Type::single(Atomic::TString));
3213 b
3214 }
3215
3216 #[test]
3217 fn substitute_non_empty_array_key_and_value() {
3218 let ty = Type::single(Atomic::TNonEmptyArray {
3219 key: Box::new(t_param("T")),
3220 value: Box::new(t_param("T")),
3221 });
3222 let result = ty.substitute_templates(&bindings_t_string());
3223 assert_eq!(result.types.len(), 1);
3224 let Atomic::TNonEmptyArray { key, value } = &result.types[0] else {
3225 panic!("expected TNonEmptyArray");
3226 };
3227 assert!(matches!(key.types[0], Atomic::TString));
3228 assert!(matches!(value.types[0], Atomic::TString));
3229 }
3230
3231 #[test]
3232 fn substitute_non_empty_list_value() {
3233 let ty = Type::single(Atomic::TNonEmptyList {
3234 value: Box::new(t_param("T")),
3235 });
3236 let result = ty.substitute_templates(&bindings_t_string());
3237 let Atomic::TNonEmptyList { value } = &result.types[0] else {
3238 panic!("expected TNonEmptyList");
3239 };
3240 assert!(matches!(value.types[0], Atomic::TString));
3241 }
3242
3243 #[test]
3244 fn substitute_keyed_array_property_types() {
3245 use crate::atomic::{ArrayKey, KeyedProperty};
3246 let mut props = KeyedProperties::default();
3247 props.insert(
3248 ArrayKey::String(Arc::from("name")),
3249 KeyedProperty {
3250 ty: t_param("T"),
3251 optional: false,
3252 },
3253 );
3254 props.insert(
3255 ArrayKey::String(Arc::from("tag")),
3256 KeyedProperty {
3257 ty: t_param("T"),
3258 optional: true,
3259 },
3260 );
3261 let ty = Type::single(Atomic::TKeyedArray {
3262 properties: Arc::new(props),
3263 is_open: true,
3264 is_list: false,
3265 });
3266 let result = ty.substitute_templates(&bindings_t_string());
3267 let Atomic::TKeyedArray {
3268 properties,
3269 is_open,
3270 is_list,
3271 } = &result.types[0]
3272 else {
3273 panic!("expected TKeyedArray");
3274 };
3275 assert!(is_open);
3276 assert!(!is_list);
3277 assert!(matches!(
3278 properties[&ArrayKey::String(Arc::from("name"))].ty.types[0],
3279 Atomic::TString
3280 ));
3281 assert!(properties[&ArrayKey::String(Arc::from("tag"))].optional);
3282 assert!(matches!(
3283 properties[&ArrayKey::String(Arc::from("tag"))].ty.types[0],
3284 Atomic::TString
3285 ));
3286 }
3287
3288 #[test]
3289 fn substitute_callable_params_and_return() {
3290 use crate::atomic::FnParam;
3291 let ty = Type::single(Atomic::TCallable {
3292 params: Some(Box::new(vec![FnParam {
3293 name: Name::new("x"),
3294 ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3295 out_ty: None,
3296 default: None,
3297 is_variadic: false,
3298 is_byref: false,
3299 is_optional: false,
3300 }])),
3301 return_type: Some(Box::new(t_param("T"))),
3302 is_pure: false,
3303 });
3304 let result = ty.substitute_templates(&bindings_t_string());
3305 let Atomic::TCallable {
3306 params,
3307 return_type,
3308 ..
3309 } = &result.types[0]
3310 else {
3311 panic!("expected TCallable");
3312 };
3313 let param_ty = params.as_ref().unwrap()[0].ty.as_ref().unwrap();
3314 let param_union = param_ty.to_union();
3315 assert!(matches!(param_union.types[0], Atomic::TString));
3316 let ret = return_type.as_ref().unwrap();
3317 assert!(matches!(ret.types[0], Atomic::TString));
3318 }
3319
3320 #[test]
3321 fn substitute_callable_bare_no_panic() {
3322 let ty = Type::single(Atomic::TCallable {
3324 params: None,
3325 return_type: None,
3326 is_pure: false,
3327 });
3328 let result = ty.substitute_templates(&bindings_t_string());
3329 assert!(matches!(
3330 result.types[0],
3331 Atomic::TCallable {
3332 params: None,
3333 return_type: None,
3334 ..
3335 }
3336 ));
3337 }
3338
3339 #[test]
3340 fn substitute_closure_params_return_and_this() {
3341 use crate::atomic::FnParam;
3342 let ty = Type::single(Atomic::TClosure {
3343 data: Box::new(crate::atomic::ClosureData {
3344 params: Box::new([FnParam {
3345 name: Name::new("a"),
3346 ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3347 out_ty: None,
3348 default: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3349 is_variadic: true,
3350 is_byref: true,
3351 is_optional: true,
3352 }]),
3353 return_type: t_param("T"),
3354 this_type: Some(t_param("T")),
3355 is_pure: false,
3356 is_static: false,
3357 rejects_surplus_args: false,
3358 }),
3359 });
3360 let result = ty.substitute_templates(&bindings_t_string());
3361 let Atomic::TClosure { data } = &result.types[0] else {
3362 panic!("expected TClosure");
3363 };
3364 let (params, return_type, this_type) = (&data.params, &data.return_type, &data.this_type);
3365 let p = ¶ms[0];
3366 let ty_union = p.ty.as_ref().unwrap().to_union();
3367 let default_union = p.default.as_ref().unwrap().to_union();
3368 assert!(matches!(ty_union.types[0], Atomic::TString));
3369 assert!(matches!(default_union.types[0], Atomic::TString));
3370 assert!(p.is_variadic);
3372 assert!(p.is_byref);
3373 assert!(p.is_optional);
3374 assert!(matches!(return_type.types[0], Atomic::TString));
3375 assert!(matches!(
3376 this_type.as_ref().unwrap().types[0],
3377 Atomic::TString
3378 ));
3379 }
3380
3381 #[test]
3382 fn substitute_conditional_all_branches() {
3383 let ty = Type::single(conditional(
3384 None,
3385 t_param("T"),
3386 t_param("T"),
3387 Type::single(Atomic::TInt),
3388 ));
3389 let result = ty.substitute_templates(&bindings_t_string());
3390 let Atomic::TConditional { data } = &result.types[0] else {
3391 panic!("expected TConditional");
3392 };
3393 let (subject, if_true, if_false) = (&data.subject, &data.if_true, &data.if_false);
3394 assert!(matches!(subject.types[0], Atomic::TString));
3395 assert!(matches!(if_true.types[0], Atomic::TString));
3396 assert!(matches!(if_false.types[0], Atomic::TInt));
3397 }
3398
3399 #[test]
3400 fn resolve_conditional_is_null_non_null_arg() {
3401 let ty = Type::single(conditional(
3402 Some(Name::new("x")),
3403 Type::single(Atomic::TNull),
3404 Type::single(Atomic::TInt),
3405 Type::single(Atomic::TString),
3406 ));
3407 let result = ty.resolve_conditional_returns(|name| {
3408 if name == "x" {
3409 Some(Type::single(Atomic::TString)) } else {
3411 None
3412 }
3413 });
3414 assert!(result.types.len() == 1);
3415 assert!(matches!(result.types[0], Atomic::TString));
3416 }
3417
3418 #[test]
3419 fn resolve_conditional_is_null_null_arg() {
3420 let ty = Type::single(conditional(
3421 Some(Name::new("x")),
3422 Type::single(Atomic::TNull),
3423 Type::single(Atomic::TInt),
3424 Type::single(Atomic::TString),
3425 ));
3426 let result = ty.resolve_conditional_returns(|name| {
3427 if name == "x" {
3428 Some(Type::single(Atomic::TNull)) } else {
3430 None
3431 }
3432 });
3433 assert!(result.types.len() == 1);
3434 assert!(matches!(result.types[0], Atomic::TInt));
3435 }
3436
3437 #[test]
3438 fn resolve_conditional_is_null_nullable_arg_widens_to_branch_union() {
3439 let mut nullable_str = Type::single(Atomic::TString);
3440 nullable_str.add_type(Atomic::TNull);
3441 let ty = Type::single(conditional(
3442 Some(Name::new("x")),
3443 Type::single(Atomic::TNull),
3444 Type::single(Atomic::TInt),
3445 Type::single(Atomic::TString),
3446 ));
3447 let result = ty.resolve_conditional_returns(|name| {
3448 if name == "x" {
3449 Some(nullable_str.clone())
3450 } else {
3451 None
3452 }
3453 });
3454 assert_eq!(result.types.len(), 2);
3456 assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
3457 assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
3458 }
3459
3460 #[test]
3461 fn resolve_conditional_nested_widens_inner_branch() {
3462 let inner = Type::single(conditional(
3465 Some(Name::new("x")),
3466 Type::single(Atomic::TString),
3467 Type::single(Atomic::TString),
3468 Type::single(Atomic::TFloat),
3469 ));
3470 let ty = Type::single(conditional(
3471 Some(Name::new("x")),
3472 Type::single(Atomic::TNull),
3473 Type::single(Atomic::TInt),
3474 inner,
3475 ));
3476 let result = ty.resolve_conditional_returns(|_| None);
3478 assert!(
3479 result
3480 .types
3481 .iter()
3482 .all(|t| !matches!(t, Atomic::TConditional { .. })),
3483 "no TConditional should survive: {:?}",
3484 result.types
3485 );
3486 assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
3487 assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
3488 assert!(result.types.iter().any(|t| matches!(t, Atomic::TFloat)));
3489 }
3490
3491 #[test]
3492 fn resolve_conditional_nested_resolves_inner_branch() {
3493 let inner = Type::single(conditional(
3497 Some(Name::new("x")),
3498 Type::single(Atomic::TString),
3499 Type::single(Atomic::TString),
3500 Type::single(Atomic::TFloat),
3501 ));
3502 let ty = Type::single(conditional(
3503 Some(Name::new("x")),
3504 Type::single(Atomic::TNull),
3505 Type::single(Atomic::TInt),
3506 inner,
3507 ));
3508 let result = ty.resolve_conditional_returns(|name| {
3510 if name == "x" {
3511 Some(Type::single(Atomic::TString))
3512 } else {
3513 None
3514 }
3515 });
3516 assert!(
3517 result
3518 .types
3519 .iter()
3520 .all(|t| !matches!(t, Atomic::TConditional { .. })),
3521 "no TConditional should survive: {:?}",
3522 result.types
3523 );
3524 assert_eq!(result.types.len(), 1);
3525 assert!(matches!(result.types[0], Atomic::TString));
3526 }
3527
3528 #[test]
3529 fn resolve_conditional_true_subject_bool_arg_widens() {
3530 let ty = Type::single(conditional(
3534 Some(Name::new("x")),
3535 Type::single(Atomic::TTrue),
3536 Type::single(Atomic::TInt),
3537 Type::single(Atomic::TString),
3538 ));
3539 let result = ty.resolve_conditional_returns(|name| {
3540 if name == "x" {
3541 Some(Type::single(Atomic::TBool))
3542 } else {
3543 None
3544 }
3545 });
3546 assert_eq!(result.types.len(), 2);
3547 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3548 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3549 }
3550
3551 #[test]
3552 fn resolve_conditional_true_subject_mixed_arg_widens() {
3553 let ty = Type::single(conditional(
3556 Some(Name::new("x")),
3557 Type::single(Atomic::TTrue),
3558 Type::single(Atomic::TInt),
3559 Type::single(Atomic::TString),
3560 ));
3561 let result = ty.resolve_conditional_returns(|name| {
3562 if name == "x" {
3563 Some(Type::mixed())
3564 } else {
3565 None
3566 }
3567 });
3568 assert_eq!(result.types.len(), 2);
3569 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3570 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3571 }
3572
3573 #[test]
3574 fn resolve_conditional_true_subject_literal_args() {
3575 let ty = Type::single(conditional(
3578 Some(Name::new("x")),
3579 Type::single(Atomic::TTrue),
3580 Type::single(Atomic::TInt),
3581 Type::single(Atomic::TString),
3582 ));
3583 let false_arg = ty.clone().resolve_conditional_returns(|name| {
3584 if name == "x" {
3585 Some(Type::single(Atomic::TFalse))
3586 } else {
3587 None
3588 }
3589 });
3590 assert_eq!(false_arg.types.len(), 1);
3591 assert!(matches!(false_arg.types[0], Atomic::TString));
3592
3593 let true_arg = ty.resolve_conditional_returns(|name| {
3594 if name == "x" {
3595 Some(Type::single(Atomic::TTrue))
3596 } else {
3597 None
3598 }
3599 });
3600 assert_eq!(true_arg.types.len(), 1);
3601 assert!(matches!(true_arg.types[0], Atomic::TInt));
3602 }
3603
3604 #[test]
3605 fn resolve_conditional_bool_subject_scalar_arg_widens() {
3606 let ty = Type::single(conditional(
3610 Some(Name::new("x")),
3611 Type::single(Atomic::TBool),
3612 Type::single(Atomic::TInt),
3613 Type::single(Atomic::TString),
3614 ));
3615 let result = ty.resolve_conditional_returns(|name| {
3616 if name == "x" {
3617 Some(Type::single(Atomic::TScalar))
3618 } else {
3619 None
3620 }
3621 });
3622 assert_eq!(result.types.len(), 2);
3623 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3624 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3625 }
3626
3627 #[test]
3628 fn resolve_conditional_string_subject_bool_arg_false_branch() {
3629 let ty = Type::single(conditional(
3633 Some(Name::new("x")),
3634 Type::single(Atomic::TString),
3635 Type::single(Atomic::TInt),
3636 Type::single(Atomic::TBool),
3637 ));
3638 let result = ty.resolve_conditional_returns(|name| {
3639 if name == "x" {
3640 Some(Type::single(Atomic::TBool))
3641 } else {
3642 None
3643 }
3644 });
3645 assert_eq!(result.types.len(), 1);
3646 assert!(matches!(result.types[0], Atomic::TBool));
3647 }
3648
3649 #[test]
3650 fn resolve_conditional_list_subject_bare_array_arg_widens() {
3651 let ty = Type::single(conditional(
3654 Some(Name::new("x")),
3655 Type::single(Atomic::TList {
3656 value: Box::new(Type::mixed()),
3657 }),
3658 Type::single(Atomic::TInt),
3659 Type::single(Atomic::TString),
3660 ));
3661 let result = ty.resolve_conditional_returns(|name| {
3662 if name == "x" {
3663 Some(Type::single(Atomic::TArray {
3664 key: Box::new(Type::mixed()),
3665 value: Box::new(Type::mixed()),
3666 }))
3667 } else {
3668 None
3669 }
3670 });
3671 assert_eq!(result.types.len(), 2);
3672 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3673 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3674 }
3675
3676 #[test]
3677 fn resolve_conditional_float_subject_int_literal_false_branch() {
3678 let ty = resolve_conditional_branch(
3681 &Type::single(Atomic::TFloat),
3682 &Type::single(Atomic::TLiteralInt(42)),
3683 &Type::single(Atomic::TInt),
3684 &Type::single(Atomic::TString),
3685 );
3686 assert!(matches!(
3687 ty.as_ref(),
3688 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3689 ));
3690 }
3691
3692 #[test]
3693 fn resolve_conditional_int_subject_float_literal_false_branch() {
3694 let ty = resolve_conditional_branch(
3695 &Type::single(Atomic::TInt),
3696 &Type::single(Atomic::TLiteralFloat(1, 0)),
3697 &Type::single(Atomic::TInt),
3698 &Type::single(Atomic::TString),
3699 );
3700 assert!(matches!(
3701 ty.as_ref(),
3702 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3703 ));
3704 }
3705
3706 #[test]
3707 fn resolve_conditional_float_subject_float_literal_then_branch() {
3708 let ty = resolve_conditional_branch(
3709 &Type::single(Atomic::TFloat),
3710 &Type::single(Atomic::TLiteralFloat(1, 5)),
3711 &Type::single(Atomic::TInt),
3712 &Type::single(Atomic::TString),
3713 );
3714 assert!(matches!(
3715 ty.as_ref(),
3716 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3717 ));
3718 }
3719
3720 #[test]
3721 fn resolve_conditional_int_subject_int_literal_then_branch() {
3722 let ty = resolve_conditional_branch(
3723 &Type::single(Atomic::TInt),
3724 &Type::single(Atomic::TLiteralInt(7)),
3725 &Type::single(Atomic::TInt),
3726 &Type::single(Atomic::TString),
3727 );
3728 assert!(matches!(
3729 ty.as_ref(),
3730 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3731 ));
3732 }
3733
3734 #[test]
3735 fn resolve_conditional_int_subject_float_arg_false_branch() {
3736 let ty = resolve_conditional_branch(
3739 &Type::single(Atomic::TInt),
3740 &Type::single(Atomic::TFloat),
3741 &Type::single(Atomic::TInt),
3742 &Type::single(Atomic::TString),
3743 );
3744 assert!(matches!(
3745 ty.as_ref(),
3746 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3747 ));
3748 }
3749
3750 #[test]
3751 fn resolve_conditional_array_subject_string_arg_false_branch() {
3752 let ty = resolve_conditional_branch(
3753 &Type::single(Atomic::TArray {
3754 key: Box::new(Type::mixed()),
3755 value: Box::new(Type::mixed()),
3756 }),
3757 &Type::single(Atomic::TString),
3758 &Type::single(Atomic::TInt),
3759 &Type::single(Atomic::TString),
3760 );
3761 assert!(matches!(
3762 ty.as_ref(),
3763 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3764 ));
3765 }
3766
3767 #[test]
3768 fn resolve_conditional_array_subject_bool_arg_false_branch() {
3769 let ty = resolve_conditional_branch(
3770 &Type::single(Atomic::TArray {
3771 key: Box::new(Type::mixed()),
3772 value: Box::new(Type::mixed()),
3773 }),
3774 &Type::single(Atomic::TBool),
3775 &Type::single(Atomic::TInt),
3776 &Type::single(Atomic::TString),
3777 );
3778 assert!(matches!(
3779 ty.as_ref(),
3780 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3781 ));
3782 }
3783
3784 #[test]
3785 fn resolve_conditional_array_subject_mixed_arg_widens() {
3786 let ty = resolve_conditional_branch(
3790 &Type::single(Atomic::TArray {
3791 key: Box::new(Type::mixed()),
3792 value: Box::new(Type::mixed()),
3793 }),
3794 &Type::mixed(),
3795 &Type::single(Atomic::TInt),
3796 &Type::single(Atomic::TString),
3797 );
3798 assert!(ty.is_none());
3799 }
3800
3801 #[test]
3802 fn resolve_conditional_array_subject_list_arg_then_branch() {
3803 let ty = resolve_conditional_branch(
3806 &Type::single(Atomic::TArray {
3807 key: Box::new(Type::mixed()),
3808 value: Box::new(Type::mixed()),
3809 }),
3810 &Type::single(Atomic::TList {
3811 value: Box::new(Type::mixed()),
3812 }),
3813 &Type::single(Atomic::TInt),
3814 &Type::single(Atomic::TString),
3815 );
3816 assert!(matches!(
3817 ty.as_ref(),
3818 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3819 ));
3820 }
3821
3822 #[test]
3823 fn resolve_conditional_list_subject_keyed_list_arg_then_branch() {
3824 let ty = resolve_conditional_branch(
3826 &Type::single(Atomic::TList {
3827 value: Box::new(Type::mixed()),
3828 }),
3829 &Type::single(Atomic::TKeyedArray {
3830 properties: Arc::default(),
3831 is_open: false,
3832 is_list: true,
3833 }),
3834 &Type::single(Atomic::TInt),
3835 &Type::single(Atomic::TString),
3836 );
3837 assert!(matches!(
3838 ty.as_ref(),
3839 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3840 ));
3841 }
3842
3843 #[test]
3844 fn resolve_conditional_list_subject_list_string_union_widens() {
3845 let ty = resolve_conditional_branch(
3849 &Type::single(Atomic::TList {
3850 value: Box::new(Type::mixed()),
3851 }),
3852 &Type::from_vec(vec![
3853 Atomic::TList {
3854 value: Box::new(Type::mixed()),
3855 },
3856 Atomic::TString,
3857 ]),
3858 &Type::single(Atomic::TInt),
3859 &Type::single(Atomic::TString),
3860 );
3861 assert!(ty.is_none());
3862 }
3863
3864 #[test]
3865 fn resolve_conditional_numeric_subject_widens() {
3866 let ty = resolve_conditional_branch(
3870 &Type::single(Atomic::TNumeric),
3871 &Type::single(Atomic::TLiteralString("123".into())),
3872 &Type::single(Atomic::TInt),
3873 &Type::single(Atomic::TString),
3874 );
3875 assert!(ty.is_none());
3876 }
3877
3878 #[test]
3879 fn resolve_conditional_non_empty_string_subject_widens() {
3880 let ty = resolve_conditional_branch(
3883 &Type::single(Atomic::TNonEmptyString),
3884 &Type::single(Atomic::TString),
3885 &Type::single(Atomic::TInt),
3886 &Type::single(Atomic::TString),
3887 );
3888 assert!(ty.is_none());
3889 }
3890
3891 #[test]
3892 fn resolve_conditional_template_arg_widens() {
3893 let ty = resolve_conditional_branch(
3896 &Type::single(Atomic::TString),
3897 &t_param("T"),
3898 &Type::single(Atomic::TInt),
3899 &Type::single(Atomic::TString),
3900 );
3901 assert!(ty.is_none());
3902 }
3903
3904 #[test]
3905 fn resolve_conditional_mixed_subject_bool_arg_then_branch() {
3906 let ty = resolve_conditional_branch(
3909 &Type::single(Atomic::TMixed),
3910 &Type::single(Atomic::TBool),
3911 &Type::single(Atomic::TInt),
3912 &Type::single(Atomic::TString),
3913 );
3914 assert!(matches!(
3915 ty.as_ref(),
3916 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3917 ));
3918 }
3919
3920 #[test]
3921 fn resolve_conditional_scalar_subject_null_arg_false_branch() {
3922 let ty = resolve_conditional_branch(
3925 &Type::single(Atomic::TScalar),
3926 &Type::single(Atomic::TNull),
3927 &Type::single(Atomic::TInt),
3928 &Type::single(Atomic::TString),
3929 );
3930 assert!(matches!(
3931 ty.as_ref(),
3932 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3933 ));
3934 }
3935
3936 #[test]
3937 fn resolve_conditional_object_subject_named_arg_then_branch() {
3938 let ty = resolve_conditional_branch(
3940 &Type::single(Atomic::TObject),
3941 &Type::single(Atomic::TNamedObject {
3942 fqcn: Name::new("Foo"),
3943 type_params: empty_type_params(),
3944 }),
3945 &Type::single(Atomic::TInt),
3946 &Type::single(Atomic::TString),
3947 );
3948 assert!(matches!(
3949 ty.as_ref(),
3950 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3951 ));
3952 }
3953
3954 #[test]
3955 fn resolve_conditional_named_subject_other_class_widens() {
3956 let ty = resolve_conditional_branch(
3960 &Type::single(Atomic::TNamedObject {
3961 fqcn: Name::new("Foo"),
3962 type_params: empty_type_params(),
3963 }),
3964 &Type::single(Atomic::TNamedObject {
3965 fqcn: Name::new("Bar"),
3966 type_params: empty_type_params(),
3967 }),
3968 &Type::single(Atomic::TInt),
3969 &Type::single(Atomic::TString),
3970 );
3971 assert!(ty.is_none());
3972 }
3973
3974 #[test]
3975 fn resolve_conditional_enum_case_subject_widens() {
3976 let ty = resolve_conditional_branch(
3979 &Type::single(Atomic::TLiteralEnumCase {
3980 enum_fqcn: Name::new("RoundingMode"),
3981 case_name: Name::new("Unnecessary"),
3982 }),
3983 &Type::single(Atomic::TInt),
3984 &Type::single(Atomic::TInt),
3985 &Type::single(Atomic::TString),
3986 );
3987 assert!(ty.is_none());
3988 }
3989
3990 #[test]
3991 fn resolve_conditional_null_subject_bool_arg_false_branch() {
3992 let ty = resolve_conditional_branch(
3994 &Type::single(Atomic::TNull),
3995 &Type::single(Atomic::TBool),
3996 &Type::single(Atomic::TInt),
3997 &Type::single(Atomic::TString),
3998 );
3999 assert!(matches!(
4000 ty.as_ref(),
4001 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4002 ));
4003 }
4004
4005 #[test]
4006 fn resolve_conditional_bool_subject_true_arg_then_branch() {
4007 let ty = resolve_conditional_branch(
4010 &Type::single(Atomic::TBool),
4011 &Type::single(Atomic::TTrue),
4012 &Type::single(Atomic::TInt),
4013 &Type::single(Atomic::TString),
4014 );
4015 assert!(matches!(
4016 ty.as_ref(),
4017 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4018 ));
4019 }
4020
4021 #[test]
4022 fn substitute_intersection_parts() {
4023 let ty = Type::single(Atomic::TIntersection {
4024 parts: vec_to_type_params(vec![
4025 Type::single(Atomic::TNamedObject {
4026 fqcn: Name::new("Countable"),
4027 type_params: empty_type_params(),
4028 }),
4029 t_param("T"),
4030 ]),
4031 });
4032 let result = ty.substitute_templates(&bindings_t_string());
4033 let Atomic::TIntersection { parts } = &result.types[0] else {
4034 panic!("expected TIntersection");
4035 };
4036 assert_eq!(parts.len(), 2);
4037 assert!(matches!(parts[0].types[0], Atomic::TNamedObject { .. }));
4038 assert!(matches!(parts[1].types[0], Atomic::TString));
4039 }
4040
4041 fn shape(props: &[(&str, Atomic, bool)], is_open: bool) -> Atomic {
4042 Atomic::TKeyedArray {
4043 properties: Arc::new(
4044 props
4045 .iter()
4046 .map(|(k, ty, optional)| {
4047 (
4048 ArrayKey::String(Arc::from(*k)),
4049 KeyedProperty {
4050 ty: Type::single(ty.clone()),
4051 optional: *optional,
4052 },
4053 )
4054 })
4055 .collect(),
4056 ),
4057 is_open,
4058 is_list: false,
4059 }
4060 }
4061
4062 fn shape_with_bits(bits: u32, is_open: bool) -> Atomic {
4064 let names: Vec<String> = (0..5).map(|i| format!("k{i}")).collect();
4065 let mut props = vec![("a", Atomic::TInt, false)];
4066 props.extend(
4067 (0..5)
4068 .filter(|i| bits & (1 << i) != 0)
4069 .map(|i| (names[i].as_str(), Atomic::TString, false)),
4070 );
4071 shape(&props, is_open)
4072 }
4073
4074 fn keyed_count(ty: &Type) -> usize {
4075 ty.types
4076 .iter()
4077 .filter(|t| matches!(t, Atomic::TKeyedArray { .. }))
4078 .count()
4079 }
4080
4081 #[test]
4082 fn add_type_keeps_few_shapes_apart() {
4083 let mut ty = Type::empty();
4084 for bits in 0..MAX_KEYED_SHAPES as u32 {
4085 ty.add_type(shape_with_bits(bits, false));
4086 }
4087 assert_eq!(keyed_count(&ty), MAX_KEYED_SHAPES);
4088 }
4089
4090 #[test]
4091 fn add_type_folds_shapes_past_the_limit() {
4092 let mut ty = Type::empty();
4093 for bits in 0..32 {
4094 ty.add_type(shape_with_bits(bits, false));
4095 }
4096 assert!(keyed_count(&ty) <= MAX_KEYED_SHAPES);
4097 for t in &ty.types {
4099 let Atomic::TKeyedArray { properties, .. } = t else {
4100 continue;
4101 };
4102 assert!(!properties[&ArrayKey::String(Arc::from("a"))].optional);
4103 }
4104 for i in 0..5 {
4105 let key = ArrayKey::String(Arc::from(format!("k{i}").as_str()));
4106 assert!(ty.types.iter().any(|t| matches!(
4107 t,
4108 Atomic::TKeyedArray { properties, .. } if properties.contains_key(&key)
4109 )));
4110 }
4111 }
4112
4113 #[test]
4114 fn add_type_folds_generic_arrays_past_the_limit() {
4115 let mut ty = Type::empty();
4116 for i in 0..32 {
4117 ty.add_type(Atomic::TArray {
4118 key: Box::new(Type::single(Atomic::TInt)),
4119 value: Box::new(Type::single(Atomic::TLiteralInt(i))),
4120 });
4121 }
4122 assert!(ty.types.len() <= MAX_GENERIC_ARRAYS);
4123 for i in 0..32 {
4124 assert!(ty.types.iter().any(|t| matches!(
4125 t,
4126 Atomic::TArray { value, .. } if value.types.contains(&Atomic::TLiteralInt(i))
4127 )));
4128 }
4129 }
4130
4131 #[test]
4132 fn combine_keeps_emptiness_and_open_shape_soundness() {
4133 assert!(combine_keyed_arrays(
4135 &shape(&[], false),
4136 &shape(&[("a", Atomic::TInt, false)], false)
4137 )
4138 .is_none());
4139 assert!(combine_keyed_arrays(
4141 &shape(&[("a", Atomic::TInt, false)], true),
4142 &shape(&[("a", Atomic::TInt, false)], false)
4143 )
4144 .is_none());
4145 assert_eq!(
4147 combine_keyed_arrays(
4148 &shape(&[("a", Atomic::TInt, false)], true),
4149 &shape(
4150 &[("a", Atomic::TInt, false), ("k", Atomic::TString, false)],
4151 true
4152 )
4153 ),
4154 Some(shape(&[("a", Atomic::TInt, false)], true))
4155 );
4156 }
4157
4158 #[test]
4159 fn substitute_no_template_params_identity() {
4160 let ty = Type::single(Atomic::TInt);
4161 let result = ty.substitute_templates(&bindings_t_string());
4162 assert!(matches!(result.types[0], Atomic::TInt));
4163 }
4164}