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