lex-types 0.11.60

Type system + effect inference for Lex.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
//! Type environment: type-decl info and value-binding scopes.

use crate::types::*;
use indexmap::IndexMap;

#[derive(Debug, Clone)]
pub struct TypeDef {
    pub params: Vec<String>,
    pub kind: TypeDefKind,
}

#[derive(Debug, Clone)]
pub enum TypeDefKind {
    /// A union: variant name → optional payload.
    Union(IndexMap<String, Option<Ty>>),
    /// A record alias: `type Foo = { x :: Int }` etc.
    Alias(Ty),
    /// Built-in opaque (Map, Set, ...).
    Opaque,
}

#[derive(Debug, Clone, Default)]
pub struct TypeEnv {
    /// Type-name → definition.
    pub types: IndexMap<String, TypeDef>,
    /// Constructor name → owning type-name.
    pub ctor_to_type: IndexMap<String, String>,
    /// Import alias → dependency module mangle prefix (#963). When a dependency
    /// is resolved as a whole package, its types are registered under canonical
    /// prefix names (`error_<hash>.DbErr`); this maps an import alias `e` to
    /// that prefix so an alias-qualified annotation `e.DbErr` is normalized to
    /// the same canonical `Con` in [`ty_from_canon_env`] — making a
    /// directly-imported module and the copies inlined into its sibling modules
    /// one type. Empty in the ordinary (inlined / no-dependency) case.
    pub dep_alias_prefixes: IndexMap<String, String>,
}

impl TypeEnv {
    pub fn new_with_builtins() -> Self {
        let mut e = TypeEnv::default();
        // Result[T, E] = Ok(T) | Err(E)
        let mut r_variants = IndexMap::new();
        r_variants.insert("Ok".into(), Some(Ty::Var(0))); // T
        r_variants.insert("Err".into(), Some(Ty::Var(1))); // E
        e.types.insert("Result".into(), TypeDef {
            params: vec!["T".into(), "E".into()],
            kind: TypeDefKind::Union(r_variants),
        });
        e.ctor_to_type.insert("Ok".into(), "Result".into());
        e.ctor_to_type.insert("Err".into(), "Result".into());

        // Option[T] = Some(T) | None
        let mut o_variants = IndexMap::new();
        o_variants.insert("Some".into(), Some(Ty::Var(0))); // T
        o_variants.insert("None".into(), None);
        e.types.insert("Option".into(), TypeDef {
            params: vec!["T".into()],
            kind: TypeDefKind::Union(o_variants),
        });
        e.ctor_to_type.insert("Some".into(), "Option".into());
        e.ctor_to_type.insert("None".into(), "Option".into());

        // Nil = Unit (alias)
        e.types.insert("Nil".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Alias(Ty::Unit),
        });

        // Map, Set: opaque-ish. We just register the names so they parse as Cons.
        e.types.insert("Map".into(), TypeDef { params: vec!["K".into(), "V".into()], kind: TypeDefKind::Opaque });
        e.types.insert("Set".into(), TypeDef { params: vec!["T".into()], kind: TypeDefKind::Opaque });

