A compiler translates a program from one language into another, and you trust it every time you run anything. When it is wrong, the source code you reviewed is not the code that runs. To prove a compiler correct you need two things that informal practice leaves vague: a precise meaning for programs in both languages, called a semantics, and a theorem saying the translation preserves that meaning.
This has been done for real compilers. CompCert, a C compiler verified in the Rocq (Coq) proof assistant by Xavier Leroy and colleagues, comes with a proof that the assembly it produces behaves as the C source says. When Yang, Chen, Eide and Regehr tested many C compilers with random programs in 2011, they found wrong-code bugs in every compiler they tried except in the verified parts of CompCert (PLDI 2011). This lecture builds the same argument at toy scale: a language of arithmetic expressions, a stack machine, a compiler between them, and a correctness proof by induction. It ends with commands, loops, and the logic used to reason about them.
Notebook and cheatsheet
There is no notebook for this lecture; Homework 4 extends the language and re-proves the compiler. The code is also in
lean/LeanFV/Programs/StackMachine.lean. Cheatsheet: Semantics and compiler correctness, Hoare triples and Std.Do, induction and its goal states.
Syntax and an evaluator
A program is text, but a compiler works on its structure. The abstract syntax of a language is that structure as a tree, with the parentheses and spacing already resolved. In Lean an abstract syntax is an inductive type, one constructor per kind of node:
import Std.Tactic.Do
import Std.WP
abbrev Env := String → Nat
inductive AExp where
| num : Nat → AExp
| var : String → AExp
| plus : AExp → AExp → AExp
deriving Repr
def aeval : AExp → Env → Nat
| .num n, _ => n
| .var x, s => s x
| .plus a b, s => aeval a s + aeval b s(The two import lines are needed only for the last section.) An environment s : Env gives
every variable a value. The expression x + 3 is the tree AExp.plus (.var "x") (.num 3),
and aeval gives it a meaning by recursion on the tree: in an environment where every variable
is 4, aeval returns 7. A semantics given by a recursive function like this is called
denotational: each expression denotes a function from environments to numbers.
Definition 9.1 (Semantics).A semantics of a language assigns each program a mathematical meaning. A denotational semantics is a function from programs to meanings. An operational semantics describes how a program runs, as rules relating a program and a starting state to a result.
Big-step semantics as an inductive relation
The operational kind is written as inference rules. Read
These are called big-step rules because one judgment covers the whole evaluation. In Lean a
set of rules is an inductive relation: an inductive type whose values are derivations, with
one constructor per rule (Lecture 4 built the predicate Ev the same way).
inductive BigStep : AExp → Env → Nat → Prop
| num (n : Nat) (s : Env) : BigStep (.num n) s n
| var (x : String) (s : Env) : BigStep (.var x) s (s x)
| plus {a b : AExp} {s : Env} {m n : Nat} :
BigStep a s m → BigStep b s n → BigStep (.plus a b) s (m + n)We now have two semantics of the same language, one of each kind in the definition of
semantics (Definition 9.1), and they had better agree. One direction is induction on the
expression; the other is induction on the derivation, which induction h does when h is a
proof of BigStep e s n:
theorem bigStep_of_aeval (e : AExp) (s : Env) :
BigStep e s (aeval e s) := by
induction e with
| num n => exact .num n s
| var x => exact .var x s
| plus a b iha ihb => exact .plus iha ihb
theorem aeval_of_bigStep {e : AExp} {s : Env} {n : Nat}
(h : BigStep e s n) : aeval e s = n := by
induction h with
| num => rfl
| var => rfl
| plus _ _ iha ihb => simp [aeval, iha, ihb]Why bother with a relation when the function is simpler? For expressions there is no reason;
they always terminate. For a language with loops there is. A Lean function must terminate
(Lecture 8), but a while loop need not, so its meaning cannot be a plain function. A relation
has no such problem: a program that loops forever is simply related to no final state. The
command language at the end of this lecture is defined that way.
A stack machine and its compiler
The target is a stack machine, the design behind the JVM and WebAssembly. It has a stack of numbers and three instructions: push a constant, push the value of a variable, and replace the top two numbers by their sum.
inductive Instr where
| loadi : Nat → Instr
| load : String → Instr
| add : Instr
deriving Repr
abbrev Stack := List Nat
def exec1 : Instr → Env → Stack → Stack
| .loadi n, _, stk => n :: stk
| .load x, s, stk => s x :: stk
| .add, _, m :: n :: stk => (n + m) :: stk
| .add, _, stk => stk
def exec : List Instr → Env → Stack → Stack
| [], _, stk => stk
| i :: is, s, stk => exec is s (exec1 i s stk)The last case of exec1 is a junk value, an arbitrary answer for an input that should never
occur: add on a stack with fewer than two numbers does nothing, because a Lean function must
return something. The
correctness theorem will show that compiled code never reaches it. The compiler walks the tree
in post-order, so both operands are on the stack before add runs:
def compile : AExp → List Instr
| .num n => [.loadi n]
| .var x => [.load x]
| .plus a b => compile a ++ compile b ++ [.add]
#eval compile (.plus (.var "x") (.num 3))
#eval exec (compile (.plus (.var "x") (.num 3))) (fun _ => 4) []The first line prints [Instr.load "x", Instr.loadi 3, Instr.add] and the second prints [7],
the same 7 that aeval computed. The claim that this always happens is a square of maps that
commutes: from an expression, going right then down gives the same stack as going down then
right.
Theorem 9.1 (Compiler correctness).For every expression
and environment , exec (compile e) s [] = [aeval e s].
Why the obvious induction fails
Try to prove compiler correctness (Theorem 9.1) exactly as stated, by induction on
e. The two leaf cases are rfl. For plus a b, split the code with a lemma exec_append
(running p ++ q is running p, then q; it is proved by induction on p) and use the
induction hypothesis for a:
theorem exec_append (p q : List Instr) (s : Env) (stk : Stack) :
exec (p ++ q) s stk = exec q s (exec p s stk) := by
induction p generalizing stk with
| nil => rfl
| cons i is ih => exact ih (exec1 i s stk)theorem compile_naive (e : AExp) (s : Env) :
exec (compile e) s [] = [aeval e s] := by
induction e with
| num n => rfl
| var x => rfl
| plus a b iha ihb =>
rw [compile, exec_append, exec_append, iha]Lean stops with unsolved goals, and the goal shows why:
ihb : exec (compile b) s [] = [aeval b s]
⊢ exec [Instr.add] s (exec (compile b) s [aeval a s]) = [aeval (a.plus b) s]The code for b runs on the stack [aeval a s], because the value of a is already there.
But the induction hypothesis ihb only talks about the empty stack. The statement we are
proving is too weak to be its own induction hypothesis. This is the most common reason an
induction gets stuck (Lecture 4 met it with an accumulator), and the cure is always the same:
prove something stronger, quantified
over everything that changes between the recursive calls. Here two things change: the stack
the code starts on, and the code that runs after it.
theorem compile_correct_gen (e : AExp) (rest : List Instr)
(s : Env) (stk : Stack) :
exec (compile e ++ rest) s stk = exec rest s (aeval e s :: stk) := by
induction e generalizing rest stk with
| num n => rfl
| var x => rfl
| plus a b iha ihb =>
rw [compile, List.append_assoc, List.append_assoc, iha, ihb]
rfl
theorem compile_correct (e : AExp) (s : Env) :
exec (compile e) s [] = [aeval e s] := by
have h := compile_correct_gen e [] s []
rw [List.append_nil] at h
exact hgeneralizing rest stk makes the induction hypotheses hold for every rest and stk, not
only the ones in the goal. In the plus case, iha is used with rest := compile b ++ ([add] ++ rest),
and ihb with the stack aeval a s :: stk. After both rewrites the machine holds
aeval b s :: aeval a s :: stk with [add] ++ rest still to run, and one step of exec makes
the two sides identical, so rfl closes the goal. The original statement is the special case
rest := [], stk := []: after rewriting compile e ++ [] to compile e, the right side is
exec [] s [aeval e s], which is [aeval e s] by the definition of exec, so exact accepts
it.
Remark 9.1 (What the theorem does not say).Compiler correctness relates two definitions,
aevalandexec. If either one is not what we mean by the language or the machine, the theorem proves agreement with the wrong thing. Real verified compilers face the same gap: CompCert’s proof starts from a formal semantics of C written by its authors, and ends at a model of the processor, not at the silicon. Our machine also computes with unbounded natural numbers, where real hardware wraps around at; Lecture 10 shows how to reason about that.
The remark on what the theorem does not say (Remark 9.1) is the compiler version of
Lecture 1’s warning that the kernel checks the statement you wrote. The definitions of the two
semantics are part of what you trust, so keep them short enough to read, and test them with
#eval on examples you can compute by hand, as we did above. The generalised statement also explains the junk case: add always
finds its two operands, because they were pushed by the code before it.
Commands, Hoare triples and loop invariants
Real programs have state that changes, sequencing, and loops. Here is a small language of
commands in the style of IMP, the language of Nipkow and Klein’s Concrete Semantics. To keep
it short, the right-hand sides of assignments and the loop tests are Lean functions of the
environment rather than AExp trees, as in the WHILE language of the Hitchhiker’s Guide:
def Env.set (s : Env) (x : String) (n : Nat) : Env :=
fun y => if y = x then n else s y
inductive Com where
| skip : Com
| assign : String → (Env → Nat) → Com
| seq : Com → Com → Com
| whileDo : (Env → Bool) → Com → Com
inductive Exec : Com → Env → Env → Prop
| skip (s : Env) : Exec .skip s s
| assign (x : String) (f : Env → Nat) (s : Env) :
Exec (.assign x f) s (s.set x (f s))
| seq {c d : Com} {s t u : Env} :
Exec c s t → Exec d t u → Exec (.seq c d) s u
| whileTrue {b : Env → Bool} {c : Com} {s t u : Env} :
b s = true → Exec c s t → Exec (.whileDo b c) t u →
Exec (.whileDo b c) s u
| whileFalse {b : Env → Bool} {c : Com} {s : Env} :
b s = false → Exec (.whileDo b c) s sExec c s t says that c, started in state s, stops in state t. A loop that never stops
has no Exec derivation at all, which is exactly the point made earlier about relations.
Definition 9.2 (Hoare triple).For predicates
on states and a command , the Hoare triple holds if every run of that starts in a state satisfying and stops ends in a state satisfying . This is partial correctness: a run that never stops satisfies every triple.
A Hoare triple (Definition 9.2) is one line of Lean, a statement about all runs:
def Hoare (P : Env → Prop) (c : Com) (Q : Env → Prop) : Prop :=
∀ s t, P s → Exec c s t → Q tTony Hoare’s insight in 1969 was that triples obey simple rules, one per command, so that a
proof about a program follows the program’s shape. The interesting rule is the one for loops.
A loop invariant
In our embedding the rule is a theorem, proved by induction on the derivation of Exec. The
generalize step names the loop, so that the induction can see that only the two while
rules apply:
theorem hoare_while {I : Env → Prop} {b : Env → Bool} {c : Com}
(hc : Hoare (fun s => I s ∧ b s = true) c I) :
Hoare I (.whileDo b c) (fun s => I s ∧ b s = false) := by
intro s t hs h
generalize hw : Com.whileDo b c = w at h
induction h with
| skip => cases hw
| assign => cases hw
| seq => cases hw
| whileTrue hb hbody _ _ ih2 =>
cases hw
exact ih2 (hc _ _ ⟨hs, hb⟩ hbody) rfl
| whileFalse hb =>
cases hw
exact ⟨hs, hb⟩The course library also proves the rules for skip, assignment, sequencing and weakening.
Finding the invariant is the creative step; everything else is bookkeeping. A useful
invariant is usually a weakened form of the postcondition that mentions the loop’s progress:
for a loop that adds up a list, “the accumulator is the sum of the part already processed”.
When the loop stops, that part is the whole list, and the invariant becomes the postcondition.
Proving that the loop does stop (total correctness) needs one more ingredient, a measure that
each iteration decreases, exactly like termination_by in Lecture 8. That bookkeeping
can be automated by a verification condition generator, which walks a program with its
invariants and emits the plain logical facts that remain to be proved.
Lean ships one for its own do-notation programs. The library Std.Do, previewed in
Lean 4.22, introduced the tactic mvcgen
(reference manual). In
Lean 4.35, mvcgen still works but warns that it is deprecated: use vcgen instead. The
cheatsheet card keeps mvcgen with Std.Do’s triples. Its successor vcgen is marked
experimental (hence the set_option) and works on the newer Std.WP framework: both tactics
need import Std.Tactic.Do, and vcgen also needs import Std.WP (the first block of this
page has both). Applied to a Std.Do triple without Std.WP, vcgen stops with
Unknown constant `Std.WP.Triple.intro` . Here it verifies a loop that sums a list, with
the invariant “the accumulator is the sum of the elements seen so far”:
def mySum (l : List Nat) : Nat := Id.run do
let mut acc := 0
for x in l do
acc := acc + x
return acc
open Std.WP in
set_option experimental.vcgen true in
theorem mySum_correct (l : List Nat) : mySum l = l.sum := by
generalize h : mySum l = r
apply Id.of_run_eq_wp h (fun r => r = l.sum)
vcgen invariants
· fun pref _ acc => acc = pref.sum
with finish
#print axioms mySum_correctThe invariant receives the list prefix already processed (pref), the rest, and the current
accumulator. vcgen leaves two verification conditions, which you can see by replacing
with finish with trace_state followed by all_goals sorry: the invariant holds at the start
(⊢ 0 = [].sum), and one iteration preserves it (from b✝ = pref✝.sum, prove
acc = (pref✝ ++ [cur✝]).sum where acc is b✝ + cur✝). The third condition, that the
invariant for the whole list gives the postcondition, is simple enough for vcgen to close by
itself. The finish step of grind proves the other two, and the audit reports only the three
standard axioms. Change the invariant to acc = 0 and finish fails twice, printing the facts
it had: one iteration no longer preserves the invariant, and at the end acc = 0 does not give
acc = l.sum. A wrong invariant shows up as an unprovable verification condition, not as a
wrong theorem.
Try this
- Add a constructor
times : AExp → AExp → AExp, an instructionmul, and re-provecompile_correct_gen. Which parts of the proof change? (This is Homework 4.) - Prove that
BigStepis deterministic:BigStep e s m → BigStep e s n → m = n. Induct on the first derivation and usecaseson the second. - State compiler correctness without generalising the stack but with
rest. Does the induction go through? Explain the outcome in terms of the stuck goal above. - Write a
doprogram that computes2 * nby a loop that adds 2 a total ofntimes, and verify it withvcgenand an invariant of your choice.
Readings
- Tobias Nipkow and Gerwin Klein, Concrete Semantics with Isabelle/HOL, Springer 2014: chapter 3 (the same stack machine and compiler), chapters 7 and 12 (IMP, Hoare logic).
- Anne Baanen, Alexander Bentkamp, Jasmin Blanchette, Johannes Hölzl and Jannis Limperg, The Hitchhiker’s Guide to Logical Verification, 2023 edition: the chapters on operational semantics and Hoare logic, in Lean.
- C. A. R. Hoare, “An axiomatic basis for computer programming”, Communications of the ACM 12(10), 1969, doi 10.1145/363235.363259.
- Xavier Leroy, “Formal verification of a realistic compiler”, Communications of the ACM 52(7), 2009, doi 10.1145/1538788.1538814, and the CompCert site.
- The Lean reference manual, The
mvcgentactic, forStd.Dospecifications and invariants.