Skip to main content

mir_types/
display.rs

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