        // SqlParam = PStr(Str) | PInt(Int) | PFloat(Float) | PBool(Bool) | PNull
        // Typed parameter binding for std.sql (#362). Replaces the v1 List[Str]
        // approach so callers don't have to stringify non-string values.
        let mut sp_variants = IndexMap::new();
        sp_variants.insert("PStr".into(),   Some(Ty::str()));
        sp_variants.insert("PInt".into(),   Some(Ty::int()));
        sp_variants.insert("PFloat".into(), Some(Ty::float()));
        sp_variants.insert("PBool".into(),  Some(Ty::bool()));
        sp_variants.insert("PNull".into(),  None);
        e.types.insert("SqlParam".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Union(sp_variants),
        });
        for ctor in &["PStr", "PInt", "PFloat", "PBool", "PNull"] {
            e.ctor_to_type.insert((*ctor).into(), "SqlParam".into());
        }

        // SqlTx: opaque transaction handle (#362). Backed by the same
        // Int registry key as Db; the type system enforces that commit/
        // rollback can only be called on a value from sql.begin, not on
        // a raw Db connection.
        e.types.insert("SqlTx".into(), TypeDef { params: vec![], kind: TypeDefKind::Opaque });

        // SqlError = { message :: Str, code :: Option[Str], detail :: Option[Str] }
        // Structured error shape returned by every `std.sql` op (#380).
        // `code` carries the SQLSTATE (Postgres) or the symbolic SQLite
        // error name (`SQLITE_BUSY`, `SQLITE_CONSTRAINT_UNIQUE`, …) so
        // dialect-aware retry / conflict-handling can avoid string
        // parsing. `message` is always populated; `detail` carries a
        // driver-side detail string when present.
        let mut se_fields = IndexMap::new();
        se_fields.insert("message".into(), Ty::str());
        se_fields.insert("code".into(), Ty::Con("Option".into(), vec![Ty::str()]));
        se_fields.insert("detail".into(), Ty::Con("Option".into(), vec![Ty::str()]));
        e.types.insert("SqlError".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Alias(Ty::Record(se_fields)),
        });

        // AeadResult = { ciphertext :: Bytes, tag :: Bytes } — return
        // shape for every AEAD seal op in `std.crypto` (#382 AEAD slice).
        // The auth tag is split out from the ciphertext so callers don't
        // have to know each algorithm's tag length: AES-GCM and
        // ChaCha20-Poly1305 both happen to be 16 bytes today, but the
        // shape keeps that detail encapsulated.
        let mut ar_fields = IndexMap::new();
        ar_fields.insert("ciphertext".into(), Ty::bytes());
        ar_fields.insert("tag".into(), Ty::bytes());
        e.types.insert("AeadResult".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Alias(Ty::Record(ar_fields)),
        });

        // UdpDatagram = { data :: Bytes, host :: Str, port :: Int } —
        // what `net.udp_recv` hands back (#760).
        //
        // The sender's address is part of the value rather than something
        // the caller has to ask for separately, because with UDP it is not
        // optional detail: any host can send to an open socket, so a reply
        // that does not carry who sent it cannot be safely acted on. A
        // request/response caller must check it matches who they asked.
        let mut dg_fields = IndexMap::new();
        dg_fields.insert("data".into(), Ty::bytes());
        dg_fields.insert("host".into(), Ty::str());
        dg_fields.insert("port".into(), Ty::int());
        e.types.insert("UdpDatagram".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Alias(Ty::Record(dg_fields)),
        });

        // Iter[T]: lazy positional iterator (#364). Backed at runtime by a
        // (List[T], Int) tuple; the Int is the current cursor index. All
        // iter.* operations are compiler-inlined so no effect is needed.
        e.types.insert("Iter".into(), TypeDef { params: vec!["T".into()], kind: TypeDefKind::Opaque });

        // Stream[T]: opaque streaming iterator (#305 slice 3).
        // Built and consumed exclusively through the `stream.*` and
        // `agent.cloud_stream` effect builtins; the runtime
        // represents a Stream value as an opaque variant carrying a
        // handle id. Registered as Opaque so type-checking knows
        // `Stream[Str]` parses but doesn't unwrap it structurally.
        e.types.insert("Stream".into(), TypeDef { params: vec!["T".into()], kind: TypeDefKind::Opaque });

        // Tz = Utc | Local | Offset(Int) | Iana(Str).
        // Used by std.datetime; the variant-typed alternative to the
        // pre-v1 stringly Tz ("UTC" / "Local" / "+05:30" / IANA name).
        // Registered globally so users don't have to import a module
        // to mention `Utc` / `Iana("America/New_York")` etc.
        let mut tz_variants = IndexMap::new();
        tz_variants.insert("Utc".into(), None);
        tz_variants.insert("Local".into(), None);
        tz_variants.insert("Offset".into(), Some(Ty::int()));
        tz_variants.insert("Iana".into(), Some(Ty::str()));
        e.types.insert("Tz".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Union(tz_variants),
        });
        for ctor in &["Utc", "Local", "Offset", "Iana"] {
            e.ctor_to_type.insert((*ctor).into(), "Tz".into());
        }

        // HttpError = NetworkError(Str) | TimeoutError | TlsError(Str)
        //           | DecodeError(Str)
        // Used by std.http; structured failure shape so callers can
        // discriminate transport vs. timeout vs. TLS vs. body-decode
        // errors without parsing strings.
        let mut http_err_variants = IndexMap::new();
        http_err_variants.insert("NetworkError".into(), Some(Ty::str()));
        http_err_variants.insert("TimeoutError".into(), None);
        http_err_variants.insert("TlsError".into(), Some(Ty::str()));
        http_err_variants.insert("DecodeError".into(), Some(Ty::str()));
        e.types.insert("HttpError".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Union(http_err_variants),
        });
        for ctor in &["NetworkError", "TimeoutError", "TlsError", "DecodeError"] {
            e.ctor_to_type.insert((*ctor).into(), "HttpError".into());
        }

        // Json = JNull | JBool(Bool) | JInt(Int) | JFloat(Float)
        //      | JStr(Str) | JList(List[Json]) | JObj(List[(Str, Json)])
        // The generic JSON value ADT produced by `std.json.decode` and
        // consumed by `std.json.encode`. Structurally identical to
        // lex-schema's `json_value.Json`, so the native builtins are a
        // drop-in for that interpreted parser. Registered globally (like
        // Tz/HttpError) so a program can pattern-match `Json` without an
        // extra type import. Recursive payloads reference the type by
        // name via `Ty::Con("Json", [])`.
        let json_ty = || Ty::Con("Json".into(), vec![]);
        let mut json_variants = IndexMap::new();
        json_variants.insert("JNull".into(), None);
        json_variants.insert("JBool".into(), Some(Ty::bool()));
        json_variants.insert("JInt".into(), Some(Ty::int()));
        json_variants.insert("JFloat".into(), Some(Ty::float()));
        json_variants.insert("JStr".into(), Some(Ty::str()));
        json_variants.insert("JList".into(), Some(Ty::List(Box::new(json_ty()))));
        json_variants.insert(
            "JObj".into(),
            Some(Ty::List(Box::new(Ty::Tuple(vec![Ty::str(), json_ty()])))),
        );
        e.types.insert("Json".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Union(json_variants),
        });
        for ctor in &["JNull", "JBool", "JInt", "JFloat", "JStr", "JList", "JObj"] {
            e.ctor_to_type.insert((*ctor).into(), "Json".into());
        }

        // HttpRequest = { method, url, headers, body, timeout_ms }.
        // The std.http request shape. Anonymous record literals coerce
        // to this nominal alias at every position (per the §3.13
        // record-coercion rules), so users write
        // `{ method: "GET", url: u, headers: map.new(), body: None,
        // timeout_ms: None }` rather than a dedicated constructor —
        // builders (`http.with_header` etc.) are pure transforms over
        // the same shape.
        let mut req_fields = IndexMap::new();
        req_fields.insert("method".into(), Ty::str());
        req_fields.insert("url".into(), Ty::str());
        req_fields.insert("headers".into(), Ty::Con("Map".into(), vec![Ty::str(), Ty::str()]));
        req_fields.insert("body".into(), Ty::Con("Option".into(), vec![Ty::bytes()]));
        req_fields.insert("timeout_ms".into(), Ty::Con("Option".into(), vec![Ty::int()]));
        e.types.insert("HttpRequest".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Alias(Ty::Record(req_fields)),
        });

        // HttpResponse = { status, headers, body }. Returned by every
        // `http.{send,get,post}` happy path; also the input to
        // `http.{json_body,text_body}`.
        let mut resp_fields = IndexMap::new();
        resp_fields.insert("status".into(), Ty::int());
        resp_fields.insert("headers".into(), Ty::Con("Map".into(), vec![Ty::str(), Ty::str()]));
        resp_fields.insert("body".into(), Ty::bytes());
        e.types.insert("HttpResponse".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Alias(Ty::Record(resp_fields)),
        });

        // Matrix = { rows :: Int, cols :: Int, data :: List[Float] }.
        // Used by std.math; runtime values are the F64Array fast lane,
        // not a real record. The alias makes math.* signatures readable
        // (`:: Matrix` instead of an inline record) and lets call sites
        // unify nominally. Field access via `m.rows` would type-check
        // but fail at runtime — use `math.rows / math.cols / math.get`.
        let mut mat_fields = IndexMap::new();
        mat_fields.insert("rows".into(), Ty::int());
        mat_fields.insert("cols".into(), Ty::int());
        mat_fields.insert("data".into(), Ty::List(Box::new(Ty::float())));
        e.types.insert("Matrix".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Alias(Ty::Record(mat_fields)),
        });

        // Request = { method :: Str, path :: Str, query :: Str, body :: Str,
        //             headers :: Map[Str, Str], path_params :: Map[Str, Str] }
        // Inbound request shape used by net.serve_fn handlers.
        // `path_params` is populated by `net.serve_routed` from `:name`
        // segments in the route pattern; empty under `net.serve_fn`.
        let mut net_req_fields = IndexMap::new();
        net_req_fields.insert("method".into(), Ty::str());
        net_req_fields.insert("path".into(), Ty::str());
        net_req_fields.insert("query".into(), Ty::str());
        net_req_fields.insert("body".into(), Ty::str());
        net_req_fields.insert("headers".into(), Ty::Con("Map".into(), vec![Ty::str(), Ty::str()]));
        net_req_fields.insert("path_params".into(), Ty::Con("Map".into(), vec![Ty::str(), Ty::str()]));
        e.types.insert("Request".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Alias(Ty::Record(net_req_fields)),
        });

        // Response = { status :: Int, body :: ResponseBody, headers :: Map[Str, Str] }
        // Outbound response shape returned by net.serve_fn handlers.
        // #375: `body` is now an ADT instead of a bare Str. Streaming
        // variants (BodyStream / BodyBytes) carry an `Iter[T]` that the
        // server drains chunk-by-chunk under chunked transfer-encoding.
        let mut rb_variants = IndexMap::new();
        rb_variants.insert("BodyStr".into(),    Some(Ty::str()));
        rb_variants.insert(
            "BodyStream".into(),
            Some(Ty::Con("Iter".into(), vec![Ty::str()])),
        );
        rb_variants.insert(
            "BodyBytes".into(),
            Some(Ty::Con("Iter".into(), vec![Ty::List(Box::new(Ty::int()))])),
        );
        e.types.insert("ResponseBody".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Union(rb_variants),
        });
        for ctor in &["BodyStr", "BodyStream", "BodyBytes"] {
            e.ctor_to_type.insert((*ctor).into(), "ResponseBody".into());
        }

        let mut net_resp_fields = IndexMap::new();
        net_resp_fields.insert("status".into(), Ty::int());
        net_resp_fields.insert("body".into(), Ty::Con("ResponseBody".into(), vec![]));
        net_resp_fields.insert("headers".into(), Ty::Con("Map".into(), vec![Ty::str(), Ty::str()]));
        e.types.insert("Response".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Alias(Ty::Record(net_resp_fields)),
        });

        // WsConn = { id :: Str, path :: Str, subprotocol :: Str }
        // Passed to every net.serve_ws_fn message handler.
        let mut ws_conn_fields = IndexMap::new();
        ws_conn_fields.insert("id".into(), Ty::str());
        ws_conn_fields.insert("path".into(), Ty::str());
        ws_conn_fields.insert("subprotocol".into(), Ty::str());
        e.types.insert("WsConn".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Alias(Ty::Record(ws_conn_fields)),
        });

        // WsMessage = WsText(Str) | WsBinary(List[Int]) | WsPing | WsClose
        let mut ws_msg_variants = IndexMap::new();
        ws_msg_variants.insert("WsText".into(), Some(Ty::str()));
        ws_msg_variants.insert("WsBinary".into(), Some(Ty::List(Box::new(Ty::int()))));
        ws_msg_variants.insert("WsPing".into(), None);
        ws_msg_variants.insert("WsClose".into(), None);
        e.types.insert("WsMessage".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Union(ws_msg_variants),
        });
        for ctor in &["WsText", "WsBinary", "WsPing", "WsClose"] {
            e.ctor_to_type.insert((*ctor).into(), "WsMessage".into());
        }

        // WsAction = WsSend(Str) | WsSendBinary(List[Int]) | WsNoOp
        // Handlers return this to tell the runtime what to send back.
        // Connection close is handled automatically when the runtime receives
        // an incoming WsClose frame; handlers do not need to emit a close action.
        let mut ws_act_variants = IndexMap::new();
        ws_act_variants.insert("WsSend".into(), Some(Ty::str()));
        ws_act_variants.insert("WsSendBinary".into(), Some(Ty::List(Box::new(Ty::int()))));
        ws_act_variants.insert("WsNoOp".into(), None);
        e.types.insert("WsAction".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Union(ws_act_variants),
        });
        for ctor in &["WsSend", "WsSendBinary", "WsNoOp"] {
            e.ctor_to_type.insert((*ctor).into(), "WsAction".into());
        }

        // ConcError = AlreadyRegistered(Str) | NotRegistered(Str)
        // Returned by `conc.register` / `conc.unregister` (#444). A
        // third `TypeMismatch` variant is reserved for when the
        // SigId-tagged registry lands — see `conc_registry.rs` in
        // lex-bytecode for the deferred-design note.
        let mut ce_variants = IndexMap::new();
        ce_variants.insert("AlreadyRegistered".into(), Some(Ty::str()));
        ce_variants.insert("NotRegistered".into(), Some(Ty::str()));
        e.types.insert("ConcError".into(), TypeDef {
            params: vec![],
            kind: TypeDefKind::Union(ce_variants),
        });
        for ctor in &["AlreadyRegistered", "NotRegistered"] {
            e.ctor_to_type.insert((*ctor).into(), "ConcError".into());
        }

        // ConnRedis: opaque handle for std.redis connections (#533).
        // Backed at runtime by an Int into a process-wide registry,
        // same pattern as Db (std.sql) and Kv (std.kv).
        e.types.insert("ConnRedis".into(), TypeDef { params: vec![], kind: TypeDefKind::Opaque });

        e
    }

    pub fn add_user_type(&mut self, name: &str, decl: lex_ast::TypeDecl) -> Result<(), String> {
        match &decl.definition {
            lex_ast::TypeExpr::Union { variants } => {
                // Resolve payloads env-aware (#963: normalizes alias-qualified
                // dependency types in a variant payload, e.g. `AddColumn(s.Field)`)
                // — compute the whole map under an immutable borrow first, then
                // record constructors and insert the type.
                let mut vmap = IndexMap::new();
                for v in variants {
                    let payload = v.payload.as_ref().map(|p| ty_from_canon_env(p, &decl.params, self));
                    vmap.insert(v.name.clone(), payload);
                }
                for v in variants {
                    self.ctor_to_type.insert(v.name.clone(), name.to_string());
                }
                self.types.insert(name.to_string(), TypeDef {
                    params: decl.params.clone(),
                    kind: TypeDefKind::Union(vmap),
                });
            }
            other => {
                let ty = ty_from_canon_env(other, &decl.params, self);
                self.types.insert(name.to_string(), TypeDef {
                    params: decl.params.clone(),
                    kind: TypeDefKind::Alias(ty),
                });
            }
        }
        Ok(())
    }
}

