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