Chapter 8
Normalization by evaluation
The checker keeps asking one question: are two expressions the same? The Same rule asks it about the endpoints of an equality type (Section 4.1), the mode switch asks it about two types (Section 9.2), and check-same asks it directly. It is the judgment , or for types. Pie answers it with normalization by evaluation (NbE): evaluate both expressions to values, read the values back into syntax guided by the type, and compare the results up to the names of bound variables. This section follows that procedure through normalize.rkt and alpha.rkt.
8.1The idea#
In the first proof of Section 4.2, (λ (n) (same n)) checks against (Π ((n Nat)) (= Nat (+ zero n) n)) only if . The expression (+ zero n) is open, yet Pie must compute with it far enough to see that (iter-Nat zero n step) is just n. So the evaluator works on open terms: ctx->env (basics.rkt:477–488, Section 7.5) turns into an environment in which each free variable stands for itself, as a neutral value.
The detour through values back to syntax is needed because the normal form of an expression depends on its type: every normal function has λ at the top and every normal pair has cons, even when the expression is a variable (basics.rkt:187–199, quoted in Section 1.1). So normalization has two steps, which Pie keeps in two functions. val-of (normalize.rkt:384–484) evaluates Core in an environment to a value, written . read-back (normalize.rkt:567–611) turns a value back into Core at a type value , written ; we write for read-back-type, which reads back a type (normalize.rkt:532–562). Table 8.1 summarizes the procedure.
ctx->env of and . The left column is Core, the middle column holds values, and the right column holds Core normal forms, which α-equiv? compares.In Scheme terms, val-of is eval and do-ap is apply. Read-back goes the other way, like printing a value as a quoted expression, and it must go under λ: it applies the function to a fresh variable and reads back the result.NbE comes from Berger and Schwichtenberg, who present read-back (reification) as an inverse of the evaluation functional. Abel, Coquand and Dybjer extend it to dependent types with η. Christiansen’s tutorial builds a small checker with the same structure as Pie’s, and is the best companion to this section.Ulrich Berger and Helmut Schwichtenberg. An Inverse of the Evaluation Functional for Typed -calculus. In Proceedings of the Sixth Annual IEEE Symposium on Logic in Computer Science (LICS ’91), pages 203–211. IEEE Computer Society, 1991; Andreas Abel, Thierry Coquand, and Peter Dybjer. Normalization by Evaluation for Martin-Löf Type Theory with Typed Equality Judgements. In Proceedings of the 22nd Annual IEEE Symposium on Logic in Computer Science (LICS 2007), pages 3–12. IEEE Computer Society, 2007; and David Thrane Christiansen. Checking Dependent Types with Normalization by Evaluation: A Tutorial. https://davidchristiansen.dk/tutorials/nbe/, 2019. Online tutorial, first published 2018
8.2Evaluation#
val-of is a match on Core, one clause per form. Its first clauses show the whole policy:
normalize.rkt:384–396
384(: val-of (-> Env Core Value))
385(define (val-of ρ e)
386 (match e
387 [`(the ,t ,expr) (val-of ρ expr)]
388 ['U 'UNIVERSE]
389 ['Nat 'NAT]
390 ['zero 'ZERO]
391 [`(add1 ,n) (ADD1 (later ρ n))]
392 [`(Π ((,x ,A)) ,B)
393 (let ([A-v (later ρ A)])
394 (PI x A-v (FO-CLOS ρ x B)))]
395 [`(λ (,x) ,b)
396 (LAM x (FO-CLOS ρ x b))]the is dropped (387): annotations matter to the checker, not to computation. Each constructor clause builds only the outermost constructor and wraps its subterms with later, the call-by-need delay of Section 7.3 (add1 at 391). Π, λ and Σ build closures (392–396, 418–420), so evaluation never goes under a binder. Application delegates to do-ap (477–478), a variable is looked up in (481–483), and a TODO becomes a neutral (479–480; Section 6.2). The eliminator clauses look alike: (iter-Nat tgt (the b-t b) s) at 402–406 splits the annotated base of Core (Section 7.1) into its type and its value, delays all four pieces and calls do-iter-Nat.
8.3Eliminators: computing or getting stuck#
Every eliminator has a helper whose name begins with do- (normalize.rkt:107–108). Each helper forces its target with now: if the target is a constructor, it computes; if the target is neutral, it builds a bigger neutral. do-ap is the smallest case:
normalize.rkt:110–118
110(: do-ap (-> Value Value Value))
111(define (do-ap rator-v rand-v)
112 (match (now rator-v)
113 [(LAM x c)
114 (val-of-closure c rand-v)]
115 [(NEU (!! (PI x A c))
116 ne)
117 (NEU (val-of-closure c rand-v)
118 (N-ap ne (THE A rand-v)))]))On a LAM it instantiates the closure with the argument (113–114). This is β: ((λ (x) b) a) . On a neutral whose type is a PI, it returns a new neutral N-ap (115–118), whose type is the codomain closure c instantiated at the argument: dependent application, done on values. The argument is stored as (THE A rand-v), so that read-back can later process it at its type A. The !! in the pattern forces the delayed type (Section 1.3). do-iter-Nat shows both kinds of branch for a Nat eliminator:
normalize.rkt:133–144
133(: do-iter-Nat (-> Value Value Value Value Value))
134(define (do-iter-Nat tgt-v b-tv b-v s-v)
135 (match (now tgt-v)
136 ['ZERO b-v]
137 [(ADD1 n-1v)
138 (do-ap s-v (do-iter-Nat n-1v b-tv b-v s-v))]
139 [(NEU (!! 'NAT) ne)
140 (NEU b-tv
141 (N-iter-Nat ne
142 (THE b-tv b-v)
143 (THE (Π-type ((n b-tv)) b-tv)
144 s-v)))]))The two ι-rules are lines 136 and 138: (iter-Nat zero b s) b and (iter-Nat (add1 n) b s) (s (iter-Nat n b s)). Line 138 recurses on the predecessor before it calls do-ap, so the recursion along a numeral is strict even though the evaluator is lazy elsewhere (Section 7.3). On a neutral target of type 'NAT (139), the result is a neutral of type b-tv, the base type that Core keeps for exactly this purpose. The base is stored at that type, and the step at (Π ((n B)) B), with the base type, built by the Π-type macro as a higher-order closure (143).Result types of the other stuck eliminations, in normalize.rkt: do-which-Nat, the base type (127); do-ind-Nat, (mot tgt) (172), with the motive stored at (Π ((x Nat)) U) (175–180); do-cdr, the Σ closure applied to (car p) (196); do-replace, (mot to) (252); do-ind-=, (mot to tgt) (298); do-ind-Vec, (mot len es) (339, 350). do-trans has one neutral per stuck argument (264–273). Section 2.3 showed both branches at work: (λ (j) (+ 2 j)) computes to (λ (j) (add1 (add1 j))), while (λ (n) (+ n 2)) stays an iter-Nat stuck on n.
8.4Read-back and η#
Read-back has three functions: one for types, one for values at a type, and one for neutrals. In read-back-type (normalize.rkt:532–562) only the binders are subtle. To read back the codomain of a PI (537–542), it picks a name x^ fresh in (Section 7.6), extends with it as a free variable, and instantiates the closure at the neutral (NEU A (N-var x^)); Σ is the same (544–549). A neutral type is read back as a neutral (561–562).
read-back itself is directed by the type. The comment at 564–566 says that this is what allows η-expansion:
normalize.rkt:567–583
567(: read-back (-> Ctx Value Value Core))
568(define (read-back Γ tv v)
569 (match* ((now tv) (now v))
570 [('UNIVERSE v) (read-back-type Γ v)]
571 [('NAT 'ZERO) 'zero]
572 [('NAT (ADD1 n-1))
573 `(add1 ,(read-back Γ 'NAT n-1))]
574 [((PI x A c) f)
575 (let ((y (match f
576 [(LAM y _) y]
577 [_ x])))
578 (let ((x^ (fresh Γ y)))
579 `(λ (,x^)
580 ,(read-back
581 (bind-free Γ x^ A)
582 (val-of-closure c (NEU A (N-var x^)))
583 (do-ap f (NEU A (N-var x^)))))))]The clause is chosen by the type, before the value is examined, and that is where Pie’s η-rules live. At a PI (574–583) the result is always a λ: f is applied to a fresh neutral and the result is read back at the codomain. The binder name is that of f if it is a LAM, otherwise that of the PI (575–577), made fresh in (578); this is why the inner binder of (λ (a x₁) (a x₁)) in Section 7.6 is x₁. The clauses that follow cover the other types (normalize.rkt:584–602):
584 [((SIGMA x A c) p-v)
585 (let ((the-car (do-car p-v)))
586 `(cons ,(read-back Γ A the-car)
587 ,(read-back Γ
588 (val-of-closure c the-car)
589 (do-cdr p-v))))]
590 [('ATOM (QUOTE a))
591 `(quote ,a)]
592 [('TRIVIAL _) 'sole] ;; η-expansion
593 [((LIST E) 'NIL) 'nil]
594 [((LIST E) (LIST:: h t))
595 `(:: ,(read-back Γ E h) ,(read-back Γ (LIST E) t))]
596 [('ABSURD (NEU _ ne))
597 ;; This type annotation is half of the η law. See the
598 ;; implementation of α-equiv? for the other half.
599 `(the Absurd ,(read-back-neutral Γ ne))]
600 [((EQUAL Av _ _) (SAME v))
601 `(same ,(read-back Γ Av v))]
602 [((VEC Ev (!! 'ZERO)) _) 'vecnil]At a SIGMA (584–589) the result is always a cons (Section 2.4). At Absurd (596–599) a neutral is read back wrapped as (the Absurd ne), half of the η-rule; the other half is in α-equiv? (Section 8.6). At (Vec E zero) (602) the pattern _ accepts any value, neutral or not. The clauses after 602 rebuild the other constructors, and everything else falls through to the last clause, [(_ (NEU _ ne)) (read-back-neutral Γ ne)] (610–611): a neutral is read back as itself, with no η. Table 8.2 collects the rules.
read-back. Line numbers are in normalize.rkt. The second half of the Absurd rule is alpha.rkt:69–70.| type | every value reads back as | lines |
|---|---|---|
Π | (λ (x) …) | 574–583 |
Σ | (cons … …) | 584–589 |
Trivial | sole | 592 |
Absurd | (the Absurd ne), any two equal | 596–599 |
(Vec E zero) | vecnil | 602 |
Nat, List, Either, = | a neutral: itself (no η) | 610–611 |
(Vec E (add1 k)) | a neutral: itself (no η) | 610–611 |
Read-back of neutrals is not directed by the type: the type-directed step has already happened by the time a neutral is reached (normalize.rkt:613–615). read-back-neutral rebuilds the eliminator’s syntax and reads back each stored THE at its stored type. In the iter-Nat case (624–628) the base comes back annotated, (the B b), and the step is η-expanded like any function.
The η-rules are definitional equalities, and check-same sees them. The file below states one per row of Table 8.2, then prints three normal forms:
eta.pie
(check-same (→ (→ Nat Nat) (→ Nat Nat))
(λ (f) f) (λ (f) (λ (x) (f x))))
(check-same (→ (Pair Nat Atom) (Pair Nat Atom))
(λ (p) p) (λ (p) (cons (car p) (cdr p))))
(check-same (→ Trivial Trivial) (λ (t) t) (λ (t) sole))
(check-same (→ Absurd Absurd Absurd) (λ (a b) a) (λ (a b) b))
(check-same (→ (Vec Atom zero) (Vec Atom zero))
(λ (es) es) (λ (es) vecnil))
(the (→ Absurd Nat) (λ (x) (ind-Absurd x Nat)))
(the (→ (Vec Atom zero) (Vec Atom zero)) (λ (es) es))
(the (→ (Vec Atom 1) (Vec Atom 1)) (λ (es) es))(the (→ Absurd
Nat)
(λ (x)
(ind-Absurd (the Absurd x)
Nat)))
(the (→ (Vec Atom 0)
(Vec Atom 0))
(λ (es)
vecnil))
(the (→ (Vec Atom 1)
(Vec Atom 1))
(λ (es)
es))The five check-same forms succeed silently. The stuck ind-Absurd shows its target wrapped as (the Absurd x) (normalize.rkt:656–659). The identity on (Vec Atom 0) reads back as (λ (es) vecnil), while the identity on (Vec Atom 1) keeps es.
read-back (()
(PI x (later Nat) (CLOS () x Nat))
(LAM n (CLOS () n (iter-Nat (add1 (add1 zero)) (the Nat n) (λ (k) (add1 k))))))
do-ap ((LAM n (CLOS () n (iter-Nat (add1 (add1 zero)) (the Nat n) (λ (k) (add1 k))))) (NEU (later Nat) (N-var n)))
do-iter-Nat ((later (add1 (add1 zero))) (later Nat) (later n) (later (λ (k) (add1 k))))
force ((thunk (add1 (add1 zero))))
=> (ADD1 (later (add1 zero)))
do-iter-Nat ((later (add1 zero)) (later Nat) (later n) (later (λ (k) (add1 k))))
[…]
=> (later n)
do-ap ((later (λ (k) (add1 k))) (later n))
force ((thunk (λ (k) (add1 k))))
=> (LAM k (CLOS (n) k (add1 k)))
=> (ADD1 (later k))
=> (ADD1 (later k))
do-ap ((! (LAM k (CLOS (n) k (add1 k)))) (ADD1 (later k)))
=> (ADD1 (later k))
=> (ADD1 (later k))
=> (ADD1 (later k))
read-back ((n) NAT (ADD1 (later k)))
read-back ((n) NAT (later k))
force ((thunk k))
=> (ADD1 (later k))
read-back ((n) NAT (later k))
force ((thunk k))
force ((thunk n))
=> (NEU (later Nat) (N-var n))
=> (NEU (later Nat) (N-var n))
read-back-neutral ((n) (N-var n))
=> n
=> n
=> (add1 n)
=> (add1 (add1 n))
=> (λ (n) (add1 (add1 n)))(λ (n) (iter-Nat 2 n (λ (k) (add1 k)))) at (→ Nat Nat), traced. Indentation shows nesting; => gives the result of the call above it at the same depth. (later e) is a delay box whose expression e has not been evaluated; (! v) is a box already forced to v; (thunk e) is the delayed expression being forced. (CLOS names x body) is an FO-CLOS, showing only the names in its environment. read-back shows only the names in .8.5A worked trace#
Listing 8.1 traces one normalization: (λ (n) (+ 2 n)), with + unfolded, at type (→ Nat Nat). A script, trace.rkt, elaborates it with the real synth, evaluates the Core and reads the value back, through an instrumented copy of normalize.rkt (made by the patch in the folder traced/ next to the script) that logs do-ap, do-iter-Nat, undelay (printed as force) and the read-back functions. The type value is (PI x (later Nat) (CLOS () x Nat)), with the binder x chosen when -> was elaborated, and the term is a LAM, so read-back follows the Π clause. The binder name n of the LAM is reused, and do-ap applies the function to (NEU (later Nat) (N-var n)). do-iter-Nat forces the target (add1 (add1 zero)) and recurses on the predecessor twice before any step is applied; at ZERO it returns the base, still the delayed (later n). On the way back up each level applies the step, which the first do-ap forces and the second reuses (the !). Read-back at NAT then meets ADD1 twice, forcing the delayed predecessor each time, until it reaches the neutral n. The result is (λ (n) (add1 (add1 n))): the computation went through because the target of iter-Nat was a numeral, even though the base was a variable.
8.6Conversion#
The two judgments of equality are short functions in typechecker.rkt:
typechecker.rkt:795–800
795(: convert (-> Ctx Loc Value Value Value (Perhaps Void)))
796(define (convert Γ where tv av bv)
797 (let ([a (read-back Γ tv av)]
798 [b (read-back Γ tv bv)])
799 (if (α-equiv? a b)
800 (go (void))convert reads both values back at the same type value tv and compares the results with α-equiv?; if they differ, it reads back again to build the error message of a stop (801–807). Its companion same-type (782–790) does the same for two types, with read-back-type.
α-equiv? (alpha.rkt:9–11) walks the two Core terms together. It gives each bound variable a de Bruijn level, the depth of its binder, kept in one name-to-level list per side (17–22); the λ case binds both names at the current level and compares the bodies one level deeper (63–68). Two bound variables are equal when their levels are equal, two free variables when their names are equal, and a bound variable never equals a free one (27–40). Free variables can be compared by name because the checker keeps all names in distinct (Section 7.6). Line 70, quoted in Section 5.3, is the second half of the Absurd η-rule: any two terms of the form (the Absurd …) are equal. Holes are equal only when they come from the same source location (80–83; Section 6.3).
A short Racket script calls convert directly, with Pie’s own modules and no instrumentation, in the context :
convert.rkt
#lang racket/base
(require racket/pretty pie/basics pie/normalize pie/typechecker)
(define Γ (bind-free init-ctx 'n 'NAT)) ; n : Nat
(define + '(λ (n) (λ (j) (iter-Nat n (the Nat j) (λ (s) (add1 s))))))
(define here (syntax->location #'here))
(define (conv a b)
(convert Γ here 'NAT (val-in-ctx Γ a) (val-in-ctx Γ b)))
(pretty-write (conv `((,+ zero) n) 'n))
(pretty-write (conv `((,+ n) zero) 'n))#(struct:go #<void>)
#(struct:stop
#<location>
("The expressions"
(iter-Nat n (the Nat zero) (λ (s) (add1 s)))
"and"
n
"are not the same"
Nat))The two calls replay Section 4.2 at the Racket level: (+ zero n) reads back as n, so conversion returns go; (+ n zero) reads back as a stuck iter-Nat, and no rule of read-back turns it into n, so it returns a stop carrying the message. Conversion therefore contains α, β (do-ap), the ι-rules of the do- helpers, δ (ctx->env puts the values of definitions in the environment, basics.rkt:480–482) and the η-rules of Table 8.2, and nothing else.
Is this a decision procedure? Only if read-back always terminates. For well-typed terms that is a normalization theorem. Such theorems are proved for Martin-Löf type theory with η, for instance by Abel, Coquand and DybjerAndreas Abel, Thierry Coquand, and Peter Dybjer. Normalization by Evaluation for Martin-Löf Type Theory with Typed Equality Judgements. In Proceedings of the 22nd Annual IEEE Symposium on Logic in Computer Science (LICS 2007), pages 3–12. IEEE Computer Society, 2007, but not for Pie’s exact rules, which include η for Absurd and for empty vectors. The comment at normalize.rkt:15–18 assumes it (“Pie is a total language”); the code does not prove it. As for cost, every comparison normalizes both sides completely before comparing, with no early exit and no shortcut for identical definitions; for the programs of The Little Typer that is cheap.
8.7Corner cases found by running code#
Running examples against the code turned up three places where the implementation does something the theory does not suggest. None of them was shown to produce a proof of Absurd.
Implementation note (a): η for empty vectors has no matching computation. By Table 8.2, every es : (Vec Atom zero) is definitionally vecnil, and on vecnil ind-Vec computes to its base. But do-ind-Vec computes only when both targets are constructors, [('ZERO 'VECNIL) b-v] (normalize.rkt:334), and a later clause catches a neutral vector of any length:
normalize.rkt:349–351
349 [(len-v (NEU (!! (VEC Ev _)) ne))
350 (NEU (do-ap (do-ap mot-v len-v) vec-v)
351 (N-ind-Vec2 (THE 'NAT len-v)With length ZERO and a neutral vector, the clause at 349 builds a stuck N-ind-Vec2. So (ind-Vec zero es …) is not (ind-Vec zero vecnil …), although es vecnil: at this point is not a congruence. Counting the entries of an empty vector shows it:
vec0.pie
(claim count0
(Π ((es (Vec Atom zero)))
(= Nat
(ind-Vec zero es (λ (k xs) Nat) 0 (λ (k h t ih) (add1 ih)))
0)))
(define count0 (λ (es) (same 0)))The expressions
(ind-Vec 0 es
[…]
and zero are not the same Nat
location...:
vec0.pie:7:29Transport along (same es) : (= (Vec Atom zero) es vecnil) does not help either (file vec0-transport.pie of the examples): synthesized types are read back (typechecker.rkt:606–608, and 480 and 437–438 for symm and replace), so the type of the proof already has vecnil on both sides and the motive never mentions es. The statement is provable by ind-Vec on es with a motive that relates the count of a vector to its length (file vec0-ind.pie). The fix is to let do-ind-Vec return the base whenever the length is ZERO; Section 10.5 leaves it as an exercise.
Implementation note (b): two patterns that match anything. In Racket’s match, a bare identifier is a pattern variable. Two clauses use one where a quoted symbol was probably meant: (NEU UNIVERSE ne) in read-back-type (normalize.rkt:561) and (!! ABSURD) in do-ind-Absurd (241). Both accept a neutral of any type, while do-which-Nat quotes 'NAT (126). Called by hand on neutrals of the wrong type:
patvar.rkt
#lang racket/base
(require racket/pretty pie/basics pie/normalize)
(pretty-print-columns 66)
(define n (NEU 'NAT (N-var 'n))) ; a neutral n : Nat
(writeln (read-back-type (bind-free '() 'n 'NAT) n))
(pretty-write (do-ind-Absurd n 'ATOM))
(writeln (with-handlers ([exn:fail? exn-message])
(do-which-Nat (NEU 'ATOM (N-var 'a)) 'NAT 'ZERO 'ZERO)))n
#(struct:NEU
ATOM
#(struct:N-ind-Absurd
#(struct:N-var n)
#(struct:THE UNIVERSE ATOM)))
"match: no matching clause for (NEU 'ATOM (N-var 'a))"The first two accept a Nat-typed neutral; do-which-Nat rejects an Atom-typed one. A well-typed program never reaches these clauses with the wrong type, so the checker’s behaviour is not affected.
Implementation note (c): the dummy argument of a stuck cong. A neutral cong keeps only its target and its function, stored at the type (Π-type ((x A-v)) B-v) (normalize.rkt:282). Read-back needs B for the three-argument Core cong, and gets it by instantiating that closure at an arbitrary value:
normalize.rkt:670–673
670 [(N-cong ne (THE (PI y Av c) v))
671 `(cong ,(read-back-neutral Γ ne)
672 ,(read-back-type Γ (val-of-closure c 'ABSURD))
673 ,(read-back Γ (PI y Av c) v))]Applying the closure to 'ABSURD is safe only because do-cong built it to ignore its argument. That assumes the function given to cong is non-dependent, which the checker does not enforce (Section 4.3).