/// Convert canonical TypeExpr to internal Ty, treating type params as
/// fresh-numbered Vars (0..n in declaration order). When instantiating, we
/// substitute these out.
pub fn ty_from_canon(t: &lex_ast::TypeExpr, params: &[String]) -> Ty {
    match t {
        lex_ast::TypeExpr::Named { name, args } => {
            // type param?
            if let Some(idx) = params.iter().position(|p| p == name) {
                if !args.is_empty() {
                    // Type params don't take args.
                    return Ty::Con(name.clone(), args.iter().map(|a| ty_from_canon(a, params)).collect());
                }
                return Ty::Var(idx as u32);
            }
            // Primitives.
            match name.as_str() {
                "Int" => return Ty::int(),
                "Float" => return Ty::float(),
                "Bool" => return Ty::bool(),
                "Str" => return Ty::str(),
                "Bytes" => return Ty::bytes(),
                "Unit" | "Nil" => return Ty::Unit,
                "Never" => return Ty::Never,
                "List" if args.len() == 1 => return Ty::List(Box::new(ty_from_canon(&args[0], params))),
                // `Tuple[T0, T1, ...]` is the constructor surface for
                // tuples; canonicalize to the structural Ty::Tuple so
                // it unifies with `(T0, T1)` literal-tuple syntax and
                // with std.tuple's signatures.
                "Tuple" => return Ty::Tuple(args.iter().map(|a| ty_from_canon(a, params)).collect()),
                _ => {}
            }
            Ty::Con(name.clone(), args.iter().map(|a| ty_from_canon(a, params)).collect())
        }
        lex_ast::TypeExpr::Record { fields } => {
            let mut m = IndexMap::new();
            for f in fields { m.insert(f.name.clone(), ty_from_canon(&f.ty, params)); }
            Ty::Record(m)
        }
        lex_ast::TypeExpr::Tuple { items } => Ty::Tuple(items.iter().map(|t| ty_from_canon(t, params)).collect()),
        lex_ast::TypeExpr::Function { params: ps, effects, effect_row_var, ret } => {
            // Plumb effect args (#207).
            let effs = EffectSet {
                concrete: {
                    let mut s = std::collections::BTreeSet::new();
                    for e in effects {
                        let arg = e.arg.as_ref().map(|a| match a {
                            lex_ast::EffectArg::Str { value } => crate::types::EffectArg::Str(value.clone()),
                            lex_ast::EffectArg::Int { value } => crate::types::EffectArg::Int(*value),
                            lex_ast::EffectArg::Ident { value } => crate::types::EffectArg::Ident(value.clone()),
                        });
                        s.insert(crate::types::EffectKind { name: e.name.clone(), arg });
                    }
                    s
                },
                // Open-row tail: `[io | E]` where `E` is one of the enclosing
                // type/fn's `params`. Resolve it to that param's index — the
                // same id space as `Ty::Var(idx)`, but read back through the
                // separate effect-substitution map at instantiation, so a
                // type param and an effect-row param never collide.
                var: effect_row_var
                    .as_ref()
                    .and_then(|name| params.iter().position(|p| p == name))
                    .map(|i| i as u32),
            };
            Ty::Function {
                params: ps.iter().map(|t| ty_from_canon(t, params)).collect(),
                effects: effs,
                ret: Box::new(ty_from_canon(ret, params)),
            }
        }
        lex_ast::TypeExpr::Union { .. } => {
            // Unions on the RHS of type-decls; not in arbitrary positions.
            Ty::Unit
        }
        lex_ast::TypeExpr::Refined { base, .. } => {
            // #209 slice 1: refinement types unify structurally as
            // their base type. The predicate is parsed and stored in
            // the AST (so `lex-vcs` content-addressing picks up
            // refinement edits), but static discharge and runtime
            // residual checks land in slices 2 and 3 of #209. The
            // unification behavior here means a function declaring
            // `Int{x | x > 0}` interoperates with plain `Int` callers
            // — the predicate is informational until discharge is
            // wired up.
            ty_from_canon(base, params)
        }
        lex_ast::TypeExpr::RecordWithSpreads { .. } => {
            // Caller should use ty_from_canon_env for spread resolution.
            Ty::Unit
        }
    }
}

