Skip to main content

aver/types/checker/
mod.rs

1/// Aver static type checker.
2///
3/// Two-phase analysis:
4///   Phase 1 — build a signature table from all FnDef nodes and builtins.
5///   Phase 2 — check top-level statements, then each FnDef for call-site
6///              argument types, return type, BinOp compatibility, and effects.
7///
8/// The checker keeps gradual typing for nested placeholders, but applies
9/// stricter rules for checker constraints: a bare `Unknown` does not satisfy
10/// a concrete expected type in argument/return/ascription checks.
11use 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// ---------------------------------------------------------------------------
31// Public API
32// ---------------------------------------------------------------------------
33
34#[derive(Debug, Clone)]
35pub struct TypeError {
36    pub message: String,
37    pub line: usize,
38    pub col: usize,
39}
40
41/// Result of type-checking that also carries memo-safety metadata.
42#[derive(Debug)]
43pub struct TypeCheckResult {
44    pub errors: Vec<TypeError>,
45    /// For each user-defined fn: (param_types, return_type, effects).
46    /// Used by the memo system to decide which fns qualify.
47    pub fn_sigs: HashMap<String, (Vec<Type>, Type, Vec<String>)>,
48    /// Set of type names whose values are memo-safe (hashable scalars / records of scalars).
49    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    // Export fn_sigs for memo analysis
65    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    // Compute memo-safe named types
77    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// ---------------------------------------------------------------------------
87// Internal structures
88// ---------------------------------------------------------------------------
89
90#[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    /// Field types for record types: "TypeName.fieldName" → Type.
111    /// Populated for both user-defined `record` types and built-in records
112    /// (HttpResponse, Header). Enables checked dot-access on Named types.
113    record_field_types: HashMap<String, Type>,
114    /// Variant names for sum types: "Shape" → ["Circle", "Rect", "Point"].
115    /// Pre-populated for Result and Option; extended by user-defined sum types.
116    type_variants: HashMap<String, Vec<String>>,
117    /// Top-level bindings visible from function bodies.
118    globals: HashMap<String, Type>,
119    /// Local bindings in the current function/scope.
120    locals: HashMap<String, Type>,
121    errors: Vec<TypeError>,
122    /// Return type of the function currently being checked; None at top level.
123    current_fn_ret: Option<Type>,
124    /// Line number of the function currently being checked; None at top level.
125    current_fn_line: Option<usize>,
126    /// Type names that are opaque in this module's context (imported via `exposes opaque`).
127    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    /// Check whether `required_effect` is satisfied by `caller_effects`.
160    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    /// Compatibility used for checker constraints (call args, returns, ascriptions).
221    ///
222    /// We keep gradual typing for nested placeholders (`Result<Int, Unknown>` can
223    /// still fit `Result<Int, String>`), but reject *bare* `Unknown` when a
224    /// concrete type is required. This closes common false negatives where an
225    /// unresolved expression silently passes a concrete signature.
226    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}