1use std::collections::{HashMap, HashSet};
12use std::path::Path;
13
14use super::{Type, parse_type_str_strict};
15use crate::ast::{BinOp, Expr, FnDef, Literal, Module, Pattern, Stmt, TopLevel, TypeDef};
16use crate::source::{
17 canonicalize_path, find_module_file, parse_source, require_module_declaration,
18};
19
20mod builtins;
21mod exhaustiveness;
22mod flow;
23mod infer;
24mod memo;
25mod modules;
26
27#[cfg(test)]
28mod tests;
29
30#[derive(Debug, Clone)]
35pub struct TypeError {
36 pub message: String,
37 pub line: usize,
38 pub col: usize,
39}
40
41#[derive(Debug)]
43pub struct TypeCheckResult {
44 pub errors: Vec<TypeError>,
45 pub fn_sigs: HashMap<String, (Vec<Type>, Type, Vec<String>)>,
48 pub memo_safe_types: HashSet<String>,
50}
51
52pub fn run_type_check(items: &[TopLevel]) -> Vec<TypeError> {
53 run_type_check_with_base(items, None)
54}
55
56pub fn run_type_check_with_base(items: &[TopLevel], base_dir: Option<&str>) -> Vec<TypeError> {
57 run_type_check_full(items, base_dir).errors
58}
59
60pub fn run_type_check_full(items: &[TopLevel], base_dir: Option<&str>) -> TypeCheckResult {
61 let mut checker = TypeChecker::new();
62 checker.check(items, base_dir);
63
64 let fn_sigs: HashMap<String, (Vec<Type>, Type, Vec<String>)> = checker
66 .fn_sigs
67 .iter()
68 .map(|(k, v)| {
69 (
70 k.clone(),
71 (v.params.clone(), v.ret.clone(), v.effects.clone()),
72 )
73 })
74 .collect();
75
76 let memo_safe_types = checker.compute_memo_safe_types(items);
78
79 TypeCheckResult {
80 errors: checker.errors,
81 fn_sigs,
82 memo_safe_types,
83 }
84}
85
86#[derive(Debug, Clone)]
91struct FnSig {
92 params: Vec<Type>,
93 ret: Type,
94 effects: Vec<String>,
95}
96
97#[derive(Debug, Clone)]
98struct ModuleSigCache {
99 fn_entries: Vec<(String, FnSig)>,
100 value_entries: Vec<(String, Type)>,
101 record_field_entries: Vec<(String, Type)>,
102 type_variants: Vec<(String, Vec<String>)>,
103 opaque_types: Vec<String>,
104}
105
106struct TypeChecker {
107 fn_sigs: HashMap<String, FnSig>,
108 module_sig_cache: HashMap<String, ModuleSigCache>,
109 value_members: HashMap<String, Type>,
110 record_field_types: HashMap<String, Type>,
114 type_variants: HashMap<String, Vec<String>>,
117 globals: HashMap<String, Type>,
119 locals: HashMap<String, Type>,
121 errors: Vec<TypeError>,
122 current_fn_ret: Option<Type>,
124 current_fn_line: Option<usize>,
126 opaque_types: HashSet<String>,
128}
129
130impl TypeChecker {
131 fn new() -> Self {
132 let mut type_variants = HashMap::new();
133 type_variants.insert(
134 "Result".to_string(),
135 vec!["Ok".to_string(), "Err".to_string()],
136 );
137 type_variants.insert(
138 "Option".to_string(),
139 vec!["Some".to_string(), "None".to_string()],
140 );
141
142 let mut tc = TypeChecker {
143 fn_sigs: HashMap::new(),
144 module_sig_cache: HashMap::new(),
145 value_members: HashMap::new(),
146 record_field_types: HashMap::new(),
147 type_variants,
148 globals: HashMap::new(),
149 locals: HashMap::new(),
150 errors: Vec::new(),
151 current_fn_ret: None,
152 current_fn_line: None,
153 opaque_types: HashSet::new(),
154 };
155 tc.register_builtins();
156 tc
157 }
158
159 fn caller_has_effect(&self, caller_effects: &[String], required_effect: &str) -> bool {
161 caller_effects
162 .iter()
163 .any(|declared| crate::effects::effect_satisfies(declared, required_effect))
164 }
165
166 fn error(&mut self, msg: impl Into<String>) {
167 let line = self.current_fn_line.unwrap_or(1);
168 self.errors.push(TypeError {
169 message: msg.into(),
170 line,
171 col: 0,
172 });
173 }
174
175 fn error_at_line(&mut self, line: usize, msg: impl Into<String>) {
176 self.errors.push(TypeError {
177 message: msg.into(),
178 line,
179 col: 0,
180 });
181 }
182
183 fn insert_sig(&mut self, name: &str, params: &[Type], ret: Type, effects: &[&str]) {
184 self.fn_sigs.insert(
185 name.to_string(),
186 FnSig {
187 params: params.to_vec(),
188 ret,
189 effects: effects.iter().map(|s| s.to_string()).collect(),
190 },
191 );
192 }
193
194 fn fn_type_from_sig(sig: &FnSig) -> Type {
195 Type::Fn(
196 sig.params.clone(),
197 Box::new(sig.ret.clone()),
198 sig.effects.clone(),
199 )
200 }
201
202 fn sig_from_callable_type(ty: &Type) -> Option<FnSig> {
203 match ty {
204 Type::Fn(params, ret, effects) => Some(FnSig {
205 params: params.clone(),
206 ret: *ret.clone(),
207 effects: effects.clone(),
208 }),
209 _ => None,
210 }
211 }
212
213 fn binding_type(&self, name: &str) -> Option<Type> {
214 self.locals
215 .get(name)
216 .or_else(|| self.globals.get(name))
217 .cloned()
218 }
219
220 pub(super) fn constraint_compatible(actual: &Type, expected: &Type) -> bool {
227 if matches!(actual, Type::Unknown) && !matches!(expected, Type::Unknown) {
228 return false;
229 }
230 actual.compatible(expected)
231 }
232}