/// Like `ty_from_canon` but resolves `RecordWithSpreads` by looking up base
/// type names in `env`. Called from `add_user_type` and `function_scheme` so
/// that `{ ...Post, extra :: Int }` expands to a flat `Ty::Record`.
pub fn ty_from_canon_env(t: &lex_ast::TypeExpr, params: &[String], env: &TypeEnv) -> Ty {
    // #963: normalize alias-qualified dependency type references to the
    // dependency module's canonical prefix (`e.DbErr` → `error_<hash>.DbErr`)
    // so they name the same type the dependency's own signatures (and the
    // copies inlined into its sibling modules) do. Only kicks in when a
    // dependency was resolved as a whole package.
    if !env.dep_alias_prefixes.is_empty() {
        if let Some(normalized) = normalize_dep_alias(t, env) {
            return ty_from_canon_env(&normalized, params, env);
        }
    }
    match t {
        lex_ast::TypeExpr::RecordWithSpreads { spreads, fields } => {
            let mut m = IndexMap::new();
            for spread_name in spreads {
                if let Some(td) = env.types.get(spread_name.as_str()) {
                    if let TypeDefKind::Alias(Ty::Record(spread_fields)) = &td.kind {
                        for (k, v) in spread_fields {
                            m.insert(k.clone(), v.clone());
                        }
                    }
                }
            }
            for f in fields {
                m.insert(f.name.clone(), ty_from_canon_env(&f.ty, params, env));
            }
            Ty::Record(m)
        }
        other => ty_from_canon(other, params),
    }
}

