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(properties.map_types(f)),
1008 is_open: *is_open,
1009 is_list: *is_list,
1010 },
1011 other => other.clone(),
1012 }
1013 }
1014 fn map_atoms(ty: &Type, f: impl Fn(&Atomic) -> Atomic) -> Type {
1015 let mut result = Type::empty();
1016 result.possibly_undefined = ty.possibly_undefined;
1017 result.from_docblock = ty.from_docblock;
1018 for atomic in &ty.types {
1019 result.add_type(f(atomic));
1020 }
1021 result
1022 }
1023 map_atoms(self, |a| map_values(a, relax_all))
1024 }
1025
1026 pub fn narrow_to_non_empty_collection(&self) -> Type {
1029 let mut out = Type::empty();
1030 out.from_docblock = self.from_docblock;
1031 for t in &self.types {
1032 match t {
1033 Atomic::TArray { key, value } => out.add_type(Atomic::TNonEmptyArray {
1034 key: key.clone(),
1035 value: value.clone(),
1036 }),
1037 Atomic::TList { value } => out.add_type(Atomic::TNonEmptyList {
1038 value: value.clone(),
1039 }),
1040 Atomic::TKeyedArray {
1041 properties,
1042 is_open: false,
1043 ..
1044 } if properties.is_empty() => {}
1045 _ => out.add_type(t.clone()),
1046 }
1047 }
1048 out
1049 }
1050
1051 pub fn narrow_to_empty_collection(&self) -> Type {
1061 let mut out = Type::empty();
1062 out.from_docblock = self.from_docblock;
1063 for t in &self.types {
1064 match t {
1065 Atomic::TNonEmptyArray { .. } | Atomic::TNonEmptyList { .. } => {}
1066 Atomic::TArray { .. } | Atomic::TList { .. } => {
1067 out.add_type(Atomic::TKeyedArray {
1068 properties: Arc::default(),
1069 is_open: false,
1070 is_list: true,
1071 });
1072 }
1073 _ => out.add_type(t.clone()),
1074 }
1075 }
1076 out
1077 }
1078
1079 pub fn narrow_to_list(&self) -> Type {
1091 let mut out = Type::empty();
1092 out.from_docblock = self.from_docblock;
1093 for t in &self.types {
1094 match t {
1095 Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => out.add_type(t.clone()),
1096 Atomic::TArray { key, value } if !key.narrow_to_int().is_empty() => {
1102 out.add_type(Atomic::TList {
1103 value: value.clone(),
1104 });
1105 }
1106 Atomic::TNonEmptyArray { key, value } if !key.narrow_to_int().is_empty() => {
1107 out.add_type(Atomic::TNonEmptyList {
1108 value: value.clone(),
1109 });
1110 }
1111 Atomic::TKeyedArray { is_list: true, .. } => out.add_type(t.clone()),
1112 Atomic::TMixed => out.add_type(Atomic::TList {
1113 value: Box::new(Type::mixed()),
1114 }),
1115 _ => {}
1116 }
1117 }
1118 if out.is_empty() {
1119 self.filter(|t| matches!(t, Atomic::TList { .. } | Atomic::TNonEmptyList { .. }))
1120 } else {
1121 out
1122 }
1123 }
1124
1125 pub fn narrow_to_object(&self) -> Type {
1130 let mut out = Type::empty();
1131 for t in &self.types {
1132 if matches!(t, Atomic::TMixed) {
1133 out.add_type(Atomic::TObject);
1134 } else if t.is_object() || matches!(t, Atomic::TTemplateParam { .. }) {
1135 out.add_type(t.clone());
1136 }
1137 }
1138 if out.types.is_empty() {
1139 self.filter(|t| t.is_object())
1140 .with_callable_form(self, Atomic::TObject)
1141 } else {
1142 out.with_callable_form(self, Atomic::TObject)
1143 }
1144 }
1145
1146 fn with_callable_form(mut self, source: &Type, form: Atomic) -> Type {
1149 if source
1150 .types
1151 .iter()
1152 .any(|t| matches!(t, Atomic::TCallable { .. }))
1153 {
1154 self.add_type(form);
1155 }
1156 self
1157 }
1158
1159 pub fn narrow_to_not_callable(&self) -> Type {
1162 let callable_array = callable_array();
1163 self.filter(|t| {
1164 !t.is_callable()
1165 && *t != callable_array
1166 && !matches!(t, Atomic::TNamedObject { fqcn, .. } if fqcn.eq_ignore_ascii_case("Closure"))
1167 })
1168 }
1169
1170 pub fn narrow_to_callable(&self) -> Type {
1177 let narrowed = self.filter(|t| {
1178 t.is_callable()
1179 || t.is_string()
1180 || t.is_array()
1181 || t.is_object()
1182 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1183 });
1184 let mut result = Type::empty();
1191 result.possibly_undefined = narrowed.possibly_undefined;
1192 result.from_docblock = narrowed.from_docblock;
1193 for atomic in narrowed.types {
1194 if matches!(atomic, Atomic::TObject | Atomic::TObjectShape { .. }) {
1195 result.add_type(Atomic::TCallable {
1196 params: None,
1197 return_type: None,
1198 is_pure: false,
1199 });
1200 } else {
1201 result.add_type(atomic);
1202 }
1203 }
1204 result
1205 }
1206
1207 pub fn narrow_to_scalar(&self) -> Type {
1209 self.filter_replacing(
1210 |t| {
1211 t.is_string()
1212 || t.is_int()
1213 || matches!(
1214 t,
1215 Atomic::TFloat
1216 | Atomic::TIntegralFloat
1217 | Atomic::TLiteralFloat(..)
1218 | Atomic::TBool
1219 | Atomic::TTrue
1220 | Atomic::TFalse
1221 | Atomic::TScalar
1222 | Atomic::TNumeric
1223 | Atomic::TNumericString
1224 | Atomic::TTemplateParam { .. }
1225 )
1226 },
1227 |t| matches!(t, Atomic::TMixed),
1228 Atomic::TScalar,
1229 )
1230 }
1231
1232 pub fn narrow_to_iterable(&self) -> Type {
1235 self.filter(|t| {
1236 t.is_array()
1237 || t.is_object()
1238 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1239 })
1240 }
1241
1242 pub fn narrow_to_countable(&self) -> Type {
1245 self.filter(|t| {
1246 t.is_array()
1247 || t.is_object()
1248 || matches!(t, Atomic::TMixed | Atomic::TTemplateParam { .. })
1249 })
1250 }
1251
1252 pub fn narrow_to_resource(&self) -> Type {
1254 let mut out = self.filter(|t| match t {
1255 Atomic::TResource | Atomic::TMixed => true,
1256 Atomic::TTemplateParam { as_type, .. } => as_type.is_mixed(),
1257 _ => false,
1258 });
1259 for t in out.types.iter_mut() {
1260 if matches!(t, Atomic::TMixed) {
1261 *t = Atomic::TResource;
1262 }
1263 }
1264 out
1265 }
1266
1267 pub fn narrow_to_class_string(&self) -> Type {
1272 let mut out = Type::empty();
1273 out.from_docblock = self.from_docblock;
1274 for t in &self.types {
1275 match t {
1276 Atomic::TClassString(_) => out.add_type(t.clone()),
1277 _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
1278 out.add_type(Atomic::TClassString(None));
1279 }
1280 _ => {}
1281 }
1282 }
1283 out
1284 }
1285
1286 pub fn narrow_to_interface_string(&self) -> Type {
1291 let mut out = Type::empty();
1292 out.from_docblock = self.from_docblock;
1293 for t in &self.types {
1294 match t {
1295 Atomic::TInterfaceString(_) => out.add_type(t.clone()),
1296 Atomic::TClassString(name) => {
1300 out.add_type(Atomic::TInterfaceString(*name));
1301 }
1302 _ if t.is_string() || matches!(t, Atomic::TMixed | Atomic::TScalar) => {
1303 out.add_type(Atomic::TInterfaceString(None));
1304 }
1305 _ => {}
1306 }
1307 }
1308 out
1309 }
1310
1311 pub fn merge(a: &Type, b: &Type) -> Type {
1316 if b.types.is_empty() {
1318 let mut result = a.clone();
1319 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1320 return result;
1321 }
1322 if a.types.is_empty() {
1324 let mut result = b.clone();
1325 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1326 return result;
1327 }
1328 if a.types.len() == 1 && matches!(a.types[0], Atomic::TMixed) {
1330 let mut result = a.clone();
1331 result.possibly_undefined = a.possibly_undefined || b.possibly_undefined;
1332 return result;
1333 }
1334 if b.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1336 return Type {
1337 types: smallvec::smallvec![Atomic::TMixed],
1338 possibly_undefined: a.possibly_undefined || b.possibly_undefined,
1339 from_docblock: a.from_docblock || b.from_docblock,
1340 falsy_stripped: false,
1341 possibly_absent_offset: false,
1342 };
1343 }
1344 let mut result = a.clone();
1345 result.merge_with(b);
1346 result
1347 }
1348
1349 pub fn merge_with(&mut self, other: &Type) {
1351 if self.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1352 self.possibly_undefined |= other.possibly_undefined;
1353 return;
1354 }
1355 if other.types.iter().any(|t| matches!(t, Atomic::TMixed)) {
1356 self.types.clear();
1357 self.types.push(Atomic::TMixed);
1358 self.possibly_undefined |= other.possibly_undefined;
1359 return;
1360 }
1361 for atomic in &other.types {
1362 if matches!(atomic, Atomic::TConditional { .. }) {
1364 self.add_type(atomic.clone());
1365 } else if !self.types.contains(atomic)
1366 && !self.types.iter().any(|t| matches!(t, Atomic::TMixed))
1367 {
1368 self.add_absent_type(atomic.clone());
1369 }
1370 }
1371 self.possibly_undefined |= other.possibly_undefined;
1372 }
1373
1374 pub fn intersect_with(&self, other: &Type) -> Type {
1378 if self.is_mixed() {
1379 return other.clone();
1380 }
1381 if other.is_mixed() {
1382 return self.clone();
1383 }
1384 let mut result = Type::empty();
1392 for a in &self.types {
1393 for b in &other.types {
1394 if a == b {
1395 result.add_type(a.clone());
1396 } else if atomic_subtype(b, a) {
1397 result.add_type(b.clone());
1398 } else if atomic_subtype(a, b) {
1399 result.add_type(a.clone());
1400 }
1401 }
1402 }
1403 if result.is_empty() {
1404 Type::never()
1405 } else {
1406 result
1407 }
1408 }
1409
1410 pub fn substitute_templates(&self, bindings: &FxHashMap<Name, Type>) -> Type {
1414 if bindings.is_empty() {
1415 return self.clone();
1416 }
1417 if !self.types.iter().any(atomic_may_contain_templates) {
1420 return self.clone();
1421 }
1422 let mut result = Type::empty();
1423 result.possibly_undefined = self.possibly_undefined;
1424 result.from_docblock = self.from_docblock;
1425 for atomic in &self.types {
1426 match atomic {
1427 Atomic::TTemplateParam { name, .. } => {
1428 if let Some(resolved) = bindings.get(name) {
1429 for t in &resolved.types {
1430 result.add_type(t.clone());
1431 }
1432 } else {
1433 result.add_type(atomic.clone());
1434 }
1435 }
1436 Atomic::TArray { key, value } => {
1437 result.add_type(Atomic::TArray {
1438 key: Box::new(key.substitute_templates(bindings)),
1439 value: Box::new(value.substitute_templates(bindings)),
1440 });
1441 }
1442 Atomic::TList { value } => {
1443 result.add_type(Atomic::TList {
1444 value: Box::new(value.substitute_templates(bindings)),
1445 });
1446 }
1447 Atomic::TNonEmptyArray { key, value } => {
1448 result.add_type(Atomic::TNonEmptyArray {
1449 key: Box::new(key.substitute_templates(bindings)),
1450 value: Box::new(value.substitute_templates(bindings)),
1451 });
1452 }
1453 Atomic::TNonEmptyList { value } => {
1454 result.add_type(Atomic::TNonEmptyList {
1455 value: Box::new(value.substitute_templates(bindings)),
1456 });
1457 }
1458 Atomic::TKeyedArray {
1459 properties,
1460 is_open,
1461 is_list,
1462 } => {
1463 let new_props = properties.map_types(|ty| ty.substitute_templates(bindings));
1464 result.add_type(Atomic::TKeyedArray {
1465 properties: Arc::new(new_props),
1466 is_open: *is_open,
1467 is_list: *is_list,
1468 });
1469 }
1470 Atomic::TCallable {
1471 params,
1472 return_type,
1473 is_pure,
1474 } => {
1475 result.add_type(Atomic::TCallable {
1476 params: params.as_ref().map(|ps| {
1477 Box::new(
1478 ps.iter()
1479 .map(|p| substitute_in_fn_param(p, bindings))
1480 .collect(),
1481 )
1482 }),
1483 return_type: return_type
1484 .as_ref()
1485 .map(|r| Box::new(r.substitute_templates(bindings))),
1486 is_pure: *is_pure,
1487 });
1488 }
1489 Atomic::TClosure { data } => {
1490 result.add_type(Atomic::TClosure {
1491 data: Box::new(crate::atomic::ClosureData {
1492 params: data
1493 .params
1494 .iter()
1495 .map(|p| substitute_in_fn_param(p, bindings))
1496 .collect(),
1497 return_type: data.return_type.substitute_templates(bindings),
1498 this_type: data
1499 .this_type
1500 .as_ref()
1501 .map(|t| t.substitute_templates(bindings)),
1502 is_pure: data.is_pure,
1503 is_static: data.is_static,
1504 rejects_surplus_args: data.rejects_surplus_args,
1505 is_impure: data.is_impure,
1506 }),
1507 });
1508 }
1509 Atomic::TConditional { data } => {
1510 let param_name = &data.param_name;
1511 let new_subject = data.subject.substitute_templates(bindings);
1512 let new_if_true = data.if_true.substitute_templates(bindings);
1513 let new_if_false = data.if_false.substitute_templates(bindings);
1514
1515 let resolved = if let Some(name) = param_name {
1519 if let Some(bound) = bindings.get(name) {
1520 resolve_conditional_branch(
1521 &new_subject,
1522 bound,
1523 &new_if_true,
1524 &new_if_false,
1525 )
1526 } else {
1527 None
1528 }
1529 } else {
1530 None
1531 };
1532
1533 if let Some(branch) = resolved {
1534 for t in branch.types {
1535 result.add_type(t);
1536 }
1537 } else {
1538 result.add_type(Atomic::TConditional {
1539 data: Box::new(crate::atomic::ConditionalData {
1540 param_name: *param_name,
1541 subject: new_subject,
1542 if_true: new_if_true,
1543 if_false: new_if_false,
1544 }),
1545 });
1546 }
1547 }
1548 Atomic::TKeyOf { target } => {
1549 let new_target = target.substitute_templates(bindings);
1550 if let Some(resolved) = eval_key_of_type(&new_target) {
1551 result.merge_with(&resolved);
1552 } else {
1553 result.add_type(Atomic::TKeyOf {
1554 target: Box::new(new_target),
1555 });
1556 }
1557 }
1558 Atomic::TValueOf { target } => {
1559 let new_target = target.substitute_templates(bindings);
1560 if let Some(resolved) = eval_value_of_type(&new_target) {
1561 result.merge_with(&resolved);
1562 } else {
1563 result.add_type(Atomic::TValueOf {
1564 target: Box::new(new_target),
1565 });
1566 }
1567 }
1568 Atomic::TIntersection { parts } => {
1569 result.add_type(Atomic::TIntersection {
1570 parts: vec_to_type_params(
1571 parts
1572 .iter()
1573 .map(|p| p.substitute_templates(bindings))
1574 .collect(),
1575 ),
1576 });
1577 }
1578 Atomic::TNamedObject { fqcn, type_params } => {
1579 if type_params.is_empty() && !fqcn.contains('\\') {
1581 if let Some(resolved) = bindings.get(fqcn) {
1582 for t in &resolved.types {
1583 result.add_type(t.clone());
1584 }
1585 continue;
1586 }
1587 }
1588 let new_params: Vec<Type> = type_params
1589 .iter()
1590 .map(|p| p.substitute_templates(bindings))
1591 .collect();
1592 result.add_type(Atomic::TNamedObject {
1593 fqcn: *fqcn,
1594 type_params: vec_to_type_params(new_params),
1595 });
1596 }
1597 Atomic::TClassString(Some(param_name)) => {
1599 if let Some(resolved) = bindings.get(param_name) {
1600 for r_atomic in &resolved.types {
1601 let cls_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1602 Some(*fqcn)
1603 } else {
1604 None
1605 };
1606 result.add_type(Atomic::TClassString(cls_name));
1607 }
1608 } else {
1609 result.add_type(atomic.clone());
1610 }
1611 }
1612 Atomic::TInterfaceString(Some(param_name)) => {
1614 if let Some(resolved) = bindings.get(param_name) {
1615 for r_atomic in &resolved.types {
1616 let iface_name = if let Atomic::TNamedObject { fqcn, .. } = r_atomic {
1617 Some(*fqcn)
1618 } else {
1619 None
1620 };
1621 result.add_type(Atomic::TInterfaceString(iface_name));
1622 }
1623 } else {
1624 result.add_type(atomic.clone());
1625 }
1626 }
1627 _ => {
1628 result.add_type(atomic.clone());
1629 }
1630 }
1631 }
1632 result
1633 }
1634
1635 pub fn resolve_conditional_returns<F>(self, lookup: F) -> Type
1641 where
1642 F: Fn(&str) -> Option<Type>,
1643 {
1644 self.resolve_conditional_inner(&lookup)
1645 }
1646
1647 fn resolve_conditional_inner<F>(self, lookup: &F) -> Type
1648 where
1649 F: Fn(&str) -> Option<Type>,
1650 {
1651 let mut result = Type::empty();
1652 for atomic in self.types {
1653 match atomic {
1654 Atomic::TConditional { ref data } => {
1655 let (param_name, subject, if_true, if_false) = (
1656 &data.param_name,
1657 &data.subject,
1658 &data.if_true,
1659 &data.if_false,
1660 );
1661 let resolved =
1662 param_name
1663 .and_then(|name| lookup(name.as_ref()))
1664 .and_then(|arg_ty| {
1665 resolve_conditional_branch(subject, &arg_ty, if_true, if_false)
1666 });
1667
1668 if let Some(branch) = resolved {
1669 for t in branch.resolve_conditional_inner(lookup).types {
1671 result.add_type(t);
1672 }
1673 } else {
1674 for t in if_true.clone().resolve_conditional_inner(lookup).types {
1677 result.add_type(t);
1678 }
1679 for t in if_false.clone().resolve_conditional_inner(lookup).types {
1680 result.add_type(t);
1681 }
1682 }
1683 }
1684 other => result.add_type(other),
1685 }
1686 }
1687 result
1688 }
1689
1690 pub fn is_subtype_structural(&self, other: &Type) -> bool {
1700 if other.is_mixed() {
1701 return true;
1702 }
1703 if self.is_never() {
1704 return true; }
1706 self.types.iter().all(|a| {
1707 let fits = |a: &Atomic| other.accepts_atomic_structural(a);
1708 fits(a) || composite_parts(a).is_some_and(|parts| parts.iter().all(fits))
1709 })
1710 }
1711
1712 pub fn is_subtype_by_template_bounds(&self, other: &Type) -> bool {
1715 self.is_subtype_structural(other)
1716 || self.types.iter().all(|a| match a {
1717 Atomic::TTemplateParam { as_type, .. } => {
1718 as_type.is_subtype_by_template_bounds(other)
1719 }
1720 _ => other.accepts_atomic_structural(a),
1721 })
1722 }
1723
1724 pub fn accepts_atomic_structural(&self, sub: &Atomic) -> bool {
1728 if self.is_mixed() {
1729 return true;
1730 }
1731 let int_skips_float = sub.is_int() && self.types.iter().any(Atomic::is_int);
1733 matches!(sub, Atomic::TNever)
1734 || self.types.iter().any(|b| {
1735 !(int_skips_float && matches!(b, Atomic::TFloat)) && atomic_subtype(sub, b)
1736 })
1737 }
1738
1739 fn filter<F: Fn(&Atomic) -> bool>(&self, f: F) -> Type {
1742 let mut result = Type::empty();
1743 result.possibly_undefined = self.possibly_undefined;
1744 result.from_docblock = self.from_docblock;
1745 for atomic in &self.types {
1746 if f(atomic) {
1747 result.types.push(atomic.clone());
1748 }
1749 }
1750 result
1751 }
1752
1753 fn filter_replacing<K: Fn(&Atomic) -> bool, P: Fn(&Atomic) -> bool>(
1758 &self,
1759 keep: K,
1760 placeholder: P,
1761 replacement: Atomic,
1762 ) -> Type {
1763 let mut result = Type::empty();
1764 result.possibly_undefined = self.possibly_undefined;
1765 result.from_docblock = self.from_docblock;
1766 for atomic in &self.types {
1767 if keep(atomic) {
1768 result.add_type(atomic.clone());
1769 } else if placeholder(atomic) {
1770 result.add_type(replacement.clone());
1771 }
1772 }
1773 result
1774 }
1775
1776 pub fn possibly_undefined(mut self) -> Self {
1778 self.possibly_undefined = true;
1779 self
1780 }
1781
1782 pub fn from_docblock(mut self) -> Self {
1784 self.from_docblock = true;
1785 self
1786 }
1787
1788 pub fn falsy_stripped(mut self) -> Self {
1791 self.falsy_stripped = true;
1792 self
1793 }
1794
1795 pub fn possibly_absent_offset(mut self) -> Self {
1799 self.possibly_absent_offset = true;
1800 self
1801 }
1802}
1803
1804#[derive(Clone, PartialEq, Eq, Debug)]
1818enum ValueClass {
1819 Int,
1820 Float,
1821 True,
1822 False,
1823 String,
1824 Array,
1825 List,
1827 Object,
1828 Resource,
1829 Null,
1830 Top,
1833 LitInt(i64),
1836 LitFloat(i64, i64),
1838 LitString(Arc<str>),
1840 ClassString,
1842}
1843
1844impl ValueClass {
1845 fn includes(&self, b: &Self) -> bool {
1850 self == b
1851 || matches!(
1852 (self, b),
1853 (Self::Top, _)
1854 | (Self::Int, Self::LitInt(_))
1855 | (Self::Float, Self::LitFloat(..))
1856 | (Self::String, Self::LitString(_))
1857 | (Self::String, Self::ClassString)
1858 | (Self::Array, Self::List)
1859 )
1860 }
1861
1862 fn overlaps(&self, b: &Self) -> bool {
1864 self.includes(b)
1865 || b.includes(self)
1866 || matches!(
1867 (self, b),
1868 (Self::ClassString, Self::LitString(_)) | (Self::LitString(_), Self::ClassString)
1869 )
1870 }
1871}
1872
1873fn value_classes(a: &Atomic) -> Vec<ValueClass> {
1879 use ValueClass::*;
1880 match a {
1881 Atomic::TInt
1884 | Atomic::TIntRange { .. }
1885 | Atomic::TPositiveInt
1886 | Atomic::TNegativeInt
1887 | Atomic::TNonNegativeInt
1888 | Atomic::TRefinedInt(_) => vec![Int],
1889 Atomic::TLiteralInt(v) => vec![LitInt(*v)],
1890 Atomic::TFloat | Atomic::TIntegralFloat => vec![Float],
1892 Atomic::TLiteralFloat(int_bits, frac_bits) => {
1893 vec![LitFloat(*int_bits, *frac_bits)]
1894 }
1895 Atomic::TBool => vec![True, False],
1897 Atomic::TTrue => vec![True],
1898 Atomic::TFalse => vec![False],
1899 Atomic::TString
1901 | Atomic::TNonEmptyString
1902 | Atomic::TNonFalsyString
1903 | Atomic::TRefinedString { .. }
1904 | Atomic::TNumericString
1905 | Atomic::TCallableString => vec![String],
1906 Atomic::TClassString(_)
1907 | Atomic::TInterfaceString(_)
1908 | Atomic::TEnumString
1909 | Atomic::TTraitString => vec![ClassString],
1910 Atomic::TLiteralString(s) => vec![LitString(s.clone())],
1911 Atomic::TArray { .. }
1913 | Atomic::TPropertiesOf { .. }
1914 | Atomic::TNonEmptyArray { .. }
1915 | Atomic::TKeyedArray { is_list: false, .. } => vec![Array],
1916 Atomic::TList { .. }
1917 | Atomic::TNonEmptyList { .. }
1918 | Atomic::TKeyedArray { is_list: true, .. } => vec![List],
1919 Atomic::TObject
1921 | Atomic::TObjectShape { .. }
1922 | Atomic::TNamedObject { .. }
1923 | Atomic::TStaticObject { .. }
1924 | Atomic::TSelf { .. }
1925 | Atomic::TParent { .. }
1926 | Atomic::TClosure { .. }
1927 | Atomic::TLiteralEnumCase { .. } => vec![Object],
1928 Atomic::TNull => vec![Null],
1931 Atomic::TResource | Atomic::TClosedResource => vec![Resource],
1932 Atomic::TVoid => vec![Top],
1933 Atomic::TMixed => vec![Top],
1935 Atomic::TScalar => vec![Int, Float, True, False, String],
1936 Atomic::TNumeric => vec![Int, Float],
1939 Atomic::TCallable { .. }
1941 | Atomic::TNever
1942 | Atomic::TTemplateParam { .. }
1943 | Atomic::TKeyOf { .. }
1944 | Atomic::TValueOf { .. }
1945 | Atomic::TConditional { .. }
1946 | Atomic::TIntersection { .. } => Vec::new(),
1947 }
1948}
1949
1950fn subject_is_decidable(subject: &Atomic) -> bool {
1958 matches!(
1959 subject,
1960 Atomic::TNull
1961 | Atomic::TTrue
1962 | Atomic::TFalse
1963 | Atomic::TBool
1964 | Atomic::TString
1965 | Atomic::TClassString(None)
1966 | Atomic::TInt
1967 | Atomic::TFloat
1968 | Atomic::TLiteralString(_)
1969 | Atomic::TLiteralInt(_)
1970 | Atomic::TLiteralFloat(..)
1971 | Atomic::TArray { .. }
1972 | Atomic::TList { .. }
1973 | Atomic::TObject
1974 | Atomic::TObjectShape { .. }
1975 | Atomic::TResource
1976 | Atomic::TMixed
1977 | Atomic::TScalar
1978 )
1979}
1980
1981fn resolve_conditional_branch(
2003 subject: &Type,
2004 arg_ty: &Type,
2005 if_true: &Type,
2006 if_false: &Type,
2007) -> Option<Type> {
2008 if arg_ty.types.is_empty() {
2009 return None;
2010 }
2011 if let [Atomic::TVoid] = subject.types.as_slice() {
2013 return match arg_ty.types.as_slice() {
2014 [Atomic::TVoid] => Some(if_true.clone()),
2015 types
2016 if types.iter().all(|a| {
2017 !matches!(a, Atomic::TVoid | Atomic::TMixed | Atomic::TNull)
2018 && !value_classes(a).is_empty()
2019 }) =>
2020 {
2021 Some(if_false.clone())
2022 }
2023 _ => None,
2024 };
2025 }
2026 if subject.types.is_empty() || !subject.types.iter().all(subject_is_decidable) {
2027 return None;
2028 }
2029 let subject_classes: Vec<ValueClass> = subject.types.iter().flat_map(value_classes).collect();
2030 let arg_classes: Vec<ValueClass> = arg_ty.types.iter().flat_map(value_classes).collect();
2031 if arg_classes.is_empty() {
2032 return None;
2034 }
2035 let all_match = arg_classes
2036 .iter()
2037 .all(|c| subject_classes.iter().any(|s| s.includes(c)));
2038 let any_overlap = arg_classes
2039 .iter()
2040 .any(|c| subject_classes.iter().any(|s| s.overlaps(c)));
2041 if all_match {
2042 Some(if_true.clone())
2043 } else if !any_overlap {
2044 Some(if_false.clone())
2045 } else {
2046 None
2047 }
2048}
2049
2050fn atomic_may_contain_templates(atomic: &Atomic) -> bool {
2058 match atomic {
2059 Atomic::TNamedObject { fqcn, type_params } => {
2063 !type_params.is_empty() || !fqcn.contains('\\')
2064 }
2065 Atomic::TTemplateParam { .. }
2066 | Atomic::TKeyOf { .. }
2067 | Atomic::TValueOf { .. }
2068 | Atomic::TArray { .. }
2069 | Atomic::TList { .. }
2070 | Atomic::TNonEmptyArray { .. }
2071 | Atomic::TNonEmptyList { .. }
2072 | Atomic::TKeyedArray { .. }
2073 | Atomic::TCallable { .. }
2074 | Atomic::TClosure { .. }
2075 | Atomic::TConditional { .. }
2076 | Atomic::TIntersection { .. }
2077 | Atomic::TClassString(Some(_))
2078 | Atomic::TInterfaceString(Some(_)) => true,
2079 _ => false,
2080 }
2081}
2082
2083pub fn eval_key_of_type(t: &Type) -> Option<Type> {
2084 let mut result = Type::empty();
2085 for atomic in &t.types {
2086 match atomic {
2087 Atomic::TArray { key, .. } | Atomic::TNonEmptyArray { key, .. } => {
2088 for k in &key.types {
2089 result.add_type(k.clone());
2090 }
2091 }
2092 Atomic::TList { .. } | Atomic::TNonEmptyList { .. } => {
2093 result.add_type(Atomic::TInt);
2094 }
2095 Atomic::TKeyedArray { properties, .. } => {
2096 for key in properties.keys() {
2097 match key {
2098 crate::atomic::ArrayKey::Int(n) => result.add_type(Atomic::TLiteralInt(*n)),
2099 crate::atomic::ArrayKey::String(s) => {
2100 result.add_type(Atomic::TLiteralString(s.clone()))
2101 }
2102 }
2103 }
2104 }
2105 _ => return None,
2106 }
2107 }
2108 (!result.types.is_empty()).then_some(result)
2109}
2110
2111pub fn eval_value_of_type(t: &Type) -> Option<Type> {
2112 let mut result = Type::empty();
2113 for atomic in &t.types {
2114 match atomic {
2115 Atomic::TArray { value, .. }
2116 | Atomic::TNonEmptyArray { value, .. }
2117 | Atomic::TList { value }
2118 | Atomic::TNonEmptyList { value } => {
2119 result.merge_with(value);
2120 }
2121 Atomic::TKeyedArray { properties, .. } => {
2122 for prop in properties.values() {
2123 result.merge_with(&prop.ty);
2124 }
2125 }
2126 _ => return None,
2127 }
2128 }
2129 (!result.types.is_empty()).then_some(result)
2130}
2131
2132fn substitute_in_fn_param(
2133 p: &crate::atomic::FnParam,
2134 bindings: &FxHashMap<Name, Type>,
2135) -> crate::atomic::FnParam {
2136 crate::atomic::FnParam {
2137 name: p.name,
2138 ty: p.ty.as_ref().map(|t| {
2139 let u = t.to_union();
2140 let substituted = u.substitute_templates(bindings);
2141 crate::compact::SimpleType::from_union(substituted)
2142 }),
2143 out_ty: p.out_ty.as_ref().map(|t| {
2144 let u = t.to_union();
2145 let substituted = u.substitute_templates(bindings);
2146 crate::compact::SimpleType::from_union(substituted)
2147 }),
2148 default: p.default.as_ref().map(|d| {
2149 let u = d.to_union();
2150 let substituted = u.substitute_templates(bindings);
2151 crate::compact::SimpleType::from_union(substituted)
2152 }),
2153 is_variadic: p.is_variadic,
2154 is_byref: p.is_byref,
2155 is_optional: p.is_optional,
2156 }
2157}
2158
2159fn composite_parts(atomic: &Atomic) -> Option<&'static [Atomic]> {
2166 match atomic {
2167 Atomic::TScalar => Some(&[Atomic::TInt, Atomic::TFloat, Atomic::TString, Atomic::TBool]),
2168 Atomic::TNumeric => Some(&[Atomic::TInt, Atomic::TFloat, Atomic::TNumericString]),
2169 _ => None,
2170 }
2171}
2172
2173fn object_shape_subtype(have: &KeyedProperties, want: &KeyedProperties) -> bool {
2174 want.iter().all(|(name, wanted)| match have.get(name) {
2175 Some(had) => (wanted.optional || !had.optional) && had.ty.is_subtype_structural(&wanted.ty),
2176 None => wanted.optional,
2177 })
2178}
2179
2180pub fn atomic_subtype(sub: &Atomic, sup: &Atomic) -> bool {
2182 if sub == sup {
2183 return true;
2184 }
2185 let string_keyed_array = || Atomic::TArray {
2187 key: Box::new(Type::string()),
2188 value: Box::new(Type::mixed()),
2189 };
2190 match (sub, sup) {
2191 (Atomic::TClosedResource, _) => return atomic_subtype(&Atomic::TResource, sup),
2192 (Atomic::TPropertiesOf { .. }, _) => return atomic_subtype(&string_keyed_array(), sup),
2193 (_, Atomic::TPropertiesOf { .. }) => return atomic_subtype(sub, &string_keyed_array()),
2194 (Atomic::TObjectShape { properties: have }, Atomic::TObjectShape { properties: want }) => {
2195 return object_shape_subtype(have, want);
2196 }
2197 (Atomic::TObjectShape { .. }, _) => return atomic_subtype(&Atomic::TObject, sup),
2198 (_, Atomic::TObjectShape { .. }) => return atomic_subtype(sub, &Atomic::TObject),
2200 _ => {}
2201 }
2202 match (sub, sup) {
2203 (Atomic::TNever, _) => true,
2205 (_, Atomic::TMixed) => true,
2207 (Atomic::TMixed, _) => true,
2208 (_, Atomic::TTemplateParam { as_type, .. }) => {
2213 as_type.is_mixed() || as_type.types.iter().any(|b| atomic_subtype(sub, b))
2214 }
2215
2216 (Atomic::TLiteralInt(_), Atomic::TInt) => true,
2218 (Atomic::TLiteralInt(_), Atomic::TNumeric) => true,
2219 (Atomic::TLiteralInt(_), Atomic::TScalar) => true,
2220 (Atomic::TLiteralInt(_), Atomic::TRefinedInt(IntRefinement::Literal)) => true,
2221 (Atomic::TRefinedInt(_), _) => atomic_subtype(&Atomic::TInt, sup),
2222 (_, Atomic::TRefinedInt(IntRefinement::Literal)) => false,
2223 (_, Atomic::TRefinedInt(IntRefinement::MaskOf(_))) => atomic_subtype(sub, &Atomic::TInt),
2225 (Atomic::TLiteralInt(n), Atomic::TPositiveInt) => *n > 0,
2226 (Atomic::TLiteralInt(n), Atomic::TNonNegativeInt) => *n >= 0,
2227 (Atomic::TLiteralInt(n), Atomic::TNegativeInt) => *n < 0,
2228 (Atomic::TPositiveInt, Atomic::TInt) => true,
2229 (Atomic::TPositiveInt, Atomic::TNonNegativeInt) => true,
2230 (Atomic::TPositiveInt, Atomic::TNumeric) => true,
2231 (Atomic::TPositiveInt, Atomic::TScalar) => true,
2232 (Atomic::TNegativeInt, Atomic::TInt) => true,
2233 (Atomic::TNegativeInt, Atomic::TNumeric) => true,
2234 (Atomic::TNegativeInt, Atomic::TScalar) => true,
2235 (Atomic::TNonNegativeInt, Atomic::TInt) => true,
2236 (Atomic::TNonNegativeInt, Atomic::TNumeric) => true,
2237 (Atomic::TNonNegativeInt, Atomic::TScalar) => true,
2238 (Atomic::TIntRange { .. }, Atomic::TInt) => true,
2239 (Atomic::TIntRange { .. }, Atomic::TNumeric) => true,
2240 (Atomic::TIntRange { .. }, Atomic::TScalar) => true,
2241 (Atomic::TPositiveInt, Atomic::TIntRange { min, max }) => {
2243 max.is_none() && min.is_none_or(|m| m <= 1)
2244 }
2245 (Atomic::TNegativeInt, Atomic::TIntRange { min, max }) => {
2247 min.is_none() && max.is_none_or(|m| m >= -1)
2248 }
2249 (Atomic::TNonNegativeInt, Atomic::TIntRange { min, max }) => {
2251 max.is_none() && min.is_none_or(|m| m <= 0)
2252 }
2253 (Atomic::TIntRange { min: sub_min, .. }, Atomic::TPositiveInt) => {
2255 sub_min.is_some_and(|lo| lo >= 1)
2256 }
2257 (Atomic::TIntRange { min: sub_min, .. }, Atomic::TNonNegativeInt) => {
2258 sub_min.is_some_and(|lo| lo >= 0)
2259 }
2260 (Atomic::TIntRange { max: sub_max, .. }, Atomic::TNegativeInt) => {
2261 sub_max.is_some_and(|hi| hi <= -1)
2262 }
2263 (
2265 Atomic::TIntRange {
2266 min: sub_min,
2267 max: sub_max,
2268 },
2269 Atomic::TIntRange {
2270 min: sup_min,
2271 max: sup_max,
2272 },
2273 ) => {
2274 let lower_ok = match (sub_min, sup_min) {
2275 (_, None) => true,
2276 (None, Some(_)) => false,
2277 (Some(sl), Some(su)) => sl >= su,
2278 };
2279 let upper_ok = match (sub_max, sup_max) {
2280 (None, None) | (Some(_), None) => true,
2281 (None, Some(_)) => false,
2282 (Some(sl), Some(su)) => sl <= su,
2283 };
2284 lower_ok && upper_ok
2285 }
2286
2287 (Atomic::TLiteralFloat(..), Atomic::TFloat) => true,
2288 (Atomic::TLiteralFloat(..), Atomic::TNumeric) => true,
2289 (Atomic::TLiteralFloat(..), Atomic::TScalar) => true,
2290
2291 (Atomic::TLiteralString(s), Atomic::TString) => {
2292 let _ = s;
2293 true
2294 }
2295 (Atomic::TLiteralString(s), Atomic::TCallableString) => {
2296 let _ = s;
2297 true
2298 }
2299 (Atomic::TLiteralString(s), Atomic::TNonEmptyString) => !s.is_empty(),
2300 (Atomic::TLiteralString(s), Atomic::TNonFalsyString) => !s.is_empty() && s.as_ref() != "0",
2301 (Atomic::TNonEmptyString | Atomic::TNumericString, Atomic::TNonFalsyString) => false,
2303 (Atomic::TNonFalsyString, _) => atomic_subtype(&Atomic::TNonEmptyString, sup),
2305 (_, Atomic::TNonFalsyString) => atomic_subtype(sub, &Atomic::TNonEmptyString),
2306 (
2307 Atomic::TLiteralString(s),
2308 Atomic::TRefinedString {
2309 refinement,
2310 non_empty,
2311 },
2312 ) => refinement.accepts(s) && !(*non_empty && s.is_empty()),
2313 (
2315 Atomic::TClassString(Some(_)),
2316 Atomic::TRefinedString {
2317 refinement: StringRefinement::Literal,
2318 ..
2319 },
2320 ) => true,
2321 (
2322 Atomic::TRefinedString {
2323 refinement: have,
2324 non_empty: have_non_empty,
2325 },
2326 Atomic::TRefinedString {
2327 refinement: want,
2328 non_empty: want_non_empty,
2329 },
2330 ) => have == want && (*have_non_empty || !want_non_empty),
2331 (
2333 Atomic::TRefinedString {
2334 refinement: StringRefinement::DecimalInt,
2335 ..
2336 },
2337 _,
2338 ) => atomic_subtype(&Atomic::TNumericString, sup),
2339 (Atomic::TRefinedString { non_empty, .. }, _) => {
2340 let base = if *non_empty {
2341 Atomic::TNonEmptyString
2342 } else {
2343 Atomic::TString
2344 };
2345 atomic_subtype(&base, sup)
2346 }
2347 (_, Atomic::TRefinedString { .. }) => false,
2348 (Atomic::TLiteralString(s), Atomic::TNumericString | Atomic::TNumeric) => {
2349 s.parse::<f64>().is_ok()
2350 }
2351 (Atomic::TLiteralString(_), Atomic::TClassString(_)) => true,
2354 (Atomic::TLiteralString(_), Atomic::TInterfaceString(_)) => true,
2357 (Atomic::TLiteralString(_), Atomic::TScalar) => true,
2358 (Atomic::TNonEmptyString, Atomic::TString) => true,
2359 (Atomic::TCallableString, Atomic::TString) => true,
2360 (Atomic::TNumericString, Atomic::TNonEmptyString) => true,
2362 (Atomic::TNumericString, Atomic::TString) => true,
2363 (Atomic::TClassString(_), Atomic::TNonEmptyString) => true,
2367 (Atomic::TInterfaceString(_), Atomic::TNonEmptyString) => true,
2368 (Atomic::TCallableString, Atomic::TNonEmptyString) => true,
2369 (Atomic::TEnumString, Atomic::TNonEmptyString) => true,
2370 (Atomic::TTraitString, Atomic::TNonEmptyString) => true,
2371 (Atomic::TClassString(_), Atomic::TString) => true,
2372 (Atomic::TInterfaceString(_), Atomic::TString) => true,
2373 (Atomic::TInterfaceString(_), Atomic::TClassString(None)) => true,
2378 (Atomic::TClassString(Some(_)), Atomic::TClassString(None)) => true,
2379 (Atomic::TInterfaceString(Some(a)), Atomic::TClassString(Some(b))) => a == b,
2380 (Atomic::TEnumString, Atomic::TString) => true,
2381 (Atomic::TTraitString, Atomic::TString) => true,
2382
2383 (Atomic::TTrue, Atomic::TBool) => true,
2384 (Atomic::TFalse, Atomic::TBool) => true,
2385
2386 (Atomic::TInt, Atomic::TNumeric) => true,
2387 (Atomic::TFloat, Atomic::TNumeric) => true,
2388 (Atomic::TIntegralFloat, Atomic::TNumeric) => true,
2389 (Atomic::TNumericString, Atomic::TNumeric) => true,
2390
2391 (Atomic::TInt, Atomic::TScalar) => true,
2392 (Atomic::TFloat, Atomic::TScalar) => true,
2393 (Atomic::TIntegralFloat, Atomic::TScalar) => true,
2394 (Atomic::TString, Atomic::TScalar) => true,
2395 (Atomic::TBool, Atomic::TScalar) => true,
2396 (Atomic::TNumeric, Atomic::TScalar) => true,
2397 (Atomic::TTrue, Atomic::TScalar) => true,
2398 (Atomic::TFalse, Atomic::TScalar) => true,
2399 (Atomic::TNonEmptyString, Atomic::TScalar) => true,
2403 (Atomic::TNumericString, Atomic::TScalar) => true,
2404 (Atomic::TCallableString, Atomic::TScalar) => true,
2405 (Atomic::TClassString(_), Atomic::TScalar) => true,
2406 (Atomic::TInterfaceString(_), Atomic::TScalar) => true,
2407 (Atomic::TEnumString, Atomic::TScalar) => true,
2408 (Atomic::TTraitString, Atomic::TScalar) => true,
2409
2410 (Atomic::TNamedObject { .. }, Atomic::TObject) => true,
2412 (Atomic::TStaticObject { .. }, Atomic::TObject) => true,
2413 (Atomic::TSelf { .. }, Atomic::TObject) => true,
2414 (Atomic::TLiteralEnumCase { .. }, Atomic::TObject) => true,
2416 (Atomic::TSelf { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
2418 (Atomic::TStaticObject { fqcn: a }, Atomic::TNamedObject { fqcn: b, .. }) => a == b,
2419 (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TSelf { fqcn: b }) => a == b,
2421 (Atomic::TNamedObject { fqcn: a, .. }, Atomic::TStaticObject { fqcn: b }) => a == b,
2422 (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TNamedObject { fqcn, .. }) => {
2425 enum_fqcn == fqcn
2426 }
2427 (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TSelf { fqcn })
2428 | (Atomic::TLiteralEnumCase { enum_fqcn, .. }, Atomic::TStaticObject { fqcn }) => {
2429 enum_fqcn == fqcn
2430 }
2431 (
2435 Atomic::TNamedObject {
2436 fqcn: sub_fqcn,
2437 type_params: sub_params,
2438 },
2439 Atomic::TNamedObject {
2440 fqcn: sup_fqcn,
2441 type_params: sup_params,
2442 },
2443 ) => {
2444 sub_fqcn == sup_fqcn
2445 && (sup_params.is_empty() || type_params_compatible(sub_params, sup_params))
2446 }
2447
2448 (Atomic::TIntegralFloat, Atomic::TFloat) => true,
2450
2451 (Atomic::TLiteralInt(_), Atomic::TFloat) => true,
2453 (Atomic::TPositiveInt, Atomic::TFloat) => true,
2454 (Atomic::TNegativeInt, Atomic::TFloat) => true,
2455 (Atomic::TNonNegativeInt, Atomic::TFloat) => true,
2456 (Atomic::TInt, Atomic::TFloat) => true,
2457 (Atomic::TIntRange { .. }, Atomic::TFloat) => true,
2458
2459 (Atomic::TLiteralInt(n), Atomic::TIntRange { min, max }) => {
2461 min.is_none_or(|lo| *n >= lo) && max.is_none_or(|hi| *n <= hi)
2462 }
2463
2464 (Atomic::TString, Atomic::TCallable { .. }) => true,
2466 (Atomic::TCallableString, Atomic::TCallable { .. }) => true,
2467 (Atomic::TNonEmptyString, Atomic::TCallable { .. }) => true,
2468 (Atomic::TLiteralString(_), Atomic::TCallable { .. }) => true,
2469 (Atomic::TArray { .. }, Atomic::TCallable { .. }) => true,
2470 (Atomic::TNonEmptyArray { .. }, Atomic::TCallable { .. }) => true,
2471 (Atomic::TKeyedArray { .. }, Atomic::TCallable { .. }) => true,
2472
2473 (Atomic::TClosure { .. }, Atomic::TCallable { .. }) => true,
2475 (Atomic::TCallable { .. }, Atomic::TClosure { .. }) => true,
2477 (Atomic::TClosure { data: sub }, Atomic::TClosure { data: sup }) => {
2487 fn has_nominal_type(t: &Type) -> bool {
2488 t.types.iter().any(|a| {
2489 matches!(
2490 a,
2491 Atomic::TNamedObject { .. }
2492 | Atomic::TSelf { .. }
2493 | Atomic::TStaticObject { .. }
2494 | Atomic::TTemplateParam { .. }
2495 | Atomic::TClosure { .. }
2496 | Atomic::TCallable { .. }
2497 )
2498 })
2499 }
2500 let sub_required = sub
2501 .params
2502 .iter()
2503 .filter(|p| !p.is_optional && !p.is_variadic)
2504 .count();
2505 if sub_required > sup.params.len() {
2506 false
2507 } else {
2508 let params_ok = sup.params.iter().enumerate().all(|(i, sup_param)| {
2509 let Some(sub_param) = sub.params.get(i) else {
2510 return true;
2511 };
2512 if sub_param.is_optional || sub_param.is_variadic {
2513 return true;
2514 }
2515 let (Some(sub_ty), Some(sup_ty)) =
2516 (sub_param.ty.as_ref(), sup_param.ty.as_ref())
2517 else {
2518 return true;
2519 };
2520 let (sub_u, sup_u) = (sub_ty.to_union(), sup_ty.to_union());
2521 if has_nominal_type(&sub_u) || has_nominal_type(&sup_u) {
2522 return true;
2523 }
2524 sup_u.is_subtype_structural(&sub_u)
2527 });
2528 params_ok
2529 && (sub.return_type.is_mixed()
2530 || sup.return_type.is_mixed()
2531 || sup.return_type.is_void()
2535 || has_nominal_type(&sub.return_type)
2536 || has_nominal_type(&sup.return_type)
2537 || sub.return_type.is_subtype_structural(&sup.return_type))
2538 }
2539 }
2540 (Atomic::TCallable { .. }, Atomic::TCallable { .. }) => true,
2542 (Atomic::TClosure { .. }, Atomic::TNamedObject { fqcn, .. }) => {
2544 fqcn.as_ref().eq_ignore_ascii_case("closure")
2545 }
2546 (Atomic::TClosure { .. }, Atomic::TObject) => true,
2547 (Atomic::TNamedObject { fqcn, .. }, Atomic::TClosure { .. }) => {
2549 fqcn.as_ref().eq_ignore_ascii_case("closure")
2550 }
2551 (Atomic::TNamedObject { fqcn, .. }, Atomic::TCallable { .. }) => {
2553 fqcn.as_ref().eq_ignore_ascii_case("closure")
2554 }
2555
2556 (
2564 Atomic::TIntersection { parts: sub_parts },
2565 Atomic::TIntersection { parts: sup_parts },
2566 ) => sup_parts.iter().all(|sup_part| {
2567 sub_parts
2568 .iter()
2569 .any(|sub_part| sub_part.is_subtype_structural(sup_part))
2570 }),
2571 (Atomic::TIntersection { parts }, Atomic::TObject) => parts
2572 .iter()
2573 .any(|part| part.is_subtype_structural(&Type::single(Atomic::TObject))),
2574
2575 (Atomic::TList { value }, Atomic::TArray { key, value: av }) => {
2577 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2578 }
2579 (Atomic::TNonEmptyList { value }, Atomic::TArray { key, value: av }) => {
2580 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2581 }
2582 (Atomic::TNonEmptyList { value }, Atomic::TNonEmptyArray { key, value: av }) => {
2583 Type::single(Atomic::TInt).is_subtype_structural(key) && value.is_subtype_structural(av)
2584 }
2585 (Atomic::TNonEmptyList { value }, Atomic::TList { value: lv }) => {
2586 value.is_subtype_structural(lv)
2587 }
2588 (Atomic::TNonEmptyList { value: v1 }, Atomic::TNonEmptyList { value: v2 }) => {
2589 v1.is_subtype_structural(v2)
2590 }
2591 (Atomic::TArray { key, value: av }, Atomic::TList { value: lv }) => {
2593 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2594 && av.is_subtype_structural(lv)
2595 }
2596 (Atomic::TArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
2597 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2598 && av.is_subtype_structural(lv)
2599 }
2600 (Atomic::TNonEmptyArray { key, value: av }, Atomic::TList { value: lv }) => {
2601 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2602 && av.is_subtype_structural(lv)
2603 }
2604 (Atomic::TNonEmptyArray { key, value: av }, Atomic::TNonEmptyList { value: lv }) => {
2605 matches!(key.types.as_slice(), [Atomic::TInt | Atomic::TMixed])
2606 && av.is_subtype_structural(lv)
2607 }
2608 (Atomic::TList { value: v1 }, Atomic::TList { value: v2 }) => v1.is_subtype_structural(v2),
2610 (Atomic::TNonEmptyArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
2611 k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
2612 }
2613
2614 (Atomic::TArray { key: k1, value: v1 }, Atomic::TArray { key: k2, value: v2 }) => {
2616 k1.is_subtype_structural(k2) && v1.is_subtype_structural(v2)
2617 }
2618
2619 (Atomic::TKeyedArray { properties, .. }, Atomic::TArray { key, value }) => {
2628 properties.iter().all(|(prop_key, prop)| {
2629 let key_atomic = match prop_key {
2630 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2631 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2632 };
2633 if !Type::single(key_atomic).is_subtype_structural(key) {
2634 return false; }
2636 let has_named_obj = prop.ty.types.iter().any(|a| {
2638 matches!(
2639 a,
2640 Atomic::TNamedObject { .. }
2641 | Atomic::TSelf { .. }
2642 | Atomic::TStaticObject { .. }
2643 | Atomic::TClosure { .. }
2644 | Atomic::TTemplateParam { .. }
2645 )
2646 });
2647 has_named_obj || prop.ty.is_subtype_structural(value)
2648 })
2649 }
2650 (
2651 Atomic::TKeyedArray {
2652 properties,
2653 is_open,
2654 ..
2655 },
2656 Atomic::TNonEmptyArray { key, value },
2657 ) => {
2658 (*is_open || properties.iter().any(|(_, p)| !p.optional))
2659 && properties.iter().all(|(prop_key, prop)| {
2660 let key_atomic = match prop_key {
2661 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2662 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2663 };
2664 if !Type::single(key_atomic).is_subtype_structural(key) {
2665 return false;
2666 }
2667 let has_named_obj = prop.ty.types.iter().any(|a| {
2668 matches!(
2669 a,
2670 Atomic::TNamedObject { .. }
2671 | Atomic::TSelf { .. }
2672 | Atomic::TStaticObject { .. }
2673 | Atomic::TClosure { .. }
2674 | Atomic::TTemplateParam { .. }
2675 )
2676 });
2677 has_named_obj || prop.ty.is_subtype_structural(value)
2678 })
2679 }
2680
2681 (
2683 Atomic::TKeyedArray {
2684 properties,
2685 is_list,
2686 ..
2687 },
2688 Atomic::TList { value: lv },
2689 ) => *is_list && properties.values().all(|p| p.ty.is_subtype_structural(lv)),
2690 (
2691 Atomic::TKeyedArray {
2692 properties,
2693 is_list,
2694 ..
2695 },
2696 Atomic::TNonEmptyList { value: lv },
2697 ) => {
2698 *is_list
2699 && !properties.is_empty()
2700 && properties.values().all(|p| p.ty.is_subtype_structural(lv))
2701 }
2702
2703 (
2708 Atomic::TKeyedArray {
2709 properties: sub_props,
2710 is_open: sub_open,
2711 is_list: sub_list,
2712 },
2713 Atomic::TKeyedArray {
2714 properties: sup_props,
2715 is_open: sup_open,
2716 is_list: sup_list,
2717 },
2718 ) => {
2719 if *sup_list
2721 && !*sub_list
2722 && sub_props
2723 .keys()
2724 .enumerate()
2725 .any(|(i, k)| *k != crate::atomic::ArrayKey::Int(i as i64))
2726 {
2727 return false;
2728 }
2729 let value_fits = |sub: &Type, sup: &Type| {
2731 if sub.is_subtype_by_template_bounds(sup) {
2732 return true;
2733 }
2734 let has_template = sup
2735 .types
2736 .iter()
2737 .any(|a| matches!(a, Atomic::TTemplateParam { .. }));
2738 let has_class = sup.types.iter().any(|a| {
2739 matches!(
2740 a,
2741 Atomic::TNamedObject { .. }
2742 | Atomic::TSelf { .. }
2743 | Atomic::TStaticObject { .. }
2744 | Atomic::TClosure { .. }
2745 )
2746 });
2747 has_template
2748 || (has_class && !sub.types.iter().all(Atomic::is_definitely_non_object))
2749 };
2750 let keys_satisfied = sup_props
2751 .iter()
2752 .all(|(key, sup_prop)| match sub_props.get(key) {
2753 Some(sub_prop) => {
2754 if !sup_prop.optional && sub_prop.optional {
2758 return false;
2759 }
2760 value_fits(&sub_prop.ty, &sup_prop.ty)
2761 }
2762 None => {
2763 sup_prop.optional
2764 || (*sub_open
2765 && sub_props
2766 .remainder
2767 .as_ref()
2768 .is_none_or(|rest| value_fits(rest, &sup_prop.ty)))
2769 }
2770 });
2771 let no_undeclared_extras = sub_props.iter().all(|(k, sub_prop)| {
2772 sup_props.contains_key(k)
2773 || match &sup_props.remainder {
2774 Some(rest) => value_fits(&sub_prop.ty, rest),
2775 None => *sup_open,
2776 }
2777 });
2778 keys_satisfied && no_undeclared_extras
2779 }
2780 (
2786 Atomic::TKeyedArray {
2787 properties,
2788 is_list: true,
2789 ..
2790 },
2791 Atomic::TIntersection { parts },
2792 ) if !properties.is_empty()
2793 && parts.iter().any(|part| {
2794 matches!(
2795 part.types.as_slice(),
2796 [Atomic::TKeyedArray { properties, is_open: true, is_list: false }]
2797 if properties.is_empty()
2798 )
2799 }) =>
2800 {
2801 false
2802 }
2803 (
2804 Atomic::TKeyedArray {
2805 properties,
2806 is_open,
2807 ..
2808 },
2809 Atomic::TIntersection { parts },
2810 ) => parts.iter().all(|part| {
2811 part.types.iter().any(|part_atomic| match part_atomic {
2812 Atomic::TKeyedArray {
2813 properties: sup_props,
2814 is_open: sup_open,
2815 ..
2816 } => {
2817 let keys_satisfied =
2818 sup_props
2819 .iter()
2820 .all(|(key, sup_prop)| match properties.get(key) {
2821 Some(sub_prop) => {
2822 if !sup_prop.optional && sub_prop.optional {
2823 return false;
2824 }
2825 let has_named_obj = sup_prop.ty.types.iter().any(|a| {
2826 matches!(
2827 a,
2828 Atomic::TNamedObject { .. }
2829 | Atomic::TSelf { .. }
2830 | Atomic::TStaticObject { .. }
2831 | Atomic::TClosure { .. }
2832 | Atomic::TTemplateParam { .. }
2833 )
2834 });
2835 has_named_obj
2836 || sub_prop.ty.is_subtype_by_template_bounds(&sup_prop.ty)
2837 || bare_array_may_fit(&sub_prop.ty, &sup_prop.ty)
2838 }
2839 None => *is_open || sup_prop.optional,
2840 });
2841 let has_array_part = parts.iter().any(|part| {
2842 part.types
2843 .iter()
2844 .any(|t| matches!(t, Atomic::TArray { .. }))
2845 });
2846 let has_keyed_array_part = parts.iter().any(|part| {
2847 part.types
2848 .iter()
2849 .any(|t| matches!(t, Atomic::TKeyedArray { .. }))
2850 });
2851 let keys_allowed_by_some_part = if has_array_part {
2852 true
2853 } else if has_keyed_array_part {
2854 properties.keys().all(|k| {
2855 parts.iter().any(|part| {
2856 part.types.iter().any(|t| {
2857 if let Atomic::TKeyedArray {
2858 properties: part_props,
2859 ..
2860 } = t
2861 {
2862 part_props.contains_key(k)
2863 } else {
2864 false
2865 }
2866 })
2867 })
2868 })
2869 } else {
2870 true
2871 };
2872 let no_undeclared_extras = *sup_open || keys_allowed_by_some_part;
2873 keys_satisfied && no_undeclared_extras
2874 }
2875 Atomic::TArray { key, value } => properties.iter().all(|(prop_key, prop)| {
2876 let key_atomic = match prop_key {
2877 crate::atomic::ArrayKey::String(s) => Atomic::TLiteralString(s.clone()),
2878 crate::atomic::ArrayKey::Int(n) => Atomic::TLiteralInt(*n),
2879 };
2880 if !Type::single(key_atomic).is_subtype_structural(key) {
2881 return false;
2882 }
2883 let has_named_obj = prop.ty.types.iter().any(|a| {
2884 matches!(
2885 a,
2886 Atomic::TNamedObject { .. }
2887 | Atomic::TSelf { .. }
2888 | Atomic::TStaticObject { .. }
2889 | Atomic::TClosure { .. }
2890 | Atomic::TTemplateParam { .. }
2891 )
2892 });
2893 has_named_obj || prop.ty.is_subtype_structural(value)
2894 }),
2895 Atomic::TNamedObject { .. }
2896 | Atomic::TSelf { .. }
2897 | Atomic::TStaticObject { .. }
2898 | Atomic::TClosure { .. }
2899 | Atomic::TTemplateParam { .. } => true,
2900 _ => false,
2901 })
2902 }),
2903
2904 _ => false,
2905 }
2906}
2907
2908fn bare_array_may_fit(sub: &Type, sup: &Type) -> bool {
2910 fn array_like(t: &Atomic) -> bool {
2911 match t {
2912 Atomic::TArray { .. }
2913 | Atomic::TNonEmptyArray { .. }
2914 | Atomic::TList { .. }
2915 | Atomic::TNonEmptyList { .. }
2916 | Atomic::TKeyedArray { .. } => true,
2917 Atomic::TIntersection { parts } => parts.iter().all(|p| p.types.iter().all(array_like)),
2918 _ => false,
2919 }
2920 }
2921 matches!(
2922 sub.types.as_slice(),
2923 [Atomic::TArray { key, value }]
2924 if value.is_mixed()
2925 && (key.is_mixed()
2926 || matches!(key.types.as_slice(), [Atomic::TInt, Atomic::TString] | [Atomic::TString, Atomic::TInt]))
2927 ) && sup.types.iter().all(array_like)
2928}
2929
2930fn type_params_compatible(sub: &[Type], sup: &[Type]) -> bool {
2936 if sub.len() != sup.len() {
2937 return false;
2938 }
2939 sub.iter()
2940 .zip(sup.iter())
2941 .all(|(a, b)| a == b || (is_empty_array_literal(a) && is_array_like(b)))
2942}
2943
2944fn is_empty_array_literal(t: &Type) -> bool {
2947 !t.types.is_empty()
2948 && t.types.iter().all(
2949 |atom| matches!(atom, Atomic::TKeyedArray { properties, .. } if properties.is_empty()),
2950 )
2951}
2952
2953fn is_array_like(t: &Type) -> bool {
2955 !t.types.is_empty() && t.types.iter().all(|atom| atom.is_array())
2956}
2957
2958pub struct UnionBuilder {
2965 ty: Type,
2966 strings: std::collections::HashSet<std::sync::Arc<str>>,
2967 ints: std::collections::HashSet<i64>,
2968 literals_independent: bool,
2970}
2971
2972impl Default for UnionBuilder {
2973 fn default() -> Self {
2974 Self::new()
2975 }
2976}
2977
2978impl UnionBuilder {
2979 pub fn new() -> Self {
2980 Self {
2981 ty: Type::empty(),
2982 strings: Default::default(),
2983 ints: Default::default(),
2984 literals_independent: true,
2985 }
2986 }
2987
2988 pub fn is_empty(&self) -> bool {
2989 self.ty.is_empty()
2990 }
2991
2992 pub fn merge(&mut self, other: &Type) {
2993 for a in &other.types {
2994 self.add(a.clone());
2995 }
2996 self.ty.possibly_undefined |= other.possibly_undefined;
2997 }
2998
2999 pub fn add(&mut self, atomic: Atomic) {
3000 let lone_never = matches!(self.ty.types.first(), Some(Atomic::TNever));
3002 if self.literals_independent && !lone_never {
3003 match &atomic {
3004 Atomic::TLiteralString(s) => {
3005 if self.strings.insert(s.clone()) {
3006 self.ty.types.push(atomic);
3007 }
3008 return;
3009 }
3010 Atomic::TLiteralInt(n) => {
3011 if self.ints.insert(*n) {
3012 self.ty.types.push(atomic);
3013 }
3014 return;
3015 }
3016 _ => {}
3017 }
3018 }
3019 let disturbs_literals = matches!(
3020 atomic,
3021 Atomic::TString | Atomic::TMixed | Atomic::TConditional { .. }
3022 ) || int_bounds(&atomic).is_some();
3023 self.ty.add_type(atomic);
3024 if disturbs_literals || lone_never {
3025 self.resync();
3026 }
3027 }
3028
3029 fn resync(&mut self) {
3030 self.strings.clear();
3031 self.ints.clear();
3032 self.literals_independent = true;
3033 for t in &self.ty.types {
3034 match t {
3035 Atomic::TLiteralString(s) => {
3036 self.strings.insert(s.clone());
3037 }
3038 Atomic::TLiteralInt(n) => {
3039 self.ints.insert(*n);
3040 }
3041 Atomic::TMixed | Atomic::TString => self.literals_independent = false,
3042 other if int_bounds(other).is_some() => self.literals_independent = false,
3043 _ => {}
3044 }
3045 }
3046 }
3047
3048 pub fn build(self) -> Type {
3049 self.ty
3050 }
3051}
3052
3053fn callable_array() -> Atomic {
3055 let mut properties = KeyedProperties::with_capacity_and_hasher(2, Default::default());
3056 properties.insert(
3057 ArrayKey::Int(0),
3058 KeyedProperty {
3059 ty: Type::from_vec(vec![Atomic::TClassString(None), Atomic::TObject]),
3060 optional: false,
3061 },
3062 );
3063 properties.insert(
3064 ArrayKey::Int(1),
3065 KeyedProperty {
3066 ty: Type::single(Atomic::TNonEmptyString),
3067 optional: false,
3068 },
3069 );
3070 Atomic::TKeyedArray {
3071 properties: Arc::new(properties),
3072 is_open: false,
3073 is_list: true,
3074 }
3075}
3076
3077#[cfg(test)]
3078mod tests {
3079 use std::sync::Arc;
3080
3081 use super::*;
3082
3083 fn conditional(
3084 param_name: Option<Name>,
3085 subject: Type,
3086 if_true: Type,
3087 if_false: Type,
3088 ) -> Atomic {
3089 Atomic::TConditional {
3090 data: Box::new(crate::atomic::ConditionalData {
3091 param_name,
3092 subject,
3093 if_true,
3094 if_false,
3095 }),
3096 }
3097 }
3098
3099 #[test]
3100 fn single_is_single() {
3101 let u = Type::single(Atomic::TString);
3102 assert!(u.is_single());
3103 assert!(!u.is_nullable());
3104 }
3105
3106 #[test]
3107 fn nullable_has_null() {
3108 let u = Type::nullable(Atomic::TString);
3109 assert!(u.is_nullable());
3110 assert_eq!(u.types.len(), 2);
3111 }
3112
3113 #[test]
3114 fn add_type_deduplicates() {
3115 let mut u = Type::single(Atomic::TString);
3116 u.add_type(Atomic::TString);
3117 assert_eq!(u.types.len(), 1);
3118 }
3119
3120 #[test]
3121 fn array_key_is_int_string() {
3122 let k = Type::array_key();
3123 assert!(k.is_array_key());
3124 assert_eq!(k.types.len(), 2);
3125 }
3126
3127 #[test]
3128 fn is_array_key_false_for_plain_int() {
3129 assert!(!Type::int().is_array_key());
3130 }
3131
3132 #[test]
3133 fn is_array_key_false_for_mixed() {
3134 assert!(!Type::mixed().is_array_key());
3135 }
3136
3137 #[test]
3138 fn is_array_key_false_for_int_string_null() {
3139 let mut u = Type::array_key();
3140 u.add_type(Atomic::TNull);
3141 assert!(!u.is_array_key());
3142 }
3143
3144 #[test]
3145 fn add_type_literal_subsumed_by_base() {
3146 let mut u = Type::single(Atomic::TInt);
3147 u.add_type(Atomic::TLiteralInt(42));
3148 assert_eq!(u.types.len(), 1);
3149 assert!(matches!(u.types[0], Atomic::TInt));
3150 }
3151
3152 #[test]
3153 fn true_then_false_merges_to_bool() {
3154 let mut u = Type::single(Atomic::TTrue);
3155 u.add_type(Atomic::TFalse);
3156 assert_eq!(u.types.len(), 1);
3157 assert!(matches!(u.types[0], Atomic::TBool));
3158 }
3159
3160 #[test]
3161 fn false_then_true_merges_to_bool() {
3162 let mut u = Type::single(Atomic::TFalse);
3163 u.add_type(Atomic::TTrue);
3164 assert_eq!(u.types.len(), 1);
3165 assert!(matches!(u.types[0], Atomic::TBool));
3166 }
3167
3168 #[test]
3169 fn true_alone_stays_true() {
3170 let u = Type::single(Atomic::TTrue);
3171 assert_eq!(u.types.len(), 1);
3172 assert!(matches!(u.types[0], Atomic::TTrue));
3173 }
3174
3175 #[test]
3176 fn true_false_merge_preserves_other_union_members() {
3177 let mut u = Type::single(Atomic::TTrue);
3178 u.add_type(Atomic::TNull);
3179 u.add_type(Atomic::TFalse);
3180 assert_eq!(u.types.len(), 2);
3181 assert!(u.contains(|t| matches!(t, Atomic::TBool)));
3182 assert!(u.contains(|t| matches!(t, Atomic::TNull)));
3183 }
3184
3185 #[test]
3186 fn add_type_base_widens_literals() {
3187 let mut u = Type::single(Atomic::TLiteralInt(1));
3188 u.add_type(Atomic::TLiteralInt(2));
3189 u.add_type(Atomic::TInt);
3190 assert_eq!(u.types.len(), 1);
3191 assert!(matches!(u.types[0], Atomic::TInt));
3192 }
3193
3194 #[test]
3195 fn mixed_subsumes_everything() {
3196 let mut u = Type::single(Atomic::TString);
3197 u.add_type(Atomic::TMixed);
3198 assert_eq!(u.types.len(), 1);
3199 assert!(u.is_mixed());
3200 }
3201
3202 #[test]
3203 fn remove_null() {
3204 let u = Type::nullable(Atomic::TString);
3205 let narrowed = u.remove_null();
3206 assert!(!narrowed.is_nullable());
3207 assert_eq!(narrowed.types.len(), 1);
3208 }
3209
3210 #[test]
3211 fn narrow_to_truthy_removes_null_false() {
3212 let mut u = Type::empty();
3213 u.add_type(Atomic::TString);
3214 u.add_type(Atomic::TNull);
3215 u.add_type(Atomic::TFalse);
3216 let truthy = u.narrow_to_truthy();
3217 assert!(!truthy.is_nullable());
3218 assert!(!truthy.contains(|t| matches!(t, Atomic::TFalse)));
3219 }
3220
3221 #[test]
3222 fn merge_combines_types() {
3223 let a = Type::single(Atomic::TString);
3224 let b = Type::single(Atomic::TInt);
3225 let merged = Type::merge(&a, &b);
3226 assert_eq!(merged.types.len(), 2);
3227 }
3228
3229 #[test]
3230 fn intersect_keeps_narrower_side_not_self() {
3231 let int_ty = Type::single(Atomic::TInt);
3235 let mut literals = Type::empty();
3236 literals.add_type(Atomic::TLiteralInt(1));
3237 literals.add_type(Atomic::TLiteralInt(2));
3238
3239 let narrowed = int_ty.intersect_with(&literals);
3240 assert_eq!(narrowed.types.len(), 2);
3241 assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(1))));
3242 assert!(narrowed.contains(|t| matches!(t, Atomic::TLiteralInt(2))));
3243 assert!(!narrowed.contains(|t| matches!(t, Atomic::TInt)));
3244 }
3245
3246 #[test]
3247 fn subtype_literal_int_under_int() {
3248 let sub = Type::single(Atomic::TLiteralInt(5));
3249 let sup = Type::single(Atomic::TInt);
3250 assert!(sub.is_subtype_structural(&sup));
3251 }
3252
3253 #[test]
3254 fn subtype_never_is_bottom() {
3255 let never = Type::never();
3256 let string = Type::single(Atomic::TString);
3257 assert!(never.is_subtype_structural(&string));
3258 }
3259
3260 #[test]
3261 fn subtype_everything_under_mixed() {
3262 let string = Type::single(Atomic::TString);
3263 let mixed = Type::mixed();
3264 assert!(string.is_subtype_structural(&mixed));
3265 }
3266
3267 #[test]
3268 fn subtype_enum_case_under_own_enum() {
3269 let sub = Type::single(Atomic::TLiteralEnumCase {
3270 enum_fqcn: Name::new("RoundingMode"),
3271 case_name: Name::new("Unnecessary"),
3272 });
3273 let sup = Type::single(Atomic::TNamedObject {
3274 fqcn: Name::new("RoundingMode"),
3275 type_params: empty_type_params(),
3276 });
3277 assert!(sub.is_subtype_structural(&sup));
3278 }
3279
3280 #[test]
3281 fn enum_case_not_subtype_of_unrelated_enum() {
3282 let sub = Type::single(Atomic::TLiteralEnumCase {
3283 enum_fqcn: Name::new("RoundingMode"),
3284 case_name: Name::new("Unnecessary"),
3285 });
3286 let sup = Type::single(Atomic::TNamedObject {
3287 fqcn: Name::new("Suit"),
3288 type_params: empty_type_params(),
3289 });
3290 assert!(!sub.is_subtype_structural(&sup));
3291 }
3292
3293 #[test]
3294 fn subtype_enum_case_under_own_self_and_static() {
3295 let case = |enum_fqcn: &str| {
3296 Type::single(Atomic::TLiteralEnumCase {
3297 enum_fqcn: Name::new(enum_fqcn),
3298 case_name: Name::new("A"),
3299 })
3300 };
3301 let own = Type::single(Atomic::TSelf {
3302 fqcn: Name::new("Suit"),
3303 });
3304 let own_static = Type::single(Atomic::TStaticObject {
3305 fqcn: Name::new("Suit"),
3306 });
3307 assert!(case("Suit").is_subtype_structural(&own));
3308 assert!(case("Suit").is_subtype_structural(&own_static));
3309 assert!(!case("Other").is_subtype_structural(&own));
3310 }
3311
3312 #[test]
3313 fn subtype_enum_case_under_bare_object() {
3314 let sub = Type::single(Atomic::TLiteralEnumCase {
3315 enum_fqcn: Name::new("RoundingMode"),
3316 case_name: Name::new("Unnecessary"),
3317 });
3318 let sup = Type::single(Atomic::TObject);
3319 assert!(sub.is_subtype_structural(&sup));
3320 }
3321
3322 #[test]
3323 fn template_substitution() {
3324 let mut bindings = FxHashMap::default();
3325 bindings.insert(Name::new("T"), Type::single(Atomic::TString));
3326
3327 let tmpl = Type::single(Atomic::TTemplateParam {
3328 name: Name::new("T"),
3329 as_type: Box::new(Type::mixed()),
3330 defining_entity: Name::new("MyClass"),
3331 });
3332
3333 let resolved = tmpl.substitute_templates(&bindings);
3334 assert_eq!(resolved.types.len(), 1);
3335 assert!(matches!(resolved.types[0], Atomic::TString));
3336 }
3337
3338 #[test]
3339 fn intersection_is_object() {
3340 let parts = vec![
3341 Type::single(Atomic::TNamedObject {
3342 fqcn: Name::new("Iterator"),
3343 type_params: empty_type_params(),
3344 }),
3345 Type::single(Atomic::TNamedObject {
3346 fqcn: Name::new("Countable"),
3347 type_params: empty_type_params(),
3348 }),
3349 ];
3350 let atomic = Atomic::TIntersection {
3351 parts: vec_to_type_params(parts),
3352 };
3353 assert!(atomic.is_object());
3354 assert!(!atomic.can_be_falsy());
3355 assert!(atomic.can_be_truthy());
3356 }
3357
3358 #[test]
3359 fn intersection_display_two_parts() {
3360 let parts = vec![
3361 Type::single(Atomic::TNamedObject {
3362 fqcn: Name::new("Iterator"),
3363 type_params: empty_type_params(),
3364 }),
3365 Type::single(Atomic::TNamedObject {
3366 fqcn: Name::new("Countable"),
3367 type_params: empty_type_params(),
3368 }),
3369 ];
3370 let u = Type::single(Atomic::TIntersection {
3371 parts: vec_to_type_params(parts),
3372 });
3373 assert_eq!(format!("{u}"), "Iterator&Countable");
3374 }
3375
3376 #[test]
3377 fn intersection_display_three_parts() {
3378 let parts = vec![
3379 Type::single(Atomic::TNamedObject {
3380 fqcn: Name::new("A"),
3381 type_params: empty_type_params(),
3382 }),
3383 Type::single(Atomic::TNamedObject {
3384 fqcn: Name::new("B"),
3385 type_params: empty_type_params(),
3386 }),
3387 Type::single(Atomic::TNamedObject {
3388 fqcn: Name::new("C"),
3389 type_params: empty_type_params(),
3390 }),
3391 ];
3392 let u = Type::single(Atomic::TIntersection {
3393 parts: vec_to_type_params(parts),
3394 });
3395 assert_eq!(format!("{u}"), "A&B&C");
3396 }
3397
3398 #[test]
3399 fn intersection_in_nullable_union_display() {
3400 let intersection = Atomic::TIntersection {
3401 parts: vec_to_type_params(vec![
3402 Type::single(Atomic::TNamedObject {
3403 fqcn: Name::new("Iterator"),
3404 type_params: empty_type_params(),
3405 }),
3406 Type::single(Atomic::TNamedObject {
3407 fqcn: Name::new("Countable"),
3408 type_params: empty_type_params(),
3409 }),
3410 ]),
3411 };
3412 let mut u = Type::single(intersection);
3413 u.add_type(Atomic::TNull);
3414 assert!(u.is_nullable());
3415 assert!(u.contains(|t| matches!(t, Atomic::TIntersection { .. })));
3416 }
3417
3418 fn t_param(name: &str) -> Type {
3421 Type::single(Atomic::TTemplateParam {
3422 name: Name::new(name),
3423 as_type: Box::new(Type::mixed()),
3424 defining_entity: Name::new("Fn"),
3425 })
3426 }
3427
3428 fn bindings_t_string() -> FxHashMap<Name, Type> {
3429 let mut b = FxHashMap::default();
3430 b.insert(Name::new("T"), Type::single(Atomic::TString));
3431 b
3432 }
3433
3434 #[test]
3435 fn substitute_non_empty_array_key_and_value() {
3436 let ty = Type::single(Atomic::TNonEmptyArray {
3437 key: Box::new(t_param("T")),
3438 value: Box::new(t_param("T")),
3439 });
3440 let result = ty.substitute_templates(&bindings_t_string());
3441 assert_eq!(result.types.len(), 1);
3442 let Atomic::TNonEmptyArray { key, value } = &result.types[0] else {
3443 panic!("expected TNonEmptyArray");
3444 };
3445 assert!(matches!(key.types[0], Atomic::TString));
3446 assert!(matches!(value.types[0], Atomic::TString));
3447 }
3448
3449 #[test]
3450 fn substitute_non_empty_list_value() {
3451 let ty = Type::single(Atomic::TNonEmptyList {
3452 value: Box::new(t_param("T")),
3453 });
3454 let result = ty.substitute_templates(&bindings_t_string());
3455 let Atomic::TNonEmptyList { value } = &result.types[0] else {
3456 panic!("expected TNonEmptyList");
3457 };
3458 assert!(matches!(value.types[0], Atomic::TString));
3459 }
3460
3461 #[test]
3462 fn substitute_keyed_array_property_types() {
3463 use crate::atomic::{ArrayKey, KeyedProperty};
3464 let mut props = KeyedProperties::default();
3465 props.insert(
3466 ArrayKey::String(Arc::from("name")),
3467 KeyedProperty {
3468 ty: t_param("T"),
3469 optional: false,
3470 },
3471 );
3472 props.insert(
3473 ArrayKey::String(Arc::from("tag")),
3474 KeyedProperty {
3475 ty: t_param("T"),
3476 optional: true,
3477 },
3478 );
3479 let ty = Type::single(Atomic::TKeyedArray {
3480 properties: Arc::new(props),
3481 is_open: true,
3482 is_list: false,
3483 });
3484 let result = ty.substitute_templates(&bindings_t_string());
3485 let Atomic::TKeyedArray {
3486 properties,
3487 is_open,
3488 is_list,
3489 } = &result.types[0]
3490 else {
3491 panic!("expected TKeyedArray");
3492 };
3493 assert!(is_open);
3494 assert!(!is_list);
3495 assert!(matches!(
3496 properties[&ArrayKey::String(Arc::from("name"))].ty.types[0],
3497 Atomic::TString
3498 ));
3499 assert!(properties[&ArrayKey::String(Arc::from("tag"))].optional);
3500 assert!(matches!(
3501 properties[&ArrayKey::String(Arc::from("tag"))].ty.types[0],
3502 Atomic::TString
3503 ));
3504 }
3505
3506 #[test]
3507 fn substitute_callable_params_and_return() {
3508 use crate::atomic::FnParam;
3509 let ty = Type::single(Atomic::TCallable {
3510 params: Some(Box::new(vec![FnParam {
3511 name: Name::new("x"),
3512 ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3513 out_ty: None,
3514 default: None,
3515 is_variadic: false,
3516 is_byref: false,
3517 is_optional: false,
3518 }])),
3519 return_type: Some(Box::new(t_param("T"))),
3520 is_pure: false,
3521 });
3522 let result = ty.substitute_templates(&bindings_t_string());
3523 let Atomic::TCallable {
3524 params,
3525 return_type,
3526 ..
3527 } = &result.types[0]
3528 else {
3529 panic!("expected TCallable");
3530 };
3531 let param_ty = params.as_ref().unwrap()[0].ty.as_ref().unwrap();
3532 let param_union = param_ty.to_union();
3533 assert!(matches!(param_union.types[0], Atomic::TString));
3534 let ret = return_type.as_ref().unwrap();
3535 assert!(matches!(ret.types[0], Atomic::TString));
3536 }
3537
3538 #[test]
3539 fn substitute_callable_bare_no_panic() {
3540 let ty = Type::single(Atomic::TCallable {
3542 params: None,
3543 return_type: None,
3544 is_pure: false,
3545 });
3546 let result = ty.substitute_templates(&bindings_t_string());
3547 assert!(matches!(
3548 result.types[0],
3549 Atomic::TCallable {
3550 params: None,
3551 return_type: None,
3552 ..
3553 }
3554 ));
3555 }
3556
3557 #[test]
3558 fn substitute_closure_params_return_and_this() {
3559 use crate::atomic::FnParam;
3560 let ty = Type::single(Atomic::TClosure {
3561 data: Box::new(crate::atomic::ClosureData {
3562 params: Box::new([FnParam {
3563 name: Name::new("a"),
3564 ty: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3565 out_ty: None,
3566 default: Some(crate::compact::SimpleType::from_union(t_param("T"))),
3567 is_variadic: true,
3568 is_byref: true,
3569 is_optional: true,
3570 }]),
3571 return_type: t_param("T"),
3572 this_type: Some(t_param("T")),
3573 is_pure: false,
3574 is_static: false,
3575 rejects_surplus_args: false,
3576 is_impure: false,
3577 }),
3578 });
3579 let result = ty.substitute_templates(&bindings_t_string());
3580 let Atomic::TClosure { data } = &result.types[0] else {
3581 panic!("expected TClosure");
3582 };
3583 let (params, return_type, this_type) = (&data.params, &data.return_type, &data.this_type);
3584 let p = ¶ms[0];
3585 let ty_union = p.ty.as_ref().unwrap().to_union();
3586 let default_union = p.default.as_ref().unwrap().to_union();
3587 assert!(matches!(ty_union.types[0], Atomic::TString));
3588 assert!(matches!(default_union.types[0], Atomic::TString));
3589 assert!(p.is_variadic);
3591 assert!(p.is_byref);
3592 assert!(p.is_optional);
3593 assert!(matches!(return_type.types[0], Atomic::TString));
3594 assert!(matches!(
3595 this_type.as_ref().unwrap().types[0],
3596 Atomic::TString
3597 ));
3598 }
3599
3600 #[test]
3601 fn substitute_conditional_all_branches() {
3602 let ty = Type::single(conditional(
3603 None,
3604 t_param("T"),
3605 t_param("T"),
3606 Type::single(Atomic::TInt),
3607 ));
3608 let result = ty.substitute_templates(&bindings_t_string());
3609 let Atomic::TConditional { data } = &result.types[0] else {
3610 panic!("expected TConditional");
3611 };
3612 let (subject, if_true, if_false) = (&data.subject, &data.if_true, &data.if_false);
3613 assert!(matches!(subject.types[0], Atomic::TString));
3614 assert!(matches!(if_true.types[0], Atomic::TString));
3615 assert!(matches!(if_false.types[0], Atomic::TInt));
3616 }
3617
3618 #[test]
3619 fn resolve_conditional_is_null_non_null_arg() {
3620 let ty = Type::single(conditional(
3621 Some(Name::new("x")),
3622 Type::single(Atomic::TNull),
3623 Type::single(Atomic::TInt),
3624 Type::single(Atomic::TString),
3625 ));
3626 let result = ty.resolve_conditional_returns(|name| {
3627 if name == "x" {
3628 Some(Type::single(Atomic::TString)) } else {
3630 None
3631 }
3632 });
3633 assert!(result.types.len() == 1);
3634 assert!(matches!(result.types[0], Atomic::TString));
3635 }
3636
3637 #[test]
3638 fn resolve_conditional_is_null_null_arg() {
3639 let ty = Type::single(conditional(
3640 Some(Name::new("x")),
3641 Type::single(Atomic::TNull),
3642 Type::single(Atomic::TInt),
3643 Type::single(Atomic::TString),
3644 ));
3645 let result = ty.resolve_conditional_returns(|name| {
3646 if name == "x" {
3647 Some(Type::single(Atomic::TNull)) } else {
3649 None
3650 }
3651 });
3652 assert!(result.types.len() == 1);
3653 assert!(matches!(result.types[0], Atomic::TInt));
3654 }
3655
3656 #[test]
3657 fn resolve_conditional_is_null_nullable_arg_widens_to_branch_union() {
3658 let mut nullable_str = Type::single(Atomic::TString);
3659 nullable_str.add_type(Atomic::TNull);
3660 let ty = Type::single(conditional(
3661 Some(Name::new("x")),
3662 Type::single(Atomic::TNull),
3663 Type::single(Atomic::TInt),
3664 Type::single(Atomic::TString),
3665 ));
3666 let result = ty.resolve_conditional_returns(|name| {
3667 if name == "x" {
3668 Some(nullable_str.clone())
3669 } else {
3670 None
3671 }
3672 });
3673 assert_eq!(result.types.len(), 2);
3675 assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
3676 assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
3677 }
3678
3679 #[test]
3680 fn resolve_conditional_nested_widens_inner_branch() {
3681 let inner = Type::single(conditional(
3684 Some(Name::new("x")),
3685 Type::single(Atomic::TString),
3686 Type::single(Atomic::TString),
3687 Type::single(Atomic::TFloat),
3688 ));
3689 let ty = Type::single(conditional(
3690 Some(Name::new("x")),
3691 Type::single(Atomic::TNull),
3692 Type::single(Atomic::TInt),
3693 inner,
3694 ));
3695 let result = ty.resolve_conditional_returns(|_| None);
3697 assert!(
3698 result
3699 .types
3700 .iter()
3701 .all(|t| !matches!(t, Atomic::TConditional { .. })),
3702 "no TConditional should survive: {:?}",
3703 result.types
3704 );
3705 assert!(result.types.iter().any(|t| matches!(t, Atomic::TInt)));
3706 assert!(result.types.iter().any(|t| matches!(t, Atomic::TString)));
3707 assert!(result.types.iter().any(|t| matches!(t, Atomic::TFloat)));
3708 }
3709
3710 #[test]
3711 fn resolve_conditional_nested_resolves_inner_branch() {
3712 let inner = Type::single(conditional(
3716 Some(Name::new("x")),
3717 Type::single(Atomic::TString),
3718 Type::single(Atomic::TString),
3719 Type::single(Atomic::TFloat),
3720 ));
3721 let ty = Type::single(conditional(
3722 Some(Name::new("x")),
3723 Type::single(Atomic::TNull),
3724 Type::single(Atomic::TInt),
3725 inner,
3726 ));
3727 let result = ty.resolve_conditional_returns(|name| {
3729 if name == "x" {
3730 Some(Type::single(Atomic::TString))
3731 } else {
3732 None
3733 }
3734 });
3735 assert!(
3736 result
3737 .types
3738 .iter()
3739 .all(|t| !matches!(t, Atomic::TConditional { .. })),
3740 "no TConditional should survive: {:?}",
3741 result.types
3742 );
3743 assert_eq!(result.types.len(), 1);
3744 assert!(matches!(result.types[0], Atomic::TString));
3745 }
3746
3747 #[test]
3748 fn resolve_conditional_true_subject_bool_arg_widens() {
3749 let ty = Type::single(conditional(
3753 Some(Name::new("x")),
3754 Type::single(Atomic::TTrue),
3755 Type::single(Atomic::TInt),
3756 Type::single(Atomic::TString),
3757 ));
3758 let result = ty.resolve_conditional_returns(|name| {
3759 if name == "x" {
3760 Some(Type::single(Atomic::TBool))
3761 } else {
3762 None
3763 }
3764 });
3765 assert_eq!(result.types.len(), 2);
3766 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3767 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3768 }
3769
3770 #[test]
3771 fn resolve_conditional_true_subject_mixed_arg_widens() {
3772 let ty = Type::single(conditional(
3775 Some(Name::new("x")),
3776 Type::single(Atomic::TTrue),
3777 Type::single(Atomic::TInt),
3778 Type::single(Atomic::TString),
3779 ));
3780 let result = ty.resolve_conditional_returns(|name| {
3781 if name == "x" {
3782 Some(Type::mixed())
3783 } else {
3784 None
3785 }
3786 });
3787 assert_eq!(result.types.len(), 2);
3788 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3789 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3790 }
3791
3792 #[test]
3793 fn resolve_conditional_true_subject_literal_args() {
3794 let ty = Type::single(conditional(
3797 Some(Name::new("x")),
3798 Type::single(Atomic::TTrue),
3799 Type::single(Atomic::TInt),
3800 Type::single(Atomic::TString),
3801 ));
3802 let false_arg = ty.clone().resolve_conditional_returns(|name| {
3803 if name == "x" {
3804 Some(Type::single(Atomic::TFalse))
3805 } else {
3806 None
3807 }
3808 });
3809 assert_eq!(false_arg.types.len(), 1);
3810 assert!(matches!(false_arg.types[0], Atomic::TString));
3811
3812 let true_arg = ty.resolve_conditional_returns(|name| {
3813 if name == "x" {
3814 Some(Type::single(Atomic::TTrue))
3815 } else {
3816 None
3817 }
3818 });
3819 assert_eq!(true_arg.types.len(), 1);
3820 assert!(matches!(true_arg.types[0], Atomic::TInt));
3821 }
3822
3823 #[test]
3824 fn resolve_conditional_bool_subject_scalar_arg_widens() {
3825 let ty = Type::single(conditional(
3829 Some(Name::new("x")),
3830 Type::single(Atomic::TBool),
3831 Type::single(Atomic::TInt),
3832 Type::single(Atomic::TString),
3833 ));
3834 let result = ty.resolve_conditional_returns(|name| {
3835 if name == "x" {
3836 Some(Type::single(Atomic::TScalar))
3837 } else {
3838 None
3839 }
3840 });
3841 assert_eq!(result.types.len(), 2);
3842 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3843 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3844 }
3845
3846 #[test]
3847 fn resolve_conditional_string_subject_bool_arg_false_branch() {
3848 let ty = Type::single(conditional(
3852 Some(Name::new("x")),
3853 Type::single(Atomic::TString),
3854 Type::single(Atomic::TInt),
3855 Type::single(Atomic::TBool),
3856 ));
3857 let result = ty.resolve_conditional_returns(|name| {
3858 if name == "x" {
3859 Some(Type::single(Atomic::TBool))
3860 } else {
3861 None
3862 }
3863 });
3864 assert_eq!(result.types.len(), 1);
3865 assert!(matches!(result.types[0], Atomic::TBool));
3866 }
3867
3868 #[test]
3869 fn resolve_conditional_list_subject_bare_array_arg_widens() {
3870 let ty = Type::single(conditional(
3873 Some(Name::new("x")),
3874 Type::single(Atomic::TList {
3875 value: Box::new(Type::mixed()),
3876 }),
3877 Type::single(Atomic::TInt),
3878 Type::single(Atomic::TString),
3879 ));
3880 let result = ty.resolve_conditional_returns(|name| {
3881 if name == "x" {
3882 Some(Type::single(Atomic::TArray {
3883 key: Box::new(Type::mixed()),
3884 value: Box::new(Type::mixed()),
3885 }))
3886 } else {
3887 None
3888 }
3889 });
3890 assert_eq!(result.types.len(), 2);
3891 assert!(result.contains(|t| matches!(t, Atomic::TInt)));
3892 assert!(result.contains(|t| matches!(t, Atomic::TString)));
3893 }
3894
3895 #[test]
3896 fn resolve_conditional_float_subject_int_literal_false_branch() {
3897 let ty = resolve_conditional_branch(
3900 &Type::single(Atomic::TFloat),
3901 &Type::single(Atomic::TLiteralInt(42)),
3902 &Type::single(Atomic::TInt),
3903 &Type::single(Atomic::TString),
3904 );
3905 assert!(matches!(
3906 ty.as_ref(),
3907 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3908 ));
3909 }
3910
3911 #[test]
3912 fn resolve_conditional_int_subject_float_literal_false_branch() {
3913 let ty = resolve_conditional_branch(
3914 &Type::single(Atomic::TInt),
3915 &Type::single(Atomic::TLiteralFloat(1, 0)),
3916 &Type::single(Atomic::TInt),
3917 &Type::single(Atomic::TString),
3918 );
3919 assert!(matches!(
3920 ty.as_ref(),
3921 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3922 ));
3923 }
3924
3925 #[test]
3926 fn resolve_conditional_float_subject_float_literal_then_branch() {
3927 let ty = resolve_conditional_branch(
3928 &Type::single(Atomic::TFloat),
3929 &Type::single(Atomic::TLiteralFloat(1, 5)),
3930 &Type::single(Atomic::TInt),
3931 &Type::single(Atomic::TString),
3932 );
3933 assert!(matches!(
3934 ty.as_ref(),
3935 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3936 ));
3937 }
3938
3939 #[test]
3940 fn resolve_conditional_int_subject_int_literal_then_branch() {
3941 let ty = resolve_conditional_branch(
3942 &Type::single(Atomic::TInt),
3943 &Type::single(Atomic::TLiteralInt(7)),
3944 &Type::single(Atomic::TInt),
3945 &Type::single(Atomic::TString),
3946 );
3947 assert!(matches!(
3948 ty.as_ref(),
3949 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
3950 ));
3951 }
3952
3953 #[test]
3954 fn resolve_conditional_int_subject_float_arg_false_branch() {
3955 let ty = resolve_conditional_branch(
3958 &Type::single(Atomic::TInt),
3959 &Type::single(Atomic::TFloat),
3960 &Type::single(Atomic::TInt),
3961 &Type::single(Atomic::TString),
3962 );
3963 assert!(matches!(
3964 ty.as_ref(),
3965 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3966 ));
3967 }
3968
3969 #[test]
3970 fn resolve_conditional_array_subject_string_arg_false_branch() {
3971 let ty = resolve_conditional_branch(
3972 &Type::single(Atomic::TArray {
3973 key: Box::new(Type::mixed()),
3974 value: Box::new(Type::mixed()),
3975 }),
3976 &Type::single(Atomic::TString),
3977 &Type::single(Atomic::TInt),
3978 &Type::single(Atomic::TString),
3979 );
3980 assert!(matches!(
3981 ty.as_ref(),
3982 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
3983 ));
3984 }
3985
3986 #[test]
3987 fn resolve_conditional_array_subject_bool_arg_false_branch() {
3988 let ty = resolve_conditional_branch(
3989 &Type::single(Atomic::TArray {
3990 key: Box::new(Type::mixed()),
3991 value: Box::new(Type::mixed()),
3992 }),
3993 &Type::single(Atomic::TBool),
3994 &Type::single(Atomic::TInt),
3995 &Type::single(Atomic::TString),
3996 );
3997 assert!(matches!(
3998 ty.as_ref(),
3999 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4000 ));
4001 }
4002
4003 #[test]
4004 fn resolve_conditional_array_subject_mixed_arg_widens() {
4005 let ty = resolve_conditional_branch(
4009 &Type::single(Atomic::TArray {
4010 key: Box::new(Type::mixed()),
4011 value: Box::new(Type::mixed()),
4012 }),
4013 &Type::mixed(),
4014 &Type::single(Atomic::TInt),
4015 &Type::single(Atomic::TString),
4016 );
4017 assert!(ty.is_none());
4018 }
4019
4020 #[test]
4021 fn resolve_conditional_array_subject_list_arg_then_branch() {
4022 let ty = resolve_conditional_branch(
4025 &Type::single(Atomic::TArray {
4026 key: Box::new(Type::mixed()),
4027 value: Box::new(Type::mixed()),
4028 }),
4029 &Type::single(Atomic::TList {
4030 value: Box::new(Type::mixed()),
4031 }),
4032 &Type::single(Atomic::TInt),
4033 &Type::single(Atomic::TString),
4034 );
4035 assert!(matches!(
4036 ty.as_ref(),
4037 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4038 ));
4039 }
4040
4041 #[test]
4042 fn resolve_conditional_list_subject_keyed_list_arg_then_branch() {
4043 let ty = resolve_conditional_branch(
4045 &Type::single(Atomic::TList {
4046 value: Box::new(Type::mixed()),
4047 }),
4048 &Type::single(Atomic::TKeyedArray {
4049 properties: Arc::default(),
4050 is_open: false,
4051 is_list: true,
4052 }),
4053 &Type::single(Atomic::TInt),
4054 &Type::single(Atomic::TString),
4055 );
4056 assert!(matches!(
4057 ty.as_ref(),
4058 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4059 ));
4060 }
4061
4062 #[test]
4063 fn resolve_conditional_list_subject_list_string_union_widens() {
4064 let ty = resolve_conditional_branch(
4068 &Type::single(Atomic::TList {
4069 value: Box::new(Type::mixed()),
4070 }),
4071 &Type::from_vec(vec![
4072 Atomic::TList {
4073 value: Box::new(Type::mixed()),
4074 },
4075 Atomic::TString,
4076 ]),
4077 &Type::single(Atomic::TInt),
4078 &Type::single(Atomic::TString),
4079 );
4080 assert!(ty.is_none());
4081 }
4082
4083 #[test]
4084 fn resolve_conditional_numeric_subject_widens() {
4085 let ty = resolve_conditional_branch(
4089 &Type::single(Atomic::TNumeric),
4090 &Type::single(Atomic::TLiteralString("123".into())),
4091 &Type::single(Atomic::TInt),
4092 &Type::single(Atomic::TString),
4093 );
4094 assert!(ty.is_none());
4095 }
4096
4097 #[test]
4098 fn resolve_conditional_non_empty_string_subject_widens() {
4099 let ty = resolve_conditional_branch(
4102 &Type::single(Atomic::TNonEmptyString),
4103 &Type::single(Atomic::TString),
4104 &Type::single(Atomic::TInt),
4105 &Type::single(Atomic::TString),
4106 );
4107 assert!(ty.is_none());
4108 }
4109
4110 #[test]
4111 fn resolve_conditional_template_arg_widens() {
4112 let ty = resolve_conditional_branch(
4115 &Type::single(Atomic::TString),
4116 &t_param("T"),
4117 &Type::single(Atomic::TInt),
4118 &Type::single(Atomic::TString),
4119 );
4120 assert!(ty.is_none());
4121 }
4122
4123 #[test]
4124 fn resolve_conditional_mixed_subject_bool_arg_then_branch() {
4125 let ty = resolve_conditional_branch(
4128 &Type::single(Atomic::TMixed),
4129 &Type::single(Atomic::TBool),
4130 &Type::single(Atomic::TInt),
4131 &Type::single(Atomic::TString),
4132 );
4133 assert!(matches!(
4134 ty.as_ref(),
4135 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4136 ));
4137 }
4138
4139 #[test]
4140 fn resolve_conditional_scalar_subject_null_arg_false_branch() {
4141 let ty = resolve_conditional_branch(
4144 &Type::single(Atomic::TScalar),
4145 &Type::single(Atomic::TNull),
4146 &Type::single(Atomic::TInt),
4147 &Type::single(Atomic::TString),
4148 );
4149 assert!(matches!(
4150 ty.as_ref(),
4151 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4152 ));
4153 }
4154
4155 #[test]
4156 fn resolve_conditional_object_subject_named_arg_then_branch() {
4157 let ty = resolve_conditional_branch(
4159 &Type::single(Atomic::TObject),
4160 &Type::single(Atomic::TNamedObject {
4161 fqcn: Name::new("Foo"),
4162 type_params: empty_type_params(),
4163 }),
4164 &Type::single(Atomic::TInt),
4165 &Type::single(Atomic::TString),
4166 );
4167 assert!(matches!(
4168 ty.as_ref(),
4169 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4170 ));
4171 }
4172
4173 #[test]
4174 fn resolve_conditional_named_subject_other_class_widens() {
4175 let ty = resolve_conditional_branch(
4179 &Type::single(Atomic::TNamedObject {
4180 fqcn: Name::new("Foo"),
4181 type_params: empty_type_params(),
4182 }),
4183 &Type::single(Atomic::TNamedObject {
4184 fqcn: Name::new("Bar"),
4185 type_params: empty_type_params(),
4186 }),
4187 &Type::single(Atomic::TInt),
4188 &Type::single(Atomic::TString),
4189 );
4190 assert!(ty.is_none());
4191 }
4192
4193 #[test]
4194 fn resolve_conditional_enum_case_subject_widens() {
4195 let ty = resolve_conditional_branch(
4198 &Type::single(Atomic::TLiteralEnumCase {
4199 enum_fqcn: Name::new("RoundingMode"),
4200 case_name: Name::new("Unnecessary"),
4201 }),
4202 &Type::single(Atomic::TInt),
4203 &Type::single(Atomic::TInt),
4204 &Type::single(Atomic::TString),
4205 );
4206 assert!(ty.is_none());
4207 }
4208
4209 #[test]
4210 fn resolve_conditional_null_subject_bool_arg_false_branch() {
4211 let ty = resolve_conditional_branch(
4213 &Type::single(Atomic::TNull),
4214 &Type::single(Atomic::TBool),
4215 &Type::single(Atomic::TInt),
4216 &Type::single(Atomic::TString),
4217 );
4218 assert!(matches!(
4219 ty.as_ref(),
4220 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TString)
4221 ));
4222 }
4223
4224 #[test]
4225 fn resolve_conditional_bool_subject_true_arg_then_branch() {
4226 let ty = resolve_conditional_branch(
4229 &Type::single(Atomic::TBool),
4230 &Type::single(Atomic::TTrue),
4231 &Type::single(Atomic::TInt),
4232 &Type::single(Atomic::TString),
4233 );
4234 assert!(matches!(
4235 ty.as_ref(),
4236 Some(t) if t.types.len() == 1 && matches!(t.types[0], Atomic::TInt)
4237 ));
4238 }
4239
4240 #[test]
4241 fn substitute_intersection_parts() {
4242 let ty = Type::single(Atomic::TIntersection {
4243 parts: vec_to_type_params(vec![
4244 Type::single(Atomic::TNamedObject {
4245 fqcn: Name::new("Countable"),
4246 type_params: empty_type_params(),
4247 }),
4248 t_param("T"),
4249 ]),
4250 });
4251 let result = ty.substitute_templates(&bindings_t_string());
4252 let Atomic::TIntersection { parts } = &result.types[0] else {
4253 panic!("expected TIntersection");
4254 };
4255 assert_eq!(parts.len(), 2);
4256 assert!(matches!(parts[0].types[0], Atomic::TNamedObject { .. }));
4257 assert!(matches!(parts[1].types[0], Atomic::TString));
4258 }
4259
4260 fn shape(props: &[(&str, Atomic, bool)], is_open: bool) -> Atomic {
4261 Atomic::TKeyedArray {
4262 properties: Arc::new(
4263 props
4264 .iter()
4265 .map(|(k, ty, optional)| {
4266 (
4267 ArrayKey::String(Arc::from(*k)),
4268 KeyedProperty {
4269 ty: Type::single(ty.clone()),
4270 optional: *optional,
4271 },
4272 )
4273 })
4274 .collect(),
4275 ),
4276 is_open,
4277 is_list: false,
4278 }
4279 }
4280
4281 fn shape_with_bits(bits: u32, is_open: bool) -> Atomic {
4283 let names: Vec<String> = (0..5).map(|i| format!("k{i}")).collect();
4284 let mut props = vec![("a", Atomic::TInt, false)];
4285 props.extend(
4286 (0..5)
4287 .filter(|i| bits & (1 << i) != 0)
4288 .map(|i| (names[i].as_str(), Atomic::TString, false)),
4289 );
4290 shape(&props, is_open)
4291 }
4292
4293 fn keyed_count(ty: &Type) -> usize {
4294 ty.types
4295 .iter()
4296 .filter(|t| matches!(t, Atomic::TKeyedArray { .. }))
4297 .count()
4298 }
4299
4300 #[test]
4301 fn add_type_keeps_few_shapes_apart() {
4302 let mut ty = Type::empty();
4303 for bits in 0..MAX_KEYED_SHAPES as u32 {
4304 ty.add_type(shape_with_bits(bits, false));
4305 }
4306 assert_eq!(keyed_count(&ty), MAX_KEYED_SHAPES);
4307 }
4308
4309 #[test]
4310 fn add_type_folds_shapes_past_the_limit() {
4311 let mut ty = Type::empty();
4312 for bits in 0..32 {
4313 ty.add_type(shape_with_bits(bits, false));
4314 }
4315 assert!(keyed_count(&ty) <= MAX_KEYED_SHAPES);
4316 for t in &ty.types {
4318 let Atomic::TKeyedArray { properties, .. } = t else {
4319 continue;
4320 };
4321 assert!(!properties[&ArrayKey::String(Arc::from("a"))].optional);
4322 }
4323 for i in 0..5 {
4324 let key = ArrayKey::String(Arc::from(format!("k{i}").as_str()));
4325 assert!(ty.types.iter().any(|t| matches!(
4326 t,
4327 Atomic::TKeyedArray { properties, .. } if properties.contains_key(&key)
4328 )));
4329 }
4330 }
4331
4332 #[test]
4333 fn add_type_folds_generic_arrays_past_the_limit() {
4334 let mut ty = Type::empty();
4335 for i in 0..32 {
4336 ty.add_type(Atomic::TArray {
4337 key: Box::new(Type::single(Atomic::TInt)),
4338 value: Box::new(Type::single(Atomic::TLiteralInt(i))),
4339 });
4340 }
4341 assert!(ty.types.len() <= MAX_GENERIC_ARRAYS);
4342 for i in 0..32 {
4343 assert!(ty.types.iter().any(|t| matches!(
4344 t,
4345 Atomic::TArray { value, .. } if value.types.contains(&Atomic::TLiteralInt(i))
4346 )));
4347 }
4348 }
4349
4350 #[test]
4351 fn add_type_widens_string_literals_past_the_limit() {
4352 let mut ty = Type::empty();
4353 for i in 0..MAX_LITERAL_STRINGS {
4354 ty.add_type(Atomic::TLiteralString(format!("s{i}").into()));
4355 }
4356 assert_eq!(ty.types.len(), MAX_LITERAL_STRINGS);
4357 ty.add_type(Atomic::TLiteralString("one more".into()));
4358 assert_eq!(ty.types.as_slice(), &[Atomic::TString]);
4359 ty.add_type(Atomic::TLiteralString("after".into()));
4360 assert_eq!(ty.types.as_slice(), &[Atomic::TString]);
4361 }
4362
4363 #[test]
4364 fn add_type_drops_generic_arrays_another_covers() {
4365 let list = |value: Atomic| Atomic::TList {
4366 value: Box::new(Type::single(value)),
4367 };
4368 let mut ty = Type::single(list(Atomic::TLiteralInt(0)));
4369 ty.add_type(list(Atomic::TInt));
4370 assert_eq!(ty.types.as_slice(), &[list(Atomic::TInt)]);
4371 ty.add_type(list(Atomic::TLiteralInt(1)));
4372 assert_eq!(ty.types.as_slice(), &[list(Atomic::TInt)]);
4373
4374 let mut opaque = Type::single(list(Atomic::TMixed));
4375 opaque.add_type(list(Atomic::TInt));
4376 assert_eq!(opaque.types.len(), 2);
4377
4378 let mut kinds = Type::single(Atomic::TNonEmptyList {
4379 value: Box::new(Type::single(Atomic::TInt)),
4380 });
4381 kinds.add_type(list(Atomic::TInt));
4382 assert_eq!(kinds.types.len(), 2);
4383 }
4384
4385 #[test]
4386 fn combine_keeps_emptiness_and_open_shape_soundness() {
4387 assert!(combine_keyed_arrays(
4389 &shape(&[], false),
4390 &shape(&[("a", Atomic::TInt, false)], false)
4391 )
4392 .is_none());
4393 assert!(combine_keyed_arrays(
4395 &shape(&[("a", Atomic::TInt, false)], true),
4396 &shape(&[("a", Atomic::TInt, false)], false)
4397 )
4398 .is_none());
4399 assert_eq!(
4401 combine_keyed_arrays(
4402 &shape(&[("a", Atomic::TInt, false)], true),
4403 &shape(
4404 &[("a", Atomic::TInt, false), ("k", Atomic::TString, false)],
4405 true
4406 )
4407 ),
4408 Some(shape(&[("a", Atomic::TInt, false)], true))
4409 );
4410 }
4411
4412 #[test]
4413 fn substitute_no_template_params_identity() {
4414 let ty = Type::single(Atomic::TInt);
4415 let result = ty.substitute_templates(&bindings_t_string());
4416 assert!(matches!(result.types[0], Atomic::TInt));
4417 }
4418}