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::TConditional { data } => {
267                let (subject, if_true, if_false) = (&data.subject, &data.if_true, &data.if_false);
268                match &data.param_name {
269                    Some(name) => write!(f, "(${name} is {subject} ? {if_true} : {if_false})"),
270                    None => write!(f, "({subject} is ? {if_true} : {if_false})"),
271                }
272            }
273
274            Atomic::TInterfaceString(None) => write!(f, "interface-string"),
275            Atomic::TInterfaceString(Some(iface)) => write!(f, "interface-string<{iface}>"),
276            Atomic::TEnumString => write!(f, "enum-string"),
277            Atomic::TTraitString => write!(f, "trait-string"),
278            Atomic::TLiteralEnumCase {
279                enum_fqcn,
280                case_name,
281            } => {
282                write!(f, "{enum_fqcn}::{case_name}")
283            }
284
285            Atomic::TIntersection { parts } => {
286                // Skip exact-duplicate parts (e.g. a redundant `Foo&Foo`) —
287                // hierarchy-aware redundancy (like `Iterator&Traversable`)
288                // needs class info this crate doesn't have, so only drop
289                // parts that are structurally identical to an earlier one.
290                let mut printed: Vec<&Type> = Vec::new();
291                let mut first = true;
292                for part in parts.iter() {
293                    if printed.contains(&part) {
294                        continue;
295                    }
296                    printed.push(part);
297                    if !first {
298                        f.write_str("&")?;
299                    }
300                    first = false;
301                    write!(f, "{part}")?;
302                }
303                Ok(())
304            }
305        }
306    }
307}
308
309#[cfg(test)]
310mod tests {
311    use super::*;
312
313    #[test]
314    fn int_range_unbounded_displays_as_int() {
315        assert_eq!(
316            format!(
317                "{}",
318                Atomic::TIntRange {
319                    min: None,
320                    max: None
321                }
322            ),
323            "int"
324        );
325    }
326
327    #[test]
328    fn int_range_bounded_min_displays_range() {
329        assert_eq!(
330            format!(
331                "{}",
332                Atomic::TIntRange {
333                    min: Some(0),
334                    max: None
335                }
336            ),
337            "int<0, max>"
338        );
339    }
340
341    #[test]
342    fn int_range_bounded_max_displays_range() {
343        assert_eq!(
344            format!(
345                "{}",
346                Atomic::TIntRange {
347                    min: None,
348                    max: Some(100)
349                }
350            ),
351            "int<min, 100>"
352        );
353    }
354
355    #[test]
356    fn int_range_fully_bounded_displays_range() {
357        assert_eq!(
358            format!(
359                "{}",
360                Atomic::TIntRange {
361                    min: Some(1),
362                    max: Some(10)
363                }
364            ),
365            "int<1, 10>"
366        );
367    }
368
369    #[test]
370    fn unbounded_int_range_in_union_displays_as_int() {
371        let mut u = Type::empty();
372        u.add_type(Atomic::TIntRange {
373            min: None,
374            max: None,
375        });
376        u.add_type(Atomic::TFalse);
377        assert_eq!(format!("{u}"), "int|false");
378    }
379
380    #[test]
381    fn array_of_mixed_mixed_collapses_to_array() {
382        let atomic = Atomic::TArray {
383            key: Box::new(Type::mixed()),
384            value: Box::new(Type::mixed()),
385        };
386        assert_eq!(format!("{atomic}"), "array");
387    }
388
389    #[test]
390    fn array_of_array_key_mixed_collapses_to_array() {
391        let atomic = Atomic::TArray {
392            key: Box::new(Type::array_key()),
393            value: Box::new(Type::mixed()),
394        };
395        assert_eq!(format!("{atomic}"), "array");
396    }
397
398    #[test]
399    fn array_of_int_mixed_does_not_collapse() {
400        let atomic = Atomic::TArray {
401            key: Box::new(Type::int()),
402            value: Box::new(Type::mixed()),
403        };
404        assert_eq!(format!("{atomic}"), "array<int, mixed>");
405    }
406
407    #[test]
408    fn array_of_mixed_string_does_not_collapse() {
409        let atomic = Atomic::TArray {
410            key: Box::new(Type::mixed()),
411            value: Box::new(Type::string()),
412        };
413        assert_eq!(format!("{atomic}"), "array<mixed, string>");
414    }
415
416    #[test]
417    fn non_empty_array_of_mixed_mixed_collapses() {
418        let atomic = Atomic::TNonEmptyArray {
419            key: Box::new(Type::mixed()),
420            value: Box::new(Type::mixed()),
421        };
422        assert_eq!(format!("{atomic}"), "non-empty-array");
423    }
424
425    #[test]
426    fn list_of_mixed_collapses_to_list() {
427        let atomic = Atomic::TList {
428            value: Box::new(Type::mixed()),
429        };
430        assert_eq!(format!("{atomic}"), "list");
431    }
432
433    #[test]
434    fn list_of_string_does_not_collapse() {
435        let atomic = Atomic::TList {
436            value: Box::new(Type::string()),
437        };
438        assert_eq!(format!("{atomic}"), "list<string>");
439    }
440
441    #[test]
442    fn non_empty_list_of_mixed_collapses() {
443        let atomic = Atomic::TNonEmptyList {
444            value: Box::new(Type::mixed()),
445        };
446        assert_eq!(format!("{atomic}"), "non-empty-list");
447    }
448
449    #[test]
450    fn named_object_all_mixed_params_collapses_to_bare_name() {
451        let atomic = Atomic::TNamedObject {
452            fqcn: "Traversable".into(),
453            type_params: crate::union::vec_to_type_params(vec![Type::mixed(), Type::mixed()]),
454        };
455        assert_eq!(format!("{atomic}"), "Traversable");
456    }
457
458    #[test]
459    fn named_object_with_one_concrete_param_does_not_collapse() {
460        let atomic = Atomic::TNamedObject {
461            fqcn: "Traversable".into(),
462            type_params: crate::union::vec_to_type_params(vec![Type::int(), Type::mixed()]),
463        };
464        assert_eq!(format!("{atomic}"), "Traversable<int, mixed>");
465    }
466
467    #[test]
468    fn named_object_with_mixed_bounded_template_param_does_not_collapse() {
469        // An unresolved `T` template parameter (even one bounded by `mixed`)
470        // is a meaningful part of a generic signature and must never be
471        // confused with a literal, information-free `mixed` default.
472        let template_param = Atomic::TTemplateParam {
473            name: "T".into(),
474            as_type: Box::new(Type::mixed()),
475            defining_entity: "MyClass".into(),
476        };
477        let atomic = Atomic::TNamedObject {
478            fqcn: "MyClass".into(),
479            type_params: crate::union::vec_to_type_params(vec![Type::single(template_param)]),
480        };
481        assert_eq!(format!("{atomic}"), "MyClass<T>");
482    }
483
484    fn bare_traversable() -> Atomic {
485        Atomic::TNamedObject {
486            fqcn: "Traversable".into(),
487            type_params: crate::union::empty_type_params(),
488        }
489    }
490
491    #[test]
492    fn array_mixed_mixed_or_traversable_collapses_to_iterable() {
493        let mut u = Type::single(Atomic::TArray {
494            key: Box::new(Type::array_key()),
495            value: Box::new(Type::mixed()),
496        });
497        u.add_type(bare_traversable());
498        assert_eq!(format!("{u}"), "iterable");
499    }
500
501    #[test]
502    fn parameterized_array_or_matching_traversable_collapses_to_iterable() {
503        let key = Type::string();
504        let value = Type::int();
505        let mut u = Type::single(Atomic::TArray {
506            key: Box::new(key.clone()),
507            value: Box::new(value.clone()),
508        });
509        u.add_type(Atomic::TNamedObject {
510            fqcn: "Traversable".into(),
511            type_params: crate::union::vec_to_type_params(vec![key, value]),
512        });
513        assert_eq!(format!("{u}"), "iterable<string, int>");
514    }
515
516    #[test]
517    fn iterable_collapse_preserves_other_union_members() {
518        let mut u = Type::single(Atomic::TArray {
519            key: Box::new(Type::array_key()),
520            value: Box::new(Type::mixed()),
521        });
522        u.add_type(bare_traversable());
523        u.add_type(Atomic::TNull);
524        assert_eq!(format!("{u}"), "iterable|null");
525    }
526
527    #[test]
528    fn array_with_mismatched_bare_traversable_does_not_collapse() {
529        // A bare (unparameterized) `Traversable` carries no key/value
530        // guarantee, so pairing it with a *more specific* array must not be
531        // rendered as `iterable<int, string>` — that would overclaim that the
532        // `Traversable` side is bound to the same key/value types too.
533        let mut u = Type::single(Atomic::TArray {
534            key: Box::new(Type::int()),
535            value: Box::new(Type::string()),
536        });
537        u.add_type(bare_traversable());
538        assert_eq!(format!("{u}"), "array<int, string>|Traversable");
539    }
540
541    #[test]
542    fn array_with_non_matching_parameterized_traversable_does_not_collapse() {
543        let mut u = Type::single(Atomic::TArray {
544            key: Box::new(Type::int()),
545            value: Box::new(Type::string()),
546        });
547        u.add_type(Atomic::TNamedObject {
548            fqcn: "Traversable".into(),
549            type_params: crate::union::vec_to_type_params(vec![Type::string(), Type::int()]),
550        });
551        assert_eq!(
552            format!("{u}"),
553            "array<int, string>|Traversable<string, int>"
554        );
555    }
556
557    fn named_object(fqcn: &str) -> Atomic {
558        Atomic::TNamedObject {
559            fqcn: fqcn.into(),
560            type_params: crate::union::empty_type_params(),
561        }
562    }
563
564    #[test]
565    fn intersection_drops_exact_duplicate_part() {
566        let atomic = Atomic::TIntersection {
567            parts: crate::union::vec_to_type_params(vec![
568                Type::single(named_object("Foo")),
569                Type::single(named_object("Foo")),
570            ]),
571        };
572        assert_eq!(format!("{atomic}"), "Foo");
573    }
574
575    #[test]
576    fn intersection_keeps_distinct_parts() {
577        let atomic = Atomic::TIntersection {
578            parts: crate::union::vec_to_type_params(vec![
579                Type::single(named_object("Countable")),
580                Type::single(named_object("Traversable")),
581            ]),
582        };
583        assert_eq!(format!("{atomic}"), "Countable&Traversable");
584    }
585
586    #[test]
587    fn intersection_drops_duplicate_among_three_parts() {
588        let atomic = Atomic::TIntersection {
589            parts: crate::union::vec_to_type_params(vec![
590                Type::single(named_object("Foo")),
591                Type::single(named_object("Bar")),
592                Type::single(named_object("Foo")),
593            ]),
594        };
595        assert_eq!(format!("{atomic}"), "Foo&Bar");
596    }
597}