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