3.3. Tactics: from pattern to proof#
Writing proof trees by hand is tedious: the five-line proof of \(x + x = x\) has fourteen nodes, and nobody
wants to write out contexts and substitutions. In Lean we write rw [h], calc, or simp instead. These
are tactics: programs that build the proof tree for us. Tactics lie outside the kernel. They can be
large, clever, and buggy — their output is checked by the kernel anyway:
In this section we will write two tactics: rw, which rewrites the goal with one fact, and calc, which
assembles a chain of equalities. The code is in the file tactics.py.
import inspect
import textwrap
from kernel import ProofError, Refl, Symm, Trans, CongrArg, Inst
from syntax import term, equation, show, show_equation, lean, size
from boolean import theory
import tactics
def show_code(obj):
"""Prints the code of a function or method (without the class indent)."""
print(textwrap.dedent(inspect.getsource(obj)))
j = theory()
3.3.1. Pattern matching#
To apply an axiom to an expression, we first have to find a substitution. The left-hand side of axiom H3 is
the pattern \(x + y \cdot z\); it matches the term \(x + x \cdot n(x)\) with \(x := x\), \(y := x\),
\(z := n(x)\). Finding such a substitution is called matching. The function match_pattern walks through the
pattern and the term simultaneously: it binds each variable of the pattern to the corresponding subtree of the
term, and it compares symbols.
show_code(tactics.match_pattern)
def match_pattern(pattern, t, free, s):
"""A substitution s of the variables in `free` with pattern[s] == t."""
if isinstance(pattern, str) and pattern in free:
if pattern in s:
return s if s[pattern] == t else None
return {**s, pattern: t}
if isinstance(pattern, str) or isinstance(t, str):
return s if pattern == t else None
if pattern[0] != t[0] or len(pattern) != len(t):
return None
for a, b in zip(pattern[1:], t[1:]):
s = match_pattern(a, b, free, s)
if s is None:
return None
return s
The first case is important: if a pattern variable is already bound, the new subtree must be the same as the previous one. That is why the pattern \(x \cdot n(x)\) from axiom H8 matches \((a + b) \cdot n(a + b)\) but not \(a \cdot n(b)\):
def matching(fact, text):
free, l, _ = j.facts[fact]
s = tactics.match_pattern(l, term(text), free, {})
if s is None:
return f"{fact} does not match {text}"
return f"{fact} matches {text}: " + ", ".join(
f"{x} := {show(t)}" for x, t in s.items())
print(matching("H3", "x + x * n(x)"))
print(matching("H3", "x + n(x)"))
print(matching("H8", "(a + b) * n(a + b)"))
print(matching("H8", "a * n(b)"))
H3 matches x + x * n(x): x := x, y := x, z := n(x)
H3 does not match x + n(x)
H8 matches (a + b) * n(a + b): x := a + b
H8 does not match a * n(b)
Matching is one-sided: only the pattern has variables, and the variables of the term are treated as constants. Lean does something more general — unification, in which unknowns may occur on both sides — but the principle is the same.
3.3.2. The rw tactic#
The rw tactic takes a goal, that is, an equation to be proved, and the name of a fact. It does four things:
it looks for the first subterm of the goal (first on the left-hand side, then on the right-hand side) that the left-hand side of the fact matches; with the prefix
←it uses the fact from right to left;from the match it obtains an instance \(l' = r'\) of the fact;
it “cuts out” all occurrences of \(l'\) from the goal, replacing them with a hole \(z\) — this gives the contexts \(C_L\) and \(C_R\) (the function
abstract);the new goal is \(C_L[z := r'] = C_R[z := r']\); it builds a proof of the old goal from a proof of the new one with the rules
CongrArg(on both sides) andTrans. If both sides of the new goal are identical, it closes the goal with the ruleRefl. Our version raises an error when the goal is not closed after all the rewrites; Lean’srwthen leaves the new goal open for the rest of the proof.
show_code(tactics.abstract)
show_code(tactics.rw)
def abstract(t, u, z):
"""Replaces each occurrence of the subterm u by the variable z (a hole)."""
if t == u:
return z
if isinstance(t, str):
return t
return (t[0],) + tuple(abstract(a, u, z) for a in t[1:])
def rw(*rules):
"""The tactic rw [h₁, h₂, …]: rewrites in turn, then tries rfl."""
def tactic(kernel, goal):
pieces = []
for rule in rules:
previous = goal
goal, compose = rewrite(kernel, goal, rule)
pieces.append((previous, compose))
if goal[0] != goal[1]:
raise TacticError(f"rw: the goal {show_equation(goal)} remains")
d = Refl(goal[0])
for previous, compose in reversed(pieces):
d = compose(d) or Refl(previous[0])
return d
return tactic
Take the fourth step of the proof of \(x + x = x\). The goal is \(x + x \cdot n(x) = x + 0\); the tactic
rw("H8") finds \(x \cdot n(x)\), cuts it out of the left-hand side, rewrites it to \(0\), and closes the goal:
goal = equation("x + x * n(x) = x + 0")
new, _ = tactics.rewrite(j, goal, "H8")
print("new goal: ", show_equation(new))
d = tactics.rw("H8")(j, goal)
print("proof: ", lean(d))
print("conclusion:", show_equation(j.conclusion(d)))
new goal: x + 0 = x + 0
proof: congrArg (fun z => x + z) (H8 x)
conclusion: x + x * n(x) = x + 0
This is exactly the fourth step of the proof we built by hand in the first section: the context \(x + z\) and
an instance of H8. rw works the same way in Lean: it cuts the occurrences of the pattern out of the goal
(this produces a function called the motive) and assembles the proof from congrArg and Eq.mpr — the
rule that turns an equality of propositions \(A = B\) and a proof of the proposition \(B\) into a proof of the
proposition \(A\).
3.3.3. The calc tactic#
A proof on paper is a chain of equalities. The calc tactic takes the terms of the successive links and, for
each link, a tactic that justifies the step from the previous one; it joins the proofs of the links with the
rule Trans:
show_code(tactics.calc)
def calc(first, *steps):
"""calc a = b := t₁; _ = c := t₂; … — a chain (each step a tactic)."""
def tactic(kernel, goal):
a = term(first)
if a != goal[0]:
raise TacticError(f"calc: start {show(a)}, goal {show(goal[0])}")
proofs = []
for text, t in steps:
b = term(text)
proofs.append(t(kernel, (a, b)))
a = b
if a != goal[1]:
raise TacticError(f"calc: end {show(a)}, goal {show(goal[1])}")
return trans(*proofs) or Refl(a)
return tactic
The function prove runs a tactic on a goal and passes the result to the kernel. Here is the whole proof
of \(x + x = x\) — almost as on paper:
from tactics import calc, rw, prove
tactic = calc(
"x + x",
("(x + x) * 1", rw("H6")),
("(x + x) * (x + n(x))", rw("H7")),
("x + x * n(x)", rw("H3")),
("x + 0", rw("H8")),
("x", rw("H5")))
proof = prove(j, "add_idem", "x + x = x", tactic)
print("accepted theorem:", show_equation(j.conclusion(proof)), "| nodes:", size(proof))
accepted theorem: x + x = x | nodes: 14
In the first step the goal is \(x + x = (x + x) \cdot 1\), and rw("H6") rewrites the right-hand side, so
Symm appears in the tree. Let us compare the result of the tactic with the tree that we assembled by hand in
the first section:
by_hand = Trans(Trans(Trans(Trans(
Symm(Inst("H6", (term("x + x"),))),
Symm(CongrArg("z", term("(x + x) * z"), Inst("H7", ("x",))))),
Symm(Inst("H3", ("x", "x", term("n(x)"))))),
CongrArg("z", term("x + z"), Inst("H8", ("x",)))),
Inst("H5", ("x",)))
print("the same tree:", proof == by_hand)
the same tree: True
The tactics did not invent anything new: they built exactly the tree that we would have built ourselves, only without any effort on our part.
3.3.4. Six theorems from beginning to end#
The file boolean.py contains six theorems with calc-style proofs. Let us run them one after another on a
fresh kernel and look at the size of each tree and at the axioms each theorem relies on:
3.3.5. The same proof in Lean#
We wrote the same chain in Lean 4, without Mathlib, in the file Lecture03.lean. Boolean algebra is
the class HuntingtonAlgebra there, whose fields are the axioms H1–H8, and every calc step is closed by the
tactic rw with one axiom:
theorem add_idem (x : α) : x + x = x :=
calc x + x = (x + x) * 1 := by rw [H6]
_ = (x + x) * (x + n x) := by rw [H7]
_ = x + x * n x := by rw [H3]
_ = x + 0 := by rw [H8]
_ = x := by rw [H5]
We checked the file with Lean 4.33.1, the same version in which the proof of the Riemann hypothesis was
written. The command #print axioms add_idem answers:
'add_idem' does not depend on any axioms
The axioms H1–H8 are fields of the class here, and so hypotheses of the theorem, not axioms of Lean. The
command #print add_idem shows the term that Lean’s kernel checks:
theorem add_idem : ∀ {α : Type} [inst : HuntingtonAlgebra α] (x : α), x + x = x :=
fun {α} [HuntingtonAlgebra α] x =>
trans
(trans
(trans
(trans (Eq.mpr (id (congrArg (fun _a => x + x = _a) (H6 (x + x)))) (Eq.refl (x + x)))
(Eq.mpr (id (congrArg (fun _a => (x + x) * 1 = (x + x) * _a) (H7 x))) (Eq.refl ((x + x) * 1))))
(Eq.mpr (id (congrArg (fun _a => (x + x) * (x + n x) = _a) (H3 x x (n x)))) (Eq.refl ((x + x) * (x + n x)))))
(Eq.mpr (id (congrArg (fun _a => x + _a = x + 0) (H8 x))) (Eq.refl (x + 0))))
(Eq.mpr (id (congrArg (fun _a => _a = x) (H5 x))) (Eq.refl x))
The leaves are the same as in our tree: H6 (x + x), H7 x, H3 x x (n x), H8 x, and H5 x, chained by
transitivity (trans). Lean cuts out the context just as our tactic rw does: congrArg receives a function
with a hole, fun _a => …, that covers the whole goal, and Eq.mpr transfers the proof of the new goal to
the old one.
from boolean import THEOREMS
j = theory()
proofs = {}
for name, text, tactic in THEOREMS:
proofs[name] = prove(j, name, text, tactic)
assumed = " ".join(sorted(j.assumptions[name]))
print(f"{name:13} {text:14} nodes: {size(proofs[name]):2} {assumed}")
add_idem x + x = x nodes: 14 H3 H5 H6 H7 H8
mul_idem x * x = x nodes: 14 H4 H5 H6 H7 H8
add_one x + 1 = 1 nodes: 16 H2 H3 H6 H7
mul_zero x * 0 = 0 nodes: 16 H1 H4 H5 H8
absorb x + x * y = x nodes: 14 H1 H2 H3 H4 H6 H7
compl_compl n(n(x)) = x nodes: 32 H1 H2 H4 H6 H7 H8
The longest is the proof of the involution law \(n(n(x)) = x\): nine links on paper. Its tree in Lean-style notation:
print(textwrap.fill(lean(proofs["compl_compl"]), 79))
Eq.trans (Eq.trans (Eq.trans (Eq.trans (Eq.trans (Eq.trans (Eq.trans (Eq.trans
(Eq.symm (H6 (n (n x)))) (Eq.symm (congrArg (fun z => n (n x) * z) (H7 x))))
(H4 (n (n x)) x (n x))) (Eq.trans (congrArg (fun z => n (n x) * x + z) (H2 (n
(n x)) (n x))) (congrArg (fun z => n (n x) * x + z) (H8 (n x))))) (Eq.symm
(congrArg (fun z => n (n x) * x + z) (H8 x)))) (congrArg (fun z => z + x * n x)
(H2 (n (n x)) x))) (Eq.symm (H4 x (n (n x)) (n x)))) (Eq.trans (congrArg (fun z
=> x * z) (H1 (n (n x)) (n x))) (congrArg (fun z => x * z) (H7 (n x))))) (H6 x)
Nobody would want to write such a tree by hand, yet the kernel checks it without difficulty. That is why proofs in Lean are written with tactics, while the kernel sees only trees.
3.3.6. A library of theorems#
The proof of the absorption law \(x + x \cdot y = x\) uses the earlier theorem \(x + 1 = 1\):
print(textwrap.fill(lean(proofs["absorb"]), 79))
Eq.trans (Eq.trans (Eq.trans (Eq.trans (Eq.symm (congrArg (fun z => z + x * y)
(H6 x))) (Eq.symm (H4 x 1 y))) (congrArg (fun z => x * z) (H1 1 y))) (congrArg
(fun z => x * z) (add_one y))) (H6 x)
The whole proof of the theorem add_one (16 nodes) enters here as one Inst node. Every library of
theorems works this way, Mathlib included: a theorem, once checked, becomes a new fact that is used just like
an axiom. The list of assumptions is carried through all the theorems used — the absorption law relies on
the axioms H2, H3, and H7, although its proof does not mention them at all, because they are used by the
theorem add_one.
3.3.7. A tactic that cheats#
Since a tactic is an ordinary program, it can make mistakes — or even cheat. Here is a tactic that “proves” every goal by returning reflexivity of the left-hand side:
def cheater():
def tactic(kernel, goal):
return Refl(goal[0])
return tactic
try:
prove(j, "falsehood", "x + y = x", cheater())
except ProofError as error:
print("kernel:", error)
kernel: falsehood: the proof justifies another equation
The tactic returned a correct proof — but of the equation \(x + y = x + y\), not \(x + y = x\). The kernel compares the conclusion with the stated theorem and rejects the proof. No tactic, however wrong, will introduce a false theorem into the environment: at worst, it fails to build a proof.
This is the architecture that Robin Milner proposed in the LCF system in the 1970s and that modern proof assistants have today, in various forms. A small, trusted core checks; the rest, which may be arbitrarily large and arbitrarily clever, searches. In Lean, this rest consists of the parser, the elaborator, hundreds of tactics, and automated proving tools — a bug in any of them is a nuisance, but it does not threaten correctness.
Try it yourself: Boole Lab
You can try everything from this section in the browser:
Boole Lab is a proof lab modelled
on Peano Lab, running the same kernel. You start a theorem with bl prove, write tactics as in Lean
(rw [← H6 (x + x)], symm, exact), and qed hands the tree to the kernel. The command hint and the grey
suggestions in the prompt propose the next step, and colours show which library lemma matches the goal and
where. The library contains theorems with full proofs — from idempotence to associativity, De Morgan’s laws and
the Robbins equation — and the command bl lean rewrites every proof in Lean.
3.3.8. Summary#
A tactic is a program that builds a proof tree for a goal. Tactics are outside the kernel, so they need not be trusted.
rwcombines pattern matching, cutting out a context (the motive), and the rulesCongrArg,Symm,Trans;calcjoins the links of a chain with the ruleTrans.Tactics build the same trees that we would build by hand: for \(x + x = x\) we got exactly the tree from the first section.
A theorem, once checked, becomes a fact: it enters later proofs as a single node.
A faulty or cheating tactic may fail to build a proof, but it cannot smuggle in a falsehood.
3.3.9. Exercises#
★ Prove the dual absorption law \(x \cdot (x + y) = x\) with the tactics
calcandrw. Hint: \(x \cdot (x + y) = (x + 0) \cdot (x + y) = x + 0 \cdot y = \dots\) — the theoremmul_zeroand commutativity will be useful. Which axioms does your proof use?★ Prove the equation \(n(0) = 1\). Hint: start with \(n(0) = 0 + n(0)\).
★★ The tactic below has a bug: the programmer decided that the rule
Symmis unnecessary and removes it from the proof.def no_symm(d): if isinstance(d, Symm): return no_symm(d.p) if isinstance(d, Trans): return Trans(no_symm(d.p), no_symm(d.q)) if isinstance(d, CongrArg): return CongrArg(d.z, d.C, no_symm(d.p)) return d def rw_no_symm(rule): return lambda kernel, goal: no_symm(rw(rule)(kernel, goal))
Try it on the goals \(x + 0 = x\) and \(x = x + 0\). What does the kernel answer? For which goals does the bug go unnoticed — and why is this not dangerous?
★★ Write a tactic
simp(*rules)that rewrites the goal with the given rules for as long as possible (with a limit of one hundred steps) and only then triesrfl. Use it to prove \(x + x \cdot n(x) = x\). What happens when commutativity, H1, is among the rules?★★★ The
rwtactic uses the first match it finds. Find a goal in whichrw("H1")rewrites an occurrence other than the intended one, and then write a variantrw_at(rule, path)in which the place of rewriting is specified by a path in the term tree.