9. The elaborator
Draft
What is written and what the kernel checks
Here is a complete proof in Lean, 26 characters long: example : 2 + 2 = 4 := rfl. The kernel of Section 6 could not check that line as written. Kernel terms have no infix notation: every operation is a constant applied explicitly to all of its arguments. Nothing on the line states what type the numerals have or in which universe that type lives, and rfl is a function expecting both a type and the value being equated to itself, neither of which appears on the page. Nobody writes kernel terms directly. Instead, a program called the elaborator builds a kernel term from what a mathematician writes. Wherever information is omitted, the elaborator inserts a placeholder hole and solves for it: by unification, which solves equations between terms; by searching through declared type class instances (Section 8.4); and by inserting coercions, functions that transport a term from one type to another.
Tracing how the elaborator processes real lines of code requires taking its mechanisms in order of dependence: holes come first, since a missing piece needs a name, a local context, and an expected type before anything can solve for it; unification comes next, because type class search uses unification to test each candidate instance, coercions are found by type class search, and universe constraints arise alongside term equations; finally, pattern matching is compiled down to primitive recursors. That nobody writes kernel terms directly is the third step of the series' argument, and it shapes what a machine check actually establishes: the theorem statement handed to the kernel is the elaborator's output just as much as the proof is. Because the elaborator's rules are heuristic and incomplete, the architecture rests on the separation drawn in Section 9.8: the elaborator searches without being trusted, while the kernel checks whatever term the elaborator produces.
wire characters ── syntax tree ──────────── statement ── term ── kernel term
26 24 nodes over 9 tokens, 37 → 47 37 47 + 37 nodes
its leaves (13 nodes nodes
hold no token)
line example : 2 + 2 = 4 := rfl
step 7 of 12: the statement, every argument explicit. Lean printed it after its first pass and
again with every hole filled; this view between the two is assembled from them
[..] a hole still open «..» a hole being filled at this step
@Eq.{[?u.3 + 1]} [?m.11]
(@HAdd.hAdd.{«0», [?u.4], [?u.3]} «Nat» [?m.8] [?m.11] [?m.10]
(@OfNat.ofNat.{«0»} «Nat» (nat_lit 2) «(instOfNatNat (nat_lit 2))»)
(@OfNat.ofNat.{[?u.4]} [?m.8] (nat_lit 2) [?m.4]))
(@OfNat.ofNat.{[?u.3]} [?m.11] (nat_lit 4) [?m.6])
event default instance: ?m.2 : OfNat ?m.7 2 =?= instOfNatNat ?n : OfNat Nat ?n
it fills ?m.2 and forces ?m.7 := Nat: 2 of 7 holes filled
in all 31 instance problems, 28 of which had to wait; 24 assignments;
42 comparisons of universe levels: interleaved, not one after the other
(the live figure needs JavaScript and loads about 0.2 MB of data)
?m.7 is a hole for a term, ?u.5 one for a universe level; grey marks a hole filled earlier, hatching an assignment Lean took back. Under the term: the event in Lean's words, and for each hole its type, a tick each time its instance problem was put aside, and its value. Instance problems, assignments and comparisons of levels come interleaved. The title says whether a view is Lean's own printing or assembled between two printings. Step, or click a hole or a station.Twenty-six characters of source text expanded into a statement of 47 nodes and a proof term of 37, none of the intermediate structure written by hand. After its initial pass the statement still had 7 holes and 3 unknown universe levels; across the whole line Lean made 24 assignments and picked up a type class problem 31 times, putting it back down 28 times to wait for missing type information. (A node is a single application, constant, variable, binder, or literal; here terms are counted as unfolded trees, counting a repeated subterm each time it occurs.) Those counts come from one recorded run, and they show no clean pipeline of compiler passes. Unification assignments, instance searches, and universe-level comparisons run interleaved, each unlocking information on which the others wait. Even parsing works without separate passes: Lean has no standalone lexer pass before building a syntax tree (tokens sit directly at the leaves), and notations such as 2 + 2 expand on the fly when the elaborator reaches them rather than in a dedicated macro phase.
Because these steps interleave rather than running in fixed stages, elaboration is best characterized by its input and the finished terms that the kernel of Section 6 requires.
Definition 9.1.1 (elaboration). Elaboration is the passage from the syntax tree of a command to terms of the kernel's language. For a theorem it yields two closed terms, the statement and a proof of it, in which every argument, every instance and every universe level is explicit and no hole is left. The elaborator is the program that does this. Lean elaborates the statement first, by itself, and then the proof against it.
The paper that described Lean's elaborator in 2015 defines the word by what ordinary mathematical writing leaves out, as "the process of passing from a quasi-formal and partially-specified expression to a completely precise formal one", and concedes that algorithms for it "are not well documented in the literature, making the practice something of a dark art".L. de Moura, J. Avigad, S. Kong and C. Roux, "Elaboration in Dependent Type Theory", arXiv 1505.04324 (2015), abstract and Section 1. The paper describes the Lean of 2015, which searched with backtracking and had a second mode for homotopy type theory. The elaborator of Lean 4 is another program, written in Lean itself, which postpones a problem where the old one backtracked and finds instances by tabling (Section 9.4); what carries over is the statement of the problem and its vocabulary. The reference manual of Lean 4 says it from the kernel's side: "Elaboration is the process of transforming Lean's user-facing syntax into its core type theory. This core theory is much simpler, enabling the trusted kernel to be very small.""The Lean Language Reference", in its edition for Lean 4.35.0 (lean-lang.org/doc/reference/4.35.0), Section 2, "Elaboration and Compilation".
Neither description explains the mechanism by which a program reconstructs terms that nobody wrote. Leaving a single witness blank with an underscore shows that mechanism in miniature.
Holes
When a piece of a term is omitted on purpose with _, Lean solves for the missing subterm and #print displays what it found.
theorem three : ∃ n : Nat, n + 2 = 5 := ⟨_, rfl⟩
#print three
theorem three : ∃ n, n + 2 = 5 :=
Exists.intro 3 rfl
The angle brackets construct the dependent pair required to prove an existence claim: a witness followed by a proof that the witness works. Here the underscore stands in for the witness. Lean inserts a fresh unknown ?m.13 in place of _ and moves on to the second component, rfl. Because rfl proves an equality only when its two sides compute to the same term, checking rfl against the expected type ?m.13 + 2 = 5 generates the constraint 5 =?= ?m.13 + 2. Lean simplifies that constraint to 3 =?= ?m.13 and assigns ?m.13 := 3.
That workflow is the method of undetermined coefficients adapted to dependent type theory. Whenever a piece of syntax omits a subterm, the elaborator inserts a named unknown and continues building the surrounding expression; whenever two types must agree, it records an equation containing those unknowns and solves for them. These unknowns are called metavariables: variables belonging to the elaborator's scratchpad rather than to the logic itself. Every implicit {...} argument becomes a metavariable, as does every [...] type class argument and every omitted universe level. Unlike an algebraic coefficient, however, a metavariable sits at a specific position inside a term where certain local variables are in scope: a hole inside fun x => _ may legitimately use x, whereas a hole outside that binder cannot. Each metavariable also carries a kind marking which subsystem owns it, so that eager unification does not accidentally overwrite a hole meant for type class synthesis or for a tactic block (Section 8.6).
Definition 9.2.1 (metavariable, assignment). A metavariable \(?m\) is declared with a context \(\Gamma\) and a type \(A\), written \(\Gamma \vdash\, ?m : A\). An assignment \(?m := M\) is admissible if \(\Gamma \vdash M : A\) and \(?m\) does not occur in \(M\); so \(M\) may mention the variables of \(\Gamma\) and no others. To instantiate a term is to replace each assigned metavariable in it by its value. Lean calls a metavariable natural if unification may assign it; synthetic if its value is to come from a procedure of its own, such as the search for an instance, so that unification assigns it only where it cannot avoid doing so; and synthetic opaque if unification never assigns it, as with the goal of a tactic block. Universe levels have metavariables of their own.The three kinds are set out in the comment at the head of Lean/MetavarContext.lean, Lean 4.35.0; Lean/Elab/Term/TermElabM.lean makes the hole of an instance synthetic and the goal of a tactic block synthetic opaque.
Elaboration works largely from the outside in, checking each subexpression against the type expected at its position. The anonymous constructor brackets ⟨_, rfl⟩, for example, do not name a type on their own: knowing that the expected type is ∃ n : Nat, n + 2 = 5 tells Lean to expand them to Exists.intro, whereas without an expected type Lean rejects them with Invalid `⟨...⟩` notation: The expected type of this term could not be determined.
Because information flows both inward and outward, neither subexpressions nor constraints can always be resolved in a single left-to-right pass. When an expression's expected type is still unknown, Lean postpones it: in let x := ⟨1, 2⟩; Prod.fst x, an example from Lean's own source, the anonymous brackets ⟨1, 2⟩ wait until elaborating Prod.fst x reveals that x must be a product α × β. Similarly, a type class problem cannot be solved while the type it asks about is still an unassigned metavariable, so Lean sets it aside on a pending queue and retries it whenever new assignments are made; one of the four instance problems in 2 + 2 = 4 (Section 9.1) was resumed and postponed seven times. Lean's worklist loop repeatedly retries pending problems for as long as at least one makes progress.The function synthesizeSyntheticMVars in Lean/Elab/SyntheticMVars.lean, Lean 4.35.0. Once every pending problem stalls, it applies a fallback default instance (such as defaulting unconstrained numerals to Nat) and resumes the loop; only when no default instance applies either does it run tactic blocks and report any remaining holes as stuck. That fallback is the sole reason 2 + 2 = 4 becomes a statement about natural numbers. Its seven holes are three unknown types and four type class instances; every instance waits on a type, yet nothing on the line names Nat. Only after all four instance problems stall does Lean apply the default instance instOfNatNat, and unifying OfNat Nat 2 against OfNat ?m 2 forces the type hole to become Nat, breaking the deadlock.
Beyond standing for omitted arguments, metavariables also represent open proof goals in tactic mode. Metaprogramming in Lean 4 introduces both perspectives together:
The 'Meta' in
MetaMrefers to metavariables, so we should talk about these first. Lean users do not usually interact much with metavariables – at least not consciously – but they are used all over the place in metaprograms. There are two ways to view them: as holes in an expression or as goals.Take the goal perspective first. When we prove things in Lean, we always operate on goals, such as
n m : Nat
⊢ n + m = m + nThese goals are internally represented by metavariables. Accordingly, each metavariable has a local context containing hypotheses (here
[n : Nat, m : Nat]) and a target type (heren + m = m + n). Metavariables also have a unique name, saym, and we usually render them as?m.To close a goal, we must give an expression
eof the target type. The expression may contain fvars from the metavariable's local context, but no others. Internally, closing a goal in this way corresponds to assigning the metavariable; we write?m := efor this assignment.—A. Paulino and seven co-authors, "Metaprogramming in Lean 4". A. Paulino, D. Testa, E. Ayers, E. Karunus, H. Böving, J. Limperg, S. Gadgil and S. Bhat, "Metaprogramming in Lean 4" (github.com/leanprover-community/lean4-metaprogramming-book, as of 18 November 2026), chapter "MetaM", section "Metavariables". An fvar is a free variable, here a hypothesis of the goal.
Section 10 develops that goal perspective for tactics. The kernel, by contrast, permits neither open holes nor open goals: although mvar is one of the twelve constructors of Lean's internal Expr data type (Section 6.1) so that the elaborator and kernel can share one representation, any expression still containing an mvar is unfinished elaboration work rather than a well-formed term of the logic. Handed a definition leftOpen whose body still holds an unassigned hole, Lean's kernel rejects it with (kernel) declaration has metavariables 'leftOpen'. Every hole must be eliminated before the kernel checks a declaration, regardless of what the word "implicit" might suggest.
Remark 9.2.2 (implicit does not mean optional). An argument written in braces, {α : Type}, or in square brackets, [Add α], is omitted only from the human-written source, never from the elaborated kernel term. The three characters rfl in Section 9.1 elaborate to a constant applied explicitly to a universe level, a type, and a value: Lean prints @rfl.{1} Nat followed by the fully expanded 2 + 2, and the kernel receives every piece of it.
Different kinds of omitted information require different mechanisms to reconstruct them: unification for implicit values and types, table-driven search for type class instances, automatic casts for coercions, constraint solving for universe levels, and recursor compilation for pattern matching.
What a line leaves out, and what puts it backa row to a thing the source does not write; in ink, a line as written and under it what Lean 4.35.0 made of it
9.3an implicit argument found by unification
An argument in braces, or an underscore, is a hole. Lean lays the type that a function expects over the type it is given and assigns the hole whatever stands in its place.
example (x : Nat) : 2 + x = x + 2 := Nat.add_comm _ _
fun x => Nat.add_comm 2 x
9.4an instance found by search
An argument in square brackets is a record of operations. Lean searches the declared instances for one that fits, solves that instance's own arguments the same way, and keeps a table of the goals it has met.
fun (a b : Nat) => a + b
fun a b => @HAdd.hAdd Nat Nat Nat (@instHAdd Nat instAddNat) a b
9.5a coercion found by search, then inserted
Where a term of one type stands in the place of another, Lean looks for a function from the one to the other and inserts it. It prints the function as an arrow.
def h (x y : Nat) : Int := x - y
fun x y => ↑x - ↑y
9.6a universe level found by equations between levels
Every constant is used at particular universe levels, which the source never writes. Each is an unknown, solved while types are unified.
([Nat, Int] : List Type)
List.cons.{1} Nat (List.cons.{1} Int List.nil.{1}) : List.{1} Type
9.7a definition by cases compiled
The kernel has recursors and no pattern matching. Lean compiles the equations of a definition into one function, the matcher, that analyzes cases in a fixed order.
| 0, _ => 0 | _, 0 => 0 | m + 1, n + 1 => smaller m n + 1
Nat.casesOn x (h_1 x_1) fun n => Nat.casesOn x_1 (h_2 n.succ) fun n_1 => h_3 n n_1
green: unification, which every other row calls
Unification
To use a lemma is to solve an equation. Nat.add_comm says that n + m = m + n for all n and m; to prove 2 + x = x + 2 with it, somebody has to say what n and m are.
example example (x : Nat) : 2 + x = x + 2 := Nat.add_comm _ _ as given to Lean 4.35.0
problem 2 + x = x + 2 =?= ?m.14 + ?m.15 = ?m.15 + ?m.14 as Lean prints it; ?m.14 and ?m.15 are holes
steps Lean's trace, row by row: 6 rows (17 equations between identical terms are not drawn)
2 + x = x + 2 =?= ?m.14 + ?m.15 = ?m.15 + ?m.14
└ 2 + x =?= ?m.14 + ?m.15
├ 2 =?= ?m.14
│ └ ?m.14 := 2
└ x =?= ?m.15
└ ?m.15 := x « the assignment just made, step 6 of 6
filled 2 + x = x + 2 =?= 2 + x = x + 2 the two assignments, put in place here
answer Lean accepts the example and builds the term fun x => Nat.add_comm 2 x
Seven recorded examples, 3 of them refused with Lean's message. An equation typed by the reader is
solved by the page's own unifier, not by Lean: first-order terms and patterns, no unfolding, no guess.
(the live figure needs JavaScript and loads about 0.06 MB of data)
The two underscores in Nat.add_comm _ _ create two metavariables, ?m.14 and ?m.15, giving the application the type ?m.14 + ?m.15 = ?m.15 + ?m.14. Lean solves for both unknowns by aligning that type against the target goal 2 + x = x + 2: wherever a metavariable meets a subterm, Lean assigns that subterm to the hole. (An equation typed interactively into the figure is solved by a small unifier written for the page, which handles first-order terms and patterns without unfolding definitions; the seven recorded examples are Lean's own traces.)
Two terms need not become syntactically identical after substitution to unify. Because the kernel checks types up to definitional equality (Section 6.3), any assignment under which the two sides compute to the same normal form is a valid match.
Definition 9.3.1 (unification problem). A unification problem is an equation \(M \mathrel{=?=} N\) between two terms that may contain metavariables. A solution is an admissible assignment of metavariables that makes the two sides definitionally equal (Section 6.3).
Section 2.3 introduced unification for simple types, where types contain no computations or functions: there two types match only when they are syntactically identical, the algorithm always terminates, and every solvable problem has a single most general unifier. Dependent type theory breaks all three properties.
First, because definitional equality includes computation, the unifier must evaluate and unfold definitions while comparing terms. When checking rfl (of type ?a = ?a) against the goal x + 0 = x, Lean must solve x + 0 =?= x. It succeeds by unfolding HAdd.hAdd, Add.add, and Nat.add (six unfoldings in the recorded run, which performs the comparison twice): because Nat.add recurses on its second argument, meeting 0 on the right immediately reduces x + 0 to x. Swap the summands to 0 + x, however, and the second argument is the free variable x, where recursion gets stuck. On example (x : Nat) : 0 + x = x := rfl Lean reports:
Type mismatch
rfl
has type
?m.9 = ?m.9
but is expected to have type
0 + x = x
The error prints the failed unification equation directly: rfl's type, with its hole still unassigned, alongside the goal type it could not match. The equation 0 + x = x is true for every natural number, yet proving it requires induction rather than computation alone.
Second, a metavariable can stand for an unknown function, where naive structural matching breaks down. Consider solving ?f 0 =?= 0 for ?f : Nat → Nat: the identity fun x => x, the constant zero function fun x => 0, and fun x => 2 * x all send 0 to 0, because passing a concrete constant like 0 erases whether the 0 on the right came from ?f's input. When an unknown function is applied solely to distinct bound variables that ?f itself could not already mention, such as ?f x =?= x + 1 under a binder for x, that ambiguity disappears: every x on the right had to come through ?f's argument. That well-behaved fragment is called a higher-order pattern.
Definition 9.3.2 (pattern). Let \(?m\) be declared in the context \(\Gamma\). The problem \(?m\,a_1 \dots a_n \mathrel{=?=} t\) is a pattern if \(a_1, \dots, a_n\) are distinct variables that are not in \(\Gamma\), every variable of \(t\) is in \(\Gamma\) or among the \(a_i\), every metavariable of \(t\) is declared in an initial part of \(\Gamma\), and \(?m\) does not occur in \(t\).
When those side conditions hold, moving the variable arguments across the equation as lambda binders yields a well-scoped term in \(\Gamma\), leaving room for no other solution up to definitional equality.
Proposition 9.3.3 (a pattern has one solution). In every solution of a pattern the value of \(?m\) is definitionally equal to \(\lambda a_1 \dots a_n.\, t\) (with that solution's values put for any other metavariables of \(t\)), and \(?m := \lambda a_1 \dots a_n.\, t\) is itself a solution whenever it has the type of \(?m\).
Proof. The term \(\lambda \vec a.\, t\), its binders typed as the type of \(?m\) prescribes, mentions only variables of \(\Gamma\) and does not contain \(?m\), so it is admissible if its type is right, and applied to \(\vec a\) it reduces to \(t\) by β. Conversely, let a solution give \(?m\) the value \(f\), and read \(t\) with that solution's other values put in, so that \(f\, \vec a \equiv t\). The \(a_i\) are not in \(\Gamma\), hence not free in \(f\), and they are distinct, so η applies \(n\) times: \(f \equiv \lambda \vec a.\, f\, \vec a \equiv \lambda \vec a.\, t\). ∎
Both rules are among the kernel's (Section 6.3): β computes an abstraction applied to an argument, and η identifies a function \(f\) with \(\lambda x.\, f\,x\). Lean's unifier assigns exactly this term when it finds the conditions met.The conditions are those of a comment in Lean/Meta/ExprDefEq.lean, Lean 4.35.0, which begins "We say the unification constraint is a pattern IFF" and adds that the \(a_i\) must not be local definitions. The literature calls such problems Miller patterns, and so does Lean's source elsewhere (Lean/Meta/Sym/Pattern.lean). So ?f x =?= x + 1, under a binder for x, is solved by fun x => x + 1. A hole applied to anything but distinct variables is another matter: ?f 0 =?= 0 is solved by the identity, by the constant function 0, and by infinitely many others.
Third, then: outside the patterns there is in general no best solution, and no algorithm. "Even second-order unification is known to be generally undecidable [13], but the elaborator merely needs to perform well on instances that come up in practice", the paper of 2015 says,De Moura, Avigad, Kong and Roux (2015), Section 2.2, pp. 4 and 5. Their reference [13] is W. D. Goldfarb, "The undecidability of the second-order unification problem" (1981), cited here through the paper. and it gives an instance that comes up often.
Nevertheless, it is often the case that the elaborator is required to infer an element of a Π-type, which constitutes a higher-order unification problem. For example, if e : a = b is a proof of the equality of two terms of some type A, and H : P is a proof of some expression involving a, then the term subst e H denotes a proof of the result of replacing some or all of the occurrences of a in P with b. Here, in addition to inferring the type A, we also need to infer an expression T : A → Prop denoting the context for the substitution, that is, the expression with the property that T a is convertible to P. Such an expression is inherently ambiguous; for example, if H has type R (f a a) a, then with subst e H the user may have in mind R (f b b) b or R (f a b) a or something else, and the elaborator has to rely on context and a backtracking search to find an interpretation that fits. Similar issues arise with proofs by induction, which require the system to infer an induction predicate.
—L. de Moura, J. Avigad, S. Kong and C. Roux, "Elaboration in Dependent Type Theory" (2015). Section 2.2, "Higher-order unification", p. 4. The paper's
substis substitution along an equality (Section 5.4 of this series), and itsTis what this series calls the motive.
The induction predicate is the motive of a recursor, the family of propositions indexed by the value being inducted on (Section 5.6), and Lean 4 can be watched encountering this exact ambiguity.
Example 9.3.4 (a motive computed and a motive guessed). Consider two attempts in Lean 4.35.0 to prove 0 + n = n directly with the recursor Nat.rec, leaving its motive argument for Lean to supply, with the elaboration trace recorded for each:
example (n : Nat) : 0 + n = n := Nat.rec rfl (fun k ih => congrArg Nat.succ ih) n
example (n : Nat) : 0 + n = n := @Nat.rec _ rfl (fun k ih => congrArg Nat.succ ih) n
Lean accepts the first line because it does not rely on unification to find a recursor's motive: a dedicated elaboration rule inspects the overall target type 0 + n = n, abstracts over the scrutinee n, and computes the motive fun x => 0 + x = x directly.The function mkMotive in Lean/Elab/App.lean, Lean 4.35.0. The rule serves recursors, the constants derived from them such as Nat.casesOn, and constants marked @[elab_as_elim]. In the second line, prefixing @ makes all implicit arguments positional and switches that dedicated rule off, turning the _ motive into an ordinary unification hole ?m.8. Elaborating the base-case argument rfl (whose type ?m.10 = ?m.10 is the prefix application (Eq ?m.10) ?m.10) against the base-case target ?m.8 Nat.zero yields ?m.8 Nat.zero =?= (Eq ?m.10) ?m.10. Because Nat.zero is a constant rather than a bound variable, this equation is not a pattern. Lean falls back to naive first-order structural matching, pairing function with function and argument with argument: ?m.10 := Nat.zero and ?m.8 := Eq Nat.zero, which is the wrong motive fun t => 0 = t. Under that guessed motive, the successor step is asked to deduce 0 = k.succ from ih : 0 = k, and Lean reports:
Type mismatch
congrArg Nat.succ ih
has type
Nat.zero.succ = k.succ
but is expected to have type
Nat.zero = k.succ
Both fun t => 0 + t = t and fun t => 0 = t reduce at t = 0 to 0 = 0, so both satisfy the base-case equation on which the guess was made; only the first expresses the inductive claim needed at the successor step. ◁
When none of its heuristics succeeds, Lean leaves the hole open and says so. In example : ∃ f : Nat → Nat, f 0 = 0 := ⟨_, rfl⟩, the constraint ?f 0 =?= 0 has infinitely many solutions, and Lean's error prints the incomplete proof term Exists.intro ?m.9 rfl with ?m.9 still unassigned. Lean's unifier is therefore a sound-by-verification, incomplete collection of heuristics: whenever it answers yes with an assignment, the kernel rechecks that the resulting closed terms are definitionally equal, whereas a refusal means only that its heuristics could not pick a solution. Every unification heuristic, however, begins from an equation between terms, and some omitted arguments are not determined by any equation at all.
Type classes: arguments found by search
Section 8.4 showed what a type class becomes once elaboration finishes: an ordinary structure record passed as one more function argument. A bracketed argument such as [Add α] cannot be found by unification. Unifying surrounding types can determine that α is Nat, fixing the hole's type to Add Nat, yet no equation determines which value of type Add Nat goes into the hole; any record bundling a binary operation Nat → Nat → Nat has that type. Instead, Lean synthesizes the value by searching through the instances registered in the environment. Despite the traditional name "type class inference", nothing logical is inferred: registered instances act like Horn clauses in a logic program ("a list is printable if its elements are printable"), and Lean searches backward from the desired class.
#synth Repr (List (Nat × String)) Lean 4.35.0, one recorded run in a file without imports
tried the search, top to bottom in the order Lean went (its trace, replayed as a tree)
Repr (List (Nat × String))
1 ├ @instReprListOfReprAtom ░ dead end
│ ├ Repr (Nat × String)
2 │ │ └ @instReprProdOfReprTuple █
│ │ ├ Repr Nat
3 │ │ │ └ instReprNat █
│ │ └ ReprTuple String
4 │ │ └ @instReprTupleOfRepr █
│ │ └ Repr String
5 │ │ └ instReprString █
│ └ ReprAtom (Nat × String) ░ no instance
6 └ @instReprList █
└ Repr (Nat × String) answered above: taken from the table
█ an instance of the answer ░ refused, or a dead end
6 instances tried on 6 goals, in 23 events: 5 make up the answer, 1 is a dead end, and
one answer is used twice. The search for the monad stack tries 6 instances in a file
without imports and 22 in a file that imports Lean, for the same answer.
(the live figure needs JavaScript and loads about 0.1 MB of data)
Asked how to print a list of pairs via Repr (List (Nat × String)), Lean first tried a specialized instance instReprListOfReprAtom, solved its first subgoal Repr (Nat × String) in four recursive steps, hit a dead end on its second subgoal ReprAtom (Nat × String) (pairs are compound values, not atoms), and backed out. When it next tried the general list instance instReprList, which also requires Repr (Nat × String), it pulled the already-computed pair instance straight from a memoization table instead of repeating those four steps.
Because the meaning of an operator like + in a theorem statement is whichever instance this search returns, three things must be specified cleanly: what counts as a query, which declarations may answer it, and in what order candidates are tried.
Definition 9.4.1 (instance problem). A class is a type, usually a structure, declared with the keyword class. An instance is a constant, registered for the search, whose type ends in a class applied to arguments,
where the arguments in brackets are themselves to be found by search. An instance problem is a synthetic metavariable \(?i : C\, \vec s\). Lean answers it with the first term it can build by applying an instance, whose conclusion must unify with \(C\, \vec s\), to answers for that instance's own problems. Instances of higher priority are tried first, and among equals the most recently declared.
A naive depth-first backtracking search breaks down in large libraries whenever multiple inheritance paths converge on the same subgoal or mutually applicable instances form a loop. Lean's synthesizer (SynthInstance.lean) avoids redundant work and infinite loops by pairing two work stacks with a hash table of seen subgoals; its inner loop is 11 lines:
structure State where
result? : Option AbstractMVarsResult := none
generatorStack : Array GeneratorNode := #[]
resumeStack : Array (ConsumerNode × Answer) := #[]
tableEntries : Std.HashMap Expr TableEntry := {}
-- ...
def step : SynthM Bool := do
checkSystem
let s ← get
if !s.resumeStack.isEmpty then
resume
return true
else if !s.generatorStack.isEmpty then
generate
return true
else
return false
The generatorStack holds subgoals that still have candidate instances left to try; the resumeStack holds completed answers ready to be fed back into parent instances waiting on them; and tableEntries records every subgoal encountered so far together with its discovered answers and waiting consumer nodes. Whenever a subgoal arises a second time, Lean never searches its candidate instances again: it hands over any answers already stored in the table and registers the caller to be resumed if new answers arrive. This technique is called tabling, and the paper that introduced it to Lean explains why Mathlib could not scale without it:
Typeclasses provide an elegant and effective way of managing ad-hoc polymorphism in both programming languages and interactive proof assistants. However, the increasingly sophisticated uses of typeclasses within proof assistants, especially within Lean's burgeoning mathematics library, mathlib, have elevated once-theoretical limitations of existing typeclass resolution procedures into major impediments to ongoing progress. The two most devastating limitations of existing procedures are exponential running times in the presence of diamonds and divergence in the presence of cycles. We present a new procedure, tabled typeclass resolution, that solves both problems by tabling, which is a generalization of memoizing originally introduced to address similar limitations of early logic programming systems. We have implemented our procedure for the upcoming version (v4) of Lean, and have confirmed empirically that our implementation is exponentially faster than existing systems in the presence of diamonds.
—D. Selsam, S. Ullrich and L. de Moura, "Tabled Typeclass Resolution" (2020). arXiv 2001.04301, abstract.
A diamond occurs when two inheritance paths lead from one rich class down to the same simpler class (stacking \(k\) such diamonds multiplies naive backtracking paths by \(2^k\)), while a cycle occurs when two instances can each reduce a subgoal to the other. Diamonds, the reference manual notes, "occur regularly in practice when encoding mathematical concepts using type classes", and transitive coercions readily introduce cycles."The Lean Language Reference", Section 10.3, "Instance Synthesis". The search space grows with everything imported into a file. In 2019 a file importing all of Mathlib had "access to 4256 instances among 386 classes"; slides from September 2025 cite roughly 1,500 classes and 20,000 instances; and at the commit read in this series, Mathlib's source contains 27,748 lines beginning an instance declaration.The mathlib Community, "The Lean mathematical library", CPP 2020 (arXiv 1910.09336), Section 4.3, on the library for Lean 3; L. de Moura, "The grind Tactic: proof automation in Lean", slides dated 18 September 2025, the slide "Type Classes". The last number is counted from Mathlib's source text and is a lower bound, since other commands create instances too. Consequently, the cost of synthesizing a single instance depends heavily on what is in scope: resolving the four-monad stack of Section 8.5 takes 6 candidate tries in a file without imports versus 22 tries (with 2 rejections) after import Lean to reach the exact same answer. The searches in the figure were recorded in a file without imports.
Two refinements shape how arithmetic expressions elaborate. First, class parameters marked outParam act as outputs rather than inputs of the search: Lean declares heterogeneous addition + via class HAdd.{u, v, w} (α : Type u) (β : Type v) (γ : outParam (Type w)), which lets it start searching for HAdd Nat Nat _ as soon as the two summand types are known and read the result type γ off whichever instance succeeds. Second, a class may register a @[default_instance] fallback to run when a type parameter remains unconstrained, which is how 2 + 2 = 4 defaulted to Nat in Section 9.2. A numeral in source code never enters a kernel term as a bare number. Instead, it elaborates to OfNat.ofNat applied to a target type, a raw natural literal, and an OfNat instance: instOfNatNat for Nat, while in Mathlib any type with a canonical cast from Nat (including ℝ and ℂ) receives a general instance sending literals from 2 upward through that cast, with 0 and 1 supplied by the separate classes Zero and One.instOfNatAtLeastTwo in Mathlib/Data/Nat/Cast/Defs.lean, whose one field is ofNat := n.cast. The default instance is declared in Init/Prelude.lean with the attribute @[default_instance 100].
One clause of Definition 9.4.1 deserves a direct test: Lean commits to the first valid instance it builds. What happens when two incompatible instances both fit?
Example 9.4.2 (the first solution is not the only one). Suppose a single-field wrapper structure P is given two conflicting Add P instances, declared one right after the other in Lean 4.35.0:
structure P where
x : Nat
instance one : Add P := ⟨fun a b => ⟨a.x + b.x⟩⟩
instance two : Add P := ⟨fun a b => ⟨a.x * b.x⟩⟩
#eval ((⟨2⟩ + ⟨3⟩ : P)).x
Lean prints 6 without issuing any warning: both instances have equal priority, so the more recently declared two is tried first and wins (2 * 3 = 6). A design comment in Lean's source states both the rule and its rationale: type class resolution "commits to the first solution it finds", because allowing callers to backtrack into type class search and request alternative instances "would be too inefficient".The comment at the head of Lean/MetavarContext.lean, Lean 4.35.0, where TC stands for type class resolution. What + means on any line of Lean is therefore whichever instance won the search in that file's scope. A mathematical library can stay coherent under first-match commitment only if every path to a class on a given type produces the exact same structure up to definitional equality (Remark 11.3.2), a discipline Section 11.3 examines across Mathlib's algebraic hierarchy. ◁
Both unification and instance search fill holes that are already present inside an incomplete term. Sometimes, however, a term has no holes left at all and still fails to match the type expected of it.
Coercions
A closed term of type Nat cannot stand directly where an Int is expected, because Nat and Int are distinct types in the kernel. Compare two definitions that look nearly identical on paper:
def g (x y : Nat) : Int := (x - y : Nat)
def h (x y : Nat) : Int := x - y
#print g
#print h
#eval (g 2 3, h 2 3)
def g : Nat → Nat → Int :=
fun x y => ↑(x - y)
def h : Nat → Nat → Int :=
fun x y => ↑x - ↑y
(0, -1)
The two definitions compute different functions: at 2 and 3, g returns 0 while h returns -1, and the difference lies entirely in where Lean inserted the upward arrow ↑. In g, the type annotation (x - y : Nat) forces subtraction to happen in Nat, where 2 - 3 truncates at 0 (Section 7.6), before casting the result to Int; in h, both arguments are cast to Int first and subtracted as integers. That arrow ↑ represents a conversion function that nobody wrote in the source, inserted according to the rule stated in the reference manual:
When the Lean elaborator is expecting one type but produces a term with a different type, it attempts to automatically insert a coercion, which is a specially designated function from the term's type to the expected type. Coercions make it possible to use specific types to represent data while interacting with APIs that expect less-informative types. They also allow mathematical developments to follow the usual practice of “punning”, where the same symbol is used to stand for both an algebraic structure and its carrier set, with the precise meaning determined by context.
—"The Lean Language Reference", edition for Lean 4.35.0. Section 11, "Coercions", opening paragraph.
Lean finds that conversion function using the type class search of Section 9.4 over dedicated coercion classes, then unfolds the class projection on the spot: printed with explicit arguments, ↑x in h is simply @Nat.cast Int instNatCastInt x, an ordinary function application, which is all the kernel ever sees. When elaborating an arithmetic expression built from infix operators, Lean does not wait for the outer result to mismatch. Instead, it gathers the leaf operands of the whole operator tree, searches for a single common type to which every leaf can be coerced (guided by any expected type on the whole expression), and pushes the coercions down to the leaves.The comment that opens the namespace Op in Lean/Elab/Extra.lean, Lean 4.35.0. The classes that are searched, CoeT and those it chains, are described at the head of Init/Coe.lean. Pushing coercions to the leaves is why x - y at expected type Int elaborated as ↑x - ↑y rather than ↑(x - y), and why g needed an explicit (x - y : Nat) annotation to force natural subtraction first. Lean also supports two specialized coercion forms: coercing a non-function term into a function when it is applied to an argument, and coercing a term into a type (CoeSort) when it appears after a colon. That second form enables the mathematical "punning" mentioned in the manual, letting a bundled group structure G stand directly for its underlying carrier type in g : G. Calling it punning can make ↑ sound harmlessly invisible, whereas g and h show that where a cast sits can change the meaning of a theorem.
Remark 9.5.1 (a coercion is not an inclusion). On paper, \(\mathbb N \subset \mathbb Z\) is treated as a silent subset inclusion. In Lean, ↑ is an actual function call, and it need not commute with surrounding operations: ↑(x - y) and ↑x - ↑y are distinct terms that evaluate at 2 and 3 to 0 and -1. Any formal statement mixing natural numbers with integers, reals, or complex numbers must be audited with its coercions visible, as Section 11.6 does for the Riemann hypothesis.
Of the three explicit ingredients required by Definition 9.1.1 (arguments, instances, and universe levels), one remains: the universe levels.
Universe levels are solved too
Definitions and theorems also omit universe levels, a detail ordinary mathematical writing never mentions at all.
set_option pp.universes true in
#check ([Nat, Int] : List Type)
List.cons.{1} Nat (List.cons.{1} Int List.nil.{1}) : List.{1} Type
A universe is a type whose elements are types (Section 5.5): Nat and Int have type Type (short for Type 0), which itself has type Type 1, so a list of types lives one universe higher than a list of numbers, even though nobody wrote 1 in the source. A polymorphic constant such as List.{u} is declared for all universe levels at once (Section 6.1), and each occurrence of List must supply a concrete level expression. Whenever a polymorphic constant appears, the elaborator creates fresh level metavariables (?u.1, ?u.2, …) and solves equations between level expressions as surrounding types are unified. After its first pass on 2 + 2 = 4 (Section 9.1), the statement stood at @Eq.{?u.3 + 1} ?m.11 … with three unknown levels, and finished as @Eq.{1} Nat … after 42 level comparisons such as ?u.6 =?= ?u.5 + 1 and ?u.5 =?= 0.
Universe-level constraints share the ambiguity of higher-order term equations: because max is not injective, an equation equating two maxima can have multiple incomparable solutions.
universe u v
def prod' (α : Type _) (β : Type _) : Type (max u v) := α × β
stuck at solving universe constraint
max (u + 1) (v + 1) =?= max (?u.2 + 1) (?u.4 + 1)
while trying to unify
Type (max u v) : Type ((max u v) + 1)
with
Type (max ?u.2 ?u.4) : Type (max (?u.2 + 1) (?u.4 + 1))
Writing (α : Type _) (β : Type _) introduced two fresh level unknowns ?u.2 and ?u.4 unrelated to the declared variables u and v, and the explicit return type : Type (max u v) then demanded max (u + 1) (v + 1) =?= max (?u.2 + 1) (?u.4 + 1). The assignments (u, v), (v, u), and (max u v, 0) all satisfy that constraint, and just as when an unknown function is applied to a constant, Lean refuses to guess. (A second message follows for the same constraint after turning the two unknown levels into parameters.) Omitting the return type removes the equation against u and v: def pair (α : Type _) (β : Type _) := α × β succeeds immediately, generalizing the two fresh unknowns into universe parameters pair : Type u_1 → Type u_2 → Type (max u_1 u_2).
All five mechanisms so far reconstruct pieces that the source text omitted. Elaboration also works in the opposite direction, compiling away surface syntax that the kernel's small core language does not possess.
Pattern matching is compiled away
Lean's kernel has neither match expressions nor direct recursive function definitions. Each inductive type enters the kernel with a single primitive recursor that performs one-variable case analysis and structural induction (Section 5.6), and nothing else. Multi-argument pattern matching with recursive calls is surface notation that the elaborator must compile down to recursors.
written def smaller : Nat → Nat → Nat
n✝ : Nat x✝ : Nat
| 0, _ => 0 cannot match in this case
| _, 0 => 0 .(n✝) 0 gives h_2 n✝.succ
| m + 1, n + 1 => smaller m n + 1 m (Nat.succ n) gives h_3 m n
step 8 of 18: state 8 of the 15 of Lean's match compiler; the case (Nat.succ _), _,
in which two of the three equations can still match
tree _, _ Nat.casesOn x
├ Nat.zero, _ h_1 x_1
└ (Nat.succ _), _ ? ◀ the case being compiled
kernel what it receives, as Lean prints it: 3 definitions, 252 nodes written out as trees
smaller.match_1 fun motive x x_1 h_1 h_2 h_3 => Nat.casesOn x (h_1 x_1) fun n => ?
(so far: a ? is a case not yet compiled; complete, it has 101 nodes)
smaller._f applies smaller.match_1 to three functions, one for each equation (134 nodes)
smaller fun x x_1 => Nat.brecOn (motive := fun x => Nat → Nat) x smaller._f x_1 (17 nodes)
Nat.casesOn fun {motive} t zero succ => Nat.rec zero (fun n n_ih => succ n) t
(the live figure needs JavaScript and loads about 33 kB of data)
The three pattern-matching clauses of smaller inspect two natural numbers at once, whereas Nat.rec inspects only one at a time. Lean compiles those three clauses into an auxiliary matcher function, smaller.match_1, built out of two nested calls to Nat.casesOn (Nat.rec with its induction hypothesis ignored); a second helper, smaller._f, supplies one branch function per clause to smaller.match_1.
Every match expression produces a matcher function of this shape, whose type specifies what arguments it expects and, when patterns overlap, that the earliest matching clause wins.
Definition 9.7.1 (matcher). Let a match examine values of types \(D_1, \dots, D_n\) through \(k\) alternatives, the \(i\)-th with patterns \(p_{i1}, \dots, p_{in}\) in the variables \(\vec y_i\). Its matcher is a function of type
defined from the case analysis of the types involved, without recursion, such that on values which the \(i\)-th alternative is the first to match it reduces to the \(i\)-th function applied to the values of \(\vec y_i\). The family \(P\) is the motive.
For smaller, Lean prints:
smaller.match_1 : (motive : Nat → Nat → Sort u_1) →
(x x_1 : Nat) →
((x : Nat) → motive 0 x) → ((x : Nat) → motive x 0) → ((m n : Nat) → motive m.succ n.succ) → motive x x_1
Because motive ranges over any Sort u_1, the same matcher both computes values (when u_1 > 0) and proves theorems by case analysis on how smaller branches (when Sort 0 = Prop). Clause order is baked directly into the compiled case tree. At (0, 0), both the first clause (| 0, _ => 0) and the second (| _, 0 => 0) match the inputs; when smaller.match_1 splits on the first argument and sees Nat.zero, the first clause wins immediately and the second clause is discarded as overlapped on that branch. Consequently, the equational lemma smaller.eq_2 that Lean generates for the second clause carries the side condition x = 0 → False: a clause in a pattern-matching definition holds as an equation only on inputs missed by every earlier pattern.
Lean's match compiler is a single recursive procedure that tries a fixed priority list of simplifying transformations on a matrix of remaining patterns until every leaf selects a single right-hand side; the step labels in the figure's trace come straight from its source:
private partial def process (p : Problem) : StateRefT State MetaM Unit := do
traceState p
if isDone p then
traceStep ("leaf")
processLeaf p
return
-- ...
if hasIndependentPatterns p then
traceStep ("processing independent prefixes of patterns")
let p ← processIndependentPatterns p
process p
return
-- ...
if (← isConstructorTransition p) then
let ps ← processConstructor p
tracedForM ps process
return
-- ...
checkNextPatternTypes p
throwNonSupported p
The reference manual gives the reason for all of this, and a consequence.
Lean's core type theory does not include pattern matching or recursive definitions. Instead, it provides low-level recursors that can be used to implement both case distinction and primitive recursion. Thus, the elaborator must translate definitions that use pattern matching and recursion into definitions that use recursors. This translation is additionally a proof that the function terminates for all potential arguments, because all functions that can be translated to recursors also terminate. The translation to recursors happens in two phases: during term elaboration, uses of pattern matching are replaced by appeals to auxiliary matching functions (also referred to as matcher functions) that implement the particular case distinction that occurs in the code. These auxiliary functions are themselves defined using recursors, though they do not make use of the recursors' ability to actually implement recursive behavior. The term elaborator thus returns core-language terms in which pattern matching has been replaced with the use of special functions that implement case distinction, but these terms may still contain recursive occurrences of the function being defined. A definition that still includes recursion, but has otherwise been elaborated to the core language, is called a pre-definition.
—"The Lean Language Reference", edition for Lean 4.35.0. Section 2.4, "Elaboration Results". Two marginal notes of the page are left out.
The kernel, in other words, never runs a termination checker of its own. Instead, it receives terms built solely out of primitive recursors, and only terminating functions can be translated into that form. Eliminating the recursive call that remains after match compilation belongs to the second translation phase, whose strategies Section 8.3 traces kind by kind; for smaller, Lean uses Nat.brecOn (course-of-values recursion), packaging smaller's values at all smaller predecessors into a tuple x so that the recursive call smaller m n becomes a tuple lookup x.1 n rather than a self-reference. Across all three generated definitions, smaller reaches the kernel as 252 tree nodes: 101 in smaller.match_1, 134 in smaller._f, and 17 in smaller itself.
With all six elaboration mechanisms on the table, one question governs the trust story: which of them does a reader of a machine-checked theorem have to trust?
Not trusted
Consider what actually drove elaboration across the examples so far: a heuristic guess at an induction motive, first-match commitment during instance search, a default-to-Nat tiebreaker when pending constraints stalled, and outright refusals on solvable equations. None of those heuristics is a rule of logic, and none of them needs to be trusted, because the kernel independently type-checks the closed term that comes out at the end. How much expansion happens between source text and kernel term can be measured across Lean's own library.
points 45,123 of the 89,360 theorems of the core library of Lean 4.35.0, those its sources write out,
each a point: the characters of its proof (across) against the nodes of its proof term, counted
as distinct subterms (up), both logarithmic. 41,284 have more nodes than characters; written
out as trees the terms hold 263 times the nodes, and 43,773 do. An option sets the whole theorem,
statement and proof, against type and proof term: 21,999 then have more nodes than characters.
Two are named on the canvas:
Int.max_min_distrib_left 8 characters, by omega 8,480 nodes
funext 219 characters, a written term 89 nodes
rows the same theorems by the way they were proved: how many, and the median of their nodes per
character, marked on a logarithmic axis
1 10 100
a written term 19,070 1.83 | ●
a term with tactic blocks 1,890 3.08 | ●
other tactics 16,610 3.33 | ●
simp 7,225 3.80 | ●
decide 234 5.56 | ●
grind 8 31.2 | ●
omega 86 118 | ●
(the live figure needs JavaScript and loads about 1.1 MB of data)
For nine in ten of the theorems that the library's sources write out, the proof term has more distinct subterms than the proof has characters. A written term reaches the kernel at about two distinct subterms for each character of proof; the two words by omega, eight characters on one line, reach it as a median of 997, and for Int.max_min_distrib_left as 8,480. A proof that can be read, the derivation of function extensionality from quotients, whose source stands in Section 7.3, has 219 characters for a term of 89 distinct subterms. Here are those eight characters at work.
protected theorem max_min_distrib_left (a b c : Int) : max a (min b c) = min (max a b) (max a c) := by omega
Two details explain how those numbers are measured. Lean 4.35.0's core library contains 89,360 theorems in all, 44,237 of which are auto-generated by Lean with no source span of their own; the plot shows the 45,123 human-written theorems, 41,284 of which have more distinct subterms than source characters. Because Lean stores terms in memory as directed acyclic graphs that share repeated subexpressions, counting distinct subterms (including auxiliary declarations split off by Lean) gives a much smaller number than unfolding every shared subterm into a tree: unfolded as trees, the same 45,123 proof terms contain 263 times as many nodes overall, and the 8,480 distinct subterms behind Int.max_min_distrib_left balloon to 1,324,880 tree nodes. Each theorem's proof style in the figure is classified from its source syntax rather than by querying Lean. Nor does term size alone measure how hard the kernel works: a proof by decide hands over a tiny term that forces the kernel to run an arbitrarily long computation (Section 10.4).
The kernel stays small enough to audit despite this volume because verifying a complete term is vastly simpler than reconstructing an incomplete one. The reference manual characterizes the kernel by everything it omits:
Lean's trusted kernel is a small, robust implementation of a type checker for the core type theory. It does not include a syntactic termination checker, nor does it perform unification; termination is guaranteed by elaborating all recursive functions into uses of primitive recursors, and unification is expected to have already been carried out by the elaborator. Before new inductive types or definitions are added to the environment by the command or term elaborators, they must be checked by the kernel to guard against potential bugs in elaboration.
—"The Lean Language Reference", edition for Lean 4.35.0. Section 2.3, "The Kernel", opening paragraph.
The kernel performs no unification because every hole is already filled; it runs no type class search because every instance arrives as an explicit argument; and it needs neither a match compiler nor a termination checker because all definitions arrive translated into primitive recursors. Only one job is performed twice, first in the elaborator and again in the kernel: type-checking and definitional-equality reduction. When the elaborator accepted rfl as a proof of 2 + 2 = 4, it handed the kernel @Eq.refl.{1} Nat (2 + 2), whose immediate type is 2 + 2 = 2 + 2; to verify that this term inhabits the claimed type 2 + 2 = 4, the kernel runs its own reduction rules from Section 6.3. The two programs do not unfold the exact same definitions. If a definition is marked @[irreducible] def two : Nat := 2, Lean rejects example : two = 2 := rfl with the type mismatch of Section 9.3, because @[irreducible] tells the elaborator's unifier not to spend time unfolding two during search. Overriding that search throttle via by with_unfolding_all rfl produces the kernel term Eq.refl two, which the kernel accepts without hesitation because @[irreducible] is an elaboration hint, not a logical barrier, and the kernel unfolds whatever definitions are needed to decide definitional equality.
A line of Lean is not the term that is checked. The elaborator solves for everything the line leaves out, by rules that are heuristic, incomplete and dependent on what is in scope, and none of this has to be believed, because the kernel checks the term that comes out. What no checker can say is whether that term is the statement its author had in mind.
Remark 9.8.1 (what the check does not reach). The statement of a theorem goes through the same machinery as its proof, and before it. Which type a numeral has, where the coercions sit, which instance gives + its meaning and which universe a type lives in are all settled by the elaborator, in the scope of the file. The kernel then checks that the proof term has the type that came out. To know what was proved one reads that type, with the options of Section 9.9 or as Section 13 does, which begins its chain of trust with the statement.
In Lean
Three options show what the elaborator did with a line. pp.explicit prints every argument, pp.universes every level, and trace.Meta.synthInstance the search for an instance, which the command #synth runs by itself; trace.Meta.isDefEq does the same for unification, at greater length.
set_option pp.explicit true in
#check (2 : Nat) + 2 = 4
set_option pp.universes true in
#check (2 : Nat) + 2 = 4
set_option trace.Meta.synthInstance true in
#synth HAdd Nat Nat _
@Eq Nat
(@HAdd.hAdd Nat Nat Nat (@instHAdd Nat instAddNat) (@OfNat.ofNat Nat (nat_lit 2) (instOfNatNat (nat_lit 2)))
(@OfNat.ofNat Nat (nat_lit 2) (instOfNatNat (nat_lit 2))))
(@OfNat.ofNat Nat (nat_lit 4) (instOfNatNat (nat_lit 4))) : Prop
Eq.{1} (HAdd.hAdd.{0, 0, 0} 2 2) 4 : Prop
instHAdd
[Meta.synthInstance] ✅️ HAdd Nat Nat Nat
[Meta.synthInstance] ✅️ new goal HAdd Nat Nat _tc.1
[Meta.synthInstance.instances] #[@instHAdd]
[Meta.synthInstance.apply] ✅️ apply @instHAdd to HAdd Nat Nat Nat
[Meta.synthInstance.tryResolve] ✅️ HAdd Nat Nat Nat ≟ HAdd Nat Nat Nat
[Meta.synthInstance] ✅️ new goal Add Nat
[Meta.synthInstance.instances] #[@Lean.Grind.AddCommMonoid.toAdd, @Lean.Grind.Semiring.toAdd, instAddNat]
[Meta.synthInstance.apply] ✅️ apply instAddNat to Add Nat
[Meta.synthInstance.tryResolve] ✅️ Add Nat ≟ Add Nat
[Meta.synthInstance.answer] ✅️ Add Nat
[Meta.synthInstance.resume] ✅️ propagating Add Nat to subgoal Add Nat of HAdd Nat Nat Nat
[Meta.synthInstance.resume] size: 1
[Meta.synthInstance.answer] ✅️ HAdd Nat Nat Nat
[Meta.synthInstance] result instHAdd
In the #synth trace, each subgoal opens with an array of candidate instances, tried from right to left; apply tests a candidate, ≟ unifies the subgoal with that instance's conclusion, and resume delivers a solved subgoal back to the parent instance waiting on it. The placeholder _tc.1 on the second line is HAdd's outParam result type from Section 9.4, left open until instHAdd determines it.
When the elaborator gives up, its message names the mechanism that failed.
| the line | Lean says | what gave up |
|---|---|---|
example (x : Nat) : 0 + x = x := rfl |
Type mismatch: ?m.9 = ?m.9 against 0 + x = x |
unification: no assignment that its rules can find makes the two types equal (Section 9.3) |
example (s : String) : Nat := s |
Type mismatch: String against Nat |
unification, and after it the search for a coercion from String to Nat (Section 9.5) |
example : [] = [] := rfl |
don't know how to synthesize implicit argument `α` |
nothing to go on: a hole is left that no equation determines, the type of the lists' elements (Section 9.2) |
example := fun x => toString x |
typeclass instance problem is stuck: ToString ?m.6 |
an instance problem put aside every time, its type being unknown to the end (Section 9.2) |
#synth Inhabited (Fin 0) |
failed to synthesize: Inhabited (Fin 0) |
the search for an instance ran and came back empty (Section 9.4) |
the prod' of Section 9.6 |
stuck at solving universe constraint |
a level equation with several solutions and no best one (Section 9.6) |
One kind of metavariable in Definition 9.2.1 has not yet been put to work: the synthetic-opaque hole representing the goal of a by block. Tactics are programs that construct proof terms to fill those goals, and Section 10 asks of each major tactic what term it actually hands to the kernel.