Skip to main content

mir_types/
display.rs

1use std::fmt;
2
3use crate::atomic::{Atomic, IntRefinement, PropertyFilter, StringRefinement};
4use crate::union::Type;
5
6/// Write `items` separated by `sep` straight into the formatter, avoiding the
7/// intermediate `Vec<String>` + `join` allocations.
8fn 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
22/// True when `t` is precisely `mixed` and nothing else — deliberately
23/// stricter than [`Type::is_mixed`], which also treats an unconstrained
24/// template parameter as mixed. A template placeholder is a meaningful part
25/// of a generic signature (e.g. `array<TKey, TValue>`) and must still be
26/// printed, whereas a literal, unconstrained `mixed` is a default that adds
27/// no information and can be collapsed away.
28fn is_exactly_mixed(t: &Type) -> bool {
29    matches!(t.types.as_slice(), [Atomic::TMixed])
30}
31
32/// Write a comma-separated callable/closure parameter type list, printing
33/// `mixed` for untyped params.
34fn 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
47/// PHP's `iterable` is defined as exactly `array|Traversable`, so a union
48/// containing a matching `TArray{key, value}` + `Traversable` pair prints no
49/// more information as those two members than it would as `iterable`. Returns
50/// the pair's indices (lower, higher) and the rendered replacement text.
51///
52/// The `Traversable` member only counts as a match when it's unparameterized
53/// (the bare-`iterable` decomposition) or when its type params are exactly
54/// `[key, value]` (the `iterable<K, V>` decomposition) — a bare `Traversable`
55/// paired with a *more specific* array (e.g. `array<int, string>|Traversable`)
56/// must NOT collapse, since the bare `Traversable` side carries no such
57/// key/value guarantee and collapsing would overclaim precision.
58fn 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                // A bare (unparameterized) Traversable makes no key/value
77                // guarantee, so it only pairs safely with the fully generic
78                // `array` — pairing it with a more specific array would
79                // claim the Traversable side shares that specificity too.
80                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
127/// String literal text with its non-UTF-8 bytes written as `\xNN`.
128pub 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                // Bytes that are not valid UTF-8 are stored as U+F700 + byte.
142                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                    StringRefinement::DecimalInt => "decimal-int",
171                    StringRefinement::NonDecimalInt => "non-decimal-int",
172                };
173                write!(f, "{prefix}{kind}-string")
174            }
175
176            Atomic::TInt => write!(f, "int"),
177            Atomic::TLiteralInt(n) => write!(f, "{n}"),
178            Atomic::TIntRange { min, max } => match (min, max) {
179                (None, None) => write!(f, "int"),
180                (lo, hi) => {
181                    let lo = lo.map_or_else(|| "min".to_string(), |n| n.to_string());
182                    let hi = hi.map_or_else(|| "max".to_string(), |n| n.to_string());
183                    write!(f, "int<{lo}, {hi}>")
184                }
185            },
186            Atomic::TPositiveInt => write!(f, "positive-int"),
187            Atomic::TNegativeInt => write!(f, "negative-int"),
188            Atomic::TNonNegativeInt => write!(f, "non-negative-int"),
189            Atomic::TRefinedInt(IntRefinement::Literal) => write!(f, "literal-int"),
190            Atomic::TRefinedInt(IntRefinement::MaskOf(target)) => {
191                write!(f, "int-mask-of<{target}>")
192            }
193
194            Atomic::TFloat | Atomic::TIntegralFloat => write!(f, "float"),
195            Atomic::TLiteralFloat(high, low) => {
196                let bits = ((*high as u64) << 32) | (*low as u32 as u64);
197                let value = f64::from_bits(bits);
198                write!(f, "{value}")
199            }
200
201            Atomic::TBool => write!(f, "bool"),
202            Atomic::TTrue => write!(f, "true"),
203            Atomic::TFalse => write!(f, "false"),
204
205            Atomic::TNull => write!(f, "null"),
206            Atomic::TVoid => write!(f, "void"),
207            Atomic::TNever => write!(f, "never"),
208            Atomic::TMixed => write!(f, "mixed"),
209            Atomic::TScalar => write!(f, "scalar"),
210            Atomic::TNumeric => write!(f, "numeric"),
211
212            Atomic::TObject => write!(f, "object"),
213            Atomic::TResource => write!(f, "resource"),
214            Atomic::TClosedResource => write!(f, "closed-resource"),
215            Atomic::TPropertiesOf { class, filter } => {
216                let prefix = match filter {
217                    PropertyFilter::All => "",
218                    PropertyFilter::Public => "public-",
219                    PropertyFilter::Protected => "protected-",
220                    PropertyFilter::Private => "private-",
221                };
222                write!(f, "{prefix}properties-of<{class}>")
223            }
224            Atomic::TNamedObject { fqcn, type_params } => {
225                // `Traversable<mixed, mixed>`/`Generator<mixed, mixed, mixed, mixed>`
226                // carry no more information than the bare class name — every
227                // param resolving to the unconstrained default is exactly the
228                // case an omitted type-param list would represent.
229                if type_params.is_empty() || type_params.iter().all(is_exactly_mixed) {
230                    write!(f, "{fqcn}")
231                } else {
232                    write!(f, "{fqcn}<")?;
233                    write_joined(f, type_params.iter(), ", ")?;
234                    f.write_str(">")
235                }
236            }
237            Atomic::TStaticObject { fqcn } => write!(f, "static({fqcn})"),
238            Atomic::TSelf { fqcn } => write!(f, "self({fqcn})"),
239            Atomic::TParent { fqcn } => write!(f, "parent({fqcn})"),
240
241            Atomic::TCallable {
242                params,
243                return_type,
244                is_pure,
245            } => {
246                if *is_pure {
247                    f.write_str("pure-")?;
248                }
249                match (params, return_type) {
250                    (None, None) => f.write_str("callable"),
251                    (Some(params), return_type) => {
252                        f.write_str("callable(")?;
253                        write_param_types(f, params)?;
254                        match return_type {
255                            Some(r) => write!(f, "): {r}"),
256                            None => f.write_str("): mixed"),
257                        }
258                    }
259                    (None, Some(ret)) => write!(f, "callable(): {ret}"),
260                }
261            }
262            Atomic::TClosure { data } => {
263                if data.is_pure {
264                    f.write_str("pure-")?;
265                }
266                f.write_str("Closure(")?;
267                write_param_types(f, &data.params)?;
268                write!(f, "): {}", data.return_type)
269            }
270
271            Atomic::TArray { key, value } => {
272                // `array<mixed, mixed>` and `array<array-key, mixed>` are both
273                // just `array` — `array-key` (int|string) is already the
274                // maximal legal key domain, so it's as much a "default" key
275                // as `mixed` is.
276                if is_exactly_mixed(value) && (is_exactly_mixed(key) || key.is_array_key()) {
277                    write!(f, "array")
278                } else {
279                    write!(f, "array<{key}, {value}>")
280                }
281            }
282            Atomic::TList { value } => {
283                if is_exactly_mixed(value) {
284                    write!(f, "list")
285                } else {
286                    write!(f, "list<{value}>")
287                }
288            }
289            Atomic::TNonEmptyArray { key, value } => {
290                if is_exactly_mixed(value) && (is_exactly_mixed(key) || key.is_array_key()) {
291                    write!(f, "non-empty-array")
292                } else {
293                    write!(f, "non-empty-array<{key}, {value}>")
294                }
295            }
296            Atomic::TNonEmptyList { value } => {
297                if is_exactly_mixed(value) {
298                    write!(f, "non-empty-list")
299                } else {
300                    write!(f, "non-empty-list<{value}>")
301                }
302            }
303            Atomic::TObjectShape { properties } => {
304                f.write_str("object{")?;
305                for (i, (k, v)) in properties.iter().enumerate() {
306                    if i > 0 {
307                        f.write_str(", ")?;
308                    }
309                    match k {
310                        crate::atomic::ArrayKey::String(s) => f.write_str(s)?,
311                        crate::atomic::ArrayKey::Int(n) => write!(f, "{n}")?,
312                    }
313                    if v.optional {
314                        f.write_str("?")?;
315                    }
316                    write!(f, ": {}", v.ty)?;
317                }
318                f.write_str("}")
319            }
320            Atomic::TKeyedArray { properties, .. } => {
321                f.write_str("array{")?;
322                for (i, (k, v)) in properties.iter().enumerate() {
323                    if i > 0 {
324                        f.write_str(", ")?;
325                    }
326                    match k {
327                        crate::atomic::ArrayKey::String(s) => write!(f, "'{}'", LiteralText(s))?,
328                        crate::atomic::ArrayKey::Int(n) => write!(f, "{n}")?,
329                    }
330                    if v.optional {
331                        f.write_str("?")?;
332                    }
333                    write!(f, ": {}", v.ty)?;
334                }
335                if let Some(rest) = &properties.remainder {
336                    let sep = if properties.is_empty() { "" } else { ", " };
337                    write!(f, "{sep}...<{rest}>")?;
338                }
339                f.write_str("}")
340            }
341
342            Atomic::TTemplateParam { name, .. } => write!(f, "{name}"),
343            Atomic::TKeyOf { target } => write!(f, "key-of<{target}>"),
344            Atomic::TValueOf { target } => write!(f, "value-of<{target}>"),
345            Atomic::TConditional { data } => {
346                let (subject, if_true, if_false) = (&data.subject, &data.if_true, &data.if_false);
347                match &data.param_name {
348                    Some(name) => write!(f, "(${name} is {subject} ? {if_true} : {if_false})"),
349                    None => write!(f, "({subject} is ? {if_true} : {if_false})"),
350                }
351            }
352
353            Atomic::TInterfaceString(None) => write!(f, "interface-string"),
354            Atomic::TInterfaceString(Some(iface)) => write!(f, "interface-string<{iface}>"),
355            Atomic::TEnumString => write!(f, "enum-string"),
356            Atomic::TTraitString => write!(f, "trait-string"),
357            Atomic::TLiteralEnumCase {
358                enum_fqcn,
359                case_name,
360            } => {
361                write!(f, "{enum_fqcn}::{case_name}")
362            }
363
364            Atomic::TIntersection { parts } => {
365                // Skip exact-duplicate parts (e.g. a redundant `Foo&Foo`) —
366                // hierarchy-aware redundancy (like `Iterator&Traversable`)
367                // needs class info this crate doesn't have, so only drop
368                // parts that are structurally identical to an earlier one.
369                let mut printed: Vec<&Type> = Vec::new();
370                let mut first = true;
371                for part in parts.iter() {
372                    if printed.contains(&part) {
373                        continue;
374                    }
375                    printed.push(part);
376                    if !first {
377                        f.write_str("&")?;
378                    }
379                    first = false;
380                    write!(f, "{part}")?;
381                }
382                Ok(())
383            }
384        }
385    }
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391
392    #[test]
393    fn int_range_unbounded_displays_as_int() {
394        assert_eq!(
395            format!(
396                "{}",
397                Atomic::TIntRange {
398                    min: None,
399                    max: None
400                }
401            ),
402            "int"
403        );
404    }
405
406    #[test]
407    fn int_range_bounded_min_displays_range() {
408        assert_eq!(
409            format!(
410                "{}",
411                Atomic::TIntRange {
412                    min: Some(0),
413                    max: None
414                }
415            ),
416            "int<0, max>"
417        );
418    }
419
420    #[test]
421    fn int_range_bounded_max_displays_range() {
422        assert_eq!(
423            format!(
424                "{}",
425                Atomic::TIntRange {
426                    min: None,
427                    max: Some(100)
428                }
429            ),
430            "int<min, 100>"
431        );
432    }
433
434    #[test]
435    fn int_range_fully_bounded_displays_range() {
436        assert_eq!(
437            format!(
438                "{}",
439                Atomic::TIntRange {
440                    min: Some(1),
441                    max: Some(10)
442                }
443            ),
444            "int<1, 10>"
445        );
446    }
447
448    #[test]
449    fn unbounded_int_range_in_union_displays_as_int() {
450        let mut u = Type::empty();
451        u.add_type(Atomic::TIntRange {
452            min: None,
453            max: None,
454        });
455        u.add_type(Atomic::TFalse);
456        assert_eq!(format!("{u}"), "int|false");
457    }
458
459    #[test]
460    fn array_of_mixed_mixed_collapses_to_array() {
461        let atomic = Atomic::TArray {
462            key: Box::new(Type::mixed()),
463            value: Box::new(Type::mixed()),
464        };
465        assert_eq!(format!("{atomic}"), "array");
466    }
467
468    #[test]
469    fn array_of_array_key_mixed_collapses_to_array() {
470        let atomic = Atomic::TArray {
471            key: Box::new(Type::array_key()),
472            value: Box::new(Type::mixed()),
473        };
474        assert_eq!(format!("{atomic}"), "array");
475    }
476
477    #[test]
478    fn array_of_int_mixed_does_not_collapse() {
479        let atomic = Atomic::TArray {
480            key: Box::new(Type::int()),
481            value: Box::new(Type::mixed()),
482        };
483        assert_eq!(format!("{atomic}"), "array<int, mixed>");
484    }
485
486    #[test]
487    fn array_of_mixed_string_does_not_collapse() {
488        let atomic = Atomic::TArray {
489            key: Box::new(Type::mixed()),
490            value: Box::new(Type::string()),
491        };
492        assert_eq!(format!("{atomic}"), "array<mixed, string>");
493    }
494
495    #[test]
496    fn non_empty_array_of_mixed_mixed_collapses() {
497        let atomic = Atomic::TNonEmptyArray {
498            key: Box::new(Type::mixed()),
499            value: Box::new(Type::mixed()),
500        };
501        assert_eq!(format!("{atomic}"), "non-empty-array");
502    }
503
504    #[test]
505    fn list_of_mixed_collapses_to_list() {
506        let atomic = Atomic::TList {
507            value: Box::new(Type::mixed()),
508        };
509        assert_eq!(format!("{atomic}"), "list");
510    }
511
512    #[test]
513    fn list_of_string_does_not_collapse() {
514        let atomic = Atomic::TList {
515            value: Box::new(Type::string()),
516        };
517        assert_eq!(format!("{atomic}"), "list<string>");
518    }
519
520    #[test]
521    fn non_empty_list_of_mixed_collapses() {
522        let atomic = Atomic::TNonEmptyList {
523            value: Box::new(Type::mixed()),
524        };
525        assert_eq!(format!("{atomic}"), "non-empty-list");
526    }
527
528    #[test]
529    fn named_object_all_mixed_params_collapses_to_bare_name() {
530        let atomic = Atomic::TNamedObject {
531            fqcn: "Traversable".into(),
532            type_params: crate::union::vec_to_type_params(vec![Type::mixed(), Type::mixed()]),
533        };
534        assert_eq!(format!("{atomic}"), "Traversable");
535    }
536
537    #[test]
538    fn named_object_with_one_concrete_param_does_not_collapse() {
539        let atomic = Atomic::TNamedObject {
540            fqcn: "Traversable".into(),
541            type_params: crate::union::vec_to_type_params(vec![Type::int(), Type::mixed()]),
542        };
543        assert_eq!(format!("{atomic}"), "Traversable<int, mixed>");
544    }
545
546    #[test]
547    fn named_object_with_mixed_bounded_template_param_does_not_collapse() {
548        // An unresolved `T` template parameter (even one bounded by `mixed`)
549        // is a meaningful part of a generic signature and must never be
550        // confused with a literal, information-free `mixed` default.
551        let template_param = Atomic::TTemplateParam {
552            name: "T".into(),
553            as_type: Box::new(Type::mixed()),
554            defining_entity: "MyClass".into(),
555        };
556        let atomic = Atomic::TNamedObject {
557            fqcn: "MyClass".into(),
558            type_params: crate::union::vec_to_type_params(vec![Type::single(template_param)]),
559        };
560        assert_eq!(format!("{atomic}"), "MyClass<T>");
561    }
562
563    fn bare_traversable() -> Atomic {
564        Atomic::TNamedObject {
565            fqcn: "Traversable".into(),
566            type_params: crate::union::empty_type_params(),
567        }
568    }
569
570    #[test]
571    fn array_mixed_mixed_or_traversable_collapses_to_iterable() {
572        let mut u = Type::single(Atomic::TArray {
573            key: Box::new(Type::array_key()),
574            value: Box::new(Type::mixed()),
575        });
576        u.add_type(bare_traversable());
577        assert_eq!(format!("{u}"), "iterable");
578    }
579
580    #[test]
581    fn parameterized_array_or_matching_traversable_collapses_to_iterable() {
582        let key = Type::string();
583        let value = Type::int();
584        let mut u = Type::single(Atomic::TArray {
585            key: Box::new(key.clone()),
586            value: Box::new(value.clone()),
587        });
588        u.add_type(Atomic::TNamedObject {
589            fqcn: "Traversable".into(),
590            type_params: crate::union::vec_to_type_params(vec![key, value]),
591        });
592        assert_eq!(format!("{u}"), "iterable<string, int>");
593    }
594
595    #[test]
596    fn iterable_collapse_preserves_other_union_members() {
597        let mut u = Type::single(Atomic::TArray {
598            key: Box::new(Type::array_key()),
599            value: Box::new(Type::mixed()),
600        });
601        u.add_type(bare_traversable());
602        u.add_type(Atomic::TNull);
603        assert_eq!(format!("{u}"), "iterable|null");
604    }
605
606    #[test]
607    fn array_with_mismatched_bare_traversable_does_not_collapse() {
608        // A bare (unparameterized) `Traversable` carries no key/value
609        // guarantee, so pairing it with a *more specific* array must not be
610        // rendered as `iterable<int, string>` — that would overclaim that the
611        // `Traversable` side is bound to the same key/value types too.
612        let mut u = Type::single(Atomic::TArray {
613            key: Box::new(Type::int()),
614            value: Box::new(Type::string()),
615        });
616        u.add_type(bare_traversable());
617        assert_eq!(format!("{u}"), "array<int, string>|Traversable");
618    }
619
620    #[test]
621    fn array_with_non_matching_parameterized_traversable_does_not_collapse() {
622        let mut u = Type::single(Atomic::TArray {
623            key: Box::new(Type::int()),
624            value: Box::new(Type::string()),
625        });
626        u.add_type(Atomic::TNamedObject {
627            fqcn: "Traversable".into(),
628            type_params: crate::union::vec_to_type_params(vec![Type::string(), Type::int()]),
629        });
630        assert_eq!(
631            format!("{u}"),
632            "array<int, string>|Traversable<string, int>"
633        );
634    }
635
636    fn named_object(fqcn: &str) -> Atomic {
637        Atomic::TNamedObject {
638            fqcn: fqcn.into(),
639            type_params: crate::union::empty_type_params(),
640        }
641    }
642
643    #[test]
644    fn intersection_drops_exact_duplicate_part() {
645        let atomic = Atomic::TIntersection {
646            parts: crate::union::vec_to_type_params(vec![
647                Type::single(named_object("Foo")),
648                Type::single(named_object("Foo")),
649            ]),
650        };
651        assert_eq!(format!("{atomic}"), "Foo");
652    }
653
654    #[test]
655    fn intersection_keeps_distinct_parts() {
656        let atomic = Atomic::TIntersection {
657            parts: crate::union::vec_to_type_params(vec![
658                Type::single(named_object("Countable")),
659                Type::single(named_object("Traversable")),
660            ]),
661        };
662        assert_eq!(format!("{atomic}"), "Countable&Traversable");
663    }
664
665    #[test]
666    fn intersection_drops_duplicate_among_three_parts() {
667        let atomic = Atomic::TIntersection {
668            parts: crate::union::vec_to_type_params(vec![
669                Type::single(named_object("Foo")),
670                Type::single(named_object("Bar")),
671                Type::single(named_object("Foo")),
672            ]),
673        };
674        assert_eq!(format!("{atomic}"), "Foo&Bar");
675    }
676}