Skip to main content

logicaffeine_compile/analysis/
types.rs

1//! Type inference pass for the LOGOS compilation pipeline.
2//!
3//! Provides a structured type representation (`LogosType`) and a type environment
4//! (`TypeEnv`) that replaces the ad-hoc string-based type tracking previously
5//! scattered across codegen.rs.
6//!
7//! # Pipeline Position
8//!
9//! ```text
10//! Parse → TypeInfer → Optimize → Codegen
11//!              ^ THIS MODULE
12//! ```
13//!
14//! The `TypeEnv` is computed once from the AST and passed immutably to codegen,
15//! replacing `variable_types: HashMap<Symbol, String>` and `string_vars: HashSet<Symbol>`.
16
17use std::collections::HashMap;
18
19use crate::analysis::TypeRegistry;
20use crate::ast::stmt::{BinaryOpKind, Expr, Literal, Stmt, TypeExpr};
21use crate::intern::{Interner, Symbol};
22
23/// Structured type representation for LOGOS values.
24///
25/// Replaces string-based type tracking (e.g., `"Vec<i64>"`, `"String"`)
26/// with a proper algebraic data type that supports precise queries.
27#[derive(Debug, Clone, PartialEq, Eq, Hash)]
28pub enum LogosType {
29    Int,
30    Float,
31    Bool,
32    Char,
33    Byte,
34    String,
35    Unit,
36    Seq(Box<LogosType>),
37    Map(Box<LogosType>, Box<LogosType>),
38    Set(Box<LogosType>),
39    Option(Box<LogosType>),
40    Duration,
41    Date,
42    Moment,
43    Time,
44    Span,
45    Nat,
46    /// A DOM element handle — nominal (never an `Int`), an i64 handle at runtime on every tier.
47    Element,
48    /// A DOM event handle — nominal, distinct from `Element`; an i64 handle at runtime.
49    Event,
50    /// A view value (a template with its captured bindings) — nominal.
51    View,
52    /// Exact rational (`logicaffeine_base::Rational`). A `Rational`-typed binding keeps
53    /// division exact (`7 / 2 → 7/2`) where a bare `Int` floors. Lowers to `LogosRational`.
54    Rational,
55    /// Exact base-10 fixed-point (money). `+ − ×` stay exact `Decimal` (scale preserved);
56    /// `÷` widens to `Rational`. Built via `decimal("19.99")`. Lowers to `LogosDecimal`.
57    Decimal,
58    /// Exact complex number `re + im·i`. `+ − × ÷` stay `Complex` (closed field). Built via
59    /// `complex(re, im)`. NOT ordered. Lowers to `LogosComplex`.
60    Complex,
61    /// An element of the ring ℤ/nℤ. `+ − × ÷` stay `Modular` (same modulus required, no
62    /// auto-lift). Built via `modular(value, modulus)`. NOT ordered. Lowers to `LogosModular`.
63    Modular,
64    /// A dimensioned physical quantity (`quantity(2, "inch")`). `+ −` require the same dimension,
65    /// `× ÷` combine dimensions, and it may be scaled by a number; built via `quantity`/`convert`.
66    /// The magnitude rides the exact rational tower. Lowers to `LogosQuantity`. Dimension safety is
67    /// enforced at runtime (a clean error), like `Modular`'s ring check.
68    Quantity,
69    /// An exact monetary amount in a currency (`money(19.99, "USD")` / `19.99 USD`). `+ −` require
70    /// the same currency, `× ÷` scale by a number; the amount rides the Decimal tower. Lowers to
71    /// `LogosMoney`. Currency safety is enforced at runtime (a clean error), like `Quantity`.
72    Money,
73    /// A 128-bit UUID (`uuid "…"`, `a random uuid`). An opaque identifier — no arithmetic; lowers to
74    /// `LogosUuid`. Comparable/orderable by its bytes.
75    Uuid,
76    UserDefined(Symbol),
77    /// First-class function type: fn(P1, P2, ...) -> R
78    Function(Vec<LogosType>, Box<LogosType>),
79    Unknown,
80}
81
82/// Function signature for tracked functions.
83#[derive(Debug, Clone)]
84pub struct FnSig {
85    pub params: Vec<(Symbol, LogosType)>,
86    pub return_type: LogosType,
87}
88
89/// Type environment built by a forward pass over the AST.
90///
91/// Computed once before codegen and shared immutably. Replaces the
92/// `variable_types: HashMap<Symbol, String>` and `string_vars: HashSet<Symbol>`
93/// that were incrementally built during codegen.
94#[derive(Debug)]
95pub struct TypeEnv {
96    variables: HashMap<Symbol, LogosType>,
97    functions: HashMap<Symbol, FnSig>,
98    native_functions: std::collections::HashSet<Symbol>,
99}
100
101impl LogosType {
102    /// Whether this type is Copy in Rust (no .clone() needed).
103    ///
104    /// This is the single source of truth for clone decisions,
105    /// replacing `is_copy_type()`, `has_copy_element_type()`, `has_copy_value_type()`.
106    pub fn is_copy(&self) -> bool {
107        matches!(
108            self,
109            LogosType::Int
110                | LogosType::Float
111                | LogosType::Bool
112                | LogosType::Char
113                | LogosType::Byte
114                | LogosType::Unit
115                | LogosType::Nat
116                | LogosType::Element
117                | LogosType::Event
118                | LogosType::View
119        )
120    }
121
122    /// Whether this type is numeric (Int or Float).
123    pub fn is_numeric(&self) -> bool {
124        matches!(self, LogosType::Int | LogosType::Float | LogosType::Nat)
125    }
126
127    /// Whether this type is a string.
128    pub fn is_string(&self) -> bool {
129        matches!(self, LogosType::String)
130    }
131
132    /// Whether this type is a float.
133    pub fn is_float(&self) -> bool {
134        matches!(self, LogosType::Float)
135    }
136
137    /// Get the element type for sequences and sets.
138    pub fn element_type(&self) -> Option<&LogosType> {
139        match self {
140            LogosType::Seq(inner) | LogosType::Set(inner) => Some(inner),
141            _ => None,
142        }
143    }
144
145    /// Get the value type for maps.
146    pub fn value_type(&self) -> Option<&LogosType> {
147        match self {
148            LogosType::Map(_, v) => Some(v),
149            _ => None,
150        }
151    }
152
153    /// Get the key type for maps.
154    pub fn key_type(&self) -> Option<&LogosType> {
155        match self {
156            LogosType::Map(k, _) => Some(k),
157            _ => None,
158        }
159    }
160
161    /// Numeric promotion: Z embeds into R.
162    /// If either operand is Float, the result is Float.
163    /// If both are Int (or Nat), the result is Int.
164    pub fn numeric_promotion(a: &LogosType, b: &LogosType) -> LogosType {
165        if matches!(a, LogosType::Quantity) || matches!(b, LogosType::Quantity) {
166            // A quantity carries through `+ − × ÷` (same-dimension for `+ −`, dimension-combining
167            // for `× ÷`, or scaling by a number) — the dimensional rule is enforced at runtime.
168            LogosType::Quantity
169        } else if matches!(a, LogosType::Money) || matches!(b, LogosType::Money) {
170            // Money carries through `+ −` (same currency) and scaling by a number. (A same-currency
171            // `Money ÷ Money` is a Rational ratio — that operator-specific narrowing is handled in
172            // the binary-op inference, not this operator-agnostic promotion.)
173            LogosType::Money
174        } else if a.is_float() || b.is_float() {
175            LogosType::Float
176        } else if matches!(a, LogosType::Rational) || matches!(b, LogosType::Rational) {
177            // A Rational operand carries through `+ − ×`: the exact type wins over Int.
178            LogosType::Rational
179        } else if matches!(a, LogosType::Modular) && matches!(b, LogosType::Modular) {
180            // Modular combines only with Modular (same ring; no auto-lift of a bare integer).
181            LogosType::Modular
182        } else if matches!(a, LogosType::Complex) || matches!(b, LogosType::Complex) {
183            // Complex is the top of the exact tower: a real embeds as `re + 0i`, so any
184            // operation with a Complex stays Complex (the field is closed under + − × ÷).
185            LogosType::Complex
186        } else if matches!(a, LogosType::Decimal) || matches!(b, LogosType::Decimal) {
187            // A Decimal carries through `+ − ×` (Decimal ∘ Int stays Decimal, scale kept).
188            LogosType::Decimal
189        } else if a.is_numeric() && b.is_numeric() {
190            LogosType::Int
191        } else {
192            LogosType::Unknown
193        }
194    }
195
196    /// The type that holds a value of `a` and one of `b` where the language joins numbers exactly: an integer
197    /// and a rational are both the rational they equal, item by item in lists. `None` for any other pair.
198    pub fn number_join(a: &LogosType, b: &LogosType) -> Option<LogosType> {
199        match (a, b) {
200            _ if a == b => Some(a.clone()),
201            (LogosType::Int, LogosType::Rational) | (LogosType::Rational, LogosType::Int) => Some(LogosType::Rational),
202            (LogosType::Seq(x), LogosType::Seq(y)) => LogosType::number_join(x, y).map(|t| LogosType::Seq(Box::new(t))),
203            _ => None,
204        }
205    }
206
207    /// Whether a value of this type holds a rational: one, or a list of them at any depth.
208    pub fn holds_rational(&self) -> bool {
209        match self {
210            LogosType::Rational => true,
211            LogosType::Seq(inner) => inner.holds_rational(),
212            _ => false,
213        }
214    }
215
216    /// Convert to the Rust type string used in codegen output.
217    ///
218    /// Replaces all ad-hoc string-based type conversions scattered
219    /// across codegen.rs. This is the single point of truth for
220    /// LogosType → Rust type string mapping.
221    pub fn to_rust_type(&self) -> std::string::String {
222        match self {
223            LogosType::Int => "i64".into(),
224            LogosType::Float => "f64".into(),
225            LogosType::Bool => "bool".into(),
226            LogosType::Char => "char".into(),
227            LogosType::Byte => "u8".into(),
228            LogosType::String => "String".into(),
229            LogosType::Unit => "()".into(),
230            LogosType::Nat => "u64".into(),
231            LogosType::Rational => "LogosRational".into(),
232            LogosType::Decimal => "LogosDecimal".into(),
233            LogosType::Complex => "LogosComplex".into(),
234            LogosType::Modular => "LogosModular".into(),
235            LogosType::Quantity => "LogosQuantity".into(),
236            LogosType::Money => "LogosMoney".into(),
237            LogosType::Uuid => "LogosUuid".into(),
238            LogosType::Duration => "std::time::Duration".into(),
239            LogosType::Date => "LogosDate".into(),
240            LogosType::Moment => "LogosMoment".into(),
241            LogosType::Time => "LogosTime".into(),
242            LogosType::Span => "LogosSpan".into(),
243            // Handles are the i64 every tier already moves; nominality lives in the checker.
244            LogosType::Element | LogosType::Event | LogosType::View => "i64".into(),
245            LogosType::Seq(inner) => format!("LogosSeq<{}>", inner.to_rust_type()),
246            LogosType::Map(k, v) => format!("LogosMap<{}, {}>", k.to_rust_type(), v.to_rust_type()),
247            LogosType::Set(inner) => {
248                format!("Set<{}>", inner.to_rust_type())
249            }
250            LogosType::Option(inner) => format!("Option<{}>", inner.to_rust_type()),
251            LogosType::Function(params, ret) => {
252                let params_str = params
253                    .iter()
254                    .map(|p| p.to_rust_type())
255                    .collect::<Vec<_>>()
256                    .join(", ");
257                format!("impl Fn({}) -> {}", params_str, ret.to_rust_type())
258            }
259            LogosType::UserDefined(_) => "_".into(),
260            LogosType::Unknown => "_".into(),
261        }
262    }
263
264    /// Build a LogosType from a TypeExpr AST node.
265    pub fn from_type_expr(ty: &TypeExpr, interner: &Interner) -> LogosType {
266        match ty {
267            // A `mutable` parameter erases to its underlying type; the marker only
268            // affects the parameter-passing convention (Mutable Value Semantics).
269            TypeExpr::Mutable { inner } => Self::from_type_expr(inner, interner),
270            TypeExpr::Primitive(sym) | TypeExpr::Named(sym) => {
271                Self::from_type_name(interner.resolve(*sym))
272            }
273            TypeExpr::Generic { base, params } => {
274                let base_name = interner.resolve(*base);
275                match base_name {
276                    "Seq" | "List" | "Vec" => {
277                        let elem = params
278                            .first()
279                            .map(|p| LogosType::from_type_expr(p, interner))
280                            .unwrap_or(LogosType::Unit);
281                        LogosType::Seq(Box::new(elem))
282                    }
283                    "Map" | "HashMap" => {
284                        let key = params
285                            .first()
286                            .map(|p| LogosType::from_type_expr(p, interner))
287                            .unwrap_or(LogosType::String);
288                        let val = params
289                            .get(1)
290                            .map(|p| LogosType::from_type_expr(p, interner))
291                            .unwrap_or(LogosType::String);
292                        LogosType::Map(Box::new(key), Box::new(val))
293                    }
294                    "Set" | "HashSet" => {
295                        let elem = params
296                            .first()
297                            .map(|p| LogosType::from_type_expr(p, interner))
298                            .unwrap_or(LogosType::Unit);
299                        LogosType::Set(Box::new(elem))
300                    }
301                    "Option" | "Maybe" => {
302                        let inner = params
303                            .first()
304                            .map(|p| LogosType::from_type_expr(p, interner))
305                            .unwrap_or(LogosType::Unit);
306                        LogosType::Option(Box::new(inner))
307                    }
308                    _ => LogosType::Unknown,
309                }
310            }
311            // A tuple/record type — the analysis is structural-agnostic here (as `Pair`/`Triple` already
312            // are, falling to `Unknown` above); the VM boundary + codegen carry the real per-position types.
313            TypeExpr::Tuple(_) => LogosType::Unknown,
314            TypeExpr::Record { .. } => LogosType::Unknown,
315            TypeExpr::Refinement { base, .. } => LogosType::from_type_expr(base, interner),
316            TypeExpr::Persistent { inner } => LogosType::from_type_expr(inner, interner),
317            TypeExpr::Function { inputs, output } => {
318                let params = inputs
319                    .iter()
320                    .map(|i| LogosType::from_type_expr(i, interner))
321                    .collect();
322                let ret = Box::new(LogosType::from_type_expr(output, interner));
323                LogosType::Function(params, ret)
324            }
325        }
326    }
327
328    /// Parse a LOGOS type name string into a LogosType.
329    pub(crate) fn from_type_name(name: &str) -> LogosType {
330        match name {
331            "Int" => LogosType::Int,
332            "Nat" => LogosType::Nat,
333            "Rational" => LogosType::Rational,
334            "Decimal" => LogosType::Decimal,
335            "Complex" => LogosType::Complex,
336            "Modular" => LogosType::Modular,
337            "Quantity" => LogosType::Quantity,
338            "Money" => LogosType::Money,
339            "Uuid" | "UUID" => LogosType::Uuid,
340            "Real" | "Float" => LogosType::Float,
341            "Bool" | "Boolean" => LogosType::Bool,
342            "Text" | "String" => LogosType::String,
343            "Char" => LogosType::Char,
344            "Byte" => LogosType::Byte,
345            "Unit" | "()" => LogosType::Unit,
346            "Duration" => LogosType::Duration,
347            "Date" => LogosType::Date,
348            "Moment" => LogosType::Moment,
349            "Time" => LogosType::Time,
350            "Span" => LogosType::Span,
351            "Element" => LogosType::Element,
352            "Event" => LogosType::Event,
353            "View" => LogosType::View,
354            _ => LogosType::Unknown,
355        }
356    }
357
358    /// Parse a Rust type string back into a LogosType (legacy bridge).
359    /// Handles strings like "i64", "f64", "String", "Vec<i64>",
360    /// "std::collections::HashMap<String, i64>", etc.
361    pub fn from_rust_type_str(s: &str) -> LogosType {
362        // Strip loop-bounds hoisting sentinel (e.g. "Vec<i64>|__hl:left_len" → "Vec<i64>").
363        let s = s.split("|__hl:").next().unwrap_or(s);
364        // Strip the promotable-Int sentinel ("i64|__bigint"): the value still classifies as
365        // Int (so the exact-arithmetic path fires); the tag only steers codegen to store the
366        // overflow-promoting `LogosInt` instead of a bare `i64`.
367        let s = s.split("|__bigint").next().unwrap_or(s);
368        match s {
369            "i64" => LogosType::Int,
370            "u64" => LogosType::Nat,
371            "f64" => LogosType::Float,
372            "bool" => LogosType::Bool,
373            "char" => LogosType::Char,
374            "u8" => LogosType::Byte,
375            "LogosRational" => LogosType::Rational,
376            "LogosDecimal" => LogosType::Decimal,
377            "LogosComplex" => LogosType::Complex,
378            "LogosModular" => LogosType::Modular,
379            "LogosQuantity" => LogosType::Quantity,
380            "LogosMoney" => LogosType::Money,
381            "LogosUuid" => LogosType::Uuid,
382            "String" => LogosType::String,
383            "()" => LogosType::Unit,
384            "std::time::Duration" => LogosType::Duration,
385            "LogosDate" => LogosType::Date,
386            "LogosMoment" => LogosType::Moment,
387            "LogosTime" => LogosType::Time,
388            "LogosSpan" => LogosType::Span,
389            _ => {
390                // A place that can hold `nothing` holds a value of its payload's type, or nothing.
391                if let Some(inner) = s.strip_prefix("LogosOpt<").and_then(|s| s.strip_suffix('>')) {
392                    return Self::from_rust_type_str(inner);
393                }
394                // Try to parse generic types
395                if let Some(inner) = s
396                    .strip_prefix("LogosSeq<")
397                    .or_else(|| s.strip_prefix("Vec<"))
398                    .and_then(|s| s.strip_suffix('>'))
399                {
400                    LogosType::Seq(Box::new(Self::from_rust_type_str(inner)))
401                } else if let Some(inner) = s
402                    .strip_prefix("LogosMap<")
403                    .or_else(|| s.strip_prefix("std::collections::HashMap<"))
404                    .or_else(|| s.strip_prefix("HashMap<"))
405                    .or_else(|| s.strip_prefix("rustc_hash::FxHashMap<"))
406                    .or_else(|| s.strip_prefix("FxHashMap<"))
407                    .and_then(|s| s.strip_suffix('>'))
408                {
409                    if let Some((key, val)) = inner.split_once(", ") {
410                        LogosType::Map(
411                            Box::new(Self::from_rust_type_str(key)),
412                            Box::new(Self::from_rust_type_str(val)),
413                        )
414                    } else {
415                        LogosType::Unknown
416                    }
417                } else if let Some(inner) = s
418                    .strip_prefix("std::collections::HashSet<")
419                    .or_else(|| s.strip_prefix("HashSet<"))
420                    .or_else(|| s.strip_prefix("rustc_hash::FxHashSet<"))
421                    .or_else(|| s.strip_prefix("FxHashSet<"))
422                    .or_else(|| s.strip_prefix("Set<"))
423                    .and_then(|s| s.strip_suffix('>'))
424                {
425                    LogosType::Set(Box::new(Self::from_rust_type_str(inner)))
426                } else if let Some(inner) =
427                    s.strip_prefix("Option<").and_then(|s| s.strip_suffix('>'))
428                {
429                    LogosType::Option(Box::new(Self::from_rust_type_str(inner)))
430                } else {
431                    LogosType::Unknown
432                }
433            }
434        }
435    }
436
437    /// Infer a LogosType from a literal expression.
438    pub fn from_literal(lit: &Literal) -> LogosType {
439        match lit {
440            Literal::Number(_) => LogosType::Int,
441            Literal::Float(_) => LogosType::Float,
442            Literal::Text(_) => LogosType::String,
443            Literal::Boolean(_) => LogosType::Bool,
444            Literal::Char(_) => LogosType::Char,
445            Literal::Nothing => LogosType::Unit,
446            Literal::Duration(_) => LogosType::Duration,
447            Literal::Date(_) => LogosType::Date,
448            Literal::Moment(_) => LogosType::Moment,
449            Literal::Span { .. } => LogosType::Span,
450            Literal::Time(_) => LogosType::Time,
451        }
452    }
453}
454
455impl TypeEnv {
456    pub fn new() -> Self {
457        Self {
458            variables: HashMap::new(),
459            functions: HashMap::new(),
460            native_functions: std::collections::HashSet::new(),
461        }
462    }
463
464    /// Look up the type of a variable.
465    pub fn lookup(&self, sym: Symbol) -> &LogosType {
466        self.variables.get(&sym).unwrap_or(&LogosType::Unknown)
467    }
468
469    /// Look up a function signature.
470    pub fn lookup_fn(&self, sym: Symbol) -> Option<&FnSig> {
471        self.functions.get(&sym)
472    }
473
474    /// Register a variable with its type.
475    pub fn register(&mut self, sym: Symbol, ty: LogosType) {
476        self.variables.insert(sym, ty);
477    }
478
479    /// Register a function signature.
480    pub fn register_fn(&mut self, sym: Symbol, sig: FnSig) {
481        self.functions.insert(sym, sig);
482        self.native_functions.remove(&sym);
483    }
484
485    pub(super) fn set_native_fn(&mut self, sym: Symbol, is_native: bool) {
486        if is_native {
487            self.native_functions.insert(sym);
488        } else {
489            self.native_functions.remove(&sym);
490        }
491    }
492
493    /// Infer the type of an expression given the current environment.
494    pub fn infer_expr(&self, expr: &Expr, interner: &Interner) -> LogosType {
495        self.infer_expr_with(expr, interner, &|_| None)
496    }
497
498    /// [`TypeEnv::infer_expr`], with `field` typing each read of a record's field the environment does not know.
499    pub fn infer_expr_with(
500        &self,
501        expr: &Expr,
502        interner: &Interner,
503        field: &dyn Fn(&Expr) -> Option<LogosType>,
504    ) -> LogosType {
505        match expr {
506            Expr::Literal(lit) => LogosType::from_literal(lit),
507
508            Expr::Identifier(sym) => self.lookup(*sym).clone(),
509
510            Expr::BinaryOp { op, left, right } => {
511                match op {
512                    // Comparison operators always produce Bool
513                    BinaryOpKind::Eq
514                    | BinaryOpKind::NotEq
515                    | BinaryOpKind::Lt
516                    | BinaryOpKind::Gt
517                    | BinaryOpKind::LtEq
518                    | BinaryOpKind::GtEq
519                    | BinaryOpKind::ApproxEq => LogosType::Bool,
520
521                    // And/Or: logical — truthiness in, Bool out (`&`/`|` are the bitwise spellings).
522                    BinaryOpKind::And | BinaryOpKind::Or => LogosType::Bool,
523
524                    // Concat always produces String
525                    BinaryOpKind::Concat => LogosType::String,
526
527                    // `a followed by b` — a sequence of the same type as the operands.
528                    BinaryOpKind::SeqConcat => self.infer_expr_with(left, interner, field),
529
530                    // Bitwise ops always produce Int
531                    // `& | ^` on Sets yield a Set of the left operand's type;
532                    // on ints they stay Int.
533                    BinaryOpKind::BitAnd | BinaryOpKind::BitOr => {
534                        let lt = self.infer_expr_with(left, interner, field);
535                        if matches!(lt, LogosType::Set(_)) {
536                            lt
537                        } else {
538                            LogosType::Int
539                        }
540                    }
541                    BinaryOpKind::BitXor | BinaryOpKind::Shl | BinaryOpKind::Shr => LogosType::Int,
542
543                    // Add: could be numeric or string concatenation
544                    BinaryOpKind::Add => {
545                        let lt = self.infer_expr_with(left, interner, field);
546                        let rt = self.infer_expr_with(right, interner, field);
547                        if lt.is_string() || rt.is_string() {
548                            LogosType::String
549                        } else {
550                            LogosType::numeric_promotion(&lt, &rt)
551                        }
552                    }
553
554                    // Exact division always yields a Rational (`7 / 2 → 7/2`); the
555                    // resolve pass only emits it in a Rational-typed context.
556                    BinaryOpKind::ExactDivide => LogosType::Rational,
557
558                    // Other arithmetic: numeric promotion
559                    BinaryOpKind::Subtract
560                    | BinaryOpKind::Pow
561                    | BinaryOpKind::Multiply
562                    | BinaryOpKind::Divide
563                    | BinaryOpKind::FloorDivide
564                    | BinaryOpKind::Modulo => {
565                        let lt = self.infer_expr_with(left, interner, field);
566                        let rt = self.infer_expr_with(right, interner, field);
567                        let promoted = LogosType::numeric_promotion(&lt, &rt);
568                        // Decimal division widens to an exact Rational (base-10 division need
569                        // not terminate); `+ − ×` keep it Decimal. Complex stays Complex.
570                        if matches!(op, BinaryOpKind::Divide) && promoted == LogosType::Decimal {
571                            LogosType::Rational
572                        } else {
573                            promoted
574                        }
575                    }
576                }
577            }
578
579            // `not x` — logical negation of truthiness, Bool out (`~` is the bitwise complement).
580            Expr::Not { .. } => LogosType::Bool,
581
582            Expr::Length { .. } => LogosType::Int,
583
584            Expr::Call { function, args } => {
585                let name = interner.resolve(*function);
586                match name {
587                    "pow"
588                        if self.lookup_fn(*function).is_none()
589                            || self.native_functions.contains(function) =>
590                    {
591                        match args.as_slice() {
592                            [base, exponent] => {
593                                let base = self.infer_expr_with(base, interner, field);
594                                let exponent = self.infer_expr_with(exponent, interner, field);
595                                if base == LogosType::Modular && exponent == LogosType::Int {
596                                    LogosType::Modular
597                                } else {
598                                    LogosType::numeric_promotion(&base, &exponent)
599                                }
600                            }
601                            _ => LogosType::Unknown,
602                        }
603                    }
604                    "sqrt" | "parseFloat" => LogosType::Float,
605                    "decimal" => LogosType::Decimal,
606                    "complex" => LogosType::Complex,
607                    "modular" => LogosType::Modular,
608                    // `quantity(value, "unit")` and `convert(q, "unit")` both yield a Quantity.
609                    "quantity" | "convert" => LogosType::Quantity,
610                    "money" => LogosType::Money,
611                    // `<money> in EUR` desugars to `to_currency(money, "EUR")` — still Money.
612                    "to_currency" => LogosType::Money,
613                    // UUID constructors all yield a Uuid; `uuid_version` reads its version nibble.
614                    "uuid" | "uuid_nil" | "uuid_max" | "uuid_v1" | "uuid_v3" | "uuid_v4"
615                    | "uuid_v5" | "uuid_v6" | "uuid_v7" | "uuid_v8" | "uuid_dns" | "uuid_url"
616                    | "uuid_oid" | "uuid_x500" => LogosType::Uuid,
617                    "uuid_version" => LogosType::Int,
618                    // Byte-level primitives for the Logos-written UUID constructors: hashes and byte
619                    // views are `Seq of Int`; `uuid_from_bytes` rebuilds a Uuid.
620                    "md5" | "sha1" | "text_bytes" | "uuid_bytes" => {
621                        LogosType::Seq(Box::new(LogosType::Int))
622                    }
623                    "readReals" => LogosType::Seq(Box::new(LogosType::Float)),
624                    "uuid_from_bytes" => LogosType::Uuid,
625                    "set_rate" | "set_rates" => LogosType::Unit,
626                    "parse_timestamp" => LogosType::Moment,
627                    "format_timestamp" => LogosType::String,
628                    // The byte→Text builtin (the inverse of `text_bytes`): rebuilds a `String` from a
629                    // `Seq of Int` of UTF-8 bytes. Typing it lets a `Let s be text_from_bytes(bs)` binding
630                    // know `s` is a non-Copy `String`, so the AOT value-copy clone fires (a bare move would
631                    // strand a later read of `s` as a use-after-move).
632                    "text_from_bytes" => LogosType::String,
633                    "year_of" | "month_of" | "day_of" | "weekday_of" | "hour_of" | "minute_of"
634                    | "second_of" | "week_of" | "quarter_of" => LogosType::Int,
635                    "date_of" => LogosType::Date,
636                    "time_of" => LogosType::Time,
637                    "makeDate" => LogosType::Date,
638                    "makeMoment" => LogosType::Moment,
639                    "seconds_between" | "months_between" | "years_between" => LogosType::Int,
640                    "add_seconds" => LogosType::Moment,
641                    "in_zone" => LogosType::String,
642                    "local_instant" => LogosType::Moment,
643                    "parseInt" | "floor" | "ceil" | "round" => LogosType::Int,
644                    "abs" | "min" | "max" => {
645                        // Preserves type of arguments — infer from first arg
646                        if let Some(first) = args.first() {
647                            self.infer_expr_with(first, interner, field)
648                        } else {
649                            LogosType::Unknown
650                        }
651                    }
652                    // `{k: v, …}` desugars to `mapOf(k, v, …)` (flat pairs) — a Map of the first
653                    // pair's key/value types; `{a, …}` to `setOf(a, …)` — a Set of the first
654                    // element's type. Typing the literal lets numeric key coercion and element
655                    // reads specialise.
656                    "mapOf" => match (args.first(), args.get(1)) {
657                        (Some(k), Some(v)) => LogosType::Map(
658                            Box::new(self.infer_expr_with(k, interner, field)),
659                            Box::new(self.infer_expr_with(v, interner, field)),
660                        ),
661                        _ => LogosType::Unknown,
662                    },
663                    "setOf" => match args.first() {
664                        Some(e) => LogosType::Set(Box::new(self.infer_expr_with(e, interner, field))),
665                        None => LogosType::Unknown,
666                    },
667                    _ => {
668                        // Look up function signature
669                        if let Some(sig) = self.lookup_fn(*function) {
670                            sig.return_type.clone()
671                        } else {
672                            LogosType::Unknown
673                        }
674                    }
675                }
676            }
677
678            Expr::Index { collection, .. } => {
679                let coll_ty = self.infer_expr_with(collection, interner, field);
680                match &coll_ty {
681                    LogosType::Seq(inner) => (**inner).clone(),
682                    LogosType::Map(_, v) => (**v).clone(),
683                    _ => LogosType::Unknown,
684                }
685            }
686
687            Expr::List(items) => {
688                let mut types = items.iter().map(|e| self.infer_expr_with(e, interner, field));
689                let first = types.next().unwrap_or(LogosType::Unknown);
690                let elem_type = types.try_fold(first.clone(), |held, t| LogosType::number_join(&held, &t)).unwrap_or(first);
691                LogosType::Seq(Box::new(elem_type))
692            }
693
694            Expr::New {
695                type_name,
696                type_args,
697                ..
698            } => {
699                let name = interner.resolve(*type_name);
700                match name {
701                    "Seq" | "List" | "Vec" => {
702                        let elem = type_args
703                            .first()
704                            .map(|t| LogosType::from_type_expr(t, interner))
705                            .unwrap_or(LogosType::Unit);
706                        LogosType::Seq(Box::new(elem))
707                    }
708                    "Map" | "HashMap" => {
709                        let key = type_args
710                            .first()
711                            .map(|t| LogosType::from_type_expr(t, interner))
712                            .unwrap_or(LogosType::String);
713                        let val = type_args
714                            .get(1)
715                            .map(|t| LogosType::from_type_expr(t, interner))
716                            .unwrap_or(LogosType::String);
717                        LogosType::Map(Box::new(key), Box::new(val))
718                    }
719                    "Set" | "HashSet" => {
720                        let elem = type_args
721                            .first()
722                            .map(|t| LogosType::from_type_expr(t, interner))
723                            .unwrap_or(LogosType::Unit);
724                        LogosType::Set(Box::new(elem))
725                    }
726                    _ => LogosType::Unknown,
727                }
728            }
729
730            Expr::FieldAccess { .. } => field(expr).unwrap_or(LogosType::Unknown),
731
732            Expr::OptionSome { value } => {
733                let inner = self.infer_expr_with(value, interner, field);
734                LogosType::Option(Box::new(inner))
735            }
736
737            Expr::OptionNone => LogosType::Option(Box::new(LogosType::Unknown)),
738
739            Expr::Range { .. } => LogosType::Seq(Box::new(LogosType::Int)),
740
741            Expr::Contains { .. } => LogosType::Bool,
742
743            Expr::Copy { expr: inner } | Expr::Give { value: inner } => {
744                self.infer_expr_with(inner, interner, field)
745            }
746
747            Expr::WithCapacity { value, .. } => self.infer_expr_with(value, interner, field),
748
749            _ => LogosType::Unknown,
750        }
751    }
752
753    /// Build a TypeEnv from a program's statements via a single forward pass.
754    ///
755    /// For each statement, registers variable types and function signatures
756    /// into the environment. Since LOGOS programs are forward-declared,
757    /// no fixpoint iteration is needed.
758    pub fn infer_program(stmts: &[Stmt], interner: &Interner, _registry: &TypeRegistry) -> Self {
759        let mut env = Self::new();
760        env.infer_stmts(stmts, interner);
761        env
762    }
763
764    /// Walk a slice of statements, registering types.
765    fn infer_stmts(&mut self, stmts: &[Stmt], interner: &Interner) {
766        for stmt in stmts {
767            self.infer_stmt(stmt, interner);
768        }
769    }
770
771    /// Infer types from a single statement.
772    fn infer_stmt(&mut self, stmt: &Stmt, interner: &Interner) {
773        match stmt {
774            Stmt::Let { var, ty, value, .. } => {
775                let inferred = if let Some(type_expr) = ty {
776                    // Explicit type annotation takes priority
777                    let base_ty = LogosType::from_type_expr(type_expr, interner);
778                    if base_ty != LogosType::Unknown {
779                        base_ty
780                    } else {
781                        self.infer_expr(value, interner)
782                    }
783                } else {
784                    self.infer_expr(value, interner)
785                };
786                self.register(*var, inferred);
787            }
788
789            Stmt::Set { target, value } => {
790                // If we don't already have a type for target, infer from value
791                if self.lookup(*target) == &LogosType::Unknown {
792                    let inferred = self.infer_expr(value, interner);
793                    if inferred != LogosType::Unknown {
794                        self.register(*target, inferred);
795                    }
796                }
797            }
798
799            Stmt::FunctionDef {
800                name,
801                params,
802                body,
803                return_type,
804                is_native,
805                ..
806            } => {
807                // Register parameter types
808                let param_types: Vec<(Symbol, LogosType)> = params
809                    .iter()
810                    .map(|(sym, ty)| (*sym, LogosType::from_type_expr(ty, interner)))
811                    .collect();
812
813                // Register params in the env for body inference
814                for (sym, ty) in &param_types {
815                    self.register(*sym, ty.clone());
816                }
817
818                // Infer body
819                self.infer_stmts(body, interner);
820
821                // Determine return type
822                let ret_ty = if let Some(rt) = return_type {
823                    LogosType::from_type_expr(rt, interner)
824                } else {
825                    self.infer_return_type(body, interner)
826                };
827
828                self.register_fn(
829                    *name,
830                    FnSig {
831                        params: param_types,
832                        return_type: ret_ty,
833                    },
834                );
835                self.set_native_fn(*name, *is_native);
836            }
837
838            Stmt::Repeat {
839                pattern,
840                iterable,
841                body,
842            } => {
843                // Infer the element type from the iterable
844                let iterable_ty = self.infer_expr(iterable, interner);
845                let elem_ty = match &iterable_ty {
846                    LogosType::Seq(inner) => (**inner).clone(),
847                    LogosType::Set(inner) => (**inner).clone(),
848                    LogosType::Map(k, _v) => (**k).clone(),
849                    _ => LogosType::Unknown,
850                };
851                match pattern {
852                    crate::ast::stmt::Pattern::Identifier(sym) => {
853                        self.register(*sym, elem_ty);
854                    }
855                    crate::ast::stmt::Pattern::Tuple(syms) => {
856                        // For tuple destructuring, we don't have enough info
857                        for sym in syms {
858                            self.register(*sym, LogosType::Unknown);
859                        }
860                    }
861                }
862                self.infer_stmts(body, interner);
863            }
864
865            Stmt::If {
866                then_block,
867                else_block,
868                ..
869            } => {
870                self.infer_stmts(then_block, interner);
871                if let Some(else_b) = else_block {
872                    self.infer_stmts(else_b, interner);
873                }
874            }
875
876            Stmt::While { body, .. } => {
877                self.infer_stmts(body, interner);
878            }
879
880            Stmt::Inspect { arms, .. } => {
881                for arm in arms {
882                    // Register bindings from pattern match as Unknown
883                    for (_field, binding) in &arm.bindings {
884                        self.register(*binding, LogosType::Unknown);
885                    }
886                    self.infer_stmts(arm.body, interner);
887                }
888            }
889
890            Stmt::Zone { body, .. } => {
891                self.infer_stmts(body, interner);
892            }
893
894            Stmt::ReadFrom { var, .. } => {
895                // ReadFrom always gives String
896                self.register(*var, LogosType::String);
897            }
898
899            Stmt::CreatePipe {
900                var, element_type, ..
901            } => {
902                let elem = LogosType::from_type_name(interner.resolve(*element_type));
903                self.register(*var, elem);
904            }
905
906            Stmt::ReceivePipe { var, .. } | Stmt::TryReceivePipe { var, .. } => {
907                // Pipe receive type depends on pipe type, default to Unknown
908                self.register(*var, LogosType::Unknown);
909            }
910
911            Stmt::Pop {
912                into: Some(var),
913                collection,
914            } => {
915                let coll_ty = self.infer_expr(collection, interner);
916                let elem_ty = coll_ty
917                    .element_type()
918                    .cloned()
919                    .unwrap_or(LogosType::Unknown);
920                self.register(*var, elem_ty);
921            }
922
923            Stmt::AwaitMessage { into, .. } => {
924                self.register(*into, LogosType::Unknown);
925            }
926
927            Stmt::Concurrent { tasks } | Stmt::Parallel { tasks } => {
928                self.infer_stmts(tasks, interner);
929            }
930
931            // A `Reversibly:` block runs its body in the enclosing scope (output-transparent),
932            // so a variable it introduces / retypes is visible after the block — infer through it.
933            Stmt::Reversibly { body } => {
934                self.infer_stmts(body, interner);
935            }
936
937            _ => {}
938        }
939    }
940
941    /// Infer the return type from a function body by scanning Return statements.
942    fn infer_return_type(&self, body: &[Stmt], interner: &Interner) -> LogosType {
943        for stmt in body {
944            if let Stmt::Return { value: Some(expr) } = stmt {
945                return self.infer_expr(expr, interner);
946            }
947        }
948        LogosType::Unit
949    }
950
951    /// Export the type environment as a LogosType map for RefinementContext seeding.
952    pub fn to_logos_type_map(&self) -> HashMap<Symbol, LogosType> {
953        self.variables
954            .iter()
955            .filter(|(_, ty)| **ty != LogosType::Unknown)
956            .map(|(sym, ty)| (*sym, ty.clone()))
957            .collect()
958    }
959
960    /// Convert the type environment to the legacy string-based format.
961    pub fn to_legacy_variable_types(&self) -> HashMap<Symbol, std::string::String> {
962        self.variables
963            .iter()
964            .filter(|(_, ty)| **ty != LogosType::Unknown)
965            .map(|(sym, ty)| (*sym, ty.to_rust_type()))
966            .collect()
967    }
968
969    /// Convert the type environment to the legacy string var set.
970    pub fn to_legacy_string_vars(&self) -> std::collections::HashSet<Symbol> {
971        self.variables
972            .iter()
973            .filter(|(_, ty)| ty.is_string())
974            .map(|(sym, _)| *sym)
975            .collect()
976    }
977}
978
979/// Centralized name resolution for Rust identifier output.
980///
981/// Wraps the interner and ensures all identifier output goes through
982/// keyword escaping. Makes it impossible to forget escaping.
983pub struct RustNames<'a> {
984    interner: &'a Interner,
985}
986
987impl<'a> RustNames<'a> {
988    pub fn new(interner: &'a Interner) -> Self {
989        Self { interner }
990    }
991
992    /// Resolve a symbol to a Rust-safe identifier (always escapes keywords).
993    pub fn ident(&self, sym: Symbol) -> std::string::String {
994        crate::codegen::escape_rust_ident(self.interner.resolve(sym))
995    }
996
997    /// Get the raw name for pattern matching (native functions, type names, etc.).
998    pub fn raw(&self, sym: Symbol) -> &str {
999        self.interner.resolve(sym)
1000    }
1001}
1002
1003#[cfg(test)]
1004#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/analysis/types/tests.rs"]
1005mod tests;