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::TOpenResource => write!(f, "open-resource"),
216            Atomic::TPropertiesOf { class, filter } => {
217                let prefix = match filter {
218                    PropertyFilter::All => "",
219                    PropertyFilter::Public => "public-",
220                    PropertyFilter::Protected => "protected-",
221                    PropertyFilter::Private => "private-",
222                };
223                write!(f, "{prefix}properties-of<{class}>")
224            }
225            Atomic::TNamedObject { fqcn, type_params } => {
226                // `Traversable<mixed, mixed>`/`Generator<mixed, mixed, mixed, mixed>`
227                // carry no more information than the bare class name — every
228                // param resolving to the unconstrained default is exactly the
229                // case an omitted type-param list would represent.
230                if type_params.is_empty() || type_params.iter().all(is_exactly_mixed) {
231                    write!(f, "{fqcn}")
232                } else {
233                    write!(f, "{fqcn}<")?;
234                    write_joined(f, type_params.iter(), ", ")?;
235                    f.write_str(">")
236                }
237            }
238            Atomic::TStaticObject { fqcn } => write!(f, "static({fqcn})"),
239            Atomic::TSelf { fqcn } => write!(f, "self({fqcn})"),
240            Atomic::TParent { fqcn } => write!(f, "parent({fqcn})"),
241
242            Atomic::TCallable {
243                params,
244                return_type,
245                is_pure,
246            } => {
247                if *is_pure {
248                    f.write_str("pure-")?;
249                }
250                match (params, return_type) {
251                    (None, None) => f.write_str("callable"),
252                    (Some(params), return_type) => {
253                        f.write_str("callable(")?;
254                        write_param_types(f, params)?;
255                        match return_type {
256                            Some(r) => write!(f, "): {r}"),
257                            None => f.write_str("): mixed"),
258                        }
259                    }
260                    (None, Some(ret)) => write!(f, "callable(): {ret}"),
261                }
262            }
263            Atomic::TClosure { data } => {
264                if data.is_pure {
265                    f.write_str("pure-")?;
266                }
267                f.write_str("Closure(")?;
268                write_param_types(f, &data.params)?;
269                write!(f, "): {}", data.return_type)
270            }
271
272            Atomic::TArray { key, value } => {
273                // `array<mixed, mixed>` and `array<array-key, mixed>` are both
274                // just `array` — `array-key` (int|string) is already the
275                // maximal legal key domain, so it's as much a "default" key
276                // as `mixed` is.
277                if is_exactly_mixed(value) && (is_exactly_mixed(key) || key.is_array_key()) {
278                    write!(f, "array")
279                } else {
280                    write!(f, "array<{key}, {value}>")
281                }
282            }
283            Atomic::TList { value } => {
284                if is_exactly_mixed(value) {
285                    write!(f, "list")
286                } else {
287                    write!(f, "list<{value}>")
288                }
289            }
290            Atomic::TNonEmptyArray { key, value } => {
291                if is_exactly_mixed(value) && (is_exactly_mixed(key) || key.is_array_key()) {
292                    write!(f, "non-empty-array")
293                } else {
294                    write!(f, "non-empty-array<{key}, {value}>")
295                }
296            }
297            Atomic::TNonEmptyList { value } => {
298                if is_exactly_mixed(value) {
299                    write!(f, "non-empty-list")
300                } else {
301                    write!(f, "non-empty-list<{value}>")
302                }
303            }
304            Atomic::TObjectShape { properties } => {
305                f.write_str("object{")?;
306                for (i, (k, v)) in properties.iter().enumerate() {
307                    if i > 0 {
308                        f.write_str(", ")?;
309                    }
310                    match k {
311                        crate::atomic::ArrayKey::String(s) => f.write_str(s)?,
312                        crate::atomic::ArrayKey::Int(n) => write!(f, "{n}")?,
313                    }
314                    if v.optional {
315                        f.write_str("?")?;
316                    }
317                    write!(f, ": {}", v.ty)?;
318                }
319                f.write_str("}")
320            }
321            Atomic::TKeyedArray { properties, .. } => {
322                f.write_str("array{")?;
323                for (i, (k, v)) in properties.iter().enumerate() {
324                    if i > 0 {
325                        f.write_str(", ")?;
326                    }
327                    match k {
328                        crate::atomic::ArrayKey::String(s) => write!(f, "'{}'", LiteralText(s))?,
329                        crate::atomic::ArrayKey::Int(n) => write!(f, "{n}")?,
330                    }
331                    if v.optional {
332                        f.write_str("?")?;
333                    }
334                    write!(f, ": {}", v.ty)?;
335                }
336                if let Some(rest) = &properties.remainder {
337                    let sep = if properties.is_empty() { "" } else { ", " };
338                    write!(f, "{sep}...<{rest}>")?;
339                }
340                f.write_str("}")
341            }
342
343            Atomic::TTemplateParam { name, .. } => write!(f, "{name}"),
344            Atomic::TKeyOf { target } => write!(f, "key-of<{target}>"),
345            Atomic::TValueOf { target } => write!(f, "value-of<{target}>"),
346            Atomic::TConditional { data } => {
347                let (subject, if_true, if_false) = (&data.subject, &data.if_true, &data.if_false);
348                match &data.param_name {
349                    Some(name) => write!(f, "(${name} is {subject} ? {if_true} : {if_false})"),
350                    None => write!(f, "({subject} is ? {if_true} : {if_false})"),
351                }
352            }
353
354            Atomic::TInterfaceString(None) => write!(f, "interface-string"),
355            Atomic::TInterfaceString(Some(iface)) => write!(f, "interface-string<{iface}>"),
356            Atomic::TEnumString => write!(f, "enum-string"),
357            Atomic::TTraitString => write!(f, "trait-string"),
358            Atomic::TLiteralEnumCase {
359                enum_fqcn,
360                case_name,
361            } => {
362                write!(f, "{enum_fqcn}::{case_name}")
363            }
364
365            Atomic::TIntersection { parts } => {
366                // Skip exact-duplicate parts (e.g. a redundant `Foo&Foo`) —
367                // hierarchy-aware redundancy (like `Iterator&Traversable`)
368                // needs class info this crate doesn't have, so only drop
369                // parts that are structurally identical to an earlier one.
370                let mut printed: Vec<&Type> = Vec::new();
371                let mut first = true;
372                for part in parts.iter() {
373                    if printed.contains(&part) {
374                        continue;
375                    }
376                    printed.push(part);
377                    if !first {
378                        f.write_str("&")?;
379                    }
380                    first = false;
381                    write!(f, "{part}")?;
382                }
383                Ok(())
384            }
385        }
386    }
387}
388
389#[cfg(test)]
390mod tests {
391    use super::*;
392
393    #[test]
394    fn int_range_unbounded_displays_as_int() {
395        assert_eq!(
396            format!(
397                "{}",
398                Atomic::TIntRange {
399                    min: None,
400                    max: None
401                }
402            ),
403            "int"
404        );
405    }
406
407    #[test]
408    fn int_range_bounded_min_displays_range() {
409        assert_eq!(
410            format!(
411                "{}",
412                Atomic::TIntRange {
413                    min: Some(0),
414                    max: None
415                }
416            ),
417            "int<0, max>"
418        );
419    }
420
421    #[test]
422    fn int_range_bounded_max_displays_range() {
423        assert_eq!(
424            format!(
425                "{}",
426                Atomic::TIntRange {
427                    min: None,
428                    max: Some(100)
429                }
430            ),
431            "int<min, 100>"
432        );
433    }
434
435    #[test]
436    fn int_range_fully_bounded_displays_range() {
437        assert_eq!(
438            format!(
439                "{}",
440                Atomic::TIntRange {
441                    min: Some(1),
442                    max: Some(10)
443                }
444            ),
445            "int<1, 10>"
446        );
447    }
448
449    #[test]
450    fn unbounded_int_range_in_union_displays_as_int() {
451        let mut u = Type::empty();
452        u.add_type(Atomic::TIntRange {
453            min: None,
454            max: None,
455        });
456        u.add_type(Atomic::TFalse);
457        assert_eq!(format!("{u}"), "int|false");
458    }
459
460    #[test]
461    fn array_of_mixed_mixed_collapses_to_array() {
462        let atomic = Atomic::TArray {
463            key: Box::new(Type::mixed()),
464            value: Box::new(Type::mixed()),
465        };
466        assert_eq!(format!("{atomic}"), "array");
467    }
468
469    #[test]
470    fn array_of_array_key_mixed_collapses_to_array() {
471        let atomic = Atomic::TArray {
472            key: Box::new(Type::array_key()),
473            value: Box::new(Type::mixed()),
474        };
475        assert_eq!(format!("{atomic}"), "array");
476    }
477
478    #[test]
479    fn array_of_int_mixed_does_not_collapse() {
480        let atomic = Atomic::TArray {
481            key: Box::new(Type::int()),
482            value: Box::new(Type::mixed()),
483        };
484        assert_eq!(format!("{atomic}"), "array<int, mixed>");
485    }
486
487    #[test]
488    fn array_of_mixed_string_does_not_collapse() {
489        let atomic = Atomic::TArray {
490            key: Box::new(Type::mixed()),
491            value: Box::new(Type::string()),
492        };
493        assert_eq!(format!("{atomic}"), "array<mixed, string>");
494    }
495
496    #[test]
497    fn non_empty_array_of_mixed_mixed_collapses() {
498        let atomic = Atomic::TNonEmptyArray {
499            key: Box::new(Type::mixed()),
500            value: Box::new(Type::mixed()),
501        };
502        assert_eq!(format!("{atomic}"), "non-empty-array");
503    }
504
505    #[test]
506    fn list_of_mixed_collapses_to_list() {
507        let atomic = Atomic::TList {
508            value: Box::new(Type::mixed()),
509        };
510        assert_eq!(format!("{atomic}"), "list");
511    }
512
513    #[test]
514    fn list_of_string_does_not_collapse() {
515        let atomic = Atomic::TList {
516            value: Box::new(Type::string()),
517        };
518        assert_eq!(format!("{atomic}"), "list<string>");
519    }
520
521    #[test]
522    fn non_empty_list_of_mixed_collapses() {
523        let atomic = Atomic::TNonEmptyList {
524            value: Box::new(Type::mixed()),
525        };
526        assert_eq!(format!("{atomic}"), "non-empty-list");
527    }
528
529    #[test]
530    fn named_object_all_mixed_params_collapses_to_bare_name() {
531        let atomic = Atomic::TNamedObject {
532            fqcn: "Traversable".into(),
533            type_params: crate::union::vec_to_type_params(vec![Type::mixed(), Type::mixed()]),
534        };
535        assert_eq!(format!("{atomic}"), "Traversable");
536    }
537
538    #[test]
539    fn named_object_with_one_concrete_param_does_not_collapse() {
540        let atomic = Atomic::TNamedObject {
541            fqcn: "Traversable".into(),
542            type_params: crate::union::vec_to_type_params(vec![Type::int(), Type::mixed()]),
543        };
544        assert_eq!(format!("{atomic}"), "Traversable<int, mixed>");
545    }
546
547    #[test]
548    fn named_object_with_mixed_bounded_template_param_does_not_collapse() {
549        // An unresolved `T` template parameter (even one bounded by `mixed`)
550        // is a meaningful part of a generic signature and must never be
551        // confused with a literal, information-free `mixed` default.
552        let template_param = Atomic::TTemplateParam {
553            name: "T".into(),
554            as_type: Box::new(Type::mixed()),
555            defining_entity: "MyClass".into(),
556        };
557        let atomic = Atomic::TNamedObject {
558            fqcn: "MyClass".into(),
559            type_params: crate::union::vec_to_type_params(vec![Type::single(template_param)]),
560        };
561        assert_eq!(format!("{atomic}"), "MyClass<T>");
562    }
563
564    fn bare_traversable() -> Atomic {
565        Atomic::TNamedObject {
566            fqcn: "Traversable".into(),
567            type_params: crate::union::empty_type_params(),
568        }
569    }
570
571    #[test]
572    fn array_mixed_mixed_or_traversable_collapses_to_iterable() {
573        let mut u = Type::single(Atomic::TArray {
574            key: Box::new(Type::array_key()),
575            value: Box::new(Type::mixed()),
576        });
577        u.add_type(bare_traversable());
578        assert_eq!(format!("{u}"), "iterable");
579    }
580
581    #[test]
582    fn parameterized_array_or_matching_traversable_collapses_to_iterable() {
583        let key = Type::string();
584        let value = Type::int();
585        let mut u = Type::single(Atomic::TArray {
586            key: Box::new(key.clone()),
587            value: Box::new(value.clone()),
588        });
589        u.add_type(Atomic::TNamedObject {
590            fqcn: "Traversable".into(),
591            type_params: crate::union::vec_to_type_params(vec![key, value]),
592        });
593        assert_eq!(format!("{u}"), "iterable<string, int>");
594    }
595
596    #[test]
597    fn iterable_collapse_preserves_other_union_members() {
598        let mut u = Type::single(Atomic::TArray {
599            key: Box::new(Type::array_key()),
600            value: Box::new(Type::mixed()),
601        });
602        u.add_type(bare_traversable());
603        u.add_type(Atomic::TNull);
604        assert_eq!(format!("{u}"), "iterable|null");
605    }
606
607    #[test]
608    fn array_with_mismatched_bare_traversable_does_not_collapse() {
609        // A bare (unparameterized) `Traversable` carries no key/value
610        // guarantee, so pairing it with a *more specific* array must not be
611        // rendered as `iterable<int, string>` — that would overclaim that the
612        // `Traversable` side is bound to the same key/value types too.
613        let mut u = Type::single(Atomic::TArray {
614            key: Box::new(Type::int()),
615            value: Box::new(Type::string()),
616        });
617        u.add_type(bare_traversable());
618        assert_eq!(format!("{u}"), "array<int, string>|Traversable");
619    }
620
621    #[test]
622    fn array_with_non_matching_parameterized_traversable_does_not_collapse() {
623        let mut u = Type::single(Atomic::TArray {
624            key: Box::new(Type::int()),
625            value: Box::new(Type::string()),
626        });
627        u.add_type(Atomic::TNamedObject {
628            fqcn: "Traversable".into(),
629            type_params: crate::union::vec_to_type_params(vec![Type::string(), Type::int()]),
630        });
631        assert_eq!(
632            format!("{u}"),
633            "array<int, string>|Traversable<string, int>"
634        );
635    }
636
637    fn named_object(fqcn: &str) -> Atomic {
638        Atomic::TNamedObject {
639            fqcn: fqcn.into(),
640            type_params: crate::union::empty_type_params(),
641        }
642    }
643
644    #[test]
645    fn intersection_drops_exact_duplicate_part() {
646        let atomic = Atomic::TIntersection {
647            parts: crate::union::vec_to_type_params(vec![
648                Type::single(named_object("Foo")),
649                Type::single(named_object("Foo")),
650            ]),
651        };
652        assert_eq!(format!("{atomic}"), "Foo");
653    }
654
655    #[test]
656    fn intersection_keeps_distinct_parts() {
657        let atomic = Atomic::TIntersection {
658            parts: crate::union::vec_to_type_params(vec![
659                Type::single(named_object("Countable")),
660                Type::single(named_object("Traversable")),
661            ]),
662        };
663        assert_eq!(format!("{atomic}"), "Countable&Traversable");
664    }
665
666    #[test]
667    fn intersection_drops_duplicate_among_three_parts() {
668        let atomic = Atomic::TIntersection {
669            parts: crate::union::vec_to_type_params(vec![
670                Type::single(named_object("Foo")),
671                Type::single(named_object("Bar")),
672                Type::single(named_object("Foo")),
673            ]),
674        };
675        assert_eq!(format!("{atomic}"), "Foo&Bar");
676    }
677}