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 ⇝\rightsquigarrow 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).

Table 9.1: The judgments of typechecker.rkt. Every function also takes Γ\Gamma, and the first three take a Renaming (Section 7.6). Every result is wrapped in Perhaps.
JudgmentFunction, linesInputs →\to output
Γ⊢e 𝗍𝗒𝗉𝖾⇝c\Gamma \vdash e\ \mathsf{type} \rightsquigarrow cis-type, 89–195Src →\to Core
Γ⊢e⇒A⇝c\Gamma \vdash e \Rightarrow A \rightsquigarrow csynth, 198–653Src →\to (the A c)\texttt{(the}\ A\ c\texttt{)}, both Core
Γ⊢e⇐V⇝c\Gamma \vdash e \Leftarrow V \rightsquigarrow ccheck, 656–777Src, Value →\to Core
Γ⊢A≡B 𝗍𝗒𝗉𝖾\Gamma \vdash A \equiv B\ \mathsf{type}same-type, 780–790two Values →\to nothing
Γ⊢a≡b:V\Gamma \vdash a \equiv b : Vconvert, 793–807three Values →\to nothing

Every function returns a Perhaps (Section 7.7): either (go x)\texttt{(go}\ x\texttt{)} with the result, or (stop loc msg)\texttt{(stop}\ \mathit{loc}\ \mathit{msg}\texttt{)}. 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 ⇐\Leftarrow and ⇒\Rightarrow as two modes of one miniKanren relation (typeo Γ e T)\texttt{(typeo}\ \Gamma\ e\ T\texttt{)}, 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, right and TODO (typechecker.rkt:663–771). Each clause except the one for TODO forces the expected type with now and takes it apart; the type supplies what the form alone does not say, such as the domain of a λ or the element type of nil.
  • Synthesized: variables, application, the, every eliminator, and every type former other than U, each of which synthesizes U when its parts are elements of U. A few constructors synthesize too, because the form alone fixes their type: zero, add1 and 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.

Γ⊢e⇒A⇝e′Γ⊢𝗏𝖺𝗅(A)≡V 𝗍𝗒𝗉𝖾Γ⊢e⇐V⇝e′  (Switch) \dfrac{\Gamma \vdash e \Rightarrow A \rightsquigarrow e' \qquad \Gamma \vdash \mathsf{val}(A) \equiv V\ \mathsf{type}}{\Gamma \vdash e \Leftarrow V \rightsquigarrow e'} \; (\text{Switch})

It applies to every ee 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:9

No 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 TT fresh, would bind TT 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 VV be the expected type.

