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        TypeExpr::Owned(inner) => format!("owned<{}>", format_type(inner)),
72    }
73}
74
75/// Produce a detail string describing why a Shape type is incompatible with
76/// another Shape type — e.g. "missing field 'age' (int)" or "field 'name'
77/// has type int, expected string". Returns `None` if both types are not shapes.
78pub fn shape_mismatch_detail(expected: &TypeExpr, actual: &TypeExpr) -> Option<String> {
79    if let (TypeExpr::Shape(ef), TypeExpr::Shape(af)) = (expected, actual) {
80        let mut details = Vec::new();
81        for field in ef {
82            if field.optional {
83                continue;
84            }
85            match af.iter().find(|f| f.name == field.name) {
86                None => details.push(format!(
87                    "missing field '{}' ({})",
88                    field.name,
89                    format_type(&field.type_expr)
90                )),
91                Some(actual_field) => {
92                    let e_str = format_type(&field.type_expr);
93                    let a_str = format_type(&actual_field.type_expr);
94                    if e_str != a_str {
95                        details.push(format!(
96                            "field '{}' has type {}, expected {}",
97                            field.name, a_str, e_str
98                        ));
99                    }
100                }
101            }
102        }
103        if details.is_empty() {
104            None
105        } else {
106            Some(details.join("; "))
107        }
108    } else {
109        None
110    }
111}
112
113/// If `types` is exactly two members and one is `nil`, return the
114/// non-`nil` member when it can be safely rendered as `T?`. Mirrors the
115/// formatter's rule in `harn-fmt::helpers::optional_sugar_inner`: only
116/// types that appear at primary precedence (or below) can be sugared,
117/// because postfix `?` parses tighter than `&` / `|` / `fn(...) -> ...`
118/// return positions.
119fn optional_sugar_inner(types: &[TypeExpr]) -> Option<&TypeExpr> {
120    if types.len() != 2 {
121        return None;
122    }
123    let nil_idx = types
124        .iter()
125        .position(|t| matches!(t, TypeExpr::Named(n) if n == "nil"))?;
126    let inner = &types[1 - nil_idx];
127    if matches!(
128        inner,
129        TypeExpr::Union(_) | TypeExpr::Intersection(_) | TypeExpr::FnType { .. }
130    ) {
131        return None;
132    }
133    if matches!(inner, TypeExpr::Named(n) if n == "nil") {
134        return None;
135    }
136    Some(inner)
137}
138
139/// Returns true when the type is obvious from the RHS expression
140/// (e.g. `let x = 42` is obviously int — no hint needed).
141pub(super) fn is_obvious_type(value: &SNode, _ty: &TypeExpr) -> bool {
142    matches!(
143        &value.node,
144        Node::IntLiteral(_)
145            | Node::FloatLiteral(_)
146            | Node::StringLiteral(_)
147            | Node::BoolLiteral(_)
148            | Node::NilLiteral
149            | Node::ListLiteral(_)
150            | Node::DictLiteral(_)
151            | Node::InterpolatedString(_)
152    )
153}