/// Deep-rewrite alias-qualified dependency type names (`e.DbErr`) to their
/// module's canonical prefix (`error_<hash>.DbErr`) using
/// [`TypeEnv::dep_alias_prefixes`]. Returns `Some(rewritten)` only when a name
/// actually changed, so the caller can proceed on the rewritten form without
/// re-entering (the rewritten form has no alias names left). See #963.
fn normalize_dep_alias(t: &lex_ast::TypeExpr, env: &TypeEnv) -> Option<lex_ast::TypeExpr> {
    use lex_ast::TypeExpr as T;
    match t {
        T::Named { name, args } => {
            let renamed = name
                .split_once('.')
                .and_then(|(alias, rest)| {
                    env.dep_alias_prefixes.get(alias).map(|p| format!("{p}.{rest}"))
                });
            let new_args: Vec<Option<T>> = args.iter().map(|a| normalize_dep_alias(a, env)).collect();
            if renamed.is_none() && new_args.iter().all(|a| a.is_none()) {
                return None;
            }
            let args = args
                .iter()
                .zip(new_args)
                .map(|(orig, changed)| changed.unwrap_or_else(|| orig.clone()))
                .collect();
            Some(T::Named { name: renamed.unwrap_or_else(|| name.clone()), args })
        }
        T::Record { fields } => rewrite_fields(fields, env).map(|fields| T::Record { fields }),
        T::Tuple { items } => rewrite_items(items, env).map(|items| T::Tuple { items }),
        T::Function { params, effects, effect_row_var, ret } => {
            let new_params: Vec<Option<T>> = params.iter().map(|p| normalize_dep_alias(p, env)).collect();
            let new_ret = normalize_dep_alias(ret, env);
            if new_ret.is_none() && new_params.iter().all(|p| p.is_none()) {
                return None;
            }
            let params = params
                .iter()
                .zip(new_params)
                .map(|(orig, changed)| changed.unwrap_or_else(|| orig.clone()))
                .collect();
            Some(T::Function {
                params,
                effects: effects.clone(),
                effect_row_var: effect_row_var.clone(),
                ret: Box::new(new_ret.unwrap_or_else(|| (**ret).clone())),
            })
        }
        T::Union { variants } => {
            let rewritten: Vec<Option<T>> = variants
                .iter()
                .map(|v| v.payload.as_ref().and_then(|p| normalize_dep_alias(p, env)))
                .collect();
            if rewritten.iter().all(|r| r.is_none()) {
                return None;
            }
            let variants = variants
                .iter()
                .zip(rewritten)
                .map(|(v, changed)| lex_ast::UnionVariant {
                    name: v.name.clone(),
                    payload: changed.or_else(|| v.payload.clone()),
                })
                .collect();
            Some(T::Union { variants })
        }
        T::RecordWithSpreads { spreads, fields } => {
            // Spread base names could be alias-qualified too.
            let new_spreads: Vec<String> = spreads
                .iter()
                .map(|s| {
                    s.split_once('.')
                        .and_then(|(a, rest)| env.dep_alias_prefixes.get(a).map(|p| format!("{p}.{rest}")))
                        .unwrap_or_else(|| s.clone())
                })
                .collect();
            let spreads_changed = new_spreads != *spreads;
            let new_fields = rewrite_fields(fields, env);
            if !spreads_changed && new_fields.is_none() {
                return None;
            }
            Some(T::RecordWithSpreads {
                spreads: new_spreads,
                fields: new_fields.unwrap_or_else(|| fields.clone()),
            })
        }
        T::Refined { base, binding, predicate } => normalize_dep_alias(base, env).map(|b| T::Refined {
            base: Box::new(b),
            binding: binding.clone(),
            predicate: predicate.clone(),
        }),
    }
}

fn rewrite_fields(fields: &[lex_ast::TypeField], env: &TypeEnv) -> Option<Vec<lex_ast::TypeField>> {
    let rewritten: Vec<Option<lex_ast::TypeExpr>> =
        fields.iter().map(|f| normalize_dep_alias(&f.ty, env)).collect();
    if rewritten.iter().all(|r| r.is_none()) {
        return None;
    }
    Some(
        fields
            .iter()
            .zip(rewritten)
            .map(|(f, changed)| lex_ast::TypeField {
                name: f.name.clone(),
                ty: changed.unwrap_or_else(|| f.ty.clone()),
            })
            .collect(),
    )
}

fn rewrite_items(items: &[lex_ast::TypeExpr], env: &TypeEnv) -> Option<Vec<lex_ast::TypeExpr>> {
    let rewritten: Vec<Option<lex_ast::TypeExpr>> =
        items.iter().map(|it| normalize_dep_alias(it, env)).collect();
    if rewritten.iter().all(|r| r.is_none()) {
        return None;
    }
    Some(
        items
            .iter()
            .zip(rewritten)
            .map(|(it, changed)| changed.unwrap_or_else(|| it.clone()))
            .collect(),
    )
}