Skip to main content

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