summaryrefslogtreecommitdiff
path: root/dhall/src/semantics/tck/typecheck.rs
blob: d99f54902cb3fe5f053a17044db916524410b764 (plain)
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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
use std::borrow::Cow;
use std::cmp::max;
use std::collections::HashMap;

use crate::error::{ErrorBuilder, TypeError, TypeMessage};
use crate::semantics::merge_maps;
use crate::semantics::{
    type_of_builtin, Binder, BuiltinClosure, Closure, TyEnv, TyExpr,
    TyExprKind, Type, Value, ValueKind,
};
use crate::syntax::{
    BinOp, Builtin, Const, Expr, ExprKind, InterpolatedTextContents, Span,
};
use crate::Normalized;

fn type_of_recordtype<'a>(
    tys: impl Iterator<Item = Cow<'a, TyExpr>>,
) -> Result<Type, TypeError> {
    // An empty record type has type Type
    let mut k = Const::Type;
    for t in tys {
        match t.get_type()?.as_const() {
            Some(c) => k = max(k, c),
            None => return mkerr("InvalidFieldType"),
        }
    }
    Ok(Value::from_const(k))
}

fn function_check(a: Const, b: Const) -> Const {
    if b == Const::Type {
        Const::Type
    } else {
        max(a, b)
    }
}

fn mkerr<T, S: ToString>(x: S) -> Result<T, TypeError> {
    Err(TypeError::new(TypeMessage::Custom(x.to_string())))
}

