Chapter 7

Inside Pie: syntax, values and contexts

From here on we read the implementation. Chapter 8 explains how Pie computes and decides equality, and Chapter 9 how it checks programs. Both manipulate the data structures that this section describes, most of them defined in basics.rkt. The Racket idioms of the excerpts were explained in the paragraph “Reading the Racket” of Section 1.3.

Besides Pie programs, we show the output of two Racket scripts, repr.rkt and elaborate.rkt, which call Pie’s modules directly.The scripts call the modules of an unmodified copy of Pie. Racket prints a struct as #(struct:NAME field ...) and a box as #&. For long values, repr.rkt uses a compact printer of its own, which forces nothing: a struct prints as (NAME field ...), a delayed value not yet computed as (later e), one already computed as (! v).

7.1Src and Core

Pie has two syntaxes. The parser produces Src, the syntax the user wrote, whose every node is a struct @ pairing a source location with the node (basics.rkt:59–62). The locations let an error message point at the exact subterm. The grammar Src-Stx (basics.rkt:83–132) keeps all of the sugar: -> with several arguments, Π, λ and Σ with several binders, Pair, numerals as Racket naturals, and application to several arguments.

Elaboration (Chapter 9) turns Src into Core, the syntax that evaluation and read-back work on. Core terms are plain quasiquoted S-expressions without locations, “because they by definition are not written by a user” (basics.rkt:134–137). An excerpt of the grammar:

