Skip to main content

lex_types/
checker.rs

1//! M3: type checker. Walks the canonical AST, infers types via unification,
2//! and checks declared signatures and effects.
3
4use crate::builtins::{module_for_import, module_scope};
5use crate::env::{TypeDefKind, TypeEnv, ty_from_canon};
6use crate::error::{PositionedError, TypeError};
7use crate::position::Position;
8use crate::types::*;
9use crate::unifier::{UnifyError, Unifier};
10use indexmap::IndexMap;
11use lex_ast as a;
12use std::collections::{BTreeMap, HashMap};
13
14/// Field names + type-tag schema extracted from a `Result[Record{...}, _]`
15/// return type. Used by the `parse` → `parse_strict_typed` rewrite (#322).
16type FieldSchema = (Vec<String>, Vec<(String, String)>);
17
18/// Result of checking a whole program.
19pub struct ProgramTypes {
20    pub fn_signatures: IndexMap<String, Scheme>,
21    pub type_env: TypeEnv,
22    /// For #168: per-call required-fields map for `module.parse(s)`
23    /// calls whose inferred result type is `Result[Record{...}, _]`.
24    /// Keyed by `&CExpr as *const _ as usize` so callers can do an
25    /// O(1) pointer-equality lookup during a separate AST rewrite
26    /// pass. Empty unless any matching call sites were found.
27    ///
28    /// See [`check_and_rewrite_program`] for the function that
29    /// populates this and applies the rewrite in one step.
30    pub parse_required_fields: HashMap<usize, Vec<String>>,
31    /// For #322: per-call type schema alongside the field names.
32    /// Each entry is a `Vec<(field_name, type_tag)>` parallel to
33    /// `parse_required_fields`. Used by the rewrite pass to inject
34    /// the third argument to `parse_strict`.
35    pub parse_type_schemas: HashMap<usize, Vec<(String, String)>>,
36}
37
38/// Variant of [`check_program`] that stamps a source [`Position`]
39/// onto every emitted error (#306 slice 1).
40///
41/// `positions` is keyed by function name and supplies the position
42/// of each `fn` declaration in the source. Errors from a given
43/// function are tagged with that function's position; errors that
44/// don't map to a single function (e.g. type-decl-level errors)
45/// keep `position = None`.
46///
47/// Slice 1 ships function-level granularity. Slice 1.5 will plumb
48/// per-expression spans through canonicalize so deep-body errors
49/// land on the offending sub-expression rather than its enclosing
50/// function.
51pub fn check_program_with_positions(
52    stages: &[a::Stage],
53    positions: &BTreeMap<String, Position>,
54) -> Result<ProgramTypes, Vec<PositionedError>> {
55    check_program_inner(stages, Some(positions))
56        .map_err(|errs| errs.into_iter().map(|(e, fn_name)| {
57            let pos = fn_name.as_deref().and_then(|n| positions.get(n)).cloned();
58            PositionedError::new(e, pos)
59        }).collect())
60}
61
62pub fn check_program(stages: &[a::Stage]) -> Result<ProgramTypes, Vec<TypeError>> {
63    check_program_inner(stages, None)
64        .map_err(|errs| errs.into_iter().map(|(e, _)| e).collect())
65}
66
67fn check_program_inner(
68    stages: &[a::Stage],
69    _positions: Option<&BTreeMap<String, Position>>,
70) -> Result<ProgramTypes, Vec<(TypeError, Option<String>)>> {
71    let mut tcx = Checker::new();
72    // Each entry is (error, optional fn name the error came from)
73    // so callers can resolve the error to a source position.
74    let mut errors: Vec<(TypeError, Option<String>)> = Vec::new();
75
76    // Pass 1: gather imports → bring module values into scope.
77    for stage in stages {
78        if let a::Stage::Import(i) = stage {
79            if let Some(mod_name) = module_for_import(&i.reference) {
80                if let Some(ty) = module_scope(mod_name, &tcx.type_env) {
81                    tcx.globals.insert(i.alias.clone(), Scheme {
82                        // Module-level signatures use Var(0..n) and
83                        // effect-vars on stdlib HOFs (list.map's `[E]`
84                        // etc.); generalize both.
85                        vars: collect_vars(&ty),
86                        eff_vars: collect_eff_vars(&ty),
87                        ty,
88                    });
89                    tcx.module_aliases.insert(i.alias.clone(), mod_name.to_string());
90                }
91            }
92        }
93    }
94
95    // Pass 2: register user-declared types.
96    for stage in stages {
97        if let a::Stage::TypeDecl(td) = stage {
98            if let Err(e) = tcx.type_env.add_user_type(&td.name, td.clone()) {
99                errors.push((TypeError::RecursiveTypeWithoutConstructor {
100                    at_node: "n_0".into(),
101                    name: e,
102                }, None));
103            }
104        }
105    }
106
107    // Pass 3: register fn signatures (so mutual recursion works).
108    for stage in stages {
109        if let a::Stage::FnDecl(fd) = stage {
110            let scheme = function_scheme(fd);
111            tcx.globals.insert(fd.name.clone(), scheme);
112            // #209 slice 2: keep the original params so call-site
113            // refinement discharge can see the predicate before it
114            // gets stripped to its base type by `ty_from_canon`.
115            tcx.fn_params.insert(fd.name.clone(), fd.params.clone());
116        }
117    }
118
119    // Pass 4: check each fn body. With #306 slice 1, every emitted
120    // error is paired with the source fn it came from so the public
121    // [`check_program_with_positions`] wrapper can stamp the
122    // function's source position onto a [`PositionedError`].
123    let mut signatures = IndexMap::new();
124    for stage in stages {
125        if let a::Stage::FnDecl(fd) = stage {
126            match tcx.check_fn(fd) {
127                Ok(scheme) => { signatures.insert(fd.name.clone(), scheme); }
128                Err(es) => {
129                    errors.extend(es.into_iter().map(|e| (e, Some(fd.name.clone()))));
130                }
131            }
132        }
133    }
134
135    if errors.is_empty() {
136        // #168: walk pending parse-call records and resolve each
137        // call's return type now that all unification has settled.
138        // A call shows up here only if the call site syntactically
139        // looks like `<alias>.parse(s)` for an alias bound to one
140        // of {json, toml, yaml} via the import pass.
141        let mut parse_required_fields = HashMap::new();
142        let mut parse_type_schemas = HashMap::new();
143        for (call_ptr, ret_ty) in &tcx.pending_parse_calls {
144            if let Some((fields, schema)) = extract_record_fields_and_schema(&tcx.u, &tcx.type_env, ret_ty) {
145                parse_required_fields.insert(*call_ptr, fields);
146                parse_type_schemas.insert(*call_ptr, schema);
147            }
148        }
149        Ok(ProgramTypes {
150            fn_signatures: signatures,
151            type_env: tcx.type_env,
152            parse_required_fields,
153            parse_type_schemas,
154        })
155    } else {
156        Err(errors)
157    }
158}
159
160/// Type-check `stages` and rewrite every `module.parse(s)` call
161/// where the inferred T is a Record into the equivalent
162/// `module.parse_strict(s, [field_names])` (#168). Existing
163/// [`check_program`] keeps the old immutable signature for tests
164/// and tools that don't want the AST rewritten.
165pub fn check_and_rewrite_program(
166    stages: &mut [a::Stage],
167) -> Result<ProgramTypes, Vec<TypeError>> {
168    // Borrow as immutable for the type-check pass — the side-table
169    // it produces is keyed by `*const CExpr as usize`, and the Vec
170    // backing storage doesn't move between this borrow and the
171    // mutable one below.
172    let pt = check_program(&*stages)?;
173    if !pt.parse_required_fields.is_empty() {
174        rewrite_parse_calls(stages, &pt.parse_required_fields, &pt.parse_type_schemas);
175    }
176    Ok(pt)
177}
178
179/// Walk `stages` mutably and, for every `CExpr::Call` whose
180/// pointer (cast to `usize`) is a key in `required`, rewrite it
181/// from `module.parse(s)` into `module.parse_strict(s, [...], [...])`.
182///
183/// Assumptions:
184///
185/// - The `usize` keys come from the same physical AST passed
186///   here. This is true when called from
187///   [`check_and_rewrite_program`].
188/// - Every key corresponds to a call whose callee is
189///   `FieldAccess(_, "parse")`. The type-checker only inserts
190///   keys when this holds, so we panic if the assumption is
191///   violated — that's a checker bug, not a user error.
192fn rewrite_parse_calls(
193    stages: &mut [a::Stage],
194    required: &HashMap<usize, Vec<String>>,
195    schemas: &HashMap<usize, Vec<(String, String)>>,
196) {
197    for stage in stages.iter_mut() {
198        if let a::Stage::FnDecl(fd) = stage {
199            rewrite_in_expr(&mut fd.body, required, schemas);
200        }
201    }
202}
203
204fn rewrite_in_expr(
205    expr: &mut a::CExpr,
206    required: &HashMap<usize, Vec<String>>,
207    schemas: &HashMap<usize, Vec<(String, String)>>,
208) {
209    let ptr = expr as *const a::CExpr as usize;
210    let do_rewrite = required.get(&ptr).cloned();
211    let do_schema = schemas.get(&ptr).cloned();
212    // Recurse into children first; rewriting the call itself
213    // doesn't touch the source-arg, so the order doesn't change
214    // semantics — but processing children up front means a
215    // hypothetical nested parse-of-parse still gets rewritten
216    // correctly.
217    match expr {
218        a::CExpr::Call { callee, args } => {
219            rewrite_in_expr(callee, required, schemas);
220            for a in args.iter_mut() { rewrite_in_expr(a, required, schemas); }
221        }
222        a::CExpr::Let { value, body, .. } => {
223            rewrite_in_expr(value, required, schemas);
224            rewrite_in_expr(body, required, schemas);
225        }
226        a::CExpr::Match { scrutinee, arms } => {
227            rewrite_in_expr(scrutinee, required, schemas);
228            for arm in arms.iter_mut() { rewrite_in_expr(&mut arm.body, required, schemas); }
229        }
230        a::CExpr::Block { statements, result } => {
231            for s in statements.iter_mut() { rewrite_in_expr(s, required, schemas); }
232            rewrite_in_expr(result, required, schemas);
233        }
234        a::CExpr::Constructor { args, .. } => {
235            for a in args.iter_mut() { rewrite_in_expr(a, required, schemas); }
236        }
237        a::CExpr::RecordLit { fields } => {
238            for f in fields.iter_mut() { rewrite_in_expr(&mut f.value, required, schemas); }
239        }
240        a::CExpr::TupleLit { items } | a::CExpr::ListLit { items } => {
241            for it in items.iter_mut() { rewrite_in_expr(it, required, schemas); }
242        }
243        a::CExpr::FieldAccess { value, .. } => rewrite_in_expr(value, required, schemas),
244        a::CExpr::Lambda { body, .. } => rewrite_in_expr(body, required, schemas),
245        a::CExpr::BinOp { lhs, rhs, .. } => {
246            rewrite_in_expr(lhs, required, schemas);
247            rewrite_in_expr(rhs, required, schemas);
248        }
249        a::CExpr::UnaryOp { expr, .. } => rewrite_in_expr(expr, required, schemas),
250        a::CExpr::Return { value } => rewrite_in_expr(value, required, schemas),
251        a::CExpr::Literal { .. } | a::CExpr::Var { .. } => {}
252    }
253    if let Some(fields) = do_rewrite {
254        match expr {
255            a::CExpr::Call { callee, args } => {
256                if let a::CExpr::FieldAccess { field, .. } = callee.as_mut() {
257                    debug_assert_eq!(field, "parse",
258                        "rewrite_in_expr: only `.parse` calls should be in the table");
259                    // Use parse_strict_typed (internal, 3-arg) rather than the
260                    // public 2-arg parse_strict so direct callers aren't broken.
261                    *field = "parse_strict_typed".to_string();
262                }
263                // Second argument: List[Str] of required field names.
264                args.push(a::CExpr::ListLit {
265                    items: fields.into_iter()
266                        .map(|f| a::CExpr::Literal {
267                            value: a::CLit::Str { value: f },
268                        })
269                        .collect(),
270                });
271                // Third argument: List[(Str, Str)] type schema (#322).
272                let schema = do_schema.unwrap_or_default();
273                args.push(a::CExpr::ListLit {
274                    items: schema.into_iter()
275                        .map(|(name, tag)| a::CExpr::TupleLit {
276                            items: vec![
277                                a::CExpr::Literal { value: a::CLit::Str { value: name } },
278                                a::CExpr::Literal { value: a::CLit::Str { value: tag } },
279                            ],
280                        })
281                        .collect(),
282                });
283            }
284            _ => unreachable!("rewrite table key must point to a Call expression"),
285        }
286    }
287}
288
289/// Given an inferred return type from a `module.parse(s)` call,
290/// resolve through the unifier and any type aliases, then look
291/// for `Result[Record{...}, _]`. Returns `(field_names, schema)`
292/// where `schema` is a `Vec<(field_name, type_tag)>` for #322.
293/// Returns `None` if the shape doesn't match.
294fn extract_record_fields_and_schema(
295    u: &Unifier,
296    env: &TypeEnv,
297    ty: &Ty,
298) -> Option<FieldSchema> {
299    let resolved = u.resolve(ty);
300    let Ty::Con(ref name, ref args) = resolved else { return None; };
301    if name != "Result" || args.len() != 2 { return None; }
302    let ok_ty = u.resolve(&args[0]);
303    let unfolded = unfold_record_alias_static(env, ok_ty);
304    if let Ty::Record(fields) = unfolded {
305        let names: Vec<String> = fields.keys().cloned().collect();
306        let schema: Vec<(String, String)> = fields.iter()
307            .map(|(k, v)| (k.clone(), ty_to_tag(u, v)))
308            .collect();
309        Some((names, schema))
310    } else {
311        None
312    }
313}
314
315/// Convert a `Ty` to a compact string tag for the type schema
316/// injected by the rewrite pass (#322). The runtime uses these
317/// tags to validate JSON field values against the declared Lex type.
318fn ty_to_tag(u: &Unifier, ty: &Ty) -> String {
319    let resolved = u.resolve(ty);
320    match &resolved {
321        Ty::Prim(Prim::Int)   => "Int".to_string(),
322        Ty::Prim(Prim::Float) => "Float".to_string(),
323        Ty::Prim(Prim::Bool)  => "Bool".to_string(),
324        Ty::Prim(Prim::Str)   => "Str".to_string(),
325        Ty::Con(name, args) if name == "Option" && args.len() == 1 => {
326            format!("Option[{}]", ty_to_tag(u, &args[0]))
327        }
328        Ty::List(inner) => {
329            format!("List[{}]", ty_to_tag(u, inner))
330        }
331        Ty::Record(_) => "Record".to_string(),
332        _ => "Any".to_string(),
333    }
334}
335
336/// Standalone version of `Checker::unfold_record_alias` —
337/// resolves a `Ty::Con` whose definition is a type alias (record
338/// or otherwise) to the underlying type. Module-level helper
339/// because we need it after the `Checker` has been
340/// moved/destructured.
341fn unfold_record_alias_static(env: &TypeEnv, ty: Ty) -> Ty {
342    if let Ty::Con(ref n, ref args) = ty {
343        if args.is_empty() {
344            if let Some(td) = env.types.get(n) {
345                if let TypeDefKind::Alias(inner) = &td.kind {
346                    return inner.clone();
347                }
348            }
349        }
350    }
351    ty
352}
353
354fn collect_vars(t: &Ty) -> Vec<TyVarId> {
355    let mut out = Vec::new();
356    fn walk(t: &Ty, out: &mut Vec<TyVarId>) {
357        match t {
358            Ty::Var(v) => { if !out.contains(v) { out.push(*v); } }
359            Ty::Prim(_) | Ty::Unit | Ty::Never => {}
360            Ty::List(inner) => walk(inner, out),
361            Ty::Tuple(items) => for it in items { walk(it, out); },
362            Ty::Record(fs) => for v in fs.values() { walk(v, out); },
363            Ty::Con(_, args) => for a in args { walk(a, out); },
364            Ty::Function { params, ret, .. } => {
365                for p in params { walk(p, out); }
366                walk(ret, out);
367            }
368        }
369    }
370    walk(t, &mut out);
371    out
372}
373
374/// Walk a type and collect every effect-row variable id that appears
375/// inside any function-type's effect set. Used to generalize stdlib
376/// HOF schemes alongside ordinary type vars.
377fn collect_eff_vars(t: &Ty) -> Vec<u32> {
378    let mut out = Vec::new();
379    fn walk(t: &Ty, out: &mut Vec<u32>) {
380        match t {
381            Ty::Var(_) | Ty::Prim(_) | Ty::Unit | Ty::Never => {}
382            Ty::List(inner) => walk(inner, out),
383            Ty::Tuple(items) => for it in items { walk(it, out); },
384            Ty::Record(fs) => for v in fs.values() { walk(v, out); },
385            Ty::Con(_, args) => for a in args { walk(a, out); },
386            Ty::Function { params, effects, ret } => {
387                if let Some(v) = effects.var {
388                    if !out.contains(&v) { out.push(v); }
389                }
390                for p in params { walk(p, out); }
391                walk(ret, out);
392            }
393        }
394    }
395    walk(t, &mut out);
396    out
397}
398
399fn function_scheme(fd: &a::FnDecl) -> Scheme {
400    // Collect type-param ids in order; map their names to fresh Var(idx).
401    let params: Vec<Ty> = fd.params.iter().map(|p| ty_from_canon(&p.ty, &fd.type_params)).collect();
402    let ret = ty_from_canon(&fd.return_type, &fd.type_params);
403    // Plumb effect args (#207). A canonical-AST `EffectDecl` already
404    // carries `Option<EffectArg>`; map it into the type-system kind so
405    // subsumption can honor parameterized effects.
406    let effects = EffectSet {
407        concrete: {
408            let mut s = std::collections::BTreeSet::new();
409            for e in &fd.effects {
410                let arg = e.arg.as_ref().map(|a| match a {
411                    a::EffectArg::Str { value } => crate::types::EffectArg::Str(value.clone()),
412                    a::EffectArg::Int { value } => crate::types::EffectArg::Int(*value),
413                    a::EffectArg::Ident { value } => crate::types::EffectArg::Ident(value.clone()),
414                });
415                s.insert(crate::types::EffectKind { name: e.name.clone(), arg });
416            }
417            s
418        },
419        var: None,
420    };
421    let ty = Ty::Function { params, effects, ret: Box::new(ret) };
422    let vars: Vec<TyVarId> = (0..fd.type_params.len() as u32).collect();
423    // User-declared functions don't carry effect-row variables today
424    // (the surface syntax has no `[E]` form for user types). Only
425    // stdlib HOFs do, and those are loaded via module_scope.
426    Scheme { vars, eff_vars: Vec::new(), ty }
427}
428
429struct Checker {
430    u: Unifier,
431    type_env: TypeEnv,
432    globals: IndexMap<String, Scheme>,
433    /// Imported alias → canonical module name (e.g. `cfg` → `toml`).
434    /// Populated during the import pass; consulted by `check_call`
435    /// to recognise `cfg.parse(...)` as a stdlib parse call.
436    module_aliases: IndexMap<String, String>,
437    /// For #168: every `<alias>.parse(s)` call where alias is in
438    /// `module_aliases` and maps to {json, toml, yaml}, recorded
439    /// here as `(call_pointer_as_usize, return_type_var)`. After
440    /// the whole program type-checks, we walk this and resolve
441    /// each return type through the unifier — at that point any
442    /// `Result[Manifest, _]` constraints from match patterns or
443    /// let-annotations have settled.
444    pending_parse_calls: Vec<(usize, Ty)>,
445    /// Per-function param list, retained so call-site discharge can
446    /// see refinement predicates (#209 slice 2). The main `globals`
447    /// scheme strips refinements (`Refined` unifies as its base);
448    /// this side-table keeps the pre-stripped `TypeExpr` available
449    /// for static discharge of literal arguments.
450    fn_params: IndexMap<String, Vec<a::Param>>,
451}
452
453impl Checker {
454    fn new() -> Self {
455        Self {
456            u: Unifier::new(),
457            type_env: TypeEnv::new_with_builtins(),
458            globals: IndexMap::new(),
459            module_aliases: IndexMap::new(),
460            pending_parse_calls: Vec::new(),
461            fn_params: IndexMap::new(),
462        }
463    }
464
465    /// If `ty` is a `Ty::Con(name, [])` whose definition is a type
466    /// alias (record or otherwise), return the aliased type.
467    /// Otherwise return `ty` unchanged.
468    fn unfold_record_alias(&self, ty: Ty) -> Ty {
469        if let Ty::Con(ref n, ref args) = ty {
470            if args.is_empty() {
471                if let Some(td) = self.type_env.types.get(n) {
472                    if let TypeDefKind::Alias(inner) = &td.kind {
473                        return inner.clone();
474                    }
475                }
476            }
477        }
478        ty
479    }
480
481    /// True iff `ty` is a 0-arg `Ty::Con(name, [])` whose definition
482    /// is a `TypeDefKind::Alias`. Used by `unify_coerce_inner` to
483    /// detect the case where both sides are nominal aliases and
484    /// unfolding would collapse the nominal distinction (#323).
485    fn is_alias_con(&self, ty: &Ty) -> bool {
486        if let Ty::Con(name, args) = ty {
487            if args.is_empty() {
488                if let Some(td) = self.type_env.types.get(name) {
489                    return matches!(td.kind, TypeDefKind::Alias(_));
490                }
491            }
492        }
493        false
494    }
495
496    /// Whether `callee` is a `<alias>.parse` field access where
497    /// `<alias>` was imported from one of the stdlib modules whose
498    /// `parse` returns `Result[T, Str]` and whose `parse_strict`
499    /// shape exists for #168 enforcement (json / toml / yaml).
500    fn is_module_parse_call(&self, callee: &a::CExpr) -> bool {
501        if let a::CExpr::FieldAccess { value, field } = callee {
502            if field != "parse" { return false; }
503            if let a::CExpr::Var { name } = value.as_ref() {
504                if let Some(module) = self.module_aliases.get(name) {
505                    return matches!(module.as_str(), "json" | "toml" | "yaml");
506                }
507            }
508        }
509        false
510    }
511
512    /// Unify two types, asymmetrically coercing an anonymous record
513    /// against a nominal record alias at any level of nesting. So a
514    /// `{ x: 1, y: 2 }` literal can be passed to a fn taking
515    /// `Inner = { x :: Int, y :: Int }`, even when the literal is the
516    /// inner field of an outer record literal.
517    ///
518    /// We deliberately keep nominal-vs-nominal mismatches strict: two
519    /// distinct `Ty::Con` names won't unify just because their record
520    /// shapes match. The coercion fires only when one side is a bare
521    /// `Ty::Record` and the other is a `Ty::Con` whose alias is a
522    /// record.
523    fn unify_with_record_coercion(&mut self, a: &Ty, b: &Ty) -> Result<(), UnifyError> {
524        let a = self.u.resolve(a);
525        let b = self.u.resolve(b);
526        self.unify_coerce_inner(a, b)
527    }
528
529    fn unify_coerce_inner(&mut self, a: Ty, b: Ty) -> Result<(), UnifyError> {
530        // #323: alias unfolding. If exactly one side is an `alias-Con`
531        // — a 0-arg `Ty::Con(name, [])` whose definition is a type
532        // alias (Record or non-record) — unfold both sides so the
533        // structural cases below can match (`Errors` ↔ `List[…]`,
534        // `Path` ↔ `Tuple(…)`, `Maybe` ↔ `Option[…]`,
535        // `UserId` ↔ `Int`, …).
536        //
537        // Three cases intentionally bypass unfolding:
538        //
539        // - **Same-named Cons** (`Test` vs `Test`): preserve nominal
540        //   identity. The Con-Con same-name case below recurses on
541        //   args; eager unfold here would force the nominal name
542        //   to evaporate, breaking unifications elsewhere that
543        //   still see the nominal `Con`.
544        // - **Var on either side**: don't unfold against an unbound
545        //   variable, because the plain unifier would bind the var
546        //   to the unfolded shape and lose the nominal name. The
547        //   var binds to the nominal `Con` instead, and later
548        //   unifications against concrete shapes re-enter this
549        //   function and unfold then.
550        // - **Two distinct alias-Cons** (`Apple` vs `Box`, both
551        //   declared as record aliases with identical shapes):
552        //   preserve nominal distinction between aliases. Unfolding
553        //   both would collapse the test of "same shape, different
554        //   names" into "same shape" and erase the names.
555        let (a, b) = match (&a, &b) {
556            (Ty::Con(n1, _), Ty::Con(n2, _)) if n1 == n2 => (a, b),
557            (Ty::Var(_), _) | (_, Ty::Var(_)) => (a, b),
558            (Ty::Con(_, _), Ty::Con(_, _))
559                if self.is_alias_con(&a) && self.is_alias_con(&b) =>
560            {
561                (a, b)
562            }
563            _ => {
564                let a_u = if let Ty::Con(_, _) = &a {
565                    self.unfold_record_alias(a.clone())
566                } else {
567                    a
568                };
569                let b_u = if let Ty::Con(_, _) = &b {
570                    self.unfold_record_alias(b.clone())
571                } else {
572                    b
573                };
574                (a_u, b_u)
575            }
576        };
577
578        match (&a, &b) {
579            (Ty::Record(fa), Ty::Record(fb)) => {
580                if fa.len() != fb.len() {
581                    return Err(UnifyError::Mismatch { a: a.clone(), b: b.clone() });
582                }
583                for (k, va) in fa.clone() {
584                    match fb.get(&k) {
585                        Some(vb) => self.unify_coerce_inner(va, vb.clone())?,
586                        None => return Err(UnifyError::Mismatch { a: a.clone(), b: b.clone() }),
587                    }
588                }
589                Ok(())
590            }
591            (Ty::List(ta), Ty::List(tb)) => {
592                self.unify_coerce_inner((**ta).clone(), (**tb).clone())
593            }
594            (Ty::Tuple(xs), Ty::Tuple(ys)) if xs.len() == ys.len() => {
595                for (x, y) in xs.clone().into_iter().zip(ys.clone()) {
596                    self.unify_coerce_inner(x, y)?;
597                }
598                Ok(())
599            }
600            // Recurse into Con-Con pairs so record-alias coercion reaches
601            // arbitrary nesting depth (e.g. Result[T, MyAlias]) (#328).
602            (Ty::Con(n1, a1), Ty::Con(n2, a2)) if n1 == n2 && a1.len() == a2.len() => {
603                for (x, y) in a1.clone().into_iter().zip(a2.clone()) {
604                    self.unify_coerce_inner(x, y)?;
605                }
606                Ok(())
607            }
608            _ => self.u.unify(&a, &b),
609        }
610    }
611
612    fn check_fn(&mut self, fd: &a::FnDecl) -> Result<Scheme, Vec<TypeError>> {
613        // Instantiate fn's signature with fresh vars for its type params.
614        let scheme = function_scheme(fd);
615        let (param_tys, declared_effects, ret_ty) = match instantiate(&scheme, &mut self.u) {
616            Ty::Function { params, effects, ret } => (params, effects, *ret),
617            _ => unreachable!(),
618        };
619
620        let mut locals: IndexMap<String, Ty> = IndexMap::new();
621        for (p, t) in fd.params.iter().zip(param_tys.iter()) {
622            locals.insert(p.name.clone(), t.clone());
623        }
624
625        let mut inferred_effects = EffectSet::empty();
626        let body_ty = self.check_expr(&fd.body, "n_0", &mut locals, &mut inferred_effects)
627            .map_err(|e| vec![e])?;
628
629        // The body may produce an anonymous record literal where the
630        // signature expects a nominal record alias (and vice-versa,
631        // and at any nested level). `unify_with_record_coercion`
632        // handles that asymmetry while keeping nominal-vs-nominal
633        // mismatches strict.
634        if let Err(e) = self.unify_with_record_coercion(&body_ty, &ret_ty) {
635            return Err(vec![mismatch_err("n_0", e, &self.u, vec![format!("in function `{}`", fd.name)])]);
636        }
637
638        if !inferred_effects.is_subset(&declared_effects) {
639            // Pick the first undeclared effect for the error.
640            for e in inferred_effects.concrete.iter() {
641                if !declared_effects.concrete.iter().any(|d| d.subsumes(e)) {
642                    return Err(vec![TypeError::EffectNotDeclared {
643                        at_node: "n_0".into(),
644                        effect: e.pretty(),
645                    }]);
646                }
647            }
648        }
649
650        Ok(scheme)
651    }
652
653    fn check_expr(
654        &mut self,
655        e: &a::CExpr,
656        node_id: &str,
657        locals: &mut IndexMap<String, Ty>,
658        effs: &mut EffectSet,
659    ) -> Result<Ty, TypeError> {
660        match e {
661            a::CExpr::Literal { value } => Ok(lit_type(value)),
662            a::CExpr::Var { name } => {
663                if let Some(t) = locals.get(name) {
664                    return Ok(t.clone());
665                }
666                if let Some(scheme) = self.globals.get(name).cloned() {
667                    return Ok(instantiate(&scheme, &mut self.u));
668                }
669                Err(TypeError::UnknownIdentifier { at_node: node_id.into(), name: name.clone() })
670            }
671            a::CExpr::Constructor { name, args } => self.check_constructor(name, args, node_id, locals, effs),
672            a::CExpr::Call { callee, args } => self.check_call(e, callee, args, node_id, locals, effs),
673            a::CExpr::Let { name, ty, value, body } => {
674                let v_ty = self.check_expr(value, node_id, locals, effs)?;
675                if let Some(declared) = ty {
676                    let d = ty_from_canon(declared, &[]);
677                    if let Err(err) = self.unify_with_record_coercion(&v_ty, &d) {
678                        return Err(mismatch_err(node_id, err, &self.u, vec![format!("in let `{}`", name)]));
679                    }
680                }
681                let prev = locals.insert(name.clone(), v_ty);
682                let body_ty = self.check_expr(body, node_id, locals, effs)?;
683                match prev {
684                    Some(p) => { locals.insert(name.clone(), p); }
685                    None => { locals.shift_remove(name); }
686                }
687                Ok(body_ty)
688            }
689            a::CExpr::Match { scrutinee, arms } => {
690                let scrut_ty = self.check_expr(scrutinee, node_id, locals, effs)?;
691                if arms.is_empty() {
692                    return Err(TypeError::NonExhaustiveMatch {
693                        at_node: node_id.into(), missing: vec!["_".into()]
694                    });
695                }
696                let result_ty = self.u.fresh();
697                for arm in arms {
698                    let mut arm_locals = locals.clone();
699                    self.bind_pattern(&arm.pattern, &scrut_ty, &mut arm_locals, node_id)?;
700                    let arm_ty = self.check_expr(&arm.body, node_id, &mut arm_locals, effs)?;
701                    if let Err(err) = self.unify_with_record_coercion(&arm_ty, &result_ty) {
702                        return Err(mismatch_err(node_id, err, &self.u, vec!["in match arm".into()]));
703                    }
704                }
705                Ok(result_ty)
706            }
707            a::CExpr::Block { statements, result } => {
708                for s in statements {
709                    self.check_expr(s, node_id, locals, effs)?;
710                }
711                self.check_expr(result, node_id, locals, effs)
712            }
713            a::CExpr::RecordLit { fields } => {
714                let mut tys = IndexMap::new();
715                for f in fields {
716                    if tys.contains_key(&f.name) {
717                        return Err(TypeError::DuplicateField {
718                            at_node: node_id.into(), field: f.name.clone()
719                        });
720                    }
721                    let ft = self.check_expr(&f.value, node_id, locals, effs)?;
722                    tys.insert(f.name.clone(), ft);
723                }
724                Ok(Ty::Record(tys))
725            }
726            a::CExpr::TupleLit { items } => {
727                let mut ts = Vec::new();
728                for it in items { ts.push(self.check_expr(it, node_id, locals, effs)?); }
729                Ok(Ty::Tuple(ts))
730            }
731            a::CExpr::ListLit { items } => {
732                let elem = self.u.fresh();
733                for it in items {
734                    let t = self.check_expr(it, node_id, locals, effs)?;
735                    if let Err(err) = self.unify_with_record_coercion(&t, &elem) {
736                        return Err(mismatch_err(node_id, err, &self.u, vec!["in list literal".into()]));
737                    }
738                }
739                Ok(Ty::List(Box::new(elem)))
740            }
741            a::CExpr::FieldAccess { value, field } => {
742                let vt = self.check_expr(value, node_id, locals, effs)?;
743                let resolved = self.u.resolve(&vt);
744                // Unfold a Record-aliased Con (e.g. `type Request = { ... }`).
745                let resolved = match resolved {
746                    Ty::Con(ref n, _) => match self.type_env.types.get(n) {
747                        Some(td) => match &td.kind {
748                            TypeDefKind::Alias(inner @ Ty::Record(_)) => inner.clone(),
749                            _ => resolved,
750                        },
751                        None => resolved,
752                    },
753                    other => other,
754                };
755                match resolved {
756                    Ty::Record(fields) => fields.get(field).cloned()
757                        .ok_or_else(|| TypeError::UnknownField {
758                            at_node: node_id.into(),
759                            record_type: Ty::Record(fields.clone()).pretty(),
760                            field: field.clone(),
761                        }),
762                    other => Err(TypeError::TypeMismatch {
763                        at_node: node_id.into(),
764                        expected: "record".into(),
765                        got: other.pretty(),
766                        context: vec![format!("field access `.{}`", field)],
767                    }),
768                }
769            }
770            a::CExpr::Lambda { params, return_type, effects: l_effects, body } => {
771                let param_tys: Vec<Ty> = params.iter().map(|p| ty_from_canon(&p.ty, &[])).collect();
772                let ret_ty = ty_from_canon(return_type, &[]);
773                let declared = EffectSet {
774                    concrete: {
775                        let mut s = std::collections::BTreeSet::new();
776                        for e in l_effects {
777                            let arg = e.arg.as_ref().map(|a| match a {
778                                a::EffectArg::Str { value } => crate::types::EffectArg::Str(value.clone()),
779                                a::EffectArg::Int { value } => crate::types::EffectArg::Int(*value),
780                                a::EffectArg::Ident { value } => crate::types::EffectArg::Ident(value.clone()),
781                            });
782                            s.insert(crate::types::EffectKind { name: e.name.clone(), arg });
783                        }
784                        s
785                    },
786                    var: None,
787                };
788                let mut inner_locals = locals.clone();
789                for (p, t) in params.iter().zip(param_tys.iter()) {
790                    inner_locals.insert(p.name.clone(), t.clone());
791                }
792                let mut inner_effs = EffectSet::empty();
793                let body_ty = self.check_expr(body, node_id, &mut inner_locals, &mut inner_effs)?;
794                if let Err(err) = self.unify_with_record_coercion(&body_ty, &ret_ty) {
795                    return Err(mismatch_err(node_id, err, &self.u, vec!["in lambda body".into()]));
796                }
797                if !inner_effs.is_subset(&declared) {
798                    for e in inner_effs.concrete.iter() {
799                        if !declared.concrete.iter().any(|d| d.subsumes(e)) {
800                            return Err(TypeError::EffectNotDeclared {
801                                at_node: node_id.into(),
802                                effect: e.pretty(),
803                            });
804                        }
805                    }
806                }
807                Ok(Ty::function(param_tys, declared, ret_ty))
808            }
809            a::CExpr::BinOp { op, lhs, rhs } => self.check_binop(op, lhs, rhs, node_id, locals, effs),
810            a::CExpr::UnaryOp { op, expr } => {
811                let t = self.check_expr(expr, node_id, locals, effs)?;
812                match op.as_str() {
813                    "-" => {
814                        // Either Int or Float; we pick Int by default if unconstrained.
815                        let r = self.u.resolve(&t);
816                        match r {
817                            Ty::Prim(Prim::Int) | Ty::Prim(Prim::Float) => Ok(t),
818                            Ty::Var(_) => {
819                                // default to Int.
820                                self.u.unify(&t, &Ty::int()).map_err(|e| mismatch_err(node_id, e, &self.u, vec![]))?;
821                                Ok(Ty::int())
822                            }
823                            other => Err(TypeError::TypeMismatch {
824                                at_node: node_id.into(),
825                                expected: "Int or Float".into(),
826                                got: other.pretty(),
827                                context: vec!["unary `-`".into()],
828                            }),
829                        }
830                    }
831                    "not" => {
832                        self.u.unify(&t, &Ty::bool()).map_err(|e| mismatch_err(node_id, e, &self.u, vec!["unary `not`".into()]))?;
833                        Ok(Ty::bool())
834                    }
835                    other => panic!("unknown unary op: {other}"),
836                }
837            }
838            a::CExpr::Return { value } => {
839                // For now treat Return as having type Never; the surrounding
840                // context will unify with the actual return type.
841                self.check_expr(value, node_id, locals, effs)?;
842                Ok(Ty::Never)
843            }
844        }
845    }
846
847    fn check_binop(
848        &mut self,
849        op: &str,
850        lhs: &a::CExpr,
851        rhs: &a::CExpr,
852        node_id: &str,
853        locals: &mut IndexMap<String, Ty>,
854        effs: &mut EffectSet,
855    ) -> Result<Ty, TypeError> {
856        let lt = self.check_expr(lhs, node_id, locals, effs)?;
857        let rt = self.check_expr(rhs, node_id, locals, effs)?;
858        match op {
859            "+" => {
860                // #308: `+` is overloaded over Int, Float, and Str.
861                // Str concatenation dispatches at the VM layer
862                // (Op::NumAdd in bytecode handles all three).
863                // #323: unfold one-step type aliases on the resolved
864                // type so `type UserId = Int; id + id` works under
865                // Option-A transparency. Same below for the other
866                // numeric operator groups.
867                self.u.unify(&lt, &rt).map_err(|e| mismatch_err(node_id, e, &self.u, vec![format!("operator `{op}`")]))?;
868                let r = self.unfold_record_alias(self.u.resolve(&lt));
869                match r {
870                    Ty::Prim(Prim::Int) | Ty::Prim(Prim::Float) | Ty::Prim(Prim::Str) => Ok(lt),
871                    Ty::Var(_) => {
872                        self.u.unify(&lt, &Ty::int()).map_err(|e| mismatch_err(node_id, e, &self.u, vec![format!("operator `{op}`")]))?;
873                        Ok(Ty::int())
874                    }
875                    other => Err(TypeError::TypeMismatch {
876                        at_node: node_id.into(),
877                        expected: "Int, Float, or Str".into(),
878                        got: other.pretty(),
879                        context: vec![format!("operator `{op}`")],
880                    }),
881                }
882            }
883            "-" | "*" | "/" | "%" => {
884                self.u.unify(&lt, &rt).map_err(|e| mismatch_err(node_id, e, &self.u, vec![format!("operator `{op}`")]))?;
885                let r = self.unfold_record_alias(self.u.resolve(&lt));
886                match r {
887                    Ty::Prim(Prim::Int) | Ty::Prim(Prim::Float) => Ok(lt),
888                    Ty::Var(_) => {
889                        self.u.unify(&lt, &Ty::int()).map_err(|e| mismatch_err(node_id, e, &self.u, vec![format!("operator `{op}`")]))?;
890                        Ok(Ty::int())
891                    }
892                    other => Err(TypeError::TypeMismatch {
893                        at_node: node_id.into(),
894                        expected: "Int or Float".into(),
895                        got: other.pretty(),
896                        context: vec![format!("operator `{op}`")],
897                    }),
898                }
899            }
900            "==" | "!=" => {
901                self.u.unify(&lt, &rt).map_err(|e| mismatch_err(node_id, e, &self.u, vec![format!("operator `{op}`")]))?;
902                Ok(Ty::bool())
903            }
904            "<" | "<=" | ">" | ">=" => {
905                self.u.unify(&lt, &rt).map_err(|e| mismatch_err(node_id, e, &self.u, vec![format!("operator `{op}`")]))?;
906                let r = self.unfold_record_alias(self.u.resolve(&lt));
907                match r {
908                    Ty::Prim(Prim::Int) | Ty::Prim(Prim::Float) | Ty::Prim(Prim::Str) => Ok(Ty::bool()),
909                    Ty::Var(_) => {
910                        self.u.unify(&lt, &Ty::int()).map_err(|e| mismatch_err(node_id, e, &self.u, vec![format!("operator `{op}`")]))?;
911                        Ok(Ty::bool())
912                    }
913                    other => Err(TypeError::TypeMismatch {
914                        at_node: node_id.into(),
915                        expected: "Int, Float, or Str".into(),
916                        got: other.pretty(),
917                        context: vec![format!("operator `{op}`")],
918                    }),
919                }
920            }
921            "and" | "or" => {
922                self.u.unify(&lt, &Ty::bool()).map_err(|e| mismatch_err(node_id, e, &self.u, vec![format!("operator `{op}`")]))?;
923                self.u.unify(&rt, &Ty::bool()).map_err(|e| mismatch_err(node_id, e, &self.u, vec![format!("operator `{op}`")]))?;
924                Ok(Ty::bool())
925            }
926            other => panic!("unknown binop: {other}"),
927        }
928    }
929
930    fn check_call(
931        &mut self,
932        call_expr: &a::CExpr,
933        callee: &a::CExpr,
934        args: &[a::CExpr],
935        node_id: &str,
936        locals: &mut IndexMap<String, Ty>,
937        effs: &mut EffectSet,
938    ) -> Result<Ty, TypeError> {
939        // #168: snapshot the call's address before the recursive
940        // descent so we can later rewrite this exact node. Pointer
941        // identity is only meaningful while the AST stays put,
942        // which it does until check_program returns and the AST
943        // is handed back to the caller. `is_module_parse_call`
944        // recognises `<alias>.parse` where alias was bound to one
945        // of {json, toml, yaml} during the import pass.
946        let parse_call_ptr = if self.is_module_parse_call(callee) {
947            Some(call_expr as *const a::CExpr as usize)
948        } else {
949            None
950        };
951        let callee_ty = self.check_expr(callee, node_id, locals, effs)?;
952        let resolved = self.u.resolve(&callee_ty);
953        match resolved {
954            Ty::Function { params, effects, ret } => {
955                if params.len() != args.len() {
956                    return Err(TypeError::ArityMismatch {
957                        at_node: node_id.into(),
958                        expected: params.len(),
959                        got: args.len(),
960                    });
961                }
962                for (i, (a, p)) in args.iter().zip(params.iter()).enumerate() {
963                    let at = self.check_expr(a, node_id, locals, effs)?;
964                    if let Err(err) = self.unify_with_record_coercion(&at, p) {
965                        return Err(mismatch_err(node_id, err, &self.u, vec![format!("argument {} of call", i + 1)]));
966                    }
967                }
968                // #209 slice 2: refinement discharge for direct named
969                // calls. Look up the callee's original params (kept
970                // pre-strip in `fn_params`), and for each refined
971                // param attempt static discharge against the call
972                // arg. Refuted = type error; Deferred = pass (slice
973                // 3 will add a runtime residual check).
974                if let a::CExpr::Var { name: callee_name } = callee {
975                    if let Some(callee_params) = self.fn_params.get(callee_name).cloned() {
976                        for (i, (param, arg)) in callee_params.iter().zip(args.iter()).enumerate() {
977                            if let a::TypeExpr::Refined { binding, predicate, .. } = &param.ty {
978                                let outcome = crate::discharge::try_discharge(
979                                    predicate, binding, arg);
980                                if let crate::discharge::DischargeOutcome::Refuted { reason } = outcome {
981                                    return Err(TypeError::RefinementViolation {
982                                        at_node: node_id.into(),
983                                        fn_name: callee_name.clone(),
984                                        param_index: i,
985                                        binding: binding.clone(),
986                                        reason,
987                                    });
988                                }
989                            }
990                        }
991                    }
992                }
993                // Re-resolve effects after unifying args: an effect-row
994                // variable on the function type may have been bound by
995                // an argument's closure type, and we want the
996                // *post-binding* set when propagating to the caller.
997                let resolved_effects = self.u.resolve_effects(&effects);
998                effs.extend(&resolved_effects);
999                // #168: snapshot the post-arg-unification return type
1000                // for stdlib parse calls. Resolution to the eventual
1001                // `Result[Record{...}, _]` shape happens at the end
1002                // of `check_program` once the whole program's
1003                // unification has settled — match-pattern annotations
1004                // and let-type-annotations may bind T after this
1005                // point.
1006                if let Some(ptr) = parse_call_ptr {
1007                    self.pending_parse_calls.push((ptr, (*ret).clone()));
1008                }
1009                Ok(*ret)
1010            }
1011            Ty::Var(_) => {
1012                // Build a function type and unify.
1013                let mut p_tys = Vec::new();
1014                for a in args { p_tys.push(self.check_expr(a, node_id, locals, effs)?); }
1015                let r = self.u.fresh();
1016                let f = Ty::function(p_tys, EffectSet::empty(), r.clone());
1017                self.u.unify(&callee_ty, &f).map_err(|e| mismatch_err(node_id, e, &self.u, vec!["in call".into()]))?;
1018                Ok(r)
1019            }
1020            other => Err(TypeError::TypeMismatch {
1021                at_node: node_id.into(),
1022                expected: "function".into(),
1023                got: other.pretty(),
1024                context: vec!["in call".into()],
1025            }),
1026        }
1027    }
1028
1029    fn check_constructor(
1030        &mut self,
1031        name: &str,
1032        args: &[a::CExpr],
1033        node_id: &str,
1034        locals: &mut IndexMap<String, Ty>,
1035        effs: &mut EffectSet,
1036    ) -> Result<Ty, TypeError> {
1037        let owning = self.type_env.ctor_to_type.get(name).cloned()
1038            .ok_or_else(|| TypeError::UnknownVariant {
1039                at_node: node_id.into(),
1040                constructor: name.to_string(),
1041            })?;
1042        let def = self.type_env.types.get(&owning).cloned()
1043            .expect("ctor_to_type points to a real type");
1044        let variants = match &def.kind {
1045            TypeDefKind::Union(v) => v.clone(),
1046            _ => return Err(TypeError::UnknownVariant {
1047                at_node: node_id.into(),
1048                constructor: name.to_string(),
1049            }),
1050        };
1051        // Instantiate the type's params with fresh vars; substitute into
1052        // both the variant's payload type and the resulting Con(...).
1053        let mut subst = IndexMap::new();
1054        let mut con_args = Vec::with_capacity(def.params.len());
1055        for (i, _p) in def.params.iter().enumerate() {
1056            let fresh = self.u.fresh();
1057            subst.insert(i as u32, fresh.clone());
1058            con_args.push(fresh);
1059        }
1060        let payload = variants.get(name).cloned().flatten();
1061        match (payload, args) {
1062            (None, []) => Ok(Ty::Con(owning, con_args)),
1063            (Some(payload), args) => {
1064                let inst_payload = subst_vars(&payload, &subst, &IndexMap::new());
1065                let arg_count = match &inst_payload {
1066                    Ty::Tuple(items) => items.len(),
1067                    _ => 1,
1068                };
1069                if arg_count != args.len() {
1070                    return Err(TypeError::ArityMismatch {
1071                        at_node: node_id.into(),
1072                        expected: arg_count,
1073                        got: args.len(),
1074                    });
1075                }
1076                if args.len() == 1 {
1077                    let at = self.check_expr(&args[0], node_id, locals, effs)?;
1078                    self.unify_with_record_coercion(&at, &inst_payload).map_err(|e| mismatch_err(node_id, e, &self.u, vec![format!("constructor `{}`", name)]))?;
1079                } else if let Ty::Tuple(items) = inst_payload {
1080                    for (i, (a, t)) in args.iter().zip(items.iter()).enumerate() {
1081                        let at = self.check_expr(a, node_id, locals, effs)?;
1082                        self.unify_with_record_coercion(&at, t).map_err(|e| mismatch_err(node_id, e, &self.u, vec![format!("constructor `{}` arg {}", name, i + 1)]))?;
1083                    }
1084                }
1085                Ok(Ty::Con(owning, con_args))
1086            }
1087            (None, _) => Err(TypeError::ArityMismatch {
1088                at_node: node_id.into(), expected: 0, got: args.len(),
1089            }),
1090        }
1091    }
1092
1093    fn bind_pattern(
1094        &mut self,
1095        pat: &a::Pattern,
1096        ty: &Ty,
1097        locals: &mut IndexMap<String, Ty>,
1098        node_id: &str,
1099    ) -> Result<(), TypeError> {
1100        match pat {
1101            a::Pattern::PWild => Ok(()),
1102            a::Pattern::PVar { name } => {
1103                locals.insert(name.clone(), ty.clone());
1104                Ok(())
1105            }
1106            a::Pattern::PLiteral { value } => {
1107                let lt = lit_type(value);
1108                self.unify_with_record_coercion(&lt, ty).map_err(|e| mismatch_err(node_id, e, &self.u, vec!["in pattern".into()]))?;
1109                Ok(())
1110            }
1111            a::Pattern::PConstructor { name, args } => {
1112                // Re-use constructor logic but in pattern position.
1113                let owning = self.type_env.ctor_to_type.get(name).cloned()
1114                    .ok_or_else(|| TypeError::UnknownVariant {
1115                        at_node: node_id.into(), constructor: name.clone(),
1116                    })?;
1117                let def = self.type_env.types.get(&owning).cloned().unwrap();
1118                let mut subst = IndexMap::new();
1119                let mut con_args = Vec::new();
1120                for (i, _) in def.params.iter().enumerate() {
1121                    let fresh = self.u.fresh();
1122                    subst.insert(i as u32, fresh.clone());
1123                    con_args.push(fresh);
1124                }
1125                let con_ty = Ty::Con(owning.clone(), con_args);
1126                self.unify_with_record_coercion(&con_ty, ty).map_err(|e| mismatch_err(node_id, e, &self.u, vec![format!("constructor pattern `{}`", name)]))?;
1127                let payload = match &def.kind {
1128                    TypeDefKind::Union(v) => v.get(name).cloned().flatten(),
1129                    _ => None,
1130                };
1131                match (payload, args.as_slice()) {
1132                    (None, []) => Ok(()),
1133                    (Some(payload), args) => {
1134                        let inst = subst_vars(&payload, &subst, &IndexMap::new());
1135                        if args.len() == 1 {
1136                            self.bind_pattern(&args[0], &inst, locals, node_id)?;
1137                        } else if let Ty::Tuple(items) = inst {
1138                            for (a, t) in args.iter().zip(items.iter()) {
1139                                self.bind_pattern(a, t, locals, node_id)?;
1140                            }
1141                        }
1142                        Ok(())
1143                    }
1144                    (None, _) => Err(TypeError::ArityMismatch {
1145                        at_node: node_id.into(), expected: 0, got: args.len(),
1146                    }),
1147                }
1148            }
1149            a::Pattern::PRecord { fields } => {
1150                // Unfold a record-aliased Con (`type Bands = { ... }`)
1151                // so a structural `{ idea: pat, ... }` pattern can match
1152                // a nominal-typed scrutinee, mirror of #79's literal
1153                // coercion at every position.
1154                let resolved = self.unfold_record_alias(self.u.resolve(ty));
1155                let rec = match resolved {
1156                    Ty::Record(r) => r,
1157                    _ => return Err(TypeError::TypeMismatch {
1158                        at_node: node_id.into(),
1159                        expected: "record".into(),
1160                        got: ty.pretty(),
1161                        context: vec!["in record pattern".into()],
1162                    }),
1163                };
1164                for f in fields {
1165                    let ft = rec.get(&f.name).cloned()
1166                        .ok_or_else(|| TypeError::UnknownField {
1167                            at_node: node_id.into(),
1168                            record_type: Ty::Record(rec.clone()).pretty(),
1169                            field: f.name.clone(),
1170                        })?;
1171                    self.bind_pattern(&f.pattern, &ft, locals, node_id)?;
1172                }
1173                Ok(())
1174            }
1175            a::Pattern::PTuple { items } => {
1176                let resolved = self.u.resolve(ty);
1177                let tup = match resolved {
1178                    Ty::Tuple(t) => t,
1179                    Ty::Var(_) => {
1180                        let fresh: Vec<Ty> = items.iter().map(|_| self.u.fresh()).collect();
1181                        let tup_ty = Ty::Tuple(fresh.clone());
1182                        self.unify_with_record_coercion(&tup_ty, ty).map_err(|e| mismatch_err(node_id, e, &self.u, vec!["in tuple pattern".into()]))?;
1183                        fresh
1184                    }
1185                    other => return Err(TypeError::TypeMismatch {
1186                        at_node: node_id.into(),
1187                        expected: "tuple".into(),
1188                        got: other.pretty(),
1189                        context: vec!["in tuple pattern".into()],
1190                    }),
1191                };
1192                if tup.len() != items.len() {
1193                    return Err(TypeError::ArityMismatch {
1194                        at_node: node_id.into(), expected: tup.len(), got: items.len(),
1195                    });
1196                }
1197                for (p, t) in items.iter().zip(tup.iter()) {
1198                    self.bind_pattern(p, t, locals, node_id)?;
1199                }
1200                Ok(())
1201            }
1202        }
1203    }
1204}
1205
1206fn lit_type(l: &a::CLit) -> Ty {
1207    match l {
1208        a::CLit::Int { .. } => Ty::int(),
1209        a::CLit::Float { .. } => Ty::float(),
1210        a::CLit::Str { .. } => Ty::str(),
1211        a::CLit::Bytes { .. } => Ty::bytes(),
1212        a::CLit::Bool { .. } => Ty::bool(),
1213        a::CLit::Unit => Ty::Unit,
1214    }
1215}
1216
1217fn instantiate(s: &Scheme, u: &mut Unifier) -> Ty {
1218    let mut ty_subst = IndexMap::new();
1219    for v in &s.vars { ty_subst.insert(*v, u.fresh()); }
1220    let mut eff_subst = IndexMap::new();
1221    for v in &s.eff_vars { eff_subst.insert(*v, u.fresh_eff_id()); }
1222    subst_vars(&s.ty, &ty_subst, &eff_subst)
1223}
1224
1225fn subst_vars(
1226    t: &Ty,
1227    subst: &IndexMap<TyVarId, Ty>,
1228    eff_subst: &IndexMap<u32, u32>,
1229) -> Ty {
1230    match t {
1231        Ty::Var(v) => subst.get(v).cloned().unwrap_or_else(|| Ty::Var(*v)),
1232        Ty::Prim(_) | Ty::Unit | Ty::Never => t.clone(),
1233        Ty::List(inner) => Ty::List(Box::new(subst_vars(inner, subst, eff_subst))),
1234        Ty::Tuple(items) => Ty::Tuple(items.iter().map(|t| subst_vars(t, subst, eff_subst)).collect()),
1235        Ty::Record(fs) => {
1236            let mut out = IndexMap::new();
1237            for (k, v) in fs { out.insert(k.clone(), subst_vars(v, subst, eff_subst)); }
1238            Ty::Record(out)
1239        }
1240        Ty::Con(n, args) => Ty::Con(n.clone(),
1241            args.iter().map(|t| subst_vars(t, subst, eff_subst)).collect()),
1242        Ty::Function { params, effects, ret } => {
1243            // Refresh the effect-row variable if it's quantified in the
1244            // scheme; concrete kinds carry through unchanged.
1245            let new_effects = EffectSet {
1246                concrete: effects.concrete.clone(),
1247                var: effects.var.and_then(|v| eff_subst.get(&v).copied()).or(effects.var),
1248            };
1249            Ty::Function {
1250                params: params.iter().map(|t| subst_vars(t, subst, eff_subst)).collect(),
1251                effects: new_effects,
1252                ret: Box::new(subst_vars(ret, subst, eff_subst)),
1253            }
1254        }
1255    }
1256}
1257
1258fn mismatch_err(node_id: &str, e: UnifyError, u: &Unifier, context: Vec<String>) -> TypeError {
1259    match e {
1260        UnifyError::Mismatch { a, b } => TypeError::TypeMismatch {
1261            at_node: node_id.into(),
1262            expected: u.resolve(&b).pretty(),
1263            got: u.resolve(&a).pretty(),
1264            context,
1265        },
1266        UnifyError::Infinite { .. } => TypeError::InfiniteType { at_node: node_id.into() },
1267        UnifyError::EffectMismatch { a, b } => {
1268            // Render effect mismatches as a type-mismatch in compact
1269            // form, e.g. `[net]` vs `[]`. Avoids inventing a new
1270            // TypeError variant + wire format right now.
1271            let render = |e: &EffectSet| -> String {
1272                let mut parts: Vec<String> = e.concrete.iter()
1273                    .map(crate::types::EffectKind::pretty).collect();
1274                if let Some(v) = e.var { parts.push(format!("?e{}", v)); }
1275                if parts.is_empty() { "[]".into() } else { format!("[{}]", parts.join(", ")) }
1276            };
1277            TypeError::TypeMismatch {
1278                at_node: node_id.into(),
1279                expected: render(&b),
1280                got: render(&a),
1281                context,
1282            }
1283        }
1284    }
1285}