V=(PI y A c)x′=𝖿𝗋𝖾𝗌𝗁Γ(x)Γ,x′:A⊢b⇐c((NEU A (N-var x′)))⇝b′Γ⊢(λ (x) b)⇐V⇝(λ (x′) b′)  (Lam) \dfrac{V = \texttt{(PI}\ y\ A\ c\texttt{)} \qquad x' = \mathsf{fresh}_\Gamma(x) \qquad \Gamma, x'{:}A \vdash b \Leftarrow c(\texttt{(NEU}\ A\ \texttt{(N-var}\ x'\texttt{))}) \rightsquigarrow b'}{\Gamma \vdash \texttt{(}\lambda\ \texttt{(}x\texttt{)}\ b\texttt{)} \Leftarrow V \rightsquigarrow \texttt{(}\lambda\ \texttt{(}x'\texttt{)}\ b'\texttt{)}} \; (\text{Lam})

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 Γ\Gamma, 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 Γ\Gamma already holds p, so the parameter becomes p₁; in the second, the inner x is renamed because the outer one is in Γ\Gamma when the inner λ is checked. A λ checked against a type that is not a Π fails with the same message as the application below.

Application.

Γ⊢f⇒T⇝f′𝗏𝖺𝗅(T)=(PI x A c)Γ⊢a⇐A⇝a′Γ⊢(f a)⇒𝗋𝖻𝗍Γ(c(𝗏𝖺𝗅(a′)))⇝(f′ a′)  (App) \dfrac{\Gamma \vdash f \Rightarrow T \rightsquigarrow f' \qquad \mathsf{val}(T) = \texttt{(PI}\ x\ A\ c\texttt{)} \qquad \Gamma \vdash a \Leftarrow A \rightsquigarrow a'}{\Gamma \vdash \texttt{(}f\ a\texttt{)} \Rightarrow \mathsf{rbt}_\Gamma(c(\mathsf{val}(a'))) \rightsquigarrow \texttt{(}f'\ a'\texttt{)}} \; (\text{App})

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 B[a′/x]B[a'/x] 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.

Γ⊢A 𝗍𝗒𝗉𝖾⇝A′Γ,x′:𝗏𝖺𝗅(A′)⊢B 𝗍𝗒𝗉𝖾⇝B′Γ⊢(Π ((x A)) B) 𝗍𝗒𝗉𝖾⇝(Π ((x′ A′)) B′)  (Π-Type) \dfrac{\Gamma \vdash A\ \mathsf{type} \rightsquigarrow A' \qquad \Gamma, x'{:}\mathsf{val}(A') \vdash B\ \mathsf{type} \rightsquigarrow B'}{\Gamma \vdash \texttt{(}\Pi\ \texttt{((}x\ A\texttt{))}\ B\texttt{)}\ \mathsf{type} \rightsquigarrow \texttt{(}\Pi\ \texttt{((}x'\ A'\texttt{))}\ B'\texttt{)}} \; (\Pi\text{-Type}) Γ⊢A⇐U⇝A′Γ,x′:𝗏𝖺𝗅(A′)⊢B⇐U⇝B′Γ⊢(Π ((x A)) B)⇒U⇝(Π ((x′ A′)) B′)  (Π-U) \dfrac{\Gamma \vdash A \Leftarrow \texttt{U} \rightsquigarrow A' \qquad \Gamma, x'{:}\mathsf{val}(A') \vdash B \Leftarrow \texttt{U} \rightsquigarrow B'}{\Gamma \vdash \texttt{(}\Pi\ \texttt{((}x\ A\texttt{))}\ B\texttt{)} \Rightarrow \texttt{U} \rightsquigarrow \texttt{(}\Pi\ \texttt{((}x'\ A'\texttt{))}\ B'\texttt{)}} \; (\Pi\text{-U})

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 Γ\Gamma 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 from fresh-binder, which avoids the names in Γ\Gamma and every name occurring in the codomain (typechecker.rkt:98–106; basics.rkt:549–551). In the last call below, the codomain mentions the variable x of Γ\Gamma, so the binder is x₁; a binder named x would 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).
  • Pair becomes Σ. In is-type the binder (x, or x₁ and so on) comes from fresh-binder (typechecker.rkt:134–140), so it never occurs in the second component and resugaring turns the Σ back into a Pair. In synth the binder a (or a₁, …) is chosen by fresh, which avoids only the names in Γ\Gamma (typechecker.rkt:305–312), so it can capture an unbound a of the second component, and the result then prints as a Σ (the implementation note of Section 7.6).
  • A numeral n>0n > 0 is elaborated as (add1 n−1)\texttt{(add1}\ n-1\texttt{)}, checking n−1n-1 against Nat recursively (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 Γ⊢e⇐U⇝c\Gamma \vdash e \Leftarrow \texttt{U} \rightsquigarrow c implies Γ⊢e 𝗍𝗒𝗉𝖾⇝c\Gamma \vdash e\ \mathsf{type} \rightsquigarrow c (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 Γ\Gamma (Section 7.5). A claim adds a name with its type:

x∉dom(Γ)Γ⊢T 𝗍𝗒𝗉𝖾⇝T′Γ⊢(claim x T)⇝Γ,x↦𝖼𝗅𝖺𝗂𝗆 𝗏𝖺𝗅(T′)  (Claim) \dfrac{x \notin \mathrm{dom}(\Gamma) \qquad \Gamma \vdash T\ \mathsf{type} \rightsquigarrow T'}{\Gamma \vdash \texttt{(claim}\ x\ T\texttt{)} \rightsquigarrow \Gamma, x \mapsto \mathsf{claim}\ \mathsf{val}(T')} \; (\text{Claim})

A definition replaces the claim by the claimed type and a value:

Γ(x)=𝖼𝗅𝖺𝗂𝗆 VΓ⊢e⇐V⇝e′Γ⊢(define x e)⇝(Γ∖x),x↦𝖽𝖾𝖿 V 𝗏𝖺𝗅(e′)  (Define) \dfrac{\Gamma(x) = \mathsf{claim}\ V \qquad \Gamma \vdash e \Leftarrow V \rightsquigarrow e'}{\Gamma \vdash \texttt{(define}\ x\ e\texttt{)} \rightsquigarrow (\Gamma \setminus x), x \mapsto \mathsf{def}\ V\ \mathsf{val}(e')} \; (\text{Define})

Claim is add-claim (typechecker.rkt:831–836), which calls not-used to reject any name already in Γ\Gamma (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 Γ\Gamma 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:8

The driver is the macro pie-module-begin (main.rkt:119–159). It walks the forms in order, threading Γ\Gamma, 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:0

Implementation 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.