145     (List 'which-Nat Core (List 'the Core Core) Core)
146     (List 'iter-Nat Core (List 'the Core Core) Core)
147     (List 'rec-Nat Core (List 'the Core Core) Core)
148     (List 'ind-Nat Core Core Core Core)
149     (List 'Π (List (List Symbol Core)) Core)
150     (List 'λ (List Symbol) Core)

Π, λ and Σ bind one variable each, application takes one argument (basics.rkt:182), and there is no ->, Pair or numeral: a numeral becomes a chain of add1 (typechecker.rkt:639–647). elaborate.rkt prints, for three inputs, the Core that synth produces and the normal form after resugaring (Section 9.6):

SURFACE  (-> Nat Atom Nat)
CORE     (the U (Π ((x Nat)) (Π ((x₁ Atom)) Nat)))
RESUGAR  (the U (→ Nat Atom Nat))
SURFACE  (Pair Nat Atom)
CORE     (the U (Σ ((a Nat)) Atom))
RESUGAR  (the U (Pair Nat Atom))
SURFACE  (the (-> Nat Nat Nat) (λ (x x) x))
CORE     (the (Π ((x Nat)) (Π ((x₁ Nat)) Nat)) (λ (x) (λ (x₁) x₁)))
RESUGAR  (the (→ Nat Nat Nat) (λ (x x₁) x₁))

The binders x, x₁ and a were invented by the elaborator, and the shadowed x was renamed (Section 7.6).

Core also records two things the user did not write. First, the base of which-Nat, iter-Nat, rec-Nat and rec-List is stored with its type, as (the B b) (lines 145–147 above, and 160). The evaluator needs that type when the target is stuck. Then do-which-Nat cannot compute, and it builds a neutral term whose type is the base type (normalize.rkt:126–131; Section 7.4). The eliminators that take a motive need no such annotation: their result type comes from the motive. Second, Core cong has a third argument, the result type that the checker found while synthesizing (basics.rkt:168; typechecker.rkt:459–472); printing drops it again (resugar.rkt:87–92).

7.2Values and closures

Evaluation turns Core into values, whose constructors are written in capitals so that they cannot be confused with Core (basics.rkt:198–199, quoted in Section 1.1). Type values such as 'NAT, PI and VEC sit next to ADD1, LAM and VEC::, because in a dependent type theory a type is computed like any other value. Two members of the union Value (basics.rkt:230–243) are new to a Scheme programmer: NEU is a neutral value (Section 7.4), and DELAY supports call-by-need evaluation (Section 7.3). A binding form, PI, LAM or SIGMA, keeps the name of its variable and a closure for its body (basics.rkt:209–217). The name is not needed to compute; read-back uses it as a suggestion when it invents a variable (Section 8.4), which is why normal forms reuse the names the user wrote.

A closure is a body waiting for the value of its variable. Pie has two kinds:

521(struct FO-CLOS ([env : Env] [var : Symbol] [expr : Core]) #:transparent)
529(struct HO-CLOS ([proc : (-> Value Value)]) #:transparent)

A first-order closure FO-CLOS is the closure of a Scheme interpreter: an environment, a parameter and a body, here a Core expression. A higher-order closure HO-CLOS is a Racket procedure standing for one. val-of-closure instantiates either kind, by evaluating the body in the extended environment or by calling the procedure (normalize.rkt:720–725). val-of builds an FO-CLOS whenever it meets a binder. The values of (λ (x) (add1 x)) and (Π ((x Nat)) Nat) in the empty context are

value of (λ (x) (add1 x)):
#(struct:LAM x #(struct:FO-CLOS () x (add1 x)))
value of (Π ((x Nat)) Nat):
#(struct:PI
  x
  #(struct:DELAY #&#(struct:DELAY-CLOS () Nat))
  #(struct:FO-CLOS () x Nat))

Evaluation stops at the binder: the body is kept as syntax, together with the empty environment ().

Why two kinds? An FO-CLOS is easy to inspect, but hard to build from values the checker already has, because they would first have to be read back into Core (basics.rkt:514–528). The checker needs such closures often: the type of the step of ind-Nat, for instance, is assembled from the value of the motive (Section 3.1). The macro Π-type builds a PI whose result type is an HO-CLOS:

 97(define-syntax (Π-type stx)
 98  (syntax-parse stx
 99    [(_ () ret) (syntax/loc stx ret)]
100    [(_ ((x:id arg-t) b ...) ret)
101     (syntax/loc stx
102       (PI 'x arg-t (HO-CLOS (λ (x) (Π-type (b ...) ret)))))]))

Read-back cannot look inside a procedure. It applies the closure to a fresh neutral variable and reads back the result, exactly as for an FO-CLOS (normalize.rkt:537–542).

7.3Call-by-need

val-of evaluates only the outermost constructor of a term. Every subterm is wrapped by later in a DELAY, a mutable box that first holds a DELAY-CLOS, an environment with a Core expression not yet evaluated (basics.rkt:201–205):

50(: later (-> Env Core Value))
51(define (later ρ expr)
52  (DELAY (box (DELAY-CLOS ρ expr))))

now forces a delayed value. It evaluates the expression and overwrites the box with the result, so the work is done at most once:

70(: now (-> Value Value))
71(define (now v)
72  (match v
73    [(DELAY (and b (box v)))
74     (if (DELAY-CLOS? v)
75         (let ((the-value (undelay v)))
76           (set-box! b the-value)
77           the-value)
78         v)]
79    [other other]))

This is Scheme’s delay and force with memoization, written by hand. A DELAY is not a Pie value, only a device for evaluation order, so every function that inspects the shape of a value must call now first, or match with the pattern (!! p), which calls now and then matches p (normalize.rkt:81–91). Sharing shows when a delayed expression is used twice. The script evaluates ((λ (x) (cons x x)) (f zero)), with f bound to a function value whose body is a Racket procedure that counts its calls:

value of ((λ (x) (cons x x)) (f zero)), compact:
(CONS (later x) (later x))
applications of f after forcing the car: 1
applications of f after forcing the cdr too: 1
the pair now, compact:
(CONS (! (ADD1 (later zero))) (! (ADD1 (later zero))))

Each field of the pair is a delayed lookup of x, and x is bound to a single box holding (f zero). Forcing the car fills that box, and forcing the cdr finds it full, so f runs once.

Implementation note. The comment introducing call-by-need claims more laziness than the code provides. It says that (zerop (double 10000)) evaluated lazily needs “only one step to discover that the value has add1 at the top” (normalize.rkt:20–28). But the eliminators do not delay their recursive calls. In do-iter-Nat (Section 8.3) the clause for ADD1 computes the recursive call before do-ap runs (normalize.rkt:137–138). To find the top constructor of (iter-Nat n 0 step), Pie applies the step n times, as a step whose body counts its calls shows:

iter-Nat on 10 reaches ADD1 after 10 applications of the step
iter-Nat on 100 reaches ADD1 after 100 applications of the step
iter-Nat on 1000 reaches ADD1 after 1000 applications of the step

So double in the comment’s example applies its step 10000 times, not once.

7.4Neutral terms

When a variable has no value, an eliminator applied to it cannot compute, as the stuck iter-Nat of Section 2.3 showed. The evaluator represents it by a neutral term, a value that records the stuck elimination, always paired with its type:

229(struct NEU ([type : Value] [neutral : Neutral]) #:transparent)

The type is needed twice. Read-back is directed by types, so it must know the type of a neutral to η-expand it (Section 8.4). And an eliminator applied to a neutral must compute the type of its own stuck result: do-ap on a neutral function takes the result type from the function’s Π type (normalize.rkt:115–118).

The neutrals themselves are one struct per eliminator, typed so that only stuck terms can be represented:

249(struct N-var ([name : Symbol]) #:transparent)
250(struct N-TODO ([where : Srcloc] [type : Value]) #:transparent)
251(struct N-which-Nat ([target : Neutral] [base : Norm] [step : Norm]) #:transparent)
252(struct N-iter-Nat ([target : Neutral] [base : Norm] [step : Norm]) #:transparent)

The target of N-iter-Nat has type Neutral, so it cannot be a numeral. Every other argument is a Norm, a value paired with its type by the struct THE (basics.rkt:320), so that read-back can process it by its type too, for example by η-expanding a stuck iter-Nat’s step. An eliminator with two targets can be stuck on either or both, so trans and ind-Vec have three structs each (basics.rkt:269–271, 278–295).

With a free variable g of type (Π ((n Nat)) Nat) in the context, the script evaluates (which-Nat (g zero) (the Nat zero) (λ (n) n)) and reads it back at Nat:

value of (which-Nat (g zero) (the Nat zero) (λ (n) n)), compact:
(NEU
 (later Nat)
 (N-which-Nat
  (N-ap (N-var g) (THE (! NAT) (later zero)))
  (THE (later Nat) (later zero))
  (THE (PI n NAT (HO-CLOS <procedure>)) (later (λ (n) n)))))
its read-back at Nat:
(which-Nat (g zero) (the Nat zero) (λ (n) n))

The application (g zero) is an N-ap that keeps its argument with the type Nat. The which-Nat is stuck because its target is stuck; its base keeps the type recorded in Core, and its step the type (Π ((n Nat)) Nat) that Π-type built (normalize.rkt:130). Read-back turns each struct back into the eliminator it records (read-back-neutral, normalize.rkt:616–711).

7.5Contexts and environments

The checker’s context Γ is a list mapping names to binders of three kinds:

411(define-type Binder (U Def Free Claim))
412(define-type Claim claim)
413(struct claim ([type : Value]) #:transparent)
414(struct def ([type : Value] [value : Value]) #:transparent #:type-name Def)
415(struct free ([type : Value]) #:transparent #:type-name Free)

A free binder is a variable bound by λ, Π or Σ while checking; a def binder is a definition, with its type and value; a claim binder “doesn’t actually bind a name; however, it reserves the name for later definition” (basics.rkt:405–410). The lookup of a type skips claims:

420(: var-type (-> Ctx Loc Symbol (Perhaps Value)))
421(define (var-type Γ where x)
422  (match Γ
423    ['() (stop where `("Unknown variable" ,x))]
424    [(cons (cons y (claim tv)) Γ-next)
425     (var-type Γ-next where x)]
426    [(cons (cons y b) Γ-next)
427     (if (eqv? x y)
428         (go (binder-type b))
429         (var-type Γ-next where x))]))

So a claimed name is unknown until it is defined, even inside its own definition. This is half of the mechanism behind “Unknown variable loop” in Section 2.5; the other half is in add-def (Section 9.5). Binding a free name that is already in Γ is an internal error (basics.rkt:442–446), so the elaborator keeps all names distinct (Section 7.6).

Evaluation needs an environment, a list mapping names to values (basics.rkt:468–469). ctx->env computes one from Γ:

477(: ctx->env (-> Ctx Env))
478(define (ctx->env Γ)
479  (match Γ
480    [(cons (cons x (def tv v)) Γ-next)
481     (cons (cons x v)
482           (ctx->env Γ-next))]
483    [(cons (cons x (free tv)) Γ-next)
484     (cons (cons x (NEU tv (N-var x)))
485           (ctx->env Γ-next))]
486    [(cons (cons x (claim tv)) Γ-next)
487     (ctx->env Γ-next)]
488    ['() '()]))

A free variable evaluates to itself, as the neutral (NEU tv (N-var x)), which is what makes open terms, such as the body of a λ under check, evaluable. A definition contributes its value, so definitions are always unfolded (the δ-rule). A claim contributes nothing. For a context with a claimed f, a free y and a defined five, the script prints the environment and the types of y and f:

ctx->env of ((f claim Nat) (y free Nat) (five def Nat 1)):
((y . #(struct:NEU NAT #(struct:N-var y)))
 (five . #(struct:ADD1 ZERO)))
var-type of y:
#(struct:go NAT)
var-type of f, which is only claimed:
#(struct:stop #<location> ("Unknown variable" f))

7.6Names

Pie represents variables by name, not by De Bruijn indices, so it must invent names that do not clash. freshen takes the names in use and a suggestion, and returns the suggestion if it is free (fresh.rkt:7–11). Otherwise split-name separates a stem from a subscript number, 1 when there is none (100–105), and freshen-aux counts up until the name is free (14–18). fresh avoids the names of Γ; fresh-binder also avoids every name occurring in a Src expression, bound names included (basics.rkt:541–551, 562–566). From the script:

freshen:
(x₁ x₂ x₂ n-1₁ y)
fresh in a context that has g:
g₁
fresh-binder for x in (Π ((x Nat)) (= Nat x x)):
x₁
read-back-type of (Π ((x Nat)) Nat) in a context that has x:
(Π ((x₁ Nat)) Nat)

Names are freshened in three places. The elaborator invents the binders of -> and Pair. When the user shadows a binder, the elaborator picks a fresh name and records the pair in a renaming, an association list consulted with assv whenever a variable is looked up (typechecker.rkt:76–82, 632). That is how (λ (x x) x) got its x₁ in Section 7.1. Finally, read-back freshens every binder it rebuilds (normalize.rkt:539, 546, 578).

Invented names show up in normal forms. The identity id of Section 2.2, applied to two function types, and a λ whose two parameters have the same name, written with the aliases Pi and lambda:

functions-names.pie

(claim id (Π ((A U)) (→ A A)))
(define id (λ (A a) a))
(id (→ Nat Nat))
(id (Π ((y Nat)) Nat))
(the (Pi ((x Nat) (x Nat)) Nat) (lambda (x x) x))
(the (→ (→ Nat
           Nat)
         Nat
       Nat)
  (λ (a x₁)
    (a x₁)))
(the (→ (→ Nat
           Nat)
         Nat
       Nat)
  (λ (a y)
    (a y)))
(the (→ Nat Nat
       Nat)
  (λ (x x₁)
    x₁))

The identity on functions prints as (λ (a x₁) (a x₁)), not (λ (a) a): read-back at a Π type always builds a λ, applied to all its arguments, which is the η-rule for Π (Section 8.4). When read-back η-expands a function that is not a LAM, it names the new λ after the binder of the Π type (normalize.rkt:575–577). For (Π ((y Nat)) Nat) that binder is the user’s y. For (→ Nat Nat) it is an invented x, renamed x₁ by read-back-type when the type of (id (→ Nat Nat)) was read back, because the outer arrow already bound x.

Implementation note. The elaborator invents binders with fresh-binder, except in one clause. When Pair is synthesized at U, its binder is chosen with fresh, which ignores the second component:

305     [`(Pair ,A ,D)
306      (let ([a (fresh Γ 'a)])

If the second component mentions an unbound a, the invented binder captures it, and Pair becomes a dependent pair. A claim elaborates its type with is-type, whose Pair clause uses fresh-binder (typechecker.rkt:134–140), so (claim p (Pair Nat (Vec Atom a))) fails with “Unknown variable a”. A define checks its body against the claimed U, and the mode switch (typechecker.rkt:772–774) sends it to the synth clause:

pair-capture.pie

(claim T U)
(define T (Pair Nat (Vec Atom a)))
T
(the T (cons 2 (vec:: 'x (vec:: 'y vecnil))))
(the U
  (Σ ((a Nat))
   (Vec Atom a)))
[…]

This program should fail with “Unknown variable a”. What it accepts is a well-formed Σ type, so this is a scoping mistake in the elaborator, not a way to prove something false. Using fresh-binder on line 306, as the -> clauses do (typechecker.rkt:210), would fix it.

7.7Errors as values

Every judgment of the checker can fail, and Pie does not use exceptions for it. A result has type (Perhaps α): either (go result) or (stop where message), where the message mixes strings and Core (basics.rkt:325–341). Results are chained with go-on:

347(define-syntax (go-on stx)
348  (syntax-parse stx
349    [(go-on () e) (syntax/loc stx e)]
350    [(go-on ((p0 b0) (p b) ...) e)
351     (syntax/loc stx
352       (match b0
353         [(go p0) (go-on ((p b) ...) e)]
354         [(stop where msg) (stop where msg)]))]))

go-on is let* in an error monad: it binds the contents of each go in turn and returns the first stop unchanged. The rules of Chapter 9 are go-on blocks whose bindings are the premises, so a rule fails at its first failed premise. We saw a go and a stop from var-type in Section 7.5. Only at the top level does a stop become a Racket exception (main.rkt:158–159), whose text is the message with its Core parts resugared and pretty-printed (pie-err.rkt:25–30; pretty.rkt:191–200).