Skip to main content

logicaffeine_compile/analysis/
unify.rs

1//! Unification engine for the bidirectional type checker.
2//!
3//! Provides Robinson unification for [`InferType`], which extends [`LogosType`]
4//! with type variables for the inference pass. After inference, [`UnificationTable::zonk`]
5//! converts `InferType → LogosType`. Unsolved variables become `LogosType::Unknown`,
6//! preserving the existing codegen safety net.
7//!
8//! # Architecture
9//!
10//! ```text
11//! InferType  ←  inference pass (this module + check.rs)
12//!     │
13//!     │  zonk (after inference)
14//!     ▼
15//! LogosType  →  codegen (unchanged)
16//! ```
17
18use std::collections::HashMap;
19
20use crate::analysis::{FieldType, LogosType, TypeDef, TypeRegistry};
21use crate::intern::{Interner, Symbol};
22
23// ============================================================================
24// Core types
25// ============================================================================
26
27/// A type variable used during inference.
28#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
29pub struct TyVar(pub u32);
30
31/// Inference-time type representation.
32///
33/// Extends [`LogosType`] with:
34/// - [`InferType::Var`] — an unbound type variable
35/// - [`InferType::Function`] — a function type (not needed in codegen)
36/// - [`InferType::Unknown`] — propagated uncertainty (unifies with anything)
37#[derive(Clone, PartialEq, Debug)]
38pub enum InferType {
39    // Ground types mirroring LogosType
40    Int,
41    Float,
42    Bool,
43    Char,
44    Byte,
45    String,
46    Unit,
47    Nat,
48    Rational,
49    Duration,
50    Date,
51    Moment,
52    Time,
53    Span,
54    /// A DOM element handle. Nominal: distinct from `Int` and from `Event`, even though
55    /// every tier represents it as an i64 handle at runtime.
56    Element,
57    /// A DOM event handle (the argument of an event handler). Nominal, like `Element`.
58    Event,
59    /// A view value (a template with its captured bindings). Nominal.
60    View,
61    Seq(Box<InferType>),
62    Map(Box<InferType>, Box<InferType>),
63    Set(Box<InferType>),
64    Option(Box<InferType>),
65    /// A user struct or enum, applied to its type arguments (`Box of Int` is `UserDefined(Box,
66    /// [Int])`; a type with no parameters has none). An EMPTY argument list also stands for a bare
67    /// reference to a generic type whose arguments were not written, and unifies with any
68    /// application of it.
69    UserDefined(Symbol, Vec<InferType>),
70    // Inference-only types
71    Var(TyVar),
72    Function(Vec<InferType>, Box<InferType>),
73    Unknown,
74}
75
76/// A type error detected during unification or checking.
77#[derive(Debug, Clone)]
78pub enum TypeError {
79    Mismatch {
80        expected: InferType,
81        found: InferType,
82    },
83    InfiniteType {
84        var: TyVar,
85        ty: InferType,
86    },
87    ArityMismatch {
88        expected: usize,
89        found: usize,
90    },
91    FieldNotFound {
92        type_name: Symbol,
93        field_name: Symbol,
94    },
95    NotAFunction {
96        found: InferType,
97    },
98    /// A call to a name that exists NOWHERE in the post-prelude program — not a
99    /// user function, not a builtin, not a bound variable, not a variant
100    /// constructor. Caught at check time by
101    /// [`crate::analysis::known_calls::check_unknown_calls`], with the same
102    /// message every runtime tier uses (`Unknown function: <name>`), or a
103    /// retired builtin's own refusal
104    /// ([`crate::semantics::builtins::retired_builtin`]).
105    UnknownFunction {
106        name: Symbol,
107    },
108    /// Dimension-incoherent quantity arithmetic (`2 meters + 1 gram`) caught statically by the
109    /// [`crate::analysis::dimension_check::DimensionChecker`]. Carries its own ready message.
110    DimensionMismatch {
111        message: std::string::String,
112    },
113}
114
115impl TypeError {
116    pub fn expected_str(&self) -> std::string::String {
117        match self {
118            TypeError::Mismatch { expected, .. } => expected.to_logos_name(),
119            TypeError::ArityMismatch { expected, .. } => format!("{} arguments", expected),
120            TypeError::FieldNotFound { .. } => "a known field".to_string(),
121            TypeError::NotAFunction { .. } => "a function".to_string(),
122            TypeError::UnknownFunction { .. } => "a defined function".to_string(),
123            TypeError::InfiniteType { .. } => "a finite type".to_string(),
124            TypeError::DimensionMismatch { .. } => "a matching dimension".to_string(),
125        }
126    }
127
128    pub fn found_str(&self) -> std::string::String {
129        match self {
130            TypeError::Mismatch { found, .. } => found.to_logos_name(),
131            TypeError::ArityMismatch { found, .. } => format!("{} arguments", found),
132            TypeError::FieldNotFound { field_name, .. } => format!("{:?}", field_name),
133            TypeError::NotAFunction { found } => found.to_logos_name(),
134            TypeError::UnknownFunction { name } => format!("{:?}", name),
135            TypeError::InfiniteType { ty, .. } => ty.to_logos_name(),
136            TypeError::DimensionMismatch { message } => message.clone(),
137        }
138    }
139
140    /// Convert this TypeError into a `ParseErrorKind` for user-facing reporting.
141    ///
142    /// Uses `interner` to resolve symbol names (field names, type names) into strings.
143    pub fn to_parse_error_kind(
144        &self,
145        interner: &crate::intern::Interner,
146    ) -> crate::error::ParseErrorKind {
147        use crate::error::ParseErrorKind;
148        match self {
149            TypeError::Mismatch { expected, found } => ParseErrorKind::TypeMismatchDetailed {
150                expected: expected.describe(interner),
151                found: found.describe(interner),
152                context: String::new(),
153            },
154            TypeError::InfiniteType { var, ty } => ParseErrorKind::InfiniteType {
155                var_description: format!("type variable α{}", var.0),
156                type_description: ty.describe(interner),
157            },
158            TypeError::ArityMismatch { expected, found } => ParseErrorKind::ArityMismatch {
159                function: String::from("function"),
160                expected: *expected,
161                found: *found,
162            },
163            TypeError::FieldNotFound {
164                type_name,
165                field_name,
166            } => ParseErrorKind::FieldNotFound {
167                type_name: interner.resolve(*type_name).to_string(),
168                field_name: interner.resolve(*field_name).to_string(),
169                available: vec![],
170            },
171            TypeError::NotAFunction { found } => ParseErrorKind::NotAFunction {
172                found_type: found.describe(interner),
173            },
174            TypeError::UnknownFunction { name } => {
175                let name = interner.resolve(*name);
176                ParseErrorKind::Custom(match crate::semantics::builtins::retired_builtin(name) {
177                    Some(refusal) => refusal.to_string(),
178                    None => format!("Unknown function: {}", name),
179                })
180            }
181            TypeError::DimensionMismatch { message } => ParseErrorKind::Custom(message.clone()),
182        }
183    }
184}
185
186// ============================================================================
187// Unification table
188// ============================================================================
189
190/// A quantified polymorphic type.
191///
192/// Stores a set of bound type variables and a body type that may reference them.
193/// Used for generic function signatures: `forall [T]. T -> T`.
194#[derive(Clone, Debug)]
195pub struct TypeScheme {
196    /// The bound type variables (one per generic type parameter).
197    pub vars: Vec<TyVar>,
198    /// The body type, which may contain `InferType::Var(tv)` for each `tv` in `vars`.
199    pub body: InferType,
200}
201
202/// Where the names in a written type are looked up while converting it: the program's registry
203/// (so a user struct or enum is a `UserDefined`, not `Unknown`) and the type parameters in scope,
204/// each standing for the type it is currently bound to.
205pub struct TypeScope<'s> {
206    pub interner: &'s Interner,
207    pub registry: Option<&'s TypeRegistry>,
208    pub params: &'s HashMap<Symbol, InferType>,
209    /// Each bare type name that IS a namespaced type (`Point` for `Geometry::Point`), so both
210    /// spellings read as one type (see `TypeRegistry::namespaced_twins`).
211    pub twins: Option<&'s HashMap<Symbol, Symbol>>,
212}
213
214impl TypeScope<'_> {
215    /// The one identity a user type named `name` has: its namespaced twin when the bare spelling
216    /// names one, else itself.
217    pub fn canonical(&self, name: Symbol) -> Symbol {
218        self.twins
219            .and_then(|t| t.get(&name))
220            .copied()
221            .unwrap_or(name)
222    }
223}
224
225/// Union-Find table implementing Robinson unification with occurs check.
226///
227/// Type variables are allocated by `fresh` and resolved by `find`.
228/// `zonk` fully resolves a type after inference, converting remaining
229/// unbound variables to [`InferType::Unknown`] (which maps to `LogosType::Unknown`).
230pub struct UnificationTable {
231    bindings: Vec<Option<InferType>>,
232    next_id: u32,
233}
234
235impl UnificationTable {
236    pub fn new() -> Self {
237        Self {
238            bindings: Vec::new(),
239            next_id: 0,
240        }
241    }
242
243    /// Allocate a fresh unbound type variable, returning the wrapped `InferType`.
244    pub fn fresh(&mut self) -> InferType {
245        let id = self.next_id;
246        self.next_id += 1;
247        self.bindings.push(None);
248        InferType::Var(TyVar(id))
249    }
250
251    /// Allocate a fresh unbound type variable, returning the raw `TyVar`.
252    pub fn fresh_var(&mut self) -> TyVar {
253        let id = self.next_id;
254        self.next_id += 1;
255        self.bindings.push(None);
256        TyVar(id)
257    }
258
259    /// Instantiate a `TypeScheme` by replacing each quantified variable with a fresh one.
260    ///
261    /// Each call site of a generic function gets independent fresh variables so that
262    /// two calls to `identity(42)` and `identity(true)` do not interfere.
263    pub fn instantiate(&mut self, scheme: &TypeScheme) -> InferType {
264        self.instantiate_with(scheme, &[]).0
265    }
266
267    /// [`Self::instantiate`], also carrying `also` through the same fresh variables — so a
268    /// function's declared type arguments come out as what THIS instantiation solves them to.
269    pub fn instantiate_with(
270        &mut self,
271        scheme: &TypeScheme,
272        also: &[InferType],
273    ) -> (InferType, Vec<InferType>) {
274        if scheme.vars.is_empty() {
275            return (scheme.body.clone(), also.to_vec());
276        }
277        let subst: HashMap<TyVar, TyVar> = scheme
278            .vars
279            .iter()
280            .map(|&old_tv| (old_tv, self.fresh_var()))
281            .collect();
282        let body = self.substitute_vars(&scheme.body, &subst);
283        let also = also
284            .iter()
285            .map(|t| self.substitute_vars(t, &subst))
286            .collect();
287        (body, also)
288    }
289
290    /// Substitute type variables according to `subst`, walking the type recursively.
291    fn substitute_vars(&self, ty: &InferType, subst: &HashMap<TyVar, TyVar>) -> InferType {
292        match ty {
293            InferType::Var(tv) => {
294                let resolved = self.find(*tv);
295                match &resolved {
296                    InferType::Var(rtv) => {
297                        if let Some(&new_tv) = subst.get(rtv) {
298                            InferType::Var(new_tv)
299                        } else {
300                            InferType::Var(*rtv)
301                        }
302                    }
303                    other => self.substitute_vars(&other.clone(), subst),
304                }
305            }
306            InferType::Seq(inner) => InferType::Seq(Box::new(self.substitute_vars(inner, subst))),
307            InferType::Map(k, v) => InferType::Map(
308                Box::new(self.substitute_vars(k, subst)),
309                Box::new(self.substitute_vars(v, subst)),
310            ),
311            InferType::Set(inner) => InferType::Set(Box::new(self.substitute_vars(inner, subst))),
312            InferType::Option(inner) => {
313                InferType::Option(Box::new(self.substitute_vars(inner, subst)))
314            }
315            InferType::UserDefined(sym, args) => InferType::UserDefined(
316                *sym,
317                args.iter()
318                    .map(|a| self.substitute_vars(a, subst))
319                    .collect(),
320            ),
321            InferType::Function(params, ret) => InferType::Function(
322                params
323                    .iter()
324                    .map(|p| self.substitute_vars(p, subst))
325                    .collect(),
326                Box::new(self.substitute_vars(ret, subst)),
327            ),
328            other => other.clone(),
329        }
330    }
331
332    /// Follow the binding chain for a type variable (iterative, no path compression).
333    pub fn find(&self, tv: TyVar) -> InferType {
334        let mut current = tv;
335        loop {
336            match &self.bindings[current.0 as usize] {
337                None => return InferType::Var(current),
338                Some(InferType::Var(tv2)) => current = *tv2,
339                Some(ty) => return ty.clone(),
340            }
341        }
342    }
343
344    /// Walk the top level of a type: if it's a bound variable, resolve one step.
345    fn walk(&self, ty: &InferType) -> InferType {
346        match ty {
347            InferType::Var(tv) => self.find(*tv),
348            other => other.clone(),
349        }
350    }
351
352    /// Resolve type variables, keeping unbound variables as `Var(tv)`.
353    ///
354    /// Unlike `zonk`, this does not convert unbound variables to `Unknown`.
355    /// Use this during inference to preserve generic type params as `Var(tv)`
356    /// so they can be unified at call sites.
357    pub fn resolve(&self, ty: &InferType) -> InferType {
358        match ty {
359            InferType::Var(tv) => {
360                let resolved = self.find(*tv);
361                match &resolved {
362                    InferType::Var(_) => resolved, // keep as Var — intentionally unbound
363                    other => self.resolve(&other.clone()),
364                }
365            }
366            InferType::Seq(inner) => InferType::Seq(Box::new(self.resolve(inner))),
367            InferType::Map(k, v) => {
368                InferType::Map(Box::new(self.resolve(k)), Box::new(self.resolve(v)))
369            }
370            InferType::Set(inner) => InferType::Set(Box::new(self.resolve(inner))),
371            InferType::Option(inner) => InferType::Option(Box::new(self.resolve(inner))),
372            InferType::UserDefined(sym, args) => {
373                InferType::UserDefined(*sym, args.iter().map(|a| self.resolve(a)).collect())
374            }
375            InferType::Function(params, ret) => {
376                let params = params.iter().map(|p| self.resolve(p)).collect();
377                InferType::Function(params, Box::new(self.resolve(ret)))
378            }
379            other => other.clone(),
380        }
381    }
382
383    /// Fully resolve all type variables in a type.
384    ///
385    /// Unbound variables become [`InferType::Unknown`], which maps to
386    /// `LogosType::Unknown` when converted by `to_logos_type`.
387    pub fn zonk(&self, ty: &InferType) -> InferType {
388        match ty {
389            InferType::Var(tv) => {
390                let resolved = self.find(*tv);
391                match &resolved {
392                    InferType::Var(_) => InferType::Unknown,
393                    other => self.zonk(other),
394                }
395            }
396            InferType::Seq(inner) => InferType::Seq(Box::new(self.zonk(inner))),
397            InferType::Map(k, v) => InferType::Map(Box::new(self.zonk(k)), Box::new(self.zonk(v))),
398            InferType::Set(inner) => InferType::Set(Box::new(self.zonk(inner))),
399            InferType::Option(inner) => InferType::Option(Box::new(self.zonk(inner))),
400            InferType::UserDefined(sym, args) => {
401                InferType::UserDefined(*sym, args.iter().map(|a| self.zonk(a)).collect())
402            }
403            InferType::Function(params, ret) => {
404                let params = params.iter().map(|p| self.zonk(p)).collect();
405                InferType::Function(params, Box::new(self.zonk(ret)))
406            }
407            other => other.clone(),
408        }
409    }
410
411    /// Zonk then convert to `LogosType`. Unsolved variables become `Unknown`.
412    pub fn to_logos_type(&self, ty: &InferType) -> LogosType {
413        let zonked = self.zonk(ty);
414        infer_to_logos(&zonked)
415    }
416
417    /// Unify what was written (`found`) with what its position promises (`expected`) — a
418    /// return type, a parameter, a field, an annotation, an element type — binding type
419    /// variables as needed. The order only names the sides of a mismatch, and every caller
420    /// passes the value's type first.
421    ///
422    /// Returns `Ok(())` if unification succeeds (bindings may be updated).
423    /// Returns `Err(TypeError)` on a genuine type contradiction.
424    pub fn unify(&mut self, found: &InferType, expected: &InferType) -> Result<(), TypeError> {
425        let found = self.walk(found);
426        let expected = self.walk(expected);
427        self.unify_walked(&found, &expected)
428    }
429
430    fn unify_walked(&mut self, a: &InferType, b: &InferType) -> Result<(), TypeError> {
431        match (a, b) {
432            // Unknown unifies with anything (propagated uncertainty) — and binds nothing: a
433            // variable joined with `Unknown` has learned nothing, and stays open for the
434            // constraints that do know its type.
435            (InferType::Unknown, _) | (_, InferType::Unknown) => Ok(()),
436
437            // Same variable: trivially unified
438            (InferType::Var(va), InferType::Var(vb)) if va == vb => Ok(()),
439
440            // Bind a variable to a type
441            (InferType::Var(tv), ty) => {
442                let tv = *tv;
443                let ty = ty.clone();
444                self.occurs_check(tv, &ty)?;
445                self.bindings[tv.0 as usize] = Some(ty);
446                Ok(())
447            }
448            (ty, InferType::Var(tv)) => {
449                let tv = *tv;
450                let ty = ty.clone();
451                self.occurs_check(tv, &ty)?;
452                self.bindings[tv.0 as usize] = Some(ty);
453                Ok(())
454            }
455
456            // Ground type equality
457            (InferType::Int, InferType::Int) => Ok(()),
458            (InferType::Float, InferType::Float) => Ok(()),
459            (InferType::Bool, InferType::Bool) => Ok(()),
460            (InferType::Char, InferType::Char) => Ok(()),
461            (InferType::Byte, InferType::Byte) => Ok(()),
462            (InferType::String, InferType::String) => Ok(()),
463            (InferType::Unit, InferType::Unit) => Ok(()),
464            (InferType::Nat, InferType::Nat) => Ok(()),
465            (InferType::Duration, InferType::Duration) => Ok(()),
466            (InferType::Date, InferType::Date) => Ok(()),
467            (InferType::Moment, InferType::Moment) => Ok(()),
468            (InferType::Time, InferType::Time) => Ok(()),
469            (InferType::Span, InferType::Span) => Ok(()),
470            // The DOM handle types are nominal: each unifies only with itself — never with
471            // `Int` (the runtime representation is not the type) and never with each other.
472            (InferType::Element, InferType::Element) => Ok(()),
473            (InferType::Event, InferType::Event) => Ok(()),
474            (InferType::View, InferType::View) => Ok(()),
475
476            // Nat embeds into Int for numeric contexts
477            (InferType::Nat, InferType::Int) | (InferType::Int, InferType::Nat) => Ok(()),
478
479            // Byte ↔ Int promotion (numeric literals infer as Int, adapt to Byte in context)
480            (InferType::Byte, InferType::Int) | (InferType::Int, InferType::Byte) => Ok(()),
481
482            // Rational equality + integer embedding: an integer IS an exact rational, so a
483            // `Let x: Rational be 5` (or `… be 7 / 2`, whose `ExactDivide` infers numeric)
484            // unifies against the `Rational` annotation. Mirrors Nat/Byte embedding into Int.
485            (InferType::Rational, InferType::Rational) => Ok(()),
486            (InferType::Rational, InferType::Int | InferType::Nat)
487            | (InferType::Int | InferType::Nat, InferType::Rational) => Ok(()),
488
489            // User-defined types unify when they name the same type and their arguments unify. A
490            // bare reference (no arguments) unifies with every application of its type.
491            (InferType::UserDefined(a, a_args), InferType::UserDefined(b, b_args)) if a == b => {
492                if a_args.is_empty() || b_args.is_empty() {
493                    return Ok(());
494                }
495                if a_args.len() != b_args.len() {
496                    return Err(TypeError::ArityMismatch {
497                        expected: a_args.len(),
498                        found: b_args.len(),
499                    });
500                }
501                let (a_args, b_args) = (a_args.clone(), b_args.clone());
502                for (x, y) in a_args.iter().zip(b_args.iter()) {
503                    self.unify(x, y)?;
504                }
505                Ok(())
506            }
507
508            // Structural recursion
509            (InferType::Seq(a_inner), InferType::Seq(b_inner)) => {
510                let a_inner = (**a_inner).clone();
511                let b_inner = (**b_inner).clone();
512                self.unify(&a_inner, &b_inner)
513            }
514            (InferType::Set(a_inner), InferType::Set(b_inner)) => {
515                let a_inner = (**a_inner).clone();
516                let b_inner = (**b_inner).clone();
517                self.unify(&a_inner, &b_inner)
518            }
519            (InferType::Option(a_inner), InferType::Option(b_inner)) => {
520                let a_inner = (**a_inner).clone();
521                let b_inner = (**b_inner).clone();
522                self.unify(&a_inner, &b_inner)
523            }
524            (InferType::Map(ak, av), InferType::Map(bk, bv)) => {
525                let ak = (**ak).clone();
526                let bk = (**bk).clone();
527                let av = (**av).clone();
528                let bv = (**bv).clone();
529                self.unify(&ak, &bk)?;
530                self.unify(&av, &bv)
531            }
532            (InferType::Function(a_params, a_ret), InferType::Function(b_params, b_ret)) => {
533                if a_params.len() != b_params.len() {
534                    return Err(TypeError::ArityMismatch {
535                        expected: a_params.len(),
536                        found: b_params.len(),
537                    });
538                }
539                let a_params = a_params.clone();
540                let b_params = b_params.clone();
541                let a_ret = (**a_ret).clone();
542                let b_ret = (**b_ret).clone();
543                for (ap, bp) in a_params.iter().zip(b_params.iter()) {
544                    self.unify(ap, bp)?;
545                }
546                self.unify(&a_ret, &b_ret)
547            }
548
549            // Type mismatch: `a` is the value's type, `b` its position's (see `unify`).
550            (a, b) => Err(TypeError::Mismatch {
551                expected: b.clone(),
552                found: a.clone(),
553            }),
554        }
555    }
556
557    /// Check that `tv` does not appear in `ty`.
558    ///
559    /// Prevents infinite types like `α = List<α>`.
560    fn occurs_check(&self, tv: TyVar, ty: &InferType) -> Result<(), TypeError> {
561        match ty {
562            InferType::Var(tv2) => {
563                let resolved = self.find(*tv2);
564                match &resolved {
565                    InferType::Var(rtv) => {
566                        if *rtv == tv {
567                            Err(TypeError::InfiniteType {
568                                var: tv,
569                                ty: ty.clone(),
570                            })
571                        } else {
572                            Ok(())
573                        }
574                    }
575                    other => self.occurs_check(tv, &other.clone()),
576                }
577            }
578            InferType::Seq(inner) | InferType::Set(inner) | InferType::Option(inner) => {
579                self.occurs_check(tv, inner)
580            }
581            InferType::Map(k, v) => {
582                self.occurs_check(tv, k)?;
583                self.occurs_check(tv, v)
584            }
585            InferType::UserDefined(_, args) => {
586                for a in args {
587                    self.occurs_check(tv, a)?;
588                }
589                Ok(())
590            }
591            InferType::Function(params, ret) => {
592                for p in params {
593                    self.occurs_check(tv, p)?;
594                }
595                self.occurs_check(tv, ret)
596            }
597            _ => Ok(()),
598        }
599    }
600}
601
602// ============================================================================
603// InferType helpers
604// ============================================================================
605
606impl InferType {
607    /// Convert a `TypeExpr` AST node to `InferType`.
608    ///
609    /// Unlike `LogosType::from_type_expr`, this correctly handles
610    /// `TypeExpr::Function { inputs, output }` by producing
611    /// `InferType::Function(...)` instead of `Unknown`.
612    pub fn from_type_expr(ty: &crate::ast::stmt::TypeExpr, interner: &Interner) -> InferType {
613        Self::from_type_expr_with_params(ty, interner, &HashMap::new())
614    }
615
616    /// Convert a `TypeExpr` to `InferType`, substituting generic type parameters.
617    ///
618    /// When `type_params` maps a name like `T` to a `TyVar`, any `TypeExpr::Primitive(T)`
619    /// or `TypeExpr::Named(T)` in the expression produces `InferType::Var(tv)` instead
620    /// of `Unknown`. This is used for generic function signatures where `T` is a type
621    /// parameter, not a concrete type name.
622    pub fn from_type_expr_with_params(
623        ty: &crate::ast::stmt::TypeExpr,
624        interner: &Interner,
625        type_params: &HashMap<Symbol, TyVar>,
626    ) -> InferType {
627        let params = type_params
628            .iter()
629            .map(|(s, tv)| (*s, InferType::Var(*tv)))
630            .collect();
631        Self::from_type_expr_in(
632            ty,
633            &TypeScope {
634                interner,
635                registry: None,
636                params: &params,
637                twins: None,
638            },
639        )
640    }
641
642    /// Convert a `TypeExpr` to `InferType` inside `scope`: a type parameter becomes the type it
643    /// stands for, and a user struct or enum becomes `UserDefined` applied to its arguments.
644    pub fn from_type_expr_in(ty: &crate::ast::stmt::TypeExpr, scope: &TypeScope) -> InferType {
645        use crate::ast::stmt::TypeExpr;
646        match ty {
647            // A `mutable` parameter unifies as its underlying type.
648            TypeExpr::Mutable { inner } => Self::from_type_expr_in(inner, scope),
649            TypeExpr::Primitive(sym) | TypeExpr::Named(sym) => {
650                Self::from_applied_name(*sym, None, scope)
651            }
652            TypeExpr::Generic { base, params } => {
653                let args = params
654                    .iter()
655                    .map(|p| Self::from_type_expr_in(p, scope))
656                    .collect();
657                Self::from_applied_name(*base, Some(args), scope)
658            }
659            // A tuple/record type — inference treats it structurally-opaquely (like `Pair`/`Triple`, which
660            // fall to `Unknown` above). The VM boundary + codegen carry the real per-position types.
661            TypeExpr::Tuple(_) => InferType::Unknown,
662            TypeExpr::Record { .. } => InferType::Unknown,
663            TypeExpr::Refinement { base, .. } => Self::from_type_expr_in(base, scope),
664            TypeExpr::Persistent { inner } => Self::from_type_expr_in(inner, scope),
665            TypeExpr::Function { inputs, output } => {
666                let param_types: Vec<InferType> = inputs
667                    .iter()
668                    .map(|p| Self::from_type_expr_in(p, scope))
669                    .collect();
670                let ret_type = Self::from_type_expr_in(output, scope);
671                InferType::Function(param_types, Box::new(ret_type))
672            }
673        }
674    }
675
676    /// The type a written name denotes, bare (`applied` is `None`) or applied to type arguments:
677    /// a type parameter in scope, a built-in collection or `Option`, a primitive, or a registered
678    /// user struct/enum (through any alias). `Option` is always the built-in, whatever the prelude
679    /// declares; a user's own `Maybe` is theirs, and only an undeclared `Maybe` is `Option`. A
680    /// bare collection name names no element type (`Unknown`); an applied one missing an argument
681    /// keeps its historical default.
682    fn from_applied_name(
683        base: Symbol,
684        applied: Option<Vec<InferType>>,
685        scope: &TypeScope,
686    ) -> InferType {
687        if applied.as_ref().map_or(true, |args| args.is_empty()) {
688            if let Some(param) = scope.params.get(&base) {
689                return param.clone();
690            }
691        }
692        let name = scope.interner.resolve(base);
693        let user = scope.registry.and_then(|r| r.get(base));
694        let declared_by_user = matches!(user, Some(TypeDef::Struct { .. } | TypeDef::Enum { .. }));
695        let is_option = name == "Option" || (name == "Maybe" && !declared_by_user);
696        let Some(args) = applied else {
697            if is_option {
698                return InferType::Option(Box::new(InferType::Unknown));
699            }
700            let primitive = Self::from_type_name(name);
701            if primitive != InferType::Unknown {
702                return primitive;
703            }
704            return match user {
705                Some(TypeDef::Struct { .. } | TypeDef::Enum { .. }) => {
706                    InferType::UserDefined(scope.canonical(base), Vec::new())
707                }
708                Some(TypeDef::Alias { target }) if *target != base => {
709                    Self::from_applied_name(*target, None, scope)
710                }
711                _ => InferType::Unknown,
712            };
713        };
714        let mut args = args.into_iter();
715        if is_option {
716            return InferType::Option(Box::new(args.next().unwrap_or(InferType::Unit)));
717        }
718        match name {
719            "Seq" | "List" | "Vec" => {
720                return InferType::Seq(Box::new(args.next().unwrap_or(InferType::Unit)))
721            }
722            "Set" | "HashSet" => {
723                return InferType::Set(Box::new(args.next().unwrap_or(InferType::Unit)))
724            }
725            "Map" | "HashMap" => {
726                let k = args.next().unwrap_or(InferType::String);
727                let v = args.next().unwrap_or(InferType::String);
728                return InferType::Map(Box::new(k), Box::new(v));
729            }
730            _ => {}
731        }
732        let args: Vec<InferType> = args.collect();
733        if args.is_empty() {
734            let primitive = Self::from_type_name(name);
735            if primitive != InferType::Unknown {
736                return primitive;
737            }
738        }
739        match user {
740            Some(TypeDef::Struct { .. } | TypeDef::Enum { .. }) => {
741                InferType::UserDefined(scope.canonical(base), args)
742            }
743            Some(TypeDef::Alias { target }) if *target != base => {
744                Self::from_applied_name(*target, Some(args), scope)
745            }
746            _ => InferType::Unknown,
747        }
748    }
749
750    /// Convert a registry `FieldType` to `InferType`.
751    ///
752    /// `type_params` maps generic type parameter names (e.g., `T`, `U`) to
753    /// type variable indices allocated by [`UnificationTable::fresh`].
754    pub fn from_field_type(
755        ty: &FieldType,
756        interner: &Interner,
757        type_params: &HashMap<Symbol, TyVar>,
758    ) -> InferType {
759        let params = type_params
760            .iter()
761            .map(|(s, tv)| (*s, InferType::Var(*tv)))
762            .collect();
763        Self::from_field_type_in(
764            ty,
765            &TypeScope {
766                interner,
767                registry: None,
768                params: &params,
769                twins: None,
770            },
771        )
772    }
773
774    /// Convert a registry `FieldType` to `InferType` inside `scope` — how a generic record's field
775    /// is read at one application of the record (`value: T` of a `Box of Int` is `Int`).
776    pub fn from_field_type_in(ty: &FieldType, scope: &TypeScope) -> InferType {
777        match ty {
778            FieldType::Primitive(sym) => InferType::from_type_name(scope.interner.resolve(*sym)),
779            FieldType::Named(sym) => {
780                if let Some(param) = scope.params.get(sym) {
781                    return param.clone();
782                }
783                // A field of one of the exact extension's types is typed as a binding declared one is.
784                if crate::analysis::tower::TOWER_TYPES.contains(&scope.interner.resolve(*sym)) {
785                    return InferType::Unknown;
786                }
787                match Self::from_applied_name(*sym, None, scope) {
788                    InferType::Unknown => InferType::UserDefined(scope.canonical(*sym), Vec::new()),
789                    known => known,
790                }
791            }
792            FieldType::Generic { base, params } => {
793                let args = params
794                    .iter()
795                    .map(|p| Self::from_field_type_in(p, scope))
796                    .collect();
797                Self::from_applied_name(*base, Some(args), scope)
798            }
799            FieldType::TypeParam(sym) => {
800                scope.params.get(sym).cloned().unwrap_or(InferType::Unknown)
801            }
802            // A tuple is structurally opaque to inference, exactly as a written `(A, B)` is.
803            FieldType::Tuple(_) | FieldType::Record(_) => InferType::Unknown,
804        }
805    }
806
807    /// Infer `InferType` from a literal value.
808    pub fn from_literal(lit: &crate::ast::stmt::Literal) -> InferType {
809        use crate::ast::stmt::Literal;
810        match lit {
811            Literal::Number(_) => InferType::Int,
812            Literal::Float(_) => InferType::Float,
813            Literal::Text(_) => InferType::String,
814            Literal::Boolean(_) => InferType::Bool,
815            Literal::Char(_) => InferType::Char,
816            Literal::Nothing => InferType::Unit,
817            Literal::Duration(_) => InferType::Duration,
818            Literal::Date(_) => InferType::Date,
819            Literal::Moment(_) => InferType::Moment,
820            Literal::Span { .. } => InferType::Span,
821            Literal::Time(_) => InferType::Time,
822        }
823    }
824
825    /// Parse a LOGOS type name into `InferType`.
826    pub fn from_type_name(name: &str) -> InferType {
827        match name {
828            "Int" => InferType::Int,
829            "Nat" => InferType::Nat,
830            "Rational" => InferType::Rational,
831            "Real" | "Float" => InferType::Float,
832            "Bool" | "Boolean" => InferType::Bool,
833            "Text" | "String" => InferType::String,
834            "Char" => InferType::Char,
835            "Byte" => InferType::Byte,
836            "Unit" | "()" => InferType::Unit,
837            "Duration" => InferType::Duration,
838            "Date" => InferType::Date,
839            "Moment" => InferType::Moment,
840            "Time" => InferType::Time,
841            "Span" => InferType::Span,
842            "Element" => InferType::Element,
843            "Event" => InferType::Event,
844            "View" => InferType::View,
845            _ => InferType::Unknown,
846        }
847    }
848
849    /// Human-readable type name in Logos terms, for error messages: a user type by its own name
850    /// and arguments (`Outcome`, `Box of Int`).
851    pub fn describe(&self, interner: &crate::intern::Interner) -> std::string::String {
852        self.render(Some(interner))
853    }
854
855    /// [`describe`](Self::describe) where no interner is at hand: a user type reads as "a
856    /// user-defined type".
857    pub fn to_logos_name(&self) -> std::string::String {
858        self.render(None)
859    }
860
861    /// The name a program writes for this type when it is one of the language's own scalars
862    /// (`Int`, `Real`, `Text`, …); `None` for a collection, a user type, a function or a variable.
863    pub fn primitive_name(&self) -> Option<&'static str> {
864        Some(match self {
865            InferType::Int => "Int",
866            InferType::Float => "Real",
867            InferType::Bool => "Bool",
868            InferType::Char => "Char",
869            InferType::Byte => "Byte",
870            InferType::String => "Text",
871            InferType::Unit => "Unit",
872            InferType::Nat => "Nat",
873            InferType::Rational => "Rational",
874            InferType::Duration => "Duration",
875            InferType::Date => "Date",
876            InferType::Moment => "Moment",
877            InferType::Time => "Time",
878            InferType::Span => "Span",
879            InferType::Element => "Element",
880            InferType::Event => "Event",
881            InferType::View => "View",
882            _ => return None,
883        })
884    }
885
886    fn render(&self, interner: Option<&crate::intern::Interner>) -> std::string::String {
887        match self {
888            InferType::Int => "Int".into(),
889            InferType::Float => "Real".into(),
890            InferType::Bool => "Bool".into(),
891            InferType::Char => "Char".into(),
892            InferType::Byte => "Byte".into(),
893            InferType::String => "Text".into(),
894            InferType::Unit => "Unit".into(),
895            InferType::Nat => "Nat".into(),
896            InferType::Rational => "Rational".into(),
897            InferType::Duration => "Duration".into(),
898            InferType::Date => "Date".into(),
899            InferType::Moment => "Moment".into(),
900            InferType::Time => "Time".into(),
901            InferType::Span => "Span".into(),
902            InferType::Element => "Element".into(),
903            InferType::Event => "Event".into(),
904            InferType::View => "View".into(),
905            InferType::Seq(inner) => format!("Seq of {}", inner.render(interner)),
906            InferType::Map(k, v) => {
907                format!("Map of {} and {}", k.render(interner), v.render(interner))
908            }
909            InferType::Set(inner) => format!("Set of {}", inner.render(interner)),
910            InferType::Option(inner) => format!("Option of {}", inner.render(interner)),
911            InferType::UserDefined(name, args) => match interner {
912                Some(interner) if args.is_empty() => interner.resolve(*name).to_string(),
913                Some(interner) => {
914                    let args: Vec<std::string::String> =
915                        args.iter().map(|a| a.render(Some(interner))).collect();
916                    format!("{} of {}", interner.resolve(*name), args.join(" and "))
917                }
918                None => "a user-defined type".into(),
919            },
920            InferType::Var(_) => "an unknown type".into(),
921            InferType::Function(params, ret) => {
922                let params_str = params
923                    .iter()
924                    .map(|p| p.render(interner))
925                    .collect::<Vec<_>>()
926                    .join(", ");
927                format!("fn({}) -> {}", params_str, ret.render(interner))
928            }
929            InferType::Unknown => "unknown".into(),
930        }
931    }
932
933    /// Convert a known-ground `InferType` to `LogosType`.
934    ///
935    /// # Panics
936    ///
937    /// Panics if called on a `Var`. Callers must `zonk` first.
938    pub fn to_logos_type_ground(&self) -> LogosType {
939        match self {
940            InferType::Int => LogosType::Int,
941            InferType::Float => LogosType::Float,
942            InferType::Bool => LogosType::Bool,
943            InferType::Char => LogosType::Char,
944            InferType::Byte => LogosType::Byte,
945            InferType::String => LogosType::String,
946            InferType::Unit => LogosType::Unit,
947            InferType::Nat => LogosType::Nat,
948            InferType::Rational => LogosType::Rational,
949            InferType::Duration => LogosType::Duration,
950            InferType::Date => LogosType::Date,
951            InferType::Moment => LogosType::Moment,
952            InferType::Time => LogosType::Time,
953            InferType::Span => LogosType::Span,
954            InferType::Element => LogosType::Element,
955            InferType::Event => LogosType::Event,
956            InferType::View => LogosType::View,
957            InferType::Seq(inner) => LogosType::Seq(Box::new(inner.to_logos_type_ground())),
958            InferType::Map(k, v) => LogosType::Map(
959                Box::new(k.to_logos_type_ground()),
960                Box::new(v.to_logos_type_ground()),
961            ),
962            InferType::Set(inner) => LogosType::Set(Box::new(inner.to_logos_type_ground())),
963            InferType::Option(inner) => LogosType::Option(Box::new(inner.to_logos_type_ground())),
964            InferType::UserDefined(sym, _) => LogosType::UserDefined(*sym),
965            InferType::Function(params, ret) => LogosType::Function(
966                params.iter().map(|p| p.to_logos_type_ground()).collect(),
967                Box::new(ret.to_logos_type_ground()),
968            ),
969            InferType::Unknown => LogosType::Unknown,
970            InferType::Var(_) => panic!("to_logos_type_ground called on unresolved Var"),
971        }
972    }
973}
974
975// ============================================================================
976// Helpers
977// ============================================================================
978
979/// Numeric promotion: Float wins; Int + Int = Int; Nat + Nat = Nat; Byte + Byte = Byte;
980/// Byte + Int (literal context) = Byte; otherwise error.
981pub fn unify_numeric(a: &InferType, b: &InferType) -> Result<InferType, TypeError> {
982    match (a, b) {
983        (InferType::Float, _) | (_, InferType::Float) => Ok(InferType::Float),
984        // A Rational operand promotes the result to Rational (the exact type wins over Int).
985        (InferType::Rational, InferType::Rational | InferType::Int | InferType::Nat)
986        | (InferType::Int | InferType::Nat, InferType::Rational) => Ok(InferType::Rational),
987        (InferType::Int, InferType::Int) => Ok(InferType::Int),
988        (InferType::Nat, InferType::Int) | (InferType::Int, InferType::Nat) => Ok(InferType::Int),
989        (InferType::Nat, InferType::Nat) => Ok(InferType::Nat),
990        (InferType::Byte, InferType::Byte) => Ok(InferType::Byte),
991        (InferType::Byte, InferType::Int) | (InferType::Int, InferType::Byte) => {
992            Ok(InferType::Byte)
993        }
994        _ => Err(TypeError::Mismatch {
995            expected: InferType::Int,
996            found: a.clone(),
997        }),
998    }
999}
1000
1001/// Convert a zonked `InferType` to `LogosType`.
1002pub fn infer_to_logos(ty: &InferType) -> LogosType {
1003    match ty {
1004        InferType::Int => LogosType::Int,
1005        InferType::Float => LogosType::Float,
1006        InferType::Bool => LogosType::Bool,
1007        InferType::Char => LogosType::Char,
1008        InferType::Byte => LogosType::Byte,
1009        InferType::String => LogosType::String,
1010        InferType::Unit => LogosType::Unit,
1011        InferType::Nat => LogosType::Nat,
1012        InferType::Rational => LogosType::Rational,
1013        InferType::Duration => LogosType::Duration,
1014        InferType::Date => LogosType::Date,
1015        InferType::Moment => LogosType::Moment,
1016        InferType::Time => LogosType::Time,
1017        InferType::Span => LogosType::Span,
1018        InferType::Element => LogosType::Element,
1019        InferType::Event => LogosType::Event,
1020        InferType::View => LogosType::View,
1021        InferType::Seq(inner) => LogosType::Seq(Box::new(infer_to_logos(inner))),
1022        InferType::Map(k, v) => {
1023            LogosType::Map(Box::new(infer_to_logos(k)), Box::new(infer_to_logos(v)))
1024        }
1025        InferType::Set(inner) => LogosType::Set(Box::new(infer_to_logos(inner))),
1026        InferType::Option(inner) => LogosType::Option(Box::new(infer_to_logos(inner))),
1027        InferType::UserDefined(sym, _) => LogosType::UserDefined(*sym),
1028        InferType::Function(params, ret) => LogosType::Function(
1029            params.iter().map(infer_to_logos).collect(),
1030            Box::new(infer_to_logos(ret)),
1031        ),
1032        InferType::Unknown | InferType::Var(_) => LogosType::Unknown,
1033    }
1034}
1035
1036// ============================================================================
1037// Tests
1038// ============================================================================
1039
1040#[cfg(test)]
1041#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/analysis/unify/tests.rs"]
1042mod tests;