Skip to main content

harn_parser/typechecker/
format.rs

1//! Display helpers for type expressions and shape mismatches.
2//!
3//! `format_type` is the canonical pretty-printer for `TypeExpr` (also used
4//! by `harn-lsp` and `harn-fmt` via re-export). `shape_mismatch_detail`
5//! produces a one-line "missing field …" / "field 'x' has type …" diff that
6//! enriches type-error messages.
7
8use crate::ast::*;
9
10/// Pretty-print a type expression for display in error messages.
11pub fn format_type(ty: &TypeExpr) -> String {
12    match ty {
13        TypeExpr::Named(n) => n.clone(),
14        TypeExpr::Union(types) => {
15            if let Some(inner) = optional_sugar_inner(types) {
16                return format!("{}?", format_type(inner));
17            }
18            types
19                .iter()
20                .map(format_type)
21                .collect::<Vec<_>>()
22                .join(" | ")
23        }
24        TypeExpr::Intersection(types) => types
25            .iter()
26            .map(|m| match m {
27                // `T | nil` arms render as the sugared `T?`, which binds
28                // tighter than `&` and reads back unambiguously.
29                TypeExpr::Union(members) if optional_sugar_inner(members).is_some() => {
30                    format_type(m)
31                }
32                // Other nested unions still get parenthesised for readability.
33                TypeExpr::Union(_) => format!("({})", format_type(m)),
34                _ => format_type(m),
35            })
36            .collect::<Vec<_>>()
37            .join(" & "),
38        TypeExpr::Shape(fields) => {
39            let inner: Vec<String> = fields
40                .iter()
41                .map(|f| {
42                    let opt = if f.optional { "?" } else { "" };
43                    format!("{}{opt}: {}", f.name, format_type(&f.type_expr))
44                })
45                .collect();
46            format!("{{{}}}", inner.join(", "))
47        }
48        TypeExpr::List(inner) => format!("list<{}>", format_type(inner)),
49        TypeExpr::Iter(inner) => format!("iter<{}>", format_type(inner)),
50        TypeExpr::Generator(inner) => format!("Generator<{}>", format_type(inner)),
51        TypeExpr::Stream(inner) => format!("Stream<{}>", format_type(inner)),
52        TypeExpr::DictType(k, v) => format!("dict<{}, {}>", format_type(k), format_type(v)),
53        TypeExpr::Applied { name, args } => {
54            let args_str = args.iter().map(format_type).collect::<Vec<_>>().join(", ");
55            format!("{name}<{args_str}>")
56        }
57        TypeExpr::FnType {
58            params,
59            return_type,
60        } => {
61            let params_str = params
62                .iter()
63                .map(format_type)
64                .collect::<Vec<_>>()
65                .join(", ");
66            format!("fn({}) -> {}", params_str, format_type(return_type))
67        }
68        TypeExpr::Never => "never".to_string(),
69        TypeExpr::LitString(s) => format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")),
70        TypeExpr::LitInt(v) => v.to_string(),
71    }
72}
73
74/// Produce a detail string describing why a Shape type is incompatible with
75/// another Shape type — e.g. "missing field 'age' (int)" or "field 'name'
76/// has type int, expected string". Returns `None` if both types are not shapes.
77pub fn shape_mismatch_detail(expected: &TypeExpr, actual: &TypeExpr) -> Option<String> {
78    if let (TypeExpr::Shape(ef), TypeExpr::Shape(af)) = (expected, actual) {
79        let mut details = Vec::new();
80        for field in ef {
81            if field.optional {
82                continue;
83            }
84            match af.iter().find(|f| f.name == field.name) {
85                None => details.push(format!(
86                    "missing field '{}' ({})",
87                    field.name,
88                    format_type(&field.type_expr)
89                )),
90                Some(actual_field) => {
91                    let e_str = format_type(&field.type_expr);
92                    let a_str = format_type(&actual_field.type_expr);
93                    if e_str != a_str {
94                        details.push(format!(
95                            "field '{}' has type {}, expected {}",
96                            field.name, a_str, e_str
97                        ));
98                    }
99                }
100            }
101        }
102        if details.is_empty() {
103            None
104        } else {
105            Some(details.join("; "))
106        }
107    } else {
108        None
109    }
110}
111
112/// If `types` is exactly two members and one is `nil`, return the
113/// non-`nil` member when it can be safely rendered as `T?`. Mirrors the
114/// formatter's rule in `harn-fmt::helpers::optional_sugar_inner`: only
115/// types that appear at primary precedence (or below) can be sugared,
116/// because postfix `?` parses tighter than `&` / `|` / `fn(...) -> ...`
117/// return positions.
118fn optional_sugar_inner(types: &[TypeExpr]) -> Option<&TypeExpr> {
119    if types.len() != 2 {
120        return None;
121    }
122    let nil_idx = types
123        .iter()
124        .position(|t| matches!(t, TypeExpr::Named(n) if n == "nil"))?;
125    let inner = &types[1 - nil_idx];
126    if matches!(
127        inner,
128        TypeExpr::Union(_) | TypeExpr::Intersection(_) | TypeExpr::FnType { .. }
129    ) {
130        return None;
131    }
132    if matches!(inner, TypeExpr::Named(n) if n == "nil") {
133        return None;
134    }
135    Some(inner)
136}
137
138/// Returns true when the type is obvious from the RHS expression
139/// (e.g. `let x = 42` is obviously int — no hint needed).
140pub(super) fn is_obvious_type(value: &SNode, _ty: &TypeExpr) -> bool {
141    matches!(
142        &value.node,
143        Node::IntLiteral(_)
144            | Node::FloatLiteral(_)
145            | Node::StringLiteral(_)
146            | Node::BoolLiteral(_)
147            | Node::NilLiteral
148            | Node::ListLiteral(_)
149            | Node::DictLiteral(_)
150            | Node::InterpolatedString(_)
151    )
152}