/// When all sub-expressions have been typed, check the remaining toplevel
/// layer.
fn type_one_layer(
    env: &TyEnv,
    kind: &ExprKind<TyExpr, Normalized>,
    span: Span,
) -> Result<Type, TypeError> {
    Ok(match kind {
        ExprKind::Import(..) => unreachable!(
            "There should remain no imports in a resolved expression"
        ),
        ExprKind::Var(..)
        | ExprKind::Const(Const::Sort)
        | ExprKind::Embed(..) => unreachable!(), // Handled in type_with

        ExprKind::Lam(binder, annot, body) => {
            let body_ty = body.get_type()?;
            let body_ty = body_ty.to_tyexpr(env.as_varenv().insert());
            let pi_ekind = ExprKind::Pi(binder.clone(), annot.clone(), body_ty);
            let pi_ty = type_one_layer(env, &pi_ekind, Span::Artificial)?;
            let ty = TyExpr::new(
                TyExprKind::Expr(pi_ekind),
                Some(pi_ty),
                Span::Artificial,
            );
            ty.eval(env.as_nzenv())
        }
        ExprKind::Pi(_, annot, body) => {
            let ks = match annot.get_type()?.as_const() {
                Some(k) => k,
                _ => {
                    return mkerr(
                        ErrorBuilder::new(format!(
                            "Invalid input type: `{}`",
                            annot.get_type()?.to_expr_tyenv(env),
                        ))
                        .span_err(
                            &annot.span(),
                            format!(
                                "this has type: `{}`",
                                annot.get_type()?.to_expr_tyenv(env)
                            ),
                        )
                        .help(
                            format!(
                                "The input type of a function must have type `Type`, `Kind` or `Sort`",
                            ),
                        )
                        .format(),
                    );
                }
            };
            let kt = match body.get_type()?.as_const() {
                Some(k) => k,
                _ => return mkerr("Invalid output type"),
            };

            Value::from_const(function_check(ks, kt))
        }
        ExprKind::Let(_, _, _, body) => body.get_type()?,

        ExprKind::Const(Const::Type) => Value::from_const(Const::Kind),
        ExprKind::Const(Const::Kind) => Value::from_const(Const::Sort),
        ExprKind::Builtin(b) => {
            let t_expr = type_of_builtin(*b);
            let t_tyexpr = type_with(env, &t_expr)?;
            t_tyexpr.eval(env.as_nzenv())
        }
        ExprKind::BoolLit(_) => Value::from_builtin(Builtin::Bool),
        ExprKind::NaturalLit(_) => Value::from_builtin(Builtin::Natural),
        ExprKind::IntegerLit(_) => Value::from_builtin(Builtin::Integer),
        ExprKind::DoubleLit(_) => Value::from_builtin(Builtin::Double),
        ExprKind::TextLit(interpolated) => {
            let text_type = Value::from_builtin(Builtin::Text);
            for contents in interpolated.iter() {
                use InterpolatedTextContents::Expr;
                if let Expr(x) = contents {
                    if x.get_type()? != text_type {
                        return mkerr("InvalidTextInterpolation");
                    }
                }
            }
            text_type
        }
        ExprKind::EmptyListLit(t) => {
            let t = t.eval(env.as_nzenv());
            match &*t.kind() {
                ValueKind::AppliedBuiltin(BuiltinClosure {
                    b: Builtin::List,
                    args,
                    ..
                }) if args.len() == 1 => {}
                _ => return mkerr("InvalidListType"),
            };
            t
        }
        ExprKind::NEListLit(xs) => {
            let mut iter = xs.iter();
            let x = iter.next().unwrap();
            for y in iter {
                if x.get_type()? != y.get_type()? {
                    return mkerr("InvalidListElement");
                }
            }
            let t = x.get_type()?;
            if t.get_type()?.as_const() != Some(Const::Type) {
                return mkerr("InvalidListType");
            }

            Value::from_builtin(Builtin::List).app(t)
        }
        ExprKind::SomeLit(x) => {
            let t = x.get_type()?;
            if t.get_type()?.as_const() != Some(Const::Type) {
                return mkerr("InvalidOptionalType");
            }

            Value::from_builtin(Builtin::Optional).app(t)
        }
        ExprKind::RecordLit(kvs) => {
            use std::collections::hash_map::Entry;
            let mut kts = HashMap::new();
            for (x, v) in kvs {
                // Check for duplicated entries
                match kts.entry(x.clone()) {
                    Entry::Occupied(_) => {
                        return mkerr("RecordTypeDuplicateField")
                    }
                    Entry::Vacant(e) => e.insert(v.get_type()?),
                };
            }

            let ty = type_of_recordtype(
                kts.iter()
                    .map(|(_, t)| Cow::Owned(t.to_tyexpr(env.as_varenv()))),
            )?;
            Value::from_kind_and_type(ValueKind::RecordType(kts), ty)
        }
        ExprKind::RecordType(kts) => {
            use std::collections::hash_map::Entry;
            let mut seen_fields = HashMap::new();
            for (x, _) in kts {
                // Check for duplicated entries
                match seen_fields.entry(x.clone()) {
                    Entry::Occupied(_) => {
                        return mkerr("RecordTypeDuplicateField")
                    }
                    Entry::Vacant(e) => e.insert(()),
                };
            }

            type_of_recordtype(kts.iter().map(|(_, t)| Cow::Borrowed(t)))?
        }
        ExprKind::UnionType(kts) => {
            use std::collections::hash_map::Entry;
            let mut seen_fields = HashMap::new();
            // Check that all types are the same const
            let mut k = None;
            for (x, t) in kts {
                if let Some(t) = t {
                    match (k, t.get_type()?.as_const()) {
                        (None, Some(k2)) => k = Some(k2),
                        (Some(k1), Some(k2)) if k1 == k2 => {}
                        _ => return mkerr("InvalidFieldType"),
                    }
                }
                match seen_fields.entry(x) {
                    Entry::Occupied(_) => {
                        return mkerr("UnionTypeDuplicateField")
                    }
                    Entry::Vacant(e) => e.insert(()),
                };
            }

            // An empty union type has type Type;
            // an union type with only unary variants also has type Type
            let k = k.unwrap_or(Const::Type);

            Value::from_const(k)
        }
        ExprKind::Field(scrut, x) => {
            match &*scrut.get_type()?.kind() {
                ValueKind::RecordType(kts) => match kts.get(&x) {
                    Some(tth) => tth.clone(),
                    None => return mkerr("MissingRecordField"),
                },
                // TODO: branch here only when scrut.get_type() is a Const
                _ => {
                    let scrut_nf = scrut.eval(env.as_nzenv());
                    match scrut_nf.kind() {
                        ValueKind::UnionType(kts) => match kts.get(x) {
                            // Constructor has type T -> < x: T, ... >
                            Some(Some(ty)) => {
                                // Can't fail because uniontypes must have type Const(_).
                                let kt = scrut.get_type()?.as_const().unwrap();
                                // The type of the field must be Const smaller than `kt`, thus the
                                // function type has type `kt`.
                                let pi_ty = Value::from_const(kt);

                                Value::from_kind_and_type(
                                    ValueKind::PiClosure {
                                        binder: Binder::new(x.clone()),
                                        annot: ty.clone(),
                                        closure: Closure::new_constant(
                                            scrut_nf,
                                        ),
                                    },
                                    pi_ty,
                                )
                            }
                            Some(None) => scrut_nf,
                            None => return mkerr("MissingUnionField"),
                        },
                        _ => return mkerr("NotARecord"),
                    }
                } // _ => mkerr("NotARecord"),
            }
        }
        ExprKind::Annot(x, t) => {
            let t = t.eval(env.as_nzenv());
            let x_ty = x.get_type()?;
            if x_ty != t {
                return mkerr(format!(
                    "annot mismatch: ({} : {}) : {}",
                    x.to_expr_tyenv(env),
                    x_ty.to_tyexpr(env.as_varenv()).to_expr_tyenv(env),
                    t.to_tyexpr(env.as_varenv()).to_expr_tyenv(env)
                ));
                // return mkerr(format!(
                //     "annot mismatch: {} != {}",
                //     x_ty.to_tyexpr(env.as_varenv()).to_expr_tyenv(env),
                //     t.to_tyexpr(env.as_varenv()).to_expr_tyenv(env)
                // ));
                // return mkerr(format!("annot mismatch: {:#?} : {:#?}", x, t,));
            }
            x_ty
        }
        ExprKind::Assert(t) => {
            let t = t.eval(env.as_nzenv());
            match &*t.kind() {
                ValueKind::Equivalence(x, y) if x == y => {}
                ValueKind::Equivalence(..) => return mkerr("AssertMismatch"),
                _ => return mkerr("AssertMustTakeEquivalence"),
            }
            t
        }
        ExprKind::App(f, arg) => match f.get_type()?.kind() {
            ValueKind::PiClosure { annot, closure, .. } => {
                if arg.get_type()? != *annot {
                    return mkerr(
                        ErrorBuilder::new_span_err(
                            &span,
                            format!("Wrong type of function argument"),
                        )
                        .span_err(
                            &f.span(),
                            format!(
                                "this expects an argument of type: {}",
                                annot.to_expr_tyenv(env),
                            ),
                        )
                        .span_err(
                            &arg.span(),
                            format!(
                                "but this has type: {}",
                                arg.get_type()?.to_expr_tyenv(env),
                            ),
                        )
                        .format(),
                    );
                }

                let arg_nf = arg.eval(env.as_nzenv());
                closure.apply(arg_nf)
            }
            _ => {
                return mkerr(
                    ErrorBuilder::new(format!(
                        "Trying to apply an argument \
                         to a value that is not a function"
                    ))
                    .span_err(
                        &f.span(),
                        format!(
                            "this has type: `{}`",
                            f.get_type()?.to_expr_tyenv(env)
                        ),
                    )
                    .help("only functions can be applied to")
                    .format(),
                )
            }
        },
        ExprKind::BoolIf(x, y, z) => {
            if *x.get_type()?.kind() != ValueKind::from_builtin(Builtin::Bool) {
                return mkerr("InvalidPredicate");
            }
            if y.get_type()?.get_type()?.as_const() != Some(Const::Type) {
                return mkerr("IfBranchMustBeTerm");
            }
            if z.get_type()?.get_type()?.as_const() != Some(Const::Type) {
                return mkerr("IfBranchMustBeTerm");
            }
            if y.get_type()? != z.get_type()? {
                return mkerr("IfBranchMismatch");
            }

            y.get_type()?
        }
        ExprKind::BinOp(BinOp::RightBiasedRecordMerge, x, y) => {
            let x_type = x.get_type()?;
            let y_type = y.get_type()?;

            // Extract the LHS record type
            let kts_x = match x_type.kind() {
                ValueKind::RecordType(kts) => kts,
                _ => return mkerr("MustCombineRecord"),
            };
            // Extract the RHS record type
            let kts_y = match y_type.kind() {
                ValueKind::RecordType(kts) => kts,
                _ => return mkerr("MustCombineRecord"),
            };

            // Union the two records, prefering
            // the values found in the RHS.
            let kts = merge_maps::<_, _, _, !>(kts_x, kts_y, |_, _, r_t| {
                Ok(r_t.clone())
            })?;

            // Construct the final record type
            let ty = type_of_recordtype(
                kts.iter()
                    .map(|(_, t)| Cow::Owned(t.to_tyexpr(env.as_varenv()))),
            )?;
            Value::from_kind_and_type(ValueKind::RecordType(kts), ty)
        }
        ExprKind::BinOp(BinOp::RecursiveRecordMerge, x, y) => {
            let ekind = ExprKind::BinOp(
                BinOp::RecursiveRecordTypeMerge,
                x.get_type()?.to_tyexpr(env.as_varenv()),
                y.get_type()?.to_tyexpr(env.as_varenv()),
            );
            let ty = type_one_layer(env, &ekind, Span::Artificial)?;
            TyExpr::new(TyExprKind::Expr(ekind), Some(ty), Span::Artificial)
                .eval(env.as_nzenv())
        }
        ExprKind::BinOp(BinOp::RecursiveRecordTypeMerge, x, y) => {
            let x_val = x.eval(env.as_nzenv());
            let y_val = y.eval(env.as_nzenv());
            let kts_x = match x_val.kind() {
                ValueKind::RecordType(kts) => kts,
                _ => return mkerr("RecordTypeMergeRequiresRecordType"),
            };
            let kts_y = match y_val.kind() {
                ValueKind::RecordType(kts) => kts,
                _ => return mkerr("RecordTypeMergeRequiresRecordType"),
            };
            for (k, tx) in kts_x {
                if let Some(ty) = kts_y.get(k) {
                    type_one_layer(
                        env,
                        &ExprKind::BinOp(
                            BinOp::RecursiveRecordTypeMerge,
                            tx.to_tyexpr(env.as_varenv()),
                            ty.to_tyexpr(env.as_varenv()),
                        ),
                        Span::Artificial,
                    )?;
                }
            }

            // A RecordType's type is always a const
            let xk = x.get_type()?.as_const().unwrap();
            let yk = y.get_type()?.as_const().unwrap();
            Value::from_const(max(xk, yk))
        }
        ExprKind::BinOp(BinOp::ListAppend, l, r) => {
            let l_ty = l.get_type()?;
            match &*l_ty.kind() {
                ValueKind::AppliedBuiltin(BuiltinClosure {
                    b: Builtin::List,
                    ..
                }) => {}
                _ => return mkerr("BinOpTypeMismatch"),
            }

            if l_ty != r.get_type()? {
                return mkerr("BinOpTypeMismatch");
            }

            l_ty
        }
        ExprKind::BinOp(BinOp::Equivalence, l, r) => {
            if l.get_type()? != r.get_type()? {
                return mkerr("EquivalenceTypeMismatch");
            }
            if l.get_type()?.get_type()?.as_const() != Some(Const::Type) {
                return mkerr("EquivalenceArgumentsMustBeTerms");
            }

            Value::from_const(Const::Type)
        }
        ExprKind::BinOp(o, l, r) => {
            let t = Value::from_builtin(match o {
                BinOp::BoolAnd
                | BinOp::BoolOr
                | BinOp::BoolEQ
                | BinOp::BoolNE => Builtin::Bool,
                BinOp::NaturalPlus | BinOp::NaturalTimes => Builtin::Natural,
                BinOp::TextAppend => Builtin::Text,
                BinOp::ListAppend
                | BinOp::RightBiasedRecordMerge
                | BinOp::RecursiveRecordMerge
                | BinOp::RecursiveRecordTypeMerge
                | BinOp::Equivalence => unreachable!(),
                BinOp::ImportAlt => unreachable!("ImportAlt leftover in tck"),
            });

            if l.get_type()? != t {
                return mkerr("BinOpTypeMismatch");
            }

            if r.get_type()? != t {
                return mkerr("BinOpTypeMismatch");
            }

            t
        }
        ExprKind::Merge(record, union, type_annot) => {
            let record_type = record.get_type()?;
            let handlers = match record_type.kind() {
                ValueKind::RecordType(kts) => kts,
                _ => return mkerr("Merge1ArgMustBeRecord"),
            };

            let union_type = union.get_type()?;
            let variants = match union_type.kind() {
                ValueKind::UnionType(kts) => Cow::Borrowed(kts),
                ValueKind::AppliedBuiltin(BuiltinClosure {
                    b: Builtin::Optional,
                    args,
                    ..
                }) if args.len() == 1 => {
                    let ty = &args[0];
                    let mut kts = HashMap::new();
                    kts.insert("None".into(), None);
                    kts.insert("Some".into(), Some(ty.clone()));
                    Cow::Owned(kts)
                }
                _ => return mkerr("Merge2ArgMustBeUnionOrOptional"),
            };

            let mut inferred_type = None;
            for (x, handler_type) in handlers {
                let handler_return_type = match variants.get(x) {
                    // Union alternative with type
                    Some(Some(variant_type)) => match handler_type.kind() {
                        ValueKind::PiClosure { closure, annot, .. } => {
                            if variant_type != annot {
                                return mkerr(
                                    ErrorBuilder::new(format!(
                                        "Wrong handler input type"
                                    ))
                                    .span_err(
                                        &span,
                                        format!(
                                            "in this merge expression",
                                        ),
                                    )
                                    .span_err(
                                        &record.span(),
                                        format!(
                                            "the handler `{}` expects a value of type: `{}`",
                                            x,
                                            annot.to_expr_tyenv(env)
                                        ),
                                    )
                                    .span_err(
                                        &union.span(),
                                        format!(
                                            "but the corresponding variant has type: `{}`",
                                            variant_type.to_expr_tyenv(env)
                                        ),
                                    )
                                    .help("only functions can be applied to")
                                    .format(),
                                );
                            }

                            closure.remove_binder().or_else(|()| {
                                mkerr("MergeReturnTypeIsDependent")
                            })?
                        }
                        _ =>
                                return mkerr(
                                    ErrorBuilder::new(format!(
                                        "Handler is not a function"
                                    ))
                                    .span_err(
                                        &span,
                                        format!(
                                            "in this merge expression",
                                        ),
                                    )
                                    .span_err(
                                        &record.span(),
                                        format!(
                                            "the handler `{}` had type: `{}`",
                                            x,
                                            handler_type.to_expr_tyenv(env)
                                        ),
                                    )
                                    .span_help(
                                        &union.span(),
                                        format!(
                                            "the corresponding variant has type: `{}`",
                                            variant_type.to_expr_tyenv(env)
                                        ),
                                    )
                                    .help(format!(
                                            "a handler for this variant must be a function that takes an input of type: `{}`",
                                            variant_type.to_expr_tyenv(env)
                                        ))
                                    .format(),
                                )
                    },
                    // Union alternative without type
                    Some(None) => handler_type.clone(),
                    None => return mkerr("MergeHandlerMissingVariant"),
                };
                match &inferred_type {
                    None => inferred_type = Some(handler_return_type),
                    Some(t) => {
                        if t != &handler_return_type {
                            return mkerr("MergeHandlerTypeMismatch");
                        }
                    }
                }
            }
            for x in variants.keys() {
                if !handlers.contains_key(x) {
                    return mkerr("MergeVariantMissingHandler");
                }
            }

            let type_annot =
                type_annot.as_ref().map(|t| t.eval(env.as_nzenv()));
            match (inferred_type, type_annot) {
                (Some(t1), Some(t2)) => {
                    if t1 != t2 {
                        return mkerr("MergeAnnotMismatch");
                    }
                    t1
                }
                (Some(t), None) => t,
                (None, Some(t)) => t,
                (None, None) => return mkerr("MergeEmptyNeedsAnnotation"),
            }
        }
        ExprKind::ToMap(_, _) => unimplemented!("toMap"),
        ExprKind::Projection(record, labels) => {
            let record_type = record.get_type()?;
            let kts = match record_type.kind() {
                ValueKind::RecordType(kts) => kts,
                _ => return mkerr("ProjectionMustBeRecord"),
            };

            let mut new_kts = HashMap::new();
            for l in labels {
                match kts.get(l) {
                    None => return mkerr("ProjectionMissingEntry"),
                    Some(t) => {
                        use std::collections::hash_map::Entry;
                        match new_kts.entry(l.clone()) {
                            Entry::Occupied(_) => {
                                return mkerr("ProjectionDuplicateField")
                            }
                            Entry::Vacant(e) => e.insert(t.clone()),
                        }
                    }
                };
            }

            Value::from_kind_and_type(
                ValueKind::RecordType(new_kts),
                record_type.get_type()?,
            )
        }
        ExprKind::ProjectionByExpr(_, _) => {
            unimplemented!("selection by expression")
        }
        ExprKind::Completion(_, _) => unimplemented!("record completion"),
    })
}

