Everyone is talking about interactive theorem provers like Lean 4 and Coq right now. From formalizing frontier mathematics to verifying production code, the hype on social media is hard to miss. However, most people still treat these tools like magic boxes , and few actually know what happens under the hood when Lean 4 “proves” a theorem.
This post answers that question by implementing a toy Lean 4-style theorem prover from scratch. Walking through the core mechanics step by step will give you a deeper, more confident understanding of what modern theorem provers actually do, and why we can trust them.
The full source code written in Rust is available at https://github.com/h5i-dev/MiniLean4.
The detailed and interactive e-Book about MiniLean is now available at https://learn.h5i.dev/
1. Propositions are types
At its core, a theorem prover has one job: deciding whether a proof is valid. Because a computer cannot directly verify a proof written in plain English, we need a formal bridge between mathematics and code. That bridge is the Curry–Howard correspondence, often summarized by a simple slogan: propositions are types, and proofs are programs.
In programming terms, think of a mathematical proposition as a type signature, and its proof as a program (or value) that satisfies that signature. If we can write a well-typed expression tof type A(written t: A), then the proposition Ais proven true. If no such program can be constructed, the proposition cannot be proven.
Consider logical implication: A → B( Aimplies B). To prove A → Bmathematically, we assume Ais true and use it to derive B. In programming, this is simply a function that takes an argument of type Aand returns a result of type B. If you can implement that function, you have proven the implication.
The same idea extends naturally to universal quantification (“for all x…”). Suppose we want to prove that “for every xof type A, the property B(x)holds. Just like implication, we prove this by writing a function that takes any input x: Aand returns a proof of B(x).
Notice the twist here: the return type B(x)actually changes depending on the value of the input x. In standard programming languages, return types can’t depend on runtime values, so we need a dependent function type (or Π-type), written as:
Press enter or click to view image in full size
For example, let’s express the statement “every proposition implies itself.” In Lean’s type theory, the universe of all propositions is written as Sort 0(or Prop). Using a dependent type, we can write this statement as:
Press enter or click to view image in full size
To prove it, we write a function that takes any proposition Pand returns the identity proof for that specific P:
Press enter or click to view image in full size
This brings us to the central insight behind modern theorem provers: proving a theorem is just writing a program of the right type, and verifying a proof is just type-checking that program. A Lean-style kernel doesn’t need to “understand” mathematical truth , and it only needs to be a type checker.
2. Syntax
To build our minimal theorem prover, we don’t need a massive programming language. In fact, our entire core calculus consists of just five kinds of terms (we’ll add one more later):
Press enter or click to view image in full size
Here, uis a natural number representing a universe level, and xis a variable name. Let’s break down what each construct does:
Sort 𝑢: A universe containing types.𝑥: A variable.Π(𝑥:𝐴). 𝐵: A Π-type (dependent function type), whose result type 𝐵 may depend on the input 𝑥.𝜆(𝑥:𝐴). 𝑡: A 𝜆-abstraction, i.e. a function that takes 𝑥 : 𝐴 and returns 𝑡.𝑡 𝑠: Function application.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Term {
Sort(u64),
Var(String),
Pi(String, Box<Term>, Box<Term>),
Lam(String, Box<Term>, Box<Term>),
App(Box<Term>, Box<Term>),
}Everything is a Term
Notice that types and expressions share the exact same syntax. There is no separate grammar for “types” versus “values” or “proofs” versus “propositions”. Whether a given term Ais actually a valid type is decided dynamically by the type checker. For instance, our earlier theorem (“every proposition implies itself”) and its proof are both constructed from the exact same building blocks:
Press enter or click to view image in full size
Associativity and Carring
As in functional languages like Haskell, Lean, and OCaml, function application associates to the left, while arrows associate to the right:
f a bmeans(f a) bA -> B -> CmeansA -> (B -> C)
For example, 𝜆(𝑎:𝐴). 𝜆(𝑏:𝐵). 𝑎 has type 𝐴 → 𝐵 → 𝐴, and applied to 𝑥 : 𝐴 and 𝑦 : 𝐵 it is written (𝜆(𝑎:𝐴). 𝜆(𝑏:𝐵). 𝑎) 𝑥 𝑦, that is, ( (𝜆(𝑎:𝐴). 𝜆(𝑏:𝐵). 𝑎) 𝑥) 𝑦.
3. Typing Rules as Logical Inference
Now that we have our syntax, how does the kernel verify a proof? It checks types under a context Γ, which is an ordered list of assumptions:
Press enter or click to view image in full size
It records the type of each variable in scope, and we write dom(Γ) for the set {𝑥_1, . . . , 𝑥_𝑛}. Since C-Ext below forbids repeated names, Γ can be used like a dictionary from names to types, and T-Var is simply a lookup. Unlike a plain dictionary, however, the order matters: 𝐴_𝑖 may mention 𝑥_1, . . . , 𝑥_𝑖−1, as in 𝑃 : Sort 0, ℎ : 𝑃. We use two judgments:
⊢ Γ ok: the contextΓis well formed.Γ ⊢ 𝑡 : 𝐴under the assumptions inΓ, the term𝑡has type𝐴.
Press enter or click to view image in full size
Here,
A
---
Bmeans that A inducesB . B[x -> a] also denotes substituting x in B with a , and 𝐴 ≡ B denotes that the term A and B are equivalent (we’ll explain the definition of equivalence, later).
Seeing Curry–Howard in Action
To see just how directly these typing rules mirror formal logic, consider second-order propositional logic, where formulas are built from proposition variables P, 𝑄, . . . , implication (𝜑 → 𝜓 ), and universal quantification over propositions (∀𝑃 . 𝜑).
If we translate each logical formula 𝜑to its corresponding type 𝜑*, mapping 𝜑 → 𝜓to 𝜑* → 𝜓* and ∀𝑃 . 𝜑to Π(P : Sort 0). 𝜑* , then the standard rules of natural deduction match our kernel’s typing rules line for line (omitting well-formedness premises for readability):
Press enter or click to view image in full size
Look closely at the two columns above: if you erase the program terms (h, 𝜆, t, f, a) from the right-hand side, you get the exact rules of logical deduction on the left! Every step of a logical proof corresponds to constructing a syntax tree node in our programming language.
What Do We Need to Implement This?
At first glance, turning these rules into a type-checking function seems almost trivial. However, there are some subtle details are hiding inside the rules above:
T-Apprelies on substitution. How do we substitute terms inside dependent types without accidentally capturing bound variable names?T-Convrelies on equality (𝐴 ≡ B): How do we evaluate terms and decide whether two different-looking types compute to the same normal form? For example, how does the kernel know thatΠ(P:Sort 0). P -> PandΠ(Q:Sort 0). Q-> Qare the exact same type?
Section 5 in this article will cover those topics, while we can trete them as black box functions at this point.
What About Falsehood? (Consistency)
Translating every logical proof into a well-typed term guarantees that our type checker can verify any valid deduction. For the kernel to be trustworthy, however, we also need the opposite guarantee: it must never accept a term for a false proposition. In logic, falsehood (⊥) can be defined as ∀𝑃 . P, the absurd claim that “every proposition holds”. In our type theory, this translates to the type:
Press enter or click to view image in full size
A type system in which no closed term inhabits Π(P:Sort 0). P is called consistent. Thus, the entire trustworthiness of our theorem prover boils down to a single property: ensuring that no closed program of type Π(P:Sort 0). Pcan ever pass the type checker.
4. Type Checker
Now we have some intuitive understanding of building blocks to create the type checker.
If you look back at our typing rules, you’ll notice a catch: the first five rules (T-Sort, T-Var, T-Pi, T-Lam, T-App) are triggered by the exact syntax of the expression we are looking at. The sixth rule, T-Conv (type conversion), has no syntax trigger, and it says we are allowed to simplify a type via computation at any time. If you are writing a program, how does the code know when to run T-Conv?
Press enter or click to view image in full size
The Solution: infer vs. check The trick is that we never run T-Conv randomly. Instead, we split our type checker into two simple functions:
infer(ctx, expr): Takes an expression and computes (infers) its type from the bottom up.check(ctx, expr, expected_type): Infers the type ofexpr, and then checks if it equalsexpected_typeby normalizing both and comparing them based on alpha-equivalence (will explain what it is later).
In other words, T-Conv is no longer a separate step we have to guess when to apply, and it happens automatically inside check !
4.1 The Type Checker in 35 Lines of Code
Let’s look at the type checker first. Notice how the five match branches in infer map 1-to-1 to our five syntax constructs (Sort, Var, Pi, Lam, App):
impl Kernel {
/// Infers the type of `t` and requires it to be a universe `Sort u`.
/// Returns `u`.
pub fn infer_sort(&self, ctx: &Context, t: &Term) -> Result<u64> {
match self.whnf(&self.infer(ctx, t)?)? {
Term::Sort(u) => Ok(u),
other => Err(format!("expected a type, got {other:?}")),
}
} /// `Gamma |- t : ?`
pub fn infer(&self, ctx: &Context, t: &Term) -> Result<Term> {
match t {
// T-Sort
Term::Sort(u) => Ok(Term::Sort(u.checked_add(1).ok_or("universe overflow")?)),
// T-Var
Term::Var(x) => ctx
.iter()
.rev()
.find(|(name, _)| name == x)
.map(|(_, ty)| ty.clone())
.ok_or_else(|| format!("unbound local: {x}")),
// T-Pi: Sort 0 is impredicative.
Term::Pi(x, domain, body) => {
let domain_level = self.infer_sort(ctx, domain)?;
let (x, body) = rename_binder_if_needed(ctx, x, body);
let mut extended = ctx.clone();
extended.push((x, (**domain).clone()));
let body_level = self.infer_sort(&extended, &body)?;
Ok(Term::Sort(if body_level == 0 {
0
} else {
domain_level.max(body_level)
}))
}
// T-Lam
Term::Lam(x, domain, body) => {
self.infer_sort(ctx, domain)?;
let (x, body) = rename_binder_if_needed(ctx, x, body);
let mut extended = ctx.clone();
extended.push((x.clone(), (**domain).clone()));
let body_type = self.infer(&extended, &body)?;
Ok(Term::Pi(x, domain.clone(), Box::new(body_type)))
}
// T-App
Term::App(f, a) => match self.whnf(&self.infer(ctx, f)?)? {
Term::Pi(x, domain, codomain) => {
self.check(ctx, a, &domain)?;
Ok(subst(&codomain, &x, a))
}
ty => Err(format!("application of non-function: {ty:?}")),
},
}
}
/// `Gamma |- t : expected`, using T-Conv to compare the inferred type.
pub fn check(&self, ctx: &Context, t: &Term, expected: &Term) -> Result<()> {
self.infer_sort(ctx, expected)?;
let actual = self.infer(ctx, t)?;
if self.is_def_eq(&actual, expected)? {
Ok(())
} else {
Err(format!(
"type mismatch: actual {actual:?}, expected {expected:?}"
))
}
}
}
4.2 Watching the Kernel in Action
To verify a theorem TheoremType with a proof proof_term, the user calls check(empty_ctx, proof_term, TheoremType). Let's see how this handles three quick scenarios.
For example, suppose we want to verify our proof of “every proposition implies itself”:
- Theorem (expected type):
Π(𝑃:Sort 0). 𝑃 → 𝑃(which is shorthand forΠ(𝑃:Sort 0). Π (_: 𝑃. 𝑃)) - Proof (expression):
𝜆(𝑃:Sort 0). 𝜆(ℎ:𝑃). ℎ
When check runs infer on our proof:
- The outer
Lamputs𝑃:Sort 0intoctx. - The inner
Lamputsℎ:𝑃intoctx. - The inner body
Var(h)looks upℎinctxand returns its type:𝑃. - Wrapping those results back up in
Πtypes,inferreturnsΠ(𝑃:Sort 0). Π (h: 𝑃. 𝑃). - Finally,
checkcomparesΠ(𝑃:Sort 0). Π (h: 𝑃. 𝑃)withΠ(𝑃:Sort 0). Π (_: 𝑃. 𝑃)usingalpha_eq. They match, so the proof is accepted!
5. Inductive Types
So far, our theorem prover can verify proofs involving functions, implications, and universal quantification. But there is one obvious limitation: we cannot even define natural numbers yet!
In Lean 4, we can introduce new types using inductive declarations:
inductive Nat where
| zero : Nat
| succ : Nat → NatThis declaration tells Lean that every natural number is constructed in one of two ways:
zerorepresents zero.succ nrepresents the successor of a natural numbern.
For example, the number two is represented as succ (succ zero) .
But there is a deeper question: How does the kernel know that mathematical induction is valid for this newly defined type? We never explicitly defined an induction principle. We only declared two constructors!
The answer is that the kernel automatically generates a recursor from the constructors. A recursor provides both the induction principle for proving properties and the computational rules for recursively processing values.
5.1 From Constructors to Mathematical Induction
Consider our Nat declaration again:
Nat.zero : Nat
Nat.succ : Nat → NatSuppose we want to prove some property P n for every natural number n.
Since every natural number is built using zero and succ, we only need to handle two cases.
(Case 1: zero) We must prove that the property holds for zero:
base : P zero(Case 2: succ) Suppose the property already holds for some natural number n. We need to show that it also holds for succ n:
step : (n : Nat) → P n → P (succ n)Notice that P n appears as an argument to step. This is the induction hypothesis.
Once we have both base and step, we can conclude that P n holds for any natural number n. In other words, we have derived the mathematical induction principle:
Nat.rec :
(P : Nat → Prop) →
P zero →
((n : Nat) → P n → P (succ n)) →
(n : Nat) → P nThe remarkable part is that the kernel can generate this type automatically, using nothing more than the two constructor declarations. For each constructor, the kernel creates one case. Whenever a constructor contains a recursive field, the kernel adds an induction hypothesis for that field.
- For
zero, there are no recursive fields, so we only needP zero. - For
succ, there is one recursive fieldn : Nat, so we needP nto constructP (succ n).
5.2 Mathematical Induction and Recursive Programming Are the Same Mechanism
There is something even more interesting about this construction: mathematical induction and recursive programming are two uses of exactly the same recursor.
To see why, let’s generalize the previous type. Instead of requiring P n to be a proposition, let M n be any type belonging to Sort u:
Nat.rec :
(M : Nat → Sort u) →
M zero →
((n : Nat) → M n → M (succ n)) →
(n : Nat) → M nThe only difference is that the result type can now live in different universes.
(Case 1: Mathematical induction (u = 0)): When u = 0, we have:
M : Nat → Sort 0Since Sort 0 is Prop, M n is a proposition. Therefore, the recursor constructs proofs:
Nat.rec :
(P : Nat → Prop) →
P zero →
((n : Nat) → P n → P (succ n)) →
(n : Nat) → P nThis is precisely mathematical induction.
(Case 2: Recursive programming (u = 1)): Now suppose we want to implement a recursive function that doubles a natural number. Instead of a proposition, choose:
M : Nat → Sort 1
M n = NatHere, Nat is an ordinary data type living in Sort 1, not a proposition. Substituting this motive into the same recursor gives:
Nat.rec :
Nat →
((n : Nat) → Nat → Nat) →
Nat → NatThe base case must return a Nat, and the successor case receives the previously computed result. We can now implement doubling:
def double (n : Nat) : Nat :=
Nat.rec
(motive := fun _ => Nat)
0
(fun _ result => Nat.succ (Nat.succ result))
nIts computation follows these equations:
double zero ↦ zero
double (succ n) ↦ succ (succ (double n))For example, the following result is 4:
double (succ (succ zero))
↦ succ (succ (double (succ zero)))
↦ succ (succ (succ (succ (double zero))))
↦ succ (succ (succ (succ zero)))Notice that we did not introduce any new recursion mechanism. We simply used Nat.rec with a different motive. When M n : Sort 0, the result is a proof. When M n : Sort 1, the result is ordinary data. The kernel uses the same recursor, with different result types!!
Strictly speaking, this works whenever elimination into the chosen universe is permitted. For
Nat, both propositional and computational elimination are allowed.
5.3 Generalizing Recursors: A Tree with Three Constructors
Natural numbers have only two constructors, and only one of them is recursive. Let’s consider a slightly more interesting inductive type:
inductive Tree where
| leaf : Tree
| node : Tree → Tree
| branch : Tree → Tree → TreeThere are three ways to construct a tree:
Tree.leaf : Tree
Tree.node : Tree → Tree
Tree.branch : Tree → Tree → TreeFor example:
Tree.branch (Tree.node Tree.leaf) Tree.leafThis represents a tree with four constructor occurrences. Now suppose we want to construct some result M t for every tree t, where:
M : Tree → Sort uJust as with Nat, the recursor needs one case for each constructor.
(Case 1: leaf): leaf has no recursive fields, so we only need:
m_leaf : M leaf(Case 2: node): node takes one subtree t : Tree. The recursor therefore provides an induction hypothesis M t:
m_node :
(t : Tree) →
M t →
M (node t)(Case 3: branch): branch takes two subtrees, l and r. Consequently, the recursor provides two induction hypotheses:
m_branch :
(l : Tree) →
(r : Tree) →
M l →
M r →
M (branch l r)Putting these cases together, the kernel generates:
Tree.rec :
(M : Tree → Sort u) →
M leaf →
((t : Tree) → M t → M (node t)) →
((l : Tree) → (r : Tree) →
M l → M r → M (branch l r)) →
(t : Tree) → M tCompare this with Nat.rec. The mechanism is identical! The only differences are the number of constructors and the number of recursive fields in each constructor.
How Does MiniLean4 Generate These Types?
In our implementation, inductive declarations are represented by Rust structures:
pub struct InductiveSpec {
pub name: String,
pub params: Context,
pub indices: Context,
pub universe_level: u64,
pub constructors: Vec<ConstructorSpec>,
}pub struct ConstructorSpec {
pub name: String,
pub fields: Context,
pub result_indices: Vec<Term>,
}
For Tree, both params and indices are empty, and we will explain why we need them later. The three constructors have zero, one, and two fields, respectively.
The recursor generator examines each constructor and adds induction hypotheses for its recursive fields. Conceptually, the code looks like this:
for constructor in &inductive.constructors {
let mut binders = constructor.fields.clone(); for recursive_field in &constructor.recursive_fields {
let ih_type = /* motive applied to recursive field */;
binders.push(("__ih".into(), ih_type));
}
let goa
l = /* motive applied to constructor result */;
let minor_premise = telescope(&binders, goal);
}
Here, telescope builds nested dependent function types from a list of typed arguments. For branch, the kernel starts with:
l : Tree
r : TreeBecause both fields are recursive, it adds:
ih_l : M l
ih_r : M rFinally, it produces:
(l : Tree) →
(r : Tree) →
M l →
M r →
M (branch l r)This is exactly the branch case of Tree.rec.
5.4 How Does the Recursor Actually Compute? Iota Reduction
We have generated the type of Tree.rec, but we still need to explain how it computes. Let’s use the recursor to count the number of constructor occurrences in a tree. We want:
size(leaf) = 1
size(node t) = 1 + size(t)
size(branch l r) = 1 + size(l) + size(r)Choose the motive:
M t = NatThe three cases become:
m_leaf = 1
m_node = λ t ih. 1 + ih
m_branch = λ l r ih_l ih_r. 1 + ih_l + ih_rNow consider:
size(branch (node leaf) leaf)How does the kernel evaluate this expression? It inspects the constructor of the tree. Since the constructor is branch, it selects m_branch and recursively processes both subtrees.
More generally, Tree.rec follows three computation rules:
Tree.rec M m_leaf m_node m_branch leaf
↦ m_leafTree.rec M m_leaf m_node m_branch (node t)
↦ m_node t
(Tree.rec M m_leaf m_node m_branch t)
Tree.rec M m_leaf m_node m_branch (branch l r)
↦ m_branch l r
(Tree.rec M m_leaf m_node m_branch l)
(Tree.rec M m_leaf m_node m_branch r)
These are called ι-reduction (iota-reduction) rules. For our example:
size(branch (node leaf) leaf)
↦ 1 + size(node leaf) + size(leaf)
↦ 1 + (1 + size(leaf)) + 1
↦ 1 + (1 + 1) + 1
= 4The kernel does not need a hardcoded implementation of Tree.size. It only needs to know which constructor was used, which case to select, and which recursive fields need to be processed.
5.5 Strict Positivity: Why Some Constructors Are Forbidden
One of the importnat thing about inductive types is that not every constructor type is safe. Consider this declaration:
inductive Bad where
| mk : (Bad → False) → BadAt first glance, it looks similar to our recursive Tree constructors. But there is a crucial difference. Compare:
Tree → Tree -- Allowed
(Bad → False) → Bad -- RejectedIn the first case, the constructor directly receives a value of the inductive type. In the second case, the constructor receives a function that takes the inductive type as an argument.
Why does this matter? Suppose we allowed the second constructor and generated an unrestricted recursor. We could define:
f : Bad → False
f (Bad.mk g) = g (Bad.mk g)Here, g : Bad → False, and Bad.mk g : Bad, so the right-hand side has type False. Now substitute f for g:
f (Bad.mk f)
↦ f (Bad.mk f)
↦ f (Bad.mk f)
↦ ...The computation never terminates, and the unrestricted recursor would allow us to construct a closed term of type False. This would make the logic inconsistent.
To prevent this, inductive declarations must satisfy strict positivity. In our simplified kernel, recursive fields must have one of the following forms:
I
B → I
B₁ → B₂ → I
...Here, I is the inductive type being defined, and none of the argument types B, B₁, B₂, etc. may contain I. For example:
Tree -- Allowed
Nat → Tree -- Allowed
Tree → Nat -- Not a valid recursive field
(Tree → Nat) → Tree -- RejectedWhy is Nat → Tree allowed? Because the function produces a Tree. We can recursively process every tree returned by that function. Suppose a constructor contains:
f : Nat → TreeThen its induction hypothesis has type:
ih : (n : Nat) → M (f n)In contrast, a field of type Tree → Nat consumes trees rather than producing them. It does not provide the recursive subtrees needed by this recursor construction.
5.6 Parameters and Indices: From Lists to Length-Indexed Vectors
Our Nat and Tree examples had no parameters or indices. Let’s now consider a polymorphic list:
inductive List (A : Type) where
| nil : List A
| cons : A → List A → List AHere, A is a parameter. It determines the type of the elements stored in the list. For example:
List Nat
List Boolare different types, but within a particular list, the element type remains fixed.
The constructors have types:
nil : List A
cons : A → List A → List AThe recursor can therefore use the following cases:
m_nil : M nilm_cons :
(a : A) →
(xs : List A) →
M xs →
M (cons a xs)
This is exactly the same mechanism we used for Nat and Tree. But ordinary lists do not encode their lengths in their types. Both an empty list and a list of three natural numbers have type List Nat.
What if we want the length to be part of the type? We can define a length-indexed vector:
inductive Vec (A : Type) : Nat → Type where
| nil : Vec A 0
| cons : (n : Nat) → A → Vec A n → Vec A (Nat.succ n)Now:
Vec Nat 0
Vec Nat 2are different types.
The distinction is:
Ais a parameter, fixed throughout the recursive computation.nis an index, which may change depending on the constructor.
The constructors make this explicit:
nil : Vec A 0cons : (n : Nat) →
A →
Vec A n →
Vec A (succ n)
The cons constructor receives a vector of length n and produces one of length succ n. This information changes the recursor’s motive.
For ordinary lists:
M : List A → Sort uFor vectors:
M : (n : Nat) → Vec A n → Sort uThe motive must now depend on both the vector and its length. In particular, the cons case becomes:
m_cons :
(n : Nat) →
(a : A) →
(xs : Vec A n) →
M n xs →
M (succ n) (cons n a xs)Notice that the induction hypothesis concerns a vector of length n, while the result concerns a vector of length succ n.
Indices allow the kernel to express and verify how type-level information changes across constructors. In our implementation, parameters and indices are stored separately in InductiveSpec. Each constructor also stores its result_indices.
During recursor generation, the kernel uses the recursive field’s indices to construct the induction hypothesis and the constructor’s result indices to construct the goal. Parameters are fixed before introducing the motive, while indices become arguments to the motive itself.
5.7 Equality Is Also an Inductive Type!
So far, we have used inductive types to represent data such as natural numbers, trees, and lists. But here is something surprising: even mathematical equality can be defined as an inductive type!
In Lean 4, equality is defined essentially as follows:
inductive Eq (A : Type) (a : A) : A → Prop where
| refl : Eq A a aLet’s unpack this definition. Eq A a b represents the proposition that a equals b. It has two parameters, A and a, and one index, b. Unlike Nat or Tree, equality has only one constructor:
Eq.refl : (A : Type) → (a : A) → Eq A a aIn other words, the only way to construct an equality proof directly is to show that something equals itself. But how can this single constructor justify rewriting an expression using an equality proof? The answer, once again, is the recursor!
Deriving Eq.rec
Just as we generated Nat.rec and Tree.rec, the kernel generates a recursor for Eq. Suppose we want to establish a property M b h for any value b and equality proof h : Eq A a b. Our motive has type:
M : (b : A) → Eq A a b → Sort uSince equality has only one constructor, refl, we only need to handle one case:
base : M a (Eq.refl A a)From this, the recursor allows us to construct the property for any equality proof:
Eq.rec :
(A : Type) →
(a : A) →
(M : (b : A) → Eq A a b → Sort u) →
M a (Eq.refl A a) →
(b : A) →
(h : Eq A a b) →
M b hThis may look complicated, but the meaning is simple: If a property holds when two values are identical, it also holds whenever we have a proof that those values are equal.
Equality Gives Us Rewriting
For example, suppose we have:
h : Eq Nat a b
P : Nat → Prop
pa : P aWe want to construct a proof of P b. Choose the motive:
M b h = P bThe base case is simply pa : P a. Therefore, Eq.rec gives us:
Eq.rec Nat a M pa b h : P bThis is exactly the logical principle behind rewriting with equality. The computation rule is also straightforward:
Eq.rec A a M base a (Eq.refl A a)
↦ baseWhen the equality proof is refl, the recursor simply returns the base case. This is another example of ι-reduction, using precisely the same general mechanism as Nat.rec and Tree.rec.
Why Is Eq Different from Nat?
There is one important difference: Eq A a b lives in Prop, or Sort 0, while Nat lives in Sort 1.
Lean generally restricts eliminating arbitrary proofs in Prop into computational data types. However, equality is a special case: it has only one constructor, with no fields, so its recursor may eliminate into larger universes. Our implementation checks this restriction when registering inductive declarations.
The important takeaway is that equality does not need to be a primitive logical rule hardcoded into the kernel. Its elimination principle can be generated from an inductive declaration, just like the induction principle for natural numbers.
6. Tactics: Building an Interactive Theorem Prover
We now have a kernel capable of checking proof terms, defining inductive types, and evaluating recursive computations. In principle, this is already enough to prove many theorems. But there is a usability problem.
Consider our very first theorem:
(P : Prop) → P → PWe can prove it by writing a lambda expression directly:
fun (P : Prop) (h : P) => hFor this simple theorem, writing a proof term is easy. But for larger theorems, manually constructing deeply nested lambda expressions, function applications, and recursors quickly becomes painful.
This is where tactics come in. Instead of writing the complete proof term ourselves, we can interactively transform a theorem into smaller goals using commands such as intro, apply, rw, and induction.
For example:
theorem identity (P : Prop) : P → P := by
intro h
exact hAlthough this looks very different from a lambda expression, both proofs ultimately represent the same term:
fun (h : P) => hThe crucial point is that tactics do not introduce new logical rules. They construct proof terms that are checked by the same kernel we already implemented.
6.1 What Is a Goal?
Suppose we want to prove:
P → PIn tactic mode, Lean displays something like:
P : Prop
⊢ P → PThe symbol ⊢ separates the local context from the proposition we want to prove. We can represent a goal as two pieces of information:
struct Goal {
context: Context,
target: Term,
}Here, context contains the available variables and hypotheses, while target is the type of the proof term we need to construct.
For example:
Context:
P : PropTarget:
P → P
corresponds to a goal whose context contains P : Prop and whose target is P → P. Mathematically, this is the typing judgment:
P : Prop ⊢ ?proof : P → PThe question mark means that the proof term has not been constructed yet. We call such an unfinished term a metavariable or hole.
For now, imagine that every goal represents a missing part of a proof. A tactic either fills that missing part or replaces it with smaller holes.
Let’s implement two of the most basic tactics in the next few subsections.
6.2. `intro`: Turn an Implication into an Assumption
Suppose our goal is:
P : Prop
⊢ P → PWe execute:
intro hThe goal changes to:
P : Prop
h : P
⊢ PWhat happened? We were trying to construct a function of type P → P. The intro tactic introduced its argument h : P, leaving us to construct the function body. This is exactly the same operation as constructing a lambda expression.
Before:
?proof : P → PAfter:
?proof = fun (h : P) => ?bodywhere:
h : P ⊢ ?body : PWe have not completed the proof. We have only replaced one hole with another, smaller hole. More generally, if the goal is:
Γ ⊢ (x : A) → Bthen intro x transforms it into:
Γ, x : A ⊢ BThe resulting proof term will be:
fun (x : A) => bodyThis corresponds directly to the T-Lam typing rule from Section 3.
6.3. `exact`: Fill the Hole with a Proof Term
We now have:
P : Prop
h : P
⊢ PExecute:
exact hThe tactic checks that h has the expected type P.
Since:
h : Pthe goal is solved.
The generated proof term is simply:
hCombining the two tactics, we obtain:
fun (h : P) => hwhich the kernel can verify using the ordinary typing rules. This also suggests a straightforward implementation for exact. Conceptually, the tactic needs to do little more than:
fn exact(kernel: &Kernel, goal: &Goal, term: &Term) -> Result<()> {
kernel.check(&goal.context, term, &goal.target)
}This simplified function checks whether a term solves the goal. A complete tactic engine must also store the term in the corresponding proof hole.
Notice that exact does not decide whether a proposition is mathematically true. It delegates type checking to the kernel.
6.3 apply: Proving a Goal Backwards
Now consider a slightly more interesting theorem:
theorem compose (P Q R : Prop)
(f : P → Q) (g : Q → R) (p : P) : R := by
apply g
apply f
exact pThe initial goal is:
f : P → Q
g : Q → R
p : P
⊢ RWe have a function g : Q → R. If we can construct a proof of Q, applying g will give us a proof of R.
Therefore, executing:
apply gchanges the goal to:
⊢ QSimilarly, since f : P → Q, executing:
apply fchanges the goal to:
⊢ PFinally:
exact pcloses the proof. The complete proof term is:
g (f p)This is an important distinction between apply and exact.
exact gfails becauseghas typeQ → R, notR.apply gsucceeds because it creates a new goal for the missing argument ofg.
apply can also generate multiple goals Suppose we have:
f : P → Q → R
⊢ RApplying f requires two arguments:
?p : P
?q : QThe tactic generates two goals:
Goal 1:
⊢ PGoal 2:
⊢ Q
The partially constructed proof term is:
f ?p ?qOnce both holes are filled, the proof is complete. This is why an interactive theorem prover needs to manage multiple goals rather than only a single target. A simple tactic state might look like:
struct TacticState {
goals: Vec<Goal>,
}However, this is not yet sufficient to reconstruct the complete proof term. We also need to remember how the goals fit together. That leads us to metavariables.
6.4 Metavariables: How the Kernel Gets a Complete Proof
So far, we have described tactics as transforming goals. But there is a subtle problem. Suppose we start with:
⊢ P → Pand execute:
intro hWe now have:
h : P
⊢ PIf we only store the new goal, we have forgotten that its solution must be wrapped in a lambda expression.
Similarly, after apply g, we need to remember that the eventual proof must be an application of g. In other words, a list of goals is not enough. We must also track the partially constructed proof term.
We can extend our expression language with a metavariable:
enum Term {
// Existing term constructors...
MetaVar(usize),
}This is an illustration of the tactic layer’s internal representation. Unlike ordinary kernel terms, metavariables are not accepted as unfinished proofs by the trusted kernel.
We can maintain a mapping from metavariable IDs to their assignments. For example, start with:
?0 : P → PAfter intro h, assign:
?0 := fun (h : P) => ?1where:
?1 : PAfter exact h, assign:
?1 := hSubstituting the assignments gives:
?0 = fun (h : P) => hNo holes remain.
The tactic engine can now send the complete term to the kernel:
kernel.check(&empty_context, &proof, &theorem_type)?;This final check is essential. A tactic implementation may have bugs. It might introduce an incorrect substitution, generate malformed applications, or make invalid assumptions while manipulating goals. But as long as every resulting proof is independently checked by a sound kernel, a bug in a tactic cannot make an invalid theorem pass verification.
6.5 rw: Rewriting with Equality
In Section 5, we defined equality as an inductive type and generated its recursor. Recall that an equality proof has type:
h : Eq A a bIntuitively, h tells us that a and b are equal. The rw tactic uses this proof to replace one expression with another.
Consider:
theorem rewrite_example
(P : Nat → Prop) (a b : Nat)
(h : a = b) (pa : P a) : P b := by
rw [← h]
exact paInitially, the goal is:
P : Nat → Prop
a b : Nat
h : a = b
pa : P a
⊢ P bThe command:
rw [← h]rewrites the target using the equality in the reverse direction, from b to a. The new goal is:
⊢ P aNow exact pa solves it.
But why is this logically sound? Because the rw tactic can construct a proof using the equality recursor from Section 5. Recall the general idea of Eq.rec:
Eq.rec :
(M : (b : A) → Eq A a b → Sort u) →
M a (refl a) →
(b : A) →
(h : Eq A a b) →
M b hFor our example, choose:
M b h = P bThen the base case requires a proof of P a, which we already have. Applying Eq.rec transports this proof along h : a = b and produces a proof of P b. Conceptually, the completed proof is:
Eq.rec (M := fun b _ => P b) pa b hThe precise Lean 4 elaboration may use specialized equality-transport constants and additional implicit arguments, but the logical mechanism is the same.
6.6 induction: Using the Recursor as a Tactic
Now we can connect the tactic system to the inductive types we implemented in Section 5.
Recall that Nat.rec has the type:
Nat.rec :
(M : Nat → Sort u) →
M zero →
((n : Nat) → M n → M (succ n)) →
(n : Nat) → M nWhen M n is a proposition, this is exactly mathematical induction. Therefore, an induction tactic does not need to introduce another logical principle. It only needs to construct an application of Nat.rec.
Suppose our goal is:
n : Nat
⊢ P nwhere:
P : Nat → PropExecute:
induction n with
| zero => ...
| succ k ih => ...The tactic creates two goals.
Base case:
⊢ P zeroInductive step:
k : Nat
ih : P k
⊢ P (succ k)These are precisely the two arguments required by Nat.rec. The proof term being constructed has the form:
Nat.rec
(M := P)
?base
(fun k ih => ?step)
nHere, ?base and ?step are metavariables that the remaining tactics must fill.
Let’s think about a concrete exmaple of proving n + 0 = n. Consider:
theorem add_zero (n : Nat) : n + 0 = n := by
induction n with
| zero =>
rfl
| succ n ih =>
rw [Nat.succ_add, ih]The initial goal is:
n : Nat
⊢ n + 0 = nAfter induction n, we obtain:
Case zero:
⊢ 0 + 0 = 0and:
Case succ:
n : Nat
ih : n + 0 = n
⊢ (succ n) + 0 = succ nIn the base case, both sides compute to the same value, so rfl succeeds.
In the successor case, Nat.succ_add rewrites the left-hand side using the recursive definition of addition, and ih completes the proof. The generated proof has the same essential structure as:
Nat.rec
(M := fun n => n + 0 = n)
base_proof
(fun n ih => step_proof)
nThis is a direct application of the recursor we already generated from the Nat constructors.
Note that the exact rewriting steps depend on how addition is defined. In Lean 4, a simpler proof of n + 0 = n is also available by computation, but the induction-based version makes the generated recursor explicit.
Generalizing induction Beyond Nat
For the Tree type from Section 5:
inductive Tree where
| leaf : Tree
| node : Tree → Tree
| branch : Tree → Tree → Treethe tactic:
induction t with
| leaf => ...
| node child ih => ...
| branch left right ih_left ih_right => ...generates three goals instead of two.
The node case receives one induction hypothesis, while the branch case receives two. This is not special logic implemented for trees. The tactic simply uses the constructor cases required by Tree.rec. The general principle is:
An induction tactic turns a goal into the constructor cases required by the inductive type’s recursor, then assembles their proofs into a recursor application.
That is why the inductive type machinery from Section 5 is so useful: we can build a generic induction tactic rather than implementing a separate induction rule for every type.
6.7 Implementing a Minimal Tactic Engine in Rust
We now have enough pieces to sketch a small tactic engine. The kernel already provides trusted operations such as:
kernel.infer(...)
kernel.check(...)
kernel.is_def_eq(...)The tactic engine adds a separate layer that manages unfinished proofs. A possible minimal design is:
struct ProofGoal {
context: Context,
target: Term,
metavariable_id: usize,
}struct TacticState {
goals: Vec<ProofGoal>,
assignments: HashMap<usize, Term>,
next_metavariable_id: usize,
}
The responsibilities of the main tactics can then be summarized as follows:
Press enter or click to view image in full size
A tactic is therefore just a program that reads the current proof state, creates or assigns metavariables, and updates the remaining goals.
For example, the essence of intro is:
fn intro(state: &mut TacticState, name: &str) -> Result<()> {
let goal = state.pop_goal()?; let (binder, domain, body) = expect_pi(&goal.target)?;
let new_target = rename_binder_body(&body, &binder, name);
let new_goal = state.fresh_goal(
extend_context(&goal.context, name, &domain),
new_target,
);
state.assign(
goal.metavariable_id,
lam(name, domain, new_goal.as_term()),
)?;
state.push_goal(new_goal);
Ok(())
}
intro does not prove anything by itself. It replaces a hole with a lambda expression containing another hole. Likewise, apply replaces a hole with a function application containing holes for the missing arguments.
7. The Machinery Under the Hood: Substitution, 𝛼-Equivalence, and Conversion
The above type checker internally calles various functional operations to compare and normalize expressions: capture-avoiding substitution (for T-App and function evaluation), 𝛼-equivalence (for comparing types up to bound variable names), and conversion (for T-Conv).
7.1 Free Variables and Capture-Avoiding Substitution
In our syntax, Π (x: A). Band 𝜆(x: A), tact as binders: any occurrence of xinside the body Bor trefers to the bound parameter. Crucially, the binder’s scope covers only the body , and xis not bound inside the type annotation A. Variables that are not bound by any enclosing Πor 𝜆are called free variables, written FT(x):
Press enter or click to view image in full size
/// The free variables `FV(t)`.
pub fn fv(t: &Term) -> HashSet<String> {
match t {
Term::Sort(_) => HashSet::new(),
Term::Var(x) => HashSet::from([x.clone()]),
Term::App(f, a) => {
let mut names = fv(f);
names.extend(fv(a));
names
}
Term::Pi(x, a, b) | Term::Lam(x, a, b) => {
let mut names = fv(a);
let mut body_names = fv(b);
body_names.remove(x);
names.extend(body_names);
names
}
}
}Suppose we want to compute (𝜆 (y: A). x) [x -> y]. The original function (𝜆 (y: A). x)ignores its argument yand returns the outer free variable x. If we naively replace xwith y, we get (𝜆 (y: A). y) , which is the identity function! The free variable yhas been accidentally “captured” by the 𝜆 (y: A) binder, completely changing the meaning of the program.
To prevent this, substitution must be capture-avoiding: whenever a binder’s variable yappears free in the replacement terms (y \in FV(s)), we must first rename the binder to a fresh variable zbefore descending into the body.
Press enter or click to view image in full size
pub fn subst(t: &Term, x: &str, replacement: &Term) -> Term {
match t {
Term::Sort(_) => t.clone(),
Term::Var(y) => {
if y == x {
replacement.clone()
} else {
t.clone()
}
}
Term::App(f, a) => app(subst(f, x, replacement), subst(a, x, replacement)),
Term::Pi(y, domain, body) | Term::Lam(y, domain, body) => {
let substituted_domain = subst(domain, x, replacement);
let (renamed_binder, substituted_body) = if y == x || !fv(body).contains(x) {
(y.clone(), (**body).clone())
} else if !fv(replacement).contains(y) {
(y.clone(), subst(body, x, replacement))
} else {
let mut avoid = all_names(body);
avoid.extend(all_names(domain));
avoid.extend(all_names(replacement));
avoid.insert(x.to_string());
let z = fresh(y, &avoid);
let body_with_z = subst(body, y, &var(&z));
(z, subst(&body_with_z, x, replacement))
};
let domain = Box::new(substituted_domain);
let body = Box::new(substituted_body);
if matches!(t, Term::Pi(..)) {
Term::Pi(renamed_binder, domain, body)
} else {
Term::Lam(renamed_binder, domain, body)
}
}
}
}7.2 alpha-Equivalence: Variable Names Don’t Matte
In any programming language, renaming a function’s parameter doesn’t change what the function does. For example, fun (x: A) => x is the exact same function as fun (y: A) => y .
Similarly, in our theorem prover, Π(𝑃:Sort 0). 𝑃 → 𝑃and Π(𝑄:Sort 0). 𝑄 → Q express the exact same proposition. Terms that are identical except for the names of their bound variables are called 𝛼-equivalent (written as =𝛼).
When the kernel checks whether two types are equal, a simple string or AST equality check (s == t) won't work because P and Q are different variable names. On the other hand, repeatedly renaming variables in the AST to make them match is slow and messy, how do we know which fresh names to pick?
While the detailed mechanism is out of the scope of this article, alpha-equivalence check usually compare binder positions instead of variable names, and the kernel walks both ASTs side-by-side and compares how many binders outward each variable points.
For example, suppose we want to check whether these two nested functions are alpha-equivalent:
𝜆(𝑥:𝐴). 𝜆(𝑦:𝐵). x𝜆(𝑎:𝐴). 𝜆(𝑏:𝐵). a
As the algorithm steps inside the binders on both sides, it records the parameter names in two lists (stacks), E1 and E2:
- Pass the first binder:
E1 = [x]andE2 = [a]. - Pass the second binder:
E1 = [x, y]andE2 = [a, b].
We then look up how far back each variable appears in its respective list (counting from the innermost binder at index 0).
- In
E1 = [x, y],xis at distance1from the right. - In
E2 = [a, b],ais also at distance1from the right.
pub fn alpha(a: &Term, b: &Term) -> bool {
fn binder_distance(bound: &[String], x: &str) -> Option<usize> {
bound.iter().rev().position(|name| name == x)
}
fn go(a: &Term, b: &Term, bound_a: &mut Vec<String>, bound_b: &mut Vec<String>) -> bool {
match (a, b) {
(Term::Sort(u), Term::Sort(v)) => u == v,
(Term::Var(x), Term::Var(y)) => {
match (binder_distance(bound_a, x), binder_distance(bound_b, y)) {
(Some(i), Some(j)) => i == j,
(None, None) => x == y,
_ => false,
}
}
(Term::App(f, a), Term::App(g, b)) => {
go(f, g, bound_a, bound_b) && go(a, b, bound_a, bound_b)
}
(Term::Pi(x, a, b), Term::Pi(y, c, d)) | (Term::Lam(x, a, b), Term::Lam(y, c, d)) => {
if !go(a, c, bound_a, bound_b) {
return false;
}
bound_a.push(x.clone());
bound_b.push(y.clone());
let bodies_equal = go(b, d, bound_a, bound_b);
bound_a.pop();
bound_b.pop();
bodies_equal
}
_ => false,
}
}
go(a, b, &mut vec![], &mut vec![])
}7.3 beta-Reduction: Simplyfing the dependent types
In languages like Rust, TypeScript, or Java, type checking is purely static: the compiler never has to run your functions just to check if two types match.
In a dependent type theory like Lean, however, types can contain ordinary function calls. And that means two types that look completely different on the surface might actually be the same type once you evaluate them!
For example, let Id = 𝜆(𝑋:Sort 0). X be the identity function on propositions. Consider these two types:
- Type A: (
𝜆(𝑋:Sort 0). X) P(i.e.,Id P) - Type B:
P
Syntactically, Type A is a function application while Type B is a single variable, so they are not alpha-equivalent. Yet if we actually run the function application in Type A by plugging P into X, it evaluates directly to P. Thus, any proof of Id Pmust also be accepted as a valid proof of P.
More formally, evaluating a function application by substituting the argument into the function body is called 𝛽-reduction:
Press enter or click to view image in full size
When we repeatedly apply 𝛽-reduction everywhere inside a term until no more function applications can be simplified, the resulting expression is in normal form.
Term::Lam(x, _, body) if !args.is_empty() => Some(apps(
subst(&body, &x, &args[0]),
args[1..].iter().cloned(),
)),7.4 Conversion
To decide 𝑠 ≡ 𝑡, the kernel normalizes both terms and compares the results with =𝛼 . This procedure relies on two facts. First, 𝛽-reduction is confluent: different reduction orders cannot lead to different normal forms, so 𝑠 ≡ 𝑡 holds exactly when the normal forms of 𝑠 and 𝑡 are 𝛼-equivalent. Second, every well-typed term has a normal form, so normalization terminates.
Press enter or click to view image in full size
8. Conclusion
We started with a simple question: What actually happens when Lean 4 verifies a mathematical proof?
By building a miniature theorem prover from scratch, we have seen that the answer is surprisingly elegant. At its core, a theorem prover is a type checker. Thanks to the Curry–Howard correspondence, propositions can be represented as types, proofs as programs, and proof verification as ordinary type checking.
Of course, MiniLean4 is far from a complete implementation of Lean 4. The real system includes sophisticated elaboration, universe polymorphism, type classes, powerful metaprogramming facilities, and many other features. Our implementation also deliberately simplifies several aspects of inductive types and tactics.
Nevertheless, the fundamental architecture is already there. Once you understand how a few typing rules, reduction rules, and recursors fit together, interactive theorem proving starts to look much less like magic and much more like a carefully designed programming language.
You can explore the complete implementation, run the examples, and experiment with your own extensions in the MiniLean4 GitHub repository.