About this notebook
Companion to Lecture 11: Metaprogramming and automation. Every cell below was executed against the course’s pinned Lean 4 + Mathlib (see
lean/lean-toolchain); each Lean result is exactly what Lean printed. Download the notebook (.ipynb)
Lecture 11 says that a tactic is an ordinary Lean program that writes part of a proof term. Here you write several, run them on goals, and look inside the terms they build. You will:
- write a macro, then an extensible tactic made of
syntaxand severalmacro_rules, and watch the order in which Lean tries the rules; - write an elaborator that looks at the shape of the goal and picks a tactic for it;
- print the raw
Exprof terms and goals, and seeintroturn a bound variable into a hypothesis; - break a tactic on purpose, and watch the kernel reject its term;
- add lemmas to the simp set and ask
simp?what it used.
As in every notebook, each grey %%lean cell is sent to a real Lean process, and the box
under it is Lean’s answer: green for accepted, gold for accepted with a sorry, and
red-brown for a cell that is meant to fail.
import leanmagic
leanmagic.setup("import LeanFV.Meta.Tactics")Lean 4.35.0 ready; header `import LeanFV.Meta.Tactics` elaborated.
The header loads Lean’s metaprogramming API and the course file
lean/LeanFV/Meta/Tactics.lean. That file holds the finished tactics of Lecture 11
(my_trivial, show_goal, my_assumption) and two printers, #expr_tree and show_expr,
that we use in section 3. Everything else we build here, under new names.
1. Macros
The smallest tactic is a macro with one rule. close_it is just another name for rfl:
macro "close_it" : tactic => `(tactic| rfl)
example : 3 * 4 = 12 := by close_it✓ Lean accepted this (no messages)
A macro does no reasoning of its own. On a goal that rfl cannot close, the error is
rfl’s error, word for word:
This cell is meant to fail:
example (p : Prop) (hp : p) : p := by close_it✗ rejected, as intended
error, line 1Tactic `rfl` failed: Expected the goal to be a binary relation
Hint: Reflexivity tactics can only be used on goals of the form `x ~ x` or `R x x`
p : Prop
hp : p
⊢ p
To make a tactic that others can extend, declare its syntax once and give it rules with
macro_rules. Each rule is a separate declaration, so a later file can add more. When
several rules apply, which does Lean try first? Let each rule announce itself with trace
and find out:
syntax "probe" : tactic
macro_rules
| `(tactic| probe) => `(tactic| (trace "older rule: rfl"; rfl))
macro_rules
| `(tactic| probe) => `(tactic| (trace "newer rule: assumption"; assumption))
example : 2 + 2 = 4 := by probe✓ Lean accepted this
newer rule: assumption older rule: rfl
The newer rule ran first. assumption failed (there are no hypotheses), so Lean backtracked
and tried the older rule, and rfl succeeded. The order is: newest rule first, then older
ones, until one works. Core Lean’s trivial is built exactly like this, from six rules.
Here is a small automation tactic in the same style. Its last rule is recursive: it splits a conjunction and calls itself on both halves.
syntax "auto1" : tactic
macro_rules | `(tactic| auto1) => `(tactic| rfl)
macro_rules | `(tactic| auto1) => `(tactic| assumption)
macro_rules | `(tactic| auto1) => `(tactic| omega)
macro_rules | `(tactic| auto1) => `(tactic| (constructor <;> auto1))
example (p : Prop) (hp : p) : p := by auto1
example (a b : Nat) (h : a < b) : a + 1 ≤ b + 5 := by auto1
example (a : Nat) (p q : Prop) (hp : p) (hq : q) : (p ∧ a + 0 = a) ∧ q := by
auto1✓ Lean accepted this (no messages)
And a goal it cannot do. Before you run it, guess which rule’s message you will see.
This cell is meant to fail:
example (p q : Prop) (hq : q) : p ∨ q := by auto1✗ rejected, as intended
warning, line 1Tactic `constructor` applied constructor `Or.inl`, but `Or.inr` also matches the goal.
Hint: Use `constructor!` to apply the first matching constructor without this warning:
[apply] constructor!
error, line 1Tactic `rfl` failed: The left-hand side
p
is not definitionally equal to the right-hand side
q
p q : Prop
hq : q
⊢ p ∨ q
Two messages. The warning comes from the newest rule: constructor chose Or.inl, and
then auto1 could not prove p. Messages from a branch that failed are still printed. The
error comes from the last rule tried, the oldest one, rfl. It reads p ∨ q as the
relation Or applied to p and q, and complains that p and q differ. So when a
macro tactic fails, the error belongs to whichever rule happened to run last, and it can
look unrelated to your goal.
Your turn
Add a fifth rule so that
auto1proves the last goal. Hint:rightturnsp ∨ qintoq. Write it as(right; auto1)so that the new goal is handled byauto1too.
2. An elaborator that reads the goal
A macro cannot look at the goal; an elaborator can. step below gets the main goal (a
metavariable), reads its type, and puts it in weak head normal form with whnfR, which
unfolds just enough to expose the outermost constructor. Then it chooses a tactic by the shape
of the goal and runs it with evalTactic:
goal shape step runs
A ∧ B constructor (two new goals)
A → B, ∀ x, B intro (a new hypothesis)
a = b first | rfl | omega
anything else assumptionopen Lean Elab Tactic Meta
elab "step" : tactic => do
let g ← getMainGoal
let t ← g.withContext do whnfR (← g.getType)
if t.isAppOfArity ``And 2 then
evalTactic (← `(tactic| constructor))
else if t.isForall then
evalTactic (← `(tactic| intro))
else if t.isAppOfArity ``Eq 3 then
evalTactic (← `(tactic| first | rfl | omega))
else
evalTactic (← `(tactic| assumption))
theorem two_facts (p q : Prop) : p → q → p ∧ q := by
repeat step
#print two_facts✓ Lean accepted this
theorem two_facts : ∀ (p q : Prop), p → q → p ∧ q := fun p q a a_1 ↦ ⟨a, a_1⟩
repeat step ran step five times: two intros, one constructor, two assumptions.
The names a and a_1 in the printed term are the ones intro invents when you give it
none. step is a tiny policy: a rule that maps a goal to a tactic. Notebook 12 runs a
search over such choices, and the AI provers of Lecture 12 replace the hand-written rule
with a trained model.
A policy is only as good as its cases. step has no case for ∨, so it tries
assumption, which fails; repeat stops quietly, and the goal is left open:
This cell is meant to fail:
example (p q : Prop) (hq : q) : p ∨ q := by
repeat step✗ rejected, as intended
error, line 1unsolved goals
p q : Prop
hq : q
⊢ p ∨ q
3. What tactics build: Expr
Every term is an Expr, a tree with twelve kinds of node. The ones you will see below:
const Nat a declared constant (with universe levels, e.g. Eq.{1})
app a function applied to arguments; the first child is the function
lam x / forallE x fun x => ... / ∀ x, ... (children: type, body)
bvar 0 the variable bound by the nearest enclosing lam/forallE
fvar n a hypothesis n from the local context
sort 0 Prop (sort 1 is Type)
lit 2 a raw number literal#expr_tree t, from the course file, prints the Expr of a term with one node per line.
(Lean stores f a b as app (app f a) b; the printer shows the whole application as one
app node with the function first.) Start with 2 + 2 = 4:
#expr_tree 2 + 2 = 4✓ Lean accepted this
app
const Eq.{1}
const Nat
app
const HAdd.hAdd.{0, 0, 0}
const Nat
const Nat
const Nat
app
const instHAdd.{0}
const Nat
const instAddNat
app
const OfNat.ofNat.{0}
const Nat
lit 2
app
const instOfNatNat
lit 2
app
const OfNat.ofNat.{0}
const Nat
lit 2
app
const instOfNatNat
lit 2
app
const OfNat.ofNat.{0}
const Nat
lit 4
app
const instOfNatNat
lit 4
Five symbols on the screen, thirty-three lines of tree. Eq gets the type Nat as an
extra argument; + is HAdd.hAdd with three types and an instance argument saying which
addition to use; and each numeral is OfNat.ofNat applied to a type, a raw literal and
another instance. The elaborator inserted all of that. Notebook 1’s term trees hide these
arguments; the kernel sees every one.
Bound variables have no names in the term, only distances. In the identity function on
proofs below, both leaves are bvar 0, yet they point to different binders: under lam p,
the type of h is the nearest bound variable, p; in the body, the nearest is h itself.
#expr_tree fun (p : Prop) (h : p) => h✓ Lean accepted this
lam p
type: sort 0
body: lam h
type: bvar 0
body: bvar 0
Inside a proof, show_expr prints the current goal the same way. Watch the variable n
change kind when intro moves it into the context: before, it is bvar 0 under a
forallE; after, it is fvar n, a hypothesis.
example : ∀ n : Nat, n + 0 = n := by
show_expr
intro n
show_expr
rfl✓ Lean accepted this
forallE n
type: const Nat
body: app
const Eq.{1}
const Nat
app
const HAdd.hAdd.{0, 0, 0}
const Nat
const Nat
const Nat
app
const instHAdd.{0}
const Nat
const instAddNat
bvar 0
app
const OfNat.ofNat.{0}
const Nat
lit 0
app
const instOfNatNat
lit 0
bvar 0
app
const Eq.{1}
const Nat
app
const HAdd.hAdd.{0, 0, 0}
const Nat
const Nat
const Nat
app
const instHAdd.{0}
const Nat
const instAddNat
fvar n
app
const OfNat.ofNat.{0}
const Nat
lit 0
app
const instOfNatNat
lit 0
fvar n
4. Break a tactic on purpose
Here is an assumption tactic with a bug. It assigns the most recent hypothesis to the goal
without checking that the types match. MVarId.assign does not check either, so nothing
stops it while the tactic runs.
elab "bad_assumption" : tactic => do
let g ← getMainGoal
match (← getLCtx).lastDecl with
| some d => g.assign d.toExpr; replaceMainGoal [] -- no type check
| none => throwError "no hypotheses"✓ Lean accepted this (no messages)
Use it on a goal it cannot honestly prove. The tactic finishes, the elaborator accepts its work, and then the finished term reaches the kernel:
This cell is meant to fail:
theorem oops (p q : Prop) (hp : p) : q := by
bad_assumption✗ rejected, as intended
error, line 1(kernel) declaration type mismatch, 'oops' has type
∀ (p q : Prop), p → p
but it is expected to have type
∀ (p q : Prop), p → q
The error starts with (kernel): it was the kernel, re-checking the whole term, that found
a proof of p posing as a proof of q. The library’s my_assumption does the same job
correctly, by asking isDefEq before it assigns anything:
theorem honest (p q : Prop) (_hp : p) (hq : q) : q := by
my_assumption
#print axioms honest✓ Lean accepted this
'honest' does not depend on any axioms
The kernel cannot catch everything. A tactic may simply use sorry, and then there is no
wrong term to reject: the term contains an explicit gap. Lean accepts such a proof with a
warning, so the gold box below is not a success, and #print axioms names the gap as
sorryAx. This is why an audit always ends with #print axioms.
elab "cheat" : tactic => do
evalTactic (← `(tactic| sorry))
theorem fake (p : Prop) : p := by cheat
#print axioms fake◐ accepted with sorry: goals left open
'fake' depends on axioms: [sorryAx]
goal at line 4p : Prop
⊢ p
5. The simp set
simp rewrites with every lemma tagged @[simp]. Here is a recursive function with its two
defining equations tagged, and a lemma about appending lists proved by induction with simp:
def total : List Nat → Nat
| [] => 0
| x :: xs => x + total xs
@[simp] theorem total_nil : total [] = 0 := rfl
@[simp] theorem total_cons (x : Nat) (xs : List Nat) :
total (x :: xs) = x + total xs := rfl
theorem total_append (xs ys : List Nat) :
total (xs ++ ys) = total xs + total ys := by
induction xs with
| nil => simp
| cons x xs ih => simp [ih, Nat.add_assoc]✓ Lean accepted this (no messages)
total_append is not tagged, so simp cannot use it yet, and nothing else in the simp set
fits total (xs ++ [a]):
This cell is meant to fail:
example (xs : List Nat) (a : Nat) : total (xs ++ [a]) = total xs + a := by
simp✗ rejected, as intended
error, line 2`simp` made no progress
Tag it, and ask simp? to report which lemmas it used. The answer is a simp only call you
can paste in place of simp?; it is faster, and it does not change when someone adds a new
simp lemma to the library.
attribute [simp] total_append
example (xs : List Nat) (a : Nat) : total (xs ++ [a]) = total xs + a := by
simp?✓ Lean accepted this
Try this: [apply] simp only [total_append, total_cons, total_nil, Nat.add_zero, Nat.add_left_cancel_iff]
The list has our three lemmas and two from core Lean, Nat.add_zero and
Nat.add_left_cancel_iff, which finish off the arithmetic.
Try this
- Give
stepa case for∨. Why doesfirst | left | rightfail onq → p ∨ q, whilefirst | (left; assumption) | (right; assumption)succeeds? (firstkeeps the first tactic that runs, not the first that leads to a proof.)- Write
my_contradiction: find a hypothesis whose type isFalseand close the goal withFalse.elim. Test it on a goal with no such hypothesis and read your own error message.- Run
#expr_tree fun (n : Nat) => n + 1and#expr_tree ∀ n : Nat, n + 1 > n. Which parts of the two trees are the same?- Fix
bad_assumptionby checking the type withisDefEqbeforeassign, and confirm thatoopsnow fails inside your tactic, with your own message, before the kernel ever sees a term.