/// `type_with` typechecks an expressio in the provided environment.
pub(crate) fn type_with(
    env: &TyEnv,
    expr: &Expr<Normalized>,
) -> Result<TyExpr, TypeError> {
    let (tyekind, ty) = match expr.as_ref() {
        ExprKind::Var(var) => match env.lookup(&var) {
            Some((v, ty)) => (TyExprKind::Var(v), Some(ty)),
            None => {
                return mkerr(
                    ErrorBuilder::new(format!("unbound variable `{}`", var))
                        .span_err(&expr.span(), "not found in this scope")
                        .format(),
                )
            }
        },
        ExprKind::Const(Const::Sort) => {
            (TyExprKind::Expr(ExprKind::Const(Const::Sort)), None)
        }
        ExprKind::Embed(p) => {
            return Ok(p.clone().into_value().to_tyexpr_noenv())
        }
        ekind => {
            let ekind = match ekind {
                ExprKind::Lam(binder, annot, body) => {
                    let annot = type_with(env, annot)?;
                    let annot_nf = annot.eval(env.as_nzenv());
                    let body_env = env.insert_type(binder, annot_nf);
                    let body = type_with(&body_env, body)?;
                    ExprKind::Lam(binder.clone(), annot, body)
                }
                ExprKind::Pi(binder, annot, body) => {
                    let annot = type_with(env, annot)?;
                    let annot_nf = annot.eval(env.as_nzenv());
                    let body_env = env.insert_type(binder, annot_nf);
                    let body = type_with(&body_env, body)?;
                    ExprKind::Pi(binder.clone(), annot, body)
                }
                ExprKind::Let(binder, annot, val, body) => {
                    let val = if let Some(t) = annot {
                        t.rewrap(ExprKind::Annot(val.clone(), t.clone()))
                    } else {
                        val.clone()
                    };
                    let val = type_with(env, &val)?;
                    let val_nf = val.eval(&env.as_nzenv());
                    let body_env = env.insert_value(&binder, val_nf);
                    let body = type_with(&body_env, body)?;
                    ExprKind::Let(binder.clone(), None, val, body)
                }
                _ => ekind.traverse_ref(|e| type_with(env, e))?,
            };

            let ty = type_one_layer(env, &ekind, expr.span())?;
            (TyExprKind::Expr(ekind), Some(ty))
        }
    };

    Ok(TyExpr::new(tyekind, ty, expr.span()))
}

/// Typecheck an expression and return the expression annotated with types if type-checking
/// succeeded, or an error if type-checking failed.
pub(crate) fn typecheck(e: &Expr<Normalized>) -> Result<TyExpr, TypeError> {
    type_with(&TyEnv::new(), e)
}

/// Like `typecheck`, but additionally checks that the expression's type matches the provided type.
pub(crate) fn typecheck_with(
    expr: &Expr<Normalized>,
    ty: Expr<Normalized>,
) -> Result<TyExpr, TypeError> {
    typecheck(&expr.rewrap(ExprKind::Annot(expr.clone(), ty)))
}