3.2. A minimal kernel#
In the previous section we used the kernel as a black box: we gave it a proof tree, and it answered which
equation the tree justifies. Now we open the box. The whole kernel is one file, kernel.py, and one class,
Kernel. We will see almost all of its code, because this is exactly the point: the kernel should
be small enough to be read and understood.
import inspect
import textwrap
import kernel
from kernel import Kernel, ProofError, Refl, Symm, Trans, CongrArg, Inst, subst
from syntax import term, equation, show, show_equation
def show_code(obj):
"""Prints the code of a function or method (without the class indent)."""
print(textwrap.dedent(inspect.getsource(obj)))
3.2.1. Terms#
A term is a tree. In Python we write terms as tuples: the first element of a tuple is the symbol of an
operation, and the remaining ones are the arguments. Variables and constants are strings. The parser from the
file syntax.py turns the usual notation into tuples, and the function show turns
them back:
t = term("x + y * n(x)")
print(t)
print(show(t))
('+', 'x', ('*', 'y', ('n', 'x')))
x + y * n(x)
Which symbols are allowed and how many arguments they take is given by the signature — a dictionary that the kernel receives when it is created. For Boolean algebra:
from boolean import SIGNATURE
print(SIGNATURE)
{'+': 2, '*': 2, 'n': 1, '0': 0, '1': 0}
Constants are symbols with zero arguments, and any other identifier can be a variable — the method is_var
recognizes variables. The method term checks whether a string or a tuple is a well-formed term of this
signature; the kernel calls it for every term that it receives from outside. Both methods accept only plain
strings and tuples (type(t) is str), not objects of their subclasses — we will see why when we prove the kernel sound in §3.4:
show_code(Kernel.is_var)
show_code(Kernel.term)
def is_var(self, x):
"""Is x a variable: a name (identifier) outside the signature?"""
return type(x) is str and x.isidentifier() and x not in self.signature
def term(self, t):
"""Checks that t is a well-formed term of the signature.
Only plain strings and tuples (type(...) is ...): a subclass of str
with its own == could fool the comparison of middles in Trans."""
if type(t) is str:
if self.signature.get(t) == 0 or self.is_var(t):
return t
elif (type(t) is tuple and t and type(t[0]) is str
and self.signature.get(t[0]) == len(t) - 1):
for a in t[1:]:
self.term(a)
return t
raise ProofError(f"not a term: {t!r}")
The parser is not part of the kernel, but it is not irrelevant to trust. The kernel checks a proof of the statement that it was given. If the parser misread a string, the kernel would check a different statement from the one we have in mind. We will return to this problem in §3.4.
3.2.2. Substitution#
The rule Inst requires substituting terms for variables. This takes four lines:
show_code(subst)
def subst(t, s):
"""Replaces at once the variables in the dict s (variable -> term)."""
if isinstance(t, str):
return s.get(t, t)
return (t[0],) + tuple(subst(a, s) for a in t[1:])
Substitution is simultaneous: the substitution \(x := y\), \(y := x\) swaps the two variables instead of giving \(x + x\), as substituting one after the other would (first \(x := y\), then \(y := x\)). The second example is the instance of axiom H3 from the third step of the proof of \(x + x = x\):
print(show(subst(term("x + y"), {"x": "y", "y": "x"})))
s = {"x": "x", "y": "x", "z": term("n(x)")}
print(show(subst(term("x + y * z"), s)))
y + x
x + x * n(x)
Why is it so simple? Our terms have no bound variables: they contain no quantifiers \(\forall\), \(\exists\), and no \(\lambda\)-functions. If they did, substitution would require care. Let us substitute \(y := x\) in the formula \(\forall x\ (x + y = y + x)\) by simply replacing letters. We get \(\forall x\ (x + x = x + x)\), which is a completely different statement, because the new \(x\) has been “captured” by the quantifier. The kernels of Lean and other proof assistants have to guard against this; one of the solutions is de Bruijn indices (more in §3.5). We avoid this problem by choosing a logic without bound variables.
3.2.3. The heart of the kernel: the method conclusion#
The most important method of the kernel takes a proof tree and returns a pair of terms: the left-hand and the
right-hand side of the equation that the tree justifies. If the tree is not a valid proof, it raises the
exception ProofError.
show_code(Kernel.conclusion)
def conclusion(self, d):
"""The equation (left, right) that the proof d justifies."""
match d:
case Refl(t):
return self.term(t), t
case Symm(p):
a, b = self.conclusion(p)
return b, a
case Trans(p, q):
a, b = self.conclusion(p)
b2, c = self.conclusion(q)
if b != b2:
raise ProofError(f"Trans: middles {b!r} and {b2!r}")
return a, c
case CongrArg(z, C, p):
if not self.is_var(z):
raise ProofError(f"CongrArg: {z!r} is not a variable")
self.term(C)
a, b = self.conclusion(p)
return subst(C, {z: a}), subst(C, {z: b})
case Inst(name, args):
if name not in self.facts:
raise ProofError(f"unknown fact: {name}")
variables, l, r = self.facts[name]
if len(args) != len(variables):
raise ProofError(f"{name}: wrong number of arguments")
s = dict(zip(variables, map(self.term, args)))
return subst(l, s), subst(r, s)
raise ProofError(f"not a proof: {d!r}")
The match statement recognizes the kind of node and immediately unpacks its fields. The five cases are the
five rules:
Refl(t)— only checks that \(t\) is a term and returns \((t, t)\).Symm(p)— computes the conclusion of the subtree \(p\) and swaps its sides.Trans(p, q)— computes the conclusions of both subtrees and compares the middle terms. This is the only place in the methodconclusionwhere the kernel compares terms (the methodtheoremlater compares the conclusion with the stated theorem); the comparisonb != b2checks that the trees are identical, not that they are equal “after simplification”.CongrArg(z, C, p)— checks that \(z\) is a variable and \(C\) is a term, and inserts both sides of the conclusion of \(p\) into the hole \(z\) of the context \(C\).Inst(name, args)— looks up the fact with this name, checks the number of arguments, and substitutes them for the variables of the fact.
The method is recursive: it computes the conclusion of a tree from the conclusions of its subtrees and visits each node exactly once. There is no searching or guessing here at all. The kernel does not know why the proof looks the way it does; it only checks whether each node is a correct application of a rule.
3.2.4. The environment: axioms and theorems#
The kernel stores an environment: the dictionary facts, which assigns to the name of a fact
its variables and both sides of its equation. Facts are added by two methods. An axiom enters the environment
without a proof. A theorem enters it only if the conclusion of its proof is exactly the stated equation:
show_code(Kernel.axiom)
show_code(Kernel.theorem)
show_code(Kernel._add)
def axiom(self, name, variables, l, r):
self._add(name, variables, l, r, {name})
def theorem(self, name, variables, l, r, proof):
"""Adds ∀ variables, l = r — only when the proof justifies it."""
if self.conclusion(proof) != (l, r):
raise ProofError(f"{name}: the proof justifies another equation")
used = used_facts(proof)
assumed = set().union(*(self.assumptions[n] for n in used))
self._add(name, variables, l, r, assumed)
def _add(self, name, variables, l, r, assumptions):
variables = tuple(variables)
if name in self.facts:
raise ProofError(f"name already taken: {name}")
self.term(l), self.term(r)
if not all(map(self.is_var, variables)): # a constant is no variable
raise ProofError(f"{name}: {variables!r} are not all variables")
if not (term_vars(l, self.signature)
| term_vars(r, self.signature)) <= set(variables):
raise ProofError(f"{name}: undeclared variable")
self.facts[name] = (variables, l, r)
self.assumptions[name] = frozenset(assumptions)
A few details matter:
a proof can refer only to facts that are already in the environment, so no proof can appeal to itself or to a theorem proved “later”;
the name of a fact must be new, so a theorem, once accepted, cannot be replaced;
the declared variables of a fact must be variables, not constants: otherwise the rule
Instwould substitute terms for constants (the first version of the kernel did not guard against this — details in §3.4);all variables of the equation must be declared: a theorem says “for all \(x\)”, and we know which \(x\) is meant.
Let us build the environment of Boolean algebra with six theorems from the file boolean.py. Their proofs are
built by tactics, the subject of the next section; the kernel checks them in the same way as a proof
assembled by hand.
from boolean import theory_with_theorems
j, proofs = theory_with_theorems()
for name, (variables, l, r) in j.facts.items():
print(f"{name:13} ∀ {', '.join(variables):8} {show(l)} = {show(r)}")
H1 ∀ x, y x + y = y + x
H2 ∀ x, y x * y = y * x
H3 ∀ x, y, z x + y * z = (x + y) * (x + z)
H4 ∀ x, y, z x * (y + z) = x * y + x * z
H5 ∀ x x + 0 = x
H6 ∀ x x * 1 = x
H7 ∀ x x + n(x) = 1
H8 ∀ x x * n(x) = 0
add_idem ∀ x x + x = x
mul_idem ∀ x x * x = x
add_one ∀ x x + 1 = 1
mul_zero ∀ x x * 0 = 0
absorb ∀ x, y x + x * y = x
compl_compl ∀ x n(n(x)) = x
3.2.5. What a theorem rests on#
With every fact, the kernel records the set of axioms on which this fact rests: an axiom rests on itself, and
a theorem on the union of the assumptions of the facts used in its proof. The command #print axioms in Lean
works in a similar way.
for name in proofs:
print(f"{name:13} {' '.join(sorted(j.assumptions[name]))}")
add_idem H3 H5 H6 H7 H8
mul_idem H4 H5 H6 H7 H8
add_one H2 H3 H6 H7
mul_zero H1 H4 H5 H8
absorb H1 H2 H3 H4 H6 H7
compl_compl H1 H2 H4 H6 H7 H8
The proof of the equation \(x + x = x\) uses neither commutativity (H1, H2) nor axiom H4. Such information can
be valuable: the theorem then holds in every structure in which just the axioms used by the proof hold. For
the proof of the Riemann hypothesis, #print axioms lists Lean’s three standard axioms and nothing else — this
means that nowhere in the 175,187 files was an assumption about prime numbers or about the zeros of the
function \(\zeta\) added.
3.2.6. What the kernel rejects#
Let us watch the kernel in action on a few bad proofs. The function check prints the conclusion
or the reason for rejection:
def check(d):
try:
print("accepted:", show_equation(j.conclusion(d)))
except ProofError as error:
print("rejected:", error)
check(Trans(Inst("H5", ("x",)), Inst("H6", ("x",)))) # the middles differ
check(Inst("H3", ("x",))) # too few arguments
check(Inst("H9", ("x",))) # no such fact
check(Refl(("+", "x"))) # + takes two arguments
check(Trans(Symm(Inst("H5", ("x",))), Inst("H5", ("x",))))
rejected: Trans: middles 'x' and ('*', 'x', '1')
rejected: H3: wrong number of arguments
rejected: unknown fact: H9
rejected: not a term: ('+', 'x')
accepted: x = x
The first proof tries to join \(x + 0 = x\) with \(x \cdot 1 = x\), and the middle terms \(x\) and \(x \cdot 1\)
differ. The last one is correct: \(x = x + 0\) and \(x + 0 = x\) imply \(x = x\). There is also an error of
a different kind: a correct proof, but of a different statement from the one stated. The kernel will accept
the tree Inst("H5", ("x",)), because it proves the equation \(x + 0 = x\), but not as a proof of the equation
\(x + x = x\):
try:
j.theorem("wrong", ["x"], *equation("x + x = x"), Inst("H5", ("x",)))
except ProofError as error:
print("rejected:", error)
rejected: wrong: the proof justifies another equation
3.2.7. The kernel does not check axioms#
What if someone added an axiom that is not true? The kernel will accept it without discussion: an axiom is an
assumption, not a theorem. Let us add the “miracle” \(x + y = x\) (the axiom miracle) and
use it to prove the false equation \(x + 1 = x\):
from boolean import theory
j2 = theory()
j2.axiom("miracle", ["x", "y"], *equation("x + y = x"))
j2.theorem("falsehood", ["x"], *equation("x + 1 = x"), Inst("miracle", ("x", "1")))
print("accepted; assumptions:", sorted(j2.assumptions["falsehood"]))
accepted; assumptions: ['miracle']
The kernel was right: \(x + 1 = x\) follows from the axiom miracle. The kernel checks logical consequence,
not the truth of the axioms, and the list of assumptions immediately reveals where the falsehood came from.
This is exactly how sorry works in Lean: this command closes a proof by adding the axiom sorryAx, and
#print axioms shows it. That is why, for the proof of the Riemann hypothesis, it was so important that the
list of axioms contains only the three standard entries.
3.2.8. How big is the kernel?#
Let us count the lines of code of the kernel, skipping blank lines, comments, and documentation strings (docstrings):
import ast
source = inspect.getsource(kernel)
docs = set()
for node in ast.walk(ast.parse(source)):
if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef)):
first_one = node.body[0]
if isinstance(first_one, ast.Expr) and isinstance(
first_one.value, ast.Constant):
docs.update(range(first_one.lineno, first_one.end_lineno + 1))
loc = [w for i, w in enumerate(source.splitlines(), start=1)
if w.strip() and not w.strip().startswith("#") and i not in docs]
print("lines of kernel code:", len(loc))
lines of kernel code: 103
That is fewer than a hundred and twenty lines, which can be read in a quarter of an hour. The principle that a program we trust should be small enough to be checked by hand is called the de Bruijn criterion, after N. G. de Bruijn, the creator of the Automath system. Lean’s kernel is much larger than ours, because its logic is much richer, but the idea is the same: everything outside the kernel — the parser, tactics, automated proving — may make mistakes and still will not introduce a false theorem.
3.2.9. Summary#
Terms are tuples; the signature says which symbols are allowed. Without bound variables, substitution is an ordinary, simultaneous replacement of variables.
The method
conclusionis five cases of amatchstatement, one for each rule. The kernel searches for nothing: it visits each node once and, in the methodconclusion, compares terms only in the ruleTrans.A theorem enters the environment only if the conclusion of its proof is exactly the stated equation; facts are added one by one, so there is no circular reasoning.
The kernel checks that statements follow from the axioms, not that the axioms are true. The list of assumptions (
#print axioms) shows what a theorem really rests on.
3.2.10. Exercises#
★ Predict on paper the conclusion of the proof
Trans(Inst("H1", ("x", "y")), Inst("H1", ("y", "x"))), and then check it with the methodj.conclusion. Build a similar proof of the equation \(x \cdot y = x \cdot y\) that does not use the ruleRefl.★ In a copy of the method
conclusion, add printing of every visited node and trace how the kernel checks the proof of \(x + x = x\) from the previous section. How many times does the kernel compare terms in the ruleTrans?★★ Build a “broken kernel”: a subclass of the class
Kernelin which the ruleTransdoes not check whether the middle terms are equal. Build a “proof” of the equation \(x + y = x\) in it and point out the node that smuggles in the falsehood.★★★ Add to the kernel the rule
Congr(f, p₁, …, pₖ): the equations \(a_i = b_i\) imply \(f(a_1, \dots, a_k) = f(b_1, \dots, b_k)\) (in Lean,congr). Show that the new rule is redundant: every use of it can be replaced by the rulesCongrArgandTrans(for a constant, which has no arguments, by the ruleRefl). Write a function that does this.