Chapter 9
Bidirectional checking as elaboration
The last two sections described the data the checker works on and the test it uses for equality. This section describes the checker itself, typechecker.rkt:1–897. It does two jobs in one pass. It decides whether a Src term is well typed, and it translates the term into Core. A checker that produces a translated term as a side product of checking is called an elaborator. Each form of judgment in the appendix of The Little TyperDaniel P. Friedman and David Thrane Christiansen. The Little Typer. MIT Press, Cambridge, MA, 2018 becomes one Racket function, and the output of each function is the term written after in the judgment.
9.1Judgments as functions#
Table 9.1 lists the five functions. A comment above each one names the judgment it implements (typechecker.rkt:89, 198, 656, 780, 793).
typechecker.rkt. Every function also takes , and the first three take a Renaming (Section 7.6). Every result is wrapped in Perhaps.| Judgment | Function, lines | Inputs output |
|---|---|---|
is-type, 89–195 | Src Core | |
synth, 198–653 | Src , both Core | |
check, 656–777 | Src, Value Core | |
same-type, 780–790 | two Values nothing | |
convert, 793–807 | three Values nothing |
Every function returns a Perhaps (Section 7.7): either with the result, or . A rule with several premises is written as one go-on, with one binding per premise, so the first premise that fails becomes the result of the whole rule. The two equality judgments were described in Section 8.6.
Note the asymmetry between the two middle rows. check receives the expected type as a Value, while synth returns the type it found as Core, so a caller that needs a synthesized type as a value evaluates the Core again with val-in-ctx (typechecker.rkt:603, 773).
9.2Modes#
In Section 1.4 we read and as two modes of one miniKanren relation , which Pie writes as two functions. The split follows the usual recipe of bidirectional typingBenjamin C. Pierce and David N. Turner. Local Type Inference. ACM Transactions on Programming Languages and Systems, 22(1):1–44, 2000; and Jana Dunfield and Neel Krishnaswami. Bidirectional Typing. ACM Computing Surveys, 54(5):98:1–98:38, 2021: introduction forms are checked and elimination forms synthesize.
- Only checked:
λ,cons,nil,same,vecnil,vec::,left,rightandTODO(typechecker.rkt:663–771). Each clause except the one forTODOforces the expected type withnowand takes it apart; the type supplies what the form alone does not say, such as the domain of aλor the element type ofnil. - Synthesized: variables, application,
the, every eliminator, and every type former other thanU, each of which synthesizesUwhen its parts are elements ofU. A few constructors synthesize too, because the form alone fixes their type:zero,add1and numerals,sole, quoted atoms, and::, whose element type is taken from its head (typechecker.rkt:411–414).
Two rules connect the modes. The first is the annotation rule Ann, which Section 1.4 used to show how to read a rule, together with its four lines of code (typechecker.rkt:591–594). The Core result is e-out alone: the annotation is erased. The pair (the t-out e-out) is only the way synth returns a type together with a term.The (the Nat 0) that appears in normal forms does not come from the user. synth inserts it around the base of which-Nat, iter-Nat, rec-Nat and rec-List (typechecker.rkt:260–261, 273–274, 288–289, 401–404), because a stuck elimination needs the type of its base (Section 7.1).
The second rule is the mode switch, which turns synthesis into checking.
It applies to every that is not one of the checked-only forms, because it is the last clause of check (typechecker.rkt:772–774):
772 [else (go-on ((`(the ,t-out ,e-out) (synth Γ r e))
773 (_ (same-type Γ (src-loc e) (val-in-ctx Γ t-out) tv)))
774 (go e-out))]))A wrong type found this way is reported by same-type, which prints the expected type first. The file switch-mismatch.pie holds (the Nat (quote a)) and gives:
Expected Nat but given Atom
location...:
switch-mismatch.pie:2:9No rule lets a checked-only form synthesize without an annotation. When synth meets a form for which it has no clause, such as a bare constructor, its last clause stops with “Can’t determine a type” (typechecker.rkt:648–650). Section 2.6 listed the positions where this happens.
Why no unification is needed. In every rule, the inputs of each premise are known by the time it runs, from the inputs of the conclusion or from the outputs of earlier premises. Take ind-Nat (Section 3.1). The target is checked against Nat, and the motive against (Π ((n Nat)) U). Once the motive is elaborated and evaluated, (mot zero) is known, so the base can be checked, and the same holds for the step. Nothing has to be guessed. The relational typeo, run on a bare (λ (x) x) with fresh, would bind to a Π type whose domain is a new logic variable, left for later goals to fill in. Pie would need types that contain unknowns, and unification on them. Core has no form for a metavariable that unification could solve (basics.rkt:138–182; its TODO is a hole that is never solved, Section 6.2), so synth has nothing to return, and it stops. The price is the annotations of Section 2.6. In return, each judgment is an ordinary function from inputs to a result or an error, and no constraint is ever left pending.
An eliminator clause of synth first finds the type of its target, then inspects that type value, and then checks the remaining arguments against types it builds directly as values, with HO-CLOS and the Π-type macro (Section 7.2), so that check can receive them as its fourth argument.
9.3Rules next to code#
We now put three rules next to their code. The rules for ind-Nat, same and cong were paired with their code in Section 3.1, Section 4.1 and Section 4.3. Rules leave out the Renaming argument.
Checking λ. Let be the expected type.
In the code (typechecker.rkt:663–676) the expected type is forced with now and must be a PI. The body is checked against the codomain closure applied to a neutral variable. This is the trick of read-back (Chapter 8) used inside the checker: to look under a binder, give the binder a value that is a variable. The parameter gets a name that is fresh for , and the Renaming maps the user’s name to it. A λ with several parameters is rewritten into nested one-parameter λs before checking (typechecker.rkt:677–684). We call the elaborator from Racket with a script, elab.rkt, which parses a datum with parse-pie and prints what synth, check or is-type returns. The renaming shows when the name is already taken:
check (λ (p) p) against (Π ((n Nat)) Nat), with p : Nat in Γ
=> (λ (p₁) p₁)
check (λ (x x) x) against (Π ((a Nat)) (Π ((b Nat)) Nat))
=> (λ (x) (λ (x₁) x₁))In the first call already holds p, so the parameter becomes p₁; in the second, the inner x is renamed because the outer one is in when the inner λ is checked. A λ checked against a type that is not a Π fails with the same message as the application below.
Application.
The code (typechecker.rkt:599–611) carries the book’s form of the rule as a comment:
595 ;;; Γ ⊢ f synth ~> (the (Pi ((x A)) B) f')
596 ;;; Γ ⊢ a ∈ A ~> a'
597 ;;; ----------------------------------------
598 ;;; Γ ⊢ (f a) synth ~> (the B[a'/x] (f' a'))The substitution of the comment is not done on syntax. The codomain closure is applied to the value of the argument (608), and the resulting type value is read back to Core (606). Application to several arguments peels off the last argument and recurs on the rest (typechecker.rkt:612–629), so (f a b) elaborates to ((f a) b). The result is not normalized: an annotated β-redex stays a β-redex in Core. An operator whose type is not a Π, such as zero in (the Nat (zero 1)), is rejected at 610–611 with “Not a function type:” followed by that type.
Π, as a type and as an element of U. Π has two formation rules, one for each judgment that can be asked about it.
In is-type (typechecker.rkt:115–121) the premises are again is-type. In synth they are checks against 'UNIVERSE, with a binder name made fresh for and recorded in the Renaming (typechecker.rkt:226–235). The difference matters for a Π whose domain is U. U is a type (typechecker.rkt:96), so Π-Type accepts (Π ((A U)) A). But checking U against U goes through the mode switch to synth, which refuses U (typechecker.rkt:206–208; Section 5.4), so Π-U fails: (the U (Π ((A U)) A)) is rejected at the domain U with “U is a type, but it does not have a type.” At top level the type alone is accepted and printed without the (Section 9.5), as the first output of pi-is-a-type.pie shows:
(Π ((A U))
A)
[…]9.4Elaboration#
The output of the judgments is Core (Section 7.1), so every piece of sugar is removed by the clause that handles it.
->becomes Π. The binder name comes fromfresh-binder, which avoids the names in and every name occurring in the codomain (typechecker.rkt:98–106;basics.rkt:549–551). In the last call below, the codomain mentions the variablexof , so the binder isx₁; a binder namedxwould capture it.- An arrow with several arguments, and Π or Σ with several binders, are peeled one argument or binder at a time (
typechecker.rkt:107–114, 122–131, 150–159). Pairbecomes Σ. Inis-typethe binder (x, orx₁and so on) comes fromfresh-binder(typechecker.rkt:134–140), so it never occurs in the second component and resugaring turns the Σ back into aPair. Insynththe bindera(ora₁, …) is chosen byfresh, which avoids only the names in (typechecker.rkt:305–312), so it can capture an unboundaof the second component, and the result then prints as a Σ (the implementation note of Section 7.6).- A numeral is elaborated as , checking against
Natrecursively (typechecker.rkt:639–647).
Selected calls from the output of elab.rkt:
synth (the (-> Nat Nat Nat) (λ (a b) a))
=> (the (Π ((x Nat)) (Π ((x₁ Nat)) Nat)) (λ (a) (λ (b) a)))
[…]
is-type (Pair Nat Atom)
=> (Σ ((x Nat)) Atom)
synth (Pair Nat Atom)
=> (the U (Σ ((a Nat)) Atom))
is-type (-> Nat (= Nat x x)) under x : Nat
=> (Π ((x₁ Nat)) (= Nat x x))The type judgment. Most of is-type is one clause per type former. Its last clause covers everything else by checking the expression against U, the rule implies (typechecker.rkt:179–192). This clause is what lets a defined name of type U be used as a type:
type-defined-type.pie
(claim T U)
(define T Nat)
(claim x T)
(define x 4)
x
T(the Nat 4)
(the U Nat)When the check fails, lines 183–192 replace its message: a variable gets “Expected U but given” followed by its type, and anything else, such as the 5 in (claim x 5), gets “Not a type”.
9.5The top level#
A Pie file is a sequence of claim, define, check-same and expressions (parser.rkt:395–423). claim and define extend (Section 7.5). A claim adds a name with its type:
A definition replaces the claim by the claimed type and a value:
Claim is add-claim (typechecker.rkt:831–836), which calls not-used to reject any name already in (typechecker.rkt:812–816) and then is-type. Define is add-def:
849(: add-def (-> Ctx Symbol Loc Src (Perhaps Ctx)))
850(define (add-def Γ f f-loc expr)
851 (go-on ((tv (get-claim Γ f-loc f))
852 (expr-out (check Γ '() expr tv)))
853 (go (bind-val (remove-claim f Γ) f tv (val-in-ctx Γ expr-out)))))In it, get-claim returns the claimed type, or stops if there is no claim or the name is already defined (typechecker.rkt:818–829). The body is checked in the that still holds the claim, and var-type skips claims, which is why a definition cannot mention itself (Section 2.5). Only after the check is the claim replaced by the definition (853). A second (claim n Nat) gives “The name n is aready used.”, with the typo of typechecker.rkt:815; a second define gives “The name n is already defined.”; and (define n 3) alone gives
No claim: n
location...:
top-define-no-claim.pie:2:8The driver is the macro pie-module-begin (main.rkt:119–159). It walks the forms in order, threading , and turns the first stop into an exception with raise-pie-error (pie-err.rkt:25–30). A check-same elaborates its type, checks both expressions against it and calls convert (rep.rkt:50–58). A bare expression goes through norm (rep.rkt:25–36) and is then resugared and printed (main.rkt:152–157). norm synthesizes, evaluates, and reads back both the type and the term. When synthesis fails, it tries the expression as a type with norm-type (rep.rkt:12–15), and if that succeeds it returns the type alone, without the. This is why U and (Π ((A U)) A) print as bare types (Section 9.3), while a type that does synthesize, such as T in Section 9.4, prints as (the U Nat). The error of the first attempt is reported only if both attempts fail.
Checking happens at compile time. The loop of main.rkt:119–159 runs inside the #%module-begin macro, so results are printed while the module is expanded. The compiled module keeps the TODO reports but not the results (Section 6.2). On a file with one TODO, phase.pie, raco make phase.pie prints the two results while it compiles, and running the compiled file afterwards prints only the TODO goal.
9.6Printing#
What norm returns is Core. Before printing, resugar (resugar.rkt:11–109) puts sugar back: add1 chains ending in zero become numerals (17–25), nested λs merge (32–35), a Π whose variable is not free in its codomain becomes → and a Σ in the same situation becomes Pair (36–51), curried applications are flattened (98–107), and the type argument of Core cong is dropped (87–92). The test for → is made one binder at a time, using the free variables that resugar* returns together with each term, so an arrow and a Π can appear side by side. The pretty-printer print-pie (pretty.rkt:99–175) then chooses the line breaks.
Error messages take another path. A message is a list of strings and Core terms (Section 7.7), and pprint-message prints the strings as they are, a symbol inline between spaces, and any other Core term resugared on its own indented line (pretty.rkt:191–200). A symbol is not resugared, so in the message for (check-same Nat 0 1) the Core zero is printed as zero, while (add1 zero) becomes 1:
The expressions zero and
1
are not the same Nat
location...:
print-zero-in-message.pie:2:0Implementation notes. Two defects of the printing layer showed up while running examples.
First, resugar has rules that print lists and vectors as (list …) and (vec …) (resugar.rkt:52–77), which are not Pie syntax. The rules that start a list match (:: hd (nil)), but Core nil and vecnil are symbols, so those rules never fire. The rules that extend a list, and the vec:: rule (74–75), test whether the resugared tail starts with the symbol list, so a tail that applies a variable named list is mistaken for a list. The file print-list-var-only.pie annotates (λ (list) (:: 1 (list 2))) with its type and prints
(the (→ (→ Nat
(List Nat))
(List Nat))
(λ (list)
(list 1 2)))Second, the parser rewrites Pi and ∏ to Π without syntax/loc (parser.rkt:281–284), while Sigma uses it (296–297). A malformed Pi, such as (Pi (x Nat) Nat), is therefore reported at parser.rkt:282:18 rather than in the user’s file, while the message for (Sigma (x Nat) Nat) starts with print-sigma-shape.pie:2:0.