Skip to main content

logicaffeine_compile/analysis/
check.rs

1//! Bidirectional type checker for the LOGOS compilation pipeline.
2//!
3//! Replaces `TypeEnv::infer_program()` with a proper constraint-solving pass
4//! that eliminates `Unknown` for field access, empty collections, option literals,
5//! pipe receives, inspect arm bindings, and closure call expressions.
6//!
7//! # Architecture
8//!
9//! ```text
10//! AST
11//!  │
12//!  ├── preregister_functions   ← forward-reference pre-pass
13//!  │
14//!  └── infer_stmt / infer_expr ← bidirectional checking
15//!           │
16//!           └── UnificationTable ← Robinson unification (from unify.rs)
17//!                    │
18//!                    └── zonk → TypeEnv (LogosType) → codegen
19//! ```
20
21use std::collections::HashMap;
22
23use crate::analysis::unify::{
24    unify_numeric, InferType, TyVar, TypeError, TypeScheme, TypeScope, UnificationTable,
25};
26use crate::analysis::{FieldType, FnSig, LogosType, TypeDef, TypeEnv, TypeRegistry};
27use crate::ast::stmt::{BinaryOpKind, Expr, Pattern, Stmt, StmtId};
28use crate::intern::{Interner, Symbol};
29
30// ============================================================================
31// Data structures
32// ============================================================================
33
34/// A registered function's signature, supporting both monomorphic and generic functions.
35///
36/// For generic functions (non-empty `scheme.vars`), each call site must instantiate
37/// the scheme to get fresh type variables, preventing cross-call contamination.
38/// For monomorphic functions (`scheme.vars` is empty), `scheme.body` is the direct type.
39#[derive(Clone, Debug)]
40struct FunctionRecord {
41    /// Parameter names (for binding in the function scope).
42    param_names: Vec<Symbol>,
43    is_native: bool,
44    /// The quantified type scheme: `forall vars. Function(param_types, return_type)`.
45    /// For monomorphic functions, `vars` is empty and body is used directly.
46    scheme: TypeScheme,
47    /// The DECLARED type parameters in declaration order, each as the type its variable resolves
48    /// to — instantiated with the scheme, they are the type arguments one call is solved for.
49    declared: Vec<InferType>,
50}
51
52/// A node of the checked program, by address. The checker and a later pass over the SAME
53/// statements agree on it without the AST carrying ids.
54#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
55pub enum Site {
56    Expr(usize),
57    Stmt(usize),
58}
59
60impl Site {
61    pub fn of_expr(e: &Expr) -> Self {
62        Site::Expr(e as *const Expr as *const () as usize)
63    }
64
65    pub fn of_stmt(s: &Stmt) -> Self {
66        Site::Stmt(s as *const Stmt as *const () as usize)
67    }
68}
69
70/// One call of a generic function, as the checker solved it.
71#[derive(Debug, Clone)]
72pub struct CallInstance {
73    /// The declared type arguments, in declaration order.
74    pub type_args: Vec<InferType>,
75    /// Every argument's type was fully known. When one was not, a type argument the call leaves
76    /// open may be one the checker failed to see, not one that nothing constrains.
77    pub precise: bool,
78}
79
80/// What the checker solved at every generic site of a program — the input to monomorphization.
81///
82/// Types are RESOLVED, not zonked: a site inside a generic function's body still names that
83/// function's own type variables (listed in `type_params`), to be substituted once per instance.
84/// A variable nothing constrained stays a variable.
85#[derive(Debug, Default)]
86pub struct Instantiations {
87    /// Each call of a generic function.
88    pub calls: HashMap<Site, CallInstance>,
89    /// Each `New` / `NewVariant` and `some` / `none`: the type it builds.
90    pub constructed: HashMap<Site, InferType>,
91    /// Each empty sequence literal (`[]`): the sequence type its context gives it.
92    pub empty_lists: HashMap<Site, InferType>,
93    /// Each `Inspect`: the type of the value it inspects.
94    pub scrutinees: HashMap<Site, InferType>,
95    /// Each generic function's type parameters in declaration order, each as the type its
96    /// variable resolved to (its own unbound variable, unless the body pinned it).
97    pub type_params: HashMap<Symbol, Vec<(Symbol, InferType)>>,
98}
99
100/// Bidirectional type checking environment.
101///
102/// Scopes are pushed/popped around function bodies and match arms.
103/// All bindings are also written to `all_vars` for later `TypeEnv` output.
104struct CheckEnv<'r> {
105    /// Stacked scopes (innermost last). Variables resolved from inner-to-outer.
106    scopes: Vec<HashMap<Symbol, InferType>>,
107    /// Flat map of every variable ever bound — accumulated for `TypeEnv` output.
108    all_vars: HashMap<Symbol, InferType>,
109    /// Registered function signatures.
110    functions: HashMap<Symbol, FunctionRecord>,
111    /// Expected return type inside the current function body.
112    current_return_type: Option<InferType>,
113    /// Unification table for type variables.
114    table: UnificationTable,
115    registry: &'r TypeRegistry,
116    interner: &'r Interner,
117    /// The type parameters of the generic function whose body is being checked, each standing
118    /// for its variable — so a `T` written in the body (`a new Seq of T`) means that variable.
119    type_params_in_scope: HashMap<Symbol, InferType>,
120    /// Every generic site solved so far, unresolved until the program is checked.
121    sites: Instantiations,
122    /// Each generic call's argument types, to judge its precision once the program is checked.
123    call_arg_types: HashMap<Site, Vec<InferType>>,
124    /// Each bare type name that IS a namespaced type, so both spellings are one type.
125    twins: HashMap<Symbol, Symbol>,
126}
127
128impl<'r> CheckEnv<'r> {
129    fn new(registry: &'r TypeRegistry, interner: &'r Interner) -> Self {
130        Self {
131            scopes: vec![HashMap::new()],
132            all_vars: HashMap::new(),
133            functions: HashMap::new(),
134            current_return_type: None,
135            table: UnificationTable::new(),
136            registry,
137            interner,
138            type_params_in_scope: HashMap::new(),
139            sites: Instantiations::default(),
140            call_arg_types: HashMap::new(),
141            twins: registry.namespaced_twins(interner),
142        }
143    }
144
145    /// The one identity a user type named `name` has (see `TypeScope::canonical`).
146    fn canonical(&self, name: Symbol) -> Symbol {
147        self.twins.get(&name).copied().unwrap_or(name)
148    }
149
150    /// A written type, read with the registry and the type parameters in scope.
151    fn written_type(&self, ty: &crate::ast::stmt::TypeExpr) -> InferType {
152        self.written_type_with(ty, &self.type_params_in_scope)
153    }
154
155    fn written_type_with(
156        &self,
157        ty: &crate::ast::stmt::TypeExpr,
158        params: &HashMap<Symbol, InferType>,
159    ) -> InferType {
160        InferType::from_type_expr_in(
161            ty,
162            &TypeScope {
163                interner: self.interner,
164                registry: Some(self.registry),
165                params,
166                twins: Some(&self.twins),
167            },
168        )
169    }
170
171    /// A field's declared type at one application of its record or enum, `args` bound to the
172    /// type's own parameters in order.
173    fn field_type_at(&self, ty: &FieldType, generics: &[Symbol], args: &[InferType]) -> InferType {
174        let params: HashMap<Symbol, InferType> =
175            generics.iter().copied().zip(args.iter().cloned()).collect();
176        InferType::from_field_type_in(
177            ty,
178            &TypeScope {
179                interner: self.interner,
180                registry: Some(self.registry),
181                params: &params,
182                twins: Some(&self.twins),
183            },
184        )
185    }
186
187    /// The type arguments one construction of `type_sym` is solved for: the written ones, or a
188    /// fresh variable per type parameter when none were written.
189    fn applied_args(
190        &mut self,
191        type_sym: Symbol,
192        written: &[crate::ast::stmt::TypeExpr],
193    ) -> (Vec<Symbol>, Vec<InferType>) {
194        let generics = match self.registry.get(type_sym) {
195            Some(TypeDef::Struct { generics, .. } | TypeDef::Enum { generics, .. }) => {
196                generics.clone()
197            }
198            _ => Vec::new(),
199        };
200        let args = if written.len() == generics.len() && !written.is_empty() {
201            written.iter().map(|t| self.written_type(t)).collect()
202        } else {
203            generics.iter().map(|_| self.table.fresh()).collect()
204        };
205        (generics, args)
206    }
207
208    /// Every generic site with its types resolved as far as the whole program determines them.
209    fn into_instantiations(self) -> Instantiations {
210        fn mentions_unknown(t: &InferType) -> bool {
211            match t {
212                InferType::Unknown => true,
213                InferType::Seq(i) | InferType::Set(i) | InferType::Option(i) => mentions_unknown(i),
214                InferType::Map(k, v) => mentions_unknown(k) || mentions_unknown(v),
215                InferType::UserDefined(_, args) => args.iter().any(mentions_unknown),
216                InferType::Function(ps, r) => {
217                    ps.iter().any(mentions_unknown) || mentions_unknown(r)
218                }
219                _ => false,
220            }
221        }
222        let table = &self.table;
223        let sites = self.sites;
224        let arg_types = self.call_arg_types;
225        Instantiations {
226            calls: sites
227                .calls
228                .into_iter()
229                .map(|(k, v)| {
230                    let precise = arg_types.get(&k).map_or(true, |ts| {
231                        ts.iter().all(|t| !mentions_unknown(&table.resolve(t)))
232                    });
233                    let type_args = v.type_args.iter().map(|t| table.resolve(t)).collect();
234                    (k, CallInstance { type_args, precise })
235                })
236                .collect(),
237            constructed: sites
238                .constructed
239                .into_iter()
240                .map(|(k, v)| (k, table.resolve(&v)))
241                .collect(),
242            empty_lists: sites
243                .empty_lists
244                .into_iter()
245                .map(|(k, v)| (k, table.resolve(&v)))
246                .collect(),
247            scrutinees: sites
248                .scrutinees
249                .into_iter()
250                .map(|(k, v)| (k, table.resolve(&v)))
251                .collect(),
252            type_params: sites
253                .type_params
254                .into_iter()
255                .map(|(f, ps)| {
256                    (
257                        f,
258                        ps.into_iter()
259                            .map(|(p, t)| (p, table.resolve(&t)))
260                            .collect(),
261                    )
262                })
263                .collect(),
264        }
265    }
266
267    fn push_scope(&mut self) {
268        self.scopes.push(HashMap::new());
269    }
270
271    fn pop_scope(&mut self) {
272        self.scopes.pop();
273    }
274
275    /// Bind a variable in the current scope, also recording in `all_vars`.
276    fn bind_var(&mut self, sym: Symbol, ty: InferType) {
277        if let Some(scope) = self.scopes.last_mut() {
278            scope.insert(sym, ty.clone());
279        }
280        self.all_vars.insert(sym, ty);
281    }
282
283    /// Look up a variable, searching scopes from innermost to outermost.
284    ///
285    /// Uses `resolve` (not `zonk`) so that unbound type variables from generic
286    /// function parameters remain as `Var(tv)` during inference, enabling
287    /// proper unification at call sites.
288    fn lookup_var(&self, sym: Symbol) -> Option<InferType> {
289        for scope in self.scopes.iter().rev() {
290            if let Some(ty) = scope.get(&sym) {
291                return Some(self.table.resolve(ty));
292            }
293        }
294        None
295    }
296
297    /// Convert the check environment into a `TypeEnv` for codegen.
298    fn into_type_env(self) -> TypeEnv {
299        let mut type_env = TypeEnv::new();
300
301        // Collect all variable bindings, zonk each to a concrete LogosType
302        for (sym, ty) in self.all_vars {
303            let logos_ty = self.table.to_logos_type(&ty);
304            type_env.register(sym, logos_ty);
305        }
306
307        // Collect function signatures — instantiate monomorphic view for codegen
308        for (name, rec) in self.functions {
309            // Zonk the scheme body to extract concrete param/return types for TypeEnv.
310            // For generic functions, unsolved vars zonk to Unknown, which is fine
311            // since codegen uses TypeExpr (not TypeEnv) for generic param types.
312            if let InferType::Function(param_types, ret_box) = &rec.scheme.body {
313                let ret_logos = self.table.to_logos_type(ret_box);
314                let params: Vec<(Symbol, LogosType)> = rec
315                    .param_names
316                    .iter()
317                    .zip(param_types.iter())
318                    .map(|(sym, ty)| (*sym, self.table.to_logos_type(ty)))
319                    .collect();
320                type_env.register_fn(
321                    name,
322                    FnSig {
323                        params,
324                        return_type: ret_logos,
325                    },
326                );
327                type_env.set_native_fn(name, rec.is_native);
328            }
329        }
330
331        type_env
332    }
333}
334
335// ============================================================================
336// Pre-pass: forward reference registration
337// ============================================================================
338
339impl<'r> CheckEnv<'r> {
340    /// Register all top-level function signatures before the main checking pass.
341    ///
342    /// This enables forward references and mutual recursion: any function can
343    /// call any other function regardless of declaration order.
344    ///
345    /// For generic functions (non-empty `generics`), allocates a fresh `TyVar` per
346    /// type parameter and builds a `TypeScheme` so call sites can instantiate them.
347    fn preregister_functions(&mut self, stmts: &[Stmt]) {
348        for stmt in stmts {
349            if let Stmt::FunctionDef {
350                name,
351                generics,
352                params,
353                return_type,
354                is_native,
355                ..
356            } = stmt
357            {
358                // Allocate one TyVar per generic type parameter
359                let type_param_map: HashMap<Symbol, TyVar> = generics
360                    .iter()
361                    .map(|&sym| (sym, self.table.fresh_var()))
362                    .collect();
363                let in_scope: HashMap<Symbol, InferType> = type_param_map
364                    .iter()
365                    .map(|(s, tv)| (*s, InferType::Var(*tv)))
366                    .collect();
367
368                let param_types: Vec<InferType> = params
369                    .iter()
370                    .map(|(_, ty_expr)| self.written_type_with(ty_expr, &in_scope))
371                    .collect();
372                let param_names: Vec<Symbol> = params.iter().map(|(sym, _)| *sym).collect();
373
374                let ret_type = if let Some(rt) = return_type {
375                    self.written_type_with(rt, &in_scope)
376                } else {
377                    self.table.fresh()
378                };
379
380                let generic_vars: Vec<TyVar> = generics
381                    .iter()
382                    .filter_map(|sym| type_param_map.get(sym).copied())
383                    .collect();
384                let declared = generic_vars.iter().map(|tv| InferType::Var(*tv)).collect();
385
386                let scheme = TypeScheme {
387                    vars: generic_vars,
388                    body: InferType::Function(param_types, Box::new(ret_type)),
389                };
390
391                self.functions.insert(
392                    *name,
393                    FunctionRecord {
394                        param_names,
395                        scheme,
396                        declared,
397                        is_native: *is_native,
398                    },
399                );
400            }
401        }
402    }
403}
404
405// ============================================================================
406// Core inference
407// ============================================================================
408
409impl<'r> CheckEnv<'r> {
410    /// Check an expression against an expected type (checking mode).
411    ///
412    /// Handles numeric literal coercion (`5` against `Real` → `Float`) and
413    /// structural checking before falling through to synthesis + unification.
414    fn check_expr(&mut self, expr: &Expr, expected: &InferType) -> Result<InferType, TypeError> {
415        use crate::ast::stmt::Literal;
416
417        // Number literals are polymorphic: 5 checks against Int, Float, Nat, or Byte
418        if let Expr::Literal(Literal::Number(_)) = expr {
419            match expected {
420                InferType::Float => return Ok(InferType::Float),
421                InferType::Nat => return Ok(InferType::Nat),
422                InferType::Int => return Ok(InferType::Int),
423                InferType::Byte => return Ok(InferType::Byte),
424                _ => {}
425            }
426        }
427
428        // `nothing` is polymorphic: it is `None` when checked against Option(T),
429        // and the unit value `()` in all other contexts.
430        if let Expr::Literal(Literal::Nothing) = expr {
431            if let InferType::Option(_) = expected {
432                return Ok(expected.clone());
433            }
434        }
435
436        // List literals: check EACH element against the expected element type so
437        // the numeric-literal coercion applies element-wise (e.g. `[1, 2, 3]`
438        // under a `Seq of Real` annotation), instead of synthesizing the element
439        // type from items[0] alone and failing to unify with the annotation.
440        if let Expr::List(items) = expr {
441            if let InferType::Seq(elem) = self.table.resolve(expected) {
442                for item in items {
443                    self.check_expr(item, &elem)?;
444                }
445                return Ok(InferType::Seq(elem));
446            }
447        }
448
449        // Default: synthesize then unify
450        let inferred = self.infer_expr(expr)?;
451        self.table.unify(&inferred, expected)?;
452        Ok(self.table.resolve(expected))
453    }
454
455    /// Infer the type of an expression (synthesis mode).
456    fn infer_expr(&mut self, expr: &Expr) -> Result<InferType, TypeError> {
457        match expr {
458            Expr::Literal(lit) => Ok(InferType::from_literal(lit)),
459
460            Expr::Identifier(sym) => Ok(self.lookup_var(*sym).unwrap_or(InferType::Unknown)),
461
462            Expr::BinaryOp { op, left, right } => self.infer_binary_op(*op, left, right),
463
464            Expr::Length { collection } => {
465                self.infer_expr(collection)?;
466                Ok(InferType::Int)
467            }
468
469            Expr::Call { function, args } => self.infer_call(*function, args, Site::of_expr(expr)),
470
471            Expr::Index { collection, index } => {
472                let coll_ty = self.infer_expr(collection)?;
473                self.infer_expr(index)?;
474                let walked = self.table.resolve(&coll_ty);
475                match walked {
476                    InferType::Seq(inner) => Ok(*inner),
477                    InferType::Map(_, v) => Ok(*v),
478                    _ => Ok(InferType::Unknown),
479                }
480            }
481
482            Expr::List(items) => {
483                // Every element is inferred, not just the first: a later element may hold a
484                // generic call or construction whose instantiation must be solved too. The first
485                // element names the element type; the rest join it where they can.
486                let elem_type = match items.split_first() {
487                    None => self.table.fresh(),
488                    Some((first, rest)) => {
489                        let first_ty = self.infer_expr(first)?;
490                        for item in rest {
491                            let item_ty = self.infer_expr(item)?;
492                            self.table.unify(&first_ty, &item_ty).ok();
493                        }
494                        first_ty
495                    }
496                };
497                let ty = InferType::Seq(Box::new(elem_type));
498                if items.is_empty() {
499                    self.sites
500                        .empty_lists
501                        .insert(Site::of_expr(expr), ty.clone());
502                }
503                Ok(ty)
504            }
505
506            Expr::OptionSome { value } => {
507                let inner = self.infer_expr(value)?;
508                let ty = InferType::Option(Box::new(inner));
509                self.sites
510                    .constructed
511                    .insert(Site::of_expr(expr), ty.clone());
512                Ok(ty)
513            }
514
515            Expr::OptionNone => {
516                let elem_var = self.table.fresh();
517                let ty = InferType::Option(Box::new(elem_var));
518                self.sites
519                    .constructed
520                    .insert(Site::of_expr(expr), ty.clone());
521                Ok(ty)
522            }
523
524            Expr::Range { start, end } => {
525                self.infer_expr(start)?;
526                self.infer_expr(end)?;
527                Ok(InferType::Seq(Box::new(InferType::Int)))
528            }
529
530            Expr::Contains { collection, value } => {
531                self.infer_expr(collection)?;
532                self.infer_expr(value)?;
533                Ok(InferType::Bool)
534            }
535
536            Expr::Copy { expr: inner } | Expr::Give { value: inner } => self.infer_expr(inner),
537
538            Expr::WithCapacity { value, capacity } => {
539                self.infer_expr(capacity)?;
540                self.infer_expr(value)
541            }
542
543            Expr::FieldAccess { object, field } => {
544                let obj_ty = self.infer_expr(object)?;
545                self.infer_field_access(obj_ty, *field)
546            }
547
548            Expr::New {
549                type_name,
550                type_args,
551                init_fields,
552            } => {
553                let name = self.interner.resolve(*type_name);
554                let ty = match name {
555                    "Seq" | "List" | "Vec" => {
556                        let elem = type_args
557                            .first()
558                            .map(|t| self.written_type(t))
559                            .unwrap_or_else(|| self.table.fresh());
560                        InferType::Seq(Box::new(elem))
561                    }
562                    "Map" | "HashMap" => {
563                        let key = type_args
564                            .first()
565                            .map(|t| self.written_type(t))
566                            .unwrap_or(InferType::String);
567                        let val = type_args
568                            .get(1)
569                            .map(|t| self.written_type(t))
570                            .unwrap_or(InferType::String);
571                        InferType::Map(Box::new(key), Box::new(val))
572                    }
573                    "Set" | "HashSet" => {
574                        let elem = type_args
575                            .first()
576                            .map(|t| self.written_type(t))
577                            .unwrap_or_else(|| self.table.fresh());
578                        InferType::Set(Box::new(elem))
579                    }
580                    _ => {
581                        // A struct constructor's field initialisers were never checked: the arm
582                        // matched `..` and returned the nominal type, so `a new P with x "text"`
583                        // stored a Text in an Int field and `a new P with z 5` invented a field,
584                        // both silently. Each initialiser is checked against the declared field,
585                        // read at this construction's type arguments.
586                        let (_, args) = self.applied_args(*type_name, type_args);
587                        let struct_ty = InferType::UserDefined(self.canonical(*type_name), args);
588                        for (field, value) in init_fields {
589                            let value_ty = self.infer_expr(value)?;
590                            // `infer_field_access` raises `FieldNotFound` for a name the struct
591                            // does not declare, so an invented field is caught here too.
592                            let field_ty = self.infer_field_access(struct_ty.clone(), *field)?;
593                            self.table.unify(&value_ty, &field_ty)?;
594                        }
595                        struct_ty
596                    }
597                };
598                self.sites
599                    .constructed
600                    .insert(Site::of_expr(expr), ty.clone());
601                Ok(ty)
602            }
603
604            // A variant's payload is checked against its declared fields, read at this
605            // construction's type arguments — which the payload itself solves: `a new Just with
606            // value 42` is a `Maybe of Int`. A payload-free variant (`a new Nothing`) leaves them
607            // open for the context to settle.
608            Expr::NewVariant {
609                enum_name,
610                variant,
611                fields,
612            } => {
613                let (generics, args) = self.applied_args(*enum_name, &[]);
614                let declared: Vec<(Symbol, FieldType)> = match self.registry.get(*enum_name) {
615                    Some(TypeDef::Enum { variants, .. }) => variants
616                        .iter()
617                        .find(|v| v.name == *variant)
618                        .map(|v| v.fields.iter().map(|f| (f.name, f.ty.clone())).collect())
619                        .unwrap_or_default(),
620                    _ => Vec::new(),
621                };
622                for (field, value) in fields {
623                    match declared.iter().find(|(name, _)| name == field) {
624                        Some((_, fty)) => {
625                            let expected = self.field_type_at(fty, &generics, &args);
626                            self.check_widening(value, &expected)?;
627                        }
628                        None => {
629                            self.infer_expr(value)?;
630                        }
631                    }
632                }
633                let ty = InferType::UserDefined(self.canonical(*enum_name), args);
634                self.sites
635                    .constructed
636                    .insert(Site::of_expr(expr), ty.clone());
637                Ok(ty)
638            }
639
640            Expr::CallExpr { callee, args } => self.infer_call_expr(callee, args),
641
642            Expr::Closure {
643                params,
644                body: closure_body,
645                return_type,
646            } => self.infer_closure(params, closure_body, return_type),
647
648            Expr::InterpolatedString(parts) => {
649                for part in parts {
650                    if let crate::ast::stmt::StringPart::Expr { value, .. } = part {
651                        self.infer_expr(value)?;
652                    }
653                }
654                Ok(InferType::String)
655            }
656
657            Expr::Slice {
658                collection,
659                start,
660                end,
661            } => {
662                self.infer_expr(start)?;
663                self.infer_expr(end)?;
664                self.infer_expr(collection)
665            }
666
667            Expr::Union { left, right } | Expr::Intersection { left, right } => {
668                self.infer_expr(right)?;
669                self.infer_expr(left)
670            }
671
672            // EVERY REMAINING EXPRESSION KIND, NAMED: none has a type this checker models, but
673            // each one's operands are still inferred — a generic call inside a tuple or a negation
674            // must be solved like any other.
675            Expr::Not { operand } => {
676                self.infer_expr(operand)?;
677                Ok(InferType::Unknown)
678            }
679            Expr::Tuple(items) => {
680                for item in items {
681                    self.infer_expr(item)?;
682                }
683                Ok(InferType::Unknown)
684            }
685            Expr::ManifestOf { zone } => {
686                self.infer_expr(zone)?;
687                Ok(InferType::Unknown)
688            }
689            Expr::ChunkAt { index, zone } => {
690                self.infer_expr(index)?;
691                self.infer_expr(zone)?;
692                Ok(InferType::Unknown)
693            }
694            Expr::Dom(query) => {
695                if let Some(selector) = query.selector() {
696                    self.infer_expr(selector)?;
697                }
698                Ok(InferType::Unknown)
699            }
700            Expr::Escape { .. } | Expr::View(_) => Ok(InferType::Unknown),
701        }
702    }
703
704    /// Infer a binary operation's result type.
705    fn infer_binary_op(
706        &mut self,
707        op: BinaryOpKind,
708        left: &Expr,
709        right: &Expr,
710    ) -> Result<InferType, TypeError> {
711        match op {
712            BinaryOpKind::Eq
713            | BinaryOpKind::NotEq
714            | BinaryOpKind::Lt
715            | BinaryOpKind::Gt
716            | BinaryOpKind::LtEq
717            | BinaryOpKind::GtEq
718            | BinaryOpKind::ApproxEq => {
719                self.infer_expr(left)?;
720                self.infer_expr(right)?;
721                Ok(InferType::Bool)
722            }
723
724            // And/Or: type-aware — integer operands → Int (bitwise), else → Bool (logical)
725            BinaryOpKind::And | BinaryOpKind::Or => {
726                let lt = self.infer_expr(left)?;
727                self.infer_expr(right)?;
728                if lt == InferType::Int {
729                    Ok(InferType::Int)
730                } else {
731                    Ok(InferType::Bool)
732                }
733            }
734
735            BinaryOpKind::Concat => {
736                self.infer_expr(left)?;
737                self.infer_expr(right)?;
738                Ok(InferType::String)
739            }
740
741            // `a followed by b` — result is a sequence of the same type as the operands.
742            BinaryOpKind::SeqConcat => {
743                self.infer_expr(right)?;
744                self.infer_expr(left)
745            }
746
747            BinaryOpKind::BitXor
748            | BinaryOpKind::BitAnd
749            | BinaryOpKind::BitOr
750            | BinaryOpKind::Shl
751            | BinaryOpKind::Shr => {
752                self.infer_expr(left)?;
753                self.infer_expr(right)?;
754                Ok(InferType::Int)
755            }
756
757            BinaryOpKind::Add => {
758                let lt = self.infer_expr(left)?;
759                let rt = self.infer_expr(right)?;
760                if lt == InferType::String || rt == InferType::String {
761                    Ok(InferType::String)
762                } else if lt == InferType::Unknown || rt == InferType::Unknown {
763                    Ok(InferType::Unknown)
764                } else {
765                    unify_numeric(&lt, &rt).or(Ok(InferType::Unknown))
766                }
767            }
768
769            // Exact division always yields a Rational (`7 / 2 → 7/2`); the resolve pass
770            // only emits it in a Rational-typed context.
771            BinaryOpKind::ExactDivide => {
772                self.infer_expr(left)?;
773                self.infer_expr(right)?;
774                Ok(InferType::Rational)
775            }
776
777            BinaryOpKind::Subtract
778            | BinaryOpKind::Multiply
779            | BinaryOpKind::Divide
780            | BinaryOpKind::FloorDivide
781            | BinaryOpKind::Modulo
782            | BinaryOpKind::Pow => {
783                let lt = self.infer_expr(left)?;
784                let rt = self.infer_expr(right)?;
785                if lt == InferType::Unknown || rt == InferType::Unknown {
786                    Ok(InferType::Unknown)
787                } else {
788                    unify_numeric(&lt, &rt).or(Ok(InferType::Unknown))
789                }
790            }
791        }
792    }
793
794    /// Infer a named function call.
795    ///
796    /// For generic functions, instantiates the `TypeScheme` with fresh type variables,
797    /// then unifies the instantiated parameter types with the argument types. The
798    /// instantiated return type is then resolved and returned as the call result type.
799    fn infer_call(
800        &mut self,
801        function: Symbol,
802        args: &[&Expr],
803        site: Site,
804    ) -> Result<InferType, TypeError> {
805        let name = self.interner.resolve(function);
806        match name {
807            "pow"
808                if self
809                    .functions
810                    .get(&function)
811                    .map_or(true, |rec| rec.is_native) =>
812            {
813                let arg_types = args
814                    .iter()
815                    .map(|arg| self.infer_expr(arg))
816                    .collect::<Result<Vec<_>, _>>()?;
817                Ok(match arg_types.as_slice() {
818                    [base, exponent] => {
819                        let base = self.table.resolve(base);
820                        let exponent = self.table.resolve(exponent);
821                        if base == InferType::Unknown || exponent == InferType::Unknown {
822                            InferType::Unknown
823                        } else {
824                            unify_numeric(&base, &exponent).unwrap_or(InferType::Unknown)
825                        }
826                    }
827                    _ => InferType::Unknown,
828                })
829            }
830            // `readReals(path)`: the file's numbers, a `Seq of Real`.
831            "readReals" => {
832                for arg in args {
833                    self.infer_expr(arg)?;
834                }
835                Ok(InferType::Seq(Box::new(InferType::Float)))
836            }
837            "sqrt" | "parseFloat" | "parseInt" | "floor" | "ceil" | "round" | "abs" | "min"
838            | "max" => {
839                // A built-in's arguments are expressions like any other: a generic call among them
840                // is solved here too.
841                let mut arg_types = Vec::with_capacity(args.len());
842                for arg in args {
843                    arg_types.push(self.infer_expr(arg)?);
844                }
845                Ok(match name {
846                    "sqrt" | "parseFloat" => InferType::Float,
847                    "parseInt" | "floor" | "ceil" | "round" => InferType::Int,
848                    _ => arg_types.into_iter().next().unwrap_or(InferType::Unknown),
849                })
850            }
851            // `{k: v, …}` is `mapOf(k, v, …)` in flat pairs and `{a, …}` is `setOf(a, …)`: a Map
852            // of the first pair's key and value types, a Set of the first element's type, each
853            // later pair or element joined to the first as a list literal's elements are.
854            "mapOf" | "setOf" if !args.is_empty() && !self.functions.contains_key(&function) => {
855                let mut arg_types = Vec::with_capacity(args.len());
856                for arg in args {
857                    arg_types.push(self.infer_expr(arg)?);
858                }
859                let stride = if name == "mapOf" { 2 } else { 1 };
860                for (at, ty) in arg_types.iter().enumerate().skip(stride) {
861                    self.table.unify(&arg_types[at % stride], ty).ok();
862                }
863                Ok(match name {
864                    "mapOf" if arg_types.len() >= 2 => InferType::Map(
865                        Box::new(arg_types[0].clone()),
866                        Box::new(arg_types[1].clone()),
867                    ),
868                    "mapOf" => InferType::Unknown,
869                    _ => InferType::Set(Box::new(arg_types[0].clone())),
870                })
871            }
872            _ => {
873                if let Some(rec) = self.functions.get(&function).cloned() {
874                    // Instantiate the scheme: each call site gets fresh type variables
875                    // for generic params so calls don't interfere with each other.
876                    let (instantiated, type_args) =
877                        self.table.instantiate_with(&rec.scheme, &rec.declared);
878                    let generic = !type_args.is_empty();
879                    if generic {
880                        self.sites.calls.insert(
881                            site,
882                            CallInstance {
883                                type_args,
884                                precise: true,
885                            },
886                        );
887                    }
888
889                    if let InferType::Function(param_types, ret_box) = instantiated {
890                        // Arity is checked BEFORE unification, because `zip` stops at the shorter
891                        // side: a call with too few or too many arguments used to type-check
892                        // cleanly against the arguments it did have, so `ArityMismatch` was
893                        // unreachable from source and `add(1)` reached the runtime.
894                        if args.len() != param_types.len() {
895                            return Err(TypeError::ArityMismatch {
896                                expected: param_types.len(),
897                                found: args.len(),
898                            });
899                        }
900                        // Unify each argument type with the instantiated parameter type
901                        let mut arg_types = Vec::with_capacity(args.len());
902                        for (arg, param_ty) in args.iter().zip(param_types.iter()) {
903                            arg_types.push(self.check_widening(arg, param_ty)?);
904                        }
905                        if generic {
906                            self.call_arg_types.insert(site, arg_types);
907                        }
908                        // RESOLVED, not zonked: a result still open (a generic call inside a
909                        // generic body) keeps its variable, so the enclosing call can solve it.
910                        Ok(self.table.resolve(&ret_box))
911                    } else {
912                        // Should not happen, but fall back gracefully
913                        Ok(InferType::Unknown)
914                    }
915                } else {
916                    Ok(InferType::Unknown)
917                }
918            }
919        }
920    }
921
922    /// Check `value` flowing into a slot of type `expected` — a call's parameter, a variant's
923    /// field.
924    ///
925    /// ★ AN INT VALUE WIDENS TO A `Real` SLOT — `scaleHalf(5)` into `(x: Real)`, the coercion
926    /// LOGOS performs everywhere and the one
927    /// `parity_stdlib_aot_rust::int_literal_to_real_param_coerces_on_aot_rust` specifies. The
928    /// unifier has no `(Int, Float)` arm, and deliberately should not: making them unify
929    /// SYMMETRICALLY would also accept a Real where an Int is wanted, which is a real mistake the
930    /// checker has to keep catching.
931    ///
932    /// So it is handled HERE, directionally, and keyed on EACH SLOT'S OWN TYPE rather than on the
933    /// call — `mix(1, 2)` into `(a: Int) and (b: Real)` must widen the second argument and leave
934    /// the first an i64, because coercing it would emit `(2) as f64` where an i64 is wanted.
935    fn check_widening(
936        &mut self,
937        value: &Expr,
938        expected: &InferType,
939    ) -> Result<InferType, TypeError> {
940        let value_ty = self.infer_expr(value)?;
941        let widens = matches!(
942            self.table.resolve(&value_ty),
943            InferType::Int | InferType::Nat
944        ) && matches!(self.table.resolve(expected), InferType::Float);
945        if !widens {
946            self.table.unify(&value_ty, expected)?;
947        }
948        Ok(value_ty)
949    }
950
951    /// Infer a call-expression (calling a closure/function-value).
952    fn infer_call_expr(&mut self, callee: &Expr, args: &[&Expr]) -> Result<InferType, TypeError> {
953        let callee_ty = self.infer_expr(callee)?;
954        let ret_var = self.table.fresh();
955        let arg_types: Vec<InferType> = args
956            .iter()
957            .map(|a| self.infer_expr(a))
958            .collect::<Result<_, _>>()?;
959        let fn_ty = InferType::Function(arg_types, Box::new(ret_var.clone()));
960
961        let walked = self.table.resolve(&callee_ty);
962        match walked {
963            InferType::Unknown => Ok(ret_var),
964            InferType::Function(_, _) => {
965                self.table.unify(&walked, &fn_ty)?;
966                Ok(ret_var)
967            }
968            InferType::Var(_) => {
969                self.table.unify(&walked, &fn_ty)?;
970                Ok(ret_var)
971            }
972            other => Err(TypeError::NotAFunction { found: other }),
973        }
974    }
975
976    /// Infer a closure literal.
977    fn infer_closure(
978        &mut self,
979        params: &[(Symbol, &crate::ast::stmt::TypeExpr)],
980        body: &crate::ast::stmt::ClosureBody,
981        return_type: &Option<&crate::ast::stmt::TypeExpr>,
982    ) -> Result<InferType, TypeError> {
983        let param_types: Vec<InferType> = params
984            .iter()
985            .map(|(_, ty_expr)| self.written_type(ty_expr))
986            .collect();
987
988        let ret_type = if let Some(rt) = return_type {
989            self.written_type(rt)
990        } else {
991            self.table.fresh()
992        };
993
994        self.push_scope();
995        for ((sym, _), ty) in params.iter().zip(param_types.iter()) {
996            self.bind_var(*sym, ty.clone());
997        }
998
999        let prev_return = self.current_return_type.take();
1000        self.current_return_type = Some(ret_type.clone());
1001
1002        match body {
1003            crate::ast::stmt::ClosureBody::Expression(expr) => {
1004                let body_ty = self.infer_expr(expr)?;
1005                // Best-effort unification: won't fail compilation on ambiguity
1006                self.table.unify(&body_ty, &ret_type).ok();
1007            }
1008            crate::ast::stmt::ClosureBody::Block(stmts) => {
1009                // Expression inference speaks plain `TypeError`, so a finding inside a closure's
1010                // block is named from the statement that holds the closure outward.
1011                for stmt in *stmts {
1012                    self.infer_stmt(stmt).map_err(|traced| traced.error)?;
1013                }
1014            }
1015        }
1016
1017        self.current_return_type = prev_return;
1018        self.pop_scope();
1019
1020        Ok(InferType::Function(param_types, Box::new(ret_type)))
1021    }
1022
1023    /// Infer the type of a field access on a struct.
1024    fn infer_field_access(&self, obj_ty: InferType, field: Symbol) -> Result<InferType, TypeError> {
1025        let resolved = self.table.resolve(&obj_ty);
1026        match &resolved {
1027            InferType::UserDefined(type_sym, args) => {
1028                if let Some(TypeDef::Struct {
1029                    fields, generics, ..
1030                }) = self.registry.get(*type_sym)
1031                {
1032                    if let Some(field_def) = fields.iter().find(|f| f.name == field) {
1033                        // A bare reference to a generic record reads its parameters as unknown.
1034                        let args: Vec<InferType> = if args.len() == generics.len() {
1035                            args.clone()
1036                        } else {
1037                            generics.iter().map(|_| InferType::Unknown).collect()
1038                        };
1039                        Ok(self.field_type_at(&field_def.ty, generics, &args))
1040                    } else {
1041                        Err(TypeError::FieldNotFound {
1042                            type_name: *type_sym,
1043                            field_name: field,
1044                        })
1045                    }
1046                } else {
1047                    // Not a struct in registry → Unknown (defensive)
1048                    Ok(InferType::Unknown)
1049                }
1050            }
1051            // Can't resolve field on non-struct type
1052            _ => Ok(InferType::Unknown),
1053        }
1054    }
1055}
1056
1057// ============================================================================
1058// Statement inference
1059// ============================================================================
1060
1061/// A type error on its way out of the statements it was found in, naming each
1062/// one as it passes, innermost first. The trail lives in the error itself, so
1063/// an error some caller recovers from takes its trail with it.
1064#[derive(Debug)]
1065struct Traced {
1066    error: TypeError,
1067    trail: Vec<StmtId>,
1068}
1069
1070impl From<TypeError> for Traced {
1071    fn from(error: TypeError) -> Self {
1072        Traced {
1073            error,
1074            trail: Vec::new(),
1075        }
1076    }
1077}
1078
1079impl<'r> CheckEnv<'r> {
1080    fn infer_stmt(&mut self, stmt: &Stmt) -> Result<(), Traced> {
1081        self.infer_stmt_kind(stmt).map_err(|mut traced| {
1082            traced.trail.push(StmtId::of(stmt));
1083            traced
1084        })
1085    }
1086
1087    fn infer_stmt_kind(&mut self, stmt: &Stmt) -> Result<(), Traced> {
1088        match stmt {
1089            Stmt::Let { var, ty, value, .. } => {
1090                let final_ty = if let Some(type_expr) = ty {
1091                    let annotated = self.written_type(type_expr);
1092                    if annotated != InferType::Unknown {
1093                        // Checking mode: value must be compatible with annotation
1094                        self.check_expr(value, &annotated)?
1095                    } else {
1096                        self.infer_expr(value)?
1097                    }
1098                } else {
1099                    self.infer_expr(value)?
1100                };
1101                self.bind_var(*var, final_ty);
1102                Ok(())
1103            }
1104
1105            // What a lent place holds while the call holds its value keeps the place's type.
1106            Stmt::Set { value, .. } | Stmt::SetIndex { value, .. } | Stmt::SetField { value, .. }
1107                if crate::optimize::facts::holds_expr(crate::optimize::facts::Fact::Vacated, value) =>
1108            {
1109                Ok(())
1110            }
1111
1112            Stmt::Set { target, value } => {
1113                let inferred = self.infer_expr(value)?;
1114                // If target already has a type, unify. Otherwise just bind.
1115                if let Some(existing) = self.lookup_var(*target) {
1116                    if existing != InferType::Unknown {
1117                        self.table.unify(&inferred, &existing).ok();
1118                    }
1119                }
1120                // Update binding
1121                let resolved = self.table.resolve(&inferred);
1122                if resolved != InferType::Unknown {
1123                    self.bind_var(*target, resolved);
1124                }
1125                Ok(())
1126            }
1127
1128            Stmt::FunctionDef {
1129                name,
1130                generics,
1131                params,
1132                body,
1133                return_type,
1134                is_native,
1135                ..
1136            } => {
1137                // Build a type-param map: Symbol("T") → TyVar
1138                // Re-use the TyVars already allocated in preregister_functions if present,
1139                // or allocate fresh ones if this function was not pre-registered.
1140                let type_param_map: HashMap<Symbol, TyVar> = {
1141                    // Try to recover the same TyVars from the pre-registered scheme
1142                    let existing_vars: Vec<TyVar> = self.functions
1143                        .get(name)
1144                        .map(|rec| rec.scheme.vars.clone())
1145                        .unwrap_or_default();
1146                    if existing_vars.len() == generics.len() {
1147                        generics.iter().copied().zip(existing_vars).collect()
1148                    } else {
1149                        generics.iter().map(|&sym| (sym, self.table.fresh_var())).collect()
1150                    }
1151                };
1152
1153                let in_scope: HashMap<Symbol, InferType> =
1154                    type_param_map.iter().map(|(s, tv)| (*s, InferType::Var(*tv))).collect();
1155                let param_types: Vec<InferType> = params
1156                    .iter()
1157                    .map(|(_, ty_expr)| self.written_type_with(ty_expr, &in_scope))
1158                    .collect();
1159                let param_names: Vec<Symbol> = params.iter().map(|(sym, _)| *sym).collect();
1160
1161                let ret_type = if let Some(rt) = return_type {
1162                    self.written_type_with(rt, &in_scope)
1163                } else if let Some(rec) = self.functions.get(name) {
1164                    // Recover pre-registered return type from the scheme body
1165                    if let InferType::Function(_, ret_box) = &rec.scheme.body {
1166                        *ret_box.clone()
1167                    } else {
1168                        self.table.fresh()
1169                    }
1170                } else {
1171                    self.table.fresh()
1172                };
1173
1174                let generic_vars: Vec<TyVar> = generics
1175                    .iter()
1176                    .filter_map(|sym| type_param_map.get(sym).copied())
1177                    .collect();
1178                if !generic_vars.is_empty() {
1179                    self.sites.type_params.insert(
1180                        *name,
1181                        generics.iter().map(|g| (*g, InferType::Var(type_param_map[g]))).collect(),
1182                    );
1183                }
1184
1185                // Native functions: register scheme, no body to check
1186                if *is_native {
1187                    let declared = generic_vars.iter().map(|tv| InferType::Var(*tv)).collect();
1188                    let scheme = TypeScheme {
1189                        vars: generic_vars,
1190                        body: InferType::Function(param_types, Box::new(ret_type)),
1191                    };
1192                    self.functions.insert(*name, FunctionRecord { param_names, scheme, declared, is_native: *is_native });
1193                    return Ok(());
1194                }
1195
1196                // Save previous return context
1197                let prev_return_type = self.current_return_type.take();
1198                self.current_return_type = Some(ret_type.clone());
1199                let prev_type_params = std::mem::replace(&mut self.type_params_in_scope, in_scope);
1200
1201                // Check body in a new scope with params bound
1202                self.push_scope();
1203                for (sym, ty) in param_names.iter().zip(param_types.iter()) {
1204                    self.bind_var(*sym, ty.clone());
1205                }
1206                let checked = body.iter().try_for_each(|s| self.infer_stmt(s));
1207                self.pop_scope();
1208
1209                self.type_params_in_scope = prev_type_params;
1210                self.current_return_type = prev_return_type;
1211                checked?;
1212
1213                // After checking the body, update the registered scheme with resolved types.
1214                // Use `resolve` (not `zonk`) so generic TyVars remain as `Var(tv)` in
1215                // the scheme body — they will be instantiated fresh at each call site.
1216                let resolved_params: Vec<InferType> = param_types
1217                    .iter()
1218                    .map(|ty| self.table.resolve(ty))
1219                    .collect();
1220                let resolved_ret = self.table.resolve(&ret_type);
1221
1222                // Generalize over EVERY free type variable in the resolved
1223                // signature, not just the declared generics: a function with an
1224                // INFERRED (unannotated) return type allocates a fresh return
1225                // variable that is genuinely polymorphic but absent from
1226                // `generic_vars`. Leaving it free would share it across call
1227                // sites (cross-call contamination); adding it to `vars` makes
1228                // `instantiate` freshen it per call.
1229                fn collect_type_vars(ty: &InferType, acc: &mut Vec<TyVar>) {
1230                    match ty {
1231                        InferType::Var(tv) => {
1232                            if !acc.contains(tv) {
1233                                acc.push(*tv);
1234                            }
1235                        }
1236                        InferType::Seq(i) | InferType::Set(i) | InferType::Option(i) => {
1237                            collect_type_vars(i, acc)
1238                        }
1239                        InferType::Map(k, v) => {
1240                            collect_type_vars(k, acc);
1241                            collect_type_vars(v, acc);
1242                        }
1243                        InferType::UserDefined(_, args) => {
1244                            for a in args {
1245                                collect_type_vars(a, acc);
1246                            }
1247                        }
1248                        InferType::Function(ps, r) => {
1249                            for p in ps {
1250                                collect_type_vars(p, acc);
1251                            }
1252                            collect_type_vars(r, acc);
1253                        }
1254                        _ => {}
1255                    }
1256                }
1257                // Generalize over the ROOTS the declared parameters resolved to: checking the body
1258                // may have bound a parameter's own variable to another (a recursive call unifies
1259                // it with that call's fresh variable), and a scheme quantifying the stale variable
1260                // would leave its body un-freshened at every later call.
1261                let declared: Vec<InferType> =
1262                    generic_vars.iter().map(|tv| self.table.resolve(&InferType::Var(*tv))).collect();
1263                let mut scheme_vars = Vec::new();
1264                for d in &declared {
1265                    collect_type_vars(d, &mut scheme_vars);
1266                }
1267                for p in &resolved_params {
1268                    collect_type_vars(p, &mut scheme_vars);
1269                }
1270                collect_type_vars(&resolved_ret, &mut scheme_vars);
1271                let scheme = TypeScheme {
1272                    vars: scheme_vars,
1273                    body: InferType::Function(resolved_params, Box::new(resolved_ret)),
1274                };
1275                self.functions.insert(*name, FunctionRecord { param_names, scheme, declared, is_native: *is_native });
1276                Ok(())
1277            }
1278
1279            Stmt::Return { value } => {
1280                let ty = match value {
1281                    Some(expr) => self.infer_expr(expr)?,
1282                    None => InferType::Unit,
1283                };
1284                if let Some(expected) = self.current_return_type.clone() {
1285                    // Hard check for explicit return type annotations
1286                    if expected != InferType::Unknown {
1287                        self.table.unify(&ty, &expected)?;
1288                    }
1289                }
1290                Ok(())
1291            }
1292
1293            Stmt::Repeat { pattern, iterable, body } => {
1294                let iterable_ty = self.infer_expr(iterable)?;
1295                let elem_ty = match self.table.resolve(&iterable_ty) {
1296                    InferType::Seq(inner) | InferType::Set(inner) => *inner,
1297                    // A Map yields (key, value) tuples per entry at runtime
1298                    // (semantics/collections.rs `iteration_snapshot`), NOT bare
1299                    // keys. InferType has no tuple type, so a single loop
1300                    // variable binds to Unknown — sound (it cannot drive a wrong
1301                    // specialization), unlike the bare key type `K`.
1302                    InferType::Map(_, _) => InferType::Unknown,
1303                    _ => InferType::Unknown,
1304                };
1305                match pattern {
1306                    Pattern::Identifier(sym) => self.bind_var(*sym, elem_ty),
1307                    Pattern::Tuple(syms) => {
1308                        for sym in syms {
1309                            self.bind_var(*sym, InferType::Unknown);
1310                        }
1311                    }
1312                }
1313                for s in *body {
1314                    self.infer_stmt(s)?;
1315                }
1316                Ok(())
1317            }
1318
1319            Stmt::If { then_block, else_block, .. } => {
1320                for s in *then_block {
1321                    self.infer_stmt(s)?;
1322                }
1323                if let Some(else_b) = else_block {
1324                    for s in *else_b {
1325                        self.infer_stmt(s)?;
1326                    }
1327                }
1328                Ok(())
1329            }
1330
1331            Stmt::While { body, .. } => {
1332                for s in *body {
1333                    self.infer_stmt(s)?;
1334                }
1335                Ok(())
1336            }
1337
1338            Stmt::Inspect { target, arms, .. } => {
1339                let target_ty = self.infer_expr(target)?;
1340                self.sites.scrutinees.insert(Site::of_stmt(stmt), target_ty.clone());
1341                for arm in arms {
1342                    self.push_scope();
1343                    self.infer_inspect_arm(arm, &target_ty)?;
1344                    self.pop_scope();
1345                }
1346                Ok(())
1347            }
1348
1349            Stmt::Zone { body, .. } => {
1350                for s in *body {
1351                    self.infer_stmt(s)?;
1352                }
1353                Ok(())
1354            }
1355
1356            Stmt::ReadFrom { var, .. } => {
1357                self.bind_var(*var, InferType::String);
1358                Ok(())
1359            }
1360
1361            Stmt::CreatePipe { var, element_type, .. } => {
1362                let elem = InferType::from_type_name(self.interner.resolve(*element_type));
1363                self.bind_var(*var, elem);
1364                Ok(())
1365            }
1366
1367            Stmt::ReceivePipe { var, pipe } => {
1368                // Pipe var was registered with its element type by CreatePipe
1369                let elem_ty = self.infer_expr(pipe)?;
1370                self.bind_var(*var, elem_ty);
1371                Ok(())
1372            }
1373
1374            Stmt::TryReceivePipe { var, pipe } => {
1375                let elem_ty = self.infer_expr(pipe)?;
1376                // TryReceivePipe yields Option of elem type
1377                self.bind_var(*var, InferType::Option(Box::new(elem_ty)));
1378                Ok(())
1379            }
1380
1381            Stmt::Pop { into: Some(var), collection } => {
1382                let coll_ty = self.infer_expr(collection)?;
1383                let elem_ty = match self.table.resolve(&coll_ty) {
1384                    InferType::Seq(inner) | InferType::Set(inner) => *inner,
1385                    _ => InferType::Unknown,
1386                };
1387                self.bind_var(*var, elem_ty);
1388                Ok(())
1389            }
1390
1391            Stmt::AwaitMessage { into, .. } => {
1392                self.bind_var(*into, InferType::Unknown);
1393                Ok(())
1394            }
1395
1396            Stmt::LaunchTaskWithHandle { handle, .. } => {
1397                self.bind_var(*handle, InferType::Unknown);
1398                Ok(())
1399            }
1400
1401            Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
1402                for s in *tasks {
1403                    self.infer_stmt(s)?;
1404                }
1405                Ok(())
1406            }
1407
1408            Stmt::Select { branches } => {
1409                for branch in branches {
1410                    match branch {
1411                        crate::ast::stmt::SelectBranch::Receive { var, pipe, body } => {
1412                            let elem_ty = self.infer_expr(pipe)?;
1413                            self.push_scope();
1414                            self.bind_var(*var, elem_ty);
1415                            for s in *body {
1416                                self.infer_stmt(s)?;
1417                            }
1418                            self.pop_scope();
1419                        }
1420                        crate::ast::stmt::SelectBranch::Timeout { body, .. } => {
1421                            for s in *body {
1422                                self.infer_stmt(s)?;
1423                            }
1424                        }
1425                    }
1426                }
1427                Ok(())
1428            }
1429
1430            // `Show x.` — the printed expression was never inferred, so ANY type error inside a
1431            // `Show` was invisible to the checker. That single gap accounted for most of the
1432            // ill-typed programs `largo check` used to accept: `Show totl.` (undefined),
1433            // `Show add(1).` (wrong arity), `Show double("abc").` (wrong argument type) all sat
1434            // inside a statement the checker skipped entirely.
1435            Stmt::Show { object, recipient } => {
1436                self.infer_expr(object)?;
1437                self.infer_expr(recipient)?;
1438                Ok(())
1439            }
1440
1441            // A call used as a statement rather than a value: `add(1).` must still check its
1442            // arguments and arity.
1443            Stmt::Call { function, args } => {
1444                let arg_refs: Vec<&Expr> = args.iter().copied().collect();
1445                self.infer_call(*function, &arg_refs, Site::of_stmt(stmt))?;
1446                Ok(())
1447            }
1448
1449            // `Push v to xs.` — the element type must match what the collection holds.
1450            Stmt::Push { value, collection } => {
1451                let value_ty = self.infer_expr(value)?;
1452                let coll_ty = self.infer_expr(collection)?;
1453                if let InferType::Seq(elem) = self.table.resolve(&coll_ty) {
1454                    self.table.unify(&value_ty, &elem)?;
1455                }
1456                Ok(())
1457            }
1458
1459
1460            // `Set p's x to v.` — the value must match the declared field type. Without this arm a
1461            // Text could be stored in an `Int` field and no tier ever complained.
1462            Stmt::SetField { object, field, value } => {
1463                let obj_ty = self.infer_expr(object)?;
1464                let value_ty = self.infer_expr(value)?;
1465                // `infer_field_access` also raises `FieldNotFound`, so assigning to a field the
1466                // struct does not have is caught here too, not just a type mismatch on one it has.
1467                let field_ty = self.infer_field_access(obj_ty, *field)?;
1468                self.table.unify(&value_ty, &field_ty)?;
1469                Ok(())
1470            }
1471
1472            // `Set item k of m to v.` — both the key and the value must match the collection.
1473            Stmt::SetIndex { collection, index, value } => {
1474                let coll_ty = self.infer_expr(collection)?;
1475                let index_ty = self.infer_expr(index)?;
1476                let value_ty = self.infer_expr(value)?;
1477                match self.table.resolve(&coll_ty) {
1478                    InferType::Map(key_ty, val_ty) => {
1479                        self.table.unify(&index_ty, &key_ty)?;
1480                        self.table.unify(&value_ty, &val_ty)?;
1481                    }
1482                    InferType::Seq(elem) => {
1483                        self.table.unify(&value_ty, &elem)?;
1484                    }
1485                    _ => {}
1486                }
1487                Ok(())
1488            }
1489
1490            // `Swap a and b.` — swapping two names requires them to hold the same type.
1491            Stmt::Swap { a, b } => {
1492                if let (Some(ta), Some(tb)) = (self.lookup_var(*a), self.lookup_var(*b)) {
1493                    self.table.unify(&ta, &tb)?;
1494                }
1495                Ok(())
1496            }
1497
1498            // `Pop from xs.` with no destination. The existing `Pop` arm only matched the form
1499            // that binds a name, so this one fell through the old wildcard — a gap the
1500            // exhaustiveness check surfaced the moment it was removed. Nothing is bound, but the
1501            // collection is still an expression worth inferring.
1502            Stmt::Pop { collection, into: None, .. } => {
1503                self.infer_expr(collection)?;
1504                Ok(())
1505            }
1506
1507            // EVERY REMAINING STATEMENT KIND, NAMED EXPLICITLY AND DELIBERATELY UNCHECKED.
1508            //
1509            // This match has NO WILDCARD, and that is the point. It used to end in `_ => Ok(())`,
1510            // which meant `Show`, `Push` and a statement-level call were silently skipped by the
1511            // type checker — the single biggest reason `largo check` accepted broken programs. A
1512            // wildcard cannot tell "this statement needs no checking" apart from "nobody has got
1513            // to this one yet", so it hid 62 statement kinds behind an answer that looked settled.
1514            //
1515            // Listing them by name costs one line per new variant and buys the property that
1516            // matters: a statement kind added to the language CANNOT silently skip type checking,
1517            // because this file stops compiling until someone classifies it. That is the same
1518            // discipline the op catalogs use, applied to the checker.
1519            //
1520            // These are not claimed to be type-safe — they are claimed to be UNCHECKED, on the
1521            // record. Most carry expressions that should eventually be inferred (the `Assert`
1522            // family, the CRDT operations, the IO and channel statements); the logic-mode
1523            // declarations (`Axiom`, `Theorem`, `Theory`, `ForAll`, `Definition`) genuinely have
1524            // nothing for this checker to constrain. Moving one out of this group is a Wave 2
1525            // task, and the ill-typed corpus in `type_checker_rejects_lock` says which ones pay.
1526
1527            Stmt::Add { .. } | Stmt::AdvanceTime { .. } | Stmt::AppendToSequence { .. } |
1528            Stmt::Assert { .. } | Stmt::AwaitTask { .. } | Stmt::Axiom(..) | Stmt::Break |
1529            Stmt::Check { .. } | Stmt::CloseChannel { .. } | Stmt::ComponentDef(..) |
1530            Stmt::ConnectTo { .. } | Stmt::DecreaseCrdt { .. } | Stmt::Definition(..) |
1531            Stmt::DirectiveDef { .. } | Stmt::During { .. } | Stmt::Escape { .. } | Stmt::Expect { .. } |
1532            Stmt::ExpectFail { .. } | Stmt::ExpectOutput { .. } | Stmt::Fetch { .. } | Stmt::ForAll { .. } |
1533            Stmt::Give { .. } | Stmt::GivenFetch { .. } | Stmt::GivenFile { .. } |
1534            Stmt::IncreaseCrdt { .. } | Stmt::JoinCrdt { .. } | Stmt::LaunchTask { .. } |
1535            Stmt::LetPeerAgent { .. } | Stmt::Listen { .. } | Stmt::MergeCrdt { .. } |
1536            Stmt::MiddlewareDef { .. } | Stmt::Mount { .. } | Stmt::Observe { .. } |
1537            Stmt::RedirectDef { .. } | Stmt::Remove { .. } | Stmt::Replay { .. } | Stmt::Require { .. } |
1538            Stmt::ResolveConflict { .. } | Stmt::Reversibly { .. } | Stmt::RouteDef { .. } |
1539            Stmt::RuntimeAssert { .. } | Stmt::Fail { .. } | Stmt::SendMessage { .. } | Stmt::SendPipe { .. } |
1540            Stmt::Serve { .. } | Stmt::ServeFetches | Stmt::Sleep { .. } | Stmt::Spawn { .. } |
1541            Stmt::Splice { .. } | Stmt::StopTask { .. } | Stmt::StreamMessage { .. } |
1542            Stmt::StructDef { .. } | Stmt::Sync { .. } | Stmt::TestDef { .. } | Stmt::Theorem(..) |
1543            Stmt::Theory(..) | Stmt::Trust { .. } | Stmt::TrySendPipe { .. } | Stmt::Ui(..) |
1544            Stmt::WriteFile { .. } |
1545            // An opaque failure-site marker: an id, no type to check or infer.
1546            Stmt::Site(_) => Ok(()),
1547        }
1548    }
1549
1550    /// Process a single Inspect match arm, binding variant field types — read at the inspected
1551    /// value's own type arguments when it has them (`When Just (v)` on a `Maybe of Int` binds an
1552    /// `Int`, and `When Some (v)` on an `Option of Text` a `Text`). A type parameter the value
1553    /// does not pin stays unknown.
1554    fn infer_inspect_arm(
1555        &mut self,
1556        arm: &crate::ast::stmt::MatchArm,
1557        target_ty: &InferType,
1558    ) -> Result<(), Traced> {
1559        let target = self.table.resolve(target_ty);
1560        let bound: Option<Vec<(Symbol, InferType)>> = arm.variant.map(|variant_sym| {
1561            if let InferType::Option(inner) = &target {
1562                // `Some (v)`: the one payload is the Option's element.
1563                return arm
1564                    .bindings
1565                    .iter()
1566                    .map(|(_, b)| (*b, (**inner).clone()))
1567                    .collect();
1568            }
1569            let applied = match &target {
1570                InferType::UserDefined(enum_sym, args) => match self.registry.get(*enum_sym) {
1571                    Some(TypeDef::Enum {
1572                        variants, generics, ..
1573                    }) => variants
1574                        .iter()
1575                        .find(|v| v.name == variant_sym)
1576                        .map(|v| (v.clone(), generics.clone(), args.clone())),
1577                    _ => None,
1578                },
1579                _ => None,
1580            };
1581            let (variant_def, generics, args) = match applied {
1582                Some(found) => found,
1583                None => match self.registry.find_variant(variant_sym) {
1584                    Some((enum_sym, v)) => {
1585                        let generics = match self.registry.get(enum_sym) {
1586                            Some(TypeDef::Enum { generics, .. }) => generics.clone(),
1587                            _ => Vec::new(),
1588                        };
1589                        (v.clone(), generics, Vec::new())
1590                    }
1591                    None => {
1592                        return arm
1593                            .bindings
1594                            .iter()
1595                            .map(|(_, b)| (*b, InferType::Unknown))
1596                            .collect();
1597                    }
1598                },
1599            };
1600            let args: Vec<InferType> = if args.len() == generics.len() {
1601                args
1602            } else {
1603                generics.iter().map(|_| InferType::Unknown).collect()
1604            };
1605            arm.bindings
1606                .iter()
1607                .map(|(field_sym, binding_sym)| {
1608                    let ty = variant_def
1609                        .fields
1610                        .iter()
1611                        .find(|f| f.name == *field_sym)
1612                        .map(|f| self.field_type_at(&f.ty, &generics, &args))
1613                        .unwrap_or(InferType::Unknown);
1614                    (*binding_sym, ty)
1615                })
1616                .collect()
1617        });
1618        match bound {
1619            Some(bindings) => {
1620                for (binding_sym, ty) in bindings {
1621                    self.bind_var(binding_sym, ty);
1622                }
1623            }
1624            // Otherwise arm: wildcard bindings
1625            None => {
1626                for (_, binding_sym) in &arm.bindings {
1627                    self.bind_var(*binding_sym, InferType::Unknown);
1628                }
1629            }
1630        }
1631
1632        for s in arm.body {
1633            self.infer_stmt(s)?;
1634        }
1635        Ok(())
1636    }
1637}
1638
1639// ============================================================================
1640// Entry point
1641// ============================================================================
1642
1643/// One typechecker finding with the top-level statement it belongs to.
1644///
1645/// `stmt_index` maps 1:1 onto `Parser::stmt_spans()`, giving IDE diagnostics
1646/// a real source span; `trail` names the statements the finding propagated
1647/// out through, innermost first, so a finding inside a function body or a loop
1648/// resolves through `Parser::nested_stmt_spans()` to the statement at fault.
1649#[derive(Debug)]
1650pub struct IndexedTypeError {
1651    pub stmt_index: Option<usize>,
1652    pub trail: Vec<StmtId>,
1653    pub error: TypeError,
1654}
1655
1656/// Collect EVERY failing top-level statement instead of bailing at the first.
1657///
1658/// The environment after a failed statement is best-effort: inference simply
1659/// continues with whatever bindings succeeded, so one bad `Let` does not
1660/// cascade into errors on unrelated later statements. The strict fail-fast
1661/// contract lives in [`check_program_located`], which every compile path uses.
1662pub fn check_program_collect(
1663    stmts: &[Stmt],
1664    interner: &Interner,
1665    registry: &TypeRegistry,
1666) -> (TypeEnv, Vec<IndexedTypeError>) {
1667    let mut errors = Vec::new();
1668
1669    if let Err(e) =
1670        crate::analysis::dimension_check::DimensionChecker::new(interner).check_program(stmts)
1671    {
1672        let owner = e.trail.last().copied();
1673        errors.push(IndexedTypeError {
1674            stmt_index: stmts.iter().position(|s| Some(StmtId::of(s)) == owner),
1675            trail: e.trail,
1676            error: TypeError::DimensionMismatch { message: e.message },
1677        });
1678    }
1679
1680    let mut env = CheckEnv::new(registry, interner);
1681    env.preregister_functions(stmts);
1682
1683    for (index, stmt) in stmts.iter().enumerate() {
1684        if let Err(Traced { error, trail }) = env.infer_stmt(stmt) {
1685            errors.push(IndexedTypeError {
1686                stmt_index: Some(index),
1687                trail,
1688                error,
1689            });
1690        }
1691    }
1692
1693    (env.into_type_env(), errors)
1694}
1695
1696/// Check `stmts` as far as each statement goes — a failing statement does not stop the rest — and
1697/// answer what every generic site was solved at. The input to monomorphization; a backend with
1698/// no generics of its own reads which instance each call and construction needs from here.
1699pub fn infer_instantiations(
1700    stmts: &[Stmt],
1701    interner: &Interner,
1702    registry: &TypeRegistry,
1703) -> Instantiations {
1704    let mut env = CheckEnv::new(registry, interner);
1705    env.preregister_functions(stmts);
1706    for stmt in stmts {
1707        let _ = env.infer_stmt(stmt);
1708    }
1709    env.into_instantiations()
1710}
1711
1712/// Check a LOGOS program and return a typed `TypeEnv` for codegen.
1713///
1714/// Replaces `TypeEnv::infer_program`. Returns `Err(TypeError)` only on
1715/// genuine type contradictions (e.g., `Let x: Int be "hello"`).
1716/// Ambiguous types fall back to `LogosType::Unknown` silently.
1717pub fn check_program(
1718    stmts: &[Stmt],
1719    interner: &Interner,
1720    registry: &TypeRegistry,
1721) -> Result<TypeEnv, TypeError> {
1722    check_program_located(stmts, interner, registry).map_err(|e| e.error)
1723}
1724
1725/// A type error and the top-level function it was found in — `None` for a `## Main` statement. A
1726/// checked program has no source spans left (lowering writes functions of its own), so the function
1727/// is the location a report can give.
1728#[derive(Debug, Clone)]
1729pub struct LocatedTypeError {
1730    pub error: TypeError,
1731    pub within: Option<Symbol>,
1732}
1733
1734impl LocatedTypeError {
1735    /// The user-facing error, naming where a mismatch was found: the function its author wrote, or
1736    /// the construct (`## Route GET /agent`, a component's action) a compiler-written function was
1737    /// lowered from, found among the declarations in `program`. A synthesized name is never shown.
1738    pub fn to_parse_error_kind(
1739        &self,
1740        interner: &Interner,
1741        program: &[Stmt],
1742    ) -> crate::error::ParseErrorKind {
1743        let mut kind = self.error.to_parse_error_kind(interner);
1744        if let (crate::error::ParseErrorKind::TypeMismatchDetailed { context, .. }, Some(f)) =
1745            (&mut kind, self.within)
1746        {
1747            if context.is_empty() {
1748                let name = interner.resolve(f);
1749                let place = if logicaffeine_language::parser::lgx_lower::is_compiler_written(name) {
1750                    logicaffeine_language::parser::lgx_lower::authored_construct(
1751                        name, program, interner,
1752                    )
1753                } else {
1754                    Some(format!("`{name}`"))
1755                };
1756                if let Some(place) = place {
1757                    *context = format!("in {place}");
1758                }
1759            }
1760        }
1761        kind
1762    }
1763}
1764
1765/// The first type the program names that nothing supplies, with where it is named: the index of the
1766/// top-level statement that names it, or `None` for a field of a declared record or variant (a
1767/// declaration is not a statement). A name is supplied by the registry (a record, enum or alias the
1768/// program declares or imports, a builtin, an intrinsic generic), by the language itself
1769/// (`codegen::types::is_language_type_name`, and the dimension words `Quantity of <Dimension>`
1770/// takes, `Dimension::by_name`), or as a type parameter the declaration itself introduces. Run on
1771/// the program the parser returned, whose top-level statements align with its statement spans, so a
1772/// statement's refusal is located. A written type counts wherever it stands: a construction, a
1773/// collection's element type, an annotation, a typed fetch, a function's parameters and return
1774/// type, a record's or variant's field types.
1775pub fn first_undeclared_type(
1776    stmts: &[Stmt],
1777    registry: &TypeRegistry,
1778    interner: &Interner,
1779) -> Option<(Option<usize>, Symbol)> {
1780    use crate::analysis::callgraph::{collect_type_refs_from_stmts, type_names_in_type_expr};
1781    use std::collections::HashSet;
1782    let supplied = |sym: Symbol, own_params: &HashSet<Symbol>| {
1783        let name = interner.resolve(sym);
1784        own_params.contains(&sym)
1785            || registry.get(sym).is_some()
1786            || crate::codegen::types::is_language_type_name(name)
1787            || logicaffeine_base::dimension::Dimension::by_name(name).is_some()
1788    };
1789    let first_of = |named: HashSet<Symbol>, own_params: &HashSet<Symbol>| {
1790        let mut undeclared: Vec<Symbol> = named
1791            .into_iter()
1792            .filter(|sym| !supplied(*sym, own_params))
1793            .collect();
1794        undeclared.sort_by(|a, b| interner.resolve(*a).cmp(interner.resolve(*b)));
1795        undeclared.first().copied()
1796    };
1797    for (index, stmt) in stmts.iter().enumerate() {
1798        let mut named: HashSet<Symbol> = HashSet::new();
1799        let mut own_params: HashSet<Symbol> = HashSet::new();
1800        match stmt {
1801            Stmt::FunctionDef {
1802                generics,
1803                params,
1804                return_type,
1805                body,
1806                ..
1807            } => {
1808                own_params.extend(generics.iter().copied());
1809                for (_, ty) in params {
1810                    type_names_in_type_expr(ty, &mut named);
1811                }
1812                if let Some(ty) = return_type {
1813                    type_names_in_type_expr(ty, &mut named);
1814                }
1815                collect_type_refs_from_stmts(body, &mut named);
1816            }
1817            other => collect_type_refs_from_stmts(std::slice::from_ref(other), &mut named),
1818        }
1819        if let Some(first) = first_of(named, &own_params) {
1820            return Some((Some(index), first));
1821        }
1822    }
1823    let mut declared: Vec<(Symbol, &TypeDef)> = registry
1824        .iter_types()
1825        .map(|(sym, def)| (*sym, def))
1826        .collect();
1827    declared.sort_by(|a, b| interner.resolve(a.0).cmp(interner.resolve(b.0)));
1828    for (_, def) in declared {
1829        let (fields, generics): (Vec<&FieldType>, &Vec<Symbol>) = match def {
1830            TypeDef::Struct {
1831                fields, generics, ..
1832            } => (fields.iter().map(|f| &f.ty).collect(), generics),
1833            TypeDef::Enum {
1834                variants, generics, ..
1835            } => (
1836                variants
1837                    .iter()
1838                    .flat_map(|v| v.fields.iter().map(|f| &f.ty))
1839                    .collect(),
1840                generics,
1841            ),
1842            _ => continue,
1843        };
1844        let mut named: HashSet<Symbol> = HashSet::new();
1845        for ty in fields {
1846            written_type_names(ty, &mut named);
1847        }
1848        let own_params: HashSet<Symbol> = generics.iter().copied().collect();
1849        if let Some(first) = first_of(named, &own_params) {
1850            return Some((None, first));
1851        }
1852    }
1853    None
1854}
1855
1856/// The type names a declared field's type WRITES: every named type and generic head, never a
1857/// `Primitive` — those are the language's own scalars, or discovery's marker for a field whose type it
1858/// could not read, which names nothing the program wrote.
1859fn written_type_names(ty: &FieldType, names: &mut std::collections::HashSet<Symbol>) {
1860    match ty {
1861        FieldType::Named(sym) => {
1862            names.insert(*sym);
1863        }
1864        FieldType::Generic { base, params } => {
1865            names.insert(*base);
1866            for p in params {
1867                written_type_names(p, names);
1868            }
1869        }
1870        FieldType::Tuple(items) => {
1871            for t in items {
1872                written_type_names(t, names);
1873            }
1874        }
1875        FieldType::Record(fields) => {
1876            for (_, t) in fields {
1877                written_type_names(t, names);
1878            }
1879        }
1880        FieldType::Primitive(_) | FieldType::TypeParam(_) => {}
1881    }
1882}
1883
1884/// [`check_program`], reporting which top-level function a failure is in.
1885pub fn check_program_located(
1886    stmts: &[Stmt],
1887    interner: &Interner,
1888    registry: &TypeRegistry,
1889) -> Result<TypeEnv, LocatedTypeError> {
1890    // Dimension coherence is a type property: reject `2 meters + 1 gram` here, statically, before
1891    // any code is generated (a length and a mass have no common dimension).
1892    crate::analysis::dimension_check::DimensionChecker::new(interner)
1893        .check_program(stmts)
1894        .map_err(|e| LocatedTypeError {
1895            error: TypeError::DimensionMismatch { message: e.message },
1896            within: None,
1897        })?;
1898
1899    Ok(checked(stmts, interner, registry)?.into_type_env())
1900}
1901
1902/// The type of every binding the program's ROOT declares, as the checker settled it once the whole
1903/// program was read. Exact where [`TypeEnv`] is not: its variables are one flat map, so a function's
1904/// own `x` and the program's `x` share an entry there.
1905pub fn root_binding_types(
1906    stmts: &[Stmt],
1907    interner: &Interner,
1908    registry: &TypeRegistry,
1909) -> Result<HashMap<Symbol, InferType>, LocatedTypeError> {
1910    let env = checked(stmts, interner, registry)?;
1911    let root = env.scopes.first().cloned().unwrap_or_default();
1912    Ok(root
1913        .into_iter()
1914        .map(|(name, ty)| (name, env.table.zonk(&ty)))
1915        .collect())
1916}
1917
1918/// The environment after checking every top-level statement: function signatures registered first,
1919/// for forward references, then each statement in order.
1920fn checked<'r>(
1921    stmts: &[Stmt],
1922    interner: &'r Interner,
1923    registry: &'r TypeRegistry,
1924) -> Result<CheckEnv<'r>, LocatedTypeError> {
1925    let mut env = CheckEnv::new(registry, interner);
1926    env.preregister_functions(stmts);
1927    for stmt in stmts {
1928        if let Err(Traced { error, .. }) = env.infer_stmt(stmt) {
1929            let within = match stmt {
1930                Stmt::FunctionDef { name, .. } => Some(*name),
1931                _ => None,
1932            };
1933            return Err(LocatedTypeError { error, within });
1934        }
1935    }
1936    Ok(env)
1937}
1938
1939// ============================================================================
1940// Tests
1941// ============================================================================
1942
1943#[cfg(test)]
1944#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/analysis/check/tests.rs"]
1945mod tests;