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        // SqlParam = PStr(Str) | PInt(Int) | PFloat(Float) | PBool(Bool) | PNull
66        // Typed parameter binding for std.sql (#362). Replaces the v1 List[Str]
67        // approach so callers don't have to stringify non-string values.
68        let mut sp_variants = IndexMap::new();
69        sp_variants.insert("PStr".into(),   Some(Ty::str()));
70        sp_variants.insert("PInt".into(),   Some(Ty::int()));
71        sp_variants.insert("PFloat".into(), Some(Ty::Con("Float".into(), vec![])));
72        sp_variants.insert("PBool".into(),  Some(Ty::Con("Bool".into(), vec![])));
73        sp_variants.insert("PNull".into(),  None);
74        e.types.insert("SqlParam".into(), TypeDef {
75            params: vec![],
76            kind: TypeDefKind::Union(sp_variants),
77        });
78        for ctor in &["PStr", "PInt", "PFloat", "PBool", "PNull"] {
79            e.ctor_to_type.insert((*ctor).into(), "SqlParam".into());
80        }
81
82        // SqlTx: opaque transaction handle (#362). Backed by the same
83        // Int registry key as Db; the type system enforces that commit/
84        // rollback can only be called on a value from sql.begin, not on
85        // a raw Db connection.
86        e.types.insert("SqlTx".into(), TypeDef { params: vec![], kind: TypeDefKind::Opaque });
87
88        // Iter[T]: lazy positional iterator (#364). Backed at runtime by a
89        // (List[T], Int) tuple; the Int is the current cursor index. All
90        // iter.* operations are compiler-inlined so no effect is needed.
91        e.types.insert("Iter".into(), TypeDef { params: vec!["T".into()], kind: TypeDefKind::Opaque });
92
93        // Stream[T]: opaque streaming iterator (#305 slice 3).
94        // Built and consumed exclusively through the `stream.*` and
95        // `agent.cloud_stream` effect builtins; the runtime
96        // represents a Stream value as an opaque variant carrying a
97        // handle id. Registered as Opaque so type-checking knows
98        // `Stream[Str]` parses but doesn't unwrap it structurally.
99        e.types.insert("Stream".into(), TypeDef { params: vec!["T".into()], kind: TypeDefKind::Opaque });
100
101        // Tz = Utc | Local | Offset(Int) | Iana(Str).
102        // Used by std.datetime; the variant-typed alternative to the
103        // pre-v1 stringly Tz ("UTC" / "Local" / "+05:30" / IANA name).
104        // Registered globally so users don't have to import a module
105        // to mention `Utc` / `Iana("America/New_York")` etc.
106        let mut tz_variants = IndexMap::new();
107        tz_variants.insert("Utc".into(), None);
108        tz_variants.insert("Local".into(), None);
109        tz_variants.insert("Offset".into(), Some(Ty::int()));
110        tz_variants.insert("Iana".into(), Some(Ty::str()));
111        e.types.insert("Tz".into(), TypeDef {
112            params: vec![],
113            kind: TypeDefKind::Union(tz_variants),
114        });
115        for ctor in &["Utc", "Local", "Offset", "Iana"] {
116            e.ctor_to_type.insert((*ctor).into(), "Tz".into());
117        }
118
119        // HttpError = NetworkError(Str) | TimeoutError | TlsError(Str)
120        //           | DecodeError(Str)
121        // Used by std.http; structured failure shape so callers can
122        // discriminate transport vs. timeout vs. TLS vs. body-decode
123        // errors without parsing strings.
124        let mut http_err_variants = IndexMap::new();
125        http_err_variants.insert("NetworkError".into(), Some(Ty::str()));
126        http_err_variants.insert("TimeoutError".into(), None);
127        http_err_variants.insert("TlsError".into(), Some(Ty::str()));
128        http_err_variants.insert("DecodeError".into(), Some(Ty::str()));
129        e.types.insert("HttpError".into(), TypeDef {
130            params: vec![],
131            kind: TypeDefKind::Union(http_err_variants),
132        });
133        for ctor in &["NetworkError", "TimeoutError", "TlsError", "DecodeError"] {
134            e.ctor_to_type.insert((*ctor).into(), "HttpError".into());
135        }
136
137        // HttpRequest = { method, url, headers, body, timeout_ms }.
138        // The std.http request shape. Anonymous record literals coerce
139        // to this nominal alias at every position (per the §3.13
140        // record-coercion rules), so users write
141        // `{ method: "GET", url: u, headers: map.new(), body: None,
142        // timeout_ms: None }` rather than a dedicated constructor —
143        // builders (`http.with_header` etc.) are pure transforms over
144        // the same shape.
145        let mut req_fields = IndexMap::new();
146        req_fields.insert("method".into(), Ty::str());
147        req_fields.insert("url".into(), Ty::str());
148        req_fields.insert("headers".into(), Ty::Con("Map".into(), vec![Ty::str(), Ty::str()]));
149        req_fields.insert("body".into(), Ty::Con("Option".into(), vec![Ty::bytes()]));
150        req_fields.insert("timeout_ms".into(), Ty::Con("Option".into(), vec![Ty::int()]));
151        e.types.insert("HttpRequest".into(), TypeDef {
152            params: vec![],
153            kind: TypeDefKind::Alias(Ty::Record(req_fields)),
154        });
155
156        // HttpResponse = { status, headers, body }. Returned by every
157        // `http.{send,get,post}` happy path; also the input to
158        // `http.{json_body,text_body}`.
159        let mut resp_fields = IndexMap::new();
160        resp_fields.insert("status".into(), Ty::int());
161        resp_fields.insert("headers".into(), Ty::Con("Map".into(), vec![Ty::str(), Ty::str()]));
162        resp_fields.insert("body".into(), Ty::bytes());
163        e.types.insert("HttpResponse".into(), TypeDef {
164            params: vec![],
165            kind: TypeDefKind::Alias(Ty::Record(resp_fields)),
166        });
167
168        // Matrix = { rows :: Int, cols :: Int, data :: List[Float] }.
169        // Used by std.math; runtime values are the F64Array fast lane,
170        // not a real record. The alias makes math.* signatures readable
171        // (`:: Matrix` instead of an inline record) and lets call sites
172        // unify nominally. Field access via `m.rows` would type-check
173        // but fail at runtime — use `math.rows / math.cols / math.get`.
174        let mut mat_fields = IndexMap::new();
175        mat_fields.insert("rows".into(), Ty::int());
176        mat_fields.insert("cols".into(), Ty::int());
177        mat_fields.insert("data".into(), Ty::List(Box::new(Ty::float())));
178        e.types.insert("Matrix".into(), TypeDef {
179            params: vec![],
180            kind: TypeDefKind::Alias(Ty::Record(mat_fields)),
181        });
182
183        // Request = { method :: Str, path :: Str, query :: Str, body :: Str,
184        //             headers :: Map[Str, Str] }
185        // Inbound request shape used by net.serve_fn handlers.
186        let mut net_req_fields = IndexMap::new();
187        net_req_fields.insert("method".into(), Ty::str());
188        net_req_fields.insert("path".into(), Ty::str());
189        net_req_fields.insert("query".into(), Ty::str());
190        net_req_fields.insert("body".into(), Ty::str());
191        net_req_fields.insert("headers".into(), Ty::Con("Map".into(), vec![Ty::str(), Ty::str()]));
192        e.types.insert("Request".into(), TypeDef {
193            params: vec![],
194            kind: TypeDefKind::Alias(Ty::Record(net_req_fields)),
195        });
196
197        // Response = { status :: Int, body :: Str, headers :: Map[Str, Str] }
198        // Outbound response shape returned by net.serve_fn handlers.
199        let mut net_resp_fields = IndexMap::new();
200        net_resp_fields.insert("status".into(), Ty::int());
201        net_resp_fields.insert("body".into(), Ty::str());
202        net_resp_fields.insert("headers".into(), Ty::Con("Map".into(), vec![Ty::str(), Ty::str()]));
203        e.types.insert("Response".into(), TypeDef {
204            params: vec![],
205            kind: TypeDefKind::Alias(Ty::Record(net_resp_fields)),
206        });
207
208        // WsConn = { id :: Str, path :: Str, subprotocol :: Str }
209        // Passed to every net.serve_ws_fn message handler.
210        let mut ws_conn_fields = IndexMap::new();
211        ws_conn_fields.insert("id".into(), Ty::str());
212        ws_conn_fields.insert("path".into(), Ty::str());
213        ws_conn_fields.insert("subprotocol".into(), Ty::str());
214        e.types.insert("WsConn".into(), TypeDef {
215            params: vec![],
216            kind: TypeDefKind::Alias(Ty::Record(ws_conn_fields)),
217        });
218
219        // WsMessage = WsText(Str) | WsBinary(List[Int]) | WsPing | WsClose
220        let mut ws_msg_variants = IndexMap::new();
221        ws_msg_variants.insert("WsText".into(), Some(Ty::str()));
222        ws_msg_variants.insert("WsBinary".into(), Some(Ty::List(Box::new(Ty::int()))));
223        ws_msg_variants.insert("WsPing".into(), None);
224        ws_msg_variants.insert("WsClose".into(), None);
225        e.types.insert("WsMessage".into(), TypeDef {
226            params: vec![],
227            kind: TypeDefKind::Union(ws_msg_variants),
228        });
229        for ctor in &["WsText", "WsBinary", "WsPing", "WsClose"] {
230            e.ctor_to_type.insert((*ctor).into(), "WsMessage".into());
231        }
232
233        // WsAction = WsSend(Str) | WsSendBinary(List[Int]) | WsNoOp
234        // Handlers return this to tell the runtime what to send back.
235        // Connection close is handled automatically when the runtime receives
236        // an incoming WsClose frame; handlers do not need to emit a close action.
237        let mut ws_act_variants = IndexMap::new();
238        ws_act_variants.insert("WsSend".into(), Some(Ty::str()));
239        ws_act_variants.insert("WsSendBinary".into(), Some(Ty::List(Box::new(Ty::int()))));
240        ws_act_variants.insert("WsNoOp".into(), None);
241        e.types.insert("WsAction".into(), TypeDef {
242            params: vec![],
243            kind: TypeDefKind::Union(ws_act_variants),
244        });
245        for ctor in &["WsSend", "WsSendBinary", "WsNoOp"] {
246            e.ctor_to_type.insert((*ctor).into(), "WsAction".into());
247        }
248
249        e
250    }
251
252    pub fn add_user_type(&mut self, name: &str, decl: lex_ast::TypeDecl) -> Result<(), String> {
253        match &decl.definition {
254            lex_ast::TypeExpr::Union { variants } => {
255                let mut vmap = IndexMap::new();
256                for v in variants {
257                    let payload = v.payload.as_ref().map(|p| ty_from_canon(p, &decl.params));
258                    vmap.insert(v.name.clone(), payload);
259                    self.ctor_to_type.insert(v.name.clone(), name.to_string());
260                }
261                self.types.insert(name.to_string(), TypeDef {
262                    params: decl.params.clone(),
263                    kind: TypeDefKind::Union(vmap),
264                });
265            }
266            other => {
267                let ty = ty_from_canon_env(other, &decl.params, self);
268                self.types.insert(name.to_string(), TypeDef {
269                    params: decl.params.clone(),
270                    kind: TypeDefKind::Alias(ty),
271                });
272            }
273        }
274        Ok(())
275    }
276}
277
278/// Convert canonical TypeExpr to internal Ty, treating type params as
279/// fresh-numbered Vars (0..n in declaration order). When instantiating, we
280/// substitute these out.
281pub fn ty_from_canon(t: &lex_ast::TypeExpr, params: &[String]) -> Ty {
282    match t {
283        lex_ast::TypeExpr::Named { name, args } => {
284            // type param?
285            if let Some(idx) = params.iter().position(|p| p == name) {
286                if !args.is_empty() {
287                    // Type params don't take args.
288                    return Ty::Con(name.clone(), args.iter().map(|a| ty_from_canon(a, params)).collect());
289                }
290                return Ty::Var(idx as u32);
291            }
292            // Primitives.
293            match name.as_str() {
294                "Int" => return Ty::int(),
295                "Float" => return Ty::float(),
296                "Bool" => return Ty::bool(),
297                "Str" => return Ty::str(),
298                "Bytes" => return Ty::bytes(),
299                "Unit" | "Nil" => return Ty::Unit,
300                "Never" => return Ty::Never,
301                "List" if args.len() == 1 => return Ty::List(Box::new(ty_from_canon(&args[0], params))),
302                // `Tuple[T0, T1, ...]` is the constructor surface for
303                // tuples; canonicalize to the structural Ty::Tuple so
304                // it unifies with `(T0, T1)` literal-tuple syntax and
305                // with std.tuple's signatures.
306                "Tuple" => return Ty::Tuple(args.iter().map(|a| ty_from_canon(a, params)).collect()),
307                _ => {}
308            }
309            Ty::Con(name.clone(), args.iter().map(|a| ty_from_canon(a, params)).collect())
310        }
311        lex_ast::TypeExpr::Record { fields } => {
312            let mut m = IndexMap::new();
313            for f in fields { m.insert(f.name.clone(), ty_from_canon(&f.ty, params)); }
314            Ty::Record(m)
315        }
316        lex_ast::TypeExpr::Tuple { items } => Ty::Tuple(items.iter().map(|t| ty_from_canon(t, params)).collect()),
317        lex_ast::TypeExpr::Function { params: ps, effects, ret } => {
318            // Plumb effect args (#207).
319            let effs = EffectSet {
320                concrete: {
321                    let mut s = std::collections::BTreeSet::new();
322                    for e in effects {
323                        let arg = e.arg.as_ref().map(|a| match a {
324                            lex_ast::EffectArg::Str { value } => crate::types::EffectArg::Str(value.clone()),
325                            lex_ast::EffectArg::Int { value } => crate::types::EffectArg::Int(*value),
326                            lex_ast::EffectArg::Ident { value } => crate::types::EffectArg::Ident(value.clone()),
327                        });
328                        s.insert(crate::types::EffectKind { name: e.name.clone(), arg });
329                    }
330                    s
331                },
332                var: None,
333            };
334            Ty::Function {
335                params: ps.iter().map(|t| ty_from_canon(t, params)).collect(),
336                effects: effs,
337                ret: Box::new(ty_from_canon(ret, params)),
338            }
339        }
340        lex_ast::TypeExpr::Union { .. } => {
341            // Unions on the RHS of type-decls; not in arbitrary positions.
342            Ty::Unit
343        }
344        lex_ast::TypeExpr::Refined { base, .. } => {
345            // #209 slice 1: refinement types unify structurally as
346            // their base type. The predicate is parsed and stored in
347            // the AST (so `lex-vcs` content-addressing picks up
348            // refinement edits), but static discharge and runtime
349            // residual checks land in slices 2 and 3 of #209. The
350            // unification behavior here means a function declaring
351            // `Int{x | x > 0}` interoperates with plain `Int` callers
352            // — the predicate is informational until discharge is
353            // wired up.
354            ty_from_canon(base, params)
355        }
356        lex_ast::TypeExpr::RecordWithSpreads { .. } => {
357            // Caller should use ty_from_canon_env for spread resolution.
358            Ty::Unit
359        }
360    }
361}
362
363/// Like `ty_from_canon` but resolves `RecordWithSpreads` by looking up base
364/// type names in `env`. Called from `add_user_type` and `function_scheme` so
365/// that `{ ...Post, extra :: Int }` expands to a flat `Ty::Record`.
366pub fn ty_from_canon_env(t: &lex_ast::TypeExpr, params: &[String], env: &TypeEnv) -> Ty {
367    match t {
368        lex_ast::TypeExpr::RecordWithSpreads { spreads, fields } => {
369            let mut m = IndexMap::new();
370            for spread_name in spreads {
371                if let Some(td) = env.types.get(spread_name.as_str()) {
372                    if let TypeDefKind::Alias(Ty::Record(spread_fields)) = &td.kind {
373                        for (k, v) in spread_fields {
374                            m.insert(k.clone(), v.clone());
375                        }
376                    }
377                }
378            }
379            for f in fields {
380                m.insert(f.name.clone(), ty_from_canon_env(&f.ty, params, env));
381            }
382            Ty::Record(m)
383        }
384        other => ty_from_canon(other, params),
385    }
386}