typeck-lang 0.3.0

Profile-driven type checking over HIR: dynamic, gradual, static (generics, traits, inference), and Hindley-Milner from one checker.
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
//! Coercion (a value meeting a context of another type) and joins (the type
//! of `if`/`match` branches that disagree).
//!
//! Unification is tried first; the profile's implicit conversions only when
//! it fails. Every accepted conversion is recorded for lowering.

use alloc::vec::Vec;

use hir_lang::{ExprId, ItemId, ItemKind, NodeRef, Prim};

use super::Ctx;
use crate::{
    diag::DiagnosticKind,
    error::CheckError,
    profile::RecordTyping,
    typed::Coercion,
    types::{Tag, Type, TypeId},
};

/// The outcome of a coercion attempt.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Fit {
    /// Equal types (after unification), or a value that never exists.
    Same,
    /// Accepted with an implicit conversion.
    Converted(Coercion),
    /// Rejected; nothing changed.
    No,
}

impl Ctx<'_> {
    /// Whether a value of `found` may be used where `expected` is required.
    pub(crate) fn coerce(&mut self, found: TypeId, expected: TypeId) -> Result<Fit, CheckError> {
        if found == expected {
            return Ok(Fit::Same);
        }
        self.coerce_with(found, expected, true)
    }

    fn coerce_with(
        &mut self,
        found: TypeId,
        expected: TypeId,
        wrap: bool,
    ) -> Result<Fit, CheckError> {
        let (f, x) = (self.resolve(found), self.resolve(expected));
        let (ft, xt) = (self.tag(f), self.tag(x));
        // A diverging expression fits anywhere without constraining it.
        if ft == Tag::Never {
            return Ok(Fit::Same);
        }
        if self.unify(found, expected)? {
            return Ok(Fit::Same);
        }
        if xt == Tag::Any {
            return Ok(Fit::Converted(Coercion::ToAny));
        }
        if ft == Tag::Null {
            let ok = xt == Tag::Nullable || (!self.profile.null_safety && self.reference_like(x));
            return Ok(if ok {
                Fit::Converted(Coercion::Null)
            } else {
                Fit::No
            });
        }
        if xt == Tag::Nullable && wrap {
            // `T` into `T?`. Nullable layers can stack through variables;
            // peel them all, then convert without wrapping again.
            let mut inner = x;
            while self.tag(inner) == Tag::Nullable {
                self.meter.tick(1)?;
                inner = self.resolve(TypeId::from_raw(self.types.node(inner).x));
            }
            return Ok(match self.coerce_with(f, inner, false)? {
                Fit::No => Fit::No,
                _ => Fit::Converted(Coercion::WrapNullable),
            });
        }
        if self.profile.numeric_widening {
            if let (Some(a), Some(b)) = (self.prim_of(f), self.prim_of(x)) {
                if widens(a, b) {
                    return Ok(Fit::Converted(Coercion::Widen));
                }
            }
        }
        if self.profile.subtyping {
            if let (Type::Adt { .. }, Type::Adt { .. }) = (self.types.get(f), self.types.get(x)) {
                if self.upcast(f, x)? {
                    return Ok(Fit::Converted(Coercion::Subclass));
                }
                if self.profile.records == RecordTyping::Structural && self.record_width(f, x)? {
                    return Ok(Fit::Converted(Coercion::RecordWidth));
                }
            } else if self.profile.records == RecordTyping::Structural && self.record_width(f, x)? {
                return Ok(Fit::Converted(Coercion::RecordWidth));
            }
        }
        // Unions, intersections, and interface types.
        if let Some(fit) = self.coerce_compound(f, x)? {
            return Ok(fit);
        }
        // Views borrow the store; copy out the ids before unifying.
        enum Shape {
            Unsize(TypeId, TypeId),
            Refs(bool, TypeId, TypeId),
        }
        let shape = match (self.types.get(f), self.types.get(x)) {
            (Type::Array { elem, .. }, Type::Slice(target)) => Some(Shape::Unsize(elem, target)),
            (
                Type::Ref {
                    mutable: fm,
                    inner: fi,
                },
                Type::Ref {
                    mutable: false,
                    inner: xi,
                },
            ) => Some(Shape::Refs(fm, fi, xi)),
            _ => None,
        };
        match shape {
            Some(Shape::Unsize(elem, target)) if self.unify(elem, target)? => {
                return Ok(Fit::Converted(Coercion::Unsize));
            }
            Some(Shape::Refs(fm, fi, xi)) => {
                let (fi_r, xi_r) = (self.resolve(fi), self.resolve(xi));
                let unsize = match (self.types.get(fi_r), self.types.get(xi_r)) {
                    (Type::Array { elem, .. }, Type::Slice(target)) => Some((elem, target)),
                    _ => None,
                };
                if let Some((elem, target)) = unsize {
                    if self.unify(elem, target)? {
                        return Ok(Fit::Converted(Coercion::Unsize));
                    }
                }
                if fm && self.unify(fi, xi)? {
                    return Ok(Fit::Converted(Coercion::Reborrow));
                }
                // `&T` as `&dyn Iface` (and `&A & B` as `&A`).
                if matches!(self.tag(xi_r), Tag::Dyn | Tag::Union | Tag::Inter)
                    || self.tag(fi_r) == Tag::Inter
                {
                    if let Some(Fit::Converted(c)) = self.coerce_compound(fi_r, xi_r)? {
                        return Ok(Fit::Converted(c));
                    }
                }
            }
            _ => {}
        }
        Ok(Fit::No)
    }

    /// Coercions into and out of unions, intersections, and `dyn` types.
    /// `None`: none applies.
    fn coerce_compound(&mut self, f: TypeId, x: TypeId) -> Result<Option<Fit>, CheckError> {
        let (ft, xt) = (self.tag(f), self.tag(x));
        // A value into a union containing (a supertype of) its type; a
        // union into a union containing all its members.
        if xt == Tag::Union {
            let members = self.types.kids(x).to_vec();
            let found: Vec<TypeId> = if ft == Tag::Union {
                self.types.kids(f).to_vec()
            } else {
                alloc::vec![f]
            };
            let snap = self.infer.snapshot();
            let mut all = true;
            for &v in &found {
                let mut ok = members.contains(&v);
                for &m in &members {
                    if ok {
                        break;
                    }
                    ok = self.coerce_with(v, m, true)? != Fit::No;
                }
                if !ok {
                    all = false;
                    break;
                }
            }
            if all {
                self.infer.commit();
                return Ok(Some(Fit::Converted(Coercion::ToUnion)));
            }
            self.infer.rollback(snap);
            return Ok(None);
        }
        // Into an intersection: into every member.
        if xt == Tag::Inter {
            let members = self.types.kids(x).to_vec();
            let snap = self.infer.snapshot();
            let mut same = true;
            for m in members {
                match self.coerce_with(f, m, true)? {
                    Fit::Same => {}
                    Fit::Converted(_) => same = false,
                    Fit::No => {
                        self.infer.rollback(snap);
                        return Ok(None);
                    }
                }
            }
            self.infer.commit();
            return Ok(Some(if same {
                Fit::Same
            } else {
                Fit::Converted(Coercion::Subclass)
            }));
        }
        // Out of an intersection: as any member.
        if ft == Tag::Inter {
            let members = self.types.kids(f).to_vec();
            for m in members {
                let snap = self.infer.snapshot();
                if self.coerce_with(m, x, true)? != Fit::No {
                    self.infer.commit();
                    return Ok(Some(Fit::Converted(Coercion::FromIntersection)));
                }
                self.infer.rollback(snap);
            }
            return Ok(None);
        }
        // Into a `dyn` type: the value's type must implement each
        // interface (checked as goals), with the bound associated types.
        if xt == Tag::Dyn && !matches!(ft, Tag::Var | Tag::Error) {
            let want = self.types.kids(x).to_vec();
            if ft == Tag::Dyn {
                // Upcasting a trait object: every wanted interface is one of
                // the value's.
                let have = self.types.kids(f).to_vec();
                let ok = want.iter().all(|w| {
                    let wi = self.trait_item(*w);
                    have.iter().any(|h| self.trait_item(*h) == wi)
                });
                return Ok(ok.then_some(Fit::Converted(Coercion::ToDyn)));
            }
            let at = self.coerce_site;
            for tr in want {
                let Some(iface) = self.trait_item(tr) else {
                    continue;
                };
                let args = self.trait_args(tr);
                let slots: Vec<TypeId> = self
                    .types
                    .kids(tr)
                    .get(args.len()..)
                    .unwrap_or(&[])
                    .to_vec();
                let bare = self.types.trait_ref(iface, &args);
                self.oblige_impl(f, bare, at);
                for (assoc, v) in self.assoc_types(iface).into_iter().zip(slots) {
                    self.oblige_projection(f, bare, assoc, v, at);
                }
                self.dyn_uses.push((self.cur_item, f, bare));
            }
            return Ok(Some(Fit::Converted(Coercion::ToDyn)));
        }
        Ok(None)
    }

    /// Whether `sub` is (an instance of) a subclass of `sup`'s class, with
    /// arguments that agree: unifies them when it is.
    pub(crate) fn upcast(&mut self, sub: TypeId, sup: TypeId) -> Result<bool, CheckError> {
        let sup = self.resolve(sup);
        let Type::Adt { item: want, .. } = self.types.get(sup) else {
            return Ok(false);
        };
        for base in self.base_types(sub)? {
            if let Type::Adt { item, .. } = self.types.get(self.resolve(base)) {
                if item == want {
                    let snap = self.infer.snapshot();
                    if self.unify(base, sup)? {
                        self.infer.commit();
                        return Ok(true);
                    }
                    self.infer.rollback(snap);
                }
            }
        }
        Ok(false)
    }

    /// Types that `null` may stand for when the profile has no null safety.
    fn reference_like(&self, t: TypeId) -> bool {
        match self.types.get(t) {
            Type::Ref { .. }
            | Type::Ptr { .. }
            | Type::Adt { .. }
            | Type::Foreign { .. }
            | Type::Extern { .. }
            | Type::Fn { .. }
            | Type::Slice(_)
            | Type::Map { .. }
            | Type::Nullable(_)
            | Type::Record(_)
            | Type::Param(_)
            | Type::ImplParam(_)
            | Type::Dyn(_)
            | Type::Opaque { .. }
            | Type::Union(_)
            | Type::Intersection(_)
            | Type::Async(_)
            | Type::Task(_)
            | Type::Generator { .. } => true,
            Type::Prim(p) => p == Prim::Str,
            _ => false,
        }
    }

    /// Whether class `sub` inherits (transitively) from class `sup`.
    pub(crate) fn is_subclass(&mut self, sub: ItemId, sup: ItemId) -> Result<bool, CheckError> {
        if !matches!(self.item_kind(sub), ItemKind::Class(_)) {
            return Ok(false);
        }
        self.new_visit();
        let mut stack: Vec<ItemId> = alloc::vec![sub];
        while let Some(c) = stack.pop() {
            self.meter.tick(1)?;
            if c == sup {
                return Ok(true);
            }
            if !self.visit(c) {
                continue;
            }
            stack.extend(self.idx.bases_of(c).iter().copied());
        }
        Ok(false)
    }

    /// Structural width subtyping: `found` has every field of `expected`
    /// (with equal types), and possibly more.
    fn record_width(&mut self, found: TypeId, expected: TypeId) -> Result<bool, CheckError> {
        let (Some(ff), Some(xf)) = (
            self.record_fields_of(found),
            self.record_fields_of(expected),
        ) else {
            return Ok(false);
        };
        let snap = self.infer.snapshot();
        let mut i = 0;
        for want in &xf {
            while ff.get(i).is_some_and(|f| f.name < want.name) {
                i += 1;
            }
            let ok = match ff.get(i) {
                Some(have) if have.name == want.name => self.unify(have.ty, want.ty)?,
                _ => false,
            };
            if !ok {
                self.infer.rollback(snap);
                return Ok(false);
            }
        }
        self.infer.commit();
        Ok(true)
    }

    /// The sorted fields of an anonymous record or a named-field record item.
    pub(crate) fn record_fields_of(&self, t: TypeId) -> Option<Vec<crate::types::Field>> {
        let n = self.types.node(t);
        match n.tag {
            Tag::Record => Some(self.types.fields_of(&n).to_vec()),
            Tag::Adt if n.len == 0 => {
                let (start, len) = (*self.record_fields.get(n.x as usize)?)?;
                self.field_pool
                    .get(start as usize..(start as usize).saturating_add(len as usize))
                    .map(<[_]>::to_vec)
            }
            _ => None,
        }
    }

    /// Coerces expression `e` (of type `found`) to `expected`, reporting a
    /// mismatch at `e` and recording any conversion.
    pub(crate) fn coerce_expr(
        &mut self,
        e: ExprId,
        found: TypeId,
        expected: TypeId,
    ) -> Result<bool, CheckError> {
        self.coerce_site = NodeRef::Expr(e);
        match self.coerce(found, expected)? {
            Fit::Same => Ok(true),
            Fit::Converted(c) => {
                self.coercions.push((e, c, expected));
                Ok(true)
            }
            Fit::No => {
                self.report(
                    NodeRef::Expr(e),
                    DiagnosticKind::Mismatch { expected, found },
                );
                self.poison(e);
                Ok(false)
            }
        }
    }

    /// The common type of two branches. Tries equality, then converting
    /// either side into the other, then `null` with `T`; on failure reports
    /// at the later branch.
    pub(crate) fn join(
        &mut self,
        prev: TypeId,
        prev_expr: Option<ExprId>,
        next: TypeId,
        next_expr: ExprId,
    ) -> Result<TypeId, CheckError> {
        let (pt, nt) = (self.tag(prev), self.tag(next));
        if pt == Tag::Never || pt == Tag::Error {
            return Ok(next);
        }
        if nt == Tag::Never || nt == Tag::Error {
            return Ok(prev);
        }
        if self.unify(prev, next)? {
            return Ok(prev);
        }
        match self.coerce(next, prev)? {
            Fit::Same => return Ok(prev),
            Fit::Converted(c) => {
                self.coercions.push((next_expr, c, prev));
                return Ok(prev);
            }
            Fit::No => {}
        }
        if let Some(pe) = prev_expr {
            match self.coerce(prev, next)? {
                Fit::Same => return Ok(next),
                Fit::Converted(c) => {
                    self.coercions.push((pe, c, next));
                    return Ok(next);
                }
                Fit::No => {}
            }
        }
        // `null` and `T` join to `T?` under null safety.
        if self.profile.null_safety && (pt == Tag::Null || nt == Tag::Null) {
            let (other, other_expr, null_expr) = if pt == Tag::Null {
                (next, Some(next_expr), prev_expr)
            } else {
                (prev, prev_expr, Some(next_expr))
            };
            let joined = self.types.nullable(other);
            if let Some(e) = other_expr {
                self.coercions.push((e, Coercion::WrapNullable, joined));
            }
            if let Some(e) = null_expr {
                self.coercions.push((e, Coercion::Null, joined));
            }
            return Ok(joined);
        }
        self.report(
            NodeRef::Expr(next_expr),
            DiagnosticKind::Mismatch {
                expected: prev,
                found: next,
            },
        );
        self.poison(next_expr);
        Ok(prev)
    }
}

