/- Lecture 3 — the soundness of the kernel from the directory kernel/, proved in Lean 4. The kernel (kernel/kernel.py) receives a proof — a tree of the rules Refl, Symm, Trans, CongrArg, Inst — and computes which equation this proof justifies (`conclusion`). We rewrite it in Lean (`check`) and prove: if every fact of the environment is true in an algebra A and the kernel accepts a proof with the conclusion l = r, then l = r is true in A for every valuation of the variables. The careful proof exposed two holes in the Python kernel (now fixed); in Lean both are impossible by construction — see the comments at `Term` and `Term.decEq`. No Mathlib: Lean alone is enough. Check: lean KernelSoundness.lean Compiled without errors: Lean 4.33.1. -/ /-! ## 1. Terms -/ /-- A term: a variable, or a symbol applied to a list of arguments; a constant is a symbol without arguments. Python: `'x'`, `'0'`, `('+', 'x', ('n', 'x'))`; Lean: `var "x"`, `app "0" []`, `app "+" [var "x", app "n" [var "x"]]`. A variable and a constant are different constructors, so they cannot be confused. In Python both are strings — hence the first hole: the constant 0 declared as a variable of the theorem x * 0 = 0 gave x * y = y. A term contains a list of terms (a nested type), so every function on terms has a twin for lists — that is how Lean computes on them structurally. -/ inductive Term where | var (x : String) | app (f : String) (args : List Term) mutual /-- Are two terms equal? (For a nested type Lean does not derive this by itself.) The result is not a bare "yes/no" but a proof of `a = b` or a proof of `a ≠ b`, so the comparison of the middles in Trans cannot lie — in Python a subclass of `str` with its own `==` fooled it. -/ def Term.decEq : (a b : Term) → Decidable (a = b) | .var x, .var y => if h : x = y then isTrue (by rw [h]) else isFalse (fun e => h (Term.var.inj e)) | .app f as, .app g bs => if h : f = g then match Term.decEqAll as bs with | isTrue h' => isTrue (by rw [h, h']) | isFalse h' => isFalse (fun e => h' (Term.app.inj e).2) else isFalse (fun e => h (Term.app.inj e).1) | .var _, .app _ _ => isFalse nofun | .app _ _, .var _ => isFalse nofun def Term.decEqAll : (as bs : List Term) → Decidable (as = bs) | [], [] => isTrue rfl | a :: as, b :: bs => match Term.decEq a b, Term.decEqAll as bs with | isTrue h₁, isTrue h₂ => isTrue (by rw [h₁, h₂]) | isFalse h₁, _ => isFalse (fun e => h₁ (List.cons.inj e).1) | _, isFalse h₂ => isFalse (fun e => h₂ (List.cons.inj e).2) | [], _ :: _ => isFalse nofun | _ :: _, [] => isFalse nofun end instance : DecidableEq Term := Term.decEq /-! ## 2. Algebras and values of terms -/ /-- An algebra: a set `α` and an interpretation of the symbols. Every symbol has a value for every list of arguments, also an ill-formed one (e.g. `+` with one argument) — then an arbitrary one. That is why soundness needs no signature check (Python: `Kernel.term`): every term has a value, and the signature only says in which language we state theorems. -/ structure Algebra (α : Type) where fn : String → List α → α mutual /-- The value of a term in the algebra `A` under the valuation `v` of the variables. -/ def Term.eval {α : Type} (A : Algebra α) (v : String → α) : Term → α | .var x => v x | .app f args => A.fn f (Term.evalAll A v args) def Term.evalAll {α : Type} (A : Algebra α) (v : String → α) : List Term → List α | [] => [] | t :: ts => t.eval A v :: Term.evalAll A v ts end /-! ## 3. Substitution -/ mutual /-- Substitution: the variable `x` goes to the term `σ x` (Python: `subst`). Constants are not touched by a substitution: they are `app`, not `var`. -/ def Term.subst (σ : String → Term) : Term → Term | .var x => σ x | .app f args => .app f (Term.substAll σ args) def Term.substAll (σ : String → Term) : List Term → List Term | [] => [] | t :: ts => t.subst σ :: Term.substAll σ ts end /-- `σ` changed at one place: `x` goes to `t` (Python: `s[x] = t`). `update .var z a` changes only `z` to `a` (Python: `{z: a}`). -/ def update (σ : String → Term) (x : String) (t : Term) : String → Term := fun y => if y = x then t else σ y /-- Like `dict(zip(variables, args))`: variables outside the list stay (`s.get(t, t)`), and when a variable repeats, the later pair wins. -/ def substitution (vars : List String) (args : List Term) : String → Term := (vars.zip args).foldl (fun σ (x, t) => update σ x t) Term.var mutual /-- The substitution lemma: the value of `t[σ]` under `v` is the value of `t` under the valuation `x ↦ value of σ x`. -/ theorem eval_subst {α : Type} (A : Algebra α) (v : String → α) (σ : String → Term) : ∀ t : Term, (t.subst σ).eval A v = t.eval A (fun x => (σ x).eval A v) | .var _ => rfl | .app f args => congrArg (A.fn f) (evalAll_subst A v σ args) theorem evalAll_subst {α : Type} (A : Algebra α) (v : String → α) (σ : String → Term) : ∀ ts : List Term, Term.evalAll A v (Term.substAll σ ts) = Term.evalAll A (fun x => (σ x).eval A v) ts | [] => rfl | t :: ts => by show Term.eval A v (t.subst σ) :: Term.evalAll A v (Term.substAll σ ts) = _ rw [eval_subst A v σ t, evalAll_subst A v σ ts]; rfl end mutual /-- The value of a term depends only on the values of its variables. -/ theorem eval_ext {α : Type} (A : Algebra α) {v w : String → α} (h : ∀ x, v x = w x) : ∀ t : Term, t.eval A v = t.eval A w | .var x => h x | .app f args => congrArg (A.fn f) (evalAll_ext A h args) theorem evalAll_ext {α : Type} (A : Algebra α) {v w : String → α} (h : ∀ x, v x = w x) : ∀ ts : List Term, Term.evalAll A v ts = Term.evalAll A w ts | [] => rfl | t :: ts => by show Term.eval A v t :: Term.evalAll A v ts = _ rw [eval_ext A h t, evalAll_ext A h ts]; rfl end /-! ## 4. Proofs and the kernel -/ /-- A proof: a tree of five rules, named as in kernel.py. -/ inductive Proof where | Refl (t : Term) -- t = t | Symm (p : Proof) -- from a = b follows b = a | Trans (p q : Proof) -- from a = b and b = c follows a = c | CongrArg (z : String) (C : Term) (p : Proof) -- from a = b follows C[z:=a] = C[z:=b] | Inst (name : String) (args : List Term) -- the fact `name` for concrete terms /-- A fact `∀ vars, lhs = rhs` (Python: `(variables, left, right)`). The list `vars` holds names of variables: "0" is here the variable `var "0"`, not the constant 0. -/ structure Fact where vars : List String lhs : Term rhs : Term /-- An environment: name ↦ fact (Python: the dict `facts`); `none` — no such fact. -/ abbrev Env := String → Option Fact /-- The kernel: the equation a proof justifies (Python: `Kernel.conclusion`); `none` where Python raises `ProofError`. No signature check (see `Algebra`) and no question whether `z` in CongrArg is a variable (it always is). We check the number of arguments in Inst like Python, although soundness does not need it: every substitution preserves truth. -/ def check (Γ : Env) : Proof → Option (Term × Term) | .Refl t => some (t, t) | .Symm p => match check Γ p with | some (a, b) => some (b, a) | none => none | .Trans p q => match check Γ p with | some (a, b) => match check Γ q with | some (b', c) => if b = b' then some (a, c) else none -- the middles must be equal | none => none | none => none | .CongrArg z C p => match check Γ p with | some (a, b) => some (C.subst (update .var z a), C.subst (update .var z b)) | none => none | .Inst name args => match Γ name with | some f => if args.length = f.vars.length then some (f.lhs.subst (substitution f.vars args), f.rhs.subst (substitution f.vars args)) else none -- wrong number of arguments | none => none -- unknown fact /-- The names of the facts a proof refers to (Python: `used_facts`). -/ def used : Proof → List String | .Refl _ => [] | .Symm p => used p | .Trans p q => used p ++ used q | .CongrArg _ _ p => used p | .Inst name _ => [name] /-! ## 5. Truth of equations -/ /-- `l = r` is true in `A`: both sides have equal values under every valuation. -/ def Holds {α : Type} (A : Algebra α) (l r : Term) : Prop := ∀ v : String → α, l.eval A v = r.eval A v /-- `A` is a model of the environment `Γ`: every fact of `Γ` is true in `A`. -/ def Model {α : Type} (A : Algebra α) (Γ : Env) : Prop := ∀ name f, Γ name = some f → Holds A f.lhs f.rhs section Lemmas variable {α : Type} {A : Algebra α} {a b c : Term} theorem Holds.symm (h : Holds A a b) : Holds A b a := fun v => (h v).symm theorem Holds.trans (h₁ : Holds A a b) (h₂ : Holds A b c) : Holds A a c := fun v => (h₁ v).trans (h₂ v) /-- A substitution in a true equation gives a true equation (the rule Inst). -/ theorem Holds.subst (σ : String → Term) (h : Holds A a b) : Holds A (a.subst σ) (b.subst σ) := fun v => by rw [eval_subst, eval_subst]; exact h _ /-- The context lemma (the rule CongrArg): from `a = b` follows `C[z:=a] = C[z:=b]`. -/ theorem Holds.context (z : String) (C : Term) (h : Holds A a b) : Holds A (C.subst (update .var z a)) (C.subst (update .var z b)) := fun v => by rw [eval_subst, eval_subst] apply eval_ext intro y unfold update split · exact h v -- y = z: the values of a and b are equal · rfl -- another variable: the same on both sides end Lemmas /-! ## 6. The soundness theorem -/ /-- **Relative soundness** (the counterpart of `#print axioms`): it is enough that `A` satisfies the facts the proof `d` really uses — `used d`, from which Python builds the field `assumptions`. Induction on the proof tree: one case for each rule. -/ theorem relative_soundness {α : Type} (A : Algebra α) (Γ : Env) (d : Proof) {l r : Term} (hu : ∀ name ∈ used d, ∀ f, Γ name = some f → Holds A f.lhs f.rhs) (h : check Γ d = some (l, r)) : Holds A l r := by induction d generalizing l r with | Refl t => cases h -- l and r are t exact fun _ => rfl | Symm p ih => simp only [check] at h split at h next a b hp => cases h; exact (ih hu hp).symm next => cases h | Trans p q ihp ihq => simp only [check] at h split at h next a b hp => split at h next b' c hq => split at h next hb => -- hb : b = b' cases h; subst hb exact (ihp (fun m hm => hu m (List.mem_append_left _ hm)) hp).trans (ihq (fun m hm => hu m (List.mem_append_right _ hm)) hq) next => cases h next => cases h next => cases h | CongrArg z C p ih => simp only [check] at h split at h next a b hp => cases h; exact (ih hu hp).context z C next => cases h | Inst name args => simp only [check] at h split at h next f hf => split at h next => cases h; exact (hu name (List.mem_singleton_self _) f hf).subst _ next => cases h next => cases h /-- **The soundness theorem of the kernel.** If `A` is a model of `Γ` and the kernel accepts the proof `d` with the conclusion `l = r`, then the equation `l = r` is true in `A`. -/ theorem soundness {α : Type} (A : Algebra α) (Γ : Env) (hΓ : Model A Γ) (d : Proof) {l r : Term} (h : check Γ d = some (l, r)) : Holds A l r := relative_soundness A Γ d (fun name _ f hf => hΓ name f hf) h /-! ## 7. The environment grows, and its facts stay true -/ /-- Adding a fact under a name (Python: `self.facts[name] = …`). -/ def extend (Γ : Env) (name : String) (f : Fact) : Env := fun m => if m = name then some f else Γ m /-- `Kernel.axiom`: adds a fact without a proof, provided the name is free. We do not check that `vars` covers all the variables of the fact: `Holds` quantifies over all of them anyway. -/ def addAxiom (Γ : Env) (name : String) (f : Fact) : Option Env := if (Γ name).isSome then none else some (extend Γ name f) /-- `Kernel.theorem`: adds a fact like an axiom, but only when the kernel computes from the proof exactly the announced equation. -/ def addTheorem (Γ : Env) (name : String) (f : Fact) (d : Proof) : Option Env := if check Γ d = some (f.lhs, f.rhs) then addAxiom Γ name f else none /-- The environments that can be built from `Γ₀` by adding axioms from the allowed set `Ax` and theorems accepted by the kernel. -/ inductive Reachable (Ax : Fact → Prop) (Γ₀ : Env) : Env → Prop | start : Reachable Ax Γ₀ Γ₀ | ax {Γ Γ' : Env} {name : String} {f : Fact} : Reachable Ax Γ₀ Γ → Ax f → addAxiom Γ name f = some Γ' → Reachable Ax Γ₀ Γ' | thm {Γ Γ' : Env} {name : String} {f : Fact} {d : Proof} : Reachable Ax Γ₀ Γ → addTheorem Γ name f d = some Γ' → Reachable Ax Γ₀ Γ' /-- Adding to a model a fact true in `A` gives a model. -/ theorem model_extend {α : Type} {A : Algebra α} {Γ Γ' : Env} {name : String} {f : Fact} (hΓ : Model A Γ) (hf : Holds A f.lhs f.rhs) (h : addAxiom Γ name f = some Γ') : Model A Γ' := by unfold addAxiom at h split at h <;> cases h -- name taken: h is false intro m g hg unfold extend at hg split at hg next => cases hg; exact hf -- m is the new name next => exact hΓ m g hg -- an old fact /-- **The environment invariant.** If `A` satisfies the initial facts and the allowed axioms, then it satisfies every fact of every reachable environment. Theorems need no assumption: their truth is guaranteed by the kernel (`soundness`). -/ theorem invariant {α : Type} (A : Algebra α) {Ax : Fact → Prop} {Γ₀ Γ : Env} (hAx : ∀ f, Ax f → Holds A f.lhs f.rhs) (h₀ : Model A Γ₀) (h : Reachable Ax Γ₀ Γ) : Model A Γ := by induction h with | start => exact h₀ | ax _ hf hd ih => exact model_extend ih (hAx _ hf) hd | @thm Γ Γ' name f d _ hd ih => unfold addTheorem at hd split at hd next hc => exact model_extend ih (soundness A Γ ih d hc) hd next => cases hd /-! ## 8. An example: the two-element Boolean algebra -/ /-- Printing like `show` in syntax.py: the fewest parentheses, `*` binds tighter than `+`. -/ def Term.pretty : Term → Nat → String | .var x, _ => x | .app f [], _ => f | .app "n" [a], _ => s!"n({a.pretty 0})" | .app "+" [a, b], o => let s := s!"{a.pretty 0} + {b.pretty 1}"; if o ≥ 1 then s!"({s})" else s | .app "*" [a, b], o => let s := s!"{a.pretty 1} * {b.pretty 2}"; if o ≥ 2 then s!"({s})" else s | .app f args, _ => f ++ "(" ++ ", ".intercalate (args.map (·.pretty 0)) ++ ")" instance : Repr Term := ⟨fun t _ => t.pretty 0⟩ namespace Example -- Terms written as in boolean.py: x + y, x * y, n x, 0, 1. instance : Add Term := ⟨fun a b => .app "+" [a, b]⟩ instance : Mul Term := ⟨fun a b => .app "*" [a, b]⟩ instance : OfNat Term 0 := ⟨.app "0" []⟩ instance : OfNat Term 1 := ⟨.app "1" []⟩ def n (t : Term) : Term := .app "n" [t] def x : Term := .var "x" def y : Term := .var "y" def z : Term := .var "z" /-- The algebra {false, true}: `+` is `||`, `*` is `&&`, `n` is `!`, `0` is false, `1` is true; ill-formed applications get false. -/ def bool2 : Algebra Bool where fn f args := match args with | [] => if f = "1" then true else false | [a] => if f = "n" then !a else false | [a, b] => if f = "+" then a || b else if f = "*" then a && b else false | _ :: _ :: _ :: _ => false /-- Huntington's axioms H1–H8 (as in kernel/boolean.py). -/ def H : Env | "H1" => some ⟨["x", "y"], x + y, y + x⟩ | "H2" => some ⟨["x", "y"], x * y, y * x⟩ | "H3" => some ⟨["x", "y", "z"], x + y * z, (x + y) * (x + z)⟩ | "H4" => some ⟨["x", "y", "z"], x * (y + z), x * y + x * z⟩ | "H5" => some ⟨["x"], x + 0, x⟩ | "H6" => some ⟨["x"], x * 1, x⟩ | "H7" => some ⟨["x"], x + n x, 1⟩ | "H8" => some ⟨["x"], x * n x, 0⟩ | _ => none /-- A proof of x + x = x — exactly the tree the `calc` tactic builds in kernel/boolean.py. -/ def add_idem : Proof := .Trans (.Trans (.Trans (.Trans (.Symm (.Inst "H6" [x + x])) (.Symm (.CongrArg "z" ((x + x) * z) (.Inst "H7" [x])))) (.Symm (.Inst "H3" [x, x, n x]))) (.CongrArg "z" (x + z) (.Inst "H8" [x]))) (.Inst "H5" [x]) #eval check H add_idem #eval used add_idem #eval (addTheorem H "add_idem" ⟨["x"], x + x, x⟩ add_idem).isSome #eval (addTheorem H "wrong" ⟨["x"], x + x, 1⟩ add_idem).isSome -- another equation -- A broken proof: Trans of x + 0 = x (H5) and x * 1 = x (H6) — the middles x and x * 1 differ. #eval check H (.Trans (.Inst "H5" [x]) (.Inst "H6" [x])) -- The first hole from Python does not occur here: the fact x * 0 = 0 with "variables" x, 0 -- gives with the arguments x, y still x * 0 = 0, since substitution changes `var "0"`, not -- the constant 0. #eval check (extend H "bad" ⟨["x", "0"], x * 0, 0⟩) (.Inst "bad" [x, y]) /-- H1–H8 are true in {false, true}: we check all values of x, y, z. -/ theorem model_bool2 : Model bool2 H := by intro name f h unfold H at h split at h <;> cases h <;> intro v <;> dsimp only [Term.eval, Term.evalAll, x, y, z, n] <;> cases v "x" <;> cases v "y" <;> cases v "z" <;> rfl /-- A corollary of soundness: x + x = x is true in {false, true}. The hypothesis `check H add_idem = some (x + x, x)` is checked by `decide`: Lean's kernel runs our kernel. -/ theorem add_idem_bool2 : Holds bool2 (x + x) x := soundness bool2 H model_bool2 add_idem (by decide) end Example -- Which axioms of Lean do these theorems rely on? (Like the field `assumptions` in Python.) -- On none: not even `propext`, `funext` or classical logic is needed. #print axioms soundness #print axioms relative_soundness #print axioms invariant #print axioms Example.add_idem_bool2