1use rustc_hash::FxHashMap;
2use serde::{Deserialize, Serialize};
3use smallvec::SmallVec;
4use std::sync::{Arc, OnceLock};
5
6use crate::atomic::{
7 ArrayKey, Atomic, IntRefinement, KeyedProperties, KeyedProperty, StringRefinement,
8};
9use crate::symbol::Name;
10
11pub fn empty_type_params() -> Arc<[Type]> {
15 static EMPTY: OnceLock<Arc<[Type]>> = OnceLock::new();
16 EMPTY.get_or_init(|| Arc::from([] as [Type; 0])).clone()
17}
18
19pub fn vec_to_type_params(v: Vec<Type>) -> Arc<[Type]> {
22 if v.is_empty() {
23 empty_type_params()
24 } else {
25 Arc::from(v)
26 }
27}
28
29pub type AtomicVec = SmallVec<[Atomic; 2]>;
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum CloneValidity {
35 Cloneable,
37 Invalid,
39 PossiblyInvalid,
41 Unknown,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
50pub struct Type {
51 pub types: AtomicVec,
52 pub possibly_undefined: bool,
54 pub from_docblock: bool,
56 pub falsy_stripped: bool,
64 pub possibly_absent_offset: bool,
75}
76
77type IntBounds = (Option<i64>, Option<i64>);
78
79fn int_bounds(a: &Atomic) -> Option<IntBounds> {
81 match a {
82 Atomic::TInt => Some((None, None)),
83 Atomic::TLiteralInt(n) => Some((Some(*n), Some(*n))),
84 Atomic::TPositiveInt => Some((Some(1), None)),
85 Atomic::TNonNegativeInt => Some((Some(0), None)),
86 Atomic::TNegativeInt => Some((None, Some(-1))),
87 Atomic::TIntRange { min, max } => Some((*min, *max)),
88 _ => None,
89 }
90}
91
92fn bounds_contain(outer: IntBounds, inner: IntBounds) -> bool {
93 let lo_ok = match (outer.0, inner.0) {
94 (None, _) => true,
95 (Some(o), Some(i)) => o <= i,
96 (Some(_), None) => false,
97 };
98 let hi_ok = match (outer.1, inner.1) {
99 (None, _) => true,
100 (Some(o), Some(i)) => o >= i,
101 (Some(_), None) => false,
102 };
103 lo_ok && hi_ok
104}
105
106const MAX_KEYED_SHAPES: usize = 8;
113
114const MAX_GENERIC_ARRAYS: usize = 8;
117
118const MAX_LITERAL_STRINGS: usize = 128;
122
123pub(crate) fn combine_generic_arrays(a: &Atomic, b: &Atomic) -> Option<Atomic> {
125 let union = |x: &Type, y: &Type| {
126 let mut t = x.clone();
127 t.merge_with(y);
128 Box::new(t)
129 };
130 Some(match (a, b) {
131 (Atomic::TArray { key: ka, value: va }, Atomic::TArray { key: kb, value: vb }) => {
132 Atomic::TArray {
133 key: union(ka, kb),
134 value: union(va, vb),
135 }
136 }
137 (
138 Atomic::TNonEmptyArray { key: ka, value: va },
139 Atomic::TNonEmptyArray { key: kb, value: vb },
140 ) => Atomic::TNonEmptyArray {
141 key: union(ka, kb),
142 value: union(va, vb),
143 },
144 (Atomic::TList { value: va }, Atomic::TList { value: vb }) => Atomic::TList {
145 value: union(va, vb),
146 },
147 (Atomic::TNonEmptyList { value: va }, Atomic::TNonEmptyList { value: vb }) => {
148 Atomic::TNonEmptyList {
149 value: union(va, vb),
150 }
151 }
152 _ => return None,
153 })
154}
155
156fn array_covered(sub: &Atomic, sup: &Atomic) -> bool {
160 fn parts(a: &Atomic) -> Option<(Option<&Type>, &Type)> {
161 match a {
162 Atomic::TArray { key, value } | Atomic::TNonEmptyArray { key, value } => {
163 Some((Some(key), value))
164 }
165 Atomic::TList { value } | Atomic::TNonEmptyList { value } => Some((None, value)),
166 _ => None,
167 }
168 }
169 let fits = |x: &Type, y: &Type| {
170 values_covered(x, y) || (!is_opaque(x) && !is_opaque(y) && x.is_subtype_structural(y))
171 };
172 if std::mem::discriminant(sub) != std::mem::discriminant(sup) {
173 return false;
174 }
175 if let (
176 Atomic::TKeyedArray {
177 properties: pa,
178 is_open: oa,
179 is_list: la,
180 },
181 Atomic::TKeyedArray {
182 properties: pb,
183 is_open: ob,
184 is_list: lb,
185 },
186 ) = (sub, sup)
187 {
188 return oa == ob
189 && la == lb
190 && pa.len() == pb.len()
191 && pa.iter().all(|(key, x)| {
192 pb.get(key)
193 .is_some_and(|y| x.optional == y.optional && values_covered(&x.ty, &y.ty))
194 })
195 && match (&pa.remainder, &pb.remainder) {
196 (None, None) => true,
197 (Some(a), Some(b)) => values_covered(a, b),
198 _ => false,
199 };
200 }
201 match (parts(sub), parts(sup)) {
202 (Some((sub_key, sub_value)), Some((sup_key, sup_value))) => {
203 fits(sub_value, sup_value)
204 && match (sub_key, sup_key) {
205 (Some(a), Some(b)) => fits(a, b),
206 _ => true,
207 }
208 }
209 _ => false,
210 }
211}
212
213fn values_covered(x: &Type, y: &Type) -> bool {
217 if is_opaque(x) || is_opaque(y) {
218 return x == y;
219 }
220 x.types.iter().all(|a| {
221 let scalar_refinement =
222 !matches!(a, Atomic::TKeyedArray { .. }) && crate::generalize::is_generalizable(a);
223 y.types.iter().any(|b| {
224 a == b
225 || array_covered(a, b)
226 || (scalar_refinement
227 && !(a.is_int() && matches!(b, Atomic::TFloat))
228 && atomic_subtype(a, b))
229 })
230 })
231}
232
233fn is_opaque(t: &Type) -> bool {
234 t.types
235 .iter()
236 .any(|a| matches!(a, Atomic::TMixed | Atomic::TTemplateParam { .. }))
237}
238
239fn combine_keyed_arrays(a: &Atomic, b: &Atomic) -> Option<Atomic> {
244 let (
245 Atomic::TKeyedArray {
246 properties: pa,
247 is_open: oa,
248 is_list: la,
249 },
250 Atomic::TKeyedArray {
251 properties: pb,
252 is_open: ob,
253 is_list: lb,
254 },
255 ) = (a, b)
256 else {
257 return None;
258 };
259 let non_empty = |p: &KeyedProperties| p.values().any(|v| !v.optional);
260 if oa != ob || la != lb || non_empty(pa) != non_empty(pb) {
261 return None;
262 }
263 let mut properties =
264 KeyedProperties::with_capacity_and_hasher(pa.len().max(pb.len()), Default::default());
265 for (key, x) in pa.iter() {
266 let prop = match pb.get(key) {
267 Some(y) => {
268 let mut ty = x.ty.clone();
269 ty.merge_with(&y.ty);
270 KeyedProperty {
271 ty,
272 optional: x.optional || y.optional,
273 }
274 }
275 None if *oa => continue,
278 None => KeyedProperty {
279 ty: x.ty.clone(),
280 optional: true,
281 },
282 };
283 properties.insert(key.clone(), prop);
284 }
285 if !*oa {
286 for (key, y) in pb.iter() {
287 if !pa.contains_key(key) {
288 properties.insert(
289 key.clone(),
290 KeyedProperty {
291 ty: y.ty.clone(),
292 optional: true,
293 },
294 );
295 }
296 }
297 }
298 Some(Atomic::TKeyedArray {
299 properties: Arc::new(properties),
300 is_open: *oa,
301 is_list: *la,
302 })
303}
304
305impl Type {
306 pub fn empty() -> Self {
309 Self {
310 types: SmallVec::new(),
311 possibly_undefined: false,
312 from_docblock: false,
313 falsy_stripped: false,
314 possibly_absent_offset: false,
315 }
316 }
317
318 pub fn single(atomic: Atomic) -> Self {
319 let mut types = SmallVec::new();
320 types.push(atomic);
321 Self {
322 types,
323 possibly_undefined: false,
324 from_docblock: false,
325 falsy_stripped: false,
326 possibly_absent_offset: false,
327 }
328 }
329
330 pub fn mixed() -> Self {
331 Self::single(Atomic::TMixed)
332 }
333
334 pub fn void() -> Self {
335 Self::single(Atomic::TVoid)
336 }
337
338 pub fn never() -> Self {
339 Self::single(Atomic::TNever)
340 }
341
342 pub fn null() -> Self {
343 Self::single(Atomic::TNull)
344 }
345
346 pub fn bool() -> Self {
347 Self::single(Atomic::TBool)
348 }
349
350 pub fn int() -> Self {
351 Self::single(Atomic::TInt)
352 }
353
354 pub fn float() -> Self {
355 Self::single(Atomic::TFloat)
356 }
357
358 pub fn string() -> Self {
359 Self::single(Atomic::TString)
360 }
361
362 pub fn array_key() -> Self {
365 let mut u = Self::single(Atomic::TInt);
366 u.add_type(Atomic::TString);
367 u
368 }
369
370 pub fn nullable(atomic: Atomic) -> Self {
372 if matches!(atomic, Atomic::TMixed) {
374 return Self::mixed();
375 }
376 let mut types = SmallVec::new();
377 types.push(atomic);
378 types.push(Atomic::TNull);
379 Self {
380 types,
381 possibly_undefined: false,
382 from_docblock: false,
383 falsy_stripped: false,
384 possibly_absent_offset: false,
385 }
386 }
387
388 pub fn from_vec(atomics: Vec<Atomic>) -> Self {
390 let mut u = Self::empty();
391 for a in atomics {
392 u.add_type(a);
393 }
394 u
395 }
396
397 pub fn is_empty(&self) -> bool {
400 self.types.is_empty()
401 }
402
403 pub fn is_single(&self) -> bool {
404 self.types.len() == 1
405 }
406
407 pub fn is_nullable(&self) -> bool {
408 self.types.iter().any(|t| matches!(t, Atomic::TNull))
409 }
410
411 pub fn is_array_key(&self) -> bool {
416 self.types.len() == 2
417 && self.types.iter().any(|t| matches!(t, Atomic::TInt))
418 && self.types.iter().any(|t| matches!(t, Atomic::TString))
419 }
420
421 pub fn is_mixed(&self) -> bool {
422 self.types.iter().any(|t| match t {
423 Atomic::TMixed => true,
424 Atomic::TTemplateParam { as_type, .. } => as_type.is_mixed(),
425 _ => false,
426 })
427 }
428
429 pub fn is_mixed_not_template(&self) -> bool {
434 self.is_mixed()
435 && !self
436 .types
437 .iter()
438 .any(|t| matches!(t, Atomic::TTemplateParam { .. }))
439 }
440
441 pub fn is_never(&self) -> bool {
442 self.types.iter().all(|t| matches!(t, Atomic::TNever)) && !self.types.is_empty()
443 }
444
445 pub fn clone_validity(&self) -> CloneValidity {
448 if self.types.is_empty() {
449 return CloneValidity::Unknown;
450 }
451 let mut has_non_object = false;
452 let mut has_other = false; for t in &self.types {
454 match t {
455 Atomic::TTemplateParam { as_type, .. } => match as_type.clone_validity() {
456 CloneValidity::Invalid => has_non_object = true,
457 CloneValidity::PossiblyInvalid => {
458 has_non_object = true;
459 has_other = true;
460 }
461 CloneValidity::Cloneable | CloneValidity::Unknown => has_other = true,
462 },
463 other if other.is_definitely_non_object() => has_non_object = true,
464 _ => has_other = true,
465 }
466 }
467 match (has_non_object, has_other) {
468 (true, false) => CloneValidity::Invalid,
469 (true, true) => CloneValidity::PossiblyInvalid,
470 _ => CloneValidity::Cloneable,
471 }
472 }
473
474 pub fn is_void(&self) -> bool {
475 self.is_single() && matches!(self.types[0], Atomic::TVoid)
476 }
477
478 pub fn can_be_falsy(&self) -> bool {
479 self.types.iter().any(|t| t.can_be_falsy())
480 }
481
482 pub fn can_be_truthy(&self) -> bool {
483 self.types.iter().any(|t| t.can_be_truthy())
484 }
485
486 pub fn contains<F: Fn(&Atomic) -> bool>(&self, f: F) -> bool {
487 self.types.iter().any(f)
488 }
489
490 pub fn has_named_object(&self, fqcn: &str) -> bool {
491 self.types.iter().any(|t| match t {
492 Atomic::TNamedObject { fqcn: f, .. } => f.as_ref() == fqcn,
493 _ => false,
494 })
495 }
496
497 pub fn add_type(&mut self, atomic: Atomic) {
502 if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
504 return;
505 }
506
507 if matches!(atomic, Atomic::TMixed) {
509 self.types.clear();
510 self.types.push(Atomic::TMixed);
511 return;
512 }
513
514 let atomic = if let Atomic::TConditional { data } = &atomic {
517 let (if_true, if_false) = (&data.if_true, &data.if_false);
518 let mut simplified_true = Type::empty();
519 for t in &if_true.types {
520 simplified_true.add_type(t.clone());
521 }
522 let mut simplified_false = Type::empty();
523 for t in &if_false.types {
524 simplified_false.add_type(t.clone());
525 }
526 if simplified_true == simplified_false {
527 for t in simplified_true.types {
528 self.add_type(t);
529 }
530 return;
531 }
532 atomic
533 } else {
534 atomic
535 };
536
537 if self.types.contains(&atomic) {
538 return;
539 }
540 self.add_absent_type(atomic);
541 }
542
543 fn add_absent_type(&mut self, atomic: Atomic) {
545 let mut atomic = crate::generalize::cap_array_depth(atomic);
546 if matches!(atomic, Atomic::TKeyedArray { .. })
549 && self
550 .types
551 .iter()
552 .filter(|t| matches!(t, Atomic::TKeyedArray { .. }))
553 .count()
554 >= MAX_KEYED_SHAPES
555 {
556 if let Some((idx, combined)) = self
557 .types
558 .iter()
559 .enumerate()
560 .find_map(|(i, t)| combine_keyed_arrays(t, &atomic).map(|c| (i, c)))
561 {
562 self.types.remove(idx);
563 if self.types.contains(&combined) {
564 return;
565 }
566 atomic = combined;
567 }
568 }
569
570 if self.types.iter().any(|t| array_covered(&atomic, t)) {
573 return;
574 }
575 self.types.retain(|t| !array_covered(t, &atomic));
576
577 if matches!(
578 atomic,
579 Atomic::TArray { .. }
580 | Atomic::TNonEmptyArray { .. }
581 | Atomic::TList { .. }
582 | Atomic::TNonEmptyList { .. }
583 ) && self
584 .types
585 .iter()
586 .filter(|t| std::mem::discriminant(*t) == std::mem::discriminant(&atomic))
587 .count()
588 >= MAX_GENERIC_ARRAYS
589 {
590 if let Some((idx, combined)) = self
591 .types
592 .iter()
593 .enumerate()
594 .find_map(|(i, t)| combine_generic_arrays(t, &atomic).map(|c| (i, c)))
595 {
596 self.types.remove(idx);
597 if self.types.contains(&combined) {
598 return;
599 }
600 atomic = combined;
601 }
602 }
603
604 if let Some(new_bounds) = int_bounds(&atomic) {
607 if self
608 .types
609 .iter()
610 .any(|t| int_bounds(t).is_some_and(|b| bounds_contain(b, new_bounds)))
611 {
612 return;
613 }
614 self.types
615 .retain(|t| !int_bounds(t).is_some_and(|b| bounds_contain(new_bounds, b)));
616 }
617 match atomic {
619 Atomic::TClosedResource | Atomic::TOpenResource
620 if self.types.contains(&Atomic::TResource) =>
621 {
622 return
623 }
624 Atomic::TResource => self
625 .types
626 .retain(|t| !matches!(t, Atomic::TClosedResource | Atomic::TOpenResource)),
627 _ => {}
628 }
629 const LITERAL_INT: Atomic = Atomic::TRefinedInt(IntRefinement::Literal);
631 match atomic {
632 Atomic::TRefinedInt(_) if self.types.contains(&Atomic::TInt) => return,
633 Atomic::TLiteralInt(_) if self.types.contains(&LITERAL_INT) => return,
634 LITERAL_INT => self.types.retain(|t| !matches!(t, Atomic::TLiteralInt(_))),
635 Atomic::TInt => self.types.retain(|t| !matches!(t, Atomic::TRefinedInt(_))),
636 _ => {}
637 }
638 if let Atomic::TLiteralString(_) = &atomic {
640 if self.types.iter().any(|t| matches!(t, Atomic::TString)) {
641 return;
642 }
643 let literals = self
644 .types
645 .iter()
646 .filter(|t| matches!(t, Atomic::TLiteralString(_)))
647 .count();
648 if literals >= MAX_LITERAL_STRINGS {
649 atomic = Atomic::TString;
650 }
651 }
652 if matches!(
654 atomic,
655 Atomic::TNonEmptyString | Atomic::TNonFalsyString | Atomic::TRefinedString { .. }
656 ) && self.types.iter().any(|t| matches!(t, Atomic::TString))
657 {
658 return;
659 }
660 if matches!(atomic, Atomic::TNonFalsyString)
662 && self
663 .types
664 .iter()
665 .any(|t| matches!(t, Atomic::TNonEmptyString))
666 {
667 return;
668 }
669 if matches!(atomic, Atomic::TNonEmptyString) {
670 self.types.retain(|t| !matches!(t, Atomic::TNonFalsyString));
671 }
672 if matches!(atomic, Atomic::TTrue | Atomic::TFalse)
674 && self.types.iter().any(|t| matches!(t, Atomic::TBool))
675 {
676 return;
677 }
678 if matches!(atomic, Atomic::TTrue) && self.types.iter().any(|t| matches!(t, Atomic::TFalse))
681 {
682 self.types.retain(|t| !matches!(t, Atomic::TFalse));
683 self.types.push(Atomic::TBool);
684 return;
685 }
686 if matches!(atomic, Atomic::TFalse) && self.types.iter().any(|t| matches!(t, Atomic::TTrue))
687 {
688 self.types.retain(|t| !matches!(t, Atomic::TTrue));
689 self.types.push(Atomic::TBool);
690 return;
691 }
692 if matches!(atomic, Atomic::TString) {
694 self.types.retain(|t| {
695 !matches!(
696 t,
697 Atomic::TLiteralString(_)
698 | Atomic::TNonEmptyString
699 | Atomic::TNonFalsyString
700 | Atomic::TRefinedString { .. }
701 )
702 });
703 }
704 if matches!(atomic, Atomic::TBool) {
706 self.types
707 .retain(|t| !matches!(t, Atomic::TTrue | Atomic::TFalse));
708 }
709
710 if matches!(atomic, Atomic::TNever) {
712 if !self.types.is_empty() {
713 return;
714 }
715 } else {
716 self.types.retain(|t| !matches!(t, Atomic::TNever));
717 }
718
719 if let Atomic::TKeyedArray {
725 properties,
726 is_open,
727 ..
728 } = &atomic
729 {
730 if properties.is_empty() && !is_open {
731 if let Some(idx) = self.types.iter().position(|t| {
733 matches!(
734 t,
735 Atomic::TNonEmptyArray { .. } | Atomic::TNonEmptyList { .. }
736 )
737 }) {
738 let existing = self.types.remove(idx);
739 let widened = Type::single(existing).widen_non_empty();
740 for t in widened.types {
741 self.add_absent_type(t);
742 }
743 return;
744 }
745 if self
746 .types
747 .iter()
748 .any(|t| matches!(t, Atomic::TArray { .. } | Atomic::TList { .. }))
749 {
750 return; }
752 }
753 }
754
755 let is_generic_array_or_list = matches!(
758 &atomic,
759 Atomic::TArray { .. }
760 | Atomic::TNonEmptyArray { .. }
761 | Atomic::TList { .. }
762 | Atomic::TNonEmptyList { .. }
763 );
764 let mut atomic = atomic;
765 if is_generic_array_or_list {
766 let before = self.types.len();
767 self.types.retain(|t| {
768 if let Atomic::TKeyedArray {
769 properties,
770 is_open,
771 ..
772 } = t
773 {
774 !properties.is_empty() || *is_open
775 } else {
776 true
777 }
778 });
779 if self.types.len() != before {
781 if let Some(widened) = Type::single(atomic.clone()).widen_non_empty().types.pop() {
782 if widened != atomic {
783 if self.types.contains(&widened) {
784 return;
785 }
786 atomic = widened;
787 }
788 }
789 }
790 }
791
792 self.types.push(atomic);
793 if self.types.len() > crate::generalize::MAX_UNION_MEMBERS {
794 self.collapse_wide_union();
795 }
796 }
797
798 #[cold]
800 fn collapse_wide_union(&mut self) {
801 let literal = |t: &Atomic| matches!(t, Atomic::TLiteralString(_) | Atomic::TLiteralInt(_));
802 let counted = self.types.iter().filter(|t| !literal(t)).count();
803 if counted <= crate::generalize::MAX_UNION_MEMBERS
804 || !self
805 .types
806 .iter()
807 .any(|t| !literal(t) && crate::generalize::is_generalizable(t))
808 {
809 return;
810 }
811 let members = std::mem::take(&mut self.types);
812 for atomic in members {
813 let atomic = if literal(&atomic) {
814 atomic
815 } else {
816 crate::generalize::generalize_atomic(&atomic, crate::generalize::MAX_ARRAY_DEPTH)
817 };
818 self.add_type(atomic);
819 }
820 }
821
822 pub fn remove_null(&self) -> Type {
826 self.filter(|t| !matches!(t, Atomic::TNull))
827 }
828
829 pub fn remove_false(&self) -> Type {
832 let mut result = self.filter(|t| !matches!(t, Atomic::TFalse | Atomic::TBool));
833 if self.types.iter().any(|t| matches!(t, Atomic::TBool)) {
834 result.add_type(Atomic::TTrue);
835 }
836 result
837 }
838
839 pub fn remove_true(&self) -> Type {
842 let mut result = self.filter(|t| !matches!(t, Atomic::TTrue | Atomic::TBool));
843 if self.types.iter().any(|t| matches!(t, Atomic::TBool)) {
844 result.add_type(Atomic::TFalse);
845 }
846 result
847 }
848
849 pub fn core_type(&self) -> Type {
851 self.remove_null().remove_false()
852 }
853
854 pub fn narrow_to_truthy(&self) -> Type {
856 if self.is_mixed_not_template() {
857 return Type::mixed();
858 }
859 let mut result = Type::empty();
860 result.from_docblock = self.from_docblock;
861 for t in &self.types {
862 match t {
863 Atomic::TTemplateParam { .. } => result.add_type(t.clone()),
867 Atomic::TLiteralInt(0)
869 | Atomic::TLiteralFloat(0, 0)
870 | Atomic::TNull
871 | Atomic::TFalse => {}
872 Atomic::TLiteralString(s) if s.as_ref() == "" || s.as_ref() == "0" => {}
873 Atomic::TBool => result.add_type(Atomic::TTrue),
875 Atomic::TArray { key, value } => result.add_type(Atomic::TNonEmptyArray {
877 key: key.clone(),
878 value: value.clone(),
879 }),
880 Atomic::TList { value } => result.add_type(Atomic::TNonEmptyList {
881 value: value.clone(),
882 }),
883 Atomic::TString | Atomic::TNonEmptyString => {
885 result.add_type(Atomic::TNonFalsyString)
886 }
887 Atomic::TNonNegativeInt => result.add_type(Atomic::TPositiveInt),
892 Atomic::TIntRange { min: Some(0), max } if max.is_none_or(|m| m >= 1) => {
893 let atom = if max.is_none() {
894 Atomic::TPositiveInt
895 } else {
896 Atomic::TIntRange {
897 min: Some(1),
898 max: *max,
899 }
900 };
901 result.add_type(atom);
902 }
903 Atomic::TIntRange { min, max: Some(0) } => {
905 let atom = match min {
906 None => Atomic::TNegativeInt,
907 Some(n) if *n <= -1 => Atomic::TIntRange {
908 min: *min,
909 max: Some(-1),
910 },
911 _ => continue, };
913 result.add_type(atom);
914 }
915 t if !t.can_be_truthy() => {}
917 _ => result.add_type(t.clone()),
918 }
919 }
920 result
921 }
922
923 pub fn narrow_to_falsy(&self) -> Type {
925 if self.is_mixed_not_template() {
926 return Type::from_vec(vec![
927 Atomic::TNull,
928 Atomic::TFalse,
929 Atomic::TLiteralInt(0),
930 Atomic::TLiteralString("".into()),
931 Atomic::TLiteralString("0".into()),
932 ]);
933 }
934 let mut result = Type::empty();
935 result.from_docblock = self.from_docblock;
936 for t in &self.types {
937 match t {
938 Atomic::TTemplateParam { .. } => result.add_type(t.clone()),
943 Atomic::TBool => result.add_type(Atomic::TFalse),
945 Atomic::TInt => result.add_type(Atomic::TLiteralInt(0)),
947 Atomic::TFloat => result.add_type(Atomic::TLiteralFloat(0, 0)),
949 Atomic::TString => {
951 result.add_type(Atomic::TLiteralString("".into()));
952 result.add_type(Atomic::TLiteralString("0".into()));
953 }
954 Atomic::TNumericString => result.add_type(Atomic::TLiteralString("0".into())),
956 Atomic::TNonNegativeInt => result.add_type(Atomic::TLiteralInt(0)),
958 Atomic::TIntRange {
960 min: Some(0),
961 max: Some(_) | None,
962 } => result.add_type(Atomic::TLiteralInt(0)),
963 Atomic::TIntRange { max: Some(0), .. } => result.add_type(Atomic::TLiteralInt(0)),
965 t if !t.can_be_falsy() => {} _ => result.add_type(t.clone()),
967 }
968 }
969 result
970 }
971
972 pub fn narrow_instanceof(&self, class: &str) -> Type {
978 let narrowed_ty = Atomic::TNamedObject {
979 fqcn: class.into(),
980 type_params: empty_type_params(),
981 };
982 let has_object = self.types.iter().any(|t| {
984 matches!(
985 t,
986 Atomic::TObject
987 | Atomic::TObjectShape { .. }
988 | Atomic::TNamedObject { .. }
989 | Atomic::TMixed
990 | Atomic::TNull )
992 });
993 if has_object || self.is_empty() {
994 Type::single(narrowed_ty)
995 } else {
996 Type::single(narrowed_ty)
999 }
1000 }
1001
1002 pub fn narrow_to_string(&self) -> Type {
1006 self.filter_replacing(
1007 |t| t.is_string() || t.is_deferred(),
1008 |t| matches!(t, Atomic::TMixed | Atomic::TScalar),
1009 Atomic::TString,
1010 )
1011 .with_callable_form(self, Atomic::TCallableString)
1012 }
1013
1014 pub fn narrow_to_int(&self) -> Type {
1016 self.filter_replacing(
1017 |t| t.is_int() || t.is_deferred(),
1018 |t| matches!(t, Atomic::TMixed | Atomic::TScalar | Atomic::TNumeric),
1019 Atomic::TInt,
1020 )
1021 }
1022
1023 pub fn narrow_to_float(&self) -> Type {
1025 self.filter_replacing(
1026 |t| {
1027 matches!(
1028 t,
1029 Atomic::TFloat | Atomic::TIntegralFloat | Atomic::TLiteralFloat(..)
1030 ) || matches!(t, Atomic::TTemplateParam { .. } | Atomic::TValueOf { .. })
1031 },
1032 |t| matches!(t, Atomic::TMixed | Atomic::TScalar | Atomic::TNumeric),
1033 Atomic::TFloat,
1034 )
1035 }
1036
1037 pub fn narrow_to_bool(&self) -> Type {
1039 self.filter_replacing(
1040 |t| {
1041 matches!(
1042 t,
1043 Atomic::TBool
1044 | Atomic::TTrue
1045 | Atomic::TFalse
1046 | Atomic::TTemplateParam { .. }
1047 | Atomic::TValueOf { .. }
1048 )
1049 },
1050 |t| matches!(t, Atomic::TMixed | Atomic::TScalar),
1051 Atomic::TBool,
1052 )
1053 }
1054
1055 pub fn narrow_to_null(&self) -> Type {
1057 self.filter_replacing(
1058 |t| matches!(t, Atomic::TNull | Atomic::TTemplateParam { .. }),
1059 |t| matches!(t, Atomic::TMixed),
1060 Atomic::TNull,
1061 )
1062 }
1063
1064 pub fn narrow_to_array(&self) -> Type {
1066 self.filter_replacing(
1067 |t| t.is_array() || matches!(t, Atomic::TTemplateParam { .. }),
1068 |t| matches!(t, Atomic::TMixed),
1069 Atomic::TArray {
1070 key: Box::new(Type::mixed()),
1071 value: Box::new(Type::mixed()),
1072 },
1073 )
1074 .with_callable_form(self, callable_array())
1075 }
1076
1077 pub fn widen_non_empty(&self) -> Type {
1079 let mut out = Type::empty();
1080 out.from_docblock = self.from_docblock;
1081 out.possibly_undefined = self.possibly_undefined;
1082 for a in &self.types {
1083 out.add_type(match a {
1084 Atomic::TNonEmptyList { value } => Atomic::TList {
1085 value: value.clone(),
1086 },
1087 Atomic::TNonEmptyArray { key, value } => Atomic::TArray {
1088 key: key.clone(),
1089 value: value.clone(),
1090 },
1091 other => other.clone(),
1092 });
1093 }
1094 out
1095 }
1096
1097 pub fn widen_nested_non_empty(&self) -> Type {
1100 fn relax_all(ty: &Type) -> Type {
1101 map_atoms(ty, |a| match a {
1102 Atomic::TNonEmptyList { value } => Atomic::TList {
1103 value: Box::new(relax_all(value)),
1104 },
1105 Atomic::TNonEmptyArray { key, value } => Atomic::TArray {
1106 key: key.clone(),
1107 value: Box::new(relax_all(value)),
1108 },
1109 other => map_values(other, relax_all),
1110 })
1111 }
1112 fn map_values(atomic: &Atomic, f: fn(&Type) -> Type) -> Atomic {
1113 match atomic {
1114 Atomic::TArray { key, value } => Atomic::TArray {
1115 key: key.clone(),
1116 value: Box::new(f(value)),
1117 },
1118 Atomic::TList { value } => Atomic::TList {
1119 value: Box::new(f(value)),
1120 },
1121 Atomic::TNonEmptyArray { key, value } => Atomic::TNonEmptyArray {
1122 key: key.clone(),
1123 value: Box::new(f(value)),
1124 },
1125 Atomic::TNonEmptyList { value } => Atomic::TNonEmptyList {
1126 value: Box::new(f(value)),
1127 },
1128 Atomic::TKeyedArray {
1129 properties,
1130 is_open,
1131 is_list,
1132 } => Atomic::TKeyedArray {
1133 properties: Arc::new(properties.map_types(f)),
1134 is_open: *is_open,
1135 is_list: *is_list,
1136 },
1137 other => other.clone(),
1138 }
1139 }
1140 fn map_atoms(ty: &Type, f: impl Fn(&Atomic) -> Atomic) -> Type {
1141 let mut result = Type::empty();
1142 result.possibly_undefined = ty.possibly_undefined;
1143 result.from_docblock = ty.from_docblock;
1144 for atomic in &ty.types {
1145 result.add_type(f(atomic));
1146 }
1147 result
1148 }
1149 map_atoms(self, |a| map_values(a, relax_all))
1150 }
1151
1152 pub fn narrow_to_non_empty_collection(&self) -> Type {
1155 let mut out = Type::empty();
1156 out.from_docblock = self.from_docblock;
1157 for t in &self.types {
1158 match t {
1159 Atomic::TArray { key, value } => out.add_type(Atomic::TNonEmptyArray {
1160 key: key.clone(),
1161 value: value.clone(),
1162 }),
1163 Atomic::TList { value } => out.add_type(Atomic::TNonEmptyList {
1164 value: value.clone(),
1165 }),
1166 Atomic::TKeyedArray {
1167 properties,
1168 is_open: false,
1169 ..
1170 } if properties.is_empty() => {}
1171 _ => out.add_type(t.clone()),
1172 }
1173 }
1174 out
1175 }
1176
1177 pub fn narrow_to_empty_collection(&self) -> Type {
1187 let mut out = Type::empty();
1188 out.from_docblock = self.from_docblock;
1189 for t in &self.types {
1190 match t {
1191 Atomic::TNonEmptyArray { .. } | Atomic::TNonEmptyList { .. } => {}
1192 Atomic::TArray { .. } | Atomic::TList { .. } => {
1193 out.add_type(Atomic::TKeyedArray {
1194 properties: Arc::default(),
1195 is_open: false,
1196 is_list: true,
1197 });
1198 }
1199 _ => out.add_type(t.clone()),
1200 }
1201 }
1202 out
1203 }
1204
1205 pub fn narrow_to_list(&self) -> Type {
1217 let mut out = Type::empty();
1218 out.from_docblock = self.from_docblock;
1219 for t in &self.types {
1220 match t {
1221 Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => out.add_type(t.clone()),
1222 Atomic::TArray { key, value } if !key.narrow_to_int().is_empty() => {
1228 out.add_type(Atomic::TList {
1229 value: value.clone(),
1230 });
1231 }
1232 Atomic::TNonEmptyArray { key, value } if !key.narrow_to_int().is_empty() => {
1233 out.add_type(Atomic::TNonEmptyList {
1234 value: value.clone(),
1235 });
1236 }
1237 Atomic::TKeyedArray { is_list: true, .. } => out.add_type(t.clone()),
1238 Atomic::TMixed => out.add_type(Atomic::TList {
1239 value: Box::new(Type::mixed()),
1240 }),
1241 _ => {}
1242 }
1243 }
1244 if out.is_empty() {
1245 self.filter(|t| matches!(t, Atomic::TList { .. } | Atomic::TNonEmptyList { .. }))
1246 } else {
1247 out
1248 }
1249 }
1250
1251 pub fn narrow_to_object(&self) -> Type {
1256 let mut out = Type::empty();
1257 for t in &self.types {
1258 if matches!(t, Atomic::TMixed) {
1259 out.add_type(Atomic::TObject);
1260 } else if t.is_object() || matches!(t, Atomic::TTemplateParam { .. }) {
1261 out.add_type(t.clone());
1262 }
1263 }
1264 if out.types.is_empty() {
1265 self.filter(|t| t.is_object())
1266 .with_callable_form(self, Atomic::TObject)
1267 } else {
1268 out.with_callable_form(self, Atomic::TObject)
1269 }
1270 }
1271
1272 fn with_callable_form(mut self, source: &Type, form: Atomic) -> Type {
1275 if source
1276 .types
1277 .iter()
1278 .any(|t| matches!(t, Atomic::TCallable { .. }))
1279 {
1280 self.add_type(form);
1281 }
1282 self
1283 }
1284
1285 pub fn narrow_to_not_callable(&self) -> Type {
1288 let callable_array = callable_array();
1289 self.filter(|t| {
1290 !t.is_callable()
1291 && *t != callable_array
1292 && !matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.eq_ignore_ascii_case("Closure"))
1293 })
1294 }
1295
1296 pub fn narrow_to_callable(&self) -> Type {
1303 let narrowed = self.filter(|t| {
1304 t.is_callable()
1305 || t.is_string()
1306 || t.is_array()
1307 || t.is_object()
1308 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1309 });
1310 let mut result = Type::empty();
1317 result.possibly_undefined = narrowed.possibly_undefined;
1318 result.from_docblock = narrowed.from_docblock;
1319 for atomic in narrowed.types {
1320 if matches!(atomic, Atomic::TObject | Atomic::TObjectShape { .. }) {
1321 result.add_type(Atomic::TCallable {
1322 params: None,
1323 return_type: None,
1324 is_pure: false,
1325 });
1326 } else {
1327 result.add_type(atomic);
1328 }
1329 }
1330 result
1331 }
1332
1333 pub fn narrow_to_scalar(&self) -> Type {
1335 self.filter_replacing(
1336 |t| {
1337 t.is_string()
1338 || t.is_int()
1339 || matches!(
1340 t,
1341 Atomic::TFloat
1342 | Atomic::TIntegralFloat
1343 | Atomic::TLiteralFloat(..)
1344 | Atomic::TBool
1345 | Atomic::TTrue
1346 | Atomic::TFalse
1347 | Atomic::TScalar
1348 | Atomic::TNumeric
1349 | Atomic::TNumericString
1350 | Atomic::TTemplateParam { .. }
1351 )
1352 },
1353 |t| matches!(t, Atomic::TMixed),
1354 Atomic::TScalar,
1355 )
1356 }
1357
1358 pub fn narrow_to_iterable(&self) -> Type {
1361 self.filter(|t| {
1362 t.is_array()
1363 || t.is_object()
1364 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1365 })
1366 }
1367
1368 pub fn narrow_to_countable(&self) -> Type {
1371 self.filter(|t| {
1372 t.is_array()
1373 || t.is_object()
1374 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1375 })
1376 }
1377
1378 pub fn narrow_to_resource(&self) -> Type {
1380 let mut out = self.filter(|t| match t {
1381 Atomic::TResource | Atomic::TOpenResource | Atomic::TMixed => true,
1382 Atomic::TTemplateParam { as_type, .. } => as_type.is_mixed(),
1383 _ => false,
1384 });
1385 for t in out.types.iter_mut() {
1386 if matches!(t, Atomic::TMixed) {
1387 *t = Atomic::TResource;
1388 }
1389 }
1390 out
1391 }
1392
1393 pub fn narrow_to_class_string(&self) -> Type {
1398 let mut out = Type::empty();
1399 out.from_docblock = self.from_docblock;
1400 for t in &self.types {
1401 match t {
1402 Atomic::TClassString(_) => out.add_type(t.clone()),
1403 _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
1404 out.add_type(Atomic::TClassString(None));
1405 }
1406 _ => {}
1407 }
1408 }
1409 out
1410 }
1411
1412 pub fn narrow_to_interface_string(&self) -> Type {
1417 let mut out = Type::empty();
1418 out.from_docblock = self.from_docblock;
1419 for t in &self.types {
1420 match t {
1421 Atomic::TInterfaceString(_) => out.add_type(t.clone()),
1422 Atomic::TClassString(name) => {
1426 out.add_type(Atomic::TInterfaceString(*name));
1427 }
1428 _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
1429 out.add_type(Atomic::TInterfaceString(None));
1430 }
1431 _ => {}
1432 }
1433 }
1434 out
1435 }
1436
1437 pub fn merge(a: &Type, b: &Type) -> Type {
1442 if b.types.is_empty() {
1444 let mut result = a.clone();
1445 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1446 return result;
1447 }
1448 if a.types.is_empty() {
1450 let mut result = b.clone();
1451 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1452 return result;
1453 }
1454 if a.types.len() == 1 && matches!(a.types[0], Atomic::TMixed) {
1456 let mut result = a.clone();
1457 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1458 return result;
1459 }
1460 if b.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1462 return Type {
1463 types: smallvec::smallvec![Atomic::TMixed],
1464 possibly_undefined: a.possibly_undefined || b.possibly_undefined,
1465 from_docblock: a.from_docblock || b.from_docblock,
1466 falsy_stripped: false,
1467 possibly_absent_offset: false,
1468 };
1469 }
1470 let mut result = a.clone();
1471 result.merge_with(b);
1472 result
1473 }
1474
1475 pub fn merge_with(&mut self, other: &Type) {
1477 if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1478 self.possibly_undefined |= other.possibly_undefined;
1479 return;
1480 }
1481 if other.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1482 self.types.clear();
1483 self.types.push(Atomic::TMixed);
1484 self.possibly_undefined |= other.possibly_undefined;
1485 return;
1486 }
1487 for atomic in &other.types {
1488 if matches!(atomic, Atomic::TConditional { .. }) {
1490 self.add_type(atomic.clone());
1491 } else if !self.types.contains(atomic)
1492 && !self.types.iter().any(|t| matches!(t, Atomic::TMixed))
1493 {
1494 self.add_absent_type(atomic.clone());
1495 }
1496 }
1497 self.possibly_undefined |= other.possibly_undefined;
1498 }
1499
1500 pub fn intersect_with(&self, other: &Type) -> Type {
1504 if self.is_mixed() {
1505 return other.clone();
1506 }
1507 if other.is_mixed() {
1508 return self.clone();
1509 }
1510 let mut result = Type::empty();
1518 for a in &self.types {
1519 for b in &other.types {
1520 if a == b {
1521 result.add_type(a.clone());
1522 } else if atomic_subtype(b, a) {
1523 result.add_type(b.clone());
1524 } else if atomic_subtype(a, b) {
1525 result.add_type(a.clone());
1526 }
1527 }
1528 }
1529 if result.is_empty() {
1530 Type::never()
1531 } else {
1532 result
1533 }
1534 }
1535
1536 pub fn substitute_templates(&self, bindings: &FxHashMap<Name, Type>) -> Type {
1540 if bindings.is_empty() {
1541 return self.clone();
1542 }
1543 if !self.types.iter().any(atomic_may_contain_templates) {
1546 return self.clone();
1547 }
1548 let mut result = Type::empty();
1549 result.possibly_undefined = self.possibly_undefined;
1550 result.from_docblock = self.from_docblock;
1551 for atomic in &self.types {
1552 match atomic {
1553 Atomic::TTemplateParam { name, .. } => {
1554 if let Some(resolved) = bindings.get(name) {
1555 for t in &resolved.types {
1556 result.add_type(t.clone());
1557 }
1558 } else {
1559 result.add_type(atomic.clone());
1560 }
1561 }
1562 Atomic::TArray { key, value } => {
1563 result.add_type(Atomic::TArray {
1564 key: Box::new(key.substitute_templates(bindings)),
1565 value: Box::new(value.substitute_templates(bindings)),
1566 });
1567 }
1568 Atomic::TList { value } => {
1569 result.add_type(Atomic::TList {
1570 value: Box::new(value.substitute_templates(bindings)),
1571 });
1572 }
1573 Atomic::TNonEmptyArray { key, value } => {
1574 result.add_type(Atomic::TNonEmptyArray {
1575 key: Box::new(key.substitute_templates(bindings)),
1576 value: Box::new(value.substitute_templates(bindings)),
1577 });
1578 }
1579 Atomic::TNonEmptyList { value } => {
1580 result.add_type(Atomic::TNonEmptyList {
1581 value: Box::new(value.substitute_templates(bindings)),
1582 });
1583 }
1584 Atomic::TKeyedArray {
1585 properties,
1586 is_open,
1587 is_list,
1588 } => {
1589 let new_props = properties.map_types(|ty| ty.substitute_templates(bindings));
1590 result.add_type(Atomic::TKeyedArray {
1591 properties: Arc::new(new_props),
1592 is_open: *is_open,
1593 is_list: *is_list,
1594 });
1595 }
1596 Atomic::TCallable {
1597 params,
1598 return_type,
1599 is_pure,
1600 } => {
1601 result.add_type(Atomic::TCallable {
1602 params: params.as_ref().map(|ps| {
1603 Box::new(
1604 ps.iter()
1605 .map(|p| substitute_in_fn_param(p, bindings))
1606 .collect(),
1607 )
1608 }),
1609 return_type: return_type
1610 .as_ref()
1611 .map(|r| Box::new(r.substitute_templates(bindings))),
1612 is_pure: *is_pure,
1613 });
1614 }
1615 Atomic::TClosure { data } => {
1616 result.add_type(Atomic::TClosure {
1617 data: Box::new(crate::atomic::ClosureData {
1618 params: data
1619 .params
1620 .iter()
1621 .map(|p| substitute_in_fn_param(p, bindings))
1622 .collect(),
1623 return_type: data.return_type.substitute_templates(bindings),
1624 this_type: data
1625 .this_type
1626 .as_ref()
1627 .map(|t| t.substitute_templates(bindings)),
1628 is_pure: data.is_pure,
1629 is_static: data.is_static,
1630 rejects_surplus_args: data.rejects_surplus_args,
1631 is_impure: data.is_impure,
1632 }),
1633 });
1634 }
1635 Atomic::TConditional { data } => {
1636 let param_name = &data.param_name;
1637 let new_subject = data.subject.substitute_templates(bindings);
1638 let new_if_true = data.if_true.substitute_templates(bindings);
1639 let new_if_false = data.if_false.substitute_templates(bindings);
1640
1641 let resolved = if let Some(name) = param_name {
1645 if let Some(bound) = bindings.get(name) {
1646 resolve_conditional_branch(
1647 &new_subject,
1648 bound,
1649 &new_if_true,
1650 &new_if_false,
1651 )
1652 } else {
1653 None
1654 }
1655 } else {
1656 None
1657 };
1658
1659 if let Some(branch) = resolved {
1660 for t in branch.types {
1661 result.add_type(t);
1662 }
1663 } else {
1664 result.add_type(Atomic::TConditional {
1665 data: Box::new(crate::atomic::ConditionalData {
1666 param_name: *param_name,
1667 subject: new_subject,
1668 if_true: new_if_true,
1669 if_false: new_if_false,
1670 }),
1671 });
1672 }
1673 }
1674 Atomic::TKeyOf { target } => {
1675 let new_target = target.substitute_templates(bindings);
1676 if let Some(resolved) = eval_key_of_type(&new_target) {
1677 result.merge_with(&resolved);
1678 } else {
1679 result.add_type(Atomic::TKeyOf {
1680 target: Box::new(new_target),
1681 });
1682 }
1683 }
1684 Atomic::TValueOf { target } => {
1685 let new_target = target.substitute_templates(bindings);
1686 if let Some(resolved) = eval_value_of_type(&new_target) {
1687 result.merge_with(&resolved);
1688 } else {
1689 result.add_type(Atomic::TValueOf {
1690 target: Box::new(new_target),
1691 });
1692 }
1693 }
1694 Atomic::TIntersection { parts } => {
1695 result.add_type(Atomic::TIntersection {
1696 parts: vec_to_type_params(
1697 parts
1698 .iter()
1699 .map(|p| p.substitute_templates(bindings))
1700 .collect(),
1701 ),
1702 });
1703 }
1704 Atomic::TNamedObject { fqcn, type_params } => {
1705 if type_params.is_empty() && !fqcn.contains('\\') {
1707 if let Some(resolved) = bindings.get(fqcn) {
1708 for t in &resolved.types {
1709 result.add_type(t.clone());
1710 }
1711 continue;
1712 }
1713 }
1714 let new_params: Vec<Type> = type_params
1715 .iter()
1716 .map(|p| p.substitute_templates(bindings))
1717 .collect();
1718 result.add_type(Atomic::TNamedObject {
1719 fqcn: *fqcn,
1720 type_params: vec_to_type_params(new_params),
1721 });
1722 }
1723 Atomic::TClassString(Some(param_name)) => {
1725 if let Some(resolved) = bindings.get(param_name) {
1726 for r_atomic in &resolved.types {
1727 let cls_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1728 Some(*fqcn)
1729 } else {
1730 None
1731 };
1732 result.add_type(Atomic::TClassString(cls_name));
1733 }
1734 } else {
1735 result.add_type(atomic.clone());
1736 }
1737 }
1738 Atomic::TInterfaceString(Some(param_name)) => {
1740 if let Some(resolved) = bindings.get(param_name) {
1741 for r_atomic in &resolved.types {
1742 let iface_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1743 Some(*fqcn)
1744 } else {
1745 None
1746 };
1747 result.add_type(Atomic::TInterfaceString(iface_name));
1748 }
1749 } else {
1750 result.add_type(atomic.clone());
1751 }
1752 }
1753 _ => {
1754 result.add_type(atomic.clone());
1755 }
1756 }
1757 }
1758 result
1759 }
1760
1761 pub fn resolve_conditional_returns<F>(self, lookup: F) -> Type
1767 where
1768 F: Fn(&str) -> Option<Type>,
1769 {
1770 self.resolve_conditional_inner(&lookup)
1771 }
1772
1773 fn resolve_conditional_inner<F>(self, lookup: &F) -> Type
1774 where
1775 F: Fn(&str) -> Option<Type>,
1776 {
1777 let mut result = Type::empty();
1778 for atomic in self.types {
1779 match atomic {
1780 Atomic::TConditional { ref data } => {
1781 let (param_name, subject, if_true, if_false) = (
1782 &data.param_name,
1783 &data.subject,
1784 &data.if_true,
1785 &data.if_false,
1786 );
1787 let resolved =
1788 param_name
1789 .and_then(|name| lookup(name.as_ref()))
1790 .and_then(|arg_ty| {
1791 resolve_conditional_branch(subject, &arg_ty, if_true, if_false)
1792 });
1793
1794 if let Some(branch) = resolved {
1795 for t in branch.resolve_conditional_inner(lookup).types {
1797 result.add_type(t);
1798 }
1799 } else {
1800 for t in if_true.clone().resolve_conditional_inner(lookup).types {
1803 result.add_type(t);
1804 }
1805 for t in if_false.clone().resolve_conditional_inner(lookup).types {
1806 result.add_type(t);
1807 }
1808 }
1809 }
1810 other => result.add_type(other),
1811 }
1812 }
1813 result
1814 }
1815
1816 pub fn is_subtype_structural(&self, other: &Type) -> bool {
1826 if other.is_mixed() {
1827 return true;
1828 }
1829 if self.is_never() {
1830 return true; }
1832 self.types.iter().all(|a| {
1833 let fits = |a: &Atomic| other.accepts_atomic_structural(a);
1834 fits(a)
1835 || composite_parts(a).is_some_and(|parts| parts.iter().all(fits))
1836 || small_int_range(a)
1837 .is_some_and(|mut values| values.all(|n| fits(&Atomic::TLiteralInt(n))))
1838 })
1839 }
1840
1841 pub fn expand_small_int_ranges(&self) -> Option<Type> {
1843 if !self.types.iter().any(|a| small_int_range(a).is_some()) {
1844 return None;
1845 }
1846 let mut out = Type::empty();
1847 for a in &self.types {
1848 match small_int_range(a) {
1849 Some(values) => values.for_each(|n| out.add_type(Atomic::TLiteralInt(n))),
1850 None => out.add_type(a.clone()),
1851 }
1852 }
1853 Some(out)
1854 }
1855
1856 pub fn is_subtype_by_template_bounds(&self, other: &Type) -> bool {
1859 self.is_subtype_structural(other)
1860 || self.types.iter().all(|a| match a {
1861 Atomic::TTemplateParam { as_type, .. } => {
1862 as_type.is_subtype_by_template_bounds(other)
1863 }
1864 _ => other.accepts_atomic_structural(a),
1865 })
1866 }
1867
1868 pub fn accepts_atomic_structural(&self, sub: &Atomic) -> bool {
1872 if self.is_mixed() {
1873 return true;
1874 }
1875 let int_skips_float = sub.is_int() && self.types.iter().any(Atomic::is_int);
1877 matches!(sub, Atomic::TNever)
1878 || self.types.iter().any(|b| {
1879 !(int_skips_float && matches!(b, Atomic::TFloat)) && atomic_subtype(sub, b)
1880 })
1881 }
1882
1883 fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Type {
1886 let mut result = Type::empty();
1887 result.possibly_undefined = self.possibly_undefined;
1888 result.from_docblock = self.from_docblock;
1889 for atomic in &self.types {
1890 if f(atomic) {
1891 result.types.push(atomic.clone());
1892 }
1893 }
1894 result
1895 }
1896
1897 fn filter_replacing<K: Fn(&Atomic) -> bool, P: Fn(&Atomic) -> bool>(
1902 &self,
1903 keep: K,
1904 placeholder: P,
1905 replacement: Atomic,
1906 ) -> Type {
1907 let mut result = Type::empty();
1908 result.possibly_undefined = self.possibly_undefined;
1909 result.from_docblock = self.from_docblock;
1910 for atomic in &self.types {
1911 if keep(atomic) {
1912 result.add_type(atomic.clone());
1913 } else if placeholder(atomic) {
1914 result.add_type(replacement.clone());
1915 }
1916 }
1917 result
1918 }
1919
1920 pub fn possibly_undefined(mut self) -> Self {
1922 self.possibly_undefined = true;
1923 self
1924 }
1925
1926 pub fn from_docblock(mut self) -> Self {
1928 self.from_docblock = true;
1929 self
1930 }
1931
1932 pub fn falsy_stripped(mut self) -> Self {
1935 self.falsy_stripped = true;
1936 self
1937 }
1938
1939 pub fn possibly_absent_offset(mut self) -> Self {
1943 self.possibly_absent_offset = true;
1944 self
1945 }
1946}
1947
1948#[derive(Clone, PartialEq, Eq, Debug)]
1962enum ValueClass {
1963 Int,
1964 Float,
1965 True,
1966 False,
1967 String,
1968 Array,
1969 List,
1971 Object,
1972 Resource,
1973 Null,
1974 Top,
1977 LitInt(i64),
1980 LitFloat(i64, i64),
1982 LitString(Arc<str>),
1984 ClassString,
1986}
1987
1988impl ValueClass {
1989 fn includes(&self, b: &Self) -> bool {
1994 self == b
1995 || matches!(
1996 (self, b),
1997 (Self::Top, _)
1998 | (Self::Int, Self::LitInt(_))
1999 | (Self::Float, Self::LitFloat(..))
2000 | (Self::String, Self::LitString(_))
2001 | (Self::String, Self::ClassString)
2002 | (Self::Array, Self::List)
2003 )
2004 }
2005
2006 fn overlaps(&self, b: &Self) -> bool {
2008 self.includes(b)
2009 || b.includes(self)
2010 || matches!(
2011 (self, b),
2012 (Self::ClassString, Self::LitString(_)) | (Self::LitString(_), Self::ClassString)
2013 )
2014 }
2015}
2016
2017fn value_classes(a: &Atomic) -> Vec<ValueClass> {
2023 use ValueClass::*;
2024 match a {
2025 Atomic::TInt
2028 | Atomic::TIntRange { .. }
2029 | Atomic::TPositiveInt
2030 | Atomic::TNegativeInt
2031 | Atomic::TNonNegativeInt
2032 | Atomic::TRefinedInt(_) => vec![Int],
2033 Atomic::TLiteralInt(v) => vec![LitInt(*v)],
2034 Atomic::TFloat | Atomic::TIntegralFloat => vec![Float],
2036 Atomic::TLiteralFloat(int_bits, frac_bits) => {
2037 vec![LitFloat(*int_bits, *frac_bits)]
2038 }
2039 Atomic::TBool => vec![True, False],
2041 Atomic::TTrue => vec![True],
2042 Atomic::TFalse => vec![False],
2043 Atomic::TString
2045 | Atomic::TNonEmptyString
2046 | Atomic::TNonFalsyString
2047 | Atomic::TRefinedString { .. }
2048 | Atomic::TNumericString
2049 | Atomic::TCallableString => vec![String],
2050 Atomic::TClassString(_)
2051 | Atomic::TInterfaceString(_)
2052 | Atomic::TEnumString
2053 | Atomic::TTraitString => vec![ClassString],
2054 Atomic::TLiteralString(s) => vec![LitString(s.clone())],
2055 Atomic::TArray { .. }
2057 | Atomic::TPropertiesOf { .. }
2058 | Atomic::TNonEmptyArray { .. }
2059 | Atomic::TKeyedArray { is_list: false, .. } => vec![Array],
2060 Atomic::TList { .. }
2061 | Atomic::TNonEmptyList { .. }
2062 | Atomic::TKeyedArray { is_list: true, .. } => vec![List],
2063 Atomic::TObject
2065 | Atomic::TObjectShape { .. }
2066 | Atomic::TNamedObject { .. }
2067 | Atomic::TStaticObject { .. }
2068 | Atomic::TSelf { .. }
2069 | Atomic::TParent { .. }
2070 | Atomic::TClosure { .. }
2071 | Atomic::TLiteralEnumCase { .. } => vec![Object],
2072 Atomic::TNull => vec![Null],
2075 Atomic::TResource | Atomic::TClosedResource | Atomic::TOpenResource => vec![Resource],
2076 Atomic::TVoid => vec![Top],
2077 Atomic::TMixed => vec![Top],
2079 Atomic::TScalar => vec![Int, Float, True, False, String],
2080 Atomic::TNumeric => vec![Int, Float],
2083 Atomic::TCallable { .. }
2085 | Atomic::TNever
2086 | Atomic::TTemplateParam { .. }
2087 | Atomic::TKeyOf { .. }
2088 | Atomic::TValueOf { .. }
2089 | Atomic::TConditional { .. }
2090 | Atomic::TIntersection { .. } => Vec::new(),
2091 }
2092}
2093
2094fn subject_is_decidable(subject: &Atomic) -> bool {
2102 matches!(
2103 subject,
2104 Atomic::TNull
2105 | Atomic::TTrue
2106 | Atomic::TFalse
2107 | Atomic::TBool
2108 | Atomic::TString
2109 | Atomic::TClassString(None)
2110 | Atomic::TInt
2111 | Atomic::TFloat
2112 | Atomic::TLiteralString(_)
2113 | Atomic::TLiteralInt(_)
2114 | Atomic::TLiteralFloat(..)
2115 | Atomic::TArray { .. }
2116 | Atomic::TList { .. }
2117 | Atomic::TObject
2118 | Atomic::TObjectShape { .. }
2119 | Atomic::TResource
2120 | Atomic::TOpenResource
2121 | Atomic::TMixed
2122 | Atomic::TScalar
2123 )
2124}
2125
2126fn resolve_conditional_branch(
2148 subject: &Type,
2149 arg_ty: &Type,
2150 if_true: &Type,
2151 if_false: &Type,
2152) -> Option<Type> {
2153 if arg_ty.types.is_empty() {
2154 return None;
2155 }
2156 if let [Atomic::TVoid] = subject.types.as_slice() {
2158 return match arg_ty.types.as_slice() {
2159 [Atomic::TVoid] => Some(if_true.clone()),
2160 types
2161 if types.iter().all(|a| {
2162 !matches!(a, Atomic::TVoid | Atomic::TMixed | Atomic::TNull)
2163 && !value_classes(a).is_empty()
2164 }) =>
2165 {
2166 Some(if_false.clone())
2167 }
2168 _ => None,
2169 };
2170 }
2171 if subject.types.is_empty() || !subject.types.iter().all(subject_is_decidable) {
2172 return None;
2173 }
2174 let subject_classes: Vec<ValueClass> = subject.types.iter().flat_map(value_classes).collect();
2175 let arg_classes: Vec<ValueClass> = arg_ty.types.iter().flat_map(value_classes).collect();
2176 if arg_classes.is_empty() {
2177 return None;
2179 }
2180 let all_match = arg_classes
2181 .iter()
2182 .all(|c| subject_classes.iter().any(|s| s.includes(c)));
2183 let any_overlap = arg_classes
2184 .iter()
2185 .any(|c| subject_classes.iter().any(|s| s.overlaps(c)));
2186 if all_match {
2187 Some(if_true.clone())
2188 } else if !any_overlap {
2189 Some(if_false.clone())
2190 } else {
2191 None
2192 }
2193}
2194
2195fn atomic_may_contain_templates(atomic: &Atomic) -> bool {
2203 match atomic {
2204 Atomic::TNamedObject { fqcn, type_params } => {
2208 !type_params.is_empty() || !fqcn.contains('\\')
2209 }
2210 Atomic::TTemplateParam { .. }
2211 | Atomic::TKeyOf { .. }
2212 | Atomic::TValueOf { .. }
2213 | Atomic::TArray { .. }
2214 | Atomic::TList { .. }
2215 | Atomic::TNonEmptyArray { .. }
2216 | Atomic::TNonEmptyList { .. }
2217 | Atomic::TKeyedArray { .. }
2218 | Atomic::TCallable { .. }
2219 | Atomic::TClosure { .. }
2220 | Atomic::TConditional { .. }
2221 | Atomic::TIntersection { .. }
2222 | Atomic::TClassString(Some(_))
2223 | Atomic::TInterfaceString(Some(_)) => true,
2224 _ => false,
2225 }
2226}
2227
2228pub fn eval_key_of_type(t: &Type) -> Option<Type> {
2229 let mut result = Type::empty();
2230 for atomic in &t.types {
2231 match atomic {
2232 Atomic::TArray { key, .. } | Atomic::TNonEmptyArray { key, .. } => {
2233 for k in &key.types {
2234 result.add_type(k.clone());
2235 }
2236 }
2237 Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => {
2238 result.add_type(Atomic::TInt);
2239 }
2240 Atomic::TKeyedArray { properties, .. } => {
2241 for key in properties.keys() {
2242 match key {
2243 crate::atomic::ArrayKey::Int(n) => result.add_type(Atomic::TLiteralInt(*n)),
2244 crate::atomic::ArrayKey::String(s) => {
2245 result.add_type(Atomic::TLiteralString(s.clone()))
2246 }
2247 }
2248 }
2249 }
2250 _ => return None,
2251 }
2252 }
2253 (!result.types.is_empty()).then_some(result)
2254}
2255
2256pub fn eval_value_of_type(t: &Type) -> Option<Type> {
2257 let mut result = Type::empty();
2258 for atomic in &t.types {
2259 match atomic {
2260 Atomic::TArray { value, .. }
2261 | Atomic::TNonEmptyArray { value, .. }
2262 | Atomic::TList { value }
2263 | Atomic::TNonEmptyList { value } => {
2264 result.merge_with(value);
2265 }
2266 Atomic::TKeyedArray { properties, .. } => {
2267 for prop in properties.values() {
2268 result.merge_with(&prop.ty);
2269 }
2270 }
2271 _ => return None,
2272 }
2273 }
2274 (!result.types.is_empty()).then_some(result)
2275}
2276
2277fn substitute_in_fn_param(
2278 p: &crate::atomic::FnParam,
2279 bindings: &FxHashMap<Name, Type>,
2280) -> crate::atomic::FnParam {
2281 crate::atomic::FnParam {
2282 name: p.name,
2283 ty: p.ty.as_ref().map(|t| {
2284 let u = t.to_union();
2285 let substituted = u.substitute_templates(bindings);
2286 crate::compact::SimpleType::from_union(substituted)
2287 }),
2288 out_ty: p.out_ty.as_ref().map(|t| {
2289 let u = t.to_union();
2290 let substituted = u.substitute_templates(bindings);
2291 crate::compact::SimpleType::from_union(substituted)
2292 }),
2293 default: p.default.as_ref().map(|d| {
2294 let u = d.to_union();
2295 let substituted = u.substitute_templates(bindings);
2296 crate::compact::SimpleType::from_union(substituted)
2297 }),
2298 is_variadic: p.is_variadic,
2299 is_byref: p.is_byref,
2300 is_optional: p.is_optional,
2301 }
2302}
2303
2304const MAX_EXPANDED_INT_RANGE_SPAN: i64 = 16;
2312
2313fn small_int_range(atomic: &Atomic) -> Option<std::ops::RangeInclusive<i64>> {
2314 match atomic {
2315 Atomic::TIntRange {
2316 min: Some(lo),
2317 max: Some(hi),
2318 } if hi
2319 .checked_sub(*lo)
2320 .is_some_and(|d| (0..MAX_EXPANDED_INT_RANGE_SPAN).contains(&d)) =>
2321 {
2322 Some(*lo..=*hi)
2323 }
2324 _ => None,
2325 }
2326}
2327
2328fn composite_parts(atomic: &Atomic) -> Option<&'static [Atomic]> {
2329 match atomic {
2330 Atomic::TScalar => Some(&[Atomic::TInt, Atomic::TFloat, Atomic::TString, Atomic::TBool]),
2331 Atomic::TNumeric => Some(&[Atomic::TInt, Atomic::TFloat, Atomic::TNumericString]),
2332 _ => None,
2333 }
2334}
2335
2336fn object_shape_subtype(have: &KeyedProperties, want: &KeyedProperties) -> bool {
2337 want.iter().all(|(name, wanted)| match have.get(name) {
2338 Some(had) => (wanted.optional || !had.optional) && had.ty.is_subtype_structural(&wanted.ty),
2339 None => wanted.optional,
2340 })
2341}
2342
2343pub fn atomic_subtype(sub: &Atomic, sup: &Atomic) -> bool {
2345 if sub == sup {
2346 return true;
2347 }
2348 let string_keyed_array = || Atomic::TArray {
2350 key: Box::new(Type::string()),
2351 value: Box::new(Type::mixed()),
2352 };
2353 match (sub, sup) {
2354 (Atomic::TClosedResource, Atomic::TOpenResource) => return false,
2355 (Atomic::TResource, Atomic::TOpenResource) => return true,
2357 (Atomic::TClosedResource | Atomic::TOpenResource, _) => {
2358 return atomic_subtype(&Atomic::TResource, sup)
2359 }
2360 (Atomic::TPropertiesOf { .. }, _) => return atomic_subtype(&string_keyed_array(), sup),
2361 (_, Atomic::TPropertiesOf { .. }) => return atomic_subtype(sub, &string_keyed_array()),
2362 (Atomic::TObjectShape { properties: have }, Atomic::TObjectShape { properties: want }) => {
2363 return object_shape_subtype(have, want);
2364 }
2365 (Atomic::TObjectShape { .. }, _) => return atomic_subtype(&Atomic::TObject, sup),
2366 (_, Atomic::TObjectShape { .. }) => return atomic_subtype(sub, &Atomic::TObject),
2368 _ => {}
2369 }
2370 match (sub, sup) {
2371 (Atomic::TNever, _) => true,
2373 (_, Atomic::TMixed) => true,
2375 (Atomic::TMixed, _) => true,
2376 (_, Atomic::TTemplateParam { as_type, .. }) => {
2381 as_type.is_mixed() || as_type.types.iter().any(|b| atomic_subtype(sub, b))
2382 }
2383
2384 (Atomic::TLiteralInt(_), Atomic::TInt) => true,
2386 (Atomic::TLiteralInt(_), Atomic::TNumeric) => true,
2387 (Atomic::TLiteralInt(_), Atomic::TScalar) => true,
2388 (Atomic::TLiteralInt(_), Atomic::TRefinedInt(IntRefinement::Literal)) => true,
2389 (Atomic::TRefinedInt(_), _) => atomic_subtype(&Atomic::TInt, sup),
2390 (_, Atomic::TRefinedInt(IntRefinement::Literal)) => false,
2391 (_, Atomic::TRefinedInt(IntRefinement::MaskOf(_))) => atomic_subtype(sub, &Atomic::TInt),
2393 (Atomic::TLiteralInt(n), Atomic::TPositiveInt) => *n > 0,
2394 (Atomic::TLiteralInt(n), Atomic::TNonNegativeInt) => *n >= 0,
2395 (Atomic::TLiteralInt(n), Atomic::TNegativeInt) => *n < 0,
2396 (Atomic::TPositiveInt, Atomic::TInt) => true,
2397 (Atomic::TPositiveInt, Atomic::TNonNegativeInt) => true,
2398 (Atomic::TPositiveInt, Atomic::TNumeric) => true,
2399 (Atomic::TPositiveInt, Atomic::TScalar) => true,
2400 (Atomic::TNegativeInt, Atomic::TInt) => true,
2401 (Atomic::TNegativeInt, Atomic::TNumeric) => true,
2402 (Atomic::TNegativeInt, Atomic::TScalar) => true,
2403 (Atomic::TNonNegativeInt, Atomic::TInt) => true,
2404 (Atomic::TNonNegativeInt, Atomic::TNumeric) => true,
2405 (Atomic::TNonNegativeInt, Atomic::TScalar) => true,
2406 (Atomic::TIntRange { .. }, Atomic::TInt) => true,
2407 (Atomic::TIntRange { .. }, Atomic::TNumeric) => true,
2408 (Atomic::TIntRange { .. }, Atomic::TScalar) => true,
2409 (Atomic::TPositiveInt, Atomic::TIntRange { min, max }) => {
2411 max.is_none() && min.is_none_or(|m| m <= 1)
2412 }
2413 (Atomic::TNegativeInt, Atomic::TIntRange { min, max }) => {
2415 min.is_none() && max.is_none_or(|m| m >= -1)
2416 }
2417 (Atomic::TNonNegativeInt, Atomic::TIntRange { min, max }) => {
2419 max.is_none() && min.is_none_or(|m| m <= 0)
2420 }
2421 (Atomic::TIntRange { min: sub_min, .. }, Atomic::TPositiveInt) => {
2423 sub_min.is_some_and(|lo| lo >= 1)
2424 }
2425 (Atomic::TIntRange { min: sub_min, .. }, Atomic::TNonNegativeInt) => {
2426 sub_min.is_some_and(|lo| lo >= 0)
2427 }
2428 (Atomic::TIntRange { max: sub_max, .. }, Atomic::TNegativeInt) => {
2429 sub_max.is_some_and(|hi| hi <= -1)
2430 }
2431 (
2433 Atomic::TIntRange {
2434 min: sub_min,
2435 max: sub_max,
2436 },
2437 Atomic::TIntRange {
2438 min: sup_min,
2439 max: sup_max,
2440 },
2441 ) => {
2442 let lower_ok = match (sub_min, sup_min) {
2443 (_, None) => true,
2444 (None, Some(_)) => false,
2445 (Some(sl), Some(su)) => sl >= su,
2446 };
2447 let upper_ok = match (sub_max, sup_max) {
2448 (None, None) | (Some(_), None) => true,
2449 (None, Some(_)) => false,
2450 (Some(sl), Some(su)) => sl <= su,
2451 };
2452 lower_ok && upper_ok
2453 }
2454
2455 (Atomic::TLiteralFloat(..), Atomic::TFloat) => true,
2456 (Atomic::TLiteralFloat(..), Atomic::TNumeric) => true,
2457 (Atomic::TLiteralFloat(..), Atomic::TScalar) => true,
2458
2459 (Atomic::TLiteralString(s), Atomic::TString) => {
2460 let _ = s;
2461 true
2462 }
2463 (Atomic::TLiteralString(s), Atomic::TCallableString) => {
2464 let _ = s;
2465 true
2466 }
2467 (Atomic::TLiteralString(s), Atomic::TNonEmptyString) => !s.is_empty(),
2468 (Atomic::TLiteralString(s), Atomic::TNonFalsyString) => !s.is_empty() && s.as_ref() != "0",
2469 (Atomic::TNonEmptyString | Atomic::TNumericString, Atomic::TNonFalsyString) => false,
2471 (Atomic::TNonFalsyString, _) => atomic_subtype(&Atomic::TNonEmptyString, sup),
2473 (_, Atomic::TNonFalsyString) => atomic_subtype(sub, &Atomic::TNonEmptyString),
2474 (
2475 Atomic::TLiteralString(s),
2476 Atomic::TRefinedString {
2477 refinement,
2478 non_empty,
2479 },
2480 ) => refinement.accepts(s) && !(*non_empty && s.is_empty()),
2481 (
2483 Atomic::TClassString(Some(_)),
2484 Atomic::TRefinedString {
2485 refinement: StringRefinement::Literal,
2486 ..
2487 },
2488 ) => true,
2489 (
2490 Atomic::TRefinedString {
2491 refinement: have,
2492 non_empty: have_non_empty,
2493 },
2494 Atomic::TRefinedString {
2495 refinement: want,
2496 non_empty: want_non_empty,
2497 },
2498 ) => have == want && (*have_non_empty || !want_non_empty),
2499 (
2501 Atomic::TRefinedString {
2502 refinement: StringRefinement::DecimalInt,
2503 ..
2504 },
2505 _,
2506 ) => atomic_subtype(&Atomic::TNumericString, sup),
2507 (Atomic::TRefinedString { non_empty, .. }, _) => {
2508 let base = if *non_empty {
2509 Atomic::TNonEmptyString
2510 } else {
2511 Atomic::TString
2512 };
2513 atomic_subtype(&base, sup)
2514 }
2515 (_, Atomic::TRefinedString { .. }) => false,
2516 (Atomic::TLiteralString(s), Atomic::TNumericString | Atomic::TNumeric) => {
2517 s.parse::<f64>().is_ok()
2518 }
2519 (Atomic::TLiteralString(_), Atomic::TClassString(_)) => true,
2522 (Atomic::TLiteralString(_), Atomic::TInterfaceString(_)) => true,
2525 (Atomic::TLiteralString(_), Atomic::TScalar) => true,
2526 (Atomic::TNonEmptyString, Atomic::TString) => true,
2527 (Atomic::TCallableString, Atomic::TString) => true,
2528 (Atomic::TNumericString, Atomic::TNonEmptyString) => true,
2530 (Atomic::TNumericString, Atomic::TString) => true,
2531 (Atomic::TClassString(_), Atomic::TNonEmptyString) => true,
2535 (Atomic::TInterfaceString(_), Atomic::TNonEmptyString) => true,
2536 (Atomic::TCallableString, Atomic::TNonEmptyString) => true,
2537 (Atomic::TEnumString, Atomic::TNonEmptyString) => true,
2538 (Atomic::TTraitString, Atomic::TNonEmptyString) => true,
2539 (Atomic::TClassString(_), Atomic::TString) => true,
2540 (Atomic::TInterfaceString(_), Atomic::TString) => true,
2541 (Atomic::TInterfaceString(_), Atomic::TClassString(None)) => true,
2546 (Atomic::TClassString(Some(_)), Atomic::TClassString(None)) => true,
2547 (Atomic::TInterfaceString(Some(a)), Atomic::TClassString(Some(b))) => a == b,
2548 (Atomic::TEnumString, Atomic::TString) => true,
2549 (Atomic::TTraitString, Atomic::TString) => true,
2550
2551 (Atomic::TTrue, Atomic::TBool) => true,
2552 (Atomic::TFalse, Atomic::TBool) => true,
2553
2554 (Atomic::TInt, Atomic::TNumeric) => true,
2555 (Atomic::TFloat, Atomic::TNumeric) => true,
2556 (Atomic::TIntegralFloat, Atomic::TNumeric) => true,
2557 (Atomic::TNumericString, Atomic::TNumeric) => true,
2558
2559 (Atomic::TInt, Atomic::TScalar) => true,
2560 (Atomic::TFloat, Atomic::TScalar) => true,
2561 (Atomic::TIntegralFloat, Atomic::TScalar) => true,
2562 (Atomic::TString, Atomic::TScalar) => true,
2563 (Atomic::TBool, Atomic::TScalar) => true,
2564 (Atomic::TNumeric, Atomic::TScalar) => true,
2565 (Atomic::TTrue, Atomic::TScalar) => true,
2566 (Atomic::TFalse, Atomic::TScalar) => true,
2567 (Atomic::TNonEmptyString, Atomic::TScalar) => true,
2571 (Atomic::TNumericString, Atomic::TScalar) => true,
2572 (Atomic::TCallableString, Atomic::TScalar) => true,
2573 (Atomic::TClassString(_), Atomic::TScalar) => true,
2574 (Atomic::TInterfaceString(_), Atomic::TScalar) => true,
2575 (Atomic::TEnumString, Atomic::TScalar) => true,
2576 (Atomic::TTraitString, Atomic::TScalar) => true,
2577
2578 (Atomic::TNamedObject { .. }, Atomic::TObject) => true,
2580 (Atomic::TStaticObject { .. }, Atomic::TObject) => true,
2581 (Atomic::TSelf { .. }, Atomic::TObject) => true,
2582 (Atomic::TLiteralEnumCase { .. }, Atomic::TObject) => true,
2584 (Atomic::TSelf { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
2586 (Atomic::TStaticObject { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
2587 (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TSelf { fqcn: b }) => a == b,
2589 (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TStaticObject { fqcn: b }) => a == b,
2590 (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TNamedObject { fqcn, .. }) => {
2593 enum_fqcn == fqcn
2594 }
2595 (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TSelf { fqcn })
2596 | (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TStaticObject { fqcn }) => {
2597 enum_fqcn == fqcn
2598 }
2599 (
2603 Atomic::TNamedObject {
2604 fqcn: sub_fqcn,
2605 type_params: sub_params,
2606 },
2607 Atomic::TNamedObject {
2608 fqcn: sup_fqcn,
2609 type_params: sup_params,
2610 },
2611 ) => {
2612 sub_fqcn == sup_fqcn
2613 && (sup_params.is_empty() || type_params_compatible(sub_params, sup_params))
2614 }
2615
2616 (Atomic::TIntegralFloat, Atomic::TFloat) => true,
2618
2619 (Atomic::TLiteralInt(_), Atomic::TFloat) => true,
2621 (Atomic::TPositiveInt, Atomic::TFloat) => true,
2622 (Atomic::TNegativeInt, Atomic::TFloat) => true,
2623 (Atomic::TNonNegativeInt, Atomic::TFloat) => true,
2624 (Atomic::TInt, Atomic::TFloat) => true,
2625 (Atomic::TIntRange { .. }, Atomic::TFloat) => true,
2626
2627 (Atomic::TLiteralInt(n), Atomic::TIntRange { min, max }) => {
2629 min.is_none_or(|lo| *n >= lo) && max.is_none_or(|hi| *n <= hi)
2630 }
2631
2632 (Atomic::TString, Atomic::TCallable { .. }) => true,
2634 (Atomic::TCallableString, Atomic::TCallable { .. }) => true,
2635 (Atomic::TNonEmptyString, Atomic::TCallable { .. }) => true,
2636 (Atomic::TLiteralString(_), Atomic::TCallable { .. }) => true,
2637 (Atomic::TArray { .. }, Atomic::TCallable { .. }) => true,
2638 (Atomic::TNonEmptyArray { .. }, Atomic::TCallable { .. }) => true,
2639 (Atomic::TKeyedArray { .. }, Atomic::TCallable { .. }) => true,
2640
2641 (Atomic::TClosure { .. }, Atomic::TCallable { .. }) => true,
2643 (Atomic::TCallable { .. }, Atomic::TClosure { .. }) => true,
2645 (Atomic::TClosure { data: sub }, Atomic::TClosure { data: sup }) => {
2655 fn has_nominal_type(t: &Type) -> bool {
2656 t.types.iter().any(|a| {
2657 matches!(
2658 a,
2659 Atomic::TNamedObject { .. }
2660 | Atomic::TSelf { .. }
2661 | Atomic::TStaticObject { .. }
2662 | Atomic::TTemplateParam { .. }
2663 | Atomic::TClosure { .. }
2664 | Atomic::TCallable { .. }
2665 )
2666 })
2667 }
2668 let sub_required = sub
2669 .params
2670 .iter()
2671 .filter(|p| !p.is_optional && !p.is_variadic)
2672 .count();
2673 if sub_required > sup.params.len() {
2674 false
2675 } else {
2676 let params_ok = sup.params.iter().enumerate().all(|(i, sup_param)| {
2677 let Some(sub_param) = sub.params.get(i) else {
2678 return true;
2679 };
2680 if sub_param.is_optional || sub_param.is_variadic {
2681 return true;
2682 }
2683 let (Some(sub_ty), Some(sup_ty)) =
2684 (sub_param.ty.as_ref(), sup_param.ty.as_ref())
2685 else {
2686 return true;
2687 };
2688 let (sub_u, sup_u) = (sub_ty.to_union(), sup_ty.to_union());
2689 if has_nominal_type(&sub_u) || has_nominal_type(&sup_u) {
2690 return true;
2691 }
2692 sup_u.is_subtype_structural(&sub_u)
2695 });
2696 params_ok
2697 && (sub.return_type.is_mixed()
2698 || sup.return_type.is_mixed()
2699 || sup.return_type.is_void()
2703 || has_nominal_type(&sub.return_type)
2704 || has_nominal_type(&sup.return_type)
2705 || sub.return_type.is_subtype_structural(&sup.return_type))
2706 }
2707 }
2708 (Atomic::TCallable { .. }, Atomic::TCallable { .. }) => true,
2710 (Atomic::TClosure { .. }, Atomic::TNamedObject { fqcn, .. }) => {
2712 fqcn.as_ref().eq_ignore_ascii_case("closure")
2713 }
2714 (Atomic::TClosure { .. }, Atomic::TObject) => true,
2715 (Atomic::TNamedObject { fqcn, .. }, Atomic::TClosure { .. }) => {
2717 fqcn.as_ref().eq_ignore_ascii_case("closure")
2718 }
2719 (Atomic::TNamedObject { fqcn, .. }, Atomic::TCallable { .. }) => {
2721 fqcn.as_ref().eq_ignore_ascii_case("closure")
2722 }
2723
2724 (
2732 Atomic::TIntersection { parts: sub_parts },
2733 Atomic::TIntersection { parts: sup_parts },
2734 ) => sup_parts.iter().all(|sup_part| {
2735 sub_parts
2736 .iter()
2737 .any(|sub_part| sub_part.is_subtype_structural(sup_part))
2738 }),
2739 (Atomic::TIntersection { parts }, Atomic::TObject) => parts
2740 .iter()
2741 .any(|part| part.is_subtype_structural(&Type::single(Atomic::TObject))),
2742
2743 (Atomic::TList { value }, Atomic::TArray { key, value: av }) => {
2745 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2746 }
2747 (Atomic::TNonEmptyList { value }, Atomic::TArray { key, value: av }) => {
2748 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2749 }
2750 (Atomic::TNonEmptyList { value }, Atomic::TNonEmptyArray { key, value: av }) => {
2751 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2752 }
2753 (Atomic::TNonEmptyList { value }, Atomic::TList { value: lv }) => {
2754 value.is_subtype_structural(lv)
2755 }
2756 (Atomic::TNonEmptyList { value: v1 }, Atomic::TNonEmptyList { value: v2 }) => {
2757 v1.is_subtype_structural(v2)
2758 }
2759 (Atomic::TArray { key, value: av }, Atomic::TList { value: lv }) => {
2761 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2762 && av.is_subtype_structural(lv)
2763 }
2764 (Atomic::TArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
2765 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2766 && av.is_subtype_structural(lv)
2767 }
2768 (Atomic::TNonEmptyArray { key, value: av }, Atomic::TList { value: lv }) => {
2769 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2770 && av.is_subtype_structural(lv)
2771 }
2772 (Atomic::TNonEmptyArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
2773 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2774 && av.is_subtype_structural(lv)
2775 }
2776 (Atomic::TList { value: v1 }, Atomic::TList { value: v2 }) => v1.is_subtype_structural(v2),
2778 (Atomic::TNonEmptyArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
2779 k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
2780 }
2781
2782 (Atomic::TArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
2784 k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
2785 }
2786
2787 (Atomic::TKeyedArray { properties, .. }, Atomic::TArray { key, value }) => {
2796 properties.iter().all(|(prop_key, prop)| {
2797 let key_atomic = match prop_key {
2798 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2799 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2800 };
2801 if !Type::single(key_atomic).is_subtype_structural(key) {
2802 return false; }
2804 let has_named_obj = prop.ty.types.iter().any(|a| {
2806 matches!(
2807 a,
2808 Atomic::TNamedObject { .. }
2809 | Atomic::TSelf { .. }
2810 | Atomic::TStaticObject { .. }
2811 | Atomic::TClosure { .. }
2812 | Atomic::TTemplateParam { .. }
2813 )
2814 });
2815 has_named_obj || prop.ty.is_subtype_structural(value)
2816 })
2817 }
2818 (
2819 Atomic::TKeyedArray {
2820 properties,
2821 is_open,
2822 ..
2823 },
2824 Atomic::TNonEmptyArray { key, value },
2825 ) => {
2826 (*is_open || properties.iter().any(|(_, p)| !p.optional))
2827 && properties.iter().all(|(prop_key, prop)| {
2828 let key_atomic = match prop_key {
2829 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2830 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2831 };
2832 if !Type::single(key_atomic).is_subtype_structural(key) {
2833 return false;
2834 }
2835 let has_named_obj = prop.ty.types.iter().any(|a| {
2836 matches!(
2837 a,
2838 Atomic::TNamedObject { .. }
2839 | Atomic::TSelf { .. }
2840 | Atomic::TStaticObject { .. }
2841 | Atomic::TClosure { .. }
2842 | Atomic::TTemplateParam { .. }
2843 )
2844 });
2845 has_named_obj || prop.ty.is_subtype_structural(value)
2846 })
2847 }
2848
2849 (
2851 Atomic::TKeyedArray {
2852 properties,
2853 is_list,
2854 ..
2855 },
2856 Atomic::TList { value: lv },
2857 ) => *is_list && properties.values().all(|p| p.ty.is_subtype_structural(lv)),
2858 (
2859 Atomic::TKeyedArray {
2860 properties,
2861 is_list,
2862 ..
2863 },
2864 Atomic::TNonEmptyList { value: lv },
2865 ) => {
2866 *is_list
2867 && !properties.is_empty()
2868 && properties.values().all(|p| p.ty.is_subtype_structural(lv))
2869 }
2870
2871 (
2876 Atomic::TKeyedArray {
2877 properties: sub_props,
2878 is_open: sub_open,
2879 is_list: sub_list,
2880 },
2881 Atomic::TKeyedArray {
2882 properties: sup_props,
2883 is_open: sup_open,
2884 is_list: sup_list,
2885 },
2886 ) => {
2887 if *sup_list
2889 && !*sub_list
2890 && sub_props
2891 .keys()
2892 .enumerate()
2893 .any(|(i, k)| *k != crate::atomic::ArrayKey::Int(i as i64))
2894 {
2895 return false;
2896 }
2897 let value_fits = |sub: &Type, sup: &Type| {
2899 if sub.is_subtype_by_template_bounds(sup) {
2900 return true;
2901 }
2902 let has_template = sup
2903 .types
2904 .iter()
2905 .any(|a| matches!(a, Atomic::TTemplateParam { .. }));
2906 let has_class = sup.types.iter().any(|a| {
2907 matches!(
2908 a,
2909 Atomic::TNamedObject { .. }
2910 | Atomic::TSelf { .. }
2911 | Atomic::TStaticObject { .. }
2912 | Atomic::TClosure { .. }
2913 )
2914 });
2915 has_template
2916 || (has_class && !sub.types.iter().all(Atomic::is_definitely_non_object))
2917 };
2918 let keys_satisfied = sup_props
2919 .iter()
2920 .all(|(key, sup_prop)| match sub_props.get(key) {
2921 Some(sub_prop) => {
2922 if !sup_prop.optional && sub_prop.optional {
2926 return false;
2927 }
2928 value_fits(&sub_prop.ty, &sup_prop.ty)
2929 }
2930 None => {
2931 sup_prop.optional
2932 || (*sub_open
2933 && sub_props
2934 .remainder
2935 .as_ref()
2936 .is_none_or(|rest| value_fits(rest, &sup_prop.ty)))
2937 }
2938 });
2939 let no_undeclared_extras = sub_props.iter().all(|(k, sub_prop)| {
2940 sup_props.contains_key(k)
2941 || match &sup_props.remainder {
2942 Some(rest) => value_fits(&sub_prop.ty, rest),
2943 None => *sup_open,
2944 }
2945 });
2946 keys_satisfied && no_undeclared_extras
2947 }
2948 (
2954 Atomic::TKeyedArray {
2955 properties,
2956 is_list: true,
2957 ..
2958 },
2959 Atomic::TIntersection { parts },
2960 ) if !properties.is_empty()
2961 && parts.iter().any(|part| {
2962 matches!(
2963 part.types.as_slice(),
2964 [Atomic::TKeyedArray { properties, is_open: true, is_list: false }]
2965 if properties.is_empty()
2966 )
2967 }) =>
2968 {
2969 false
2970 }
2971 (
2972 Atomic::TKeyedArray {
2973 properties,
2974 is_open,
2975 ..
2976 },
2977 Atomic::TIntersection { parts },
2978 ) => parts.iter().all(|part| {
2979 part.types.iter().any(|part_atomic| match part_atomic {
2980 Atomic::TKeyedArray {
2981 properties: sup_props,
2982 is_open: sup_open,
2983 ..
2984 } => {
2985 let keys_satisfied =
2986 sup_props
2987 .iter()
2988 .all(|(key, sup_prop)| match properties.get(key) {
2989 Some(sub_prop) => {
2990 if !sup_prop.optional && sub_prop.optional {
2991 return false;
2992 }
2993 let has_named_obj = sup_prop.ty.types.iter().any(|a| {
2994 matches!(
2995 a,
2996 Atomic::TNamedObject { .. }
2997 | Atomic::TSelf { .. }
2998 | Atomic::TStaticObject { .. }
2999 | Atomic::TClosure { .. }
3000 | Atomic::TTemplateParam { .. }
3001 )
3002 });
3003 has_named_obj
3004 || sub_prop.ty.is_subtype_by_template_bounds(&sup_prop.ty)
3005 || bare_array_may_fit(&sub_prop.ty, &sup_prop.ty)
3006 }
3007 None => *is_open || sup_prop.optional,
3008 });
3009 let has_array_part = parts.iter().any(|part| {
3010 part.types
3011 .iter()
3012 .any(|t| matches!(t, Atomic::TArray { .. }))
3013 });
3014 let has_keyed_array_part = parts.iter().any(|part| {
3015 part.types
3016 .iter()
3017 .any(|t| matches!(t, Atomic::TKeyedArray { .. }))
3018 });
3019 let keys_allowed_by_some_part = if has_array_part {
3020 true
3021 } else if has_keyed_array_part {
3022 properties.keys().all(|k| {
3023 parts.iter().any(|part| {
3024 part.types.iter().any(|t| {
3025 if let Atomic::TKeyedArray {
3026 properties: part_props,
3027 ..
3028 } = t
3029 {
3030 part_props.contains_key(k)
3031 } else {
3032 false
3033 }
3034 })
3035 })
3036 })
3037 } else {
3038 true
3039 };
3040 let no_undeclared_extras = *sup_open || keys_allowed_by_some_part;
3041 keys_satisfied && no_undeclared_extras
3042 }
3043 Atomic::TArray { key, value } => properties.iter().all(|(prop_key, prop)| {
3044 let key_atomic = match prop_key {
3045 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
3046 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
3047 };
3048 if !Type::single(key_atomic).is_subtype_structural(key) {
3049 return false;
3050 }
3051 let has_named_obj = prop.ty.types.iter().any(|a| {
3052 matches!(
3053 a,
3054 Atomic::TNamedObject { .. }
3055 | Atomic::TSelf { .. }
3056 | Atomic::TStaticObject { .. }
3057 | Atomic::TClosure { .. }
3058 | Atomic::TTemplateParam { .. }
3059 )
3060 });
3061 has_named_obj || prop.ty.is_subtype_structural(value)
3062 }),
3063 Atomic::TNamedObject { .. }
3064 | Atomic::TSelf { .. }
3065 | Atomic::TStaticObject { .. }
3066 | Atomic::TClosure { .. }
3067 | Atomic::TTemplateParam { .. } => true,
3068 _ => false,
3069 })
3070 }),
3071
3072 _ => false,
3073 }
3074}
3075
3076fn bare_array_may_fit(sub: &Type, sup: &Type) -> bool {
3078 fn array_like(t: &Atomic) -> bool {
3079 match t {
3080 Atomic::TArray { .. }
3081 | Atomic::TNonEmptyArray { .. }
3082 | Atomic::TList { .. }
3083 | Atomic::TNonEmptyList { .. }
3084 | Atomic::TKeyedArray { .. } => true,
3085 Atomic::TIntersection { parts } => parts.iter().all(|p| p.types.iter().all(array_like)),
3086 _ => false,
3087 }
3088 }
3089 matches!(
3090 sub.types.as_slice(),
3091 [Atomic::TArray { key, value }]
3092 if value.is_mixed()
3093 && (key.is_mixed()
3094 || matches!(key.types.as_slice(), [Atomic::TInt, Atomic::TString] | [Atomic::TString, Atomic::TInt]))
3095 ) && sup.types.iter().all(array_like)
3096}
3097
3098fn type_params_compatible(sub: &[Type], sup: &[Type]) -> bool {
3104 if sub.len() != sup.len() {
3105 return false;
3106 }
3107 sub.iter()
3108 .zip(sup.iter())
3109 .all(|(a, b)| a == b || (is_empty_array_literal(a) && is_array_like(b)))
3110}
3111
3112fn is_empty_array_literal(t: &Type) -> bool {
3115 !t.types.is_empty()
3116 && t.types.iter().all(
3117 |atom| matches!(atom, Atomic::TKeyedArray { properties, .. } if properties.is_empty()),
3118 )
3119}
3120
3121fn is_array_like(t: &Type) -> bool {
3123 !t.types.is_empty() && t.types.iter().all(|atom| atom.is_array())
3124}
3125
3126pub struct UnionBuilder {
3133 ty: Type,
3134 strings: std::collections::HashSet<std::sync::Arc<str>>,
3135 ints: std::collections::HashSet<i64>,
3136 literals_independent: bool,
3138}
3139
3140impl Default for UnionBuilder {
3141 fn default() -> Self {
3142 Self::new()
3143 }
3144}
3145
3146impl UnionBuilder {
3147 pub fn new() -> Self {
3148 Self {
3149 ty: Type::empty(),
3150 strings: Default::default(),
3151 ints: Default::default(),
3152 literals_independent: true,
3153 }
3154 }
3155
3156 pub fn is_empty(&self) -> bool {
3157 self.ty.is_empty()
3158 }
3159
3160 pub fn merge(&mut self, other: &Type) {
3161 for a in &other.types {
3162 self.add(a.clone());
3163 }
3164 self.ty.possibly_undefined |= other.possibly_undefined;
3165 }
3166
3167 pub fn add(&mut self, atomic: Atomic) {
3168 let lone_never = matches!(self.ty.types.first(), Some(Atomic::TNever));
3170 if self.literals_independent && !lone_never {
3171 match &atomic {
3172 Atomic::TLiteralString(s) => {
3173 if self.strings.insert(s.clone()) {
3174 self.ty.types.push(atomic);
3175 }
3176 return;
3177 }
3178 Atomic::TLiteralInt(n) => {
3179 if self.ints.insert(*n) {
3180 self.ty.types.push(atomic);
3181 }
3182 return;
3183 }
3184 _ => {}
3185 }
3186 }
3187 let disturbs_literals = matches!(
3188 atomic,
3189 Atomic::TString | Atomic::TMixed | Atomic::TConditional { .. }
3190 ) || int_bounds(&atomic).is_some();
3191 self.ty.add_type(atomic);
3192 if disturbs_literals || lone_never {
3193 self.resync();
3194 }
3195 }
3196
3197 fn resync(&mut self) {
3198 self.strings.clear();
3199 self.ints.clear();
3200 self.literals_independent = true;
3201 for t in &self.ty.types {
3202 match t {
3203 Atomic::TLiteralString(s) => {
3204 self.strings.insert(s.clone());
3205 }
3206 Atomic::TLiteralInt(n) => {
3207 self.ints.insert(*n);
3208 }
3209 Atomic::TMixed | Atomic::TString => self.literals_independent = false,
3210 other if int_bounds(other).is_some() => self.literals_independent = false,
3211 _ => {}
3212 }
3213 }
3214 }
3215
3216 pub fn build(self) -> Type {
3217 self.ty
3218 }
3219}
3220
3221fn callable_array() -> Atomic {
3223 let mut properties = KeyedProperties::with_capacity_and_hasher(2, Default::default());
3224 properties.insert(
3225 ArrayKey::Int(0),
3226 KeyedProperty {
3227 ty: Type::from_vec(vec![Atomic::TClassString(None), Atomic::TObject]),
3228 optional: false,
3229 },
3230 );
3231 properties.insert(
3232 ArrayKey::Int(1),
3233 KeyedProperty {
3234 ty: Type::single(Atomic::TNonEmptyString),
3235 optional: false,
3236 },
3237 );
3238 Atomic::TKeyedArray {
3239 properties: Arc::new(properties),
3240 is_open: false,
3241 is_list: true,
3242 }
3243}
3244
3245#[cfg(test)]
3246mod tests {
3247 use std::sync::Arc;
3248
3249 use super::*;
3250
3251 fn conditional(
3252 param_name: Option<Name>,
3253 subject: Type,
3254 if_true: Type,
3255 if_false: Type,
3256 ) -> Atomic {
3257 Atomic::TConditional {
3258 data: Box::new(crate::atomic::ConditionalData {
3259 param_name,
3260 subject,
3261 if_true,
3262 if_false,
3263 }),
3264 }
3265 }
3266
3267 #[test]
3268 fn single_is_single() {
3269 let u = Type::single(Atomic::TString);
3270 assert!(u.is_single());
3271 assert!(!u.is_nullable());
3272 }
3273
3274 #[test]
3275 fn nullable_has_null() {
3276 let u = Type::nullable(Atomic::TString);
3277 assert!(u.is_nullable());
3278 assert_eq!(u.types.len(), 2);
3279 }
3280
3281 #[test]
3282 fn add_type_deduplicates() {
3283 let mut u = Type::single(Atomic::TString);
3284 u.add_type(Atomic::TString);
3285 assert_eq!(u.types.len(), 1);
3286 }
3287
3288 #[test]
3289 fn array_key_is_int_string() {
3290 let k = Type::array_key();
3291 assert!(k.is_array_key());
3292 assert_eq!(k.types.len(), 2);
3293 }
3294
3295 #[test]
3296 fn is_array_key_false_for_plain_int() {
3297 assert!(!Type::int().is_array_key());
3298 }
3299
3300 #[test]
3301 fn is_array_key_false_for_mixed() {
3302 assert!(!Type::mixed().is_array_key());
3303 }
3304
3305 #[test]
3306 fn is_array_key_false_for_int_string_null() {
3307 let mut u = Type::array_key();
3308 u.add_type(Atomic::TNull);
3309 assert!(!u.is_array_key());
3310 }
3311
3312 #[test]
3313 fn add_type_literal_subsumed_by_base() {
3314 let mut u = Type::single(Atomic::TInt);
3315 u.add_type(Atomic::TLiteralInt(42));
3316 assert_eq!(u.types.len(), 1);
3317 assert!(matches!(u.types[0], Atomic::TInt));
3318 }
3319
3320 #[test]
3321 fn true_then_false_merges_to_bool() {
3322 let mut u = Type::single(Atomic::TTrue);
3323 u.add_type(Atomic::TFalse);
3324 assert_eq!(u.types.len(), 1);
3325 assert!(matches!(u.types[0], Atomic::TBool));
3326 }
3327
3328 #[test]
3329 fn false_then_true_merges_to_bool() {
3330 let mut u = Type::single(Atomic::TFalse);
3331 u.add_type(Atomic::TTrue);
3332 assert_eq!(u.types.len(), 1);
3333 assert!(matches!(u.types[0], Atomic::TBool));
3334 }
3335
3336 #[test]
3337 fn true_alone_stays_true() {
3338 let u = Type::single(Atomic::TTrue);
3339 assert_eq!(u.types.len(), 1);
3340 assert!(matches!(u.types[0], Atomic::TTrue));
3341 }
3342
3343 #[test]
3344 fn true_false_merge_preserves_other_union_members() {
3345 let mut u = Type::single(Atomic::TTrue);
3346 u.add_type(Atomic::TNull);
3347 u.add_type(Atomic::TFalse);
3348 assert_eq!(u.types.len(), 2);
3349 assert!(u.contains(|t| matches!(t, Atomic::TBool)));
3350 assert!(u.contains(|t| matches!(t, Atomic::TNull)));
3351 }
3352
3353 #[test]
3354 fn add_type_base_widens_literals() {
3355 let mut u = Type::single(Atomic::TLiteralInt(1));
3356 u.add_type(Atomic::TLiteralInt(2));
3357 u.add_type(Atomic::TInt);
3358 assert_eq!(u.types.len(), 1);
3359 assert!(matches!(u.types[0], Atomic::TInt));
3360 }
3361
3362 #[test]
3363 fn mixed_subsumes_everything() {
3364 let mut u = Type::single(Atomic::TString);
3365 u.add_type(Atomic::TMixed);
3366 assert_eq!(u.types.len(), 1);
3367 assert!(u.is_mixed());
3368 }
3369
3370 #[test]
3371 fn remove_null() {
3372 let u = Type::nullable(Atomic::TString);
3373 let narrowed = u.remove_null();
3374 assert!(!narrowed.is_nullable());
3375 assert_eq!(narrowed.types.len(), 1);
3376 }
3377
3378 #[test]
3379 fn narrow_to_truthy_removes_null_false() {
3380 let mut u = Type::empty();
3381 u.add_type(Atomic::TString);
3382 u.add_type(Atomic::TNull);
3383 u.add_type(Atomic::TFalse);
3384 let truthy = u.narrow_to_truthy();
3385 assert!(!truthy.is_nullable());
3386 assert!(!truthy.contains(|t| matches!(t, Atomic::TFalse)));
3387 }
3388
3389 #[test]
3390 fn merge_combines_types() {
3391 let a = Type::single(Atomic::TString);
3392 let b = Type::single(Atomic::TInt);
3393 let merged = Type::merge(&a, &b);
3394 assert_eq!(merged.types.len(), 2);
3395 }
3396
3397 #[test]
3398 fn intersect_keeps_narrower_side_not_self() {
3399 let int_ty = Type::single(Atomic::TInt);
3403 let mut literals = Type::empty();
3404 literals.add_type(Atomic::TLiteralInt(1));
3405 literals.add_type(Atomic::TLiteralInt(2));
3406
3407 let narrowed = int_ty.intersect_with(&literals);
3408 assert_eq!(narrowed.types.len(), 2);
3409 assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(1))));
3410 assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(2))));
3411 assert!(!narrowed.contains(|t| matches!(t, Atomic::TInt)));
3412 }
3413
3414 #[test]
3415 fn subtype_literal_int_under_int() {
3416 let sub = Type::single(Atomic::TLiteralInt(5));
3417 let sup = Type::single(Atomic::TInt);
3418 assert!(sub.is_subtype_structural(&sup));
3419 }
3420
3421 #[test]
3422 fn subtype_never_is_bottom() {
3423 let never = Type::never();
3424 let string = Type::single(Atomic::TString);
3425 assert!(never.is_subtype_structural(&string));
3426 }
3427
3428 #[test]
3429 fn subtype_everything_under_mixed() {
3430 let string = Type::single(Atomic::TString);
3431 let mixed = Type::mixed();
3432 assert!(string.is_subtype_structural(&mixed));
3433 }
3434
3435 #[test]
3436 fn subtype_enum_case_under_own_enum() {
3437 let sub = Type::single(Atomic::TLiteralEnumCase {
3438 enum_fqcn: Name::new("RoundingMode"),
3439 case_name: Name::new("Unnecessary"),
3440 });
3441 let sup = Type::single(Atomic::TNamedObject {
3442 fqcn: Name::new("RoundingMode"),
3443 type_params: empty_type_params(),
3444 });
3445 assert!(sub.is_subtype_structural(&sup));
3446 }
3447
3448 #[test]
3449 fn enum_case_not_subtype_of_unrelated_enum() {
3450 let sub = Type::single(Atomic::TLiteralEnumCase {
3451 enum_fqcn: Name::new("RoundingMode"),
3452 case_name: Name::new("Unnecessary"),
3453 });
3454 let sup = Type::single(Atomic::TNamedObject {
3455 fqcn: Name::new("Suit"),
3456 type_params: empty_type_params(),
3457 });
3458 assert!(!sub.is_subtype_structural(&sup));
3459 }
3460
3461 #[test]
3462 fn subtype_enum_case_under_own_self_and_static() {
3463 let case = |enum_fqcn: &str| {
3464 Type::single(Atomic::TLiteralEnumCase {
3465 enum_fqcn: Name::new(enum_fqcn),
3466 case_name: Name::new("A"),
3467 })
3468 };
3469 let own = Type::single(Atomic::TSelf {
3470 fqcn: Name::new("Suit"),
3471 });
3472 let own_static = Type::single(Atomic::TStaticObject {
3473 fqcn: Name::new("Suit"),
3474 });
3475 assert!(case("Suit").is_subtype_structural(&own));
3476 assert!(case("Suit").is_subtype_structural(&own_static));
3477 assert!(!case("Other").is_subtype_structural(&own));
3478 }
3479
3480 #[test]
3481 fn subtype_enum_case_under_bare_object() {
3482 let sub = Type::single(Atomic::TLiteralEnumCase {
3483 enum_fqcn: Name::new("RoundingMode"),
3484 case_name: Name::new("Unnecessary"),
3485 });
3486 let sup = Type::single(Atomic::TObject);
3487 assert!(sub.is_subtype_structural(&sup));
3488 }
3489
3490 #[test]
3491 fn template_substitution() {
3492 let mut bindings = FxHashMap::default();
3493 bindings.insert(Name::new("T"), Type::single(Atomic::TString));
3494
3495 let tmpl = Type::single(Atomic::TTemplateParam {
3496 name: Name::new("T"),
3497 as_type: Box::new(Type::mixed()),
3498 defining_entity: Name::new("MyClass"),
3499 });
3500
3501 let resolved = tmpl.substitute_templates(&bindings);
3502 assert_eq!(resolved.types.len(), 1);
3503 assert!(matches!(resolved.types[0], Atomic::TString));
3504 }
3505
3506 #[test]
3507 fn intersection_is_object() {
3508 let parts = vec![
3509 Type::single(Atomic::TNamedObject {
3510 fqcn: Name::new("Iterator"),
3511 type_params: empty_type_params(),
3512 }),
3513 Type::single(Atomic::TNamedObject {
3514 fqcn: Name::new("Countable"),
3515 type_params: empty_type_params(),
3516 }),
3517 ];
3518 let atomic = Atomic::TIntersection {
3519 parts: vec_to_type_params(parts),
3520 };
3521 assert!(atomic.is_object());
3522 assert!(!atomic.can_be_falsy());
3523 assert!(atomic.can_be_truthy());
3524 }
3525
3526 #[test]
3527 fn intersection_display_two_parts() {
3528 let parts = vec![
3529 Type::single(Atomic::TNamedObject {
3530 fqcn: Name::new("Iterator"),
3531 type_params: empty_type_params(),
3532 }),
3533 Type::single(Atomic::TNamedObject {
3534 fqcn: Name::new("Countable"),
3535 type_params: empty_type_params(),
3536 }),
3537 ];
3538 let u = Type::single(Atomic::TIntersection {
3539 parts: vec_to_type_params(parts),
3540 });
3541 assert_eq!(format!("{u}"), "Iterator&Countable");
3542 }
3543
3544 #[test]
3545 fn intersection_display_three_parts() {
3546 let parts = vec![
3547 Type::single(Atomic::TNamedObject {
3548 fqcn: Name::new("A"),
3549 type_params: empty_type_params(),
3550 }),
3551 Type::single(Atomic::TNamedObject {
3552 fqcn: Name::new("B"),
3553 type_params: empty_type_params(),
3554 }),
3555 Type::single(Atomic::TNamedObject {
3556 fqcn: Name::new("C"),
3557 type_params: empty_type_params(),
3558 }),
3559 ];
3560 let u = Type::single(Atomic::TIntersection {
3561 parts: vec_to_type_params(parts),
3562 });
3563 assert_eq!(format!("{u}"), "A&B&C");
3564 }
3565
3566 #[test]
3567 fn intersection_in_nullable_union_display() {
3568 let intersection = Atomic::TIntersection {
3569 parts: vec_to_type_params(vec![
3570 Type::single(Atomic::TNamedObject {
3571 fqcn: Name::new("Iterator"),
3572 type_params: empty_type_params(),
3573 }),
3574 Type::single(Atomic::TNamedObject {
3575 fqcn: Name::new("Countable"),
3576 type_params: empty_type_params(),
3577 }),
3578 ]),
3579 };
3580 let mut u = Type::single(intersection);
3581 u.add_type(Atomic::TNull);
3582 assert!(u.is_nullable());
3583 assert!(u.contains(|t| matches!(t, Atomic::TIntersection { .. })));
3584 }
3585
3586 fn t_param(name: &str) -> Type {
3589 Type::single(Atomic::TTemplateParam {
3590 name: Name::new(name),
3591 as_type: Box::new(Type::mixed()),
3592 defining_entity: Name::new("Fn"),
3593 })
3594 }
3595
3596 fn bindings_t_string() -> FxHashMap<Name, Type> {
3597 let mut b = FxHashMap::default();
3598 b.insert(Name::new("T"), Type::single(Atomic::TString));
3599 b
3600 }
3601
3602 #[test]
3603 fn substitute_non_empty_array_key_and_value() {
3604 let ty = Type::single(Atomic::TNonEmptyArray {
3605 key: Box::new(t_param("T")),
3606 value: Box::new(t_param("T")),
3607 });
3608 let result = ty.substitute_templates(&bindings_t_string());
3609 assert_eq!(result.types.len(), 1);
3610 let Atomic::TNonEmptyArray { key, value } = &result.types[0] else {
3611 panic!("expected TNonEmptyArray");
3612 };
3613 assert!(matches!(key.types[0], Atomic::TString));
3614 assert!(matches!(value.types[0], Atomic::TString));
3615 }
3616
3617 #[test]
3618 fn substitute_non_empty_list_value() {
3619 let ty = Type::single(Atomic::TNonEmptyList {
3620 value: Box::new(t_param("T")),
3621 });
3622 let result = ty.substitute_templates(&bindings_t_string());
3623 let Atomic::TNonEmptyList { value } = &result.types[0] else {
3624 panic!("expected TNonEmptyList");
3625 };
3626 assert!(matches!(value.types[0], Atomic::TString));
3627 }
3628
3629 #[test]
3630 fn substitute_keyed_array_property_types() {
3631 use crate::atomic::{ArrayKey, KeyedProperty};
3632 let mut props = KeyedProperties::default();
3633 props.insert(
3634 ArrayKey::String(Arc::from("name")),
3635 KeyedProperty {
3636 ty: t_param("T"),
3637 optional: false,
3638 },
3639 );
3640 props.insert(
3641 ArrayKey::String(Arc::from("tag")),
3642 KeyedProperty {
3643 ty: t_param("T"),
3644 optional: true,
3645 },
3646 );
3647 let ty = Type::single(Atomic::TKeyedArray {
3648 properties: Arc::new(props),
3649 is_open: true,
3650 is_list: false,
3651 });
3652 let result = ty.substitute_templates(&bindings_t_string());
3653 let Atomic::TKeyedArray {
3654 properties,
3655 is_open,
3656 is_list,
3657 } = &result.types[0]
3658 else {
3659 panic!("expected TKeyedArray");
3660 };
3661 assert!(is_open);
3662 assert!(!is_list);
3663 assert!(matches!(
3664 properties[&ArrayKey::String(Arc::from("name"))].ty.types[0],
3665 Atomic::TString
3666 ));
3667 assert!(properties[&ArrayKey::String(Arc::from("tag"))].optional);
3668 assert!(matches!(
3669 properties[&ArrayKey::String(Arc::from("tag"))].ty.types[0],
3670 Atomic::TString
3671 ));
3672 }
3673
3674 #[test]
3675 fn substitute_callable_params_and_return() {
3676 use crate::atomic::FnParam;
3677 let ty = Type::single(Atomic::TCallable {
3678 params: Some(Box::new(vec![FnParam {
3679 name: Name::new("x"),
3680 ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3681 out_ty: None,
3682 default: None,
3683 is_variadic: false,
3684 is_byref: false,
3685 is_optional: false,
3686 }])),
3687 return_type: Some(Box::new(t_param("T"))),
3688 is_pure: false,
3689 });
3690 let result = ty.substitute_templates(&bindings_t_string());
3691 let Atomic::TCallable {
3692 params,
3693 return_type,
3694 ..
3695 } = &result.types[0]
3696 else {
3697 panic!("expected TCallable");
3698 };
3699 let param_ty = params.as_ref().unwrap()[0].ty.as_ref().unwrap();
3700 let param_union = param_ty.to_union();
3701 assert!(matches!(param_union.types[0], Atomic::TString));
3702 let ret = return_type.as_ref().unwrap();
3703 assert!(matches!(ret.types[0], Atomic::TString));
3704 }
3705
3706 #[test]
3707 fn substitute_callable_bare_no_panic() {
3708 let ty = Type::single(Atomic::TCallable {
3710 params: None,
3711 return_type: None,
3712 is_pure: false,
3713 });
3714 let result = ty.substitute_templates(&bindings_t_string());
3715 assert!(matches!(
3716 result.types[0],
3717 Atomic::TCallable {
3718 params: None,
3719 return_type: None,
3720 ..
3721 }
3722 ));
3723 }
3724
3725 #[test]
3726 fn substitute_closure_params_return_and_this() {
3727 use crate::atomic::FnParam;
3728 let ty = Type::single(Atomic::TClosure {
3729 data: Box::new(crate::atomic::ClosureData {
3730 params: Box::new([FnParam {
3731 name: Name::new("a"),
3732 ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3733 out_ty: None,
3734 default: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3735 is_variadic: true,
3736 is_byref: true,
3737 is_optional: true,
3738 }]),
3739 return_type: t_param("T"),
3740 this_type: Some(t_param("T")),
3741 is_pure: false,
3742 is_static: false,
3743 rejects_surplus_args: false,
3744 is_impure: false,
3745 }),
3746 });
3747 let result = ty.substitute_templates(&bindings_t_string());
3748 let Atomic::TClosure { data } = &result.types[0] else {
3749 panic!("expected TClosure");
3750 };
3751 let (params, return_type, this_type) = (&data.params, &data.return_type, &data.this_type);
3752 let p = ¶ms[0];
3753 let ty_union = p.ty.as_ref().unwrap().to_union();
3754 let default_union = p.default.as_ref().unwrap().to_union();
3755 assert!(matches!(ty_union.types[0], Atomic::TString));
3756 assert!(matches!(default_union.types[0], Atomic::TString));
3757 assert!(p.is_variadic);
3759 assert!(p.is_byref);
3760 assert!(p.is_optional);
3761 assert!(matches!(return_type.types[0], Atomic::TString));
3762 assert!(matches!(
3763 this_type.as_ref().unwrap().types[0],
3764 Atomic::TString
3765 ));
3766 }
3767
3768 #[test]
3769 fn substitute_conditional_all_branches() {
3770 let ty = Type::single(conditional(
3771 None,
3772 t_param("T"),
3773 t_param("T"),
3774 Type::single(Atomic::TInt),
3775 ));
3776 let result = ty.substitute_templates(&bindings_t_string());
3777 let Atomic::TConditional { data } = &result.types[0] else {
3778 panic!("expected TConditional");
3779 };
3780 let (subject, if_true, if_false) = (&data.subject, &data.if_true, &data.if_false);
3781 assert!(matches!(subject.types[0], Atomic::TString));
3782 assert!(matches!(if_true.types[0], Atomic::TString));
3783 assert!(matches!(if_false.types[0], Atomic::TInt));
3784 }
3785
3786 #[test]
3787 fn resolve_conditional_is_null_non_null_arg() {
3788 let ty = Type::single(conditional(
3789 Some(Name::new("x")),
3790 Type::single(Atomic::TNull),
3791 Type::single(Atomic::TInt),
3792 Type::single(Atomic::TString),
3793 ));
3794 let result = ty.resolve_conditional_returns(|name| {
3795 if name == "x" {
3796 Some(Type::single(Atomic::TString)) } else {
3798 None
3799 }
3800 });
3801 assert!(result.types.len() == 1);
3802 assert!(matches!(result.types[0], Atomic::TString));
3803 }
3804
3805 #[test]
3806 fn resolve_conditional_is_null_null_arg() {
3807 let ty = Type::single(conditional(
3808 Some(Name::new("x")),
3809 Type::single(Atomic::TNull),
3810 Type::single(Atomic::TInt),
3811 Type::single(Atomic::TString),
3812 ));
3813 let result = ty.resolve_conditional_returns(|name| {
3814 if name == "x" {
3815 Some(Type::single(Atomic::TNull)) } else {
3817 None
3818 }
3819 });
3820 assert!(result.types.len() == 1);
3821 assert!(matches!(result.types[0], Atomic::TInt));
3822 }
3823
3824 #[test]
3825 fn resolve_conditional_is_null_nullable_arg_widens_to_branch_union() {
3826 let mut nullable_str = Type::single(Atomic::TString);
3827 nullable_str.add_type(Atomic::TNull);
3828 let ty = Type::single(conditional(
3829 Some(Name::new("x")),
3830 Type::single(Atomic::TNull),
3831 Type::single(Atomic::TInt),
3832 Type::single(Atomic::TString),
3833 ));
3834 let result = ty.resolve_conditional_returns(|name| {
3835 if name == "x" {
3836 Some(nullable_str.clone())
3837 } else {
3838 None
3839 }
3840 });
3841 assert_eq!(result.types.len(), 2);
3843 assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
3844 assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
3845 }
3846
3847 #[test]
3848 fn resolve_conditional_nested_widens_inner_branch() {
3849 let inner = Type::single(conditional(
3852 Some(Name::new("x")),
3853 Type::single(Atomic::TString),
3854 Type::single(Atomic::TString),
3855 Type::single(Atomic::TFloat),
3856 ));
3857 let ty = Type::single(conditional(
3858 Some(Name::new("x")),
3859 Type::single(Atomic::TNull),
3860 Type::single(Atomic::TInt),
3861 inner,
3862 ));
3863 let result = ty.resolve_conditional_returns(|_| None);
3865 assert!(
3866 result
3867 .types
3868 .iter()
3869 .all(|t| !matches!(t, Atomic::TConditional { .. })),
3870 "no TConditional should survive: {:?}",
3871 result.types
3872 );
3873 assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
3874 assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
3875 assert!(result.types.iter().any(|t| matches!(t, Atomic::TFloat)));
3876 }
3877
3878 #[test]
3879 fn resolve_conditional_nested_resolves_inner_branch() {
3880 let inner = Type::single(conditional(
3884 Some(Name::new("x")),
3885 Type::single(Atomic::TString),
3886 Type::single(Atomic::TString),
3887 Type::single(Atomic::TFloat),
3888 ));
3889 let ty = Type::single(conditional(
3890 Some(Name::new("x")),
3891 Type::single(Atomic::TNull),
3892 Type::single(Atomic::TInt),
3893 inner,
3894 ));
3895 let result = ty.resolve_conditional_returns(|name| {
3897 if name == "x" {
3898 Some(Type::single(Atomic::TString))
3899 } else {
3900 None
3901 }
3902 });
3903 assert!(
3904 result
3905 .types
3906 .iter()
3907 .all(|t| !matches!(t, Atomic::TConditional { .. })),
3908 "no TConditional should survive: {:?}",
3909 result.types
3910 );
3911 assert_eq!(result.types.len(), 1);
3912 assert!(matches!(result.types[0], Atomic::TString));
3913 }
3914
3915 #[test]
3916 fn resolve_conditional_true_subject_bool_arg_widens() {
3917 let ty = Type::single(conditional(
3921 Some(Name::new("x")),
3922 Type::single(Atomic::TTrue),
3923 Type::single(Atomic::TInt),
3924 Type::single(Atomic::TString),
3925 ));
3926 let result = ty.resolve_conditional_returns(|name| {
3927 if name == "x" {
3928 Some(Type::single(Atomic::TBool))
3929 } else {
3930 None
3931 }
3932 });
3933 assert_eq!(result.types.len(), 2);
3934 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3935 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3936 }
3937
3938 #[test]
3939 fn resolve_conditional_true_subject_mixed_arg_widens() {
3940 let ty = Type::single(conditional(
3943 Some(Name::new("x")),
3944 Type::single(Atomic::TTrue),
3945 Type::single(Atomic::TInt),
3946 Type::single(Atomic::TString),
3947 ));
3948 let result = ty.resolve_conditional_returns(|name| {
3949 if name == "x" {
3950 Some(Type::mixed())
3951 } else {
3952 None
3953 }
3954 });
3955 assert_eq!(result.types.len(), 2);
3956 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3957 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3958 }
3959
3960 #[test]
3961 fn resolve_conditional_true_subject_literal_args() {
3962 let ty = Type::single(conditional(
3965 Some(Name::new("x")),
3966 Type::single(Atomic::TTrue),
3967 Type::single(Atomic::TInt),
3968 Type::single(Atomic::TString),
3969 ));
3970 let false_arg = ty.clone().resolve_conditional_returns(|name| {
3971 if name == "x" {
3972 Some(Type::single(Atomic::TFalse))
3973 } else {
3974 None
3975 }
3976 });
3977 assert_eq!(false_arg.types.len(), 1);
3978 assert!(matches!(false_arg.types[0], Atomic::TString));
3979
3980 let true_arg = ty.resolve_conditional_returns(|name| {
3981 if name == "x" {
3982 Some(Type::single(Atomic::TTrue))
3983 } else {
3984 None
3985 }
3986 });
3987 assert_eq!(true_arg.types.len(), 1);
3988 assert!(matches!(true_arg.types[0], Atomic::TInt));
3989 }
3990
3991 #[test]
3992 fn resolve_conditional_bool_subject_scalar_arg_widens() {
3993 let ty = Type::single(conditional(
3997 Some(Name::new("x")),
3998 Type::single(Atomic::TBool),
3999 Type::single(Atomic::TInt),
4000 Type::single(Atomic::TString),
4001 ));
4002 let result = ty.resolve_conditional_returns(|name| {
4003 if name == "x" {
4004 Some(Type::single(Atomic::TScalar))
4005 } else {
4006 None
4007 }
4008 });
4009 assert_eq!(result.types.len(), 2);
4010 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
4011 assert!(result.contains(|t| matches!(t, Atomic::TString)));
4012 }
4013
4014 #[test]
4015 fn resolve_conditional_string_subject_bool_arg_false_branch() {
4016 let ty = Type::single(conditional(
4020 Some(Name::new("x")),
4021 Type::single(Atomic::TString),
4022 Type::single(Atomic::TInt),
4023 Type::single(Atomic::TBool),
4024 ));
4025 let result = ty.resolve_conditional_returns(|name| {
4026 if name == "x" {
4027 Some(Type::single(Atomic::TBool))
4028 } else {
4029 None
4030 }
4031 });
4032 assert_eq!(result.types.len(), 1);
4033 assert!(matches!(result.types[0], Atomic::TBool));
4034 }
4035
4036 #[test]
4037 fn resolve_conditional_list_subject_bare_array_arg_widens() {
4038 let ty = Type::single(conditional(
4041 Some(Name::new("x")),
4042 Type::single(Atomic::TList {
4043 value: Box::new(Type::mixed()),
4044 }),
4045 Type::single(Atomic::TInt),
4046 Type::single(Atomic::TString),
4047 ));
4048 let result = ty.resolve_conditional_returns(|name| {
4049 if name == "x" {
4050 Some(Type::single(Atomic::TArray {
4051 key: Box::new(Type::mixed()),
4052 value: Box::new(Type::mixed()),
4053 }))
4054 } else {
4055 None
4056 }
4057 });
4058 assert_eq!(result.types.len(), 2);
4059 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
4060 assert!(result.contains(|t| matches!(t, Atomic::TString)));
4061 }
4062
4063 #[test]
4064 fn resolve_conditional_float_subject_int_literal_false_branch() {
4065 let ty = resolve_conditional_branch(
4068 &Type::single(Atomic::TFloat),
4069 &Type::single(Atomic::TLiteralInt(42)),
4070 &Type::single(Atomic::TInt),
4071 &Type::single(Atomic::TString),
4072 );
4073 assert!(matches!(
4074 ty.as_ref(),
4075 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4076 ));
4077 }
4078
4079 #[test]
4080 fn resolve_conditional_int_subject_float_literal_false_branch() {
4081 let ty = resolve_conditional_branch(
4082 &Type::single(Atomic::TInt),
4083 &Type::single(Atomic::TLiteralFloat(1, 0)),
4084 &Type::single(Atomic::TInt),
4085 &Type::single(Atomic::TString),
4086 );
4087 assert!(matches!(
4088 ty.as_ref(),
4089 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4090 ));
4091 }
4092
4093 #[test]
4094 fn resolve_conditional_float_subject_float_literal_then_branch() {
4095 let ty = resolve_conditional_branch(
4096 &Type::single(Atomic::TFloat),
4097 &Type::single(Atomic::TLiteralFloat(1, 5)),
4098 &Type::single(Atomic::TInt),
4099 &Type::single(Atomic::TString),
4100 );
4101 assert!(matches!(
4102 ty.as_ref(),
4103 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4104 ));
4105 }
4106
4107 #[test]
4108 fn resolve_conditional_int_subject_int_literal_then_branch() {
4109 let ty = resolve_conditional_branch(
4110 &Type::single(Atomic::TInt),
4111 &Type::single(Atomic::TLiteralInt(7)),
4112 &Type::single(Atomic::TInt),
4113 &Type::single(Atomic::TString),
4114 );
4115 assert!(matches!(
4116 ty.as_ref(),
4117 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4118 ));
4119 }
4120
4121 #[test]
4122 fn resolve_conditional_int_subject_float_arg_false_branch() {
4123 let ty = resolve_conditional_branch(
4126 &Type::single(Atomic::TInt),
4127 &Type::single(Atomic::TFloat),
4128 &Type::single(Atomic::TInt),
4129 &Type::single(Atomic::TString),
4130 );
4131 assert!(matches!(
4132 ty.as_ref(),
4133 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4134 ));
4135 }
4136
4137 #[test]
4138 fn resolve_conditional_array_subject_string_arg_false_branch() {
4139 let ty = resolve_conditional_branch(
4140 &Type::single(Atomic::TArray {
4141 key: Box::new(Type::mixed()),
4142 value: Box::new(Type::mixed()),
4143 }),
4144 &Type::single(Atomic::TString),
4145 &Type::single(Atomic::TInt),
4146 &Type::single(Atomic::TString),
4147 );
4148 assert!(matches!(
4149 ty.as_ref(),
4150 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4151 ));
4152 }
4153
4154 #[test]
4155 fn resolve_conditional_array_subject_bool_arg_false_branch() {
4156 let ty = resolve_conditional_branch(
4157 &Type::single(Atomic::TArray {
4158 key: Box::new(Type::mixed()),
4159 value: Box::new(Type::mixed()),
4160 }),
4161 &Type::single(Atomic::TBool),
4162 &Type::single(Atomic::TInt),
4163 &Type::single(Atomic::TString),
4164 );
4165 assert!(matches!(
4166 ty.as_ref(),
4167 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4168 ));
4169 }
4170
4171 #[test]
4172 fn resolve_conditional_array_subject_mixed_arg_widens() {
4173 let ty = resolve_conditional_branch(
4177 &Type::single(Atomic::TArray {
4178 key: Box::new(Type::mixed()),
4179 value: Box::new(Type::mixed()),
4180 }),
4181 &Type::mixed(),
4182 &Type::single(Atomic::TInt),
4183 &Type::single(Atomic::TString),
4184 );
4185 assert!(ty.is_none());
4186 }
4187
4188 #[test]
4189 fn resolve_conditional_array_subject_list_arg_then_branch() {
4190 let ty = resolve_conditional_branch(
4193 &Type::single(Atomic::TArray {
4194 key: Box::new(Type::mixed()),
4195 value: Box::new(Type::mixed()),
4196 }),
4197 &Type::single(Atomic::TList {
4198 value: Box::new(Type::mixed()),
4199 }),
4200 &Type::single(Atomic::TInt),
4201 &Type::single(Atomic::TString),
4202 );
4203 assert!(matches!(
4204 ty.as_ref(),
4205 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4206 ));
4207 }
4208
4209 #[test]
4210 fn resolve_conditional_list_subject_keyed_list_arg_then_branch() {
4211 let ty = resolve_conditional_branch(
4213 &Type::single(Atomic::TList {
4214 value: Box::new(Type::mixed()),
4215 }),
4216 &Type::single(Atomic::TKeyedArray {
4217 properties: Arc::default(),
4218 is_open: false,
4219 is_list: true,
4220 }),
4221 &Type::single(Atomic::TInt),
4222 &Type::single(Atomic::TString),
4223 );
4224 assert!(matches!(
4225 ty.as_ref(),
4226 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4227 ));
4228 }
4229
4230 #[test]
4231 fn resolve_conditional_list_subject_list_string_union_widens() {
4232 let ty = resolve_conditional_branch(
4236 &Type::single(Atomic::TList {
4237 value: Box::new(Type::mixed()),
4238 }),
4239 &Type::from_vec(vec![
4240 Atomic::TList {
4241 value: Box::new(Type::mixed()),
4242 },
4243 Atomic::TString,
4244 ]),
4245 &Type::single(Atomic::TInt),
4246 &Type::single(Atomic::TString),
4247 );
4248 assert!(ty.is_none());
4249 }
4250
4251 #[test]
4252 fn resolve_conditional_numeric_subject_widens() {
4253 let ty = resolve_conditional_branch(
4257 &Type::single(Atomic::TNumeric),
4258 &Type::single(Atomic::TLiteralString("123".into())),
4259 &Type::single(Atomic::TInt),
4260 &Type::single(Atomic::TString),
4261 );
4262 assert!(ty.is_none());
4263 }
4264
4265 #[test]
4266 fn resolve_conditional_non_empty_string_subject_widens() {
4267 let ty = resolve_conditional_branch(
4270 &Type::single(Atomic::TNonEmptyString),
4271 &Type::single(Atomic::TString),
4272 &Type::single(Atomic::TInt),
4273 &Type::single(Atomic::TString),
4274 );
4275 assert!(ty.is_none());
4276 }
4277
4278 #[test]
4279 fn resolve_conditional_template_arg_widens() {
4280 let ty = resolve_conditional_branch(
4283 &Type::single(Atomic::TString),
4284 &t_param("T"),
4285 &Type::single(Atomic::TInt),
4286 &Type::single(Atomic::TString),
4287 );
4288 assert!(ty.is_none());
4289 }
4290
4291 #[test]
4292 fn resolve_conditional_mixed_subject_bool_arg_then_branch() {
4293 let ty = resolve_conditional_branch(
4296 &Type::single(Atomic::TMixed),
4297 &Type::single(Atomic::TBool),
4298 &Type::single(Atomic::TInt),
4299 &Type::single(Atomic::TString),
4300 );
4301 assert!(matches!(
4302 ty.as_ref(),
4303 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4304 ));
4305 }
4306
4307 #[test]
4308 fn resolve_conditional_scalar_subject_null_arg_false_branch() {
4309 let ty = resolve_conditional_branch(
4312 &Type::single(Atomic::TScalar),
4313 &Type::single(Atomic::TNull),
4314 &Type::single(Atomic::TInt),
4315 &Type::single(Atomic::TString),
4316 );
4317 assert!(matches!(
4318 ty.as_ref(),
4319 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4320 ));
4321 }
4322
4323 #[test]
4324 fn resolve_conditional_object_subject_named_arg_then_branch() {
4325 let ty = resolve_conditional_branch(
4327 &Type::single(Atomic::TObject),
4328 &Type::single(Atomic::TNamedObject {
4329 fqcn: Name::new("Foo"),
4330 type_params: empty_type_params(),
4331 }),
4332 &Type::single(Atomic::TInt),
4333 &Type::single(Atomic::TString),
4334 );
4335 assert!(matches!(
4336 ty.as_ref(),
4337 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4338 ));
4339 }
4340
4341 #[test]
4342 fn resolve_conditional_named_subject_other_class_widens() {
4343 let ty = resolve_conditional_branch(
4347 &Type::single(Atomic::TNamedObject {
4348 fqcn: Name::new("Foo"),
4349 type_params: empty_type_params(),
4350 }),
4351 &Type::single(Atomic::TNamedObject {
4352 fqcn: Name::new("Bar"),
4353 type_params: empty_type_params(),
4354 }),
4355 &Type::single(Atomic::TInt),
4356 &Type::single(Atomic::TString),
4357 );
4358 assert!(ty.is_none());
4359 }
4360
4361 #[test]
4362 fn resolve_conditional_enum_case_subject_widens() {
4363 let ty = resolve_conditional_branch(
4366 &Type::single(Atomic::TLiteralEnumCase {
4367 enum_fqcn: Name::new("RoundingMode"),
4368 case_name: Name::new("Unnecessary"),
4369 }),
4370 &Type::single(Atomic::TInt),
4371 &Type::single(Atomic::TInt),
4372 &Type::single(Atomic::TString),
4373 );
4374 assert!(ty.is_none());
4375 }
4376
4377 #[test]
4378 fn resolve_conditional_null_subject_bool_arg_false_branch() {
4379 let ty = resolve_conditional_branch(
4381 &Type::single(Atomic::TNull),
4382 &Type::single(Atomic::TBool),
4383 &Type::single(Atomic::TInt),
4384 &Type::single(Atomic::TString),
4385 );
4386 assert!(matches!(
4387 ty.as_ref(),
4388 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4389 ));
4390 }
4391
4392 #[test]
4393 fn resolve_conditional_bool_subject_true_arg_then_branch() {
4394 let ty = resolve_conditional_branch(
4397 &Type::single(Atomic::TBool),
4398 &Type::single(Atomic::TTrue),
4399 &Type::single(Atomic::TInt),
4400 &Type::single(Atomic::TString),
4401 );
4402 assert!(matches!(
4403 ty.as_ref(),
4404 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4405 ));
4406 }
4407
4408 #[test]
4409 fn substitute_intersection_parts() {
4410 let ty = Type::single(Atomic::TIntersection {
4411 parts: vec_to_type_params(vec![
4412 Type::single(Atomic::TNamedObject {
4413 fqcn: Name::new("Countable"),
4414 type_params: empty_type_params(),
4415 }),
4416 t_param("T"),
4417 ]),
4418 });
4419 let result = ty.substitute_templates(&bindings_t_string());
4420 let Atomic::TIntersection { parts } = &result.types[0] else {
4421 panic!("expected TIntersection");
4422 };
4423 assert_eq!(parts.len(), 2);
4424 assert!(matches!(parts[0].types[0], Atomic::TNamedObject { .. }));
4425 assert!(matches!(parts[1].types[0], Atomic::TString));
4426 }
4427
4428 fn shape(props: &[(&str, Atomic, bool)], is_open: bool) -> Atomic {
4429 Atomic::TKeyedArray {
4430 properties: Arc::new(
4431 props
4432 .iter()
4433 .map(|(k, ty, optional)| {
4434 (
4435 ArrayKey::String(Arc::from(*k)),
4436 KeyedProperty {
4437 ty: Type::single(ty.clone()),
4438 optional: *optional,
4439 },
4440 )
4441 })
4442 .collect(),
4443 ),
4444 is_open,
4445 is_list: false,
4446 }
4447 }
4448
4449 fn shape_with_bits(bits: u32, is_open: bool) -> Atomic {
4451 let names: Vec<String> = (0..5).map(|i| format!("k{i}")).collect();
4452 let mut props = vec![("a", Atomic::TInt, false)];
4453 props.extend(
4454 (0..5)
4455 .filter(|i| bits & (1 << i) != 0)
4456 .map(|i| (names[i].as_str(), Atomic::TString, false)),
4457 );
4458 shape(&props, is_open)
4459 }
4460
4461 fn keyed_count(ty: &Type) -> usize {
4462 ty.types
4463 .iter()
4464 .filter(|t| matches!(t, Atomic::TKeyedArray { .. }))
4465 .count()
4466 }
4467
4468 #[test]
4469 fn add_type_keeps_few_shapes_apart() {
4470 let mut ty = Type::empty();
4471 for bits in 0..MAX_KEYED_SHAPES as u32 {
4472 ty.add_type(shape_with_bits(bits, false));
4473 }
4474 assert_eq!(keyed_count(&ty), MAX_KEYED_SHAPES);
4475 }
4476
4477 #[test]
4478 fn add_type_folds_shapes_past_the_limit() {
4479 let mut ty = Type::empty();
4480 for bits in 0..32 {
4481 ty.add_type(shape_with_bits(bits, false));
4482 }
4483 assert!(keyed_count(&ty) <= MAX_KEYED_SHAPES);
4484 for t in &ty.types {
4486 let Atomic::TKeyedArray { properties, .. } = t else {
4487 continue;
4488 };
4489 assert!(!properties[&ArrayKey::String(Arc::from("a"))].optional);
4490 }
4491 for i in 0..5 {
4492 let key = ArrayKey::String(Arc::from(format!("k{i}").as_str()));
4493 assert!(ty.types.iter().any(|t| matches!(
4494 t,
4495 Atomic::TKeyedArray { properties, .. } if properties.contains_key(&key)
4496 )));
4497 }
4498 }
4499
4500 #[test]
4501 fn add_type_folds_generic_arrays_past_the_limit() {
4502 let mut ty = Type::empty();
4503 for i in 0..32 {
4504 ty.add_type(Atomic::TArray {
4505 key: Box::new(Type::single(Atomic::TInt)),
4506 value: Box::new(Type::single(Atomic::TLiteralInt(i))),
4507 });
4508 }
4509 assert!(ty.types.len() <= MAX_GENERIC_ARRAYS);
4510 for i in 0..32 {
4511 assert!(ty.types.iter().any(|t| matches!(
4512 t,
4513 Atomic::TArray { value, .. } if value.types.contains(&Atomic::TLiteralInt(i))
4514 )));
4515 }
4516 }
4517
4518 #[test]
4519 fn add_type_widens_string_literals_past_the_limit() {
4520 let mut ty = Type::empty();
4521 for i in 0..MAX_LITERAL_STRINGS {
4522 ty.add_type(Atomic::TLiteralString(format!("s{i}").into()));
4523 }
4524 assert_eq!(ty.types.len(), MAX_LITERAL_STRINGS);
4525 ty.add_type(Atomic::TLiteralString("one more".into()));
4526 assert_eq!(ty.types.as_slice(), &[Atomic::TString]);
4527 ty.add_type(Atomic::TLiteralString("after".into()));
4528 assert_eq!(ty.types.as_slice(), &[Atomic::TString]);
4529 }
4530
4531 #[test]
4532 fn add_type_drops_generic_arrays_another_covers() {
4533 let list = |value: Atomic| Atomic::TList {
4534 value: Box::new(Type::single(value)),
4535 };
4536 let mut ty = Type::single(list(Atomic::TLiteralInt(0)));
4537 ty.add_type(list(Atomic::TInt));
4538 assert_eq!(ty.types.as_slice(), &[list(Atomic::TInt)]);
4539 ty.add_type(list(Atomic::TLiteralInt(1)));
4540 assert_eq!(ty.types.as_slice(), &[list(Atomic::TInt)]);
4541
4542 let mut opaque = Type::single(list(Atomic::TMixed));
4543 opaque.add_type(list(Atomic::TInt));
4544 assert_eq!(opaque.types.len(), 2);
4545
4546 let mut kinds = Type::single(Atomic::TNonEmptyList {
4547 value: Box::new(Type::single(Atomic::TInt)),
4548 });
4549 kinds.add_type(list(Atomic::TInt));
4550 assert_eq!(kinds.types.len(), 2);
4551 }
4552
4553 #[test]
4554 fn add_type_drops_shapes_another_covers() {
4555 let mut ty = Type::single(shape(&[("a", Atomic::TLiteralInt(1), false)], false));
4556 ty.add_type(shape(&[("a", Atomic::TInt, false)], false));
4557 assert_eq!(
4558 ty.types.as_slice(),
4559 &[shape(&[("a", Atomic::TInt, false)], false)]
4560 );
4561
4562 let kept = |a: Atomic, b: Atomic| {
4563 let mut ty = Type::single(a);
4564 ty.add_type(b);
4565 ty.types.len() == 2
4566 };
4567 let int_shape = shape(&[("a", Atomic::TLiteralInt(1), false)], false);
4568 assert!(kept(
4569 int_shape.clone(),
4570 shape(&[("a", Atomic::TFloat, false)], false)
4571 ));
4572 assert!(kept(
4573 int_shape.clone(),
4574 shape(&[("a", Atomic::TMixed, false)], false)
4575 ));
4576 assert!(kept(
4577 int_shape.clone(),
4578 shape(&[("a", Atomic::TInt, true)], false)
4579 ));
4580 assert!(kept(
4581 int_shape.clone(),
4582 shape(&[("a", Atomic::TInt, false)], true)
4583 ));
4584 assert!(kept(
4585 int_shape,
4586 shape(
4587 &[("a", Atomic::TInt, false), ("b", Atomic::TInt, false)],
4588 false
4589 )
4590 ));
4591 }
4592
4593 #[test]
4594 fn combine_keeps_emptiness_and_open_shape_soundness() {
4595 assert!(combine_keyed_arrays(
4597 &shape(&[], false),
4598 &shape(&[("a", Atomic::TInt, false)], false)
4599 )
4600 .is_none());
4601 assert!(combine_keyed_arrays(
4603 &shape(&[("a", Atomic::TInt, false)], true),
4604 &shape(&[("a", Atomic::TInt, false)], false)
4605 )
4606 .is_none());
4607 assert_eq!(
4609 combine_keyed_arrays(
4610 &shape(&[("a", Atomic::TInt, false)], true),
4611 &shape(
4612 &[("a", Atomic::TInt, false), ("k", Atomic::TString, false)],
4613 true
4614 )
4615 ),
4616 Some(shape(&[("a", Atomic::TInt, false)], true))
4617 );
4618 }
4619
4620 #[test]
4621 fn substitute_no_template_params_identity() {
4622 let ty = Type::single(Atomic::TInt);
4623 let result = ty.substitute_templates(&bindings_t_string());
4624 assert!(matches!(result.types[0], Atomic::TInt));
4625 }
4626}