Every tactic you have used so far, from intro to simp to omega, is a program. Most of
them are written in Lean itself: Lean 4 is implemented largely in Lean, so its parser, its
elaborator and its tactic framework are ordinary Lean code that you can read, and the same
interfaces are open to you. A file can add a new tactic in three lines and use it on the next
line. That raises two questions. How do you write one? And if anyone can write a tactic, and
tactics can be wrong, why should you believe a proof that a tactic found?
This lecture answers both. It follows a line of Lean from text to checked term, and shows the
three places where you can plug in your own code: new syntax, macros that rewrite syntax, and
elaborators that build terms. It then looks at the data structure Expr that every tactic
ultimately produces, sorts the automation you have met into decision procedures and search
procedures, and ends with the trust story: a buggy tactic can fail, or can produce a wrong
term, and the kernel still checks the term.
Notebook and cheatsheet
Notebook 11: Write a tactic builds macros and elaborators step by step, prints the
Exprof real goals, and breaks a tactic on purpose. Cheatsheet: Writing your own tactic, simp and simp lemmas, exact?, apply?, aesop, grind, The elaborator.
From text to a checked term
Definition 11.1 (Metaprogram and tactic).A metaprogram is a program that reads or builds Lean’s own syntax and terms. A tactic is a metaprogram that runs while a proof is being elaborated: it receives a list of open goals and must close them, or replace them with new ones, by writing parts of the proof term.
Lean processes a declaration in three stages. The parser turns text into Syntax, a tree of
tokens that records what you wrote and nothing more. The elaborator turns Syntax into an
Expr, the term itself: it fills in implicit arguments, finds type-class instances, inserts
coercions, and runs the tactic blocks that follow by. Along the way it expands macros,
rules that rewrite one piece of syntax into another; expansion happens on demand, whenever the
elaborator meets syntax that a macro handles. Finally the kernel type-checks the finished
Expr and, if it passes, adds the declaration to the environment.
Each stage can be extended by an ordinary Lean file except the last, as the figure shows. A tactic of your own (Definition 11.1) is either a macro, which rewrites itself into tactics that already exist, or an elaborator written in Lean’s metaprogramming API.
The bottom row is the point of the whole design. Everything left of the kernel is allowed to be clever and wrong; the kernel is small and fixed, and with the axioms and the statement it is all you must trust. The last section of this lecture shows that boundary at work.
Macros: new syntax by rewriting
The simplest extension is notation, which teaches the parser a new form and says what it
abbreviates. Here is addition on a 12-hour clock:
-- Lean: the metaprogramming API (Syntax, Expr, MetaM, TacticM).
-- Mathlib: used only for norm_num and aesop near the end.
import Lean
import Mathlib
notation:65 a " +₁₂ " b => (a + b) % 12
#eval 9 +₁₂ 5
#check fun (a b : Nat) => a +₁₂ b#eval prints 2, and #check shows that the notation has already disappeared by the time
Lean reports a type: fun a b ↦ (a + b) % 12 : ℕ → ℕ → ℕ. (Mathlib, imported above, prints
Nat as ℕ.) The 65 is the precedence
of the whole notation, the same as +, so a * b +₁₂ c parses as (a * b) +₁₂ c. The
arguments a and b carry no precedence of their own, so the right one takes as much as it
can: a +₁₂ b + c parses as a +₁₂ (b + c). To make it behave exactly like +, give them
precedences too: notation:65 a:65 " +₁₂ " b:66 => (a + b) % 12.
Definition 11.2 (Macro).A macro is a function from
SyntaxtoSyntax, run by the elaborator before it elaborates the result. Lean’s macros are hygienic: a name introduced by a macro cannot accidentally capture, or be captured by, a name the user wrote.
A tactic macro (Definition 11.2) packages a combination of existing tactics under a new name. The
right-hand side is a syntax quotation `(tactic| …), which builds the syntax of a tactic
from text. This one tries three tactics in turn and keeps the first that closes the goal:
macro "my_trivial" : tactic =>
`(tactic| first | rfl | assumption | simp)
example : 2 + 2 = 4 := by my_trivial -- rfl
example (p : Prop) (hp : p) : p := by my_trivial -- assumption
example (xs : List Nat) : xs ++ [] = xs := by my_trivial -- simpA macro knows nothing about the goal. It is a rewrite of syntax, and its behaviour is whatever the expanded tactics do. Here all three fail:
example (p q : Prop) (hp : p) (hq : q) : p ∧ q := by my_trivialLean reports only the last failure, simp made no progress, because first keeps the error
of its last alternative. (simp does not use hypotheses unless you ask, with simp [*], and
none of the three tactics splits a conjunction.)
A macro written with macro has exactly one rule. The two-step form, syntax followed by
macro_rules, declares the syntax once and lets anyone add rules later, in any file. When
several rules match, Lean tries the most recent first and falls back to older ones if the
expanded tactic fails. Core Lean’s own trivial is built this way: the
source of Init/Tactics.lean
declares syntax "trivial" : tactic and then adds six macro_rules, for assumption, rfl,
contradiction, decide, True.intro, and And.intro followed by trivial again. Our own
version:
syntax "easy" : tactic
macro_rules | `(tactic| easy) => `(tactic| rfl)
macro_rules | `(tactic| easy) => `(tactic| assumption)
macro_rules | `(tactic| easy) => `(tactic| omega)
macro_rules | `(tactic| easy) => `(tactic| apply And.intro <;> easy)
example (a b : Nat) (p : Prop) (hp : p) : p ∧ a + b = b + a := by easyThe last rule is recursive: it splits the conjunction and calls easy on each half, where the
assumption rule closes p and the omega rule closes the arithmetic.
Elaborators and the four monads
A macro cannot look at the goal. To do that you write an elaborator, a function in Lean’s
metaprogramming API. That code runs in a monad. For our purposes a monad is a context in which
a computation runs, together with what the computation may do there: read and change some
state, fail with an error, or log a message. A value of type m α is a computation that, run
in context m, returns an α, and the do notation strings such computations together. Lean
stacks four of them, each adding to the one below:
| monad | adds | typical operations |
|---|---|---|
CoreM | the environment (every declaration), options, messages | getEnv, logInfo |
MetaM | the metavariable context and the local context | inferType, isDefEq, whnf |
TermElabM | elaboration of Syntax into Expr | elabTerm |
TacticM | the list of open goals | getMainGoal, replaceMainGoal, evalTactic |
Code in a higher monad can call anything from a lower one, so a tactic can ask MetaM for the
type of an expression or whether two expressions are definitionally equal. The key notion that
MetaM adds is the metavariable.
Definition 11.3 (Goal).A metavariable is a named hole
?g : Tin a term under construction, with its own local context of hypotheses. A goal is a metavariable that a proof still has to fill. A tactic closes a goal by assigning its metavariable a term of type, which may itself contain new metavariables, the new goals.
This is the precise version of the cheatsheet picture in which each tactic fills one hole. The
first elaborator only looks. getMainGoal returns the first open goal (Definition 11.3), and
getType its statement:
open Lean Elab Tactic Meta
elab "show_goal" : tactic => do
let g ← getMainGoal -- the first open goal: a metavariable
let t ← g.getType -- its type: what is left to prove
logInfo m!"goal: {t}"
example (n : Nat) : n + 0 = n := by
show_goal
rflLean prints goal: n + 0 = n, and rfl then closes the goal. With Mathlib loaded you also
get a warning from its unused tactic linter, show_goal does nothing, which is true: the
tactic only prints. The second elaborator closes
goals. It walks through the hypotheses, asks isDefEq whether a hypothesis has the goal’s type,
and if so assigns the goal:
elab "my_assumption" : tactic => do
let g ← getMainGoal
g.withContext do
let goal ← g.getType
for d in ← getLCtx do
if d.isImplementationDetail then continue
if ← isDefEq d.type goal then
g.assign d.toExpr -- fill the hole with the hypothesis
replaceMainGoal [] -- this goal is done
return
throwError "my_assumption: no hypothesis has type{indentExpr goal}"
theorem pick (p q : Prop) (_hp : p) (hq : q) : q := by
my_assumption
#print pick#print shows the term the tactic wrote: fun p q _hp hq ↦ hq. (The underscore in _hp
tells Lean’s linter that the hypothesis is unused on purpose.) g.withContext makes the
goal’s hypotheses visible to getLCtx, and isImplementationDetail skips internal entries
such as the theorem’s own name, used for recursion. When nothing fits, the tactic fails with
the message we chose:
example (p q : Prop) (hp : p) : q := by
my_assumptionLean reports my_assumption: no hypothesis has type, followed by the goal q on its own
line.
Expressions: what every tactic produces
Whatever a tactic does, its output is an Expr. Expr is an inductive type with twelve
constructors, and #print lists them:
#print Lean.Expr| constructor | what it represents |
|---|---|
bvar | a variable bound by an enclosing fun or ∀, by its distance (a de Bruijn index) |
fvar | a free variable: a hypothesis in the local context |
mvar | a metavariable: a hole, such as an open goal |
sort | Prop, Type, Type 1, … (Sort u for a universe level u) |
const | a declared constant such as Nat.add, with universe levels |
app | the application of a function to one argument |
lam, forallE | fun x : A => b and ∀ x : A, B (also A → B) |
letE, lit, mdata, proj | let, number and string literals, annotations, structure fields |
Two design choices stand out. Application takes one argument at a time, so f a b is
app (app f a) b. And bound variables have no names inside the term: bvar 0 means “the
nearest enclosing binder”, bvar 1 the one outside it. The names you see in the infoview are
kept only for printing. A five-line command prints the raw Expr of a term, using Lean’s
repr:
elab "#raw " t:term : command =>
Command.liftTermElabM do
let e ← Term.elabTerm t none
logInfo m!"{repr (← instantiateMVars e)}"
#raw ∀ n : Nat, n = nLean prints:
Lean.Expr.forallE
`n
(Lean.Expr.const `Nat [])
(Lean.Expr.app
(Lean.Expr.app
(Lean.Expr.app (Lean.Expr.const `Eq [Lean.Level.succ (Lean.Level.zero)]) (Lean.Expr.const `Nat []))
(Lean.Expr.bvar 0))
(Lean.Expr.bvar 0))
(Lean.BinderInfo.default)Read it from the outside in. The forallE binds n : Nat; its body applies Eq to three
arguments, of which you wrote only two. The first, Nat, is the implicit type argument that
the elaborator inferred, and Eq carries the universe level 1 because Nat : Type. Both
sides of the equation are bvar 0, the variable bound by the ∀. Notebook 1 draws proof terms
as trees with the implicit arguments hidden
(Notebook 1); this is the same tree with nothing hidden,
and it is what the kernel checks. Even 2 + 2 = 4 is about thirty nodes, because + and the
numerals each carry a type and an instance; Notebook 11 prints it.
Automation: decision procedures and search
The automation you have used falls into two families, and the difference matters when it fails.
Definition 11.4 (Decision procedure and search).A decision procedure for a class of statements always terminates, and either proves the statement or reports that it is false, often with a counterexample. A search procedure explores possible proof steps and may give up on a statement that has a proof.
The simp set. simp rewrites the goal with a database of equations, the simp set, each
used from left to right until nothing more applies. The attribute @[simp], or
attribute [simp] after the fact, adds a lemma to that database. Here a new function and a
lemma about it:
def dbl (n : Nat) : Nat := n + n
theorem dbl_add (a b : Nat) : dbl (a + b) = dbl a + dbl b := by
unfold dbl
omegaAt first simp knows nothing about dbl:
example (a b c : Nat) : dbl (a + b + c) = dbl a + dbl b + dbl c := by
simpIt fails with simp made no progress. After one line it succeeds, and simp? reports the
lemmas it used, so that you can replace it with the faster and more stable simp only:
attribute [simp] dbl_add
example (a b c : Nat) : dbl (a + b + c) = dbl a + dbl b + dbl c := by
simp?Lean answers Try this: simp only [dbl_add, Nat.add_left_cancel_iff]. The second lemma
comes from the simp set that the library already provides; simp? is how you find out which
of its thousands of lemmas a call relied on. A good simp lemma makes the goal simpler: an
equation whose right side is closer to a normal form than its left. A lemma such as
a + b = b + a could be applied forever. Simp recognises such permutation lemmas and uses
one only when the result is smaller in a fixed order on terms, so simp [Nat.add_comm] stops,
but it may leave a sum in an order you did not expect (the cheatsheet card on simp has more).
Decision procedures (Definition 11.4) each cover one theory:
example (x y : Nat) (h : x < y) : 2 * x + 1 < 2 * y := by omega
theorem mod_seven : 1000 % 7 = 6 := by decide
#print axioms mod_seven
theorem xor_twice (x y : BitVec 8) : (x ^^^ y) ^^^ y = x := by bv_decide
#print axioms xor_twice
example : (2 : ℝ) ^ 10 = 1024 := by norm_numomegahandles linear arithmetic overNatandInt. Its documentation is candid: it is “not yet a full decision procedure” (two parts of the omega algorithm, the “dark” and “grey” shadows, are not implemented) but “should be effective on many problems”. Either way it builds an ordinary proof term.decideevaluates aDecidableinstance inside the kernel.#print axioms mod_sevenreports'mod_seven' does not depend on any axioms: the kernel did the arithmetic itself.bv_decideturns a statement about fixed-width bit vectors into a Boolean formula and hands it to an external SAT solver, CaDiCaL, which ships with Lean as a separate program. The solver returns a certificate in the LRAT format, and a checker proved correct in Lean checks it. The checker runs as compiled code, not in the kernel, and#print axiomsshows the price. It reports[propext, Classical.choice, Quot.sound, xor_twice._native.bv_decide.ax_1]. The last entry is an axiom thatbv_decideadded for this one proof, stating that the checker returnedtrue; you trust the compiler that ran it.norm_num(from Mathlib) proves equalities and inequalities between numerical expressions in types such asℤ,ℚandℝ, wheredecidecannot compute, building a proof term step by step.
A decision procedure also says no informatively. A false statement about bit vectors gets a counterexample:
example (x y : BitVec 8) : x + y = x := by bv_decideLean reports The prover found a counterexample, consider the following assignment:
y = 255#8, that is, y would do.
Search procedures try steps and backtrack:
example (a b : Nat) : a + b = b + a := by exact?
example (p q : Prop) (hp : p) (hq : q) : p ∧ (q ∨ False) := by aesop
example (f : Nat → Nat) (a b : Nat) (h : a = b) : f (f a) = f (f b) := by
grindexact?searches the imported library for a lemma whose conclusion fits the goal and prints what it found, here Try this:[apply] exact Nat.add_comm a b. Paste that line in place ofexact?: the search is slow, its result is not.aesop(a package that Mathlib depends on) runs a best-first search over a configurable set of rules: splitting connectives, simp, applying hypotheses and tagged lemmas.grind(core Lean) is modelled on SMT solvers: it collects facts on a shared “whiteboard”, uses congruence closure (froma = bconcludef a = f b), instantiates tagged theorems by matching, splits cases, and runs built-in solvers for linear integer arithmetic and commutative rings.
Every one of these, decision procedure or search, ends the same way: with a term, or a certificate checked by a term, that goes to the kernel.
The trust story
Here is a tactic with a bug. It is meant to be an assumption tactic, but it assigns the most recent hypothesis without checking its type:
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"
theorem oops (p q : Prop) (hp : p) : q := by
bad_assumptionThe tactic runs without complaint, and the elaborator, which trusts tactics, accepts the
result: MVarId.assign does not check types. Then the finished term goes to the kernel, which
rejects it:
(kernel) declaration type mismatch, 'oops' has type
∀ (p q : Prop), p → p
but it is expected to have type
∀ (p q : Prop), p → qThe tactic built fun p q hp ↦ hp, a proof of p, and claimed it proved q. The kernel
checked the whole term from scratch and refused. No tactic can get a wrong term past this
check.
A tactic can still avoid the check. It is Lean code, and Lean code can add a declaration
with the kernel switched off, through the option debug.skipKernelTC. This tactic does that on
purpose: it declares an auxiliary theorem with the goal as its type and True.intro as its
proof, unchecked, and closes the goal with it.
elab "cheat" : tactic => do
let g ← getMainGoal
let t ← instantiateMVars (← g.getType)
let some d ← Term.getDeclName? | throwError "no declaration"
let aux := d ++ `cheat_aux
withOptions (fun o => debug.skipKernelTC.set o true) do
addDecl (.thmDecl { name := aux, levelParams := [], type := t,
value := mkConst ``True.intro })
g.assign (mkConst aux)
replaceMainGoal []
theorem bogus : False := by cheat
#print axioms bogusThere is no error and no warning, and #print axioms reports that bogus does not depend on
any axioms. The editor and #print axioms both see a clean proof of False. What catches it is
leanchecker (Lecture 2), which replays every declaration of the compiled files through the
kernel. On this code, compiled to CheatDemo.olean with the course toolchain, it reports:
leanchecker found a problem in CheatDemo
uncaught exception: while replaying declaration 'bogus.cheat_aux':
(kernel) declaration type mismatch, 'bogus.cheat_aux' has type
True
but it is expected to have type
FalseRemark 11.1 (What the kernel cannot catch).The kernel’s check covers the term, not everything around it. A tactic can rely on a
sorry, which Lean flags with a warning and#print axiomslists assorryAx. It can rely on an axiom, asbv_decideandnative_decidedo on purpose;#print axiomslists those too. It can also skip the kernel: code run during elaboration may add a declaration unchecked, ascheatdid. Neither the editor nor#print axiomsshows this;leancheckerdoes. And no tactic, buggy or not, can make a statement mean what you intended: that is the statement-fidelity problem of Lecture 5.
So the audit of a proof never asks how its tactics work. It asks four questions, from the
remark on the kernel’s limits (Remark 11.1): does it compile, what does #print axioms
report, does leanchecker (or lake comparator) accept the compiled files, and is the
statement right. This is the de Bruijn criterion of
Lecture 1 in practice, and it is what makes it safe to let
anyone, including an AI model, write proofs with tactics nobody has reviewed, provided the last two checks are run. Lecture 12 builds
on exactly that.
Try this
- Add a rule
macro_rules | `(tactic| easy) => `(tactic| simp_all)and find a goal that only the new rule closes. Then find one where adding it makeseasyslower. - Write
my_contradiction: look for a hypothesis whose type isFalseand close the goal withFalse.elim. Test it on a goal with no such hypothesis and check the error. - In Notebook 11, print the
Exproffun (p : Prop) (h : p) => hand explain why both of itsbvars arebvar 0, yet refer to different binders. - Run
#print axiomson a theorem proved bynative_decideand compare withdecide.
Readings
- Arthur Paulino et al., Metaprogramming in Lean 4.
The standard tutorial:
Expr,MetaM, syntax, macros, elaboration and tactics, in that order. - The Lean reference manual, Notations and Macros
and the
grindtactic. - Sebastian Ullrich and Leonardo de Moura, Beyond Notations: Hygienic Macro Expansion for Theorem Proving Languages, 2020. The design of Lean 4’s macro system.
- Leonardo de Moura and Sebastian Ullrich, The Lean 4 Theorem Prover and Programming Language, CADE-28, 2021. Why Lean 4 is written in Lean.
- Jannis Limperg and Asta Halkjær From, Aesop: White-Box Best-First Proof Search for Lean, CPP 2023.
- The
bv_decidepaper (OOPSLA 2025), paper page: bit-blasting with a verified LRAT checker. - David Thrane Christiansen, Functional Programming in Lean, the chapters on monads, if the monad table above went by too fast.