Chapter 10
Pie among type theories, and building your own
Pie is small on purpose. This last section lists what it leaves out and what it takes for granted, compares it with four larger systems, and ends with a recipe for a checker of the same kind, exercises that change Pie itself, and further reading.
10.1What Pie leaves out, and what it assumes#
User-defined datatypes. A Pie file contains only claim, define, check-same and expressions: the declaration parser parse-pie-decl has exactly these four cases (parser.rkt:395–423), and the type formers are a fixed list of keywords (basics.rkt:39–51). A would-be declaration is read as an expression, an application of an unknown variable:
no-datatype.pie
;; no data declarations: (data Bool) parses as an application
(data Bool)Unknown variable data
location...:
no-datatype.pie:3:1A new type must be encoded with the types that exist. Bool can be (Either Trivial Trivial), and negation an ind-Either (bool-encoding.pie, shown with its line numbers):
2;; encode Bool as a sum of two units instead of declaring it
3(claim Bool U)
4(define Bool (Either Trivial Trivial))
5(claim not (-> Bool Bool))
6(define not
7 (λ (b)
8 (ind-Either b (λ (x) Bool)
9 (λ (t) (right sole))
10 (λ (t) (left sole)))))
11(not (left sole))
12(check-same (-> Bool Bool) (λ (b) (not (not b))) (λ (b) b))The expression on line 11 normalizes to (right sole), but the check-same on line 12 fails:
The expressions
(λ (b)
(ind-Either (ind-Either b
[…]
and
(λ (b)
b)
are not the same
[…]The encoding computes on constructors, but (not (not b)) is stuck on the neutral b, and there is no η-rule for Either that would split b into its two cases (Table 8.2). As with (+ n 0) in Section 4.2, the law holds propositionally, by a case analysis with ind-Either.
Implicit arguments and unification. Core has no form for a metavariable (basics.rkt:138–182), and nothing in the code solves constraints, so every type argument is passed by hand. Leaving one out is not an arity error but a type error at the first argument, which is checked against U:
no-implicit.pie
;; no implicit arguments: the type argument must be passed explicitly
(claim length (Π ((E U)) (-> (List E) Nat)))
(define length (λ (E es) (rec-List es 0 (λ (e es ih) (add1 ih)))))
(length Atom (:: 'a (:: 'b nil)))
(length (:: 'a (:: 'b nil)))The first call prints (the Nat 2); the second fails:
Expected U but given
(List Atom)
location...:
no-implicit.pie:6:8The mode switch (typechecker.rkt:772–774) handed the synthesized type to same-type (782–790), which compared it with U. Where a miniKanren programmer would leave a fresh logic variable for E and let unification find Atom, Pie has nothing to bind it to (Section 2.6).
General recursion and a universe hierarchy. A definition cannot mention itself, because a claimed name is invisible until its definition has been checked (Section 2.5); all recursion goes through eliminators. There is one universe, U, and U is not in U (Section 5.4).
Smaller omissions. No eliminator branches on an Atom (basics.rkt:39–51), so atoms can be compared with = and same but not cased on. No definition is opaque. ctx->env puts every def’s value into the environment (basics.rkt:477–488), so normal forms show definitions unfolded (Section 7.5), where Rocq’s Qed and Agda’s abstract blocks hide a body. Finally, pointwise equal functions are not definitionally equal, and two proofs of the same equation need not be; neither function extensionality nor UIP can be proved in general from an identity type like Pie’s = (Section 4.7).
What Pie assumes but does not prove. The implementation takes three properties of the type theory for granted.
- Normalization: every well-typed term has a normal form. Conversion reads both sides back completely (
typechecker.rkt:795–807), so it terminates only if normalization holds (“Pie is a total language”,normalize.rkt:15–18). - Consistency: no closed term without holes has type
Absurd. - Canonicity: a closed term of type
Natwithout holes normalizes to a numeral, and a closed proof of(= A a b)without holes normalizes tosame(Section 4.2).
The words “without holes” matter. A TODO checks against any type and evaluates to a neutral, an unknown constant (Section 6.3), so (the Absurd TODO) and (the (= Nat 2 3) TODO) are both accepted, with a hole report each (todo-closed.pie). Consistency and canonicity are therefore statements about complete programs, and theorems about the type theory, proved in the literature for theories close to Pie’sPer Martin-Löf. An Intuitionistic Theory of Types: Predicative Part. In H. E. Rose and J. C. Shepherdson, editors, Logic Colloquium ’73, volume 80 of Studies in Logic and the Foundations of Mathematics, pages 73–118. North-Holland, Amsterdam, 1975; and 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, not properties of this code. Pie’s rules are not exactly the ones those papers treat (its η-rule for Absurd is unusual), and the runs found three places where the implementation departs from its own specification. cong accepts dependent functions (Section 4.3), a Pair synthesized as an element of U can capture a free variable (Section 7.6), and the η-rule for empty vectors is not matched by computation (Section 8.7). None was shown to yield a proof of Absurd. Smaller defects, in comments, error messages and the printer, are noted where they come up (Section 6.4, Section 7.3, Section 8.7, Section 9.5, Section 9.6).
10.2Pie and four larger systems#
Table 10.1 sets Pie next to Agda, Rocq, Lean 4 and Idris 2. The other columns come from the documentation of those systems and the literature (Section 1.2), not from runs.
| Pie | Agda | Rocq | Lean 4 | Idris 2 | |
|---|---|---|---|---|---|
| Datatypes | fixed menu (Table 2.1); no declarations | inductive families, records | inductive families, records | inductive families, structures | inductive families |
| Recursion | none; eliminators only | pattern matching with a termination checker | fix with a syntactic guard condition | structural or well-founded recursion; partial | totality checking optional |
| Universes | one U, U not in U | Set hierarchy, universe polymorphism | cumulative Type hierarchy, impredicative Prop | Sort u, impredicative Prop, universe polymorphism | — |
| Implicit arguments | none | yes, by unification | yes, by unification | yes, by unification | yes, by unification |
| Holes | TODO: a neutral, never solved; goal printed | interaction points; metavariables solved by unification | proof mode goals; existential variables | sorry, _, tactic goals | named holes ?h, interactive editing |
| Definitional η | Π, Σ, Trivial, Absurd, (Vec E zero) | functions, records | functions, records with primitive projections | functions, structures; proof irrelevance in Prop | — |
| Equality and K | = with based J (ind-=); no K | K by default, --without-K to turn it off | eq; no K without an axiom | Eq in Prop, so UIP is definitional | — |
| Case analysis | eliminators only | dependent pattern matching | match and fix | pattern matching compiled to recursors | dependent pattern matching |
| Conversion | full normalization of both sides, then | on-demand unfolding | on-demand unfolding | on-demand unfolding | — |
| Variables | names, renaming, by de Bruijn levels | de Bruijn indices | de Bruijn indices | locally nameless | well-scoped de Bruijn indices |
All five share a core in the spirit of intensional Martin-Löf type theory: Π, Σ and an identity type, inductive types whose elimination principles carry a motive, and definitional equality checked by computing. Rocq and Lean 4 extend this core to the Calculus of Inductive Constructions, with an impredicative Prop. In Lean 4, whose Prop has definitional proof irrelevance, definitional equality is not decidable in generalMario Carneiro. The Type Theory of Lean. Master's thesis, Carnegie Mellon University, 2019; and Andreas Abel and Thierry Coquand. Failure of Normalization in Impredicative Type Theory with Proof-Irrelevant Propositional Equality. Logical Methods in Computer Science, 16(2), 2020, and its checker is incomplete there. The larger systems add declarations of inductive families, pattern matching compiled to or checked against eliminatorsThierry Coquand. Pattern Matching with Dependent Types. In Informal Proceedings of the 1992 Workshop on Types for Proofs and Programs, Båstad, Sweden, 1992; and Healfdene Goguen, Conor McBride, and James McKinna. Eliminating Dependent Pattern Matching. In Algebra, Meaning, and Computation: Essays Dedicated to Joseph A. Goguen, volume 4060 of Lecture Notes in Computer Science, pages 521–540. Springer, 2006, unification to fill in implicit arguments, universe hierarchies, and conversion checkers that unfold definitions only when a comparison needs it. Pie keeps the core and drops the rest; its checker is one file of 897 lines.
10.3Build your own#
The parts of Pie read in Chapter 7, Chapter 8 and Chapter 9 make a recipe of eight steps, each with the place in Pie that implements it.
- Two syntaxes. A surface syntax with locations and sugar, and a Core syntax for the rest of the system (
basics.rkt:54–182); elaboration translates one into the other while checking. - Values. One representation for types and terms, so that types can be computed (
basics.rkt:185–243), and closures for bodies waiting for an argument (basics.rkt:504–529). - Neutrals that carry types. Each stuck elimination keeps its non-target arguments with their types, as
THE(basics.rkt:246–320). - An evaluator.
val-ofplus onedo-function per eliminator, with a case for constructors and one for neutrals (normalize.rkt:105–484). - Type-directed read-back, where the η-rules live (
normalize.rkt:527–711). - Conversion. Read both sides back at the same type and compare up to α (
typechecker.rkt:782–807;alpha.rkt). - A bidirectional elaborator. One function per judgment, returning Core inside an error monad (
typechecker.rkt,basics.rkt:325–354). - A top level.
claimanddefine, with the claimed name kept out of scope while its definition is checked (typechecker.rkt:810–853).
Some of Pie’s choices can be simplified. Call-by-need is an optimization; because Pie is total, any order of evaluation is acceptable (normalize.rkt:15–18). One kind of closure would do (basics.rkt:507–510). Names with freshening and renamings could be replaced by de Bruijn indices or levels. What should not be dropped are the types inside neutrals and inside THE. Without them, read-back of a neutral term cannot be type-directed, and the η-rules for the arguments of a neutral would be lost (basics.rkt:316–320).
10.4A port to CHICKEN Scheme#
Pie has been ported to CHICKEN Scheme as the modules (aux pie …) of the library auxhttps://github.com/massimo-nocentini/aux.scm, commit 0803a7b. The port is derived from Pie and, like Pie, is AGPL-3.0.. Each Racket file that the port covers becomes one module, normalize.rkt becoming (aux pie normalize) and so on, with the same definitions in the same order, so the citations of this tutorial can be followed in either. (aux pie) plays the part of main.rkt. The files that serve only DrRacket (gui/, the tooltips, the slides and the editing commands) are left out. A file runs with csi -s src/test/pie-run.scm file.pie.
The eight steps of Section 10.3 were the smaller part of the work. The 4315 lines of Racket that were ported became 4564 lines of Scheme. Three more modules, 3874 lines in all, have no Pie file behind them: (aux pie racket), (aux pie syntax) and (aux pie syntax-parse) imitate what Pie takes from Racket: transparent structs, a reader that records source locations, syntax objects, Racket’s printer, and the wording of the errors that syntax-parse reports for malformed programs. They are needed because the port’s goal is to print what Pie prints, and much of what Pie prints, every location and every message about bad syntax, is written by Racket rather than by Pie.
The port is tested against Pie itself. The 121 checks of tests.rkt are ported, and 931 programs are run by both implementations: the examples of this tutorial, one program per form of Pie’s reference manual, and about 720 programs written to probe eliminators, equality, errors, holes, printing and binding. All of them print the same standard output and standard error and exit the same way, except the five that give cong a function whose type depends on its argument.
There the port departs from Pie on purposeCommit 0dc1f8a, non-dependent-codomain in (aux pie typechecker)., and makes the change of the first exercise below. Pie types (cong p f) with the codomain of f at the left end of p only, so a dependent f has (f to) read back at the wrong type. The crash of cong-dep-closed.pie in Section 4.3 is one outcome. The other is a wrong answer without any error: for a proof p of (= Nat 0 3) and an f of type (Π ((n Nat)) (Vec Atom (add1 n))), Pie prints the type (= (Vec Atom 1) …) for a vector of length 4. The port follows the book’s rule, where the function is an (→ X Y). It instantiates the codomain at two fresh variables, requires the two read-backs to be α-equivalent, and otherwise rejects the function. On cong-dep-closed.pie it prints
Expected a function whose type does not depend on its argument, got
(Π ((n Nat))
(which-Nat n
(the U Atom)
(λ (k)
Nat)))
location...:
cong-dep-closed.pie:8:53The check is stricter than soundness needs. A codomain that agrees at the two ends, as when p is (same 2), would be harmless, and the port rejects it anyway.
10.5Exercises#
These are not solved here, except that the port of Section 10.4 makes the change of the first one. Each changes a copy of Pie; re-run tests.rkt after each change (its 121 checks pass on the unmodified code). They can be done on the port of Section 10.4 as well, with make test-pie in place of tests.rkt.
- Make
congreject a dependent function (typechecker.rkt:459–475), for instance by instantiating the closure at two different fresh neutrals and requiring the results to be the same type. Re-run the dependent-congprogram of Section 4.3. - Quote the bare
UNIVERSEandABSURDin the match patterns atnormalize.rkt:561andnormalize.rkt:241, and check whether any test changes. N-ind-Vec1is declared (basics.rkt:278–283) and read back (normalize.rkt:684–689) but never built. Either remove it, or argue which well-typed terms could produce it.- Make
(ind-Vec zero es …)compute to the base whenesis neutral, so that computation matches the η-rule ofnormalize.rkt:602. Widen the first clause ofdo-ind-Vec,[('ZERO 'VECNIL) b-v](normalize.rkt:334); today such a vector is caught by the clause atnormalize.rkt:349–359, which builds a stuckN-ind-Vec2. Re-run the empty-vector programs of Section 8.7. - Add a type
Boolwith constructors and an eliminatorif. Touch the keywords (basics.rkt:39–51) andvar-name?(basics.rkt:373–393);Src-Stxand Core (basics.rkt:83–182);ValueandNeutral(basics.rkt:230–243,basics.rkt:303–312); the parser’s literals and clauses (parser.rkt:235–393) and its binders for DrRacket (parser.rkt:433–752); the rules inis-type,synthandcheck;val-of, ado-if,read-backandread-back-neutral; and the keyword macros ofpie-info.rkt:22–35.alpha.rktandresugar.rktrecognize keywords throughvar-name?(alpha.rkt:72–79,resugar.rkt:172–173), so a form that binds no variable may need no change there; find out.
10.6Further reading#
The book, Friedman and ChristiansenDaniel P. Friedman and David Thrane Christiansen. The Little Typer. MIT Press, Cambridge, MA, 2018, whose appendix gives the rules mirrored in typechecker.rkt. NbE for checkers, ChristiansenDavid Thrane Christiansen. Checking Dependent Types with Normalization by Evaluation: A Tutorial. https://davidchristiansen.dk/tutorials/nbe/, 2019. Online tutorial, first published 2018, with the same evaluator, read-back and bidirectional checker built step by step for Tartlet, a small relative of Pie. Type theory, Martin-LöfPer Martin-Löf. An Intuitionistic Theory of Types: Predicative Part. In H. E. Rose and J. C. Shepherdson, editors, Logic Colloquium ’73, volume 80 of Studies in Logic and the Foundations of Mathematics, pages 73–118. North-Holland, Amsterdam, 1975; and Per Martin-Löf. Intuitionistic Type Theory. Bibliopolis, Naples, 1984. Notes by Giovanni Sambin, and Nordström, Petersson and SmithBengt Nordström, Kent Petersson, and Jan M. Smith. Programming in Martin-Löf’s Type Theory: An Introduction. Oxford University Press, 1990 for programmers. Propositions as types, HowardW. A. Howard. The Formulae-as-Types Notion of Construction. In J. P. Seldin and J. R. Hindley, editors, To H. B. Curry: Essays on Combinatory Logic, Lambda Calculus and Formalism, pages 479–490. Academic Press, London, 1980, behind Chapter 5. Normalization by evaluation, Berger and SchwichtenbergUlrich 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, its origin, and 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, NbE for dependent types with η. Checking algorithms, CoquandThierry Coquand. An Algorithm for Type-Checking Dependent Types. Science of Computer Programming, 26(1–3):167–177, 1996, an ancestor of this design, and Löh, McBride and SwierstraAndres Löh, Conor McBride, and Wouter Swierstra. A Tutorial Implementation of a Dependently Typed Lambda Calculus. Fundamenta Informaticae, 102(2):177–207, 2010, a small λΠ checker in the same spirit. Bidirectional typing, Pierce and TurnerBenjamin C. Pierce and David N. Turner. Local Type Inference. ACM Transactions on Programming Languages and Systems, 22(1):1–44, 2000 and the survey by Dunfield and KrishnaswamiJana Dunfield and Neel Krishnaswami. Bidirectional Typing. ACM Computing Surveys, 54(5):98:1–98:38, 2021. Inductive families and equality, Paulin-MohringChristine Paulin-Mohring. Inductive Definitions in the System Coq: Rules and Properties. In Typed Lambda Calculi and Applications (TLCA ’93), volume 664 of Lecture Notes in Computer Science, pages 328–345. Springer, 1993, with the based eliminator that ind-= follows, and DybjerPeter Dybjer. Inductive Families. Formal Aspects of Computing, 6(4):440–465, 1994, the theory behind Vec. UIP and identity types, Hofmann and StreicherMartin Hofmann and Thomas Streicher. The Groupoid Interpretation of Type Theory. In Giovanni Sambin and Jan M. Smith, editors, Twenty-Five Years of Constructive Type Theory, volume 36 of Oxford Logic Guides, pages 83–111. Oxford University Press, 1998 and the HoTT bookThe Univalent Foundations Program. Homotopy Type Theory: Univalent Foundations of Mathematics. Institute for Advanced Study, Princeton, 2013. https://homotopytypetheory.org/book. Universes and totality, GirardJean-Yves Girard. Interprétation fonctionnelle et élimination des coupures de l’arithmétique d’ordre supérieur. Thèse d’État, Université Paris VII, 1972 and HurkensAntonius J. C. Hurkens. A Simplification of Girard’s Paradox. In Typed Lambda Calculi and Applications (TLCA ’95), volume 902 of Lecture Notes in Computer Science, pages 266–278. Springer, 1995 for the paradox that U not in U avoids, and TurnerDavid A. Turner. Total Functional Programming. Journal of Universal Computer Science, 10(7):751–768, 2004 on giving up general recursion. Larger systems, NorellUlf Norell. Towards a Practical Programming Language Based on Dependent Type Theory. PhD thesis, Chalmers University of Technology, 2007 for Agda, BradyEdwin Brady. Idris, a General-Purpose Dependently Typed Programming Language: Design and Implementation. Journal of Functional Programming, 23(5):552–593, 2013 for the first Idris, and de Moura and UllrichLeonardo de Moura and Sebastian Ullrich. The Lean 4 Theorem Prover and Programming Language. In Automated Deduction – CADE 28, volume 12699 of Lecture Notes in Computer Science, pages 625–635. Springer, 2021 for Lean 4.