Skip to main content

lex_types/
env.rs

1//! Type environment: type-decl info and value-binding scopes.
2
3use crate::types::*;
4use indexmap::IndexMap;
5
6#[derive(Debug, Clone)]
7pub struct TypeDef {
8    pub params: Vec<String>,
9    pub kind: TypeDefKind,
10}
11
12#[derive(Debug, Clone)]
13pub enum TypeDefKind {
14    /// A union: variant name → optional payload.
15    Union(IndexMap<String, Option<Ty>>),
16    /// A record alias: `type Foo = { x :: Int }` etc.
17    Alias(Ty),
18    /// Built-in opaque (Map, Set, ...).
19    Opaque,
20}
21
22#[derive(Debug, Clone, Default)]
23pub struct TypeEnv {
24    /// Type-name → definition.
25    pub types: IndexMap<String, TypeDef>,
26    /// Constructor name → owning type-name.
27    pub ctor_to_type: IndexMap<String, String>,
28}
29
30impl TypeEnv {
31    pub fn new_with_builtins() -> Self {
32        let mut e = TypeEnv::default();
33        // Result[T, E] = Ok(T) | Err(E)
34        let mut r_variants = IndexMap::new();
35        r_variants.insert("Ok".into(), Some(Ty::Var(0))); // T
36        r_variants.insert("Err".into(), Some(Ty::Var(1))); // E
37        e.types.insert("Result".into(), TypeDef {
38            params: vec!["T".into(), "E".into()],
39            kind: TypeDefKind::Union(r_variants),
40        });
41        e.ctor_to_type.insert("Ok".into(), "Result".into());
42        e.ctor_to_type.insert("Err".into(), "Result".into());
43
44        // Option[T] = Some(T) | None
45        let mut o_variants = IndexMap::new();
46        o_variants.insert("Some".into(), Some(Ty::Var(0))); // T
47        o_variants.insert("None".into(), None);
48        e.types.insert("Option".into(), TypeDef {
49            params: vec!["T".into()],
50            kind: TypeDefKind::Union(o_variants),
51        });
52        e.ctor_to_type.insert("Some".into(), "Option".into());
53        e.ctor_to_type.insert("None".into(), "Option".into());
54
55        // Nil = Unit (alias)
56        e.types.insert("Nil".into(), TypeDef {
57            params: vec![],
58            kind: TypeDefKind::Alias(Ty::Unit),
59        });
60
61        // Map, Set: opaque-ish. We just register the names so they parse as Cons.
62        e.types.insert("Map".into(), TypeDef { params: vec!["K".into(), "V".into()], kind: TypeDefKind::Opaque });
63        e.types.insert("Set".into(), TypeDef { params: vec!["T".into()], kind: TypeDefKind::Opaque });
64
65        // Tz = Utc | Local | Offset(Int) | Iana(Str).
66        // Used by std.datetime; the variant-typed alternative to the
67        // pre-v1 stringly Tz ("UTC" / "Local" / "+05:30" / IANA name).
68        // Registered globally so users don't have to import a module
69        // to mention `Utc` / `Iana("America/New_York")` etc.
70        let mut tz_variants = IndexMap::new();
71        tz_variants.insert("Utc".into(), None);
72        tz_variants.insert("Local".into(), None);
73        tz_variants.insert("Offset".into(), Some(Ty::int()));
74        tz_variants.insert("Iana".into(), Some(Ty::str()));
75        e.types.insert("Tz".into(), TypeDef {
76            params: vec![],
77            kind: TypeDefKind::Union(tz_variants),
78        });
79        for ctor in &["Utc", "Local", "Offset", "Iana"] {
80            e.ctor_to_type.insert((*ctor).into(), "Tz".into());
81        }
82
83        // HttpError = NetworkError(Str) | TimeoutError | TlsError(Str)
84        //           | DecodeError(Str)
85        // Used by std.http; structured failure shape so callers can
86        // discriminate transport vs. timeout vs. TLS vs. body-decode
87        // errors without parsing strings.
88        let mut http_err_variants = IndexMap::new();
89        http_err_variants.insert("NetworkError".into(), Some(Ty::str()));
90        http_err_variants.insert("TimeoutError".into(), None);
91        http_err_variants.insert("TlsError".into(), Some(Ty::str()));
92        http_err_variants.insert("DecodeError".into(), Some(Ty::str()));
93        e.types.insert("HttpError".into(), TypeDef {
94            params: vec![],
95            kind: TypeDefKind::Union(http_err_variants),
96        });
97        for ctor in &["NetworkError", "TimeoutError", "TlsError", "DecodeError"] {
98            e.ctor_to_type.insert((*ctor).into(), "HttpError".into());
99        }
100
101        // HttpRequest = { method, url, headers, body, timeout_ms }.
102        // The std.http request shape. Anonymous record literals coerce
103        // to this nominal alias at every position (per the §3.13
104        // record-coercion rules), so users write
105        // `{ method: "GET", url: u, headers: map.new(), body: None,
106        // timeout_ms: None }` rather than a dedicated constructor —
107        // builders (`http.with_header` etc.) are pure transforms over
108        // the same shape.
109        let mut req_fields = IndexMap::new();
110        req_fields.insert("method".into(), Ty::str());
111        req_fields.insert("url".into(), Ty::str());
112        req_fields.insert("headers".into(), Ty::Con("Map".into(), vec![Ty::str(), Ty::str()]));
113        req_fields.insert("body".into(), Ty::Con("Option".into(), vec![Ty::bytes()]));
114        req_fields.insert("timeout_ms".into(), Ty::Con("Option".into(), vec![Ty::int()]));
115        e.types.insert("HttpRequest".into(), TypeDef {
116            params: vec![],
117            kind: TypeDefKind::Alias(Ty::Record(req_fields)),
118        });
119
120        // HttpResponse = { status, headers, body }. Returned by every
121        // `http.{send,get,post}` happy path; also the input to
122        // `http.{json_body,text_body}`.
123        let mut resp_fields = IndexMap::new();
124        resp_fields.insert("status".into(), Ty::int());
125        resp_fields.insert("headers".into(), Ty::Con("Map".into(), vec![Ty::str(), Ty::str()]));
126        resp_fields.insert("body".into(), Ty::bytes());
127        e.types.insert("HttpResponse".into(), TypeDef {
128            params: vec![],
129            kind: TypeDefKind::Alias(Ty::Record(resp_fields)),
130        });
131
132        // Matrix = { rows :: Int, cols :: Int, data :: List[Float] }.
133        // Used by std.math; runtime values are the F64Array fast lane,
134        // not a real record. The alias makes math.* signatures readable
135        // (`:: Matrix` instead of an inline record) and lets call sites
136        // unify nominally. Field access via `m.rows` would type-check
137        // but fail at runtime — use `math.rows / math.cols / math.get`.
138        let mut mat_fields = IndexMap::new();
139        mat_fields.insert("rows".into(), Ty::int());
140        mat_fields.insert("cols".into(), Ty::int());
141        mat_fields.insert("data".into(), Ty::List(Box::new(Ty::float())));
142        e.types.insert("Matrix".into(), TypeDef {
143            params: vec![],
144            kind: TypeDefKind::Alias(Ty::Record(mat_fields)),
145        });
146
147        e
148    }
149
150    pub fn add_user_type(&mut self, name: &str, decl: lex_ast::TypeDecl) -> Result<(), String> {
151        match &decl.definition {
152            lex_ast::TypeExpr::Union { variants } => {
153                let mut vmap = IndexMap::new();
154                for v in variants {
155                    let payload = v.payload.as_ref().map(|p| ty_from_canon(p, &decl.params));
156                    vmap.insert(v.name.clone(), payload);
157                    self.ctor_to_type.insert(v.name.clone(), name.to_string());
158                }
159                self.types.insert(name.to_string(), TypeDef {
160                    params: decl.params.clone(),
161                    kind: TypeDefKind::Union(vmap),
162                });
163            }
164            other => {
165                let ty = ty_from_canon(other, &decl.params);
166                self.types.insert(name.to_string(), TypeDef {
167                    params: decl.params.clone(),
168                    kind: TypeDefKind::Alias(ty),
169                });
170            }
171        }
172        Ok(())
173    }
174}
175
176/// Convert canonical TypeExpr to internal Ty, treating type params as
177/// fresh-numbered Vars (0..n in declaration order). When instantiating, we
178/// substitute these out.
179pub fn ty_from_canon(t: &lex_ast::TypeExpr, params: &[String]) -> Ty {
180    match t {
181        lex_ast::TypeExpr::Named { name, args } => {
182            // type param?
183            if let Some(idx) = params.iter().position(|p| p == name) {
184                if !args.is_empty() {
185                    // Type params don't take args.
186                    return Ty::Con(name.clone(), args.iter().map(|a| ty_from_canon(a, params)).collect());
187                }
188                return Ty::Var(idx as u32);
189            }
190            // Primitives.
191            match name.as_str() {
192                "Int" => return Ty::int(),
193                "Float" => return Ty::float(),
194                "Bool" => return Ty::bool(),
195                "Str" => return Ty::str(),
196                "Bytes" => return Ty::bytes(),
197                "Unit" | "Nil" => return Ty::Unit,
198                "Never" => return Ty::Never,
199                "List" if args.len() == 1 => return Ty::List(Box::new(ty_from_canon(&args[0], params))),
200                // `Tuple[T0, T1, ...]` is the constructor surface for
201                // tuples; canonicalize to the structural Ty::Tuple so
202                // it unifies with `(T0, T1)` literal-tuple syntax and
203                // with std.tuple's signatures.
204                "Tuple" => return Ty::Tuple(args.iter().map(|a| ty_from_canon(a, params)).collect()),
205                _ => {}
206            }
207            Ty::Con(name.clone(), args.iter().map(|a| ty_from_canon(a, params)).collect())
208        }
209        lex_ast::TypeExpr::Record { fields } => {
210            let mut m = IndexMap::new();
211            for f in fields { m.insert(f.name.clone(), ty_from_canon(&f.ty, params)); }
212            Ty::Record(m)
213        }
214        lex_ast::TypeExpr::Tuple { items } => Ty::Tuple(items.iter().map(|t| ty_from_canon(t, params)).collect()),
215        lex_ast::TypeExpr::Function { params: ps, effects, ret } => {
216            let effs = EffectSet {
217                concrete: {
218                    let mut s = std::collections::BTreeSet::new();
219                    for e in effects { s.insert(e.name.clone()); }
220                    s
221                },
222                var: None,
223            };
224            Ty::Function {
225                params: ps.iter().map(|t| ty_from_canon(t, params)).collect(),
226                effects: effs,
227                ret: Box::new(ty_from_canon(ret, params)),
228            }
229        }
230        lex_ast::TypeExpr::Union { .. } => {
231            // Unions on the RHS of type-decls; not in arbitrary positions.
232            Ty::Unit
233        }
234    }
235}