harn_parser/typechecker/
format.rs1use crate::ast::*;
9
10pub 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 TypeExpr::Union(members) if optional_sugar_inner(members).is_some() => {
30 format_type(m)
31 }
32 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
75pub 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
113fn 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
139pub(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}