1use std::fmt;
2
3use crate::atomic::{Atomic, IntRefinement, PropertyFilter, StringRefinement};
4use crate::union::Type;
5
6fn write_joined<T: fmt::Display>(
9 f: &mut fmt::Formatter<'_>,
10 items: impl IntoIterator<Item = T>,
11 sep: &str,
12) -> fmt::Result {
13 for (i, item) in items.into_iter().enumerate() {
14 if i > 0 {
15 f.write_str(sep)?;
16 }
17 write!(f, "{item}")?;
18 }
19 Ok(())
20}
21
22fn is_exactly_mixed(t: &Type) -> bool {
29 matches!(t.types.as_slice(), [Atomic::TMixed])
30}
31
32fn write_param_types(f: &mut fmt::Formatter<'_>, params: &[crate::atomic::FnParam]) -> fmt::Result {
35 for (i, p) in params.iter().enumerate() {
36 if i > 0 {
37 f.write_str(", ")?;
38 }
39 match &p.ty {
40 Some(ty) => write!(f, "{ty}")?,
41 None => f.write_str("mixed")?,
42 }
43 }
44 Ok(())
45}
46
47fn iterable_span(types: &[Atomic]) -> Option<(usize, usize, String)> {
59 for (ai, a) in types.iter().enumerate() {
60 let Atomic::TArray { key, value } = a else {
61 continue;
62 };
63 for (ti, t) in types.iter().enumerate() {
64 if ti == ai {
65 continue;
66 }
67 let Atomic::TNamedObject { fqcn, type_params } = t else {
68 continue;
69 };
70 if fqcn.as_ref() != "Traversable" {
71 continue;
72 }
73 let is_default_key_value =
74 is_exactly_mixed(value) && (is_exactly_mixed(key) || key.is_array_key());
75 let matches = if type_params.is_empty() {
76 is_default_key_value
81 } else {
82 type_params.len() == 2
83 && &type_params[0] == key.as_ref()
84 && &type_params[1] == value.as_ref()
85 };
86 if !matches {
87 continue;
88 }
89 let rendered = if is_default_key_value {
90 "iterable".to_string()
91 } else {
92 format!("iterable<{key}, {value}>")
93 };
94 return Some((ai.min(ti), ai.max(ti), rendered));
95 }
96 }
97 None
98}
99
100impl fmt::Display for Type {
101 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102 if self.types.is_empty() {
103 return write!(f, "never");
104 }
105 if let Some((lo, hi, rendered)) = iterable_span(&self.types) {
106 let mut first = true;
107 for (i, t) in self.types.iter().enumerate() {
108 if i == hi {
109 continue;
110 }
111 if !first {
112 f.write_str("|")?;
113 }
114 first = false;
115 if i == lo {
116 f.write_str(&rendered)?;
117 } else {
118 write!(f, "{t}")?;
119 }
120 }
121 return Ok(());
122 }
123 write_joined(f, self.types.iter(), "|")
124 }
125}
126
127pub struct LiteralText<'a>(pub &'a str);
129
130impl fmt::Display for LiteralText<'_> {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 if !self
133 .0
134 .chars()
135 .any(|c| ('\u{F700}'..='\u{F7FF}').contains(&c))
136 {
137 return f.write_str(self.0);
138 }
139 for c in self.0.chars() {
140 match u32::from(c) {
141 b @ 0xF700..=0xF7FF => write!(f, "\\x{:02x}", b - 0xF700)?,
143 _ => write!(f, "{c}")?,
144 }
145 }
146 Ok(())
147 }
148}
149
150impl fmt::Display for Atomic {
151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152 match self {
153 Atomic::TString => write!(f, "string"),
154 Atomic::TLiteralString(s) => write!(f, "\"{}\"", LiteralText(s)),
155 Atomic::TCallableString => write!(f, "callable-string"),
156 Atomic::TClassString(None) => write!(f, "class-string"),
157 Atomic::TClassString(Some(cls)) => write!(f, "class-string<{cls}>"),
158 Atomic::TNonEmptyString => write!(f, "non-empty-string"),
159 Atomic::TNonFalsyString => write!(f, "non-falsy-string"),
160 Atomic::TNumericString => write!(f, "numeric-string"),
161 Atomic::TRefinedString {
162 refinement,
163 non_empty,
164 } => {
165 let prefix = if *non_empty { "non-empty-" } else { "" };
166 let kind = match refinement {
167 StringRefinement::Lowercase => "lowercase",
168 StringRefinement::Uppercase => "uppercase",
169 StringRefinement::Literal => "literal",
170 };
171 write!(f, "{prefix}{kind}-string")
172 }
173
174 Atomic::TInt => write!(f, "int"),
175 Atomic::TLiteralInt(n) => write!(f, "{n}"),
176 Atomic::TIntRange { min, max } => match (min, max) {
177 (None, None) => write!(f, "int"),
178 (lo, hi) => {
179 let lo = lo.map_or_else(|| "min".to_string(), |n| n.to_string());
180 let hi = hi.map_or_else(|| "max".to_string(), |n| n.to_string());
181 write!(f, "int<{lo}, {hi}>")
182 }
183 },
184 Atomic::TPositiveInt => write!(f, "positive-int"),
185 Atomic::TNegativeInt => write!(f, "negative-int"),
186 Atomic::TNonNegativeInt => write!(f, "non-negative-int"),
187 Atomic::TRefinedInt(IntRefinement::Literal) => write!(f, "literal-int"),
188 Atomic::TRefinedInt(IntRefinement::MaskOf(target)) => {
189 write!(f, "int-mask-of<{target}>")
190 }
191
192 Atomic::TFloat | Atomic::TIntegralFloat => write!(f, "float"),
193 Atomic::TLiteralFloat(high, low) => {
194 let bits = ((*high as u64) << 32) | (*low as u32 as u64);
195 let value = f64::from_bits(bits);
196 write!(f, "{value}")
197 }
198
199 Atomic::TBool => write!(f, "bool"),
200 Atomic::TTrue => write!(f, "true"),
201 Atomic::TFalse => write!(f, "false"),
202
203 Atomic::TNull => write!(f, "null"),
204 Atomic::TVoid => write!(f, "void"),
205 Atomic::TNever => write!(f, "never"),
206 Atomic::TMixed => write!(f, "mixed"),
207 Atomic::TScalar => write!(f, "scalar"),
208 Atomic::TNumeric => write!(f, "numeric"),
209
210 Atomic::TObject => write!(f, "object"),
211 Atomic::TResource => write!(f, "resource"),
212 Atomic::TClosedResource => write!(f, "closed-resource"),
213 Atomic::TPropertiesOf { class, filter } => {
214 let prefix = match filter {
215 PropertyFilter::All => "",
216 PropertyFilter::Public => "public-",
217 PropertyFilter::Protected => "protected-",
218 PropertyFilter::Private => "private-",
219 };
220 write!(f, "{prefix}properties-of<{class}>")
221 }
222 Atomic::TNamedObject { fqcn, type_params } => {
223 if type_params.is_empty() || type_params.iter().all(is_exactly_mixed) {
228 write!(f, "{fqcn}")
229 } else {
230 write!(f, "{fqcn}<")?;
231 write_joined(f, type_params.iter(), ", ")?;
232 f.write_str(">")
233 }
234 }
235 Atomic::TStaticObject { fqcn } => write!(f, "static({fqcn})"),
236 Atomic::TSelf { fqcn } => write!(f, "self({fqcn})"),
237 Atomic::TParent { fqcn } => write!(f, "parent({fqcn})"),
238
239 Atomic::TCallable {
240 params,
241 return_type,
242 is_pure,
243 } => {
244 if *is_pure {
245 f.write_str("pure-")?;
246 }
247 match (params, return_type) {
248 (None, None) => f.write_str("callable"),
249 (Some(params), return_type) => {
250 f.write_str("callable(")?;
251 write_param_types(f, params)?;
252 match return_type {
253 Some(r) => write!(f, "): {r}"),
254 None => f.write_str("): mixed"),
255 }
256 }
257 (None, Some(ret)) => write!(f, "callable(): {ret}"),
258 }
259 }
260 Atomic::TClosure { data } => {
261 if data.is_pure {
262 f.write_str("pure-")?;
263 }
264 f.write_str("Closure(")?;
265 write_param_types(f, &data.params)?;
266 write!(f, "): {}", data.return_type)
267 }
268
269 Atomic::TArray { key, value } => {
270 if is_exactly_mixed(value) && (is_exactly_mixed(key) || key.is_array_key()) {
275 write!(f, "array")
276 } else {
277 write!(f, "array<{key}, {value}>")
278 }
279 }
280 Atomic::TList { value } => {
281 if is_exactly_mixed(value) {
282 write!(f, "list")
283 } else {
284 write!(f, "list<{value}>")
285 }
286 }
287 Atomic::TNonEmptyArray { key, value } => {
288 if is_exactly_mixed(value) && (is_exactly_mixed(key) || key.is_array_key()) {
289 write!(f, "non-empty-array")
290 } else {
291 write!(f, "non-empty-array<{key}, {value}>")
292 }
293 }
294 Atomic::TNonEmptyList { value } => {
295 if is_exactly_mixed(value) {
296 write!(f, "non-empty-list")
297 } else {
298 write!(f, "non-empty-list<{value}>")
299 }
300 }
301 Atomic::TObjectShape { properties } => {
302 f.write_str("object{")?;
303 for (i, (k, v)) in properties.iter().enumerate() {
304 if i > 0 {
305 f.write_str(", ")?;
306 }
307 match k {
308 crate::atomic::ArrayKey::String(s) => f.write_str(s)?,
309 crate::atomic::ArrayKey::Int(n) => write!(f, "{n}")?,
310 }
311 if v.optional {
312 f.write_str("?")?;
313 }
314 write!(f, ": {}", v.ty)?;
315 }
316 f.write_str("}")
317 }
318 Atomic::TKeyedArray { properties, .. } => {
319 f.write_str("array{")?;
320 for (i, (k, v)) in properties.iter().enumerate() {
321 if i > 0 {
322 f.write_str(", ")?;
323 }
324 match k {
325 crate::atomic::ArrayKey::String(s) => write!(f, "'{}'", LiteralText(s))?,
326 crate::atomic::ArrayKey::Int(n) => write!(f, "{n}")?,
327 }
328 if v.optional {
329 f.write_str("?")?;
330 }
331 write!(f, ": {}", v.ty)?;
332 }
333 f.write_str("}")
334 }
335
336 Atomic::TTemplateParam { name, .. } => write!(f, "{name}"),
337 Atomic::TKeyOf { target } => write!(f, "key-of<{target}>"),
338 Atomic::TValueOf { target } => write!(f, "value-of<{target}>"),
339 Atomic::TConditional { data } => {
340 let (subject, if_true, if_false) = (&data.subject, &data.if_true, &data.if_false);
341 match &data.param_name {
342 Some(name) => write!(f, "(${name} is {subject} ? {if_true} : {if_false})"),
343 None => write!(f, "({subject} is ? {if_true} : {if_false})"),
344 }
345 }
346
347 Atomic::TInterfaceString(None) => write!(f, "interface-string"),
348 Atomic::TInterfaceString(Some(iface)) => write!(f, "interface-string<{iface}>"),
349 Atomic::TEnumString => write!(f, "enum-string"),
350 Atomic::TTraitString => write!(f, "trait-string"),
351 Atomic::TLiteralEnumCase {
352 enum_fqcn,
353 case_name,
354 } => {
355 write!(f, "{enum_fqcn}::{case_name}")
356 }
357
358 Atomic::TIntersection { parts } => {
359 let mut printed: Vec<&Type> = Vec::new();
364 let mut first = true;
365 for part in parts.iter() {
366 if printed.contains(&part) {
367 continue;
368 }
369 printed.push(part);
370 if !first {
371 f.write_str("&")?;
372 }
373 first = false;
374 write!(f, "{part}")?;
375 }
376 Ok(())
377 }
378 }
379 }
380}
381
382#[cfg(test)]
383mod tests {
384 use super::*;
385
386 #[test]
387 fn int_range_unbounded_displays_as_int() {
388 assert_eq!(
389 format!(
390 "{}",
391 Atomic::TIntRange {
392 min: None,
393 max: None
394 }
395 ),
396 "int"
397 );
398 }
399
400 #[test]
401 fn int_range_bounded_min_displays_range() {
402 assert_eq!(
403 format!(
404 "{}",
405 Atomic::TIntRange {
406 min: Some(0),
407 max: None
408 }
409 ),
410 "int<0, max>"
411 );
412 }
413
414 #[test]
415 fn int_range_bounded_max_displays_range() {
416 assert_eq!(
417 format!(
418 "{}",
419 Atomic::TIntRange {
420 min: None,
421 max: Some(100)
422 }
423 ),
424 "int<min, 100>"
425 );
426 }
427
428 #[test]
429 fn int_range_fully_bounded_displays_range() {
430 assert_eq!(
431 format!(
432 "{}",
433 Atomic::TIntRange {
434 min: Some(1),
435 max: Some(10)
436 }
437 ),
438 "int<1, 10>"
439 );
440 }
441
442 #[test]
443 fn unbounded_int_range_in_union_displays_as_int() {
444 let mut u = Type::empty();
445 u.add_type(Atomic::TIntRange {
446 min: None,
447 max: None,
448 });
449 u.add_type(Atomic::TFalse);
450 assert_eq!(format!("{u}"), "int|false");
451 }
452
453 #[test]
454 fn array_of_mixed_mixed_collapses_to_array() {
455 let atomic = Atomic::TArray {
456 key: Box::new(Type::mixed()),
457 value: Box::new(Type::mixed()),
458 };
459 assert_eq!(format!("{atomic}"), "array");
460 }
461
462 #[test]
463 fn array_of_array_key_mixed_collapses_to_array() {
464 let atomic = Atomic::TArray {
465 key: Box::new(Type::array_key()),
466 value: Box::new(Type::mixed()),
467 };
468 assert_eq!(format!("{atomic}"), "array");
469 }
470
471 #[test]
472 fn array_of_int_mixed_does_not_collapse() {
473 let atomic = Atomic::TArray {
474 key: Box::new(Type::int()),
475 value: Box::new(Type::mixed()),
476 };
477 assert_eq!(format!("{atomic}"), "array<int, mixed>");
478 }
479
480 #[test]
481 fn array_of_mixed_string_does_not_collapse() {
482 let atomic = Atomic::TArray {
483 key: Box::new(Type::mixed()),
484 value: Box::new(Type::string()),
485 };
486 assert_eq!(format!("{atomic}"), "array<mixed, string>");
487 }
488
489 #[test]
490 fn non_empty_array_of_mixed_mixed_collapses() {
491 let atomic = Atomic::TNonEmptyArray {
492 key: Box::new(Type::mixed()),
493 value: Box::new(Type::mixed()),
494 };
495 assert_eq!(format!("{atomic}"), "non-empty-array");
496 }
497
498 #[test]
499 fn list_of_mixed_collapses_to_list() {
500 let atomic = Atomic::TList {
501 value: Box::new(Type::mixed()),
502 };
503 assert_eq!(format!("{atomic}"), "list");
504 }
505
506 #[test]
507 fn list_of_string_does_not_collapse() {
508 let atomic = Atomic::TList {
509 value: Box::new(Type::string()),
510 };
511 assert_eq!(format!("{atomic}"), "list<string>");
512 }
513
514 #[test]
515 fn non_empty_list_of_mixed_collapses() {
516 let atomic = Atomic::TNonEmptyList {
517 value: Box::new(Type::mixed()),
518 };
519 assert_eq!(format!("{atomic}"), "non-empty-list");
520 }
521
522 #[test]
523 fn named_object_all_mixed_params_collapses_to_bare_name() {
524 let atomic = Atomic::TNamedObject {
525 fqcn: "Traversable".into(),
526 type_params: crate::union::vec_to_type_params(vec![Type::mixed(), Type::mixed()]),
527 };
528 assert_eq!(format!("{atomic}"), "Traversable");
529 }
530
531 #[test]
532 fn named_object_with_one_concrete_param_does_not_collapse() {
533 let atomic = Atomic::TNamedObject {
534 fqcn: "Traversable".into(),
535 type_params: crate::union::vec_to_type_params(vec![Type::int(), Type::mixed()]),
536 };
537 assert_eq!(format!("{atomic}"), "Traversable<int, mixed>");
538 }
539
540 #[test]
541 fn named_object_with_mixed_bounded_template_param_does_not_collapse() {
542 let template_param = Atomic::TTemplateParam {
546 name: "T".into(),
547 as_type: Box::new(Type::mixed()),
548 defining_entity: "MyClass".into(),
549 };
550 let atomic = Atomic::TNamedObject {
551 fqcn: "MyClass".into(),
552 type_params: crate::union::vec_to_type_params(vec![Type::single(template_param)]),
553 };
554 assert_eq!(format!("{atomic}"), "MyClass<T>");
555 }
556
557 fn bare_traversable() -> Atomic {
558 Atomic::TNamedObject {
559 fqcn: "Traversable".into(),
560 type_params: crate::union::empty_type_params(),
561 }
562 }
563
564 #[test]
565 fn array_mixed_mixed_or_traversable_collapses_to_iterable() {
566 let mut u = Type::single(Atomic::TArray {
567 key: Box::new(Type::array_key()),
568 value: Box::new(Type::mixed()),
569 });
570 u.add_type(bare_traversable());
571 assert_eq!(format!("{u}"), "iterable");
572 }
573
574 #[test]
575 fn parameterized_array_or_matching_traversable_collapses_to_iterable() {
576 let key = Type::string();
577 let value = Type::int();
578 let mut u = Type::single(Atomic::TArray {
579 key: Box::new(key.clone()),
580 value: Box::new(value.clone()),
581 });
582 u.add_type(Atomic::TNamedObject {
583 fqcn: "Traversable".into(),
584 type_params: crate::union::vec_to_type_params(vec![key, value]),
585 });
586 assert_eq!(format!("{u}"), "iterable<string, int>");
587 }
588
589 #[test]
590 fn iterable_collapse_preserves_other_union_members() {
591 let mut u = Type::single(Atomic::TArray {
592 key: Box::new(Type::array_key()),
593 value: Box::new(Type::mixed()),
594 });
595 u.add_type(bare_traversable());
596 u.add_type(Atomic::TNull);
597 assert_eq!(format!("{u}"), "iterable|null");
598 }
599
600 #[test]
601 fn array_with_mismatched_bare_traversable_does_not_collapse() {
602 let mut u = Type::single(Atomic::TArray {
607 key: Box::new(Type::int()),
608 value: Box::new(Type::string()),
609 });
610 u.add_type(bare_traversable());
611 assert_eq!(format!("{u}"), "array<int, string>|Traversable");
612 }
613
614 #[test]
615 fn array_with_non_matching_parameterized_traversable_does_not_collapse() {
616 let mut u = Type::single(Atomic::TArray {
617 key: Box::new(Type::int()),
618 value: Box::new(Type::string()),
619 });
620 u.add_type(Atomic::TNamedObject {
621 fqcn: "Traversable".into(),
622 type_params: crate::union::vec_to_type_params(vec![Type::string(), Type::int()]),
623 });
624 assert_eq!(
625 format!("{u}"),
626 "array<int, string>|Traversable<string, int>"
627 );
628 }
629
630 fn named_object(fqcn: &str) -> Atomic {
631 Atomic::TNamedObject {
632 fqcn: fqcn.into(),
633 type_params: crate::union::empty_type_params(),
634 }
635 }
636
637 #[test]
638 fn intersection_drops_exact_duplicate_part() {
639 let atomic = Atomic::TIntersection {
640 parts: crate::union::vec_to_type_params(vec![
641 Type::single(named_object("Foo")),
642 Type::single(named_object("Foo")),
643 ]),
644 };
645 assert_eq!(format!("{atomic}"), "Foo");
646 }
647
648 #[test]
649 fn intersection_keeps_distinct_parts() {
650 let atomic = Atomic::TIntersection {
651 parts: crate::union::vec_to_type_params(vec![
652 Type::single(named_object("Countable")),
653 Type::single(named_object("Traversable")),
654 ]),
655 };
656 assert_eq!(format!("{atomic}"), "Countable&Traversable");
657 }
658
659 #[test]
660 fn intersection_drops_duplicate_among_three_parts() {
661 let atomic = Atomic::TIntersection {
662 parts: crate::union::vec_to_type_params(vec![
663 Type::single(named_object("Foo")),
664 Type::single(named_object("Bar")),
665 Type::single(named_object("Foo")),
666 ]),
667 };
668 assert_eq!(format!("{atomic}"), "Foo&Bar");
669 }
670}