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
123fn 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 generic_array_covered(sub: &Atomic, sup: &Atomic) -> bool {
159 fn parts(a: &Atomic) -> Option<(Option<&Type>, &Type)> {
160 match a {
161 Atomic::TArray { key, value } | Atomic::TNonEmptyArray { key, value } => {
162 Some((Some(key), value))
163 }
164 Atomic::TList { value } | Atomic::TNonEmptyList { value } => Some((None, value)),
165 _ => None,
166 }
167 }
168 let opaque = |t: &Type| {
169 t.types
170 .iter()
171 .any(|a| matches!(a, Atomic::TMixed | Atomic::TTemplateParam { .. }))
172 };
173 let fits = |x: &Type, y: &Type| !opaque(x) && !opaque(y) && x.is_subtype_structural(y);
174 if std::mem::discriminant(sub) != std::mem::discriminant(sup) {
175 return false;
176 }
177 match (parts(sub), parts(sup)) {
178 (Some((sub_key, sub_value)), Some((sup_key, sup_value))) => {
179 fits(sub_value, sup_value)
180 && match (sub_key, sup_key) {
181 (Some(a), Some(b)) => fits(a, b),
182 _ => true,
183 }
184 }
185 _ => false,
186 }
187}
188
189fn combine_keyed_arrays(a: &Atomic, b: &Atomic) -> Option<Atomic> {
194 let (
195 Atomic::TKeyedArray {
196 properties: pa,
197 is_open: oa,
198 is_list: la,
199 },
200 Atomic::TKeyedArray {
201 properties: pb,
202 is_open: ob,
203 is_list: lb,
204 },
205 ) = (a, b)
206 else {
207 return None;
208 };
209 let non_empty = |p: &KeyedProperties| p.values().any(|v| !v.optional);
210 if oa != ob || la != lb || non_empty(pa) != non_empty(pb) {
211 return None;
212 }
213 let mut properties =
214 KeyedProperties::with_capacity_and_hasher(pa.len().max(pb.len()), Default::default());
215 for (key, x) in pa.iter() {
216 let prop = match pb.get(key) {
217 Some(y) => {
218 let mut ty = x.ty.clone();
219 ty.merge_with(&y.ty);
220 KeyedProperty {
221 ty,
222 optional: x.optional || y.optional,
223 }
224 }
225 None if *oa => continue,
228 None => KeyedProperty {
229 ty: x.ty.clone(),
230 optional: true,
231 },
232 };
233 properties.insert(key.clone(), prop);
234 }
235 if !*oa {
236 for (key, y) in pb.iter() {
237 if !pa.contains_key(key) {
238 properties.insert(
239 key.clone(),
240 KeyedProperty {
241 ty: y.ty.clone(),
242 optional: true,
243 },
244 );
245 }
246 }
247 }
248 Some(Atomic::TKeyedArray {
249 properties: Arc::new(properties),
250 is_open: *oa,
251 is_list: *la,
252 })
253}
254
255impl Type {
256 pub fn empty() -> Self {
259 Self {
260 types: SmallVec::new(),
261 possibly_undefined: false,
262 from_docblock: false,
263 falsy_stripped: false,
264 possibly_absent_offset: false,
265 }
266 }
267
268 pub fn single(atomic: Atomic) -> Self {
269 let mut types = SmallVec::new();
270 types.push(atomic);
271 Self {
272 types,
273 possibly_undefined: false,
274 from_docblock: false,
275 falsy_stripped: false,
276 possibly_absent_offset: false,
277 }
278 }
279
280 pub fn mixed() -> Self {
281 Self::single(Atomic::TMixed)
282 }
283
284 pub fn void() -> Self {
285 Self::single(Atomic::TVoid)
286 }
287
288 pub fn never() -> Self {
289 Self::single(Atomic::TNever)
290 }
291
292 pub fn null() -> Self {
293 Self::single(Atomic::TNull)
294 }
295
296 pub fn bool() -> Self {
297 Self::single(Atomic::TBool)
298 }
299
300 pub fn int() -> Self {
301 Self::single(Atomic::TInt)
302 }
303
304 pub fn float() -> Self {
305 Self::single(Atomic::TFloat)
306 }
307
308 pub fn string() -> Self {
309 Self::single(Atomic::TString)
310 }
311
312 pub fn array_key() -> Self {
315 let mut u = Self::single(Atomic::TInt);
316 u.add_type(Atomic::TString);
317 u
318 }
319
320 pub fn nullable(atomic: Atomic) -> Self {
322 if matches!(atomic, Atomic::TMixed) {
324 return Self::mixed();
325 }
326 let mut types = SmallVec::new();
327 types.push(atomic);
328 types.push(Atomic::TNull);
329 Self {
330 types,
331 possibly_undefined: false,
332 from_docblock: false,
333 falsy_stripped: false,
334 possibly_absent_offset: false,
335 }
336 }
337
338 pub fn from_vec(atomics: Vec<Atomic>) -> Self {
340 let mut u = Self::empty();
341 for a in atomics {
342 u.add_type(a);
343 }
344 u
345 }
346
347 pub fn is_empty(&self) -> bool {
350 self.types.is_empty()
351 }
352
353 pub fn is_single(&self) -> bool {
354 self.types.len() == 1
355 }
356
357 pub fn is_nullable(&self) -> bool {
358 self.types.iter().any(|t| matches!(t, Atomic::TNull))
359 }
360
361 pub fn is_array_key(&self) -> bool {
366 self.types.len() == 2
367 && self.types.iter().any(|t| matches!(t, Atomic::TInt))
368 && self.types.iter().any(|t| matches!(t, Atomic::TString))
369 }
370
371 pub fn is_mixed(&self) -> bool {
372 self.types.iter().any(|t| match t {
373 Atomic::TMixed => true,
374 Atomic::TTemplateParam { as_type, .. } => as_type.is_mixed(),
375 _ => false,
376 })
377 }
378
379 pub fn is_mixed_not_template(&self) -> bool {
384 self.is_mixed()
385 && !self
386 .types
387 .iter()
388 .any(|t| matches!(t, Atomic::TTemplateParam { .. }))
389 }
390
391 pub fn is_never(&self) -> bool {
392 self.types.iter().all(|t| matches!(t, Atomic::TNever)) && !self.types.is_empty()
393 }
394
395 pub fn clone_validity(&self) -> CloneValidity {
398 if self.types.is_empty() {
399 return CloneValidity::Unknown;
400 }
401 let mut has_non_object = false;
402 let mut has_other = false; for t in &self.types {
404 match t {
405 Atomic::TTemplateParam { as_type, .. } => match as_type.clone_validity() {
406 CloneValidity::Invalid => has_non_object = true,
407 CloneValidity::PossiblyInvalid => {
408 has_non_object = true;
409 has_other = true;
410 }
411 CloneValidity::Cloneable | CloneValidity::Unknown => has_other = true,
412 },
413 other if other.is_definitely_non_object() => has_non_object = true,
414 _ => has_other = true,
415 }
416 }
417 match (has_non_object, has_other) {
418 (true, false) => CloneValidity::Invalid,
419 (true, true) => CloneValidity::PossiblyInvalid,
420 _ => CloneValidity::Cloneable,
421 }
422 }
423
424 pub fn is_void(&self) -> bool {
425 self.is_single() && matches!(self.types[0], Atomic::TVoid)
426 }
427
428 pub fn can_be_falsy(&self) -> bool {
429 self.types.iter().any(|t| t.can_be_falsy())
430 }
431
432 pub fn can_be_truthy(&self) -> bool {
433 self.types.iter().any(|t| t.can_be_truthy())
434 }
435
436 pub fn contains<F: Fn(&Atomic) -> bool>(&self, f: F) -> bool {
437 self.types.iter().any(f)
438 }
439
440 pub fn has_named_object(&self, fqcn: &str) -> bool {
441 self.types.iter().any(|t| match t {
442 Atomic::TNamedObject { fqcn: f, .. } => f.as_ref() == fqcn,
443 _ => false,
444 })
445 }
446
447 pub fn add_type(&mut self, atomic: Atomic) {
452 if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
454 return;
455 }
456
457 if matches!(atomic, Atomic::TMixed) {
459 self.types.clear();
460 self.types.push(Atomic::TMixed);
461 return;
462 }
463
464 let atomic = if let Atomic::TConditional { data } = &atomic {
467 let (if_true, if_false) = (&data.if_true, &data.if_false);
468 let mut simplified_true = Type::empty();
469 for t in &if_true.types {
470 simplified_true.add_type(t.clone());
471 }
472 let mut simplified_false = Type::empty();
473 for t in &if_false.types {
474 simplified_false.add_type(t.clone());
475 }
476 if simplified_true == simplified_false {
477 for t in simplified_true.types {
478 self.add_type(t);
479 }
480 return;
481 }
482 atomic
483 } else {
484 atomic
485 };
486
487 if self.types.contains(&atomic) {
488 return;
489 }
490 self.add_absent_type(atomic);
491 }
492
493 fn add_absent_type(&mut self, atomic: Atomic) {
495 let mut atomic = atomic;
498 if matches!(atomic, Atomic::TKeyedArray { .. })
499 && self
500 .types
501 .iter()
502 .filter(|t| matches!(t, Atomic::TKeyedArray { .. }))
503 .count()
504 >= MAX_KEYED_SHAPES
505 {
506 if let Some((idx, combined)) = self
507 .types
508 .iter()
509 .enumerate()
510 .find_map(|(i, t)| combine_keyed_arrays(t, &atomic).map(|c| (i, c)))
511 {
512 self.types.remove(idx);
513 if self.types.contains(&combined) {
514 return;
515 }
516 atomic = combined;
517 }
518 }
519
520 if self.types.iter().any(|t| generic_array_covered(&atomic, t)) {
523 return;
524 }
525 self.types.retain(|t| !generic_array_covered(t, &atomic));
526
527 if matches!(
528 atomic,
529 Atomic::TArray { .. }
530 | Atomic::TNonEmptyArray { .. }
531 | Atomic::TList { .. }
532 | Atomic::TNonEmptyList { .. }
533 ) && self
534 .types
535 .iter()
536 .filter(|t| std::mem::discriminant(*t) == std::mem::discriminant(&atomic))
537 .count()
538 >= MAX_GENERIC_ARRAYS
539 {
540 if let Some((idx, combined)) = self
541 .types
542 .iter()
543 .enumerate()
544 .find_map(|(i, t)| combine_generic_arrays(t, &atomic).map(|c| (i, c)))
545 {
546 self.types.remove(idx);
547 if self.types.contains(&combined) {
548 return;
549 }
550 atomic = combined;
551 }
552 }
553
554 if let Some(new_bounds) = int_bounds(&atomic) {
557 if self
558 .types
559 .iter()
560 .any(|t| int_bounds(t).is_some_and(|b| bounds_contain(b, new_bounds)))
561 {
562 return;
563 }
564 self.types
565 .retain(|t| !int_bounds(t).is_some_and(|b| bounds_contain(new_bounds, b)));
566 }
567 match atomic {
569 Atomic::TClosedResource if self.types.contains(&Atomic::TResource) => return,
570 Atomic::TResource => self.types.retain(|t| *t != Atomic::TClosedResource),
571 _ => {}
572 }
573 const LITERAL_INT: Atomic = Atomic::TRefinedInt(IntRefinement::Literal);
575 match atomic {
576 Atomic::TRefinedInt(_) if self.types.contains(&Atomic::TInt) => return,
577 Atomic::TLiteralInt(_) if self.types.contains(&LITERAL_INT) => return,
578 LITERAL_INT => self.types.retain(|t| !matches!(t, Atomic::TLiteralInt(_))),
579 Atomic::TInt => self.types.retain(|t| !matches!(t, Atomic::TRefinedInt(_))),
580 _ => {}
581 }
582 if let Atomic::TLiteralString(_) = &atomic {
584 if self.types.iter().any(|t| matches!(t, Atomic::TString)) {
585 return;
586 }
587 let literals = self
588 .types
589 .iter()
590 .filter(|t| matches!(t, Atomic::TLiteralString(_)))
591 .count();
592 if literals >= MAX_LITERAL_STRINGS {
593 atomic = Atomic::TString;
594 }
595 }
596 if matches!(
598 atomic,
599 Atomic::TNonEmptyString | Atomic::TNonFalsyString | Atomic::TRefinedString { .. }
600 ) && self.types.iter().any(|t| matches!(t, Atomic::TString))
601 {
602 return;
603 }
604 if matches!(atomic, Atomic::TNonFalsyString)
606 && self
607 .types
608 .iter()
609 .any(|t| matches!(t, Atomic::TNonEmptyString))
610 {
611 return;
612 }
613 if matches!(atomic, Atomic::TNonEmptyString) {
614 self.types.retain(|t| !matches!(t, Atomic::TNonFalsyString));
615 }
616 if matches!(atomic, Atomic::TTrue | Atomic::TFalse)
618 && self.types.iter().any(|t| matches!(t, Atomic::TBool))
619 {
620 return;
621 }
622 if matches!(atomic, Atomic::TTrue) && self.types.iter().any(|t| matches!(t, Atomic::TFalse))
625 {
626 self.types.retain(|t| !matches!(t, Atomic::TFalse));
627 self.types.push(Atomic::TBool);
628 return;
629 }
630 if matches!(atomic, Atomic::TFalse) && self.types.iter().any(|t| matches!(t, Atomic::TTrue))
631 {
632 self.types.retain(|t| !matches!(t, Atomic::TTrue));
633 self.types.push(Atomic::TBool);
634 return;
635 }
636 if matches!(atomic, Atomic::TString) {
638 self.types.retain(|t| {
639 !matches!(
640 t,
641 Atomic::TLiteralString(_)
642 | Atomic::TNonEmptyString
643 | Atomic::TNonFalsyString
644 | Atomic::TRefinedString { .. }
645 )
646 });
647 }
648 if matches!(atomic, Atomic::TBool) {
650 self.types
651 .retain(|t| !matches!(t, Atomic::TTrue | Atomic::TFalse));
652 }
653
654 if matches!(atomic, Atomic::TNever) {
656 if !self.types.is_empty() {
657 return;
658 }
659 } else {
660 self.types.retain(|t| !matches!(t, Atomic::TNever));
661 }
662
663 if let Atomic::TKeyedArray {
669 properties,
670 is_open,
671 ..
672 } = &atomic
673 {
674 if properties.is_empty() && !is_open {
675 for existing in &self.types {
676 match existing {
677 Atomic::TArray { .. }
678 | Atomic::TNonEmptyArray { .. }
679 | Atomic::TList { .. }
680 | Atomic::TNonEmptyList { .. } => {
681 return; }
683 _ => {}
684 }
685 }
686 }
687 }
688
689 let is_generic_array_or_list = matches!(
692 &atomic,
693 Atomic::TArray { .. }
694 | Atomic::TNonEmptyArray { .. }
695 | Atomic::TList { .. }
696 | Atomic::TNonEmptyList { .. }
697 );
698 if is_generic_array_or_list {
699 self.types.retain(|t| {
700 if let Atomic::TKeyedArray {
701 properties,
702 is_open,
703 ..
704 } = t
705 {
706 !properties.is_empty() || *is_open
707 } else {
708 true
709 }
710 });
711 }
712
713 self.types.push(atomic);
714 }
715
716 pub fn remove_null(&self) -> Type {
720 self.filter(|t| !matches!(t, Atomic::TNull))
721 }
722
723 pub fn remove_false(&self) -> Type {
726 let mut result = self.filter(|t| !matches!(t, Atomic::TFalse | Atomic::TBool));
727 if self.types.iter().any(|t| matches!(t, Atomic::TBool)) {
728 result.add_type(Atomic::TTrue);
729 }
730 result
731 }
732
733 pub fn remove_true(&self) -> Type {
736 let mut result = self.filter(|t| !matches!(t, Atomic::TTrue | Atomic::TBool));
737 if self.types.iter().any(|t| matches!(t, Atomic::TBool)) {
738 result.add_type(Atomic::TFalse);
739 }
740 result
741 }
742
743 pub fn core_type(&self) -> Type {
745 self.remove_null().remove_false()
746 }
747
748 pub fn narrow_to_truthy(&self) -> Type {
750 if self.is_mixed_not_template() {
751 return Type::mixed();
752 }
753 let mut result = Type::empty();
754 result.from_docblock = self.from_docblock;
755 for t in &self.types {
756 match t {
757 Atomic::TTemplateParam { .. } => result.add_type(t.clone()),
761 Atomic::TLiteralInt(0)
763 | Atomic::TLiteralFloat(0, 0)
764 | Atomic::TNull
765 | Atomic::TFalse => {}
766 Atomic::TLiteralString(s) if s.as_ref() == "" || s.as_ref() == "0" => {}
767 Atomic::TBool => result.add_type(Atomic::TTrue),
769 Atomic::TArray { key, value } => result.add_type(Atomic::TNonEmptyArray {
771 key: key.clone(),
772 value: value.clone(),
773 }),
774 Atomic::TList { value } => result.add_type(Atomic::TNonEmptyList {
775 value: value.clone(),
776 }),
777 Atomic::TString | Atomic::TNonEmptyString => {
779 result.add_type(Atomic::TNonFalsyString)
780 }
781 Atomic::TNonNegativeInt => result.add_type(Atomic::TPositiveInt),
786 Atomic::TIntRange { min: Some(0), max } if max.is_none_or(|m| m >= 1) => {
787 let atom = if max.is_none() {
788 Atomic::TPositiveInt
789 } else {
790 Atomic::TIntRange {
791 min: Some(1),
792 max: *max,
793 }
794 };
795 result.add_type(atom);
796 }
797 Atomic::TIntRange { min, max: Some(0) } => {
799 let atom = match min {
800 None => Atomic::TNegativeInt,
801 Some(n) if *n <= -1 => Atomic::TIntRange {
802 min: *min,
803 max: Some(-1),
804 },
805 _ => continue, };
807 result.add_type(atom);
808 }
809 t if !t.can_be_truthy() => {}
811 _ => result.add_type(t.clone()),
812 }
813 }
814 result
815 }
816
817 pub fn narrow_to_falsy(&self) -> Type {
819 if self.is_mixed_not_template() {
820 return Type::from_vec(vec![
821 Atomic::TNull,
822 Atomic::TFalse,
823 Atomic::TLiteralInt(0),
824 Atomic::TLiteralString("".into()),
825 Atomic::TLiteralString("0".into()),
826 ]);
827 }
828 let mut result = Type::empty();
829 result.from_docblock = self.from_docblock;
830 for t in &self.types {
831 match t {
832 Atomic::TTemplateParam { .. } => result.add_type(t.clone()),
837 Atomic::TBool => result.add_type(Atomic::TFalse),
839 Atomic::TInt => result.add_type(Atomic::TLiteralInt(0)),
841 Atomic::TFloat => result.add_type(Atomic::TLiteralFloat(0, 0)),
843 Atomic::TString => {
845 result.add_type(Atomic::TLiteralString("".into()));
846 result.add_type(Atomic::TLiteralString("0".into()));
847 }
848 Atomic::TNumericString => result.add_type(Atomic::TLiteralString("0".into())),
850 Atomic::TNonNegativeInt => result.add_type(Atomic::TLiteralInt(0)),
852 Atomic::TIntRange {
854 min: Some(0),
855 max: Some(_) | None,
856 } => result.add_type(Atomic::TLiteralInt(0)),
857 Atomic::TIntRange { max: Some(0), .. } => result.add_type(Atomic::TLiteralInt(0)),
859 t if !t.can_be_falsy() => {} _ => result.add_type(t.clone()),
861 }
862 }
863 result
864 }
865
866 pub fn narrow_instanceof(&self, class: &str) -> Type {
872 let narrowed_ty = Atomic::TNamedObject {
873 fqcn: class.into(),
874 type_params: empty_type_params(),
875 };
876 let has_object = self.types.iter().any(|t| {
878 matches!(
879 t,
880 Atomic::TObject
881 | Atomic::TObjectShape { .. }
882 | Atomic::TNamedObject { .. }
883 | Atomic::TMixed
884 | Atomic::TNull )
886 });
887 if has_object || self.is_empty() {
888 Type::single(narrowed_ty)
889 } else {
890 Type::single(narrowed_ty)
893 }
894 }
895
896 pub fn narrow_to_string(&self) -> Type {
900 self.filter_replacing(
901 |t| t.is_string() || t.is_deferred(),
902 |t| matches!(t, Atomic::TMixed | Atomic::TScalar),
903 Atomic::TString,
904 )
905 .with_callable_form(self, Atomic::TCallableString)
906 }
907
908 pub fn narrow_to_int(&self) -> Type {
910 self.filter_replacing(
911 |t| t.is_int() || t.is_deferred(),
912 |t| matches!(t, Atomic::TMixed | Atomic::TScalar | Atomic::TNumeric),
913 Atomic::TInt,
914 )
915 }
916
917 pub fn narrow_to_float(&self) -> Type {
919 self.filter_replacing(
920 |t| {
921 matches!(
922 t,
923 Atomic::TFloat | Atomic::TIntegralFloat | Atomic::TLiteralFloat(..)
924 ) || matches!(t, Atomic::TTemplateParam { .. } | Atomic::TValueOf { .. })
925 },
926 |t| matches!(t, Atomic::TMixed | Atomic::TScalar | Atomic::TNumeric),
927 Atomic::TFloat,
928 )
929 }
930
931 pub fn narrow_to_bool(&self) -> Type {
933 self.filter_replacing(
934 |t| {
935 matches!(
936 t,
937 Atomic::TBool
938 | Atomic::TTrue
939 | Atomic::TFalse
940 | Atomic::TTemplateParam { .. }
941 | Atomic::TValueOf { .. }
942 )
943 },
944 |t| matches!(t, Atomic::TMixed | Atomic::TScalar),
945 Atomic::TBool,
946 )
947 }
948
949 pub fn narrow_to_null(&self) -> Type {
951 self.filter_replacing(
952 |t| matches!(t, Atomic::TNull | Atomic::TTemplateParam { .. }),
953 |t| matches!(t, Atomic::TMixed),
954 Atomic::TNull,
955 )
956 }
957
958 pub fn narrow_to_array(&self) -> Type {
960 self.filter_replacing(
961 |t| t.is_array() || matches!(t, Atomic::TTemplateParam { .. }),
962 |t| matches!(t, Atomic::TMixed),
963 Atomic::TArray {
964 key: Box::new(Type::mixed()),
965 value: Box::new(Type::mixed()),
966 },
967 )
968 .with_callable_form(self, callable_array())
969 }
970
971 pub fn widen_nested_non_empty(&self) -> Type {
974 fn relax_all(ty: &Type) -> Type {
975 map_atoms(ty, |a| match a {
976 Atomic::TNonEmptyList { value } => Atomic::TList {
977 value: Box::new(relax_all(value)),
978 },
979 Atomic::TNonEmptyArray { key, value } => Atomic::TArray {
980 key: key.clone(),
981 value: Box::new(relax_all(value)),
982 },
983 other => map_values(other, relax_all),
984 })
985 }
986 fn map_values(atomic: &Atomic, f: fn(&Type) -> Type) -> Atomic {
987 match atomic {
988 Atomic::TArray { key, value } => Atomic::TArray {
989 key: key.clone(),
990 value: Box::new(f(value)),
991 },
992 Atomic::TList { value } => Atomic::TList {
993 value: Box::new(f(value)),
994 },
995 Atomic::TNonEmptyArray { key, value } => Atomic::TNonEmptyArray {
996 key: key.clone(),
997 value: Box::new(f(value)),
998 },
999 Atomic::TNonEmptyList { value } => Atomic::TNonEmptyList {
1000 value: Box::new(f(value)),
1001 },
1002 Atomic::TKeyedArray {
1003 properties,
1004 is_open,
1005 is_list,
1006 } => Atomic::TKeyedArray {
1007 properties: Arc::new(
1008 properties
1009 .iter()
1010 .map(|(k, p)| {
1011 (
1012 k.clone(),
1013 crate::atomic::KeyedProperty {
1014 ty: f(&p.ty),
1015 optional: p.optional,
1016 },
1017 )
1018 })
1019 .collect(),
1020 ),
1021 is_open: *is_open,
1022 is_list: *is_list,
1023 },
1024 other => other.clone(),
1025 }
1026 }
1027 fn map_atoms(ty: &Type, f: impl Fn(&Atomic) -> Atomic) -> Type {
1028 let mut result = Type::empty();
1029 result.possibly_undefined = ty.possibly_undefined;
1030 result.from_docblock = ty.from_docblock;
1031 for atomic in &ty.types {
1032 result.add_type(f(atomic));
1033 }
1034 result
1035 }
1036 map_atoms(self, |a| map_values(a, relax_all))
1037 }
1038
1039 pub fn narrow_to_non_empty_collection(&self) -> Type {
1042 let mut out = Type::empty();
1043 out.from_docblock = self.from_docblock;
1044 for t in &self.types {
1045 match t {
1046 Atomic::TArray { key, value } => out.add_type(Atomic::TNonEmptyArray {
1047 key: key.clone(),
1048 value: value.clone(),
1049 }),
1050 Atomic::TList { value } => out.add_type(Atomic::TNonEmptyList {
1051 value: value.clone(),
1052 }),
1053 Atomic::TKeyedArray {
1054 properties,
1055 is_open: false,
1056 ..
1057 } if properties.is_empty() => {}
1058 _ => out.add_type(t.clone()),
1059 }
1060 }
1061 out
1062 }
1063
1064 pub fn narrow_to_empty_collection(&self) -> Type {
1074 let mut out = Type::empty();
1075 out.from_docblock = self.from_docblock;
1076 for t in &self.types {
1077 match t {
1078 Atomic::TNonEmptyArray { .. } | Atomic::TNonEmptyList { .. } => {}
1079 Atomic::TArray { .. } | Atomic::TList { .. } => {
1080 out.add_type(Atomic::TKeyedArray {
1081 properties: Arc::default(),
1082 is_open: false,
1083 is_list: true,
1084 });
1085 }
1086 _ => out.add_type(t.clone()),
1087 }
1088 }
1089 out
1090 }
1091
1092 pub fn narrow_to_list(&self) -> Type {
1104 let mut out = Type::empty();
1105 out.from_docblock = self.from_docblock;
1106 for t in &self.types {
1107 match t {
1108 Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => out.add_type(t.clone()),
1109 Atomic::TArray { key, value } if !key.narrow_to_int().is_empty() => {
1115 out.add_type(Atomic::TList {
1116 value: value.clone(),
1117 });
1118 }
1119 Atomic::TNonEmptyArray { key, value } if !key.narrow_to_int().is_empty() => {
1120 out.add_type(Atomic::TNonEmptyList {
1121 value: value.clone(),
1122 });
1123 }
1124 Atomic::TKeyedArray { is_list: true, .. } => out.add_type(t.clone()),
1125 Atomic::TMixed => out.add_type(Atomic::TList {
1126 value: Box::new(Type::mixed()),
1127 }),
1128 _ => {}
1129 }
1130 }
1131 if out.is_empty() {
1132 self.filter(|t| matches!(t, Atomic::TList { .. } | Atomic::TNonEmptyList { .. }))
1133 } else {
1134 out
1135 }
1136 }
1137
1138 pub fn narrow_to_object(&self) -> Type {
1143 let mut out = Type::empty();
1144 for t in &self.types {
1145 if matches!(t, Atomic::TMixed) {
1146 out.add_type(Atomic::TObject);
1147 } else if t.is_object() || matches!(t, Atomic::TTemplateParam { .. }) {
1148 out.add_type(t.clone());
1149 }
1150 }
1151 if out.types.is_empty() {
1152 self.filter(|t| t.is_object())
1153 .with_callable_form(self, Atomic::TObject)
1154 } else {
1155 out.with_callable_form(self, Atomic::TObject)
1156 }
1157 }
1158
1159 fn with_callable_form(mut self, source: &Type, form: Atomic) -> Type {
1162 if source
1163 .types
1164 .iter()
1165 .any(|t| matches!(t, Atomic::TCallable { .. }))
1166 {
1167 self.add_type(form);
1168 }
1169 self
1170 }
1171
1172 pub fn narrow_to_not_callable(&self) -> Type {
1175 let callable_array = callable_array();
1176 self.filter(|t| {
1177 !t.is_callable()
1178 && *t != callable_array
1179 && !matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.eq_ignore_ascii_case("Closure"))
1180 })
1181 }
1182
1183 pub fn narrow_to_callable(&self) -> Type {
1190 let narrowed = self.filter(|t| {
1191 t.is_callable()
1192 || t.is_string()
1193 || t.is_array()
1194 || t.is_object()
1195 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1196 });
1197 let mut result = Type::empty();
1204 result.possibly_undefined = narrowed.possibly_undefined;
1205 result.from_docblock = narrowed.from_docblock;
1206 for atomic in narrowed.types {
1207 if matches!(atomic, Atomic::TObject | Atomic::TObjectShape { .. }) {
1208 result.add_type(Atomic::TCallable {
1209 params: None,
1210 return_type: None,
1211 is_pure: false,
1212 });
1213 } else {
1214 result.add_type(atomic);
1215 }
1216 }
1217 result
1218 }
1219
1220 pub fn narrow_to_scalar(&self) -> Type {
1222 self.filter_replacing(
1223 |t| {
1224 t.is_string()
1225 || t.is_int()
1226 || matches!(
1227 t,
1228 Atomic::TFloat
1229 | Atomic::TIntegralFloat
1230 | Atomic::TLiteralFloat(..)
1231 | Atomic::TBool
1232 | Atomic::TTrue
1233 | Atomic::TFalse
1234 | Atomic::TScalar
1235 | Atomic::TNumeric
1236 | Atomic::TNumericString
1237 | Atomic::TTemplateParam { .. }
1238 )
1239 },
1240 |t| matches!(t, Atomic::TMixed),
1241 Atomic::TScalar,
1242 )
1243 }
1244
1245 pub fn narrow_to_iterable(&self) -> Type {
1248 self.filter(|t| {
1249 t.is_array()
1250 || t.is_object()
1251 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1252 })
1253 }
1254
1255 pub fn narrow_to_countable(&self) -> Type {
1258 self.filter(|t| {
1259 t.is_array()
1260 || t.is_object()
1261 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1262 })
1263 }
1264
1265 pub fn narrow_to_resource(&self) -> Type {
1267 let mut out = self.filter(|t| match t {
1268 Atomic::TResource | Atomic::TMixed => true,
1269 Atomic::TTemplateParam { as_type, .. } => as_type.is_mixed(),
1270 _ => false,
1271 });
1272 for t in out.types.iter_mut() {
1273 if matches!(t, Atomic::TMixed) {
1274 *t = Atomic::TResource;
1275 }
1276 }
1277 out
1278 }
1279
1280 pub fn narrow_to_class_string(&self) -> Type {
1285 let mut out = Type::empty();
1286 out.from_docblock = self.from_docblock;
1287 for t in &self.types {
1288 match t {
1289 Atomic::TClassString(_) => out.add_type(t.clone()),
1290 _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
1291 out.add_type(Atomic::TClassString(None));
1292 }
1293 _ => {}
1294 }
1295 }
1296 out
1297 }
1298
1299 pub fn narrow_to_interface_string(&self) -> Type {
1304 let mut out = Type::empty();
1305 out.from_docblock = self.from_docblock;
1306 for t in &self.types {
1307 match t {
1308 Atomic::TInterfaceString(_) => out.add_type(t.clone()),
1309 Atomic::TClassString(name) => {
1313 out.add_type(Atomic::TInterfaceString(*name));
1314 }
1315 _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
1316 out.add_type(Atomic::TInterfaceString(None));
1317 }
1318 _ => {}
1319 }
1320 }
1321 out
1322 }
1323
1324 pub fn merge(a: &Type, b: &Type) -> Type {
1329 if b.types.is_empty() {
1331 let mut result = a.clone();
1332 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1333 return result;
1334 }
1335 if a.types.is_empty() {
1337 let mut result = b.clone();
1338 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1339 return result;
1340 }
1341 if a.types.len() == 1 && matches!(a.types[0], Atomic::TMixed) {
1343 let mut result = a.clone();
1344 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1345 return result;
1346 }
1347 if b.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1349 return Type {
1350 types: smallvec::smallvec![Atomic::TMixed],
1351 possibly_undefined: a.possibly_undefined || b.possibly_undefined,
1352 from_docblock: a.from_docblock || b.from_docblock,
1353 falsy_stripped: false,
1354 possibly_absent_offset: false,
1355 };
1356 }
1357 let mut result = a.clone();
1358 result.merge_with(b);
1359 result
1360 }
1361
1362 pub fn merge_with(&mut self, other: &Type) {
1364 if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1365 self.possibly_undefined |= other.possibly_undefined;
1366 return;
1367 }
1368 if other.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1369 self.types.clear();
1370 self.types.push(Atomic::TMixed);
1371 self.possibly_undefined |= other.possibly_undefined;
1372 return;
1373 }
1374 for atomic in &other.types {
1375 if matches!(atomic, Atomic::TConditional { .. }) {
1377 self.add_type(atomic.clone());
1378 } else if !self.types.contains(atomic)
1379 && !self.types.iter().any(|t| matches!(t, Atomic::TMixed))
1380 {
1381 self.add_absent_type(atomic.clone());
1382 }
1383 }
1384 self.possibly_undefined |= other.possibly_undefined;
1385 }
1386
1387 pub fn intersect_with(&self, other: &Type) -> Type {
1391 if self.is_mixed() {
1392 return other.clone();
1393 }
1394 if other.is_mixed() {
1395 return self.clone();
1396 }
1397 let mut result = Type::empty();
1405 for a in &self.types {
1406 for b in &other.types {
1407 if a == b {
1408 result.add_type(a.clone());
1409 } else if atomic_subtype(b, a) {
1410 result.add_type(b.clone());
1411 } else if atomic_subtype(a, b) {
1412 result.add_type(a.clone());
1413 }
1414 }
1415 }
1416 if result.is_empty() {
1417 Type::never()
1418 } else {
1419 result
1420 }
1421 }
1422
1423 pub fn substitute_templates(&self, bindings: &FxHashMap<Name, Type>) -> Type {
1427 if bindings.is_empty() {
1428 return self.clone();
1429 }
1430 if !self.types.iter().any(atomic_may_contain_templates) {
1433 return self.clone();
1434 }
1435 let mut result = Type::empty();
1436 result.possibly_undefined = self.possibly_undefined;
1437 result.from_docblock = self.from_docblock;
1438 for atomic in &self.types {
1439 match atomic {
1440 Atomic::TTemplateParam { name, .. } => {
1441 if let Some(resolved) = bindings.get(name) {
1442 for t in &resolved.types {
1443 result.add_type(t.clone());
1444 }
1445 } else {
1446 result.add_type(atomic.clone());
1447 }
1448 }
1449 Atomic::TArray { key, value } => {
1450 result.add_type(Atomic::TArray {
1451 key: Box::new(key.substitute_templates(bindings)),
1452 value: Box::new(value.substitute_templates(bindings)),
1453 });
1454 }
1455 Atomic::TList { value } => {
1456 result.add_type(Atomic::TList {
1457 value: Box::new(value.substitute_templates(bindings)),
1458 });
1459 }
1460 Atomic::TNonEmptyArray { key, value } => {
1461 result.add_type(Atomic::TNonEmptyArray {
1462 key: Box::new(key.substitute_templates(bindings)),
1463 value: Box::new(value.substitute_templates(bindings)),
1464 });
1465 }
1466 Atomic::TNonEmptyList { value } => {
1467 result.add_type(Atomic::TNonEmptyList {
1468 value: Box::new(value.substitute_templates(bindings)),
1469 });
1470 }
1471 Atomic::TKeyedArray {
1472 properties,
1473 is_open,
1474 is_list,
1475 } => {
1476 use crate::atomic::KeyedProperty;
1477 let new_props = properties
1478 .iter()
1479 .map(|(k, prop)| {
1480 (
1481 k.clone(),
1482 KeyedProperty {
1483 ty: prop.ty.substitute_templates(bindings),
1484 optional: prop.optional,
1485 },
1486 )
1487 })
1488 .collect();
1489 result.add_type(Atomic::TKeyedArray {
1490 properties: Arc::new(new_props),
1491 is_open: *is_open,
1492 is_list: *is_list,
1493 });
1494 }
1495 Atomic::TCallable {
1496 params,
1497 return_type,
1498 is_pure,
1499 } => {
1500 result.add_type(Atomic::TCallable {
1501 params: params.as_ref().map(|ps| {
1502 Box::new(
1503 ps.iter()
1504 .map(|p| substitute_in_fn_param(p, bindings))
1505 .collect(),
1506 )
1507 }),
1508 return_type: return_type
1509 .as_ref()
1510 .map(|r| Box::new(r.substitute_templates(bindings))),
1511 is_pure: *is_pure,
1512 });
1513 }
1514 Atomic::TClosure { data } => {
1515 result.add_type(Atomic::TClosure {
1516 data: Box::new(crate::atomic::ClosureData {
1517 params: data
1518 .params
1519 .iter()
1520 .map(|p| substitute_in_fn_param(p, bindings))
1521 .collect(),
1522 return_type: data.return_type.substitute_templates(bindings),
1523 this_type: data
1524 .this_type
1525 .as_ref()
1526 .map(|t| t.substitute_templates(bindings)),
1527 is_pure: data.is_pure,
1528 is_static: data.is_static,
1529 rejects_surplus_args: data.rejects_surplus_args,
1530 is_impure: data.is_impure,
1531 }),
1532 });
1533 }
1534 Atomic::TConditional { data } => {
1535 let param_name = &data.param_name;
1536 let new_subject = data.subject.substitute_templates(bindings);
1537 let new_if_true = data.if_true.substitute_templates(bindings);
1538 let new_if_false = data.if_false.substitute_templates(bindings);
1539
1540 let resolved = if let Some(name) = param_name {
1544 if let Some(bound) = bindings.get(name) {
1545 resolve_conditional_branch(
1546 &new_subject,
1547 bound,
1548 &new_if_true,
1549 &new_if_false,
1550 )
1551 } else {
1552 None
1553 }
1554 } else {
1555 None
1556 };
1557
1558 if let Some(branch) = resolved {
1559 for t in branch.types {
1560 result.add_type(t);
1561 }
1562 } else {
1563 result.add_type(Atomic::TConditional {
1564 data: Box::new(crate::atomic::ConditionalData {
1565 param_name: *param_name,
1566 subject: new_subject,
1567 if_true: new_if_true,
1568 if_false: new_if_false,
1569 }),
1570 });
1571 }
1572 }
1573 Atomic::TKeyOf { target } => {
1574 let new_target = target.substitute_templates(bindings);
1575 if let Some(resolved) = eval_key_of_type(&new_target) {
1576 result.merge_with(&resolved);
1577 } else {
1578 result.add_type(Atomic::TKeyOf {
1579 target: Box::new(new_target),
1580 });
1581 }
1582 }
1583 Atomic::TValueOf { target } => {
1584 let new_target = target.substitute_templates(bindings);
1585 if let Some(resolved) = eval_value_of_type(&new_target) {
1586 result.merge_with(&resolved);
1587 } else {
1588 result.add_type(Atomic::TValueOf {
1589 target: Box::new(new_target),
1590 });
1591 }
1592 }
1593 Atomic::TIntersection { parts } => {
1594 result.add_type(Atomic::TIntersection {
1595 parts: vec_to_type_params(
1596 parts
1597 .iter()
1598 .map(|p| p.substitute_templates(bindings))
1599 .collect(),
1600 ),
1601 });
1602 }
1603 Atomic::TNamedObject { fqcn, type_params } => {
1604 if type_params.is_empty() && !fqcn.contains('\\') {
1606 if let Some(resolved) = bindings.get(fqcn) {
1607 for t in &resolved.types {
1608 result.add_type(t.clone());
1609 }
1610 continue;
1611 }
1612 }
1613 let new_params: Vec<Type> = type_params
1614 .iter()
1615 .map(|p| p.substitute_templates(bindings))
1616 .collect();
1617 result.add_type(Atomic::TNamedObject {
1618 fqcn: *fqcn,
1619 type_params: vec_to_type_params(new_params),
1620 });
1621 }
1622 Atomic::TClassString(Some(param_name)) => {
1624 if let Some(resolved) = bindings.get(param_name) {
1625 for r_atomic in &resolved.types {
1626 let cls_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1627 Some(*fqcn)
1628 } else {
1629 None
1630 };
1631 result.add_type(Atomic::TClassString(cls_name));
1632 }
1633 } else {
1634 result.add_type(atomic.clone());
1635 }
1636 }
1637 Atomic::TInterfaceString(Some(param_name)) => {
1639 if let Some(resolved) = bindings.get(param_name) {
1640 for r_atomic in &resolved.types {
1641 let iface_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1642 Some(*fqcn)
1643 } else {
1644 None
1645 };
1646 result.add_type(Atomic::TInterfaceString(iface_name));
1647 }
1648 } else {
1649 result.add_type(atomic.clone());
1650 }
1651 }
1652 _ => {
1653 result.add_type(atomic.clone());
1654 }
1655 }
1656 }
1657 result
1658 }
1659
1660 pub fn resolve_conditional_returns<F>(self, lookup: F) -> Type
1666 where
1667 F: Fn(&str) -> Option<Type>,
1668 {
1669 self.resolve_conditional_inner(&lookup)
1670 }
1671
1672 fn resolve_conditional_inner<F>(self, lookup: &F) -> Type
1673 where
1674 F: Fn(&str) -> Option<Type>,
1675 {
1676 let mut result = Type::empty();
1677 for atomic in self.types {
1678 match atomic {
1679 Atomic::TConditional { ref data } => {
1680 let (param_name, subject, if_true, if_false) = (
1681 &data.param_name,
1682 &data.subject,
1683 &data.if_true,
1684 &data.if_false,
1685 );
1686 let resolved =
1687 param_name
1688 .and_then(|name| lookup(name.as_ref()))
1689 .and_then(|arg_ty| {
1690 resolve_conditional_branch(subject, &arg_ty, if_true, if_false)
1691 });
1692
1693 if let Some(branch) = resolved {
1694 for t in branch.resolve_conditional_inner(lookup).types {
1696 result.add_type(t);
1697 }
1698 } else {
1699 for t in if_true.clone().resolve_conditional_inner(lookup).types {
1702 result.add_type(t);
1703 }
1704 for t in if_false.clone().resolve_conditional_inner(lookup).types {
1705 result.add_type(t);
1706 }
1707 }
1708 }
1709 other => result.add_type(other),
1710 }
1711 }
1712 result
1713 }
1714
1715 pub fn is_subtype_structural(&self, other: &Type) -> bool {
1725 if other.is_mixed() {
1726 return true;
1727 }
1728 if self.is_never() {
1729 return true; }
1731 self.types.iter().all(|a| {
1732 let fits = |a: &Atomic| other.types.iter().any(|b| atomic_subtype(a, b));
1733 fits(a) || composite_parts(a).is_some_and(|parts| parts.iter().all(fits))
1734 })
1735 }
1736
1737 pub fn is_subtype_by_template_bounds(&self, other: &Type) -> bool {
1740 self.is_subtype_structural(other)
1741 || self.types.iter().all(|a| match a {
1742 Atomic::TTemplateParam { as_type, .. } => {
1743 as_type.is_subtype_by_template_bounds(other)
1744 }
1745 _ => other.accepts_atomic_structural(a),
1746 })
1747 }
1748
1749 pub fn accepts_atomic_structural(&self, sub: &Atomic) -> bool {
1753 if self.is_mixed() {
1754 return true;
1755 }
1756 matches!(sub, Atomic::TNever) || self.types.iter().any(|b| atomic_subtype(sub, b))
1757 }
1758
1759 fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Type {
1762 let mut result = Type::empty();
1763 result.possibly_undefined = self.possibly_undefined;
1764 result.from_docblock = self.from_docblock;
1765 for atomic in &self.types {
1766 if f(atomic) {
1767 result.types.push(atomic.clone());
1768 }
1769 }
1770 result
1771 }
1772
1773 fn filter_replacing<K: Fn(&Atomic) -> bool, P: Fn(&Atomic) -> bool>(
1778 &self,
1779 keep: K,
1780 placeholder: P,
1781 replacement: Atomic,
1782 ) -> Type {
1783 let mut result = Type::empty();
1784 result.possibly_undefined = self.possibly_undefined;
1785 result.from_docblock = self.from_docblock;
1786 for atomic in &self.types {
1787 if keep(atomic) {
1788 result.add_type(atomic.clone());
1789 } else if placeholder(atomic) {
1790 result.add_type(replacement.clone());
1791 }
1792 }
1793 result
1794 }
1795
1796 pub fn possibly_undefined(mut self) -> Self {
1798 self.possibly_undefined = true;
1799 self
1800 }
1801
1802 pub fn from_docblock(mut self) -> Self {
1804 self.from_docblock = true;
1805 self
1806 }
1807
1808 pub fn falsy_stripped(mut self) -> Self {
1811 self.falsy_stripped = true;
1812 self
1813 }
1814
1815 pub fn possibly_absent_offset(mut self) -> Self {
1819 self.possibly_absent_offset = true;
1820 self
1821 }
1822}
1823
1824#[derive(Clone, PartialEq, Eq, Debug)]
1838enum ValueClass {
1839 Int,
1840 Float,
1841 True,
1842 False,
1843 String,
1844 Array,
1845 List,
1847 Object,
1848 Resource,
1849 Null,
1850 Top,
1853 LitInt(i64),
1856 LitFloat(i64, i64),
1858 LitString(Arc<str>),
1860 ClassString,
1862}
1863
1864impl ValueClass {
1865 fn includes(&self, b: &Self) -> bool {
1870 self == b
1871 || matches!(
1872 (self, b),
1873 (Self::Top, _)
1874 | (Self::Int, Self::LitInt(_))
1875 | (Self::Float, Self::LitFloat(..))
1876 | (Self::String, Self::LitString(_))
1877 | (Self::String, Self::ClassString)
1878 | (Self::Array, Self::List)
1879 )
1880 }
1881
1882 fn overlaps(&self, b: &Self) -> bool {
1884 self.includes(b)
1885 || b.includes(self)
1886 || matches!(
1887 (self, b),
1888 (Self::ClassString, Self::LitString(_)) | (Self::LitString(_), Self::ClassString)
1889 )
1890 }
1891}
1892
1893fn value_classes(a: &Atomic) -> Vec<ValueClass> {
1899 use ValueClass::*;
1900 match a {
1901 Atomic::TInt
1904 | Atomic::TIntRange { .. }
1905 | Atomic::TPositiveInt
1906 | Atomic::TNegativeInt
1907 | Atomic::TNonNegativeInt
1908 | Atomic::TRefinedInt(_) => vec![Int],
1909 Atomic::TLiteralInt(v) => vec![LitInt(*v)],
1910 Atomic::TFloat | Atomic::TIntegralFloat => vec![Float],
1912 Atomic::TLiteralFloat(int_bits, frac_bits) => {
1913 vec![LitFloat(*int_bits, *frac_bits)]
1914 }
1915 Atomic::TBool => vec![True, False],
1917 Atomic::TTrue => vec![True],
1918 Atomic::TFalse => vec![False],
1919 Atomic::TString
1921 | Atomic::TNonEmptyString
1922 | Atomic::TNonFalsyString
1923 | Atomic::TRefinedString { .. }
1924 | Atomic::TNumericString
1925 | Atomic::TCallableString => vec![String],
1926 Atomic::TClassString(_)
1927 | Atomic::TInterfaceString(_)
1928 | Atomic::TEnumString
1929 | Atomic::TTraitString => vec![ClassString],
1930 Atomic::TLiteralString(s) => vec![LitString(s.clone())],
1931 Atomic::TArray { .. }
1933 | Atomic::TPropertiesOf { .. }
1934 | Atomic::TNonEmptyArray { .. }
1935 | Atomic::TKeyedArray { is_list: false, .. } => vec![Array],
1936 Atomic::TList { .. }
1937 | Atomic::TNonEmptyList { .. }
1938 | Atomic::TKeyedArray { is_list: true, .. } => vec![List],
1939 Atomic::TObject
1941 | Atomic::TObjectShape { .. }
1942 | Atomic::TNamedObject { .. }
1943 | Atomic::TStaticObject { .. }
1944 | Atomic::TSelf { .. }
1945 | Atomic::TParent { .. }
1946 | Atomic::TClosure { .. }
1947 | Atomic::TLiteralEnumCase { .. } => vec![Object],
1948 Atomic::TNull => vec![Null],
1951 Atomic::TResource | Atomic::TClosedResource => vec![Resource],
1952 Atomic::TVoid => vec![Top],
1953 Atomic::TMixed => vec![Top],
1955 Atomic::TScalar => vec![Int, Float, True, False, String],
1956 Atomic::TNumeric => vec![Int, Float],
1959 Atomic::TCallable { .. }
1961 | Atomic::TNever
1962 | Atomic::TTemplateParam { .. }
1963 | Atomic::TKeyOf { .. }
1964 | Atomic::TValueOf { .. }
1965 | Atomic::TConditional { .. }
1966 | Atomic::TIntersection { .. } => Vec::new(),
1967 }
1968}
1969
1970fn subject_is_decidable(subject: &Atomic) -> bool {
1978 matches!(
1979 subject,
1980 Atomic::TNull
1981 | Atomic::TTrue
1982 | Atomic::TFalse
1983 | Atomic::TBool
1984 | Atomic::TString
1985 | Atomic::TClassString(None)
1986 | Atomic::TInt
1987 | Atomic::TFloat
1988 | Atomic::TLiteralString(_)
1989 | Atomic::TLiteralInt(_)
1990 | Atomic::TLiteralFloat(..)
1991 | Atomic::TArray { .. }
1992 | Atomic::TList { .. }
1993 | Atomic::TObject
1994 | Atomic::TObjectShape { .. }
1995 | Atomic::TResource
1996 | Atomic::TMixed
1997 | Atomic::TScalar
1998 )
1999}
2000
2001fn resolve_conditional_branch(
2023 subject: &Type,
2024 arg_ty: &Type,
2025 if_true: &Type,
2026 if_false: &Type,
2027) -> Option<Type> {
2028 if arg_ty.types.is_empty() {
2029 return None;
2030 }
2031 if let [Atomic::TVoid] = subject.types.as_slice() {
2033 return match arg_ty.types.as_slice() {
2034 [Atomic::TVoid] => Some(if_true.clone()),
2035 types
2036 if types.iter().all(|a| {
2037 !matches!(a, Atomic::TVoid | Atomic::TMixed | Atomic::TNull)
2038 && !value_classes(a).is_empty()
2039 }) =>
2040 {
2041 Some(if_false.clone())
2042 }
2043 _ => None,
2044 };
2045 }
2046 if subject.types.is_empty() || !subject.types.iter().all(subject_is_decidable) {
2047 return None;
2048 }
2049 let subject_classes: Vec<ValueClass> = subject.types.iter().flat_map(value_classes).collect();
2050 let arg_classes: Vec<ValueClass> = arg_ty.types.iter().flat_map(value_classes).collect();
2051 if arg_classes.is_empty() {
2052 return None;
2054 }
2055 let all_match = arg_classes
2056 .iter()
2057 .all(|c| subject_classes.iter().any(|s| s.includes(c)));
2058 let any_overlap = arg_classes
2059 .iter()
2060 .any(|c| subject_classes.iter().any(|s| s.overlaps(c)));
2061 if all_match {
2062 Some(if_true.clone())
2063 } else if !any_overlap {
2064 Some(if_false.clone())
2065 } else {
2066 None
2067 }
2068}
2069
2070fn atomic_may_contain_templates(atomic: &Atomic) -> bool {
2078 match atomic {
2079 Atomic::TNamedObject { fqcn, type_params } => {
2083 !type_params.is_empty() || !fqcn.contains('\\')
2084 }
2085 Atomic::TTemplateParam { .. }
2086 | Atomic::TKeyOf { .. }
2087 | Atomic::TValueOf { .. }
2088 | Atomic::TArray { .. }
2089 | Atomic::TList { .. }
2090 | Atomic::TNonEmptyArray { .. }
2091 | Atomic::TNonEmptyList { .. }
2092 | Atomic::TKeyedArray { .. }
2093 | Atomic::TCallable { .. }
2094 | Atomic::TClosure { .. }
2095 | Atomic::TConditional { .. }
2096 | Atomic::TIntersection { .. }
2097 | Atomic::TClassString(Some(_))
2098 | Atomic::TInterfaceString(Some(_)) => true,
2099 _ => false,
2100 }
2101}
2102
2103pub fn eval_key_of_type(t: &Type) -> Option<Type> {
2104 let mut result = Type::empty();
2105 for atomic in &t.types {
2106 match atomic {
2107 Atomic::TArray { key, .. } | Atomic::TNonEmptyArray { key, .. } => {
2108 for k in &key.types {
2109 result.add_type(k.clone());
2110 }
2111 }
2112 Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => {
2113 result.add_type(Atomic::TInt);
2114 }
2115 Atomic::TKeyedArray { properties, .. } => {
2116 for key in properties.keys() {
2117 match key {
2118 crate::atomic::ArrayKey::Int(n) => result.add_type(Atomic::TLiteralInt(*n)),
2119 crate::atomic::ArrayKey::String(s) => {
2120 result.add_type(Atomic::TLiteralString(s.clone()))
2121 }
2122 }
2123 }
2124 }
2125 _ => return None,
2126 }
2127 }
2128 (!result.types.is_empty()).then_some(result)
2129}
2130
2131pub fn eval_value_of_type(t: &Type) -> Option<Type> {
2132 let mut result = Type::empty();
2133 for atomic in &t.types {
2134 match atomic {
2135 Atomic::TArray { value, .. }
2136 | Atomic::TNonEmptyArray { value, .. }
2137 | Atomic::TList { value }
2138 | Atomic::TNonEmptyList { value } => {
2139 result.merge_with(value);
2140 }
2141 Atomic::TKeyedArray { properties, .. } => {
2142 for prop in properties.values() {
2143 result.merge_with(&prop.ty);
2144 }
2145 }
2146 _ => return None,
2147 }
2148 }
2149 (!result.types.is_empty()).then_some(result)
2150}
2151
2152fn substitute_in_fn_param(
2153 p: &crate::atomic::FnParam,
2154 bindings: &FxHashMap<Name, Type>,
2155) -> crate::atomic::FnParam {
2156 crate::atomic::FnParam {
2157 name: p.name,
2158 ty: p.ty.as_ref().map(|t| {
2159 let u = t.to_union();
2160 let substituted = u.substitute_templates(bindings);
2161 crate::compact::SimpleType::from_union(substituted)
2162 }),
2163 out_ty: p.out_ty.as_ref().map(|t| {
2164 let u = t.to_union();
2165 let substituted = u.substitute_templates(bindings);
2166 crate::compact::SimpleType::from_union(substituted)
2167 }),
2168 default: p.default.as_ref().map(|d| {
2169 let u = d.to_union();
2170 let substituted = u.substitute_templates(bindings);
2171 crate::compact::SimpleType::from_union(substituted)
2172 }),
2173 is_variadic: p.is_variadic,
2174 is_byref: p.is_byref,
2175 is_optional: p.is_optional,
2176 }
2177}
2178
2179fn composite_parts(atomic: &Atomic) -> Option<&'static [Atomic]> {
2186 match atomic {
2187 Atomic::TScalar => Some(&[Atomic::TInt, Atomic::TFloat, Atomic::TString, Atomic::TBool]),
2188 Atomic::TNumeric => Some(&[Atomic::TInt, Atomic::TFloat, Atomic::TNumericString]),
2189 _ => None,
2190 }
2191}
2192
2193fn object_shape_subtype(have: &KeyedProperties, want: &KeyedProperties) -> bool {
2194 want.iter().all(|(name, wanted)| match have.get(name) {
2195 Some(had) => (wanted.optional || !had.optional) && had.ty.is_subtype_structural(&wanted.ty),
2196 None => wanted.optional,
2197 })
2198}
2199
2200pub fn atomic_subtype(sub: &Atomic, sup: &Atomic) -> bool {
2202 if sub == sup {
2203 return true;
2204 }
2205 let string_keyed_array = || Atomic::TArray {
2207 key: Box::new(Type::string()),
2208 value: Box::new(Type::mixed()),
2209 };
2210 match (sub, sup) {
2211 (Atomic::TClosedResource, _) => return atomic_subtype(&Atomic::TResource, sup),
2212 (Atomic::TPropertiesOf { .. }, _) => return atomic_subtype(&string_keyed_array(), sup),
2213 (_, Atomic::TPropertiesOf { .. }) => return atomic_subtype(sub, &string_keyed_array()),
2214 (Atomic::TObjectShape { properties: have }, Atomic::TObjectShape { properties: want }) => {
2215 return object_shape_subtype(have, want);
2216 }
2217 (Atomic::TObjectShape { .. }, _) => return atomic_subtype(&Atomic::TObject, sup),
2218 (_, Atomic::TObjectShape { .. }) => return atomic_subtype(sub, &Atomic::TObject),
2220 _ => {}
2221 }
2222 match (sub, sup) {
2223 (Atomic::TNever, _) => true,
2225 (_, Atomic::TMixed) => true,
2227 (Atomic::TMixed, _) => true,
2228 (_, Atomic::TTemplateParam { as_type, .. }) => {
2233 as_type.is_mixed() || as_type.types.iter().any(|b| atomic_subtype(sub, b))
2234 }
2235
2236 (Atomic::TLiteralInt(_), Atomic::TInt) => true,
2238 (Atomic::TLiteralInt(_), Atomic::TNumeric) => true,
2239 (Atomic::TLiteralInt(_), Atomic::TScalar) => true,
2240 (Atomic::TLiteralInt(_), Atomic::TRefinedInt(IntRefinement::Literal)) => true,
2241 (Atomic::TRefinedInt(_), _) => atomic_subtype(&Atomic::TInt, sup),
2242 (_, Atomic::TRefinedInt(IntRefinement::Literal)) => false,
2243 (_, Atomic::TRefinedInt(IntRefinement::MaskOf(_))) => atomic_subtype(sub, &Atomic::TInt),
2245 (Atomic::TLiteralInt(n), Atomic::TPositiveInt) => *n > 0,
2246 (Atomic::TLiteralInt(n), Atomic::TNonNegativeInt) => *n >= 0,
2247 (Atomic::TLiteralInt(n), Atomic::TNegativeInt) => *n < 0,
2248 (Atomic::TPositiveInt, Atomic::TInt) => true,
2249 (Atomic::TPositiveInt, Atomic::TNonNegativeInt) => true,
2250 (Atomic::TPositiveInt, Atomic::TNumeric) => true,
2251 (Atomic::TPositiveInt, Atomic::TScalar) => true,
2252 (Atomic::TNegativeInt, Atomic::TInt) => true,
2253 (Atomic::TNegativeInt, Atomic::TNumeric) => true,
2254 (Atomic::TNegativeInt, Atomic::TScalar) => true,
2255 (Atomic::TNonNegativeInt, Atomic::TInt) => true,
2256 (Atomic::TNonNegativeInt, Atomic::TNumeric) => true,
2257 (Atomic::TNonNegativeInt, Atomic::TScalar) => true,
2258 (Atomic::TIntRange { .. }, Atomic::TInt) => true,
2259 (Atomic::TIntRange { .. }, Atomic::TNumeric) => true,
2260 (Atomic::TIntRange { .. }, Atomic::TScalar) => true,
2261 (Atomic::TPositiveInt, Atomic::TIntRange { min, max }) => {
2263 max.is_none() && min.is_none_or(|m| m <= 1)
2264 }
2265 (Atomic::TNegativeInt, Atomic::TIntRange { min, max }) => {
2267 min.is_none() && max.is_none_or(|m| m >= -1)
2268 }
2269 (Atomic::TNonNegativeInt, Atomic::TIntRange { min, max }) => {
2271 max.is_none() && min.is_none_or(|m| m <= 0)
2272 }
2273 (Atomic::TIntRange { min: sub_min, .. }, Atomic::TPositiveInt) => {
2275 sub_min.is_some_and(|lo| lo >= 1)
2276 }
2277 (Atomic::TIntRange { min: sub_min, .. }, Atomic::TNonNegativeInt) => {
2278 sub_min.is_some_and(|lo| lo >= 0)
2279 }
2280 (Atomic::TIntRange { max: sub_max, .. }, Atomic::TNegativeInt) => {
2281 sub_max.is_some_and(|hi| hi <= -1)
2282 }
2283 (
2285 Atomic::TIntRange {
2286 min: sub_min,
2287 max: sub_max,
2288 },
2289 Atomic::TIntRange {
2290 min: sup_min,
2291 max: sup_max,
2292 },
2293 ) => {
2294 let lower_ok = match (sub_min, sup_min) {
2295 (_, None) => true,
2296 (None, Some(_)) => false,
2297 (Some(sl), Some(su)) => sl >= su,
2298 };
2299 let upper_ok = match (sub_max, sup_max) {
2300 (None, None) | (Some(_), None) => true,
2301 (None, Some(_)) => false,
2302 (Some(sl), Some(su)) => sl <= su,
2303 };
2304 lower_ok && upper_ok
2305 }
2306
2307 (Atomic::TLiteralFloat(..), Atomic::TFloat) => true,
2308 (Atomic::TLiteralFloat(..), Atomic::TNumeric) => true,
2309 (Atomic::TLiteralFloat(..), Atomic::TScalar) => true,
2310
2311 (Atomic::TLiteralString(s), Atomic::TString) => {
2312 let _ = s;
2313 true
2314 }
2315 (Atomic::TLiteralString(s), Atomic::TCallableString) => {
2316 let _ = s;
2317 true
2318 }
2319 (Atomic::TLiteralString(s), Atomic::TNonEmptyString) => !s.is_empty(),
2320 (Atomic::TLiteralString(s), Atomic::TNonFalsyString) => !s.is_empty() && s.as_ref() != "0",
2321 (Atomic::TNonEmptyString | Atomic::TNumericString, Atomic::TNonFalsyString) => false,
2323 (Atomic::TNonFalsyString, _) => atomic_subtype(&Atomic::TNonEmptyString, sup),
2325 (_, Atomic::TNonFalsyString) => atomic_subtype(sub, &Atomic::TNonEmptyString),
2326 (
2327 Atomic::TLiteralString(s),
2328 Atomic::TRefinedString {
2329 refinement,
2330 non_empty,
2331 },
2332 ) => refinement.accepts(s) && !(*non_empty && s.is_empty()),
2333 (
2335 Atomic::TClassString(Some(_)),
2336 Atomic::TRefinedString {
2337 refinement: StringRefinement::Literal,
2338 ..
2339 },
2340 ) => true,
2341 (
2342 Atomic::TRefinedString {
2343 refinement: have,
2344 non_empty: have_non_empty,
2345 },
2346 Atomic::TRefinedString {
2347 refinement: want,
2348 non_empty: want_non_empty,
2349 },
2350 ) => have == want && (*have_non_empty || !want_non_empty),
2351 (Atomic::TRefinedString { non_empty, .. }, _) => {
2353 let base = if *non_empty {
2354 Atomic::TNonEmptyString
2355 } else {
2356 Atomic::TString
2357 };
2358 atomic_subtype(&base, sup)
2359 }
2360 (_, Atomic::TRefinedString { .. }) => false,
2361 (Atomic::TLiteralString(s), Atomic::TNumericString | Atomic::TNumeric) => {
2362 s.parse::<f64>().is_ok()
2363 }
2364 (Atomic::TLiteralString(_), Atomic::TClassString(_)) => true,
2367 (Atomic::TLiteralString(_), Atomic::TInterfaceString(_)) => true,
2370 (Atomic::TLiteralString(_), Atomic::TScalar) => true,
2371 (Atomic::TNonEmptyString, Atomic::TString) => true,
2372 (Atomic::TCallableString, Atomic::TString) => true,
2373 (Atomic::TNumericString, Atomic::TNonEmptyString) => true,
2375 (Atomic::TNumericString, Atomic::TString) => true,
2376 (Atomic::TClassString(_), Atomic::TNonEmptyString) => true,
2380 (Atomic::TInterfaceString(_), Atomic::TNonEmptyString) => true,
2381 (Atomic::TCallableString, Atomic::TNonEmptyString) => true,
2382 (Atomic::TEnumString, Atomic::TNonEmptyString) => true,
2383 (Atomic::TTraitString, Atomic::TNonEmptyString) => true,
2384 (Atomic::TClassString(_), Atomic::TString) => true,
2385 (Atomic::TInterfaceString(_), Atomic::TString) => true,
2386 (Atomic::TInterfaceString(_), Atomic::TClassString(None)) => true,
2391 (Atomic::TClassString(Some(_)), Atomic::TClassString(None)) => true,
2392 (Atomic::TInterfaceString(Some(a)), Atomic::TClassString(Some(b))) => a == b,
2393 (Atomic::TEnumString, Atomic::TString) => true,
2394 (Atomic::TTraitString, Atomic::TString) => true,
2395
2396 (Atomic::TTrue, Atomic::TBool) => true,
2397 (Atomic::TFalse, Atomic::TBool) => true,
2398
2399 (Atomic::TInt, Atomic::TNumeric) => true,
2400 (Atomic::TFloat, Atomic::TNumeric) => true,
2401 (Atomic::TIntegralFloat, Atomic::TNumeric) => true,
2402 (Atomic::TNumericString, Atomic::TNumeric) => true,
2403
2404 (Atomic::TInt, Atomic::TScalar) => true,
2405 (Atomic::TFloat, Atomic::TScalar) => true,
2406 (Atomic::TIntegralFloat, Atomic::TScalar) => true,
2407 (Atomic::TString, Atomic::TScalar) => true,
2408 (Atomic::TBool, Atomic::TScalar) => true,
2409 (Atomic::TNumeric, Atomic::TScalar) => true,
2410 (Atomic::TTrue, Atomic::TScalar) => true,
2411 (Atomic::TFalse, Atomic::TScalar) => true,
2412 (Atomic::TNonEmptyString, Atomic::TScalar) => true,
2416 (Atomic::TNumericString, Atomic::TScalar) => true,
2417 (Atomic::TCallableString, Atomic::TScalar) => true,
2418 (Atomic::TClassString(_), Atomic::TScalar) => true,
2419 (Atomic::TInterfaceString(_), Atomic::TScalar) => true,
2420 (Atomic::TEnumString, Atomic::TScalar) => true,
2421 (Atomic::TTraitString, Atomic::TScalar) => true,
2422
2423 (Atomic::TNamedObject { .. }, Atomic::TObject) => true,
2425 (Atomic::TStaticObject { .. }, Atomic::TObject) => true,
2426 (Atomic::TSelf { .. }, Atomic::TObject) => true,
2427 (Atomic::TLiteralEnumCase { .. }, Atomic::TObject) => true,
2429 (Atomic::TSelf { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
2431 (Atomic::TStaticObject { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
2432 (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TSelf { fqcn: b }) => a == b,
2434 (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TStaticObject { fqcn: b }) => a == b,
2435 (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TNamedObject { fqcn, .. }) => {
2438 enum_fqcn == fqcn
2439 }
2440 (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TSelf { fqcn })
2441 | (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TStaticObject { fqcn }) => {
2442 enum_fqcn == fqcn
2443 }
2444 (
2448 Atomic::TNamedObject {
2449 fqcn: sub_fqcn,
2450 type_params: sub_params,
2451 },
2452 Atomic::TNamedObject {
2453 fqcn: sup_fqcn,
2454 type_params: sup_params,
2455 },
2456 ) => {
2457 sub_fqcn == sup_fqcn
2458 && (sup_params.is_empty() || type_params_compatible(sub_params, sup_params))
2459 }
2460
2461 (Atomic::TIntegralFloat, Atomic::TFloat) => true,
2463
2464 (Atomic::TLiteralInt(_), Atomic::TFloat) => true,
2466 (Atomic::TPositiveInt, Atomic::TFloat) => true,
2467 (Atomic::TNegativeInt, Atomic::TFloat) => true,
2468 (Atomic::TNonNegativeInt, Atomic::TFloat) => true,
2469 (Atomic::TInt, Atomic::TFloat) => true,
2470 (Atomic::TIntRange { .. }, Atomic::TFloat) => true,
2471
2472 (Atomic::TLiteralInt(n), Atomic::TIntRange { min, max }) => {
2474 min.is_none_or(|lo| *n >= lo) && max.is_none_or(|hi| *n <= hi)
2475 }
2476
2477 (Atomic::TString, Atomic::TCallable { .. }) => true,
2479 (Atomic::TCallableString, Atomic::TCallable { .. }) => true,
2480 (Atomic::TNonEmptyString, Atomic::TCallable { .. }) => true,
2481 (Atomic::TLiteralString(_), Atomic::TCallable { .. }) => true,
2482 (Atomic::TArray { .. }, Atomic::TCallable { .. }) => true,
2483 (Atomic::TNonEmptyArray { .. }, Atomic::TCallable { .. }) => true,
2484 (Atomic::TKeyedArray { .. }, Atomic::TCallable { .. }) => true,
2485
2486 (Atomic::TClosure { .. }, Atomic::TCallable { .. }) => true,
2488 (Atomic::TCallable { .. }, Atomic::TClosure { .. }) => true,
2490 (Atomic::TClosure { data: sub }, Atomic::TClosure { data: sup }) => {
2500 fn has_nominal_type(t: &Type) -> bool {
2501 t.types.iter().any(|a| {
2502 matches!(
2503 a,
2504 Atomic::TNamedObject { .. }
2505 | Atomic::TSelf { .. }
2506 | Atomic::TStaticObject { .. }
2507 | Atomic::TTemplateParam { .. }
2508 | Atomic::TClosure { .. }
2509 | Atomic::TCallable { .. }
2510 )
2511 })
2512 }
2513 let sub_required = sub
2514 .params
2515 .iter()
2516 .filter(|p| !p.is_optional && !p.is_variadic)
2517 .count();
2518 if sub_required > sup.params.len() {
2519 false
2520 } else {
2521 let params_ok = sup.params.iter().enumerate().all(|(i, sup_param)| {
2522 let Some(sub_param) = sub.params.get(i) else {
2523 return true;
2524 };
2525 if sub_param.is_optional || sub_param.is_variadic {
2526 return true;
2527 }
2528 let (Some(sub_ty), Some(sup_ty)) =
2529 (sub_param.ty.as_ref(), sup_param.ty.as_ref())
2530 else {
2531 return true;
2532 };
2533 let (sub_u, sup_u) = (sub_ty.to_union(), sup_ty.to_union());
2534 if has_nominal_type(&sub_u) || has_nominal_type(&sup_u) {
2535 return true;
2536 }
2537 sup_u.is_subtype_structural(&sub_u)
2540 });
2541 params_ok
2542 && (sub.return_type.is_mixed()
2543 || sup.return_type.is_mixed()
2544 || sup.return_type.is_void()
2548 || has_nominal_type(&sub.return_type)
2549 || has_nominal_type(&sup.return_type)
2550 || sub.return_type.is_subtype_structural(&sup.return_type))
2551 }
2552 }
2553 (Atomic::TCallable { .. }, Atomic::TCallable { .. }) => true,
2555 (Atomic::TClosure { .. }, Atomic::TNamedObject { fqcn, .. }) => {
2557 fqcn.as_ref().eq_ignore_ascii_case("closure")
2558 }
2559 (Atomic::TClosure { .. }, Atomic::TObject) => true,
2560 (Atomic::TNamedObject { fqcn, .. }, Atomic::TClosure { .. }) => {
2562 fqcn.as_ref().eq_ignore_ascii_case("closure")
2563 }
2564 (Atomic::TNamedObject { fqcn, .. }, Atomic::TCallable { .. }) => {
2566 fqcn.as_ref().eq_ignore_ascii_case("closure")
2567 }
2568
2569 (
2577 Atomic::TIntersection { parts: sub_parts },
2578 Atomic::TIntersection { parts: sup_parts },
2579 ) => sup_parts.iter().all(|sup_part| {
2580 sub_parts
2581 .iter()
2582 .any(|sub_part| sub_part.is_subtype_structural(sup_part))
2583 }),
2584 (Atomic::TIntersection { parts }, Atomic::TObject) => parts
2585 .iter()
2586 .any(|part| part.is_subtype_structural(&Type::single(Atomic::TObject))),
2587
2588 (Atomic::TList { value }, Atomic::TArray { key, value: av }) => {
2590 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2591 }
2592 (Atomic::TNonEmptyList { value }, Atomic::TArray { key, value: av }) => {
2593 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2594 }
2595 (Atomic::TNonEmptyList { value }, Atomic::TNonEmptyArray { key, value: av }) => {
2596 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2597 }
2598 (Atomic::TNonEmptyList { value }, Atomic::TList { value: lv }) => {
2599 value.is_subtype_structural(lv)
2600 }
2601 (Atomic::TNonEmptyList { value: v1 }, Atomic::TNonEmptyList { value: v2 }) => {
2602 v1.is_subtype_structural(v2)
2603 }
2604 (Atomic::TArray { key, value: av }, Atomic::TList { value: lv }) => {
2606 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2607 && av.is_subtype_structural(lv)
2608 }
2609 (Atomic::TArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
2610 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2611 && av.is_subtype_structural(lv)
2612 }
2613 (Atomic::TNonEmptyArray { key, value: av }, Atomic::TList { value: lv }) => {
2614 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2615 && av.is_subtype_structural(lv)
2616 }
2617 (Atomic::TNonEmptyArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
2618 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2619 && av.is_subtype_structural(lv)
2620 }
2621 (Atomic::TList { value: v1 }, Atomic::TList { value: v2 }) => v1.is_subtype_structural(v2),
2623 (Atomic::TNonEmptyArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
2624 k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
2625 }
2626
2627 (Atomic::TArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
2629 k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
2630 }
2631
2632 (Atomic::TKeyedArray { properties, .. }, Atomic::TArray { key, value }) => {
2641 properties.iter().all(|(prop_key, prop)| {
2642 let key_atomic = match prop_key {
2643 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2644 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2645 };
2646 if !Type::single(key_atomic).is_subtype_structural(key) {
2647 return false; }
2649 let has_named_obj = prop.ty.types.iter().any(|a| {
2651 matches!(
2652 a,
2653 Atomic::TNamedObject { .. }
2654 | Atomic::TSelf { .. }
2655 | Atomic::TStaticObject { .. }
2656 | Atomic::TClosure { .. }
2657 | Atomic::TTemplateParam { .. }
2658 )
2659 });
2660 has_named_obj || prop.ty.is_subtype_structural(value)
2661 })
2662 }
2663 (
2664 Atomic::TKeyedArray {
2665 properties,
2666 is_open,
2667 ..
2668 },
2669 Atomic::TNonEmptyArray { key, value },
2670 ) => {
2671 (*is_open || properties.iter().any(|(_, p)| !p.optional))
2672 && properties.iter().all(|(prop_key, prop)| {
2673 let key_atomic = match prop_key {
2674 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2675 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2676 };
2677 if !Type::single(key_atomic).is_subtype_structural(key) {
2678 return false;
2679 }
2680 let has_named_obj = prop.ty.types.iter().any(|a| {
2681 matches!(
2682 a,
2683 Atomic::TNamedObject { .. }
2684 | Atomic::TSelf { .. }
2685 | Atomic::TStaticObject { .. }
2686 | Atomic::TClosure { .. }
2687 | Atomic::TTemplateParam { .. }
2688 )
2689 });
2690 has_named_obj || prop.ty.is_subtype_structural(value)
2691 })
2692 }
2693
2694 (
2696 Atomic::TKeyedArray {
2697 properties,
2698 is_list,
2699 ..
2700 },
2701 Atomic::TList { value: lv },
2702 ) => *is_list && properties.values().all(|p| p.ty.is_subtype_structural(lv)),
2703 (
2704 Atomic::TKeyedArray {
2705 properties,
2706 is_list,
2707 ..
2708 },
2709 Atomic::TNonEmptyList { value: lv },
2710 ) => {
2711 *is_list
2712 && !properties.is_empty()
2713 && properties.values().all(|p| p.ty.is_subtype_structural(lv))
2714 }
2715
2716 (
2721 Atomic::TKeyedArray {
2722 properties: sub_props,
2723 is_open: sub_open,
2724 is_list: sub_list,
2725 },
2726 Atomic::TKeyedArray {
2727 properties: sup_props,
2728 is_open: sup_open,
2729 is_list: sup_list,
2730 },
2731 ) => {
2732 if *sup_list
2734 && !*sub_list
2735 && sub_props
2736 .keys()
2737 .enumerate()
2738 .any(|(i, k)| *k != crate::atomic::ArrayKey::Int(i as i64))
2739 {
2740 return false;
2741 }
2742 let keys_satisfied = sup_props
2743 .iter()
2744 .all(|(key, sup_prop)| match sub_props.get(key) {
2745 Some(sub_prop) => {
2746 if !sup_prop.optional && sub_prop.optional {
2750 return false;
2751 }
2752 let has_named_obj = sup_prop.ty.types.iter().any(|a| {
2753 matches!(
2754 a,
2755 Atomic::TNamedObject { .. }
2756 | Atomic::TSelf { .. }
2757 | Atomic::TStaticObject { .. }
2758 | Atomic::TClosure { .. }
2759 | Atomic::TTemplateParam { .. }
2760 )
2761 });
2762 has_named_obj || sub_prop.ty.is_subtype_by_template_bounds(&sup_prop.ty)
2763 }
2764 None => sup_prop.optional || *sub_open,
2765 });
2766 let no_undeclared_extras =
2767 *sup_open || sub_props.keys().all(|k| sup_props.contains_key(k));
2768 keys_satisfied && no_undeclared_extras
2769 }
2770 (
2775 Atomic::TKeyedArray {
2776 properties,
2777 is_open,
2778 ..
2779 },
2780 Atomic::TIntersection { parts },
2781 ) => parts.iter().all(|part| {
2782 part.types.iter().any(|part_atomic| match part_atomic {
2783 Atomic::TKeyedArray {
2784 properties: sup_props,
2785 is_open: sup_open,
2786 ..
2787 } => {
2788 let keys_satisfied =
2789 sup_props
2790 .iter()
2791 .all(|(key, sup_prop)| match properties.get(key) {
2792 Some(sub_prop) => {
2793 if !sup_prop.optional && sub_prop.optional {
2794 return false;
2795 }
2796 let has_named_obj = sup_prop.ty.types.iter().any(|a| {
2797 matches!(
2798 a,
2799 Atomic::TNamedObject { .. }
2800 | Atomic::TSelf { .. }
2801 | Atomic::TStaticObject { .. }
2802 | Atomic::TClosure { .. }
2803 | Atomic::TTemplateParam { .. }
2804 )
2805 });
2806 has_named_obj
2807 || sub_prop.ty.is_subtype_by_template_bounds(&sup_prop.ty)
2808 || bare_array_may_fit(&sub_prop.ty, &sup_prop.ty)
2809 }
2810 None => *is_open || sup_prop.optional,
2811 });
2812 let has_array_part = parts.iter().any(|part| {
2813 part.types
2814 .iter()
2815 .any(|t| matches!(t, Atomic::TArray { .. }))
2816 });
2817 let has_keyed_array_part = parts.iter().any(|part| {
2818 part.types
2819 .iter()
2820 .any(|t| matches!(t, Atomic::TKeyedArray { .. }))
2821 });
2822 let keys_allowed_by_some_part = if has_array_part {
2823 true
2824 } else if has_keyed_array_part {
2825 properties.keys().all(|k| {
2826 parts.iter().any(|part| {
2827 part.types.iter().any(|t| {
2828 if let Atomic::TKeyedArray {
2829 properties: part_props,
2830 ..
2831 } = t
2832 {
2833 part_props.contains_key(k)
2834 } else {
2835 false
2836 }
2837 })
2838 })
2839 })
2840 } else {
2841 true
2842 };
2843 let no_undeclared_extras = *sup_open || keys_allowed_by_some_part;
2844 keys_satisfied && no_undeclared_extras
2845 }
2846 Atomic::TArray { key, value } => properties.iter().all(|(prop_key, prop)| {
2847 let key_atomic = match prop_key {
2848 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2849 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2850 };
2851 if !Type::single(key_atomic).is_subtype_structural(key) {
2852 return false;
2853 }
2854 let has_named_obj = prop.ty.types.iter().any(|a| {
2855 matches!(
2856 a,
2857 Atomic::TNamedObject { .. }
2858 | Atomic::TSelf { .. }
2859 | Atomic::TStaticObject { .. }
2860 | Atomic::TClosure { .. }
2861 | Atomic::TTemplateParam { .. }
2862 )
2863 });
2864 has_named_obj || prop.ty.is_subtype_structural(value)
2865 }),
2866 Atomic::TNamedObject { .. }
2867 | Atomic::TSelf { .. }
2868 | Atomic::TStaticObject { .. }
2869 | Atomic::TClosure { .. }
2870 | Atomic::TTemplateParam { .. } => true,
2871 _ => false,
2872 })
2873 }),
2874
2875 _ => false,
2876 }
2877}
2878
2879fn bare_array_may_fit(sub: &Type, sup: &Type) -> bool {
2881 fn array_like(t: &Atomic) -> bool {
2882 match t {
2883 Atomic::TArray { .. }
2884 | Atomic::TNonEmptyArray { .. }
2885 | Atomic::TList { .. }
2886 | Atomic::TNonEmptyList { .. }
2887 | Atomic::TKeyedArray { .. } => true,
2888 Atomic::TIntersection { parts } => parts.iter().all(|p| p.types.iter().all(array_like)),
2889 _ => false,
2890 }
2891 }
2892 matches!(
2893 sub.types.as_slice(),
2894 [Atomic::TArray { key, value }]
2895 if value.is_mixed()
2896 && (key.is_mixed()
2897 || matches!(key.types.as_slice(), [Atomic::TInt, Atomic::TString] | [Atomic::TString, Atomic::TInt]))
2898 ) && sup.types.iter().all(array_like)
2899}
2900
2901fn type_params_compatible(sub: &[Type], sup: &[Type]) -> bool {
2907 if sub.len() != sup.len() {
2908 return false;
2909 }
2910 sub.iter()
2911 .zip(sup.iter())
2912 .all(|(a, b)| a == b || (is_empty_array_literal(a) && is_array_like(b)))
2913}
2914
2915fn is_empty_array_literal(t: &Type) -> bool {
2918 !t.types.is_empty()
2919 && t.types.iter().all(
2920 |atom| matches!(atom, Atomic::TKeyedArray { properties, .. } if properties.is_empty()),
2921 )
2922}
2923
2924fn is_array_like(t: &Type) -> bool {
2926 !t.types.is_empty() && t.types.iter().all(|atom| atom.is_array())
2927}
2928
2929pub struct UnionBuilder {
2936 ty: Type,
2937 strings: std::collections::HashSet<std::sync::Arc<str>>,
2938 ints: std::collections::HashSet<i64>,
2939 literals_independent: bool,
2941}
2942
2943impl Default for UnionBuilder {
2944 fn default() -> Self {
2945 Self::new()
2946 }
2947}
2948
2949impl UnionBuilder {
2950 pub fn new() -> Self {
2951 Self {
2952 ty: Type::empty(),
2953 strings: Default::default(),
2954 ints: Default::default(),
2955 literals_independent: true,
2956 }
2957 }
2958
2959 pub fn is_empty(&self) -> bool {
2960 self.ty.is_empty()
2961 }
2962
2963 pub fn merge(&mut self, other: &Type) {
2964 for a in &other.types {
2965 self.add(a.clone());
2966 }
2967 self.ty.possibly_undefined |= other.possibly_undefined;
2968 }
2969
2970 pub fn add(&mut self, atomic: Atomic) {
2971 let lone_never = matches!(self.ty.types.first(), Some(Atomic::TNever));
2973 if self.literals_independent && !lone_never {
2974 match &atomic {
2975 Atomic::TLiteralString(s) => {
2976 if self.strings.insert(s.clone()) {
2977 self.ty.types.push(atomic);
2978 }
2979 return;
2980 }
2981 Atomic::TLiteralInt(n) => {
2982 if self.ints.insert(*n) {
2983 self.ty.types.push(atomic);
2984 }
2985 return;
2986 }
2987 _ => {}
2988 }
2989 }
2990 let disturbs_literals = matches!(
2991 atomic,
2992 Atomic::TString | Atomic::TMixed | Atomic::TConditional { .. }
2993 ) || int_bounds(&atomic).is_some();
2994 self.ty.add_type(atomic);
2995 if disturbs_literals || lone_never {
2996 self.resync();
2997 }
2998 }
2999
3000 fn resync(&mut self) {
3001 self.strings.clear();
3002 self.ints.clear();
3003 self.literals_independent = true;
3004 for t in &self.ty.types {
3005 match t {
3006 Atomic::TLiteralString(s) => {
3007 self.strings.insert(s.clone());
3008 }
3009 Atomic::TLiteralInt(n) => {
3010 self.ints.insert(*n);
3011 }
3012 Atomic::TMixed | Atomic::TString => self.literals_independent = false,
3013 other if int_bounds(other).is_some() => self.literals_independent = false,
3014 _ => {}
3015 }
3016 }
3017 }
3018
3019 pub fn build(self) -> Type {
3020 self.ty
3021 }
3022}
3023
3024fn callable_array() -> Atomic {
3026 let mut properties = KeyedProperties::with_capacity_and_hasher(2, Default::default());
3027 properties.insert(
3028 ArrayKey::Int(0),
3029 KeyedProperty {
3030 ty: Type::from_vec(vec![Atomic::TClassString(None), Atomic::TObject]),
3031 optional: false,
3032 },
3033 );
3034 properties.insert(
3035 ArrayKey::Int(1),
3036 KeyedProperty {
3037 ty: Type::single(Atomic::TNonEmptyString),
3038 optional: false,
3039 },
3040 );
3041 Atomic::TKeyedArray {
3042 properties: Arc::new(properties),
3043 is_open: false,
3044 is_list: true,
3045 }
3046}
3047
3048#[cfg(test)]
3049mod tests {
3050 use std::sync::Arc;
3051
3052 use super::*;
3053
3054 fn conditional(
3055 param_name: Option<Name>,
3056 subject: Type,
3057 if_true: Type,
3058 if_false: Type,
3059 ) -> Atomic {
3060 Atomic::TConditional {
3061 data: Box::new(crate::atomic::ConditionalData {
3062 param_name,
3063 subject,
3064 if_true,
3065 if_false,
3066 }),
3067 }
3068 }
3069
3070 #[test]
3071 fn single_is_single() {
3072 let u = Type::single(Atomic::TString);
3073 assert!(u.is_single());
3074 assert!(!u.is_nullable());
3075 }
3076
3077 #[test]
3078 fn nullable_has_null() {
3079 let u = Type::nullable(Atomic::TString);
3080 assert!(u.is_nullable());
3081 assert_eq!(u.types.len(), 2);
3082 }
3083
3084 #[test]
3085 fn add_type_deduplicates() {
3086 let mut u = Type::single(Atomic::TString);
3087 u.add_type(Atomic::TString);
3088 assert_eq!(u.types.len(), 1);
3089 }
3090
3091 #[test]
3092 fn array_key_is_int_string() {
3093 let k = Type::array_key();
3094 assert!(k.is_array_key());
3095 assert_eq!(k.types.len(), 2);
3096 }
3097
3098 #[test]
3099 fn is_array_key_false_for_plain_int() {
3100 assert!(!Type::int().is_array_key());
3101 }
3102
3103 #[test]
3104 fn is_array_key_false_for_mixed() {
3105 assert!(!Type::mixed().is_array_key());
3106 }
3107
3108 #[test]
3109 fn is_array_key_false_for_int_string_null() {
3110 let mut u = Type::array_key();
3111 u.add_type(Atomic::TNull);
3112 assert!(!u.is_array_key());
3113 }
3114
3115 #[test]
3116 fn add_type_literal_subsumed_by_base() {
3117 let mut u = Type::single(Atomic::TInt);
3118 u.add_type(Atomic::TLiteralInt(42));
3119 assert_eq!(u.types.len(), 1);
3120 assert!(matches!(u.types[0], Atomic::TInt));
3121 }
3122
3123 #[test]
3124 fn true_then_false_merges_to_bool() {
3125 let mut u = Type::single(Atomic::TTrue);
3126 u.add_type(Atomic::TFalse);
3127 assert_eq!(u.types.len(), 1);
3128 assert!(matches!(u.types[0], Atomic::TBool));
3129 }
3130
3131 #[test]
3132 fn false_then_true_merges_to_bool() {
3133 let mut u = Type::single(Atomic::TFalse);
3134 u.add_type(Atomic::TTrue);
3135 assert_eq!(u.types.len(), 1);
3136 assert!(matches!(u.types[0], Atomic::TBool));
3137 }
3138
3139 #[test]
3140 fn true_alone_stays_true() {
3141 let u = Type::single(Atomic::TTrue);
3142 assert_eq!(u.types.len(), 1);
3143 assert!(matches!(u.types[0], Atomic::TTrue));
3144 }
3145
3146 #[test]
3147 fn true_false_merge_preserves_other_union_members() {
3148 let mut u = Type::single(Atomic::TTrue);
3149 u.add_type(Atomic::TNull);
3150 u.add_type(Atomic::TFalse);
3151 assert_eq!(u.types.len(), 2);
3152 assert!(u.contains(|t| matches!(t, Atomic::TBool)));
3153 assert!(u.contains(|t| matches!(t, Atomic::TNull)));
3154 }
3155
3156 #[test]
3157 fn add_type_base_widens_literals() {
3158 let mut u = Type::single(Atomic::TLiteralInt(1));
3159 u.add_type(Atomic::TLiteralInt(2));
3160 u.add_type(Atomic::TInt);
3161 assert_eq!(u.types.len(), 1);
3162 assert!(matches!(u.types[0], Atomic::TInt));
3163 }
3164
3165 #[test]
3166 fn mixed_subsumes_everything() {
3167 let mut u = Type::single(Atomic::TString);
3168 u.add_type(Atomic::TMixed);
3169 assert_eq!(u.types.len(), 1);
3170 assert!(u.is_mixed());
3171 }
3172
3173 #[test]
3174 fn remove_null() {
3175 let u = Type::nullable(Atomic::TString);
3176 let narrowed = u.remove_null();
3177 assert!(!narrowed.is_nullable());
3178 assert_eq!(narrowed.types.len(), 1);
3179 }
3180
3181 #[test]
3182 fn narrow_to_truthy_removes_null_false() {
3183 let mut u = Type::empty();
3184 u.add_type(Atomic::TString);
3185 u.add_type(Atomic::TNull);
3186 u.add_type(Atomic::TFalse);
3187 let truthy = u.narrow_to_truthy();
3188 assert!(!truthy.is_nullable());
3189 assert!(!truthy.contains(|t| matches!(t, Atomic::TFalse)));
3190 }
3191
3192 #[test]
3193 fn merge_combines_types() {
3194 let a = Type::single(Atomic::TString);
3195 let b = Type::single(Atomic::TInt);
3196 let merged = Type::merge(&a, &b);
3197 assert_eq!(merged.types.len(), 2);
3198 }
3199
3200 #[test]
3201 fn intersect_keeps_narrower_side_not_self() {
3202 let int_ty = Type::single(Atomic::TInt);
3206 let mut literals = Type::empty();
3207 literals.add_type(Atomic::TLiteralInt(1));
3208 literals.add_type(Atomic::TLiteralInt(2));
3209
3210 let narrowed = int_ty.intersect_with(&literals);
3211 assert_eq!(narrowed.types.len(), 2);
3212 assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(1))));
3213 assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(2))));
3214 assert!(!narrowed.contains(|t| matches!(t, Atomic::TInt)));
3215 }
3216
3217 #[test]
3218 fn subtype_literal_int_under_int() {
3219 let sub = Type::single(Atomic::TLiteralInt(5));
3220 let sup = Type::single(Atomic::TInt);
3221 assert!(sub.is_subtype_structural(&sup));
3222 }
3223
3224 #[test]
3225 fn subtype_never_is_bottom() {
3226 let never = Type::never();
3227 let string = Type::single(Atomic::TString);
3228 assert!(never.is_subtype_structural(&string));
3229 }
3230
3231 #[test]
3232 fn subtype_everything_under_mixed() {
3233 let string = Type::single(Atomic::TString);
3234 let mixed = Type::mixed();
3235 assert!(string.is_subtype_structural(&mixed));
3236 }
3237
3238 #[test]
3239 fn subtype_enum_case_under_own_enum() {
3240 let sub = Type::single(Atomic::TLiteralEnumCase {
3241 enum_fqcn: Name::new("RoundingMode"),
3242 case_name: Name::new("Unnecessary"),
3243 });
3244 let sup = Type::single(Atomic::TNamedObject {
3245 fqcn: Name::new("RoundingMode"),
3246 type_params: empty_type_params(),
3247 });
3248 assert!(sub.is_subtype_structural(&sup));
3249 }
3250
3251 #[test]
3252 fn enum_case_not_subtype_of_unrelated_enum() {
3253 let sub = Type::single(Atomic::TLiteralEnumCase {
3254 enum_fqcn: Name::new("RoundingMode"),
3255 case_name: Name::new("Unnecessary"),
3256 });
3257 let sup = Type::single(Atomic::TNamedObject {
3258 fqcn: Name::new("Suit"),
3259 type_params: empty_type_params(),
3260 });
3261 assert!(!sub.is_subtype_structural(&sup));
3262 }
3263
3264 #[test]
3265 fn subtype_enum_case_under_own_self_and_static() {
3266 let case = |enum_fqcn: &str| {
3267 Type::single(Atomic::TLiteralEnumCase {
3268 enum_fqcn: Name::new(enum_fqcn),
3269 case_name: Name::new("A"),
3270 })
3271 };
3272 let own = Type::single(Atomic::TSelf {
3273 fqcn: Name::new("Suit"),
3274 });
3275 let own_static = Type::single(Atomic::TStaticObject {
3276 fqcn: Name::new("Suit"),
3277 });
3278 assert!(case("Suit").is_subtype_structural(&own));
3279 assert!(case("Suit").is_subtype_structural(&own_static));
3280 assert!(!case("Other").is_subtype_structural(&own));
3281 }
3282
3283 #[test]
3284 fn subtype_enum_case_under_bare_object() {
3285 let sub = Type::single(Atomic::TLiteralEnumCase {
3286 enum_fqcn: Name::new("RoundingMode"),
3287 case_name: Name::new("Unnecessary"),
3288 });
3289 let sup = Type::single(Atomic::TObject);
3290 assert!(sub.is_subtype_structural(&sup));
3291 }
3292
3293 #[test]
3294 fn template_substitution() {
3295 let mut bindings = FxHashMap::default();
3296 bindings.insert(Name::new("T"), Type::single(Atomic::TString));
3297
3298 let tmpl = Type::single(Atomic::TTemplateParam {
3299 name: Name::new("T"),
3300 as_type: Box::new(Type::mixed()),
3301 defining_entity: Name::new("MyClass"),
3302 });
3303
3304 let resolved = tmpl.substitute_templates(&bindings);
3305 assert_eq!(resolved.types.len(), 1);
3306 assert!(matches!(resolved.types[0], Atomic::TString));
3307 }
3308
3309 #[test]
3310 fn intersection_is_object() {
3311 let parts = vec![
3312 Type::single(Atomic::TNamedObject {
3313 fqcn: Name::new("Iterator"),
3314 type_params: empty_type_params(),
3315 }),
3316 Type::single(Atomic::TNamedObject {
3317 fqcn: Name::new("Countable"),
3318 type_params: empty_type_params(),
3319 }),
3320 ];
3321 let atomic = Atomic::TIntersection {
3322 parts: vec_to_type_params(parts),
3323 };
3324 assert!(atomic.is_object());
3325 assert!(!atomic.can_be_falsy());
3326 assert!(atomic.can_be_truthy());
3327 }
3328
3329 #[test]
3330 fn intersection_display_two_parts() {
3331 let parts = vec![
3332 Type::single(Atomic::TNamedObject {
3333 fqcn: Name::new("Iterator"),
3334 type_params: empty_type_params(),
3335 }),
3336 Type::single(Atomic::TNamedObject {
3337 fqcn: Name::new("Countable"),
3338 type_params: empty_type_params(),
3339 }),
3340 ];
3341 let u = Type::single(Atomic::TIntersection {
3342 parts: vec_to_type_params(parts),
3343 });
3344 assert_eq!(format!("{u}"), "Iterator&Countable");
3345 }
3346
3347 #[test]
3348 fn intersection_display_three_parts() {
3349 let parts = vec![
3350 Type::single(Atomic::TNamedObject {
3351 fqcn: Name::new("A"),
3352 type_params: empty_type_params(),
3353 }),
3354 Type::single(Atomic::TNamedObject {
3355 fqcn: Name::new("B"),
3356 type_params: empty_type_params(),
3357 }),
3358 Type::single(Atomic::TNamedObject {
3359 fqcn: Name::new("C"),
3360 type_params: empty_type_params(),
3361 }),
3362 ];
3363 let u = Type::single(Atomic::TIntersection {
3364 parts: vec_to_type_params(parts),
3365 });
3366 assert_eq!(format!("{u}"), "A&B&C");
3367 }
3368
3369 #[test]
3370 fn intersection_in_nullable_union_display() {
3371 let intersection = Atomic::TIntersection {
3372 parts: vec_to_type_params(vec![
3373 Type::single(Atomic::TNamedObject {
3374 fqcn: Name::new("Iterator"),
3375 type_params: empty_type_params(),
3376 }),
3377 Type::single(Atomic::TNamedObject {
3378 fqcn: Name::new("Countable"),
3379 type_params: empty_type_params(),
3380 }),
3381 ]),
3382 };
3383 let mut u = Type::single(intersection);
3384 u.add_type(Atomic::TNull);
3385 assert!(u.is_nullable());
3386 assert!(u.contains(|t| matches!(t, Atomic::TIntersection { .. })));
3387 }
3388
3389 fn t_param(name: &str) -> Type {
3392 Type::single(Atomic::TTemplateParam {
3393 name: Name::new(name),
3394 as_type: Box::new(Type::mixed()),
3395 defining_entity: Name::new("Fn"),
3396 })
3397 }
3398
3399 fn bindings_t_string() -> FxHashMap<Name, Type> {
3400 let mut b = FxHashMap::default();
3401 b.insert(Name::new("T"), Type::single(Atomic::TString));
3402 b
3403 }
3404
3405 #[test]
3406 fn substitute_non_empty_array_key_and_value() {
3407 let ty = Type::single(Atomic::TNonEmptyArray {
3408 key: Box::new(t_param("T")),
3409 value: Box::new(t_param("T")),
3410 });
3411 let result = ty.substitute_templates(&bindings_t_string());
3412 assert_eq!(result.types.len(), 1);
3413 let Atomic::TNonEmptyArray { key, value } = &result.types[0] else {
3414 panic!("expected TNonEmptyArray");
3415 };
3416 assert!(matches!(key.types[0], Atomic::TString));
3417 assert!(matches!(value.types[0], Atomic::TString));
3418 }
3419
3420 #[test]
3421 fn substitute_non_empty_list_value() {
3422 let ty = Type::single(Atomic::TNonEmptyList {
3423 value: Box::new(t_param("T")),
3424 });
3425 let result = ty.substitute_templates(&bindings_t_string());
3426 let Atomic::TNonEmptyList { value } = &result.types[0] else {
3427 panic!("expected TNonEmptyList");
3428 };
3429 assert!(matches!(value.types[0], Atomic::TString));
3430 }
3431
3432 #[test]
3433 fn substitute_keyed_array_property_types() {
3434 use crate::atomic::{ArrayKey, KeyedProperty};
3435 let mut props = KeyedProperties::default();
3436 props.insert(
3437 ArrayKey::String(Arc::from("name")),
3438 KeyedProperty {
3439 ty: t_param("T"),
3440 optional: false,
3441 },
3442 );
3443 props.insert(
3444 ArrayKey::String(Arc::from("tag")),
3445 KeyedProperty {
3446 ty: t_param("T"),
3447 optional: true,
3448 },
3449 );
3450 let ty = Type::single(Atomic::TKeyedArray {
3451 properties: Arc::new(props),
3452 is_open: true,
3453 is_list: false,
3454 });
3455 let result = ty.substitute_templates(&bindings_t_string());
3456 let Atomic::TKeyedArray {
3457 properties,
3458 is_open,
3459 is_list,
3460 } = &result.types[0]
3461 else {
3462 panic!("expected TKeyedArray");
3463 };
3464 assert!(is_open);
3465 assert!(!is_list);
3466 assert!(matches!(
3467 properties[&ArrayKey::String(Arc::from("name"))].ty.types[0],
3468 Atomic::TString
3469 ));
3470 assert!(properties[&ArrayKey::String(Arc::from("tag"))].optional);
3471 assert!(matches!(
3472 properties[&ArrayKey::String(Arc::from("tag"))].ty.types[0],
3473 Atomic::TString
3474 ));
3475 }
3476
3477 #[test]
3478 fn substitute_callable_params_and_return() {
3479 use crate::atomic::FnParam;
3480 let ty = Type::single(Atomic::TCallable {
3481 params: Some(Box::new(vec![FnParam {
3482 name: Name::new("x"),
3483 ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3484 out_ty: None,
3485 default: None,
3486 is_variadic: false,
3487 is_byref: false,
3488 is_optional: false,
3489 }])),
3490 return_type: Some(Box::new(t_param("T"))),
3491 is_pure: false,
3492 });
3493 let result = ty.substitute_templates(&bindings_t_string());
3494 let Atomic::TCallable {
3495 params,
3496 return_type,
3497 ..
3498 } = &result.types[0]
3499 else {
3500 panic!("expected TCallable");
3501 };
3502 let param_ty = params.as_ref().unwrap()[0].ty.as_ref().unwrap();
3503 let param_union = param_ty.to_union();
3504 assert!(matches!(param_union.types[0], Atomic::TString));
3505 let ret = return_type.as_ref().unwrap();
3506 assert!(matches!(ret.types[0], Atomic::TString));
3507 }
3508
3509 #[test]
3510 fn substitute_callable_bare_no_panic() {
3511 let ty = Type::single(Atomic::TCallable {
3513 params: None,
3514 return_type: None,
3515 is_pure: false,
3516 });
3517 let result = ty.substitute_templates(&bindings_t_string());
3518 assert!(matches!(
3519 result.types[0],
3520 Atomic::TCallable {
3521 params: None,
3522 return_type: None,
3523 ..
3524 }
3525 ));
3526 }
3527
3528 #[test]
3529 fn substitute_closure_params_return_and_this() {
3530 use crate::atomic::FnParam;
3531 let ty = Type::single(Atomic::TClosure {
3532 data: Box::new(crate::atomic::ClosureData {
3533 params: Box::new([FnParam {
3534 name: Name::new("a"),
3535 ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3536 out_ty: None,
3537 default: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3538 is_variadic: true,
3539 is_byref: true,
3540 is_optional: true,
3541 }]),
3542 return_type: t_param("T"),
3543 this_type: Some(t_param("T")),
3544 is_pure: false,
3545 is_static: false,
3546 rejects_surplus_args: false,
3547 is_impure: false,
3548 }),
3549 });
3550 let result = ty.substitute_templates(&bindings_t_string());
3551 let Atomic::TClosure { data } = &result.types[0] else {
3552 panic!("expected TClosure");
3553 };
3554 let (params, return_type, this_type) = (&data.params, &data.return_type, &data.this_type);
3555 let p = ¶ms[0];
3556 let ty_union = p.ty.as_ref().unwrap().to_union();
3557 let default_union = p.default.as_ref().unwrap().to_union();
3558 assert!(matches!(ty_union.types[0], Atomic::TString));
3559 assert!(matches!(default_union.types[0], Atomic::TString));
3560 assert!(p.is_variadic);
3562 assert!(p.is_byref);
3563 assert!(p.is_optional);
3564 assert!(matches!(return_type.types[0], Atomic::TString));
3565 assert!(matches!(
3566 this_type.as_ref().unwrap().types[0],
3567 Atomic::TString
3568 ));
3569 }
3570
3571 #[test]
3572 fn substitute_conditional_all_branches() {
3573 let ty = Type::single(conditional(
3574 None,
3575 t_param("T"),
3576 t_param("T"),
3577 Type::single(Atomic::TInt),
3578 ));
3579 let result = ty.substitute_templates(&bindings_t_string());
3580 let Atomic::TConditional { data } = &result.types[0] else {
3581 panic!("expected TConditional");
3582 };
3583 let (subject, if_true, if_false) = (&data.subject, &data.if_true, &data.if_false);
3584 assert!(matches!(subject.types[0], Atomic::TString));
3585 assert!(matches!(if_true.types[0], Atomic::TString));
3586 assert!(matches!(if_false.types[0], Atomic::TInt));
3587 }
3588
3589 #[test]
3590 fn resolve_conditional_is_null_non_null_arg() {
3591 let ty = Type::single(conditional(
3592 Some(Name::new("x")),
3593 Type::single(Atomic::TNull),
3594 Type::single(Atomic::TInt),
3595 Type::single(Atomic::TString),
3596 ));
3597 let result = ty.resolve_conditional_returns(|name| {
3598 if name == "x" {
3599 Some(Type::single(Atomic::TString)) } else {
3601 None
3602 }
3603 });
3604 assert!(result.types.len() == 1);
3605 assert!(matches!(result.types[0], Atomic::TString));
3606 }
3607
3608 #[test]
3609 fn resolve_conditional_is_null_null_arg() {
3610 let ty = Type::single(conditional(
3611 Some(Name::new("x")),
3612 Type::single(Atomic::TNull),
3613 Type::single(Atomic::TInt),
3614 Type::single(Atomic::TString),
3615 ));
3616 let result = ty.resolve_conditional_returns(|name| {
3617 if name == "x" {
3618 Some(Type::single(Atomic::TNull)) } else {
3620 None
3621 }
3622 });
3623 assert!(result.types.len() == 1);
3624 assert!(matches!(result.types[0], Atomic::TInt));
3625 }
3626
3627 #[test]
3628 fn resolve_conditional_is_null_nullable_arg_widens_to_branch_union() {
3629 let mut nullable_str = Type::single(Atomic::TString);
3630 nullable_str.add_type(Atomic::TNull);
3631 let ty = Type::single(conditional(
3632 Some(Name::new("x")),
3633 Type::single(Atomic::TNull),
3634 Type::single(Atomic::TInt),
3635 Type::single(Atomic::TString),
3636 ));
3637 let result = ty.resolve_conditional_returns(|name| {
3638 if name == "x" {
3639 Some(nullable_str.clone())
3640 } else {
3641 None
3642 }
3643 });
3644 assert_eq!(result.types.len(), 2);
3646 assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
3647 assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
3648 }
3649
3650 #[test]
3651 fn resolve_conditional_nested_widens_inner_branch() {
3652 let inner = Type::single(conditional(
3655 Some(Name::new("x")),
3656 Type::single(Atomic::TString),
3657 Type::single(Atomic::TString),
3658 Type::single(Atomic::TFloat),
3659 ));
3660 let ty = Type::single(conditional(
3661 Some(Name::new("x")),
3662 Type::single(Atomic::TNull),
3663 Type::single(Atomic::TInt),
3664 inner,
3665 ));
3666 let result = ty.resolve_conditional_returns(|_| None);
3668 assert!(
3669 result
3670 .types
3671 .iter()
3672 .all(|t| !matches!(t, Atomic::TConditional { .. })),
3673 "no TConditional should survive: {:?}",
3674 result.types
3675 );
3676 assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
3677 assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
3678 assert!(result.types.iter().any(|t| matches!(t, Atomic::TFloat)));
3679 }
3680
3681 #[test]
3682 fn resolve_conditional_nested_resolves_inner_branch() {
3683 let inner = Type::single(conditional(
3687 Some(Name::new("x")),
3688 Type::single(Atomic::TString),
3689 Type::single(Atomic::TString),
3690 Type::single(Atomic::TFloat),
3691 ));
3692 let ty = Type::single(conditional(
3693 Some(Name::new("x")),
3694 Type::single(Atomic::TNull),
3695 Type::single(Atomic::TInt),
3696 inner,
3697 ));
3698 let result = ty.resolve_conditional_returns(|name| {
3700 if name == "x" {
3701 Some(Type::single(Atomic::TString))
3702 } else {
3703 None
3704 }
3705 });
3706 assert!(
3707 result
3708 .types
3709 .iter()
3710 .all(|t| !matches!(t, Atomic::TConditional { .. })),
3711 "no TConditional should survive: {:?}",
3712 result.types
3713 );
3714 assert_eq!(result.types.len(), 1);
3715 assert!(matches!(result.types[0], Atomic::TString));
3716 }
3717
3718 #[test]
3719 fn resolve_conditional_true_subject_bool_arg_widens() {
3720 let ty = Type::single(conditional(
3724 Some(Name::new("x")),
3725 Type::single(Atomic::TTrue),
3726 Type::single(Atomic::TInt),
3727 Type::single(Atomic::TString),
3728 ));
3729 let result = ty.resolve_conditional_returns(|name| {
3730 if name == "x" {
3731 Some(Type::single(Atomic::TBool))
3732 } else {
3733 None
3734 }
3735 });
3736 assert_eq!(result.types.len(), 2);
3737 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3738 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3739 }
3740
3741 #[test]
3742 fn resolve_conditional_true_subject_mixed_arg_widens() {
3743 let ty = Type::single(conditional(
3746 Some(Name::new("x")),
3747 Type::single(Atomic::TTrue),
3748 Type::single(Atomic::TInt),
3749 Type::single(Atomic::TString),
3750 ));
3751 let result = ty.resolve_conditional_returns(|name| {
3752 if name == "x" {
3753 Some(Type::mixed())
3754 } else {
3755 None
3756 }
3757 });
3758 assert_eq!(result.types.len(), 2);
3759 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3760 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3761 }
3762
3763 #[test]
3764 fn resolve_conditional_true_subject_literal_args() {
3765 let ty = Type::single(conditional(
3768 Some(Name::new("x")),
3769 Type::single(Atomic::TTrue),
3770 Type::single(Atomic::TInt),
3771 Type::single(Atomic::TString),
3772 ));
3773 let false_arg = ty.clone().resolve_conditional_returns(|name| {
3774 if name == "x" {
3775 Some(Type::single(Atomic::TFalse))
3776 } else {
3777 None
3778 }
3779 });
3780 assert_eq!(false_arg.types.len(), 1);
3781 assert!(matches!(false_arg.types[0], Atomic::TString));
3782
3783 let true_arg = ty.resolve_conditional_returns(|name| {
3784 if name == "x" {
3785 Some(Type::single(Atomic::TTrue))
3786 } else {
3787 None
3788 }
3789 });
3790 assert_eq!(true_arg.types.len(), 1);
3791 assert!(matches!(true_arg.types[0], Atomic::TInt));
3792 }
3793
3794 #[test]
3795 fn resolve_conditional_bool_subject_scalar_arg_widens() {
3796 let ty = Type::single(conditional(
3800 Some(Name::new("x")),
3801 Type::single(Atomic::TBool),
3802 Type::single(Atomic::TInt),
3803 Type::single(Atomic::TString),
3804 ));
3805 let result = ty.resolve_conditional_returns(|name| {
3806 if name == "x" {
3807 Some(Type::single(Atomic::TScalar))
3808 } else {
3809 None
3810 }
3811 });
3812 assert_eq!(result.types.len(), 2);
3813 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3814 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3815 }
3816
3817 #[test]
3818 fn resolve_conditional_string_subject_bool_arg_false_branch() {
3819 let ty = Type::single(conditional(
3823 Some(Name::new("x")),
3824 Type::single(Atomic::TString),
3825 Type::single(Atomic::TInt),
3826 Type::single(Atomic::TBool),
3827 ));
3828 let result = ty.resolve_conditional_returns(|name| {
3829 if name == "x" {
3830 Some(Type::single(Atomic::TBool))
3831 } else {
3832 None
3833 }
3834 });
3835 assert_eq!(result.types.len(), 1);
3836 assert!(matches!(result.types[0], Atomic::TBool));
3837 }
3838
3839 #[test]
3840 fn resolve_conditional_list_subject_bare_array_arg_widens() {
3841 let ty = Type::single(conditional(
3844 Some(Name::new("x")),
3845 Type::single(Atomic::TList {
3846 value: Box::new(Type::mixed()),
3847 }),
3848 Type::single(Atomic::TInt),
3849 Type::single(Atomic::TString),
3850 ));
3851 let result = ty.resolve_conditional_returns(|name| {
3852 if name == "x" {
3853 Some(Type::single(Atomic::TArray {
3854 key: Box::new(Type::mixed()),
3855 value: Box::new(Type::mixed()),
3856 }))
3857 } else {
3858 None
3859 }
3860 });
3861 assert_eq!(result.types.len(), 2);
3862 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3863 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3864 }
3865
3866 #[test]
3867 fn resolve_conditional_float_subject_int_literal_false_branch() {
3868 let ty = resolve_conditional_branch(
3871 &Type::single(Atomic::TFloat),
3872 &Type::single(Atomic::TLiteralInt(42)),
3873 &Type::single(Atomic::TInt),
3874 &Type::single(Atomic::TString),
3875 );
3876 assert!(matches!(
3877 ty.as_ref(),
3878 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3879 ));
3880 }
3881
3882 #[test]
3883 fn resolve_conditional_int_subject_float_literal_false_branch() {
3884 let ty = resolve_conditional_branch(
3885 &Type::single(Atomic::TInt),
3886 &Type::single(Atomic::TLiteralFloat(1, 0)),
3887 &Type::single(Atomic::TInt),
3888 &Type::single(Atomic::TString),
3889 );
3890 assert!(matches!(
3891 ty.as_ref(),
3892 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3893 ));
3894 }
3895
3896 #[test]
3897 fn resolve_conditional_float_subject_float_literal_then_branch() {
3898 let ty = resolve_conditional_branch(
3899 &Type::single(Atomic::TFloat),
3900 &Type::single(Atomic::TLiteralFloat(1, 5)),
3901 &Type::single(Atomic::TInt),
3902 &Type::single(Atomic::TString),
3903 );
3904 assert!(matches!(
3905 ty.as_ref(),
3906 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3907 ));
3908 }
3909
3910 #[test]
3911 fn resolve_conditional_int_subject_int_literal_then_branch() {
3912 let ty = resolve_conditional_branch(
3913 &Type::single(Atomic::TInt),
3914 &Type::single(Atomic::TLiteralInt(7)),
3915 &Type::single(Atomic::TInt),
3916 &Type::single(Atomic::TString),
3917 );
3918 assert!(matches!(
3919 ty.as_ref(),
3920 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3921 ));
3922 }
3923
3924 #[test]
3925 fn resolve_conditional_int_subject_float_arg_false_branch() {
3926 let ty = resolve_conditional_branch(
3929 &Type::single(Atomic::TInt),
3930 &Type::single(Atomic::TFloat),
3931 &Type::single(Atomic::TInt),
3932 &Type::single(Atomic::TString),
3933 );
3934 assert!(matches!(
3935 ty.as_ref(),
3936 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3937 ));
3938 }
3939
3940 #[test]
3941 fn resolve_conditional_array_subject_string_arg_false_branch() {
3942 let ty = resolve_conditional_branch(
3943 &Type::single(Atomic::TArray {
3944 key: Box::new(Type::mixed()),
3945 value: Box::new(Type::mixed()),
3946 }),
3947 &Type::single(Atomic::TString),
3948 &Type::single(Atomic::TInt),
3949 &Type::single(Atomic::TString),
3950 );
3951 assert!(matches!(
3952 ty.as_ref(),
3953 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3954 ));
3955 }
3956
3957 #[test]
3958 fn resolve_conditional_array_subject_bool_arg_false_branch() {
3959 let ty = resolve_conditional_branch(
3960 &Type::single(Atomic::TArray {
3961 key: Box::new(Type::mixed()),
3962 value: Box::new(Type::mixed()),
3963 }),
3964 &Type::single(Atomic::TBool),
3965 &Type::single(Atomic::TInt),
3966 &Type::single(Atomic::TString),
3967 );
3968 assert!(matches!(
3969 ty.as_ref(),
3970 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3971 ));
3972 }
3973
3974 #[test]
3975 fn resolve_conditional_array_subject_mixed_arg_widens() {
3976 let ty = resolve_conditional_branch(
3980 &Type::single(Atomic::TArray {
3981 key: Box::new(Type::mixed()),
3982 value: Box::new(Type::mixed()),
3983 }),
3984 &Type::mixed(),
3985 &Type::single(Atomic::TInt),
3986 &Type::single(Atomic::TString),
3987 );
3988 assert!(ty.is_none());
3989 }
3990
3991 #[test]
3992 fn resolve_conditional_array_subject_list_arg_then_branch() {
3993 let ty = resolve_conditional_branch(
3996 &Type::single(Atomic::TArray {
3997 key: Box::new(Type::mixed()),
3998 value: Box::new(Type::mixed()),
3999 }),
4000 &Type::single(Atomic::TList {
4001 value: Box::new(Type::mixed()),
4002 }),
4003 &Type::single(Atomic::TInt),
4004 &Type::single(Atomic::TString),
4005 );
4006 assert!(matches!(
4007 ty.as_ref(),
4008 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4009 ));
4010 }
4011
4012 #[test]
4013 fn resolve_conditional_list_subject_keyed_list_arg_then_branch() {
4014 let ty = resolve_conditional_branch(
4016 &Type::single(Atomic::TList {
4017 value: Box::new(Type::mixed()),
4018 }),
4019 &Type::single(Atomic::TKeyedArray {
4020 properties: Arc::default(),
4021 is_open: false,
4022 is_list: true,
4023 }),
4024 &Type::single(Atomic::TInt),
4025 &Type::single(Atomic::TString),
4026 );
4027 assert!(matches!(
4028 ty.as_ref(),
4029 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4030 ));
4031 }
4032
4033 #[test]
4034 fn resolve_conditional_list_subject_list_string_union_widens() {
4035 let ty = resolve_conditional_branch(
4039 &Type::single(Atomic::TList {
4040 value: Box::new(Type::mixed()),
4041 }),
4042 &Type::from_vec(vec![
4043 Atomic::TList {
4044 value: Box::new(Type::mixed()),
4045 },
4046 Atomic::TString,
4047 ]),
4048 &Type::single(Atomic::TInt),
4049 &Type::single(Atomic::TString),
4050 );
4051 assert!(ty.is_none());
4052 }
4053
4054 #[test]
4055 fn resolve_conditional_numeric_subject_widens() {
4056 let ty = resolve_conditional_branch(
4060 &Type::single(Atomic::TNumeric),
4061 &Type::single(Atomic::TLiteralString("123".into())),
4062 &Type::single(Atomic::TInt),
4063 &Type::single(Atomic::TString),
4064 );
4065 assert!(ty.is_none());
4066 }
4067
4068 #[test]
4069 fn resolve_conditional_non_empty_string_subject_widens() {
4070 let ty = resolve_conditional_branch(
4073 &Type::single(Atomic::TNonEmptyString),
4074 &Type::single(Atomic::TString),
4075 &Type::single(Atomic::TInt),
4076 &Type::single(Atomic::TString),
4077 );
4078 assert!(ty.is_none());
4079 }
4080
4081 #[test]
4082 fn resolve_conditional_template_arg_widens() {
4083 let ty = resolve_conditional_branch(
4086 &Type::single(Atomic::TString),
4087 &t_param("T"),
4088 &Type::single(Atomic::TInt),
4089 &Type::single(Atomic::TString),
4090 );
4091 assert!(ty.is_none());
4092 }
4093
4094 #[test]
4095 fn resolve_conditional_mixed_subject_bool_arg_then_branch() {
4096 let ty = resolve_conditional_branch(
4099 &Type::single(Atomic::TMixed),
4100 &Type::single(Atomic::TBool),
4101 &Type::single(Atomic::TInt),
4102 &Type::single(Atomic::TString),
4103 );
4104 assert!(matches!(
4105 ty.as_ref(),
4106 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4107 ));
4108 }
4109
4110 #[test]
4111 fn resolve_conditional_scalar_subject_null_arg_false_branch() {
4112 let ty = resolve_conditional_branch(
4115 &Type::single(Atomic::TScalar),
4116 &Type::single(Atomic::TNull),
4117 &Type::single(Atomic::TInt),
4118 &Type::single(Atomic::TString),
4119 );
4120 assert!(matches!(
4121 ty.as_ref(),
4122 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4123 ));
4124 }
4125
4126 #[test]
4127 fn resolve_conditional_object_subject_named_arg_then_branch() {
4128 let ty = resolve_conditional_branch(
4130 &Type::single(Atomic::TObject),
4131 &Type::single(Atomic::TNamedObject {
4132 fqcn: Name::new("Foo"),
4133 type_params: empty_type_params(),
4134 }),
4135 &Type::single(Atomic::TInt),
4136 &Type::single(Atomic::TString),
4137 );
4138 assert!(matches!(
4139 ty.as_ref(),
4140 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4141 ));
4142 }
4143
4144 #[test]
4145 fn resolve_conditional_named_subject_other_class_widens() {
4146 let ty = resolve_conditional_branch(
4150 &Type::single(Atomic::TNamedObject {
4151 fqcn: Name::new("Foo"),
4152 type_params: empty_type_params(),
4153 }),
4154 &Type::single(Atomic::TNamedObject {
4155 fqcn: Name::new("Bar"),
4156 type_params: empty_type_params(),
4157 }),
4158 &Type::single(Atomic::TInt),
4159 &Type::single(Atomic::TString),
4160 );
4161 assert!(ty.is_none());
4162 }
4163
4164 #[test]
4165 fn resolve_conditional_enum_case_subject_widens() {
4166 let ty = resolve_conditional_branch(
4169 &Type::single(Atomic::TLiteralEnumCase {
4170 enum_fqcn: Name::new("RoundingMode"),
4171 case_name: Name::new("Unnecessary"),
4172 }),
4173 &Type::single(Atomic::TInt),
4174 &Type::single(Atomic::TInt),
4175 &Type::single(Atomic::TString),
4176 );
4177 assert!(ty.is_none());
4178 }
4179
4180 #[test]
4181 fn resolve_conditional_null_subject_bool_arg_false_branch() {
4182 let ty = resolve_conditional_branch(
4184 &Type::single(Atomic::TNull),
4185 &Type::single(Atomic::TBool),
4186 &Type::single(Atomic::TInt),
4187 &Type::single(Atomic::TString),
4188 );
4189 assert!(matches!(
4190 ty.as_ref(),
4191 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4192 ));
4193 }
4194
4195 #[test]
4196 fn resolve_conditional_bool_subject_true_arg_then_branch() {
4197 let ty = resolve_conditional_branch(
4200 &Type::single(Atomic::TBool),
4201 &Type::single(Atomic::TTrue),
4202 &Type::single(Atomic::TInt),
4203 &Type::single(Atomic::TString),
4204 );
4205 assert!(matches!(
4206 ty.as_ref(),
4207 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4208 ));
4209 }
4210
4211 #[test]
4212 fn substitute_intersection_parts() {
4213 let ty = Type::single(Atomic::TIntersection {
4214 parts: vec_to_type_params(vec![
4215 Type::single(Atomic::TNamedObject {
4216 fqcn: Name::new("Countable"),
4217 type_params: empty_type_params(),
4218 }),
4219 t_param("T"),
4220 ]),
4221 });
4222 let result = ty.substitute_templates(&bindings_t_string());
4223 let Atomic::TIntersection { parts } = &result.types[0] else {
4224 panic!("expected TIntersection");
4225 };
4226 assert_eq!(parts.len(), 2);
4227 assert!(matches!(parts[0].types[0], Atomic::TNamedObject { .. }));
4228 assert!(matches!(parts[1].types[0], Atomic::TString));
4229 }
4230
4231 fn shape(props: &[(&str, Atomic, bool)], is_open: bool) -> Atomic {
4232 Atomic::TKeyedArray {
4233 properties: Arc::new(
4234 props
4235 .iter()
4236 .map(|(k, ty, optional)| {
4237 (
4238 ArrayKey::String(Arc::from(*k)),
4239 KeyedProperty {
4240 ty: Type::single(ty.clone()),
4241 optional: *optional,
4242 },
4243 )
4244 })
4245 .collect(),
4246 ),
4247 is_open,
4248 is_list: false,
4249 }
4250 }
4251
4252 fn shape_with_bits(bits: u32, is_open: bool) -> Atomic {
4254 let names: Vec<String> = (0..5).map(|i| format!("k{i}")).collect();
4255 let mut props = vec![("a", Atomic::TInt, false)];
4256 props.extend(
4257 (0..5)
4258 .filter(|i| bits & (1 << i) != 0)
4259 .map(|i| (names[i].as_str(), Atomic::TString, false)),
4260 );
4261 shape(&props, is_open)
4262 }
4263
4264 fn keyed_count(ty: &Type) -> usize {
4265 ty.types
4266 .iter()
4267 .filter(|t| matches!(t, Atomic::TKeyedArray { .. }))
4268 .count()
4269 }
4270
4271 #[test]
4272 fn add_type_keeps_few_shapes_apart() {
4273 let mut ty = Type::empty();
4274 for bits in 0..MAX_KEYED_SHAPES as u32 {
4275 ty.add_type(shape_with_bits(bits, false));
4276 }
4277 assert_eq!(keyed_count(&ty), MAX_KEYED_SHAPES);
4278 }
4279
4280 #[test]
4281 fn add_type_folds_shapes_past_the_limit() {
4282 let mut ty = Type::empty();
4283 for bits in 0..32 {
4284 ty.add_type(shape_with_bits(bits, false));
4285 }
4286 assert!(keyed_count(&ty) <= MAX_KEYED_SHAPES);
4287 for t in &ty.types {
4289 let Atomic::TKeyedArray { properties, .. } = t else {
4290 continue;
4291 };
4292 assert!(!properties[&ArrayKey::String(Arc::from("a"))].optional);
4293 }
4294 for i in 0..5 {
4295 let key = ArrayKey::String(Arc::from(format!("k{i}").as_str()));
4296 assert!(ty.types.iter().any(|t| matches!(
4297 t,
4298 Atomic::TKeyedArray { properties, .. } if properties.contains_key(&key)
4299 )));
4300 }
4301 }
4302
4303 #[test]
4304 fn add_type_folds_generic_arrays_past_the_limit() {
4305 let mut ty = Type::empty();
4306 for i in 0..32 {
4307 ty.add_type(Atomic::TArray {
4308 key: Box::new(Type::single(Atomic::TInt)),
4309 value: Box::new(Type::single(Atomic::TLiteralInt(i))),
4310 });
4311 }
4312 assert!(ty.types.len() <= MAX_GENERIC_ARRAYS);
4313 for i in 0..32 {
4314 assert!(ty.types.iter().any(|t| matches!(
4315 t,
4316 Atomic::TArray { value, .. } if value.types.contains(&Atomic::TLiteralInt(i))
4317 )));
4318 }
4319 }
4320
4321 #[test]
4322 fn add_type_widens_string_literals_past_the_limit() {
4323 let mut ty = Type::empty();
4324 for i in 0..MAX_LITERAL_STRINGS {
4325 ty.add_type(Atomic::TLiteralString(format!("s{i}").into()));
4326 }
4327 assert_eq!(ty.types.len(), MAX_LITERAL_STRINGS);
4328 ty.add_type(Atomic::TLiteralString("one more".into()));
4329 assert_eq!(ty.types.as_slice(), &[Atomic::TString]);
4330 ty.add_type(Atomic::TLiteralString("after".into()));
4331 assert_eq!(ty.types.as_slice(), &[Atomic::TString]);
4332 }
4333
4334 #[test]
4335 fn add_type_drops_generic_arrays_another_covers() {
4336 let list = |value: Atomic| Atomic::TList {
4337 value: Box::new(Type::single(value)),
4338 };
4339 let mut ty = Type::single(list(Atomic::TLiteralInt(0)));
4340 ty.add_type(list(Atomic::TInt));
4341 assert_eq!(ty.types.as_slice(), &[list(Atomic::TInt)]);
4342 ty.add_type(list(Atomic::TLiteralInt(1)));
4343 assert_eq!(ty.types.as_slice(), &[list(Atomic::TInt)]);
4344
4345 let mut opaque = Type::single(list(Atomic::TMixed));
4346 opaque.add_type(list(Atomic::TInt));
4347 assert_eq!(opaque.types.len(), 2);
4348
4349 let mut kinds = Type::single(Atomic::TNonEmptyList {
4350 value: Box::new(Type::single(Atomic::TInt)),
4351 });
4352 kinds.add_type(list(Atomic::TInt));
4353 assert_eq!(kinds.types.len(), 2);
4354 }
4355
4356 #[test]
4357 fn combine_keeps_emptiness_and_open_shape_soundness() {
4358 assert!(combine_keyed_arrays(
4360 &shape(&[], false),
4361 &shape(&[("a", Atomic::TInt, false)], false)
4362 )
4363 .is_none());
4364 assert!(combine_keyed_arrays(
4366 &shape(&[("a", Atomic::TInt, false)], true),
4367 &shape(&[("a", Atomic::TInt, false)], false)
4368 )
4369 .is_none());
4370 assert_eq!(
4372 combine_keyed_arrays(
4373 &shape(&[("a", Atomic::TInt, false)], true),
4374 &shape(
4375 &[("a", Atomic::TInt, false), ("k", Atomic::TString, false)],
4376 true
4377 )
4378 ),
4379 Some(shape(&[("a", Atomic::TInt, false)], true))
4380 );
4381 }
4382
4383 #[test]
4384 fn substitute_no_template_params_identity() {
4385 let ty = Type::single(Atomic::TInt);
4386 let result = ty.substitute_templates(&bindings_t_string());
4387 assert!(matches!(result.types[0], Atomic::TInt));
4388 }
4389}