Suppose you write drivers for a phone maker, and on a Monday morning a security researcher sends you a thirty-second screen recording. An app with no permissions at all, installed from the store, asks the system for a camera and is handed one, and a moment later it is reading from the microphone, which it was never granted.
None of it is a bug in the usual sense. Every handle in the kernel, whether to a camera, a socket or a file, is the same sort of thing: a small token the app holds, with operations read, write and close that the kernel carries out on the app’s behalf. Behind each token is a private record that only the token’s own driver understands.
The camera call accepted the app’s token and set to work on the record behind it as though it were a camera’s. It never asked whether it was. The bytes were a microphone handle’s, and the call read them as camera settings, one of which was a pointer the app had chosen.
What did the token say? A handle is a claim about some resource: the holder may operate on it. But the token the camera call checked doesn’t say which kind of resource it is for, so to the kernel a handle opened for a microphone is just a handle. Hand the camera call a handle of the wrong kind and nothing in the code has anything to say.
Security people have a name for this, type confusion: a value of one type used where another was meant, the two kept apart only in the programmer’s head.1 The camera driver was not careless by the usual standard. “This record is a camera’s” was a fact its author knew when she wrote the call, and the code had nowhere to write it down.
Your first thought is the right one, and I want to watch it fail. In the last chapters a propositional letter stood for a whole claim: let be “the holder may read a camera”. If the trouble is that doesn’t say camera, write a letter that does. Let be “the holder has a camera capability”, “the holder has a camera handle” and “the holder may read a camera”. Do the same for the microphone and every other kind, and write the rule once per kind:
Now a camera handle proves , which isn’t , and the wrong-kind read fails. So far so good.
But look at what you’ve had to write. A phone’s kernel carries dozens of device kinds, so the rule is now dozens of letters and twice as many implications, every one of them a copy of the same two sentences with a different subscript. The same thing written forty times is wrong in one of them. Worse, the list changes: a driver is loaded for a new sensor, and the rule that was complete on Monday is short a kind on Tuesday.
And there’s a third problem, the one the chapter is about. The clerk who checks a proof by comparing symbols can’t see the subscript. To him and are two letters, as unrelated as and were. Nothing in his list of shapes says that the “cam” in the one is the “cam” in the other, and is as well formed as any formula on the page. You have written the kind inside the letter, and inside the letter is where the clerk can’t look.
What the kernel’s design actually says is one sentence: every kind of handle supports the same three operations. Every kind, including the sensor whose driver loads on Tuesday: nothing so far can say that.
The word keeps coming up. A payment runbook says what happens on every payment, and is used for the one on a ticket. A sorting routine promises that every element of its output is at most the next. A sale gives its discount on every day from the start to the end. A bug report said “discount not applied on the last day of the sale”; a patch changed <= to < at both ends; the tests passed; and the discount quietly disappeared from the first day. None of these is a finite list, and the one we tried to write as a finite list has just failed in three ways.
So the chapter asks two questions:
how do you say every and some, in a proof and in a type?
what does saying it cost?
The language is Frege’s (Section 4.1). The rules of proof are Gentzen’s, four of them, and each is a phrase you’ve said aloud in an argument (Section 4.2). Two of the four carry a condition on a variable, and Section 4.3 shows what each condition prevents by running a proof without it.
Then the programs go back on (Section 4.4), and the quantifiers turn out to be two things you’ve programmed with for years: a proof of for all is a function whose result type mentions its argument, and a proof of there is is a pair of a thing and evidence about it. These are dependent types, and they are what the camera call needed. By then you’ll know the trick well enough to guess the typing rules before I give them, and I’d like you to try. Section 4.5 extends the Curry–Howard correspondence to them, and normalisation then gives two facts: the logic proves no atomic sentence on its own, and a proof of there is names the thing, the existence property.
Section 4.6 ends where the chapter began, with sentences about things written down as theories and proved from, the driver theory among them. Section 4.7 puts this chapter’s type system and Chapter 5’s in one picture, the -cube, and Chapter 5 then points the same quantifier at propositions instead of things, and from there at types, which gives generics.
4.1 Predicates and quantifiers
The subscript was the right instinct. A letter with a kind inside it is two things, a claim with a gap in it and a name, and the only mistake was to glue them together where the clerk couldn’t see the join. Pull them apart:
“the holder has a camera capability”, where is a predicate, a claim with a hole in it, and is a name that fills the hole. Now and visibly share a part, and the clerk, who compares symbols, can see that they do. The sentence is still well formed, but it’s now visibly a different sentence from , and anything that said the first would be seen to say it.
This is the move the Begriffsschrift of 1879 was built around. Logic before it analysed a sentence into a subject and a predicate, “the camera” and “is live”, which is the grammar of Latin; the book analysed a sentence instead into a function and an argument, and , which is the grammar of mathematics. Its author thought it the most important thing in the book.2 It matters here because a function can take a variable as its argument.
The formula is the rule with the kind left out, a claim about whatever kind is, and it’s one formula, not forty. On the type side the same move turns Handle from a type into a function from kinds to types, Handle cam, Handle k, a type with a hole for a kind.
Universal and existential quantifiers
A formula with a hole in it isn’t a claim yet, any more than is a number. There are two ways to close the hole, and they’re the two things the forty subscripted letters were trying to write. The first is to say that the claim holds whatever fills it. For the forty kinds that would be the conjunction
with one conjunct per kind, except that the list won’t be complete on Tuesday and the clerk, as we saw, can’t tell that the conjuncts are alike. So write the conjunct once, hole and all, with a mark in front that says “for every way of filling it”:
That’s for all, and it’s an and with one case for every thing there is, written once with a parameter.
The second way to close the hole is to say that something fills it. “Some driver has registered the camera” is the disjunction
with one disjunct per driver, and we write it once:
That’s there is, an or with one case for every thing, and the thing is the tag. Logicians call it the witness.3
The quantifiers are and with the list of cases made unbounded. Everything else about them (the proof rules, the side conditions, the programs) is the bill for that.
You’ve met both ideas as a programmer. A test suite checks finitely many inputs: it is the long and with its cases written out, the forty subscripted letters again, and it says nothing about input forty-one. A function says something about every input, because its body is written once, for a parameter, and has to work for whatever arrives: that is for all, in code. And a single failing test settles “some input breaks this” by exhibiting the input: a witness.
Why it mattered
What has just happened is larger than it looks. For two thousand years logic meant the syllogism: every A is B, every B is C, so every A is C. Each sentence of a syllogism has one every or one some, at the front, and nothing in the system can put one inside another. Late in the eighteenth century the subject was declared finished.4
Here is an argument that every reader accepts and no syllogism can reach: every horse is an animal, so every head of a horse is the head of an animal.5 The conclusion has a some inside an every: for every , if is the head of some horse, then is the head of some animal. With predicates , and , “ is the head of ”, that is
and Example 4.23 derives it from in nine bars. Quantifiers nest, and nesting was the whole difficulty.
Mathematics and software are made of nested sentences:
every number has a larger one;
between any two fractions there is a third;
every request gets a response;
for every input there is an output.
A logic that can’t put a some inside an every can’t state any of these, let alone check a proof of one.
The notation was built to say all of arithmetic, and it could. Within fifty years it had raised the question whether a machine could decide which formulas follow from which, and the machine invented in 1936 to answer it, the Turing machine, is our clerk.6 And the query language of every relational database is the same logic in different clothes: an SQL query with EXISTS and NOT EXISTS in it is a formula with quantifiers, written in another notation.
The language, in the notation everyone now uses, comes in three layers: the symbols; the terms built from them, which name things; and the formulas, which make claims.
Definition 4.1 (first-order language). The symbols of a first-order language are of two kinds.
The logical symbols, which are the same in every language:
the connectives , and ;
the constant ;
the quantifiers and ;
a stock of variables .
The non-logical symbols, which make up the signature and change from one language to the next:
some constant symbols ;
some function symbols ;
some predicate symbols .
Each function symbol and each predicate symbol has an arity, the number of arguments it takes.
A predicate symbol of arity is a propositional letter, and is written .
Definition 4.2 (terms). The terms are defined inductively.
Every variable is a term.
Every constant symbol is a term.
If is a function symbol of arity and are terms, then is a term.
Nothing else is a term.
A term with no variables in it is closed.
Definition 4.3 (formulas). The formulas are defined inductively.
is a formula.
If is a predicate symbol of arity and are terms, then is a formula. (When it is a propositional letter , written without brackets.)
If and are formulas, then , and are formulas.
If is a formula and is a variable, then and are formulas.
Nothing else is a formula.
The formulas given by clauses 1 and 2 are atomic.
Three conventions make formulas readable.
abbreviates .
Familiar symbols such as and are written between their arguments, so that is the atomic formula .
Brackets are left out where nothing is lost:
the outermost pair goes;
and take precedence over ;
the arrow groups to the right;
and the quantifiers take precedence over everything else.
So is , and a quantifier whose scope is meant to be larger is followed by brackets, as in .
With the conventions in force, the two definitions fit on two lines:
Remark (looking back: letters). Nothing in the definition replaces anything. A letter of the last two chapters is a predicate symbol of arity , so every formula of those chapters is still a formula, and, once derivations have been defined, every derivation will still be a derivation.
A term names a thing and a formula makes a claim. Keep the two apart, as a parser would by giving them different types. In the symbols and are a constant and a function symbol, is a predicate symbol, and and are variables; is a term and a formula. Writing either where the other belongs would be a type error.
The kernel’s signature, which the chapter uses throughout, has
constants for the resource kinds and the drivers, , , , ;
a function symbol , the driver that owns kind ;
five predicates:
| Predicate | Reads |
|---|---|
| the holder has a capability for kind | |
| the holder has an open handle to kind | |
| the holder may read from kind | |
| driver has registered kind | |
| kind has a driver loaded |
Kinds and drivers are things of one sort as far as the language goes. A variable ranges over both; the predicates say which is which. So is a formula, though not one anybody would assert. (Logics with several sorts of thing, each with its own variables, avoid that at the cost of more bookkeeping.)
With these, the kernel’s design comes down to three sentences, which I’ll call the driver theory, (a set of sentences used as hypotheses is a theory, and Section 4.6 defines it):
| What the theory says | As a sentence |
|---|---|
| a capability for a kind opens a handle to it | |
| a handle to a kind may be read | |
| a registered kind has a driver loaded |
The open rule as the kernel states it, “a kind may be opened once some driver has registered it, and its owner has a capability for it”, is . The term names a driver without saying which; that is what a function symbol is for. The sentence is the kind a kernel team writes in a comment and would rather a machine checked.
Reading quantified sentences
The order of the quantifiers matters, and so does the connective under them. The sentence says that every kind has some driver registered for it, perhaps each a different one. The sentence says that one driver registered every kind. The symbols are the same and the claims are very different.
The connective under a quantifier follows three rules of thumb.
A condition on every goes on the left of an arrow. The theory’s first sentence is ; written with , as , it would say that every kind is one the holder has a capability and a handle for.
A description under some is joined with . Written with an arrow, is derivable as soon as some kind is known to fail , whatever says.
An any in the condition of a rule is an every over the whole rule: when is not free in , each of and derives the other, while says much less.
A negation can cross a quantifier only at a price. In this logic does not give : a proof of there is has to name the thing, and a proof that not everything is needn’t name anything. Part 2 comes back to the gap.
Turning English into formulas is where most mistakes with quantifiers are made, before a single rule has been applied. Five sentences from a driver writer’s week show these points at work.
Example 4.4 (Ivanova: a rule about every kind). Ivanova writes drivers for the phone maker of the opening, and her week is spent writing the kernel’s rules down as formulas. The kernel’s documentation says: a kind with no driver loaded can’t be read. That is a rule about every kind, so its shape is for every , if … then …:
The easy mistake is to write where the sentence has if. The formula says that no kind has a driver loaded and none can be read, which describes a phone that’s switched off.
Example 4.5 (Ivanova, cont’d: a report about some kind). The researcher’s report says: some kind can be read by an app that holds no capability for it. That’s a claim that a particular thing exists, so its shape is there is a such that … and …:
Here the easy mistake runs the other way: . That formula follows from alone.
Suppose the app has no camera capability.
That contradicts , and from a contradiction anything follows, included.
So , and the camera is the witness.
The formula would be established by an app that holds a camera capability and reads nothing at all.
Example 4.6 (Ivanova, cont’d: a named driver and an unnamed one). Two engineers summarise the boot sequence. One writes every kind is registered by its owner; the other, every kind is registered by some driver. The first uses the function symbol and the second a quantifier:
They aren’t the same claim. The first names the driver for each kind, by a rule anyone can apply: hand it the camera and it says . The second says only that each kind has a driver, perhaps a different one each time, and gives no way of finding it.
The first gives the second, as Example 4.20 below shows. Nothing in the second says that the driver it promises is the one the symbol names, so it doesn’t give the first.
Example 4.7 (Ivanova, cont’d: where the not goes). Two lines from a security review of an untrusted app: not every kind may be read, and no kind may be read. They are
The first is a mild complaint: some kinds are protected, perhaps only one. The second is a sandbox: every kind is protected. Moving the across the changes the claim, and the second is much the stronger. The sandbox can also be written , there’s no kind it may read, and Example 4.21 below gets the per-kind form from that one.
Example 4.8 (Ivanova, cont’d: a some that means every). The incident runbook says: if any kind can be read without a capability, page the security team. Write for “the security team is paged”, and as short for , can be read without a capability (an abbreviation, not a new predicate). The obvious formula is
The monitoring code checks one kind at a time, so it implements a rule that looks different: for every kind, if it can be read without a capability, page the team,
By the third rule of thumb the two say the same thing, and Example 4.22 below derives each from the other. What doesn’t say the same thing is , with the quantifier moved over the arrow as well. That one would be established by any single kind known not to be readable, whether or not anyone is ever paged.
Definition 4.9 (free variables). In and the formula is the scope of the quantifier. An occurrence of a variable in a formula is bound if it
is the variable of a quantifier or , or
lies in the scope of one,
and free otherwise. The set of variables of a term is defined by recursion on the shape of ,
and the set of free variables of a formula by recursion on the shape of , with standing for any of , and , and for either quantifier:
Definition 4.10 (sentence). A formula with no free variables is a sentence.
In , “every number has a larger one”, every occurrence of a variable is bound, and the formula is a sentence.
Free and bound occurrences can also mix, even of one variable. In the first two occurrences of are bound and the third is free, and the first is free and the other two are bound. So this is a formula and not a sentence.
Everything in is a sentence, which is what makes it a theory of every kind rather than a remark about one. The open rule is not: its is free, and it becomes a claim about a particular kind only when a term is put in for . That operation needs care, because a quantifier inside the formula can capture a variable of the term put in.
Definition 4.11 (substitution). Let be a term and a variable. For a term , the term , “ with for ”, is defined by recursion on the shape of :
For a formula , the formula is defined by recursion on the shape of :
Definition 4.12 (substitutable). A term is substitutable for in a formula when no free occurrence of in lies in the scope of a quantifier on a variable of .
We write only when is substitutable for in . So puts in for the free occurrences of , and only those: the fourth line of the last display stops at a quantifier on , because every in its scope is bound. Substitutability is what makes the last line safe. If occurred in and occurred free under the , pushing under the quantifier would turn that into a bound one and change what means. The term is not substitutable for in , for this reason; the terms and are.
When a term isn’t substitutable, rename the bound variable first, to one that occurs nowhere else. Two formulas that differ only in the names of their bound variables are treated as the same formula, so after renaming every term is substitutable. Ignoring the condition produces a bug that the section on side conditions runs all the way to .
Remark (looking back: substitution in the -calculus). The lines are those of Definition 3.18, substitution in -terms, with a quantifier in the place of a , and the last line for is the one for an abstraction, . A quantifier binds its variable exactly as a binds its parameter, and renaming before substituting is the same remedy for the same danger.
4.2 NJ with quantifiers
The rules for the connectives came from listening to how people argue: suppose, so, either way. The quantifier rules came the same way, and you’ve said all four. Here is someone showing that every kind with a capability may be read: “Let be any kind, and suppose a capability for . Then there’s a handle to , so may be read. And was any kind.” Here is someone using the register rule: “Some driver registered the camera; call it . Then by the rule, at , the camera is live.” Four phrases carry the quantifiers in those two arguments, and the four phrases are the four rules.
| Said aloud | From | To |
|---|---|---|
| let be arbitrary | , nothing assumed about | |
| in particular, for | ||
| take to be | ||
| let be such a thing; then … | ; and , supposing |
The first and the last come with a condition, and in each case the condition is what the phrase means. Arbitrary means that nothing assumed says anything about . Such a thing means that is a name made up for the duration of the argument, so the conclusion , which outlives the argument, mustn’t mention it. Those two conditions are the chapter’s other subject, and the next section takes them away to see what breaks.
You’ve used all four rules as a programmer. A function body, written for its parameter without knowing which value will arrive, is let be arbitrary. Calling the function on the value in hand is in particular, for . A failing test is take to be : one input, exhibited, settles “some input breaks this”. And code that receives “some driver registered this kind” and works with whichever it was, without being told which, is let be such a thing.
NJ was first-order from the day it was invented, in 1934: the propositional rules are the half of the system without quantifiers, and the four rules below are the other half.7
Written as bars, in the two columns of Figure 4.1, the four phrases are four rules.
(E). In particular: from , conclude with any term put in for .
(I). Take to be : from with put in, conclude .
(I). Let be arbitrary: from with a variable put in, conclude , provided nothing still assumed mentions .
(E). Let be such a thing: to get a conclusion out of , get it from the supposition that holds of a new name , which must not mention. Like (E), it discharges its supposition, and it is (E) with one case for every thing there is.
One tree before the definition, to read aloud rather than check: the argument this section began with, that a capability for any kind gives the right to read it, from the first two sentences of the driver theory. Its first piece is needed again and again in this chapter, so it gets a name. For a term , the handle tree gets a handle to from a capability for :
When a bar further down discharges its leaf , the leaf is written in brackets above the name, with the number of that bar. The argument uses , with its leaf discharged by the bar marked 1:
Let be any kind, and suppose a capability for it.
The first sentence, in particular for , gives a handle.
The second, in particular for , gives the right to read.
Discharge the supposition: if a capability for , then may be read.
The kind was arbitrary: the leaves still open are two sentences of the theory, and neither mentions , so generalise.
Here is the whole system as trees; the definition says in general what this tree did.
Definition 4.13 (derivations, with quantifiers). The derivations are defined inductively; each has a conclusion, the formula at its root. In the clauses below a derivation is drawn as a name with its conclusion written underneath it, and a formula in square brackets above a derivation is one that the clause discharges. Throughout, is a term, is a variable, and substitution is that of Definition 4.11. Two clauses refer to the open hypotheses of a tree, which are computed from its shape alone, by cases on its last rule; the next definition gives the computation.
(hypothesis) For every formula , the one-node tree whose only node is labelled is a derivation, with conclusion .
(I) If has conclusion , then for every formula ,
(E) If has conclusion and has conclusion , then
(I) If concludes and concludes , then
(E) If concludes , then
are derivations.
(I) If concludes , then for every formula the tree with root and immediate subtree is a derivation, labelled I1, and symmetrically from a derivation of , labelled I2.
(E) If concludes , and and both conclude , then
is a derivation.
(E) If concludes , then for every formula the tree with root and immediate subtree is a derivation.
(E) If concludes and is substitutable for in , then
(I) If concludes , where
is substitutable for in , and
is free neither in nor in any formula of ,
then
(I) If concludes and is substitutable for in , then
(E) If concludes and concludes , where
is substitutable for in , and
is free neither in , nor in , nor in any formula of ,
then
is a derivation.
Nothing else is a derivation.
The variable of (I) and (E) is the eigenvariable of the step.
Definition 4.14 (open hypotheses, with quantifiers). The set of open hypotheses of a derivation is defined by cases on its last rule:
where is the one subderivation of a one-premiss rule, , the two of a two-premiss rule, and , , those of (E) and (E), left to right.
Definition 4.15 (derivability, with quantifiers). We write , and say that is derivable from in NJ, when there is a derivation whose conclusion is and whose open hypotheses are a subset of , ; such a derivation witnesses .
The four new clauses combine trees as the old ones did (Figure 4.2). (E), (I) and (I) each take one tree and draw a new conclusion beneath it. (E) is the shape of (E) with a single case: a tree for , and a tree from to , combine into one tree for , discharging in the second.
What is new is that two of the four come with an eigenvariable condition, and both conditions are read off the trees: (I) looks at the open leaves of its one tree, and (E) at the open leaves of its second tree, apart from those it discharges. The notes on the triangles in the figure are these conditions. The clauses ask two more things, which the figure leaves out: that not be free in (for I), or in or (for E), and that the term put in, or , be substitutable for in .
Three clauses now discharge: (I), (E) and (E), under the conventions already in force: a bar takes every open copy of its formula, perhaps none, and a leaf is discharged by the first bar below it that discharges its formula from the part of the tree the leaf stands in. For (E) that part is the second premiss: leaves the second premiss only, and nothing in the first is discharged.
The two eigenvariable clauses are the two conditions of the table of phrases, made exact. For (I), arbitrary comes to two checks: is free in no open hypothesis, which is read off the leaves of the tree, and isn’t free in , so the formula being generalised doesn’t already talk about it. For (E), such a thing comes to three: the made-up name is free neither in the conclusion , which outlives it, nor in , nor in any other open hypothesis of the branch, so that nothing already in play is quietly identified with it.
Set the two clauses beside the turnstile, writing for the open hypotheses of the tree above the bar, and the conditions read as one: nothing to the left of the turnstile mentions . On the left is the tree; on the right, what it witnesses:
with free in no formula of , nor in ; and
with free in none of , and the formulas of .
One consequence is the order of the bars. (I) looks at the leaves still open, so a supposition that mentions must be discharged before the tree generalises over .
Worked derivations
Quantifier proofs look hard on the page, and most of the difficulty is in seeing which rule to use next. So here are seven questions about the driver theory, and the head of a horse, each done in the same order: the situation, the claim, the reasoning in words, and the tree. The hypotheses are mostly the driver theory . How trees like these are found comes after normalisation, which says what shape to look for.
Example 4.16 (Ivanova, cont’d: the boot log). The boot log has the line v4l: registered camera. Is the camera live? The register rule says that any kind any driver registers is live, so yes. The claim is
In words:
the rule holds for every driver, in particular for
v4l; andfor every kind, in particular the camera; and
the log says its condition is met.
The two (E) bars come off in the order the quantifiers were written, outermost first: for , then for . The open hypotheses are the rule and the log line, so the tree witnesses the claim.
Example 4.17 (Ivanova, cont’d: one rule for the documentation). Ivanova wants a single sentence for the driver guide: a capability for a kind gives you a handle to it and the right to read it. Does the theory support it? The claim is .
In words:
Let be any kind, and suppose a capability for it.
Then there’s a handle, by the theory’s first sentence, and so the right to read, by its second. That’s both halves.
Discharge the supposition, and since was any kind, generalise.
The handle is needed twice, once for itself and once for the read, so the tree uses the handle tree twice:
The bar marked 1 discharges both copies of at once. After it, is the theory’s first two sentences, in which isn’t free, so the (I) bar is legal and the tree witnesses the claim.
Example 4.18 (Ivanova, cont’d: can it read anything?). A reviewer of the camera app asks a blunt question: can it read anything at all? The app holds a camera capability, so yes, and a good answer says what.
The claim is . In words:
with the capability the camera has a handle,
so the camera can be read,
so some kind can be read, namely the camera.
The tree uses the handle tree , whose leaf stays open:
The last bar takes , since is with put in for . Ask the proof which kind? and it tells you: the witness is written on that bar. The open hypotheses are two of the theory’s sentences and the capability, so the tree witnesses the claim.
Example 4.19 (Ivanova, cont’d: a capability for something). Another app’s install manifest has been cut short. It records that the app was granted a capability for some kind, and the line saying which is missing. Can the app read anything? Yes: whatever kind it was, the theory lets it read that one.
The claim is . In words:
Call the kind , so that .
Then has a handle and can be read, so some kind can be read.
That conclusion doesn’t mention , so it follows whichever kind was.
Here is the branch in which is supposed, which I’ll call ; it uses the handle tree :
and here is the whole:
Check the three conditions on the (E) bar: is free in none of
the conclusion ,
, and
the theory’s two sentences, the other open hypotheses of .
The open hypotheses of the whole tree are those two sentences and , so it witnesses the claim. The argument works with the kind it was given a name for and offers the same kind back as the witness, without ever learning which kind it was.
Example 4.20 (Ivanova, cont’d: every kind has a driver). Back to the two summaries of Example 4.6. Does every kind is registered by its owner give every kind is registered by some driver? Yes: for any kind, its owner is such a driver.
The claim is . In words:
Let be any kind.
Its owner registered it, so some driver registered it, namely ; and
The kind was arbitrary.
The (I) bar takes . A witness needn’t be a constant; here it’s a term built from the variable. The (I) bar is legal because the one open hypothesis is a sentence, and that hypothesis is the claim’s, so the tree witnesses it.
Example 4.21 (Ivanova, cont’d: the sandbox). An untrusted app runs in a sandbox whose policy is one sentence: there’s no kind it may read, . The kernel enforces the sandbox one kind at a time: each time the app asks for a kind, it checks that the app may not read that one. Does the policy license the check, whatever kind is asked for?
The claim is . In words:
Let be any kind, and suppose the app may read .
Then there’s a kind it may read, which the policy denies.
So it may not read ; and was any kind.
Remember that is , so the (E) bar applies the policy to a witness, and the (I) bar makes a . The one open hypothesis is the policy, so the tree witnesses the claim. The other direction, from to , needs (E), and is part 2 of Exercise 4.6 with its hypotheses in the other order.
Example 4.22 (Ivanova, cont’d: the pager). Example 4.8 claimed that the runbook’s rule and the monitoring code’s rule say the same thing. First, the runbook gives the code’s rule: . In words:
Let be any kind, and suppose it can be read without a capability.
Then some kind can,
so the runbook says page.
That’s the sandbox tree again, with where it had , since is ; its one open hypothesis is the runbook’s rule.
Second, the code’s rule gives the runbook’s: . In words:
Suppose some kind can be read without a capability, and call it .
The code’s rule at says page.
Paging doesn’t mention , so it follows whichever kind it was.
The (E) bar is legal because is free in none of , and the code’s rule, and once the supposition is discharged the code’s rule is the one open hypothesis. The two trees together are an equivalence.
Example 4.23 (the head of a horse). Last, the argument that two thousand years of syllogisms couldn’t make: every horse is an animal, so every head of a horse is the head of an animal. The claim is that the hypothesis derives
Read the conclusion first, as the habit from the propositional case says.
It starts with , so the argument begins let be any thing.
Under that is an arrow, so suppose is the head of some horse.
That supposition starts with , so open it: call the horse .
Then is an animal, because every horse is, and is still its head, so is the head of some animal, namely .
Write for , the supposition about . The middle of the argument, in which is known, I’ll call . It comes in two pieces, to fit the page. The first, , shows that is an animal:
and the second uses it:
The whole argument wraps it in three more bars, one for each of call the horse , suppose and let be any thing, again in two pieces. The first bar, for call the horse , makes a tree I’ll call :
and the other two finish the argument:
The (E) bar is legal because appears in neither its conclusion, nor , nor the hypothesis about horses. The (I) bar is legal because, once both suppositions are discharged, the only open hypothesis is that sentence, in which isn’t free. Nine bars, and every one of them is a rule of this chapter.
Checking a tree
Checking a tree takes the four checks of the propositional case, with (E) added to the bars that discharge, and one new check for the quantifiers.
Every bar has premisses of the shape its clause requires.
Every bracket carries a number, and the bar with that number is the first bar below the leaf, on its path to the root, that discharges its formula from the part of the tree the leaf stands in.
An (I) bar discharges every open copy of its formula above it, and is vacuous only if there is none. An (E) bar discharges the left side in its second premiss and the right side in its third; an (E) bar discharges in its second premiss; neither discharges anything in its first.
Every (I) bar has free neither in nor in any leaf still open above it. Every (E) bar has free in none of , , and the leaves of its second premiss still open there other than . In all four quantifier bars the term put in, or , is substitutable.
The leaves left without brackets are the open hypotheses. The tree witnesses for every that contains them.
The fourth check is new, and the next section is about what breaks without it.
Consistency and the existence property
Two things are worth knowing about these rules before anything is built on them. Neither is a derivation; both are theorems about derivations, as Theorem 3.38 was for the propositional rules.
Theorem 4.24 (consistency). In NJ with quantifiers, no atomic formula is derivable from no hypotheses:
;
for every predicate symbol and terms .
Corollary 4.25 (disjunction property). If , then or .
Corollary 4.26 (existence property). If , then there is a term with .
The three are proved in Section 4.5, by putting the programs back on the trees and running them, as Theorem 3.38 was proved for the propositional rules.
The theorem says that the rules add nothing of their own: every fact about a particular kind, driver or day in a conclusion was put in as a hypothesis. The existence property is the quantifier’s character in one line. A theorem of the form there is doesn’t merely assert that something exists; it can be made to say what, and the worked derivations show where to look: at the (I) bar.8
4.3 Side conditions
Three things can go wrong with a quantifier rule, and each of them is a bug you’ve met in a program. You remember a side condition once you’ve watched its absence prove everything, so the third bug is run all the way to below; one of the exercises does the same for the first.
Generalising over a fixed variable
Suppose the kernel is handling a request for some kind , and the hypothesis in force is : this caller has a capability for kind . One application of (I) would give , the caller has a capability for every kind, from which, with the driver theory, it may read every kind. The (I) clause refuses it: is free in the open hypothesis , so isn’t arbitrary, whatever the argument calls it. Discharge the hypothesis first, by (I), and generalising becomes legal. But what you’ve generalised then is , and that is harmless.
The clause asks only that be free in no hypothesis used. A hypothesis about lying in untouched doesn’t block the bar, since it isn’t open. In the illegal step the leaf is open above the bar and has free, and that is exactly what the condition on (I) forbids.
Escaping witnesses
“Some driver registered the camera; call it ; so registered the camera.” The tree refuses this by the first condition of the (E) clause, that not be free in the conclusion. The other two conditions rule out two more ways of cheating, each of them a way of naming a thing that was already in play.
You might choose as the fresh name a variable that already mentions. From “some number is below ” you would then get “some number is below itself”:
The conclusion is clean of , but is free in , so the bar is illegal, and rightly so: with the hypothesis is true of the natural numbers and the conclusion is false.
Or you might choose a variable that some other open hypothesis already says something about. From “some kind has a capability” and “kind has none” you would then get a contradiction:
Here is free in neither nor , but it is free in the other open hypothesis , and the two hypotheses are consistent: the kind with the capability need not be . Together the three conditions say that you may use the thing and may not learn which thing it is, which is what a module boundary says. In the first of the three cheats it is the conclusion that fails: mentions the made-up name , which would outlive the argument that made it up.
Variable capture
The third bug is the reason (E) asks that be substitutable. Drop that condition and the system proves from two hypotheses any programmer would accept of the natural numbers:
“every number has a larger one” and “no number is less than itself”. Take to be the variable , which is not substitutable for in , since it would land under the , and pretend (E) didn’t care. The left-hand bar below is that instance, , and it’s the illegal one.
Four bars, and is the two harmless hypotheses, so the tree would witness . The system has proved from two facts about the natural numbers. The only thing that let it happen is the left-hand bar. (The (E) at the root is legal: is free in none of , and .)
You can see what went wrong in the formulas. The we substituted meant “some given number”. On landing under it came to mean “whichever the quantifier picks”. So says that some number is less than itself, which the hypothesis never said.
With the condition in force the left-hand bar isn’t available. The fix is to rename first: the hypothesis is equally well written , its legal instance at is , and nothing follows from that but what should. The one illegal bar is the left-hand (E): the term would land under in , so it is not substitutable for there, and every other bar of the tree is legal.
Remark (looking back: capture in the -calculus). Chapter 3 promised this bug on the programming side, where substitution renames a bound variable before passing under a that would capture. Running a program is substitution, , and it needs the same condition. Take , the combinator that keeps its first argument (written in that chapter’s letters), apply it to a free variable , and run it blindly:
The free has landed under the inner and been captured. The result is the identity, which returns whatever it’s given. The program’s meaning has changed. Rename first, , and the constant function we meant comes out.
On the proof side, with the free of type and the parameter of type , the program before the step is a proof of from the hypothesis , and the blind result is a proof of from nothing. Capture has swapped one theorem for another, which is what it did on the logic side too. One bug, one fix, on both sides of the correspondence.
A compiler or interpreter doesn’t substitute text when it calls a function; it carries the argument’s value in an environment. Macros and refactoring tools do substitute text, and that is where you’ve met the bug. The logic side has been known for a century, and every textbook states the condition. What the correspondence adds is that it’s the same condition.
4.4 Dependent types
Back, now, to the code where the trouble started, and to the programs. What type should the open call have? In the kernel’s old code it was an arrow from Capability to Handle, and we’ve seen what that cost.
The open function has to do two things the old type couldn’t say. It has to work for every kind, Tuesday’s included. And it has to say, in its result, which kind it was given, so that the handle it makes for the camera is a handle for the camera.
The same move, function and argument, gives the types. With Capability k and Handle k as types with a hole in them, the declarations become
cam : Kind
camCap : Capability cam -- granted at install
openHandle : (k : Kind) -> Capability k -> Handle k
readHandle : (k : Kind) -> Handle k -> Bytes k
record : (k : Kind) -> Handle k -> IO ()
Read the third line slowly, because it’s the only new thing here. The function openHandle takes a kind , then a capability for , and returns a handle to . The result type mentions the argument.
In the old code the kind and the token were one value, h :: Handle, and that was the bug. Here they’re two: the kind, and a separate value whose type has the kind in it. So the type of the function is an arrow whose right-hand side depends on what went in on the left. None of the type systems so far can write that.9
On the program side, the long and is a record with one field per kind: forty handles, one for each device. A function from kinds to handles holds the same information (hand it the camera and it returns the camera’s field), and when you don’t know how many fields there will be, a function is the only way to write the record down. So a proof of for all is a function from things.
The long or is a forty-way Either: a value with a tag saying which case it is. Here the tags are drivers, so the value is a pair of a driver and evidence about that driver. So a proof of there is is a pair of a thing and evidence about it.
One change of notation comes with the types. Logic writes , , and ; type theory writes , , and for the same four things. The last two sections used the logician’s letters; this one uses the type theorist’s, and the table at the end of the section lines them up.
The letters have a history, which the chapter’s History tells. and were the quantifiers’ first letters, chosen for the reason given in the first section: a long and is a product and a long or a sum. Logic traded them for and , and nearly every logic book since has used those. Type theory took them back, ninety years later, because in it a proof of for all is a function, an element of a product with one factor for each thing, and a proof of there is a pair, an element of a sum with one summand for each thing.10
So putting the programs back on means renaming as well as decorating: becomes and becomes , along with to and to . Before I write the rules down I’d like you to find them.
Problem 4.27. Take the four quantifier rules and decorate them with programs, as (I) and (E) were decorated with and application. What is the program for each of let be arbitrary, in particular, for , take to be and let be such a thing? And what becomes of the eigenvariable and its conditions?
The definitions below are the answer. The hint has already been given: a proof of for all is a function from things, and a proof of there is is a pair.
Definition 4.28 (dependent types). Fix a signature. Its terms name things, and its variables stand for things. The types are the formulas over the signature, written as a type theorist writes them:
where
is the pair type,
the sum type,
the dependent function type, and
the dependent pair type, with ranging over the one kind of thing the signature talks about;
negation is .
Definition 4.29 (terms of ). A second stock of variables , disjoint from the variables for things, stands for evidence. The terms are
where and are evidence variables, is a variable for things and is a term of the signature.
The first three lines are the propositional terms. In the third, the braces hold the two branches of a , which looks at the tag on : if it is , the evidence carries is called and runs; if it is , the evidence is called and runs. So is in scope in only, and in only. The fourth line has the four new forms:
an abstraction over a thing;
an application to a thing;
a pair of a thing and evidence;
the match that opens such a pair.
Definition 4.30 (context). A context is a finite list of entries of two kinds,
a variable on its own, which declares a thing, or
a typing , which declares evidence,
such that
no variable is declared twice, and
every variable free in a type in is declared earlier in than the entry that mentions it.
A term of the signature is in scope in if every variable in is declared in .
A declared variable is a thing nobody has chosen yet, a parameter, and the four new rules all turn on it. Here is the whole system. The rules for , , and are the propositional ones, except that a context may now contain declarations.
Definition 4.31 (typing rules). The judgement is defined by the rules of Figure 4.3, the propositional ones above the dotted line and the four new ones below it; the subscript is the name the -cube at the end of the chapter gives this system. In every rule, each context written must be a context in the sense of Definition 4.30; in (abs), for example, every variable free in must be declared in .
Read (E) first, because it’s a function call. You have a program that works for every and you call it on the in hand. The type of the result is the body with put in for : substitution. And has to be in scope, because a program can mention only declared names.
(I) is what happens when a definition is finished. You typed the body with declared and nothing said about it, so the program works for every , and you may say so. Proved for an arbitrary , hence for all.
(I) is the constructor: supply a thing and evidence about it, and out comes a value whose type mentions neither. (E) is the pattern match. Open the pair, giving names and to the thing and the evidence, and go on to produce something. The something may use and , but its type may not mention , because was a name you made up for the duration of the match.
Compare the rules for and , which are these four with the list of cases cut down to two: a pair with two fixed fields instead of a function from things, a tag from instead of a thing. That’s why the letters are and : a function from things is a product with one factor per thing, and a pair with a tag is a member of a sum with one summand per thing, just as is a sum with one term for each .
Side conditions and the context
The (I) clause asked that its eigenvariable be free in no open hypothesis, and the section on side conditions showed what goes wrong without the condition. Yet (I) in Figure 4.3 carries no proviso, because the context already enforces it. In the variable is the last thing declared. By the definition of a context, an entry may mention only variables declared before it, so no in can say anything about .
If you want to generalise over while some hypothesis about is still in force, the rule doesn’t apply, because isn’t last. You have to discharge every hypothesis that mentions first, with a each, and only then does come to the top. A context is a stack, and you can only pop when everything pushed after it has gone.11
The first bug of the section on side conditions fails here in another form. The kernel is handling a request for kind with in force; was declared before , so it isn’t on top of the stack, and (I) doesn’t apply.
The one condition the stack can’t enforce is the one written on (E). The type of the result isn’t in the context, so nothing stops it mentioning unless the rule says so. That is why (E) is the only rule with a freshness condition; the conditions on (E) and (I) only ask that use names already declared. It is also the condition a module system enforces, the part of a language that lets a library hide how it is built; Chapter 5 shows how.
Now some typings, as sequent-style trees, in which every node is a whole judgement with its context. The declarations above become one context. The kinds are constants of the signature, which are always in scope, so they need no declaring, and what is left is the evidence: and for the first two sentences of the driver theory (the functions openHandle and readHandle), for its register sentence, for record, and for camCap. With the types written in the predicates of the signature, that context is
It stays the same in every tree below; whatever a rule adds to it is written out in full.
Example 4.32 (Ivanova, cont’d: the camera handle). The camera’s read ticket is built in two stages. First the handle, from and the capability:
and then the read ticket, from and the tree just drawn, whose root judgement, marked (1), is a premiss:
Each (E) bar picks the kind the sentence is being used for. The program at the root is the ticket, and its type now has the camera’s kind in it.
Example 4.33 (Ivanova, cont’d: the wrong-kind read). The app’s read handler passes the camera ticket to record,12 and the checker gets as far as the ticket:
mic
Here is the term at the root of the camera’s tree, , copied across. The type confusion is a type error, and the error says which kind the handle was for. Nothing in the kernel’s code had to be clever.
Remark (looking back: Jones). The tree for the camera handle is the typing of the same ticket chain in Chapter 2, with the two (E) bars added. And the wrong-kind read is refused for the reason Jones was refused there, when he asked to rotate the signing key: a mismatch of evidence. What has changed is that the type can now say which kind the evidence is about.
Example 4.34 (Ivanova, cont’d: every kind may be read). The theory’s first two sentences, composed and then generalised, give the typing that answers Ivanova’s original question: may every kind with a capability be read? In the context , with declared and then a hypothesis about it, two (E)s and two (app)s give , by the trees of Example 4.32 with for and for . Then two bars close it, and the order they come in is the side condition:
The (abs) bar pops , the hypothesis about . Then is on top and (I) pops it. Try them the other way round and the (I) bar has nothing to apply to, because isn’t the last entry. The program is function composition with a kind threaded through it, and its type, read as a sentence, is every kind with a capability may be read, which isn’t in the theory but follows from it.
Example 4.35 (Ivanova, cont’d: the register rule). At boot the v4l driver registers the camera, and the kernel records the fact as , by (I) from : the driver and the evidence, packed together, in a value whose type says only that some driver registered the camera.
Before it hands out camera handles, the kernel needs , and the register rule gives it, once the pair is opened. The kernel holds the record as , so its context is . Opening the pair adds two entries, a driver and the evidence about it, and in that context the rule applies. Two (E)s and an (app) give
which, marked (1), is a premiss of the tree that opens the pair. In that tree, is short for :
The right-hand branch calls the rule at and and applies it to , where is a name for whichever driver it was. The side condition holds because doesn’t mention .
Suppose instead that the handler tried to conclude, from the register record, which driver registered the camera:
Inside the match, is perfectly good. Outside it there’s no . It was a name the match made up, and a type that mentions it is a type that mentions nothing. This is the escaping witness of the section on side conditions, caught by the result type.
Reduction
Running a program means rewriting an introduction met by its own elimination, and the quantifiers add two such steps, with the shapes of and of a case on a tag.
Definition 4.36 (-reduction). A step rewrites an introduction met by its elimination, anywhere inside a term. The relation is given by one rule for each introduction form met by its elimination,
together with a rule for each place a subterm can sit, as (), () and (). There is no rule for , because has no introduction form for it to meet. A term in which no step can be taken is in normal form.
The last two are the new ones. Call a function on a thing and the thing goes in for the parameter. Open a pair that was packed and the thing and the evidence go in for the two names. The table of connectives and types gains two rows:
| Connective | Type | Introduction (constructor) | Elimination (pattern match) |
|---|---|---|---|
| application | |||
| , | |||
| , | case with two branches | ||
| — | |||
| application | |||
| application | |||
let with two names |
A function from things, and a pair of a thing and evidence: that’s what the kernel checks. The first two columns are a dictionary between two notations: for , for , for and for , with and the same on both sides.
Types that mention values weren’t invented for kernels. In 1967 a mathematician at Eindhoven set out to have a machine check a whole mathematics textbook, and found that a checker couldn’t do it unless the types were allowed to mention the things the theorems were about. The language he built for the job, Automath, has the rules above, and in 1977 one of his students fed it the whole of a classic textbook of analysis,13 every lemma, and it checked.14 Most proof assistants built on dependent types count it as an ancestor.
Remark (looking back: general recursion). The remark on general recursion at the end of Chapter 3 said that a programmer who wants both recursion and a consistent logic must say in the type where the recursion is allowed to go, and that this takes a logic with more to say than the propositional one. Types that may quantify over things are that logic.
4.5 Curry–Howard with quantifiers
Rub the programs out of the typing rules of Figure 4.3, keeping the contexts and the formulas, and rename as you go: to , to , to , to . Here is what’s left of the four quantifier rules, with the declarations kept, since a declaration is a name and not evidence:
with the side conditions carried over unchanged ( in scope in the second and third, not free in in the fourth). They are the four quantifier rules of NJ, written on the turnstile: let be arbitrary, in particular, for , take to be , let be such a thing. The Curry–Howard correspondence of Theorem 3.15 extends.
Theorem 4.37 (Curry–Howard, with quantifiers). Typings in and derivations in NJ with quantifiers correspond one to one.
Erasing the terms from a typing, keeping its declared variables, and writing , , and for , , and , turns it into a derivation, with (I), (E), (I) and (E) becoming (I), (E), (I) and (E).
Decorating a derivation with terms turns it into a typing, and erasure and decoration undo each other.
Writing for the set of types of the evidence entries of , read as formulas,
for every context that declares the variables free in .
In words: a derivation with quantifiers is a program whose type mentions things, and the side conditions are the same on both sides, read off the context on one and off the leaves on the other.
Erasure treats the two kinds of variable differently, and that is the difference between quantifiers and connectives. Erasing deletes , since a variable standing for evidence has nothing to say once the evidence is gone. Erasing doesn’t delete , though, because a declared thing isn’t evidence but a name, and the formula still needs it. So a logic keeps its variables when it loses its programs, and derivations with quantifiers have variables in them, where propositional derivations had none.
A tree has no declarations. What the context records, the tree recovers by computing , the stack included. Where the type system said is the last thing declared, the (I) clause says two things: is free in no open hypothesis, which is the same fact read off the leaves; and is not free in , which a fresh declaration guarantees. The (E) clause states the one condition the type system had to write, not free in , and two that the context gave for free: is fresh for and for the other open hypotheses. Read on the turnstile, the tree’s conditions are the erased rules with the declaration turned into a test: where the context declared last, the turnstile asks that nothing to the left of it mention .
Of the two, the tree says it more sharply. The context asks that be free in no hypothesis available; the tree asks that be free in no hypothesis used. A hypothesis about lying in the context untouched blocks (I), but it doesn’t block (I), since it isn’t open. Nothing provable changes, by the theorem. But the tree states the condition that matters and nothing more, and that is one reason proof theory is written in trees.
Read through the correspondence, each quantifier rule is a shape of program. A (E) bar is a call on a thing, so two of them followed by (E) are a function called on two things and then on evidence. An (I) bar packs a pair whose first half is the witness, so a proof of there is answers which one? with its first half. An (E) bar is a that opens such a pair and works with the thing it finds without learning which it was. And a supposition used twice is an evidence variable used twice.
Example 4.38 (the worked derivations, decorated). Decorated, each of Ivanova’s seven questions and the head of a horse becomes a program of one line. The theory’s sentences go under the names the context of Section 4.4 gave them, , and , with the camera capability.
| Example | Program |
|---|---|
| 4.16, the boot log | , with the log line |
| 4.17, the documentation | |
| 4.18, anything at all? | |
| 4.19, a capability for something | , with the manifest’s record |
| 4.20, every kind has a driver | , with the first summary |
| 4.21, the sandbox | , with the sandbox policy |
| 4.22, the pager | and , with and the two rules |
| 4.23, the head of a horse | , with the hypothesis about horses |
Ask the third program which kind? and it says . The fourth opens the manifest’s record and hands back the kind it found, without learning which it was. The sandbox packs a kind and a supposed proof together and hands them to the policy, which turns any such pair into . The pager’s two programs are a function on pairs and its curried form, currying one level up. And the horse:
open the pair;
keep the horse;
swap the evidence that it’s a horse for evidence that it’s an animal;
pack it up again.
Normalisation and consistency
The theorems about running programs carry over, each with two more cases. A lemma proved for an arbitrary and then used at a particular is a detour, (I) met by (E), and it is removed by the step . A witness packed and at once unpacked is (I) met by (E), and it is removed by the step for .
Theorem 4.39 (subject reduction). If and , then .
In words: running a program never changes its type. The proof is the propositional one with two more cases, one for each new step; each needs that putting a term in for a declared variable, in a program and in its type at once, preserves typing, which is an induction on the typing tree.
Theorem 4.40 (normalisation15). Every typed term runs to a normal form. Equivalently, every derivation can be rewritten into one without detours.
Proof for terms without and . The counting proof of Theorem 3.33 goes through with one more kind of redex. Give an atomic type degree 1 and degree one more than . Putting a term in for changes no type’s shape, so has the degree of .
The fact the count rests on, that a step creates only redexes of lower degree than the one it removes, still holds for the new step .
What it substitutes is a term of the signature, which names a thing and is never an introduction form, so the substitution creates no redex.
If lands under an elimination and is an introduction form, the new redex has the degree of , less than that of , just as the body of a step does.
The rest of the count is word for word. □
The type breaks the count as does, and for the same reason: is an whose tags are things. A step on a puts its body where the stood, and has the result type , which can have any degree at all. If the stood under an elimination, the new redex can have a larger degree than the one removed.
The theorem holds all the same for every connective and both quantifiers; the proofs that reach that far add commuting conversions to the count, or argue by computable terms instead of counting, and for terms with or we take the theorem on trust.16
Proposition 4.41 (closed normal forms). A closed typed term in normal form is an introduction form: , , , , or .
In words: a closed program that has finished running is a constructor, and its type says which.
The consistency theorem (Theorem 4.24) and its two corollaries, left unproved when they were stated, now follow from these three results, as Theorem 3.38 did.
Proof of the consistency theorem and its corollaries. By the Curry–Howard theorem a closed derivation is a closed typed term, and by normalisation and subject reduction it runs to a closed normal term of the same type, which is an introduction form.
Consistency. No introduction form has type or an atomic type, so there is no closed normal term of either.
The disjunction property. A closed normal term of type is or , and its tag says which disjunct holds.
The existence property. A closed normal term of type is with , and its first half is the witness.
□
Finding a tree, with quantifiers
In the propositional case the method for finding a tree rested on the shape of a normal derivation, and the proposition on closed normal forms says the shape survives the quantifiers: introductions near the root, building the conclusion, over eliminations that hang off hypotheses and take them apart. So the method gains a line for each quantifier.
Read the conclusion.
If it starts with , the last bar is probably (I), and the argument begins let be any kind.
If it starts with , the last bar is probably (I), and the question is which witness to choose; often the hypotheses have to be taken apart before you know, so leave that bar till last, as with (I).
If a hypothesis starts with , open it early with (E) and give the thing a name, as with (E).
Example 4.19 was found that way: its (E) bar is the root, the first decision made, and the witness for its (I) bar was chosen only after that bar had named it.
4.6 Theories
Read the consistency theorem with names in the language. The logic proves no atomic sentence: neither nor nor . Whatever it proves outright has a connective or a quantifier on the outside and is about how claims relate. Every fact about a particular kind, element or day has to come from the hypotheses.
Definition 4.42 (theory). A theory is a set of sentences, used as hypotheses. A formula follows from a theory in NJ if .
A derivation from a theory is a certificate. Anyone who doubts its conclusion need neither rerun nor understand the system the theory describes: they check the bars, one rule at a time. And since the logic proves no atomic sentence on its own, every atomic fact in the conclusion came from the theory and from nowhere else.
A theory can also say what a program’s parameter must satisfy, and is then called a contract. A type checker certifies that a program is safe to run and says nothing about the contract. A program whose parameter breaks the contract fails by violating a consequence of it, and a verifier, a type checker whose types may quantify over things, can state the contract and check derivations of its consequences. That is the distance between safe and correct. Three theories follow, in increasing order of interest.
Example 4.43 (Ivanova, cont’d: the driver theory). From and , the tree of Example 4.18 without its last bar derives : two (E)s and two (E)s, with the theory’s first two sentences and the one fact. An auditor who doubts that the camera may be read checks four bars, and knows that came from the driver theory.
From alone, the tree that opened Section 4.2 derives every kind with a capability may be read, , which no runtime check settles, because it speaks of every kind at once. It is the typing of Example 4.34 with the programs gone, bar for bar.
Example 4.44 (a comparator). Here’s insertion sort, written so that the comparison is a parameter, as library sorting routines are, since a library can’t know what you’re sorting.
sort(lt, xs):
out = []
for x in xs:
i = 0
while i < length(out) and lt(out[i], x):
i = i + 1
insert x into out at position i
return out
Its type is polymorphic, a quantifier over the element type (Chapter 5 works such types out),
and the checker proves it. So this code
won’t add a string to a number,
won’t call a non-function, and
will hand back a list of the type it was given.
About sorting it has certified nothing.
Give sort a comparison that returns True when its arguments are equal, <= where < was meant. The type doesn’t change, and the program compiles, runs and returns a list that is sometimes not sorted. On a longer input a library sort may do something stranger; this is an exception Java’s sort really throws:
java.lang.IllegalArgumentException:
Comparison method violates its general contract!
The sort hasn’t checked the contract, which would cost more than the sort. It found two runs it had recorded as ordered that were not, which is the failure of a consequence of the contract.
The contract is that lt be a strict weak order, the kind of order that may leave two different elements tied, as sorting people by surname does: three sentences, with for lt(x,y).
| What the library needs | As a sentence |
|---|---|
| nothing is less than itself | |
| if and then | |
| if , every is above or below |
Call this theory . A comparator built from <= reports both and for a pair of equal elements, and no comparator obeying the contract can, because
If and , then transitivity gives , which irreflexivity forbids. As a tree, in two pieces to fit the page, the first piece, , takes transitivity down to on the supposition:
and the second uses irreflexivity, discharges the supposition and generalises:
The three (E) bars of choose , and . The discharge comes before the (I) bar for , since is free in the supposition, and at the root is irreflexivity and transitivity, so the tree witnesses the claim. Decorated, it is one line,
with and two sentences of as variables. When the sort catches a comparator reporting both and , the exception is reporting this theorem violated, on a program you’ve called a hundred times.
Example 4.45 (the sale). And the patch. With for “the discount applies on day ”, what a sale is comes to one sentence,
The patched code applies the discount only when and , so it fails the sentence at , where the sentence demands a discount and the code withholds one.
Nobody had written the sentence down, which is how the patch got approved. The bug report said “last day”, the tests said “last day”, and the only thing that said “every day” was in the head of whoever wrote the sale. Once the sentence is written, “is the patch correct?” has an answer a checker can verify, and the answer is no.
What’s still missing is a logic in which “after this patch runs, the discount applies” is itself a formula. Chapter 14 has one, and comes back to this patch.
Remark 4.46 (witnesses). The quantifier is the whose tags are things, and by the existence property a proof of it carries its tag. “Is this file readable by anyone outside the team?” is an existence question, and a yes that can’t say who is no use to a security engineer. In this logic a yes proved from no hypotheses comes with the name attached.
The insistence on a name is also worth distrusting. “Either the program halts or it doesn’t” is the kind of thing you’d like to be able to assert without producing a halting run or a proof that there’s none. “Some input breaks this function” is the kind of thing you’d like to assert without producing the input. In this logic you may assert neither, because a proof of or says which and a proof of there is says what. Whether that’s a virtue or a restriction is a question for Part 2.
4.7 The -cube
By the end of the 1980s there were a dozen typed -calculi in the literature, each with its own notation, its own rules and its own proof that its programs stop, and nobody could see at a glance how they were related. The -cube is the observation that they differ in one respect only: what is allowed to depend on what.17
In every typed calculus a term can depend on a term: that’s a function, , and it’s all the simply typed calculus had. Three more dependencies are possible, and you’ve now met each of them.
Terms that depend on types: a program that takes a type, . That’s generics, the
ainlength :: [a] -> Int, and Chapter 5 works it out.Types that depend on terms: a type that takes a thing, such as . That’s the dependent types of the section on dependent types.
Types that depend on types: a type that takes a type, such as the list type, which takes and gives . You use one every time you write
List<String>; a calculus that has them lets you write your own and check them.
Each of the three can be switched on or off independently of the others, so there are calculi, drawn as the corners of a cube. Each arrow switches one dependency on.
, the corner nearest you, is the simply typed -calculus of Chapter 3. Go up and you reach , System F, the subject of Chapter 5. Go right and you reach , types that mention things: this chapter, the heart of Automath, and of the logical framework LF, designed in 1987 for writing down logics.18 Go back and you reach , types that take types. Up and back together is , System F of 1972. The far top corner, with all three switched on, is , the calculus of constructions, and it is the calculus at the core of a proof assistant that thousands of mathematicians and engineers now use.19
Read through the Curry–Howard correspondence, every corner is a logic as well as a type system, and the cube becomes a cube of logics. is the logic of implication, the logic of Chapters 2 and 3. is first-order logic, this chapter’s predicates and quantifiers over things. is second-order propositional logic, Chapter 5’s quantifiers over propositions. is higher-order logic of every kind at once.
The edges are the moves of Part 1. Chapter 3 stood at one corner. This chapter walked one edge, to types that mention things. Chapter 5 walks another, to generics and then to the logic behind them. Nothing in this course leaves the edges that meet at ; the rest of the cube is where proof assistants live.
The picture did more than tidy up. Every corner is a part of , so one proof that the programs of all stop covers all eight calculi at once, and with it the consistency of all eight logics.
And the cube marks its own edge. Take one more step, beyond : let the type of all types be a type, . That is Girard’s paradox, which Chapter 5 tells, and there everything is provable.
History
The quantifier was invented twice, like natural deduction. Frege had it in 1879, in a notation nobody else used.20
Peirce and his student Mitchell had it by 1885, as and ,21 knowing nothing of Frege, and it was their version, carried by Schröder to Peano and by Peano to Russell, that became the logic everyone learned. Peano turned the into in 1897 and Gentzen added to match in 1934. Hilbert and Ackermann’s textbook of 1928 was the first to set out the first-order logic of this chapter as a system on its own, and to ask the question about it that Part 2 answers.22 Then the letters came back as types: in Howard’s notes, in de Bruijn’s checker, in Martin-Löf’s foundation, and, over types rather than things, in Girard’s and Reynolds’s calculus, the one in your compiler, whose story is Chapter 5’s. Figure 4.4 collects the dates.
| Who | When | What |
|---|---|---|
| Frege | 1879 | function and argument; the quantifier, in two dimensions |
| Peirce, Mitchell | 1883–85 | the quantifier again, as and |
| Peano | 1897 | |
| Hilbert & Ackermann | 1928 | first-order logic as a system of its own |
| Gentzen | 1934 | ; the quantifier rules, with their side conditions |
| Prawitz | 1965 | normalisation, quantifiers included |
| de Bruijn | 1968 | Automath: types that mention things, in a checker |
| Howard | 1969 | the quantifiers as a function from things and a pair |
| Girard; Reynolds | 1971; 1974 | over types: generics |
| Martin-Löf | 1972– | and ; a foundation on dependent types |
| Mitchell & Plotkin | 1988 | modules as existential types |
| Barendregt | 1991 | the -cube |
Summary
For two thousand years logic couldn’t put a some inside an every, and so couldn’t say most of what mathematics and specifications say. Quantifiers can. They are and with the list of cases made unbounded: is an and with a case for every thing, written once with a parameter, and an or whose tags are things. The four quantifier rules are four phrases: let be arbitrary, in particular for , take to be , let be such a thing. Two of them carry a condition on their eigenvariable, and the three ways of breaking the conditions are three bugs you’ve met, capture among them. The logic proves no atomic sentence, and a proof of there is names the thing.
Put the programs back and the quantifiers are two things you’ve programmed with: a proof of for all is a function from things, whose result type mentions its argument, and a proof of there is is a pair of a thing and evidence. These are and , the quantifiers’ first letters, which logic traded for and and type theory kept. The context, a stack, enforces every freshness condition but the one on (E), which is why that one alone is written on its rule. Erase the programs and the rules are NJ’s, bar for bar. Running a program removes detours, every typed program stops (proved by counting when there is no or , on loan when there is), and consistency and the existence property are the dividend.
A theory is a set of sentences, and “ follows from it” is a derivation, checkable by pattern matching: the driver theory, a comparator’s contract, a sale. Since the logic proves no atomic sentence on its own, everything about the camera comes from the theory. A type checker certifies that a program is safe to run. A verifier, a type checker whose types may say for all, certifies that it’s correct: what was asked of it is provable from what was assumed.
The -cube puts the type systems of Part 1 in one picture, sorted by what may depend on what. Chapter 3 is its nearest corner; this chapter’s dependent types are one step along one edge, and Chapter 5’s generics one step along another.
Exercises
Exercise 4.1. Write the typing tree for the camera’s read ticket in full, from the context of the section on dependent types, and then the tree the checker builds for record mic ticket, marking the bar at which it fails and what the error message says. Then say what the context would have to contain about the microphone for the handler to type.
Exercise 4.2. Take and the extra fact .
Derive , as a tree, and give its program.
Try to derive with the (I) bar above the (I) bar, and say which condition stops you.
Add the sentence “no kind may be read unless some driver has registered it” to the driver theory, and say which of , and you needed, and why the obvious first attempt says something weaker.
Exercise 4.3. Derive and check that its program is
Then try the converse, , and say exactly which side condition stops you.
Exercise 4.4. Derive and , and their converses, giving the program for each. (These are distributive laws one level up: a function into a pair is a pair of functions, and a pair with a tagged second component is a tagged pair.)
Exercise 4.5. Write a comparator, in any language, that violates exactly one of the three lines of the contract, and say which consequence of the contract it breaks. Which violation would a sort routine detect, and how?
Exercise 4.6.
Derive from the empty context over a signature with a constant , and say why there is no derivation when the signature has none.
Derive , using (E), and say what program it is.
Try to derive the converse, , and say where you get stuck. What would the existence property have to give up for it to go through?
Exercise 4.7. Suppose (I) carried no side condition, so that a tree could generalise over a variable free in an open hypothesis.
From the hypothesis derive, in turn,
Conclude from the two hypotheses and , for constants and , which say only that the holder has a capability for one kind and not for another.
Say which of the steps in (1) the real rule forbids, and state the corresponding compiler error.
Exercise 4.8. Try to derive : “there is a kind such that, if the holder has a capability for it, it has one for every kind”. Use the existence property to say what a closed derivation would have to hand over, and then say where every attempt sticks. Keep your attempt; Part 2 returns to this formula, together with , which NJ does not derive either.
References
- Henk Barendregt. Introduction to generalized type systems. Journal of Functional Programming, 1(2):125–154, 1991.
- Alonzo Church. A formulation of the simple theory of types. Journal of Symbolic Logic, 5(2):56–68, 1940.
- Thierry Coquand and Gérard Huet. The calculus of constructions. Information and Computation, 76(2–3):95–120, 1988.
- N. G. de Bruijn. The mathematical language AUTOMATH, its usage, and some of its extensions. In Symposium on Automatic Demonstration, volume 125 of Lecture Notes in Mathematics, pages 29–61. Springer, Berlin, 1970.
- Gottlob Frege. Begriffsschrift, eine der arithmetischen nachgebildete Formelsprache des reinen Denkens. Louis Nebert, Halle, 1879. English translation by S. Bauer-Mengelberg in J. van Heijenoort (ed.), From Frege to Gödel, Harvard University Press, 1967, pp. 1–82.
- Gerhard Gentzen. Untersuchungen über das logische Schließen I, II. Mathematische Zeitschrift, 39:176–210, 405–431, 1934. Appeared 1934–35; English translation in The Collected Papers of Gerhard Gentzen, ed. M. E. Szabo, North-Holland, 1969.
- Jean-Yves Girard. Interprétation fonctionnelle et élimination des coupures de l’arithmétique d’ordre supérieur. Thèse de doctorat d’état, Université Paris VII, 1972.
- Charles S. Peirce. On the algebra of logic: A contribution to the philosophy of notation. American Journal of Mathematics, 7(2):180–202, 1885.
- Dag Prawitz. Natural Deduction: A Proof-Theoretical Study. Almqvist & Wiksell, Stockholm, 1965.
- John C. Reynolds. Towards a theory of type structure. In Programming Symposium, Paris, 1974, volume 19 of Lecture Notes in Computer Science, pages 408–425. Springer, 1974.
- William W. Tait. Intensional interpretations of functionals of finite type I. Journal of Symbolic Logic, 32(2):198–212, 1967.
- The MITRE Corporation. CWE-843: Access of resource using incompatible type (‘type confusion’). Common Weakness Enumeration, 2024. https://cwe.mitre.org/data/definitions/843.html.
- Alan M. Turing. On computable numbers, with an application to the Entscheidungsproblem. Proceedings of the London Mathematical Society, s2-42(1):230–265, 1937.
- L. S. van Benthem Jutting. Checking Landau’s “Grundlagen” in the AUTOMATH System. PhD thesis, Eindhoven University of Technology, 1977.
- Jean van Heijenoort, editor. From Frege to Gödel: A Source Book in Mathematical Logic, 1879–1931. Harvard University Press, Cambridge, MA, 1967.
Notes
Catalogued as CWE-843, “Access of Resource Using Incompatible Type” (The MITRE Corporation, 2024). It is a staple of kernel exploits: a handle, a message or an object of one kind is fed to code written for another, and the second reads the first’s bytes as a structure of its own, pointers and all. ↩
“I believe that the replacement of the concepts subject and predicate by argument and function, respectively, will stand the test of time” (Frege, 1879, preface), in the translation in van Heijenoort. It has. Frege’s own symbol for every was a dip in the horizontal line of a formula with a Gothic letter sitting in it. His formulas were two-dimensional, which is one reason almost nobody read the book. The notation lost; the analysis won. ↩
Quine put the point as a slogan in 1948: to be is to be the value of a variable. If you want to know what a theory says exists, he argued, don’t look at its nouns; look at what its quantifiers range over. Philosophers have argued about the slogan ever since, which, for a philosopher, is a mark of success. ↩
By Kant, in the preface to the second edition of the Critique of Pure Reason (1787): since Aristotle, logic “has been unable to advance a step and, thus, to all appearance has reached its completion”. Ninety-two years later the Begriffsschrift appeared, a booklet of eighty-eight pages that van Heijenoort, who edited the standard collection of the papers that followed it, called “perhaps the most important single work ever written in logic” (van Heijenoort, 1967, p. 1). Philosophers who announce that a subject is finished have a poor record, and Kant’s is among the worst. ↩
The example is traditionally credited to Augustus De Morgan, who in the 1840s collected inferences that the syllogism could not handle and argued that logic needed relations. He was right, and was largely ignored. ↩
Gentzen (1934); the Allzeichen first appears there, Peano’s dates from 1897. The side conditions, as Gentzen stated them for trees, are the ones in the definition below, and he called the variable they restrict the Eigenvariable, the variable proper to that step. Peano, who gave logic and , also believed that mathematicians should share one language, and that it should be Latin with the grammar taken out. He invented it, called it Latino sine flexione, and wrote the last edition of his great compendium of mathematics, the Formulario Mathematico of 1908, in it. The symbols caught on; the Latin did not. ↩
All three are about theorems, with no hypotheses. From a hypothesis you can’t name a witness, since a hypothesis is assumed and not derived, and shows nothing of how it came to hold, which is why a log may say “declined or approved” without saying which. And with no constant in the signature, fails, since there is no term to be the witness: the logic assumes nothing it isn’t told, where most logic textbooks assume that something exists. ↩
The code is Haskell with one change: an argument that the type mentions is named on the arrow, as in
(k : Kind) -> Handle k, which is how languages whose types may mention values write such a type. Haskell doesn’t accept the lines by default, because its types are not allowed to mention values. That is a design decision, not a limitation of the idea. ↩Peirce (1885) for the first letters; Martin-Löf, from 1972, for the dependent types. Martin-Löf’s and may range over any type, including types that are themselves propositions, and in his system and are simply what and are called when the body is a proposition. The chapter’s and range over the signature’s one domain, which is the first-order case, and the one whose logic is Gentzen’s. ↩
Two entries may be swapped when neither depends on the other, so the stack is a stack only as far as the dependencies go. A hypothesis that doesn’t mention can always be moved below it, and generalising over with such a hypothesis in force is fine, as it should be. ↩
is the type of an action that returns nothing of interest. ↩
Landau’s Foundations of Analysis: a good choice, since nobody could accuse Landau of skipping steps. The book builds the real numbers from the natural numbers in 301 numbered theorems, and its preface for the student begins: “Please forget everything you have learned in school; for you haven’t learned it.” The preface for the teacher explains that the book is written, “as befits such easy material, in merciless telegram style”. A clerk could ask for no better source. ↩
de Bruijn (1970); the thesis is Jutting’s (1977). De Bruijn’s name sits beside Howard’s in the history of the correspondence, and this is why: he found the correspondence on his own, from the checker’s end, and built the checker. Howard’s notes of 1969 already had these two types, in their second half, as the constructions that go with the quantifiers of arithmetic. Martin-Löf made them the basis of a whole foundation for mathematics from 1972, after a first attempt that proved everything. ↩
Prawitz (1965) for the conversions, Tait (1967) for computable terms. ↩
Barendregt (1991). Barendregt’s earlier book, The Lambda Calculus: Its Syntax and Semantics (1981), is still the reference for the untyped calculus of Chapter 3. It also fixed a convention that this chapter has been quietly relying on: choose the bound variables of a term different from its free ones, and renaming is never needed, so capture can’t happen. Every author since has adopted it. In 2007 Urban, Berghofer and Norrish showed that the convention, used carelessly in a proof by rule induction, can be used to prove a wrong theorem. The bug of the section on side conditions is a patient one. ↩
The corners have their inventors: is Church (1940), is Girard (1972) and Reynolds (1974), LF is Harper, Honsell and Plotkin. ↩
The calculus is Coquand and Huet (1988)’s. The proof assistant was called Coq, after the calculus of constructions, after Thierry Coquand, and after the rooster that is the national symbol of France. In 2025 it was renamed Rocq, officially in honour of Inria’s Rocquencourt site, where it was first built. Anyone who has said the old name aloud in an English-speaking lecture theatre can guess at the unofficial reasons. ↩
Frege’s own system didn’t outlive its first decade. In June 1902, with the second volume of his Basic Laws of Arithmetic at the printer, he received a polite letter from the young Bertrand Russell, showing that one of its laws, about the extension of a concept, led to a contradiction. Frege’s logic quantified over concepts as well as objects, the second-order kind of Chapter 5, and the contradiction lived there. Frege added an appendix, which begins: “Hardly anything more unfortunate can befall a scientific writer than to have one of the foundations of his edifice shaken after the work is finished.” The quantifier survived; the edifice didn’t. ↩
Some historians think the student taught the teacher, and that Mitchell’s notation of 1883 is where Peirce’s came from. Peirce’s career went less well than his logic. The Johns Hopkins lectureship that gave him Mitchell was the only university post he ever held; he lost it in 1884 after a scandal over his remarriage, and died poor in 1914, after which Harvard bought his papers from his widow. ↩
Hilbert was sure that every such question would be answered. Closing an address at Königsberg in September 1930, broadcast on the radio, he said: Wir müssen wissen. Wir werden wissen, “we must know; we will know”. The words are on his gravestone in Göttingen. The day before, at a round table in the same meeting, a twenty-four-year-old named Kurt Gödel had announced a theorem saying that no system of proofs for arithmetic that a clerk can check settles every question it can ask. Part 3 tells that story. ↩