/// Lossless implicit numeric widening.
pub(crate) fn widens(from: Prim, to: Prim) -> bool {
    let (fb, tb) = (from.bits(), to.bits());
    if from.is_int() && to.is_int() {
        if from.is_signed() && !to.is_signed() {
            return false;
        }
        // Unsigned into signed needs a strictly wider target, and so does
        // any change of width.
        return fb < tb;
    }
    if from.is_int() && to.is_float() {
        // Every value fits the float's mantissa exactly.
        return (to == Prim::F32 && fb <= 16) || (to == Prim::F64 && fb <= 32);
    }
    from == Prim::F32 && to == Prim::F64
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_widening_table() {
        assert!(widens(Prim::I8, Prim::I64));
        assert!(widens(Prim::U8, Prim::I16));
        assert!(!widens(Prim::I8, Prim::U64));
        assert!(!widens(Prim::I64, Prim::I32));
        assert!(!widens(Prim::I64, Prim::Isize));
        assert!(widens(Prim::I32, Prim::F64));
        assert!(!widens(Prim::I64, Prim::F64));
        assert!(widens(Prim::U16, Prim::F32));
        assert!(!widens(Prim::U32, Prim::F32));
        assert!(widens(Prim::F32, Prim::F64));
        assert!(!widens(Prim::F64, Prim::F32));
        assert!(!widens(Prim::Bool, Prim::I8));
    }
}