From 380f988e02512ab356d1240578b556f64d7268e9 Mon Sep 17 00:00:00 2001 From: Stefan Langerman Date: Sun, 15 Nov 2026 10:26:48 +0000 Subject: [PATCH] feat(models): extract real-world BST pointer-machine simulation --- RotationBST.lean | 4 + RotationBST/Models/RealWorld/Abstract.lean | 36 +++ .../Models/RealWorld/AbstractBridge.lean | 3 + .../Models/RealWorld/Compiler/Abstract.lean | 62 +++++ .../RealWorld/Compiler/AbstractBridge.lean | 3 + .../Models/RealWorld/Compiler/Boundaries.lean | 88 +++++++ .../Models/RealWorld/Compiler/Branch.lean | 35 +++ .../Models/RealWorld/Compiler/Code.lean | 57 +++++ .../Compiler/Definitions/Abstract.lean | 111 +++++++++ .../Models/RealWorld/Compiler/Metadata.lean | 83 +++++++ .../Models/RealWorld/Compiler/Online.lean | 86 +++++++ .../Models/RealWorld/Compiler/Primitive.lean | 55 +++++ .../Models/RealWorld/Compiler/Relocation.lean | 55 +++++ .../RealWorld/Compiler/Representation.lean | 42 ++++ .../Models/RealWorld/Compiler/Scalar.lean | 61 +++++ .../Models/RealWorld/Compiler/Space.lean | 68 ++++++ .../Models/RealWorld/Compiler/Step.lean | 142 ++++++++++++ .../RealWorld/Definitions/Abstract.lean | 173 ++++++++++++++ .../Models/RealWorld/Linked/Abstract.lean | 28 +++ .../RealWorld/Linked/AbstractBridge.lean | 3 + .../Linked/Definitions/Abstract.lean | 115 +++++++++ .../Models/RealWorld/Linked/Execution.lean | 66 ++++++ RotationBST/Models/RealWorld/Linked/Heap.lean | 100 ++++++++ .../Models/RealWorld/Linked/Navigation.lean | 75 ++++++ .../Models/RealWorld/Linked/Preservation.lean | 116 ++++++++++ .../Models/RealWorld/Linked/Refinement.lean | 162 +++++++++++++ .../Models/RealWorld/Linked/Rotation.lean | 100 ++++++++ .../Models/RealWorld/Linked/Simulation.lean | 44 ++++ .../RealWorld/PointerMachine/Abstract.lean | 55 +++++ .../PointerMachine/AbstractBridge.lean | 3 + .../PointerMachine/Definitions/Abstract.lean | 112 +++++++++ .../RealWorld/PointerMachine/Proofs.lean | 93 ++++++++ .../RealWorld/PointerMachine/Rotation.lean | 94 ++++++++ RotationBST/Models/RealWorld/Proofs.lean | 149 ++++++++++++ RotationBSTTests.lean | 5 + RotationBSTTests/CompiledBST.lean | 148 ++++++++++++ RotationBSTTests/LinkedBST.lean | 99 ++++++++ RotationBSTTests/PointerMachineBST.lean | 38 +++ RotationBSTTests/RealWorld.lean | 38 +++ book/src/book.json | 1 + book/src/chapters/front/preface.md | 2 + book/src/chapters/models/part-models.md | 4 + book/src/chapters/models/real-world.md | 218 ++++++++++++++++++ docs/organization.md | 67 ++++++ lake-manifest.json | 12 +- lakefile.toml | 5 + 46 files changed, 3115 insertions(+), 1 deletion(-) create mode 100644 RotationBST/Models/RealWorld/Abstract.lean create mode 100644 RotationBST/Models/RealWorld/AbstractBridge.lean create mode 100644 RotationBST/Models/RealWorld/Compiler/Abstract.lean create mode 100644 RotationBST/Models/RealWorld/Compiler/AbstractBridge.lean create mode 100644 RotationBST/Models/RealWorld/Compiler/Boundaries.lean create mode 100644 RotationBST/Models/RealWorld/Compiler/Branch.lean create mode 100644 RotationBST/Models/RealWorld/Compiler/Code.lean create mode 100644 RotationBST/Models/RealWorld/Compiler/Definitions/Abstract.lean create mode 100644 RotationBST/Models/RealWorld/Compiler/Metadata.lean create mode 100644 RotationBST/Models/RealWorld/Compiler/Online.lean create mode 100644 RotationBST/Models/RealWorld/Compiler/Primitive.lean create mode 100644 RotationBST/Models/RealWorld/Compiler/Relocation.lean create mode 100644 RotationBST/Models/RealWorld/Compiler/Representation.lean create mode 100644 RotationBST/Models/RealWorld/Compiler/Scalar.lean create mode 100644 RotationBST/Models/RealWorld/Compiler/Space.lean create mode 100644 RotationBST/Models/RealWorld/Compiler/Step.lean create mode 100644 RotationBST/Models/RealWorld/Definitions/Abstract.lean create mode 100644 RotationBST/Models/RealWorld/Linked/Abstract.lean create mode 100644 RotationBST/Models/RealWorld/Linked/AbstractBridge.lean create mode 100644 RotationBST/Models/RealWorld/Linked/Definitions/Abstract.lean create mode 100644 RotationBST/Models/RealWorld/Linked/Execution.lean create mode 100644 RotationBST/Models/RealWorld/Linked/Heap.lean create mode 100644 RotationBST/Models/RealWorld/Linked/Navigation.lean create mode 100644 RotationBST/Models/RealWorld/Linked/Preservation.lean create mode 100644 RotationBST/Models/RealWorld/Linked/Refinement.lean create mode 100644 RotationBST/Models/RealWorld/Linked/Rotation.lean create mode 100644 RotationBST/Models/RealWorld/Linked/Simulation.lean create mode 100644 RotationBST/Models/RealWorld/PointerMachine/Abstract.lean create mode 100644 RotationBST/Models/RealWorld/PointerMachine/AbstractBridge.lean create mode 100644 RotationBST/Models/RealWorld/PointerMachine/Definitions/Abstract.lean create mode 100644 RotationBST/Models/RealWorld/PointerMachine/Proofs.lean create mode 100644 RotationBST/Models/RealWorld/PointerMachine/Rotation.lean create mode 100644 RotationBST/Models/RealWorld/Proofs.lean create mode 100644 RotationBSTTests/CompiledBST.lean create mode 100644 RotationBSTTests/LinkedBST.lean create mode 100644 RotationBSTTests/PointerMachineBST.lean create mode 100644 RotationBSTTests/RealWorld.lean create mode 100644 book/src/chapters/models/real-world.md diff --git a/RotationBST.lean b/RotationBST.lean index 11f2017..09721b6 100644 --- a/RotationBST.lean +++ b/RotationBST.lean @@ -15,6 +15,10 @@ public import RotationBST.Models.Region.View.Abstract public import RotationBST.Models.Geometric.Abstract public import RotationBST.Models.Equivalence.Abstract public import RotationBST.Models.Dictionary.Abstract +public import RotationBST.Models.RealWorld.Abstract +public import RotationBST.Models.RealWorld.PointerMachine.Abstract +public import RotationBST.Models.RealWorld.Linked.Abstract +public import RotationBST.Models.RealWorld.Compiler.Abstract public import RotationBST.Models.Labelled.Search.Abstract public import RotationBST.Models.LinkedSearch.Abstract diff --git a/RotationBST/Models/RealWorld/Abstract.lean b/RotationBST/Models/RealWorld/Abstract.lean new file mode 100644 index 0000000..c505e0e --- /dev/null +++ b/RotationBST/Models/RealWorld/Abstract.lean @@ -0,0 +1,36 @@ +module + +import RotationBST.Audit.Check +public import RotationBST.Models.RealWorld.AbstractBridge + +@[expose] public section +namespace RotationBST.RealWorld.Results + +theorem physical {w f r l : Nat} {p : Machine f r l} + {s t : State w f r l} {time cost : Nat} (h : Run p s t time cost) : + Pointer.Trace s.cursor.erase t.cursor.erase cost := run_physical h + +theorem bst_cost {w f r l : Nat} {p : Machine f r l} + {s t : State w f r l} {time cost : Nat} (h : Run p s t time cost) : + cost ≤ time := cost_le_time h + +theorem causal {w f r l : Nat} {p : Machine f r l} + {s t u : State w f r l} {xs : List (BitVec w)} {a b c d : Nat} + (h : Execution p s xs t a b) (k : Execution p s xs u c d) : + t = u ∧ a = c ∧ b = d := execution_unique h k + +theorem append {w f r l : Nat} {p : Machine f r l} + {s t u : State w f r l} {xs ys : List (BitVec w)} {a b c d : Nat} + (h : Execution p s xs t a b) (k : Execution p t ys u c d) : + Execution p s (xs ++ ys) u (a + c) (b + d) := execution_append h k + +end RotationBST.RealWorld.Results + +#check_bst_abstract RotationBST.RealWorld.Results allowing [ + RotationBST.Models.RealWorld.Definitions.Abstract, + RotationBST.Models.Labelled.Cursor.Definitions.Abstract, + RotationBST.Models.Multifinger.Program.Definitions.Abstract, + RotationBST.Models.Multifinger.Definitions.Abstract, + RotationBST.Models.Labelled.Abstract, + RotationBST.Models.Pointer.Machine.Abstract, + RotationBST.Models.Rotation.Abstract] diff --git a/RotationBST/Models/RealWorld/AbstractBridge.lean b/RotationBST/Models/RealWorld/AbstractBridge.lean new file mode 100644 index 0000000..8d2e889 --- /dev/null +++ b/RotationBST/Models/RealWorld/AbstractBridge.lean @@ -0,0 +1,3 @@ +module + +public import RotationBST.Models.RealWorld.Proofs diff --git a/RotationBST/Models/RealWorld/Compiler/Abstract.lean b/RotationBST/Models/RealWorld/Compiler/Abstract.lean new file mode 100644 index 0000000..4006481 --- /dev/null +++ b/RotationBST/Models/RealWorld/Compiler/Abstract.lean @@ -0,0 +1,62 @@ +module + +import RotationBST.Audit.Check +public import RotationBST.Models.RealWorld.Compiler.AbstractBridge + +@[expose] public section +namespace RotationBST.RealWorld.Compiler.Results + +/-- Compile every successful source request into one fixed pointer-machine +program, with charged dispatch, request setup and halt. -/ +theorem response {w f r l : Nat} (p : Machine f r l) + {s u : State w f r l} {t : Target w f r} {key : BitVec w} {time cost : Nat} + (width : 0 < w) (image : Image s t) + (source : RealWorld.Responds p s key u time cost) : + ∃ v actual, actual ≤ 19 * time + 3 ∧ Responds p t key v actual ∧ Image u v := + response_simulation p width image source + +/-- The compiled code is reused unchanged across the whole online sequence. -/ +theorem execution {w f r l : Nat} (p : Machine f r l) + {s u : State w f r l} {t : Target w f r} {xs : List (BitVec w)} {time cost : Nat} + (width : 0 < w) (image : Image s t) + (source : RealWorld.Execution p s xs u time cost) : + ∃ v actual, actual ≤ 19 * time + 3 * xs.length ∧ Execution p t xs v actual ∧ Image u v := + execution_simulation p width image source + +/-- Source time proportional to BST work transfers with explicit constants. -/ +theorem proportional_time {w f r l : Nat} (p : Machine f r l) + {s u : State w f r l} {t : Target w f r} {key : BitVec w} {time cost constant : Nat} + (width : 0 < w) (image : Image s t) + (source : RealWorld.Responds p s key u time cost) (bound : time ≤ constant * (cost + 1)) : + ∃ v actual, actual ≤ (19 * constant + 3) * (cost + 1) ∧ + Responds p t key v actual ∧ Image u v := proportional_response p width image source bound + +/-- No execution of compiled code allocates or removes a record. -/ +theorem storage {w f r l : Nat} (p : Machine f r l) {s t : Target w f r} {n : Nat} + (run : Cslib.PointerMachine.Runs (compile p) s t n) : t.heap.length = s.heap.length := + storage_preserved p run + +/-- Code size is fixed by the source controller, independent of tree size. -/ +theorem code_size {w f r l : Nat} (p : Machine f r l) : + (compile (w := w) p).length = 24 * l + 4 := compile_length p + +/-- Concrete successful requests have unique states and exact instruction counts. -/ +theorem deterministic {w f r l : Nat} {p : Machine f r l} {s t u : Target w f r} + {key : BitVec w} {a b : Nat} (h : Responds p s key t a) (k : Responds p s key u b) : + t = u ∧ a = b := response_unique h k + +end RotationBST.RealWorld.Compiler.Results + +/-- info: abstract audit passed for `RotationBST.RealWorld.Compiler.Results`: 6 root declarations -/ +#guard_msgs in +#check_bst_abstract RotationBST.RealWorld.Compiler.Results allowing [ + RotationBST.Models.RealWorld.Compiler.Definitions.Abstract, + RotationBST.Models.RealWorld.Definitions.Abstract, + RotationBST.Models.RealWorld.Linked.Definitions.Abstract, + RotationBST.Models.RealWorld.PointerMachine.Definitions.Abstract, + RotationBST.Models.Labelled.Cursor.Definitions.Abstract, + RotationBST.Models.Labelled.Cursor.Map.Definitions.Abstract, + RotationBST.Models.Multifinger.Program.Definitions.Abstract, + RotationBST.Models.Rotation.Abstract, + RotationBST.Models.Labelled.Ordering.Definitions.Abstract, + CslibFrontier.Computability.PointerMachine.Defs] diff --git a/RotationBST/Models/RealWorld/Compiler/AbstractBridge.lean b/RotationBST/Models/RealWorld/Compiler/AbstractBridge.lean new file mode 100644 index 0000000..abfcf98 --- /dev/null +++ b/RotationBST/Models/RealWorld/Compiler/AbstractBridge.lean @@ -0,0 +1,3 @@ +module + +public import RotationBST.Models.RealWorld.Compiler.Space diff --git a/RotationBST/Models/RealWorld/Compiler/Boundaries.lean b/RotationBST/Models/RealWorld/Compiler/Boundaries.lean new file mode 100644 index 0000000..b9a2895 --- /dev/null +++ b/RotationBST/Models/RealWorld/Compiler/Boundaries.lean @@ -0,0 +1,88 @@ +module + +public import RotationBST.Models.RealWorld.Compiler.Branch + +@[expose] public section +namespace RotationBST.RealWorld.Compiler +open Cslib.PointerMachine (Instr Runs) +variable {w f r l : Nat} + +theorem mark_block (p : Machine f r l) (pc next : Fin l) + {s : State w f r l} {t : Target w f r} (image : Image s t) (ht : t.pc = address pc) + (source : p.code pc = .mark next) + (record : Linked.Record w f (r + 4)) (read : t.deref 0 = some record) + (key : record.data 0 = s.request) : + ∃ v, Runs (compile p) t v 4 ∧ Image { s with seen := true, pc := some next } v := by + obtain ⟨c, rep, hc, hr, hq, hs, hp⟩ := image + have im : Image s t := ⟨c, rep, hc, hr, hq, hs, hp⟩ + let v1 : Target w f r := { t.setData (tempReg r) s.request with pc := address pc + 1 } + let v2 : Target w f r := { v1 with pc := address pc + 3 } + let v3 : Target w f r := { v2.setData (seenReg r) (flag w true) with pc := address pc + 4 } + let v4 : Target w f r := { v3 with pc := address next } + have h0 : (compile (w := w) p)[t.pc]? = some (.loadData (tempReg r) 0 0) := by + rw [ht]; simpa [source, block] using block_lookup (w := w) p pc 0 (by decide) + have h1 : (compile (w := w) p)[address pc + 1]? = + some (.ifTest .eq (tempReg r) (queryReg r) (address pc + 3)) := by + simpa [source, block] using block_lookup (w := w) p pc 1 (by decide) + have h3 : (compile (w := w) p)[address pc + 3]? = + some (.op (.literal 1) (seenReg r) (zeroReg r) (zeroReg r)) := by + simpa [source, block] using block_lookup (w := w) p pc 3 (by decide) + have h4 : (compile (w := w) p)[address pc + 4]? = some (.goto (address next)) := by + simpa [source, block] using block_lookup (w := w) p pc 4 (by decide) + have run1 : Runs (compile p) t v1 1 := by + simpa [Instr.effect, Instr.next, read, key, ht, v1] using one (compile p) t _ h0 (by simp) + have hq' := hq + simp only [queryReg] at hq' + have run2 : Runs (compile p) v1 v2 1 := by + simpa [v1, v2, Instr.effect, Instr.next, Cslib.PointerMachine.State.setData, + tempReg, queryReg, Fin.ext_iff, hq'] using one (compile p) v1 _ h1 (by simp) + have run3 : Runs (compile p) v2 v3 1 := by + simpa [v2, v3, Instr.effect, Instr.next, flag] using one (compile p) v2 _ h3 (by simp) + have run4 : Runs (compile p) v3 v4 1 := by + simpa [v3, v4, Instr.effect, Instr.next] using one (compile p) v3 _ h4 (by simp) + refine ⟨v4, ((run1.trans run2).trans run3).trans run4, ?_⟩ + apply image_control (u := { s with seen := true, pc := some next }) (v := v4) im rfl rfl rfl + · intro i + simpa [v4, v3, v2, v1, Cslib.PointerMachine.State.setData, + Ne.symm (user_ne_temp i), Ne.symm (user_ne_seen i)] using hr i + · simpa [v4, v3, v2, v1, Cslib.PointerMachine.State.setData, + queryReg, tempReg, seenReg, Fin.ext_iff] using hq + · simp [v4, v3, Cslib.PointerMachine.State.setData] + · rfl + +theorem finish_block (p : Machine f r l) (pc : Fin l) + {s : State w f r l} {t : Target w f r} (image : Image s t) (ht : t.pc = address pc) + (source : p.code pc = .finish) (seen : s.seen = true) (hw : 0 < w) : + ∃ v, Runs (compile p) t v 3 ∧ Image { s with pc := (none : Option (Fin l)) } v := by + obtain ⟨c, rep, hc, hr, hq, hs, hp⟩ := image + have im : Image s t := ⟨c, rep, hc, hr, hq, hs, hp⟩ + let v1 : Target w f r := { t.setData (zeroReg r) (BitVec.ofNat w 0) with pc := address pc + 1 } + let v2 : Target w f r := { v1 with pc := address pc + 2 } + let v3 : Target w f r := { v2 with pc := boundary l } + have h0 : (compile (w := w) p)[t.pc]? = + some (.op (.literal 0) (zeroReg r) (zeroReg r) (zeroReg r)) := by + rw [ht]; simpa [source, block] using block_lookup (w := w) p pc 0 (by decide) + have h1 : (compile (w := w) p)[address pc + 1]? = + some (.ifTest .eq (seenReg r) (zeroReg r) (trap l)) := by + simpa [source, block] using block_lookup (w := w) p pc 1 (by decide) + have h2 : (compile (w := w) p)[address pc + 2]? = some (.goto (boundary l)) := by + simpa [source, block] using block_lookup (w := w) p pc 2 (by decide) + have nonzero : flag w true ≠ BitVec.ofNat w 0 := flag_ne_zero hw + have run1 : Runs (compile p) t v1 1 := by + simpa [Instr.effect, Instr.next, ht, v1] using one (compile p) t _ h0 (by simp) + have hs' := hs + simp only [seenReg, seen] at hs' + have run2 : Runs (compile p) v1 v2 1 := by + simpa [v1, v2, Instr.effect, Instr.next, Cslib.PointerMachine.State.setData, + seenReg, zeroReg, Fin.ext_iff, hs', nonzero, Nat.add_assoc] using one (compile p) v1 _ h1 (by simp) + have run3 : Runs (compile p) v2 v3 1 := by + simpa [v2, v3, Instr.effect, Instr.next] using one (compile p) v2 _ h2 (by simp) + refine ⟨v3, (run1.trans run2).trans run3, ?_⟩ + apply image_control (u := { s with pc := (none : Option (Fin l)) }) (v := v3) im rfl rfl rfl + · intro i + simpa [v3, v2, v1, Cslib.PointerMachine.State.setData, Ne.symm (user_ne_zero i)] using hr i + · simpa [v3, v2, v1, Cslib.PointerMachine.State.setData, queryReg, zeroReg, Fin.ext_iff] using hq + · simpa [v3, v2, v1, Cslib.PointerMachine.State.setData, seenReg, zeroReg, Fin.ext_iff] using hs + · rfl + +end RotationBST.RealWorld.Compiler diff --git a/RotationBST/Models/RealWorld/Compiler/Branch.lean b/RotationBST/Models/RealWorld/Compiler/Branch.lean new file mode 100644 index 0000000..8fc6fa3 --- /dev/null +++ b/RotationBST/Models/RealWorld/Compiler/Branch.lean @@ -0,0 +1,35 @@ +module + +public import RotationBST.Models.RealWorld.Compiler.Primitive + +@[expose] public section +namespace RotationBST.RealWorld.Compiler +open Cslib.PointerMachine (Instr Runs step) +variable {w f r l : Nat} + +theorem branch_block (p : Machine f r l) (pc yes no : Fin l) (a b : Fin r) + {s : State w f r l} {t : Target w f r} (image : Image s t) (ht : t.pc = address pc) + (source : p.code pc = .branch a b yes no) : + ∃ v n, n ≤ 19 ∧ Runs (compile p) t v n ∧ + Image { s with pc := some (if (s.regs a).toNat < (s.regs b).toNat then yes else no) } v := by + obtain ⟨c, rep, hc, hr, hq, hs, hpc⟩ := image + have im : Image s t := ⟨c, rep, hc, hr, hq, hs, hpc⟩ + have hi : (compile (w := w) p)[t.pc]? = + some (.ifTest .lt (userReg a) (userReg b) (address yes)) := by + rw [ht] + simpa [source, block] using block_lookup (w := w) p pc 0 (by decide) + by_cases cond : (s.regs a).toNat < (s.regs b).toNat + · refine ⟨{ t with pc := address yes }, 1, by decide, ?_, ?_⟩ + · simpa [Instr.effect, Instr.next, hr, cond] using one (compile p) t _ hi (by simp) + · simpa [cond, location] using image_jump im (some yes) + · have h1 : (compile (w := w) p)[t.pc + 1]? = some (.goto (address no)) := by + rw [ht] + simpa [source, block] using block_lookup (w := w) p pc 1 (by decide) + have first : Runs (compile p) t { t with pc := t.pc + 1 } 1 := by + simpa [Instr.effect, Instr.next, hr, cond] using one (compile p) t _ hi (by simp) + refine ⟨{ t with pc := address no }, 2, by decide, ?_, ?_⟩ + · exact .tail _ _ _ _ first + (Cslib.PointerMachine.step_eq_some_iff.mpr ⟨.goto (address no), h1, by simp, rfl⟩) + · simpa [cond, location] using image_jump im (some no) + +end RotationBST.RealWorld.Compiler diff --git a/RotationBST/Models/RealWorld/Compiler/Code.lean b/RotationBST/Models/RealWorld/Compiler/Code.lean new file mode 100644 index 0000000..eec51b2 --- /dev/null +++ b/RotationBST/Models/RealWorld/Compiler/Code.lean @@ -0,0 +1,57 @@ +module + +public import RotationBST.Models.RealWorld.Compiler.Relocation + +@[expose] public section +namespace RotationBST.RealWorld.Compiler +variable {w f r l : Nat} + +theorem block_lookup (p : Machine f r l) (pc : Fin l) (k : Nat) (hk : k < stride) : + (compile (w := w) p)[address pc + k]? = + some (((block (w := w) (address pc) (p.code pc))[k]?).getD (.goto (trap l))) := by + have hi : address pc + k < boundary l := by + simp only [address, boundary, stride] at * + have := pc.isLt + omega + have hb : address pc + k < boundary l + 4 := by omega + have hd : (address pc + k) / stride = pc.val := by + simp only [address, stride] at *; omega + have hm : (address pc + k) % stride = k := by + simp only [address, stride] at *; omega + simp only [compile, List.getElem?_ofFn] + simp [hb, hi, hd, hm] + +theorem boundary_lookup (p : Machine f r l) : + (compile (w := w) p)[boundary l]? = some .halt := by + simp only [compile, List.getElem?_ofFn] + simp + +theorem entry_lookup (p : Machine f r l) : + (compile (w := w) p)[entry l]? = + some (.op (.literal 0) (seenReg r) (zeroReg r) (zeroReg r)) := by + simp only [compile, List.getElem?_ofFn] + simp [entry] + +theorem entry_next_lookup (p : Machine f r l) : + (compile (w := w) p)[entry l + 1]? = some (.goto (address p.entry)) := by + simp only [compile, List.getElem?_ofFn] + simp [entry, Nat.add_assoc] + +theorem block_length (base : Nat) (i : Instruction f r l) : + (block (w := w) base i).length ≤ stride := by + cases i <;> simp [block, stride] + rename_i op next + cases op <;> simp [Linked.program, Linked.move, Linked.rotate] + +/-- The compiler contains every relocated primitive at the correct address. -/ +theorem primitive_contains (p : Machine f r l) (pc next : Fin l) (op : Multifinger.Opcode) + (source : p.code pc = .bst op next) : + Contains (compile (w := w) p) (Linked.program op) (address pc) (address next) := by + intro k i hi + have hk := List.getElem?_eq_some_iff.mp hi |>.1 + have bound : (Linked.program (w := w) (e := f) (regs := r + 4) op).length ≤ stride := by + cases op <;> simp [Linked.program, Linked.move, Linked.rotate, stride] + have lookup := block_lookup (w := w) p pc k (by omega) + simpa [source, block, List.getElem?_map, hi] using lookup + +end RotationBST.RealWorld.Compiler diff --git a/RotationBST/Models/RealWorld/Compiler/Definitions/Abstract.lean b/RotationBST/Models/RealWorld/Compiler/Definitions/Abstract.lean new file mode 100644 index 0000000..9e279d1 --- /dev/null +++ b/RotationBST/Models/RealWorld/Compiler/Definitions/Abstract.lean @@ -0,0 +1,111 @@ +module + +public import RotationBST.Models.RealWorld.Linked.Abstract +public import RotationBST.Models.RealWorld.Definitions.Abstract + +@[expose] public section +namespace RotationBST.RealWorld.Compiler + +abbrev Target (w f r : Nat) := Linked.State w f (r + 4) +abbrev Opcode (w f r : Nat) := Linked.Instruction w f (r + 4) + +/-- User registers occupy an initial segment; four private scalar registers +hold the current request, visited flag, key temporary and zero temporary. -/ +def userReg {r : Nat} (i : Fin r) : Fin (r + 4) := ⟨i, by omega⟩ +def queryReg (r : Nat) : Fin (r + 4) := ⟨r, by omega⟩ +def seenReg (r : Nat) : Fin (r + 4) := ⟨r + 1, by omega⟩ +def tempReg (r : Nat) : Fin (r + 4) := ⟨r + 2, by omega⟩ +def zeroReg (r : Nat) : Fin (r + 4) := ⟨r + 3, by omega⟩ + +def field {f : Nat} (i : Fin f) : Fin (f + 1) := ⟨i + 1, by omega⟩ + +def stride : Nat := 24 +def address {l : Nat} (pc : Fin l) : Nat := stride * pc.val +def boundary (l : Nat) : Nat := stride * l +def trap (l : Nat) : Nat := boundary l + 1 +def entry (l : Nat) : Nat := boundary l + 2 + +/-- Relocate a primitive into a block and replace its halt by a charged +continuation jump. There is only one actual halt in the compiled program. -/ +def relocate {w f r : Nat} (base exit : Nat) : Opcode w f r → Opcode w f r + | .goto k => .goto (base + k) + | .ifPtrEq a b k => .ifPtrEq a b (base + k) + | .ifTest p a b k => .ifTest p a b (base + k) + | .halt => .goto exit + | i => i + +/-- Machine code for each semantic instruction. All bookkeeping is charged. -/ +def block {w f r l : Nat} (base : Nat) : Instruction f r l → List (Opcode w f r) + | .literal dst value next => + [.op (.literal value) (userReg dst) (zeroReg r) (zeroReg r), .goto (address next)] + | .copy dst src next => [.moveData (userReg dst) (userReg src), .goto (address next)] + | .add dst a b next => [.op .add (userReg dst) (userReg a) (userReg b), .goto (address next)] + | .sub dst a b next => [.op .sub (userReg dst) (userReg a) (userReg b), .goto (address next)] + | .branch a b yes no => [.ifTest .lt (userReg a) (userReg b) (address yes), .goto (address no)] + | .load dst i next => [.loadData (userReg dst) (field i) 0, .goto (address next)] + | .store i src next => [.storeData (field i) 0 (userReg src), .goto (address next)] + | .key dst next => [.loadData (userReg dst) 0 0, .goto (address next)] + | .query dst next => [.moveData (userReg dst) (queryReg r), .goto (address next)] + | .bst op next => (Linked.program op).map (relocate base (address next)) + | .mark next => + [.loadData (tempReg r) 0 0, .ifTest .eq (tempReg r) (queryReg r) (base + 3), + .goto (trap l), .op (.literal 1) (seenReg r) (zeroReg r) (zeroReg r), + .goto (address next)] + | .finish => + [.op (.literal 0) (zeroReg r) (zeroReg r) (zeroReg r), + .ifTest .eq (seenReg r) (zeroReg r) (trap l), .goto (boundary l)] + +/-- The whole controller is one finite program. Padding and failed checks go +to a nonhalting trap. Entry resets the visited flag using a machine instruction. -/ +def compile {w f r l : Nat} (p : Machine f r l) : List (Opcode w f r) := + List.ofFn fun i : Fin (boundary l + 4) => + if h : i.val < boundary l then + let pc : Fin l := ⟨i.val / stride, (Nat.div_lt_iff_lt_mul (by decide)).mpr (by + simpa [boundary, Nat.mul_comm] using h)⟩ + ((block (address pc) (p.code pc))[i.val % stride]?).getD (.goto (trap l)) + else if i.val = boundary l then .halt + else if i.val = entry l then .op (.literal 0) (seenReg r) (zeroReg r) (zeroReg r) + else if i.val = entry l + 1 then .goto (address p.entry) + else .goto (trap l) + +/-- Supplying a request is permitted only at the unique successful halt. +It preserves the heap and all registers except the designated input register. +Resetting the visited flag and jumping to source entry are charged code. -/ +def accept {w f r l : Nat} (key : BitVec w) (s : Target w f r) : Option (Target w f r) := + if s.pc = boundary l then some { s.setData (queryReg r) key with pc := entry l } else none + +variable {w f r l : Nat} + +def decode (x : Linked.Label w f) : Node w f := + ⟨x.2 0, fun i => x.2 (field i)⟩ + +def flag (w : Nat) (seen : Bool) : BitVec w := BitVec.ofNat w (if seen then 1 else 0) + +def location {l : Nat} : Option (Fin l) → Nat + | none => boundary l + | some pc => address pc + +/-- The full compiler invariant: linked representation, user registers, +current input, visited flag and control label. The address-labelled cursor +is ghost state; only the fixed-size machine state is available at runtime. -/ +def Image (s : State w f r l) (t : Target w f r) : Prop := + ∃ c, Linked.Realizes t c ∧ s.cursor = c.map decode ∧ + (∀ i, t.data (userReg i) = s.regs i) ∧ + t.data (queryReg r) = s.request ∧ t.data (seenReg r) = flag w s.seen ∧ + t.pc = location s.pc + + +/-- A completed request in the one compiled program, including its halt. -/ +def Responds {w f r l : Nat} (p : Machine f r l) (s : Target w f r) + (key : BitVec w) (t : Target w f r) (time : Nat) : Prop := + ∃ input, accept (l := l) key s = some input ∧ + Cslib.PointerMachine.Executes (compile p) input t time + +/-- The same code is reused for the whole request sequence. -/ +inductive Execution {w f r l : Nat} (p : Machine f r l) : + Target w f r → List (BitVec w) → Target w f r → Nat → Prop where + | nil (s) : Execution p s [] s 0 + | cons {s t u key rest a b} : Responds p s key t a → + Execution p t rest u b → Execution p s (key :: rest) u (a + b) + +end RotationBST.RealWorld.Compiler diff --git a/RotationBST/Models/RealWorld/Compiler/Metadata.lean b/RotationBST/Models/RealWorld/Compiler/Metadata.lean new file mode 100644 index 0000000..0780157 --- /dev/null +++ b/RotationBST/Models/RealWorld/Compiler/Metadata.lean @@ -0,0 +1,83 @@ +module + +public import RotationBST.Models.RealWorld.Compiler.Representation + +@[expose] public section +namespace RotationBST.RealWorld.Compiler +open Cslib.PointerMachine (Instr) +variable {w f r l : Nat} + +def updateLabel (x : Linked.Label w f) (i : Fin (f + 1)) (v : BitVec w) : Linked.Label w f := + (x.1, Function.update x.2 i v) + +theorem addresses_plug (cs : List (LabelledCursor.Frame (Linked.Label w f))) + {a b : Linked.Tree w f} (h : Linked.addresses a = Linked.addresses b) : + Linked.addresses (LabelledCursor.plug cs a) = Linked.addresses (LabelledCursor.plug cs b) := by + induction cs generalizing a b with + | nil => exact h + | cons frame cs ih => + cases frame <;> apply ih <;> simp [Linked.addresses_node, h] + +theorem keys_plug (cs : List (LabelledCursor.Frame (Linked.Label w f))) + {a b : Linked.Tree w f} (h : Linked.keys a = Linked.keys b) : + Linked.keys (LabelledCursor.plug cs a) = Linked.keys (LabelledCursor.plug cs b) := by + induction cs generalizing a b with + | nil => exact h + | cons frame cs ih => cases frame <;> apply ih <;> simp [Linked.keys, h] + +/-- A metadata store changes exactly the current node's designated word. +The key, all links, and the rest of the heap remain represented. -/ +theorem store_realizes {s : Target w f r} {a b : Linked.Tree w f} {x : Linked.Label w f} + {cs : List (LabelledCursor.Frame (Linked.Label w f))} + (h : Linked.Realizes s ⟨.node a x b, cs⟩) (i : Fin f) (src : Fin (r + 4)) : + Linked.Realizes ((Instr.storeData (field i) 0 src).effect s) + ⟨.node a (updateLabel x (field i) (s.data src)) b, cs⟩ := by + have nd := (Linked.nodup_plug cs (.node a x b)).mp h.distinct + simp only [Linked.addresses_node, List.nodup_append, List.nodup_cons, + List.mem_append, List.mem_cons] at nd + have effect : (Instr.storeData (field i) 0 src).effect s = + { s with heap := s.heap.modify x.1 (fun n => + { n with data := Function.update n.data (field i) (s.data src) }) } := by + simp [Instr.effect, Cslib.PointerMachine.State.modify, h.cursor, Linked.root] + have ad : Linked.addresses (LabelledCursor.plug cs + (.node a (updateLabel x (field i) (s.data src)) b)) = + Linked.addresses (LabelledCursor.plug cs (.node a x b)) := + addresses_plug cs (by simp [updateLabel]) + have keyeq : Linked.keys (LabelledCursor.plug cs + (.node a (updateLabel x (field i) (s.data src)) b)) = + Linked.keys (LabelledCursor.plug cs (.node a x b)) := by + apply keys_plug cs + simp [Linked.keys, updateLabel, field, Fin.ext_iff] + have valid := Instr.effect_valid (i := Instr.storeData (field i) 0 src) h.valid + rw [effect] at valid ⊢ + refine ⟨valid, ?_, ?_, ?_, ?_, ?_, h.cursor, ?_, by simp⟩ + · refine ⟨?_, Linked.represents_congr h.focus.2.1 ?_, Linked.represents_congr h.focus.2.2 ?_⟩ + · simp [h.focus.1, updateLabel, Linked.node] + · intro z hz + have ne : x.1 ≠ z := by grind + simp [ne] + · intro z hz + have ne : x.1 ≠ z := by grind + simp [ne] + · apply Linked.context_congr h.context + intro z hz + have ne : x.1 ≠ z := by grind + simp [ne] + · change (Linked.addresses (LabelledCursor.plug cs _)).Nodup + rw [ad]; exact h.distinct + · intro z + simpa only [List.length_modify, LabelledCursor.Config.tree, ad] using h.covers z + · change (Linked.keys (LabelledCursor.plug cs _)).Ordered + rw [keyeq]; exact h.ordered + · exact h.rootReg.trans (Linked.root_plug_congr cs rfl) + +theorem decode_update (x : Linked.Label w f) (i : Fin f) (v : BitVec w) : + decode (updateLabel x (field i) v) = + { decode x with data := Function.update (decode x).data i v } := by + simp only [decode, updateLabel] + simp only [field] + congr 1 + funext j + simp [Function.update_apply, Fin.ext_iff] + +end RotationBST.RealWorld.Compiler diff --git a/RotationBST/Models/RealWorld/Compiler/Online.lean b/RotationBST/Models/RealWorld/Compiler/Online.lean new file mode 100644 index 0000000..1613851 --- /dev/null +++ b/RotationBST/Models/RealWorld/Compiler/Online.lean @@ -0,0 +1,86 @@ +module + +public import RotationBST.Models.RealWorld.Compiler.Step + +@[expose] public section +namespace RotationBST.RealWorld.Compiler +open Cslib.PointerMachine (Instr Runs Executes) +variable {w f r l : Nat} + +theorem run_simulation (p : Machine f r l) {s u : State w f r l} {t : Target w f r} + {time cost : Nat} (hw : 0 < w) (image : Image s t) (run : Run p s u time cost) : + ∃ v n, n ≤ 19 * time ∧ Runs (compile p) t v n ∧ Image u v := by + induction run generalizing t with + | nil => exact ⟨t, 0, by simp, .refl t, image⟩ + | cons step rest ih => + obtain ⟨mid, a, ha, first, im⟩ := tick_simulation p hw image step + obtain ⟨v, b, hb, last, im'⟩ := ih im + exact ⟨v, a + b, by omega, first.trans last, im'⟩ + +/-- External input only replaces the designated request register. The reset +of the visited flag and entry jump take two actual instructions. -/ +theorem input_simulation (p : Machine f r l) {s u : State w f r l} {t : Target w f r} + (image : Image s t) (key : BitVec w) (accepted : RealWorld.accept p key s = some u) : + ∃ input v, accept (l := l) key t = some input ∧ Runs (compile p) input v 2 ∧ Image u v := by + obtain ⟨c, rep, hc, hr, hq, hs, hp⟩ := image + by_cases hpc : s.pc = none + · simp [RealWorld.accept, hpc] at accepted + subst u + have ht : t.pc = boundary l := by simpa [hpc, location] using hp + let input : Target w f r := { t.setData (queryReg r) key with pc := entry l } + let v1 : Target w f r := { input.setData (seenReg r) (flag w false) with pc := entry l + 1 } + let v2 : Target w f r := { v1 with pc := address p.entry } + have first : Runs (compile p) input v1 1 := by + simpa [input, v1, Instr.effect, Instr.next, flag] using + one (compile p) input _ (entry_lookup p) (by simp) + have last : Runs (compile p) v1 v2 1 := by + simpa [v1, v2, Instr.effect, Instr.next] using + one (compile p) v1 _ (entry_next_lookup p) (by simp) + refine ⟨input, v2, by simp [accept, ht, input], first.trans last, + c, realizes_control rep rfl rfl, hc, ?_, ?_, ?_, rfl⟩ + · intro i + simpa [input, v1, v2, Cslib.PointerMachine.State.setData, + Ne.symm (user_ne_seen i), Ne.symm (user_ne_query i)] using hr i + · simp [input, v1, v2, Cslib.PointerMachine.State.setData, queryReg, seenReg, Fin.ext_iff] + · simp [v1, v2, Cslib.PointerMachine.State.setData] + · simp [RealWorld.accept, hpc] at accepted + +/-- A whole successful source request is implemented by the single compiled +program, including entry bookkeeping and the final halt. -/ +theorem response_simulation (p : Machine f r l) {s u : State w f r l} {t : Target w f r} + {key : BitVec w} {time cost : Nat} (hw : 0 < w) (image : Image s t) + (response : RealWorld.Responds p s key u time cost) : + ∃ v actual, actual ≤ 19 * time + 3 ∧ Responds p t key v actual ∧ Image u v := by + obtain ⟨sourceStart, accepted, sourceRun, finished⟩ := response + obtain ⟨input, start, accepted', setup, im⟩ := input_simulation p image key accepted + obtain ⟨v, n, hn, body, im'⟩ := run_simulation p hw im sourceRun + have halt : (compile (w := w) p)[v.pc]? = some .halt := by + obtain ⟨c, rep, hc, hr, hq, hs, hp⟩ := im' + rw [hp, finished] + exact boundary_lookup p + exact ⟨v, n + 3, by omega, ⟨input, accepted', ⟨2 + n, setup.trans body, halt, by omega⟩⟩, im'⟩ + +theorem execution_simulation (p : Machine f r l) {s u : State w f r l} {t : Target w f r} + {xs : List (BitVec w)} {time cost : Nat} (hw : 0 < w) (image : Image s t) + (execution : RealWorld.Execution p s xs u time cost) : + ∃ v actual, actual ≤ 19 * time + 3 * xs.length ∧ Execution p t xs v actual ∧ Image u v := by + induction execution generalizing t with + | nil => exact ⟨t, 0, by simp, .nil t, image⟩ + | cons response rest ih => + obtain ⟨mid, a, ha, first, im⟩ := response_simulation p hw image response + obtain ⟨v, b, hb, last, im'⟩ := ih im + refine ⟨v, a + b, ?_, .cons first last, im'⟩ + simp only [List.length_cons] + omega + +/-- The concrete request protocol has one endpoint and one charged time. -/ +theorem response_unique {p : Machine f r l} {s t u : Target w f r} {key : BitVec w} + {a b : Nat} (h : Responds p s key t a) (k : Responds p s key u b) : + t = u ∧ a = b := by + obtain ⟨input, hi, run⟩ := h + obtain ⟨input', hk, run'⟩ := k + have eq : input = input' := Option.some.inj (hi.symm.trans hk) + subst input' + exact run.unique run' + +end RotationBST.RealWorld.Compiler diff --git a/RotationBST/Models/RealWorld/Compiler/Primitive.lean b/RotationBST/Models/RealWorld/Compiler/Primitive.lean new file mode 100644 index 0000000..0123f0c --- /dev/null +++ b/RotationBST/Models/RealWorld/Compiler/Primitive.lean @@ -0,0 +1,55 @@ +module + +public import RotationBST.Models.RealWorld.Compiler.Scalar + +@[expose] public section +namespace RotationBST.RealWorld.Compiler +open Cslib.PointerMachine (Instr Runs Executes) +variable {w f r l : Nat} + +def keepsData : Opcode w f r → Prop + | .moveData .. | .loadData .. | .op .. => False + | _ => True + +theorem effect_keepsData {i : Opcode w f r} (h : keepsData i) (s : Target w f r) : + (i.effect s).data = s.data := by + cases i <;> simp_all only [keepsData] + all_goals simp [Instr.effect, Cslib.PointerMachine.State.setPtr, + Cslib.PointerMachine.State.modify, Option.elim] + all_goals split <;> rfl + +theorem primitive_keepsData (op : Multifinger.Opcode) : + ∀ i ∈ Linked.program (w := w) (e := f) (regs := r + 4) op, keepsData i := by + cases op <;> simp [Linked.program, Linked.move, Linked.rotate, keepsData] + +theorem runs_keepsData {code : List (Opcode w f r)} + (good : ∀ i ∈ code, keepsData i) {s t : Target w f r} {n : Nat} (h : Runs code s t n) : + t.data = s.data := by + induction h with + | refl => rfl + | tail _ _ _ _ hs ih => + obtain ⟨i, hi, _, rfl⟩ := Cslib.PointerMachine.step_eq_some_iff.mp hs + exact (effect_keepsData (good i (List.mem_of_getElem? hi)) _).trans ih + +/-- The certified primitive runs inside the single compiled controller; +its continuation jump is included in the same constant instruction bound. -/ +theorem bst_block (p : Machine f r l) (pc next : Fin l) (op : Multifinger.Opcode) + {s : State w f r l} {t : Target w f r} {cursor : LabelledCursor.Config (Node w f)} + (image : Image s t) (ht : t.pc = address pc) (source : p.code pc = .bst op next) + (legal : LabelledCursor.perform op s.cursor = some cursor) : + ∃ v n, n ≤ 19 ∧ Runs (compile p) t v n ∧ Image { s with cursor := cursor, pc := some next } v := by + obtain ⟨c, rep, hc, hr, hq, hs, _⟩ := image + have map := LabelledCursor.perform_map decode op c + rw [← hc, legal] at map + obtain ⟨d, step, hd⟩ := Option.map_eq_some_iff.mp map + obtain ⟨v, n, bound, exec, rep', _⟩ := Linked.primitive rep step + have data : v.data = t.data := by + simpa only [Linked.start] using runs_keepsData (s := Linked.start t) (primitive_keepsData op) exec.choose_spec.1 + refine ⟨{ v with pc := address next }, n, bound, ?_, d, + realizes_control rep' rfl rfl, hd.symm, ?_, ?_, ?_, rfl⟩ + · simpa [shift, Linked.start, ← ht] using relocate_executes (primitive_contains p pc next op source) exec + · simpa [data] using hr + · simpa [data] using hq + · simpa [data] using hs + +end RotationBST.RealWorld.Compiler diff --git a/RotationBST/Models/RealWorld/Compiler/Relocation.lean b/RotationBST/Models/RealWorld/Compiler/Relocation.lean new file mode 100644 index 0000000..bb17afe --- /dev/null +++ b/RotationBST/Models/RealWorld/Compiler/Relocation.lean @@ -0,0 +1,55 @@ +module + +public import RotationBST.Models.RealWorld.Compiler.Definitions.Abstract + +@[expose] public section +namespace RotationBST.RealWorld.Compiler +open Cslib.PointerMachine (Instr Runs Executes step) +variable {w f r : Nat} + +def shift (base : Nat) (s : Target w f r) : Target w f r := { s with pc := base + s.pc } + +theorem relocate_effect (base exit : Nat) (i : Opcode w f r) (s : Target w f r) : + (relocate base exit i).effect (shift base s) = shift base (i.effect s) := by + cases i <;> simp [relocate, Instr.effect, shift, Cslib.PointerMachine.State.setPtr, + Cslib.PointerMachine.State.setData, Cslib.PointerMachine.State.deref, + Cslib.PointerMachine.State.modify, Option.elim] + all_goals split <;> simp_all only + +theorem relocate_next (base exit : Nat) (i : Opcode w f r) (s : Target w f r) + (ne : i ≠ .halt) : + (relocate base exit i).next (shift base s) = base + i.next s := by + cases i <;> simp_all [relocate, Instr.next, shift, Nat.add_assoc] + all_goals split <;> rfl + +/-- A block embedding includes its halt, which becomes the continuation jump. -/ +def Contains (target source : List (Opcode w f r)) (base exit : Nat) : Prop := + ∀ pc i, source[pc]? = some i → target[base + pc]? = some (relocate base exit i) + +theorem relocate_step {target source : List (Opcode w f r)} {base exit : Nat} + (code : Contains target source base exit) {s t : Target w f r} + (h : step source s = some t) : step target (shift base s) = some (shift base t) := by + obtain ⟨i, hi, ne, rfl⟩ := Cslib.PointerMachine.step_eq_some_iff.mp h + apply Cslib.PointerMachine.step_eq_some_iff.mpr + refine ⟨relocate base exit i, code _ _ hi, ?_, ?_⟩ + · cases i <;> simp [relocate] + · rw [relocate_effect, relocate_next _ _ _ _ ne] + rfl + +theorem relocate_runs {target source : List (Opcode w f r)} {base exit : Nat} + (code : Contains target source base exit) {s t : Target w f r} {n : Nat} + (h : Runs source s t n) : Runs target (shift base s) (shift base t) n := by + induction h with + | refl => exact .refl _ + | tail _ _ _ _ hs ih => exact .tail _ _ _ _ ih (relocate_step code hs) + +/-- Replacing the final halt by a jump preserves the total charged count. -/ +theorem relocate_executes {target source : List (Opcode w f r)} {base exit : Nat} + (code : Contains target source base exit) {s t : Target w f r} {n : Nat} + (h : Executes source s t n) : + Runs target (shift base s) { t with pc := exit } n := by + obtain ⟨k, run, halt, rfl⟩ := h + refine .tail _ _ _ _ (relocate_runs code run) ?_ + simp [step, shift, code _ _ halt, relocate, Instr.effect, Instr.next] + +end RotationBST.RealWorld.Compiler diff --git a/RotationBST/Models/RealWorld/Compiler/Representation.lean b/RotationBST/Models/RealWorld/Compiler/Representation.lean new file mode 100644 index 0000000..fa55e78 --- /dev/null +++ b/RotationBST/Models/RealWorld/Compiler/Representation.lean @@ -0,0 +1,42 @@ +module + +public import RotationBST.Models.RealWorld.Compiler.Code + +@[expose] public section +namespace RotationBST.RealWorld.Compiler +variable {w f r l : Nat} + +theorem realizes_control {s t : Target w f r} {c : Linked.Cursor w f} + (h : Linked.Realizes s c) (hp : t.ptr = s.ptr) (hh : t.heap = s.heap) : + Linked.Realizes t c := by + exact ⟨by simpa only [Cslib.PointerMachine.State.Valid, hp, hh] using h.valid, + hh ▸ h.focus, hh ▸ h.context, h.distinct, by simpa only [hh] using h.covers, + h.ordered, hp ▸ h.cursor, hp ▸ h.rootReg, h.nonempty⟩ + +theorem image_control {s u : State w f r l} {t v : Target w f r} + (h : Image s t) (hc : u.cursor = s.cursor) + (hp : v.ptr = t.ptr) (hh : v.heap = t.heap) + (hr : ∀ i, v.data (userReg i) = u.regs i) + (hq : v.data (queryReg r) = u.request) + (hs : v.data (seenReg r) = flag w u.seen) (pc : v.pc = location u.pc) : Image u v := by + obtain ⟨c, rep, eq, _, _, _, _⟩ := h + exact ⟨c, realizes_control rep hp hh, hc.trans eq, hr, hq, hs, pc⟩ + +@[simp] theorem userReg_injective {i j : Fin r} : userReg i = userReg j ↔ i = j := by + simp [userReg, Fin.ext_iff] +@[simp] theorem user_ne_query (i : Fin r) : userReg i ≠ queryReg r := by + simp [userReg, queryReg, Fin.ext_iff]; omega +@[simp] theorem user_ne_seen (i : Fin r) : userReg i ≠ seenReg r := by + simp [userReg, seenReg, Fin.ext_iff]; omega +@[simp] theorem user_ne_temp (i : Fin r) : userReg i ≠ tempReg r := by + simp [userReg, tempReg, Fin.ext_iff]; omega +@[simp] theorem user_ne_zero (i : Fin r) : userReg i ≠ zeroReg r := by + simp [userReg, zeroReg, Fin.ext_iff]; omega + +/-- Positive word width is needed to distinguish the stored visited bit. -/ +theorem flag_ne_zero (hw : 0 < w) : flag w true ≠ flag w false := by + simp [flag] + have : 1 < 2 ^ w := Nat.one_lt_pow (by omega) (by decide) + omega + +end RotationBST.RealWorld.Compiler diff --git a/RotationBST/Models/RealWorld/Compiler/Scalar.lean b/RotationBST/Models/RealWorld/Compiler/Scalar.lean new file mode 100644 index 0000000..d68a2f1 --- /dev/null +++ b/RotationBST/Models/RealWorld/Compiler/Scalar.lean @@ -0,0 +1,61 @@ +module + +public import RotationBST.Models.RealWorld.Compiler.Metadata + +@[expose] public section +namespace RotationBST.RealWorld.Compiler +open Cslib.PointerMachine (Instr Runs step) +variable {w f r l : Nat} + +theorem image_set_reg {s : State w f r l} {t : Target w f r} (h : Image s t) + (dst : Fin r) (value : BitVec w) (next : Fin l) : + Image { s with regs := Function.update s.regs dst value, pc := some next } + { t.setData (userReg dst) value with pc := address next } := by + obtain ⟨c, rep, hc, hr, hq, hs, _⟩ := h + refine ⟨c, realizes_control rep rfl rfl, hc, ?_, ?_, ?_, rfl⟩ + · intro i + simp [Cslib.PointerMachine.State.setData, Function.update_apply, hr] + · simpa [Cslib.PointerMachine.State.setData, Ne.symm (user_ne_query dst)] using hq + · simpa [Cslib.PointerMachine.State.setData, Ne.symm (user_ne_seen dst)] using hs + +theorem image_jump {s : State w f r l} {t : Target w f r} (h : Image s t) + (next : Option (Fin l)) : + Image { s with pc := next } { t with pc := location next } := by + obtain ⟨c, rep, hc, hr, hq, hs, _⟩ := h + exact ⟨c, realizes_control rep rfl rfl, hc, hr, hq, hs, rfl⟩ + +theorem one (code : List (Opcode w f r)) (t : Target w f r) (i : Opcode w f r) + (hi : code[t.pc]? = some i) (ne : i ≠ .halt) : + Runs code t { i.effect t with pc := i.next t } 1 := + .single (Cslib.PointerMachine.step_eq_some_iff.mpr ⟨i, hi, ne, rfl⟩) + +/-- A scalar instruction followed by an explicit continuation jump. -/ +theorem scalar_block (p : Machine f r l) (pc next : Fin l) (t : Target w f r) + (i : Opcode w f r) (ht : t.pc = address pc) + (hi : (block (address pc) (p.code pc))[0]? = some i) + (hj : (block (w := w) (address pc) (p.code pc))[1]? = some (.goto (address next))) + (ne : i ≠ .halt) (hn : i.next t = t.pc + 1) : + Runs (compile p) t { i.effect t with pc := address next } 2 := by + have h0 : (compile p)[t.pc]? = some i := by + rw [ht] + simpa [hi] using block_lookup (w := w) p pc 0 (by decide) + have h1 : (compile (w := w) p)[i.next t]? = some (.goto (address next)) := by + rw [hn, ht] + simpa [hj] using block_lookup (w := w) p pc 1 (by decide) + refine .tail _ _ _ _ (one _ _ _ h0 ne) ?_ + exact Cslib.PointerMachine.step_eq_some_iff.mpr ⟨.goto (address next), h1, by simp, rfl⟩ + +/-- Instantiate the scalar block when its data effect has already been identified. -/ +theorem set_reg_block (p : Machine f r l) (pc next : Fin l) + {s : State w f r l} {t : Target w f r} (image : Image s t) (ht : t.pc = address pc) + (dst : Fin r) (value : BitVec w) (i : Opcode w f r) + (hi : (block (address pc) (p.code pc))[0]? = some i) + (hj : (block (w := w) (address pc) (p.code pc))[1]? = some (.goto (address next))) + (ne : i ≠ .halt) (hn : i.next t = t.pc + 1) + (he : i.effect t = t.setData (userReg dst) value) : + ∃ v, Runs (compile p) t v 2 ∧ + Image { s with regs := Function.update s.regs dst value, pc := some next } v := by + refine ⟨_, ?_, image_set_reg image dst value next⟩ + simpa [he] using scalar_block p pc next t i ht hi hj ne hn + +end RotationBST.RealWorld.Compiler diff --git a/RotationBST/Models/RealWorld/Compiler/Space.lean b/RotationBST/Models/RealWorld/Compiler/Space.lean new file mode 100644 index 0000000..b92b6ed --- /dev/null +++ b/RotationBST/Models/RealWorld/Compiler/Space.lean @@ -0,0 +1,68 @@ +module + +public import RotationBST.Models.RealWorld.Compiler.Online + +@[expose] public section +namespace RotationBST.RealWorld.Compiler +open Cslib.PointerMachine (Instr Runs) +variable {w f r l : Nat} + +def noAlloc : Opcode w f r → Prop + | .create _ => False + | _ => True + +theorem block_noAlloc (base : Nat) (i : Instruction f r l) : + ∀ op ∈ block (w := w) base i, noAlloc op := by + cases i <;> simp [block, noAlloc] + rename_i op next + cases op <;> simp [Linked.program, Linked.move, Linked.rotate, relocate] + +theorem getD_noAlloc (ops : List (Opcode w f r)) (good : ∀ i ∈ ops, noAlloc i) + (k exit : Nat) : noAlloc ((ops[k]?).getD (.goto exit)) := by + cases h : ops[k]? with + | none => trivial + | some i => exact good i (List.mem_of_getElem? h) + +theorem compile_noAlloc (p : Machine f r l) : ∀ i ∈ compile (w := w) p, noAlloc i := by + intro i hi + obtain ⟨k, rfl⟩ := List.mem_ofFn.mp hi + dsimp + split + · exact getD_noAlloc _ (block_noAlloc _ _) _ _ + · split + · trivial + · split + · trivial + · split <;> trivial + +theorem noAlloc_length {i : Opcode w f r} (h : noAlloc i) (s : Target w f r) : + (i.effect s).heap.length = s.heap.length := by + cases i <;> simp_all only [noAlloc] + all_goals simp [Instr.effect, Cslib.PointerMachine.State.setPtr, + Cslib.PointerMachine.State.setData, Cslib.PointerMachine.State.modify, Option.elim] + all_goals split <;> simp + +theorem storage_preserved (p : Machine f r l) {s t : Target w f r} {n : Nat} + (run : Runs (compile p) s t n) : t.heap.length = s.heap.length := by + induction run with + | refl => rfl + | tail _ _ _ _ hs ih => + obtain ⟨i, hi, _, rfl⟩ := Cslib.PointerMachine.step_eq_some_iff.mp hs + exact (noAlloc_length (compile_noAlloc p i (List.mem_of_getElem? hi)) _).trans ih + +theorem compile_length (p : Machine f r l) : (compile (w := w) p).length = 24 * l + 4 := by + simp [compile, boundary, stride] + +/-- The source proportional-time certificate transfers with explicit constants. -/ +theorem proportional_response (p : Machine f r l) {s u : State w f r l} {t : Target w f r} + {key : BitVec w} {time cost constant : Nat} (hw : 0 < w) (image : Image s t) + (response : RealWorld.Responds p s key u time cost) (bound : time ≤ constant * (cost + 1)) : + ∃ v actual, actual ≤ (19 * constant + 3) * (cost + 1) ∧ + Responds p t key v actual ∧ Image u v := by + obtain ⟨v, actual, ha, resp, im⟩ := response_simulation p hw image response + refine ⟨v, actual, ?_, resp, im⟩ + have scaled := Nat.mul_le_mul_left 19 bound + simp only [Nat.mul_add, Nat.add_mul, Nat.mul_assoc, Nat.mul_one] at * + omega + +end RotationBST.RealWorld.Compiler diff --git a/RotationBST/Models/RealWorld/Compiler/Step.lean b/RotationBST/Models/RealWorld/Compiler/Step.lean new file mode 100644 index 0000000..969b1c5 --- /dev/null +++ b/RotationBST/Models/RealWorld/Compiler/Step.lean @@ -0,0 +1,142 @@ +module + +public import RotationBST.Models.RealWorld.Compiler.Boundaries + +@[expose] public section +namespace RotationBST.RealWorld.Compiler +open Cslib.PointerMachine (Instr Runs) +variable {w f r l : Nat} + +/-- Each source tick is implemented inside one program with constant overhead. -/ +theorem tick_simulation (p : Machine f r l) {s u : State w f r l} {t : Target w f r} + {out : Option Multifinger.Opcode} (hw : 0 < w) (image : Image s t) + (transition : tick p s = some (u, out)) : + ∃ v n, n ≤ 19 ∧ Runs (compile p) t v n ∧ Image u v := by + obtain ⟨c, rep, hc, hr, hq, hs, hp⟩ := image + have im : Image s t := ⟨c, rep, hc, hr, hq, hs, hp⟩ + cases hpc : s.pc with + | none => simp [tick, hpc] at transition + | some pc => + have ht : t.pc = address pc := by simpa [hpc, location] using hp + have he : eval (p.code pc) s = some (u, out) := by simpa [tick, hpc] using transition + cases source : p.code pc with + | literal dst value next => + simp only [source, eval] at he + rcases he with ⟨rfl, rfl⟩ + obtain ⟨v, run, img⟩ := set_reg_block p pc next im ht dst (BitVec.ofNat w value) + (.op (.literal value) (userReg dst) (zeroReg r) (zeroReg r)) + (by simp [source, block]) (by simp [source, block]) (by simp) rfl rfl + exact ⟨v, 2, by decide, run, img⟩ + | copy dst src next => + simp only [source, eval] at he + rcases he with ⟨rfl, rfl⟩ + obtain ⟨v, run, img⟩ := set_reg_block p pc next im ht dst (s.regs src) + (.moveData (userReg dst) (userReg src)) + (by simp [source, block]) (by simp [source, block]) (by simp) rfl + (by simp [Instr.effect, hr]) + exact ⟨v, 2, by decide, run, img⟩ + | add dst a b next => + simp only [source, eval] at he + rcases he with ⟨rfl, rfl⟩ + obtain ⟨v, run, img⟩ := set_reg_block p pc next im ht dst (s.regs a + s.regs b) + (.op .add (userReg dst) (userReg a) (userReg b)) + (by simp [source, block]) (by simp [source, block]) (by simp) rfl + (by simp [Instr.effect, hr]) + exact ⟨v, 2, by decide, run, img⟩ + | sub dst a b next => + simp only [source, eval] at he + rcases he with ⟨rfl, rfl⟩ + obtain ⟨v, run, img⟩ := set_reg_block p pc next im ht dst (s.regs a - s.regs b) + (.op .sub (userReg dst) (userReg a) (userReg b)) + (by simp [source, block]) (by simp [source, block]) (by simp) rfl + (by simp [Instr.effect, hr]) + exact ⟨v, 2, by decide, run, img⟩ + | branch a b yes no => + simp only [source, eval] at he + rcases he with ⟨rfl, rfl⟩ + exact branch_block p pc yes no a b im ht source + | query dst next => + simp only [source, eval] at he + rcases he with ⟨rfl, rfl⟩ + obtain ⟨v, run, img⟩ := set_reg_block p pc next im ht dst s.request + (.moveData (userReg dst) (queryReg r)) + (by simp [source, block]) (by simp [source, block]) (by simp) rfl + (by simp [Instr.effect, hq]) + exact ⟨v, 2, by decide, run, img⟩ + | bst op next => + simp only [source, eval] at he + cases hm : LabelledCursor.perform op s.cursor with + | none => simp [hm] at he + | some d => + simp [hm] at he + rcases he with ⟨rfl, rfl⟩ + exact bst_block p pc next op im ht source hm + | load dst i next => + rcases c with ⟨tree, cs⟩ + cases tree with + | nil => exact False.elim (rep.nonempty rfl) + | node a x b => + have read : s.cursor.read = some (decode x) := by rw [hc]; rfl + have hd : t.deref 0 = some (Linked.node (Linked.root a) (Linked.root b) (Linked.parent cs) x) := by + simp [Cslib.PointerMachine.State.deref, rep.cursor, Linked.root, rep.focus.1] + simp [source, eval, read] at he + rcases he with ⟨rfl, rfl⟩ + obtain ⟨v, run, img⟩ := set_reg_block p pc next im ht dst ((decode x).data i) + (.loadData (userReg dst) (field i) 0) + (by simp [source, block]) (by simp [source, block]) (by simp) rfl + (by simp [Instr.effect, hd, Linked.node, decode]) + exact ⟨v, 2, by decide, run, img⟩ + | key dst next => + rcases c with ⟨tree, cs⟩ + cases tree with + | nil => exact False.elim (rep.nonempty rfl) + | node a x b => + have read : s.cursor.read = some (decode x) := by rw [hc]; rfl + have hd : t.deref 0 = some (Linked.node (Linked.root a) (Linked.root b) (Linked.parent cs) x) := by + simp [Cslib.PointerMachine.State.deref, rep.cursor, Linked.root, rep.focus.1] + simp [source, eval, read] at he + rcases he with ⟨rfl, rfl⟩ + obtain ⟨v, run, img⟩ := set_reg_block p pc next im ht dst (decode x).key + (.loadData (userReg dst) 0 0) + (by simp [source, block]) (by simp [source, block]) (by simp) rfl + (by simp [Instr.effect, hd, Linked.node, decode]) + exact ⟨v, 2, by decide, run, img⟩ + | store i src next => + rcases c with ⟨tree, cs⟩ + cases tree with + | nil => exact False.elim (rep.nonempty rfl) + | node a x b => + simp [source, eval, hc, LabelledCursor.Config.map, LabelledTree.map, + LabelledCursor.Config.read, LabelledCursor.Config.write] at he + rcases he with ⟨rfl, rfl⟩ + let instr : Opcode w f r := .storeData (field i) 0 (userReg src) + have data : (instr.effect t).data = t.data := by + simp [instr, Instr.effect, Cslib.PointerMachine.State.modify, rep.cursor, Linked.root] + refine ⟨{ instr.effect t with pc := address next }, 2, by decide, + scalar_block p pc next t instr ht (by simp [source, block, instr]) + (by simp [source, block]) (by simp [instr]) rfl, + ⟨.node a (updateLabel x (field i) (t.data (userReg src))) b, cs⟩, + realizes_control (store_realizes rep i (userReg src)) rfl rfl, ?_, ?_, ?_, ?_, rfl⟩ + · simp [LabelledCursor.Config.map, LabelledTree.map, decode_update, hr] + · simpa [data] using hr + · simpa [data] using hq + · simpa [data] using hs + | mark next => + rcases c with ⟨tree, cs⟩ + cases tree with + | nil => exact False.elim (rep.nonempty rfl) + | node a x b => + have read : s.cursor.read = some (decode x) := by rw [hc]; rfl + have hd : t.deref 0 = some (Linked.node (Linked.root a) (Linked.root b) (Linked.parent cs) x) := by + simp [Cslib.PointerMachine.State.deref, rep.cursor, Linked.root, rep.focus.1] + simp [source, eval, read] at he + rcases he with ⟨key, rfl, rfl⟩ + obtain ⟨v, run, img⟩ := mark_block p pc next im ht source _ hd key + exact ⟨v, 4, by decide, run, img⟩ + | finish => + simp [source, eval] at he + rcases he with ⟨seen, rfl, rfl⟩ + obtain ⟨v, run, img⟩ := finish_block p pc im ht source seen hw + exact ⟨v, 3, by decide, run, img⟩ + +end RotationBST.RealWorld.Compiler diff --git a/RotationBST/Models/RealWorld/Definitions/Abstract.lean b/RotationBST/Models/RealWorld/Definitions/Abstract.lean new file mode 100644 index 0000000..5551ff1 --- /dev/null +++ b/RotationBST/Models/RealWorld/Definitions/Abstract.lean @@ -0,0 +1,173 @@ +module + +public import RotationBST.Models.Labelled.Cursor.Abstract +public import Cslib.Foundations.Semantics.LTS.Basic + +@[expose] public section +namespace RotationBST.RealWorld + +/-- Immutable key plus a fixed number of mutable words. -/ +structure Node (width fields : Nat) where + key : BitVec width + data : Fin fields → BitVec width + +/-- Finite code, independent of tree size and word width. No instruction +contains a Lean function for computing its result. Arithmetic is modular. -/ +inductive Instruction (fields registers labels : Nat) where + | literal (dst : Fin registers) (value : Nat) (next : Fin labels) + | copy (dst src : Fin registers) (next : Fin labels) + | add (dst a b : Fin registers) (next : Fin labels) + | sub (dst a b : Fin registers) (next : Fin labels) + | branch (a b : Fin registers) (yes no : Fin labels) + | load (dst : Fin registers) (field : Fin fields) (next : Fin labels) + | store (field : Fin fields) (src : Fin registers) (next : Fin labels) + | key (dst : Fin registers) (next : Fin labels) + | query (dst : Fin registers) (next : Fin labels) + | bst (op : Multifinger.Opcode) (next : Fin labels) + | mark (next : Fin labels) + | finish + +structure Machine (fields registers labels : Nat) where + code : Fin labels → Instruction fields registers labels + entry : Fin labels + +/-- A semantic presentation of a linked tree and one persistent finger. +The zipper describes the finger; it is not an additional runtime stack. +Node links and the finger are represented by addresses in a concrete lowering. +There is no request history, pending output list, or arbitrary private state. -/ +structure State (width fields registers labels : Nat) where + cursor : LabelledCursor.Config (Node width fields) + regs : Fin registers → BitVec width + request : BitVec width + seen : Bool + pc : Option (Fin labels) + +/-- Scalar instructions and local metadata operations are charged even though +they emit no BST opcode. A request can finish only after an explicit visit. -/ +def eval {w f r l : Nat} (i : Instruction f r l) (s : State w f r l) : + Option (State w f r l × Option Multifinger.Opcode) := do + match i with + | .literal dst value next => + return ({ s with regs := Function.update s.regs dst (BitVec.ofNat w value), pc := some next }, none) + | .copy dst src next => + return ({ s with regs := Function.update s.regs dst (s.regs src), pc := some next }, none) + | .add dst a b next => + return ({ s with regs := Function.update s.regs dst (s.regs a + s.regs b), pc := some next }, none) + | .sub dst a b next => + return ({ s with regs := Function.update s.regs dst (s.regs a - s.regs b), pc := some next }, none) + | .branch a b yes no => + return ({ s with pc := some (if (s.regs a).toNat < (s.regs b).toNat then yes else no) }, none) + | .load dst field next => + let node ← s.cursor.read + return ({ s with regs := Function.update s.regs dst (node.data field), pc := some next }, none) + | .store field src next => + let node ← s.cursor.read + let cursor ← s.cursor.write { node with data := Function.update node.data field (s.regs src) } + return ({ s with cursor, pc := some next }, none) + | .key dst next => + let node ← s.cursor.read + return ({ s with regs := Function.update s.regs dst node.key, pc := some next }, none) + | .query dst next => + return ({ s with regs := Function.update s.regs dst s.request, pc := some next }, none) + | .bst op next => + let cursor ← LabelledCursor.perform op s.cursor + return ({ s with cursor, pc := some next }, some op) + | .mark next => + let node ← s.cursor.read + if node.key = s.request then return ({ s with seen := true, pc := some next }, none) + else none + | .finish => + if s.seen then return ({ s with pc := none }, none) else none + +def tick {w f r l : Nat} (p : Machine f r l) (s : State w f r l) := + s.pc.bind fun pc => eval (p.code pc) s + +/-- Input is available only at a response boundary, one key at a time. -/ +def accept {w f r l : Nat} (p : Machine f r l) (x : BitVec w) (s : State w f r l) : + Option (State w f r l) := + if s.pc = none then some { s with request := x, seen := false, pc := some p.entry } else none + +inductive Event (width : Nat) where + | input (key : BitVec width) + | compute (output : Option Multifinger.Opcode) + +/-- CSLib supplies the transition-system vocabulary, not the instruction set. -/ +def lts {w f r l : Nat} (p : Machine f r l) : Cslib.LTS (State w f r l) (Event w) where + Tr s event t := match event with + | .input x => accept p x s = some t + | .compute out => tick p s = some (t, out) + +/-- Proof-only execution log. Each constructor charges one machine instruction; +only emitted pointer instructions contribute to BST cost. -/ +inductive Run {w f r l : Nat} (p : Machine f r l) : + State w f r l → State w f r l → Nat → Nat → Prop where + | nil {s} : Run p s s 0 0 + | cons {s t u time cost out} : tick p s = some (t, out) → + Run p t u time cost → Run p s u (time + 1) (cost + out.toList.length) + +/-- One completed request. The initial state is a boundary state. -/ +def Responds {w f r l : Nat} (p : Machine f r l) (s : State w f r l) + (x : BitVec w) (t : State w f r l) (time cost : Nat) : Prop := + ∃ start, accept p x s = some start ∧ Run p start t time cost ∧ t.pc = none + +/-- Completed online accesses. The request list is specification data; it is +never passed to an instruction or stored in a machine state. -/ +inductive Execution {w f r l : Nat} (p : Machine f r l) : + State w f r l → List (BitVec w) → State w f r l → Nat → Nat → Prop where + | nil {s} : Execution p s [] s 0 0 + | cons {s t u x xs time cost moreTime moreCost} : Responds p s x t time cost → + Execution p t xs u moreTime moreCost → + Execution p s (x :: xs) u (time + moreTime) (cost + moreCost) + +/-- Total service is a separate obligation: finite code may otherwise fail or +loop. Quantification is over every completed history and every existing key. +`initial` is supplied separately; this does not give initialization free runtime. -/ +def Total {w f r l : Nat} (p : Machine f r l) (initial : State w f r l) (nodes : Nat) : Prop := + ∀ (xs : List (BitVec w)) (s : State w f r l) (time cost : Nat), + Execution p initial xs s time cost → ∀ x : BitVec w, x.toNat < nodes → + ∃ t moreTime moreCost, Responds p s x t moreTime moreCost + +/-- Additional efficiency obligation, not a consequence of bounded storage. +The additive request unit handles accesses already at the finger. -/ +def ProportionalTime {f r l : Nat} (p : Machine f r l) (constant : Nat) : Prop := + ∀ (w : Nat) (s t : State w f r l) (x : BitVec w) (time cost : Nat), + Responds p s x t time cost → time ≤ constant * (cost + 1) + +/-- Word-size discipline for a uniform family. Enough bits for addresses and +keys; at most logarithmically many bits. Constants do not depend on n. -/ +def WordSize (width : Nat → Nat) (constant : Nat) : Prop := + ∀ n, n < 2 ^ width n ∧ width n ≤ constant * (Nat.log2 (n + 1) + 1) + +/-- Ordered immutable keys 0,...,n-1 at initialization. The addressability +condition in `WordSize` prevents truncation of these keys. -/ +def Initial {w f r l : Nat} (s : State w f r l) (n : Nat) : Prop := + s.pc = none ∧ s.cursor.context = [] ∧ + s.cursor.tree.inorder.map Node.key = List.ofFn (fun i : Fin n => BitVec.ofNat w i.val) + +/-- Runtime bound restricted to reachable response boundaries. -/ +def EfficientFrom {w f r l : Nat} (p : Machine f r l) (initial : State w f r l) + (constant : Nat) : Prop := + ∀ (xs : List (BitVec w)) (s t : State w f r l) (a b time cost : Nat) (x : BitVec w), + Execution p initial xs s a b → Responds p s x t time cost → + time ≤ constant * (cost + 1) + +/-- Uniform implementation contract. Fixed code and register/field counts are +outside the size quantifier. Initialization is a specification, not free +executable preprocessing; a construction must separately account for setup. -/ +structure Implementation (fields registers labels : Nat) where + machine : Machine fields registers labels + width : Nat → Nat + wordConstant : Nat + wordSize : WordSize width wordConstant + initial : (n : Nat) → State (width n) fields registers labels + initialized : ∀ n, Initial (initial n) n + total : ∀ n, Total machine (initial n) n + timeConstant : Nat + efficient : ∀ n, EfficientFrom machine (initial n) timeConstant + +/-- Three links, one immutable key, and f metadata words per node; r scalar +registers, root/finger/query registers and a flag. Finite control is separate. -/ +def storageWords (fields registers nodes : Nat) : Nat := + (fields + 4) * nodes + registers + 4 + +end RotationBST.RealWorld diff --git a/RotationBST/Models/RealWorld/Linked/Abstract.lean b/RotationBST/Models/RealWorld/Linked/Abstract.lean new file mode 100644 index 0000000..e1d74d5 --- /dev/null +++ b/RotationBST/Models/RealWorld/Linked/Abstract.lean @@ -0,0 +1,28 @@ +module + +import RotationBST.Audit.Check +public import RotationBST.Models.RealWorld.Linked.AbstractBridge + +@[expose] public section +namespace RotationBST.RealWorld.Linked.Results + +/-- Every legal abstract pointer operation has a bounded-time concrete +implementation preserving the entire tree, all node data, and exact storage. -/ +theorem primitive {w e regs : Nat} {s : State w e regs} {c d : Cursor w e} + {op : Multifinger.Opcode} (rep : Realizes s c) + (legal : LabelledCursor.perform op c = some d) : + ∃ t time, time ≤ 19 ∧ Cslib.PointerMachine.Executes (program op) (start s) t time ∧ + Realizes t d ∧ t.heap.length = s.heap.length := Linked.primitive rep legal + +end RotationBST.RealWorld.Linked.Results + +/-- info: abstract audit passed for `RotationBST.RealWorld.Linked.Results`: 1 root declarations -/ +#guard_msgs in +#check_bst_abstract RotationBST.RealWorld.Linked.Results allowing [ + RotationBST.Models.RealWorld.Linked.Definitions.Abstract, + RotationBST.Models.RealWorld.PointerMachine.Definitions.Abstract, + RotationBST.Models.Labelled.Cursor.Definitions.Abstract, + RotationBST.Models.Multifinger.Program.Definitions.Abstract, + RotationBST.Models.Rotation.Abstract, + RotationBST.Models.Labelled.Ordering.Definitions.Abstract, + CslibFrontier.Computability.PointerMachine.Defs] diff --git a/RotationBST/Models/RealWorld/Linked/AbstractBridge.lean b/RotationBST/Models/RealWorld/Linked/AbstractBridge.lean new file mode 100644 index 0000000..edf6cc3 --- /dev/null +++ b/RotationBST/Models/RealWorld/Linked/AbstractBridge.lean @@ -0,0 +1,3 @@ +module + +public import RotationBST.Models.RealWorld.Linked.Simulation diff --git a/RotationBST/Models/RealWorld/Linked/Definitions/Abstract.lean b/RotationBST/Models/RealWorld/Linked/Definitions/Abstract.lean new file mode 100644 index 0000000..91ea6a4 --- /dev/null +++ b/RotationBST/Models/RealWorld/Linked/Definitions/Abstract.lean @@ -0,0 +1,115 @@ +module + +public import RotationBST.Models.RealWorld.PointerMachine.Definitions.Abstract + +@[expose] public section +namespace RotationBST.RealWorld.Linked +open Cslib.PointerMachine (Pointer) + +/-- Cursor, root, parent, grandparent, middle subtree, null and comparison +register; a fixed scalar register file; left, right and parent fields. -/ +abbrev layout (extra regs : Nat) : Cslib.PointerMachine.Layout := ⟨7, regs, 3, extra + 1⟩ +abbrev State (w e regs : Nat) := Cslib.PointerMachine.State (PointerMachine.words w) (layout e regs) +abbrev Record (w e regs : Nat) := Cslib.PointerMachine.Record (PointerMachine.words w) (layout e regs) +abbrev Instruction (w e regs : Nat) := Cslib.PointerMachine.Instr (PointerMachine.words w) (layout e regs) +/-- Ghost labels retain every data field, so representation preservation also +preserves metadata. The address is not available to scalar instructions. -/ +abbrev Label (w e : Nat) := Nat × (Fin (e + 1) → BitVec w) +abbrev Tree (w e : Nat) := LabelledTree (Label w e) +abbrev Cursor (w e : Nat) := LabelledCursor.Config (Label w e) + +variable {regs : Nat} + +def root {w e : Nat} : Tree w e → Pointer + | .nil => none + | .node _ x _ => some x.1 + +def parent {w e : Nat} : List (LabelledCursor.Frame (Label w e)) → Pointer + | [] => none + | .left x _ :: _ | .right _ x :: _ => some x.1 + +def node {w e : Nat} (l r p : Pointer) (x : Label w e) : Record w e regs := + ⟨fun i => if i = 0 then l else if i = 1 then r else p, x.2⟩ + +def Represents {w e : Nat} (h : List (Record w e regs)) : Pointer → Tree w e → Prop + | _, .nil => True + | p, .node l x r => h[x.1]? = some (node (root l) (root r) p x) ∧ + Represents h (some x.1) l ∧ Represents h (some x.1) r + +/-- Representation of ancestors and siblings, parameterized by the link to +the focused subtree. This is a proof-only zipper, not a stored stack. -/ +def Context {w e : Nat} (h : List (Record w e regs)) : + Pointer → List (LabelledCursor.Frame (Label w e)) → Prop + | _, [] => True + | p, .left x r :: cs => + h[x.1]? = some (node p (root r) (parent cs) x) ∧ + Represents h (some x.1) r ∧ Context h (some x.1) cs + | p, .right l x :: cs => + h[x.1]? = some (node (root l) p (parent cs) x) ∧ + Represents h (some x.1) l ∧ Context h (some x.1) cs + +def keys {w e : Nat} : Tree w e → LabelledTree Nat + | .nil => .nil + | .node l x r => .node (keys l) (x.2 0).toNat (keys r) + +def addresses {w e : Nat} (t : Tree w e) := t.inorder.map Prod.fst + +/-- A complete representation at any nonempty cursor, with no extra records. -/ +structure Realizes {w e : Nat} (s : State w e regs) (c : Cursor w e) : Prop where + valid : s.Valid + focus : Represents s.heap (parent c.context) c.focus + context : Context s.heap (root c.focus) c.context + distinct : (addresses c.tree).Nodup + covers : ∀ a, a < s.heap.length ↔ a ∈ addresses c.tree + ordered : (keys c.tree).Ordered + cursor : s.ptr 0 = root c.focus + rootReg : s.ptr 1 = root c.tree + nonempty : c.focus ≠ .nil + +/-- Both upward opcodes follow the same parent field. Their side conditions +are supplied by the legal abstract step. -/ +def move {w e : Nat} (field : Fin 3) : List (Instruction w e regs) := + [.loadPtr 0 field 0, .halt] + +/-- Promote the cursor above its parent. `side` is the cursor's side in its +parent and `other` its opposite. Branches inspect the grandparent to repair +the appropriate link, or update the root register when the parent was root. +Null middle subtrees require no special branch: stores through null are no-ops. -/ +def rotate {w e : Nat} (side other : Fin 3) : List (Instruction w e regs) := + [ .loadPtr 2 2 0, -- 0: parent + .loadPtr 3 2 2, -- 1: grandparent + .loadPtr 4 other 0, -- 2: middle subtree + .storePtr side 2 4, -- 3: parent's child = middle + .storePtr 2 4 2, -- 4: middle's parent = parent + .storePtr other 0 2, -- 5: cursor's child = parent + .storePtr 2 2 0, -- 6: parent's parent = cursor + .storePtr 2 0 3, -- 7: cursor's parent = grandparent + .null 5, -- 8 + .ifPtrEq 3 5 16, -- 9: root case + .loadPtr 6 0 3, -- 10 + .ifPtrEq 6 2 14, -- 11: parent was grandparent's left child + .storePtr 1 3 0, -- 12: right link + .goto 17, -- 13 + .storePtr 0 3 0, -- 14: left link + .goto 17, -- 15 + .movePtr 1 0, -- 16: root register + .halt ] -- 17 + +def program {w e : Nat} : Multifinger.Opcode → List (Instruction w e regs) + | .downLeft => move 0 + | .downRight => move 1 + | .upLeft | .upRight => move 2 + | .rotateLeftChild => rotate 0 1 + | .rotateRightChild => rotate 1 0 + +/-- Each invocation starts at its entry. Registers and heap persist. -/ +def start {w e : Nat} (s : State w e regs) : State w e regs := { s with pc := 0 } + +/-- A finite evaluator used to name endpoints, not an extra machine primitive. -/ +def run {w e : Nat} (code : List (Instruction w e regs)) : Nat → State w e regs → State w e regs + | 0, s => s + | n + 1, s => match Cslib.PointerMachine.step code s with + | none => s + | some t => run code n t + +end RotationBST.RealWorld.Linked diff --git a/RotationBST/Models/RealWorld/Linked/Execution.lean b/RotationBST/Models/RealWorld/Linked/Execution.lean new file mode 100644 index 0000000..dd3dac2 --- /dev/null +++ b/RotationBST/Models/RealWorld/Linked/Execution.lean @@ -0,0 +1,66 @@ +module + +public import RotationBST.Models.RealWorld.Linked.Navigation +import Mathlib.Tactic.IntervalCases +import Mathlib.Tactic.FinCases + +@[expose] public section +namespace RotationBST.RealWorld.Linked +open Cslib.PointerMachine (Instr Runs Executes step) +variable {w e regs : Nat} + +/-- Bounded evaluator results are backed by actual charged execution, including halt. -/ +theorem run_executes (code : List (Instruction w e regs)) (fuel : Nat) (s : State w e regs) + (h : code[(run code fuel s).pc]? = some .halt) : + ∃ time ≤ fuel + 1, Executes code s (run code fuel s) time := by + induction fuel generalizing s with + | zero => exact ⟨1, by omega, 0, .refl s, h, rfl⟩ + | succ n ih => + cases hs : step code s with + | none => + simp only [run, hs] at h ⊢ + exact ⟨1, by omega, 0, .refl s, h, rfl⟩ + | some t => + simp only [run, hs] at h ⊢ + obtain ⟨time, bound, k, steps, halt, eq⟩ := ih t h + refine ⟨time + 1, by omega, k + 1, ?_, halt, by omega⟩ + exact .head _ _ _ _ hs steps + +theorem run_step (code : List (Instruction w e regs)) (n : Nat) (s : State w e regs) + (i : Instruction w e regs) (h : code[s.pc]? = some i) (ne : i ≠ .halt) : + run code (n + 1) s = run code n { i.effect s with pc := i.next s } := by + simp only [run, step, h] + +theorem run_halt (code : List (Instruction w e regs)) (n : Nat) (s : State w e regs) + (h : code[s.pc]? = some .halt) : run code n s = s := by + cases n <;> simp [run, step, h] + +theorem rotate_progress (s : State w e regs) (side other : Fin 3) (bound : s.pc < 17) : + ∃ t, step (rotate side other) s = some t ∧ s.pc < t.pc ∧ t.pc ≤ 17 := by + generalize hp : s.pc = n at * + interval_cases n <;> simp [step, rotate, hp, Instr.next] + all_goals split_ifs <;> simp_all + +theorem rotate_halts_aux (side other : Fin 3) (fuel : Nat) (s : State w e regs) + (bound : s.pc ≤ 17) (enough : 17 - s.pc < fuel) : + (rotate (w := w) (e := e) (regs := regs) side other)[(run (rotate side other) fuel s).pc]? = some .halt := by + induction fuel generalizing s with + | zero => omega + | succ n ih => + by_cases done : s.pc = 17 + · rw [run_halt _ _ _ (by simp [rotate, done])] + simp [rotate, done] + · obtain ⟨t, hs, ht, hb⟩ := rotate_progress s side other (by omega) + simp only [run, hs] + exact ih t hb (by omega) + +theorem rotate_halts (s : State w e regs) (side other : Fin 3) : + (rotate (w := w) (e := e) (regs := regs) side other)[(run (rotate side other) 18 (start s)).pc]? = some .halt := + rotate_halts_aux side other 18 (start s) (by simp [start]) (by simp [start]) + +theorem rotate_time (s : State w e regs) (side other : Fin 3) : + ∃ time ≤ 19, Executes (rotate side other) (start s) + (run (rotate side other) 18 (start s)) time := + run_executes _ _ _ (rotate_halts s side other) + +end RotationBST.RealWorld.Linked diff --git a/RotationBST/Models/RealWorld/Linked/Heap.lean b/RotationBST/Models/RealWorld/Linked/Heap.lean new file mode 100644 index 0000000..3eb3c73 --- /dev/null +++ b/RotationBST/Models/RealWorld/Linked/Heap.lean @@ -0,0 +1,100 @@ +module + +public import RotationBST.Models.RealWorld.Linked.Execution +import Mathlib.Tactic.FinCases + +@[expose] public section +namespace RotationBST.RealWorld.Linked +open Cslib.PointerMachine (Pointer) +variable {w e regs : Nat} + +@[simp] theorem root_node (l r : Tree w e) (x : Label w e) : + root (.node l x r) = some x.1 := rfl + + +/-- Addresses belonging to the ancestors and siblings, excluding the focus. -/ +def outside : List (LabelledCursor.Frame (Label w e)) → List Nat + | [] => [] + | .left x r :: cs => x.1 :: addresses r ++ outside cs + | .right l x :: cs => x.1 :: addresses l ++ outside cs + +@[simp] theorem addresses_node (a b : Tree w e) (x : Label w e) : + addresses (.node a x b) = addresses a ++ x.1 :: addresses b := by + simp [addresses, LabelledTree.inorder] + +theorem represents_congr {h k : List (Record w e regs)} {t : Tree w e} {p : Pointer} + (rep : Represents h p t) (agree : ∀ a ∈ addresses t, k[a]? = h[a]?) : + Represents k p t := by + induction t generalizing p with + | nil => trivial + | node l x r il ir => + refine ⟨?_, il rep.2.1 ?_, ir rep.2.2 ?_⟩ + · rw [agree x.1 (by simp), rep.1] + · intro a ha; exact agree a (by simp [ha]) + · intro a ha; exact agree a (by simp [ha]) + +theorem context_congr {h k : List (Record w e regs)} + {cs : List (LabelledCursor.Frame (Label w e))} {p : Pointer} + (rep : Context h p cs) (agree : ∀ a ∈ outside cs, k[a]? = h[a]?) : Context k p cs := by + induction cs generalizing p with + | nil => trivial + | cons f cs ih => + cases f with + | left x r => + refine ⟨?_, represents_congr rep.2.1 ?_, ih rep.2.2 ?_⟩ + · rw [agree x.1 (by simp [outside]), rep.1] + · intro a ha; exact agree a (by simp [outside, ha]) + · intro a ha; exact agree a (by simp [outside, ha]) + | right l x => + refine ⟨?_, represents_congr rep.2.1 ?_, ih rep.2.2 ?_⟩ + · rw [agree x.1 (by simp [outside]), rep.1] + · intro a ha; exact agree a (by simp [outside, ha]) + · intro a ha; exact agree a (by simp [outside, ha]) + +/-- Changing only the root's parent field reparents a subtree. -/ +theorem represents_reparent {h k : List (Record w e regs)} {t : Tree w e} {p q : Pointer} + (rep : Represents h p t) + (change : ∀ a ∈ addresses t, + k[a]? = (h[a]?).map (fun n => if some a = root t then + { n with ptr := Function.update n.ptr 2 q } else n)) + (distinct : (addresses t).Nodup) : Represents k q t := by + cases t with + | nil => trivial + | node l x r => + have nd := distinct + simp only [addresses_node, List.nodup_append, List.nodup_cons] at nd + refine ⟨?_, represents_congr rep.2.1 ?_, represents_congr rep.2.2 ?_⟩ + · rw [change x.1 (by simp), rep.1] + simp [root, node] + funext f + fin_cases f <;> simp + · intro a ha + have ne : a ≠ x.1 := by grind + simpa [root, ne] using change a (by simp [ha]) + · intro a ha + have ne : a ≠ x.1 := by grind + simpa [root, ne] using change a (by simp [ha]) + +theorem nodup_plug (cs : List (LabelledCursor.Frame (Label w e))) (t : Tree w e) : + (addresses (LabelledCursor.plug cs t)).Nodup ↔ (addresses t ++ outside cs).Nodup := by + induction cs generalizing t with + | nil => simp [LabelledCursor.plug, outside] + | cons f cs ih => + cases f <;> + simp only [LabelledCursor.plug, ih, outside, addresses_node, List.nodup_append, + List.nodup_cons, List.mem_append, List.mem_cons] <;> grind + +theorem root_mem {t : Tree w e} {a : Nat} (h : root t = some a) : a ∈ addresses t := by + cases t <;> simp_all [root] + +theorem parent_mem {cs : List (LabelledCursor.Frame (Label w e))} {a : Nat} + (h : parent cs = some a) : a ∈ outside cs := by + cases cs with + | nil => simp [parent] at h + | cons f cs => cases f <;> simp_all [parent, outside] + +def contextSide : List (LabelledCursor.Frame (Label w e)) → Fin 3 + | .right .. :: _ => 1 + | _ => 0 + +end RotationBST.RealWorld.Linked diff --git a/RotationBST/Models/RealWorld/Linked/Navigation.lean b/RotationBST/Models/RealWorld/Linked/Navigation.lean new file mode 100644 index 0000000..a514f3b --- /dev/null +++ b/RotationBST/Models/RealWorld/Linked/Navigation.lean @@ -0,0 +1,75 @@ +module + +public import RotationBST.Models.RealWorld.Linked.Definitions.Abstract + +@[expose] public section +namespace RotationBST.RealWorld.Linked +open Cslib.PointerMachine (Instr Runs Executes) +variable {w e regs : Nat} + +/-- Named endpoint of a single pointer load. -/ +def moved (s : State w e regs) (field : Fin 3) : State w e regs := + { (Instr.loadPtr 0 field 0).effect s with pc := 1 } + +theorem move_executes (s : State w e regs) (field : Fin 3) : + Executes (move field) (start s) (moved s field) 2 := by + refine ⟨1, .single ?_, rfl, rfl⟩ + cases hd : s.deref 0 <;> + simp only [Cslib.PointerMachine.State.deref] at hd <;> + simp [Cslib.PointerMachine.step, move, start, moved, Instr.next, Instr.effect, + Cslib.PointerMachine.State.deref, Cslib.PointerMachine.State.setPtr, hd] + +theorem moved_eq {s : State w e regs} {x : Label w e} {l r p : Cslib.PointerMachine.Pointer} + (cur : s.ptr 0 = some x.1) (hr : s.heap[x.1]? = some (node l r p x)) (f : Fin 3) : + moved s f = { s.setPtr 0 ((node (regs := regs) l r p x).ptr f) with pc := 1 } := by + simp [moved, Instr.effect, Cslib.PointerMachine.State.deref, cur, hr] + +theorem downLeft {s : State w e regs} {a b r : Tree w e} {x y : Label w e} + {cs : List (LabelledCursor.Frame (Label w e))} + (h : Realizes s ⟨.node (.node a x b) y r, cs⟩) : + Realizes (moved s 0) ⟨.node a x b, .left y r :: cs⟩ := by + have hv := (move_executes s 0).valid h.valid + have eq := moved_eq h.cursor h.focus.1 0 + rw [eq] + refine ⟨?_, h.focus.2.1, ?_, h.distinct, h.covers, h.ordered, ?_, h.rootReg, by simp⟩ + · simpa [start, eq] using hv + · exact ⟨h.focus.1, h.focus.2.2, h.context⟩ + · simp [Cslib.PointerMachine.State.setPtr, node, root] + +theorem downRight {s : State w e regs} {l a b : Tree w e} {x y : Label w e} + {cs : List (LabelledCursor.Frame (Label w e))} + (h : Realizes s ⟨.node l x (.node a y b), cs⟩) : + Realizes (moved s 1) ⟨.node a y b, .right l x :: cs⟩ := by + have hv := (move_executes s 1).valid h.valid + have eq := moved_eq h.cursor h.focus.1 1 + rw [eq] + refine ⟨?_, h.focus.2.2, ?_, h.distinct, h.covers, h.ordered, ?_, h.rootReg, by simp⟩ + · simpa [start, eq] using hv + · exact ⟨h.focus.1, h.focus.2.1, h.context⟩ + · simp [Cslib.PointerMachine.State.setPtr, node, root] + +theorem upLeft {s : State w e regs} {a b r : Tree w e} {x y : Label w e} + {cs : List (LabelledCursor.Frame (Label w e))} + (h : Realizes s ⟨.node a x b, .left y r :: cs⟩) : + Realizes (moved s 2) ⟨.node (.node a x b) y r, cs⟩ := by + have hv := (move_executes s 2).valid h.valid + have eq := moved_eq h.cursor h.focus.1 2 + rw [eq] + refine ⟨?_, ?_, h.context.2.2, h.distinct, h.covers, h.ordered, ?_, h.rootReg, by simp⟩ + · simpa [start, eq] using hv + · exact ⟨h.context.1, h.focus, h.context.2.1⟩ + · simp [Cslib.PointerMachine.State.setPtr, node, root, parent] + +theorem upRight {s : State w e regs} {l a b : Tree w e} {x y : Label w e} + {cs : List (LabelledCursor.Frame (Label w e))} + (h : Realizes s ⟨.node a y b, .right l x :: cs⟩) : + Realizes (moved s 2) ⟨.node l x (.node a y b), cs⟩ := by + have hv := (move_executes s 2).valid h.valid + have eq := moved_eq h.cursor h.focus.1 2 + rw [eq] + refine ⟨?_, ?_, h.context.2.2, h.distinct, h.covers, h.ordered, ?_, h.rootReg, by simp⟩ + · simpa [start, eq] using hv + · exact ⟨h.context.1, h.context.2.1, h.focus⟩ + · simp [Cslib.PointerMachine.State.setPtr, node, root, parent] + +end RotationBST.RealWorld.Linked diff --git a/RotationBST/Models/RealWorld/Linked/Preservation.lean b/RotationBST/Models/RealWorld/Linked/Preservation.lean new file mode 100644 index 0000000..a860b8f --- /dev/null +++ b/RotationBST/Models/RealWorld/Linked/Preservation.lean @@ -0,0 +1,116 @@ +module + +public import RotationBST.Models.RealWorld.Linked.Rotation +import Mathlib.Tactic.FinCases + +@[expose] public section +namespace RotationBST.RealWorld.Linked +open Cslib.PointerMachine (Pointer) +variable {w e regs : Nat} + +set_option maxHeartbeats 800000 in +theorem pivot_left {h : List (Record w e regs)} {a b c : Tree w e} {x y : Label w e} {g : Pointer} + (rx : Represents h (some y.1) (.node a x b)) + (ry : h[y.1]? = some (node (some x.1) (root c) g y)) + (rc : Represents h (some y.1) c) + (nd : (addresses a ++ x.1 :: addresses b ++ y.1 :: addresses c).Nodup) : + Represents (pivot h x.1 y.1 (root b) g 0 1) g (.node a x (.node b y c)) := by + have hn := nd + simp only [List.nodup_append, List.nodup_cons, List.mem_append, List.mem_cons] at hn + have xy : x.1 ≠ y.1 := by grind + have bx : root b ≠ some x.1 := by intro hb; have := root_mem hb; grind + have byy : root b ≠ some y.1 := by intro hb; have := root_mem hb; grind + refine ⟨?_, ?_, ?_⟩ + · simp [pivot, rx.1, Ne.symm xy, bx, node] + funext i; fin_cases i <;> simp + · apply represents_congr rx.2.1 + intro z hz + have xz : x.1 ≠ z := by grind + have yz : y.1 ≠ z := by grind + have bz : root b ≠ some z := by intro hb; have := root_mem hb; grind + simp [pivot_other _ _ _ _ _ _ _ _ xz yz, bz] + · refine ⟨?_, ?_, ?_⟩ + · simp [pivot, ry, xy, byy, node] + funext i; fin_cases i <;> simp + · apply represents_reparent rx.2.2 + · intro z hz + have xz : x.1 ≠ z := by grind + have yz : y.1 ≠ z := by grind + simpa only [eq_comm (a := some z) (b := root b)] using pivot_other h x.1 y.1 z (root b) g 0 1 xz yz + · grind + · apply represents_congr rc + intro z hz + have xz : x.1 ≠ z := by grind + have yz : y.1 ≠ z := by grind + have bz : root b ≠ some z := by intro hb; have := root_mem hb; grind + simp [pivot_other _ _ _ _ _ _ _ _ xz yz, bz] + +set_option maxHeartbeats 800000 in +theorem pivot_right {h : List (Record w e regs)} {a b c : Tree w e} {x y : Label w e} {g : Pointer} + (rx : Represents h (some y.1) (.node b x c)) + (ry : h[y.1]? = some (node (root a) (some x.1) g y)) + (ra : Represents h (some y.1) a) + (nd : (addresses a ++ y.1 :: addresses b ++ x.1 :: addresses c).Nodup) : + Represents (pivot h x.1 y.1 (root b) g 1 0) g (.node (.node a y b) x c) := by + have hn := nd + simp only [List.nodup_append, List.nodup_cons, List.mem_append, List.mem_cons] at hn + have xy : x.1 ≠ y.1 := by grind + have bx : root b ≠ some x.1 := by intro hb; have := root_mem hb; grind + have byy : root b ≠ some y.1 := by intro hb; have := root_mem hb; grind + refine ⟨?_, ?_, ?_⟩ + · simp [pivot, rx.1, Ne.symm xy, bx, node] + funext i; fin_cases i <;> simp + · refine ⟨?_, ?_, ?_⟩ + · simp [pivot, ry, xy, byy, node] + funext i; fin_cases i <;> simp + · apply represents_congr ra + intro z hz + have xz : x.1 ≠ z := by grind + have yz : y.1 ≠ z := by grind + have bz : root b ≠ some z := by intro hb; have := root_mem hb; grind + simp [pivot_other _ _ _ _ _ _ _ _ xz yz, bz] + · apply represents_reparent rx.2.1 + · intro z hz + have xz : x.1 ≠ z := by grind + have yz : y.1 ≠ z := by grind + simpa only [eq_comm (a := some z) (b := root b)] using + pivot_other h x.1 y.1 z (root b) g 1 0 xz yz + · grind + · apply represents_congr rx.2.2 + intro z hz + have xz : x.1 ≠ z := by grind + have yz : y.1 ≠ z := by grind + have bz : root b ≠ some z := by intro hb; have := root_mem hb; grind + simp [pivot_other _ _ _ _ _ _ _ _ xz yz, bz] + +def reconnected (h : List (Record w e regs)) (x y : Nat) (beta : Pointer) + (cs : List (LabelledCursor.Frame (Label w e))) (side other : Fin 3) := + write (pivot h x y beta (parent cs) side other) (parent cs) (contextSide cs) (some x) + +/-- Reconnect the locally rotated tree to its arbitrary ancestor context. -/ +theorem reconnect {h : List (Record w e regs)} {t : Tree w e} + {cs : List (LabelledCursor.Frame (Label w e))} {x y : Nat} {beta : Pointer} + {side other : Fin 3} + (localRep : Represents (pivot h x y beta (parent cs) side other) (parent cs) t) + (ctx : Context h (some y) cs) (nd : (addresses t ++ outside cs).Nodup) + (xm : x ∈ addresses t) (ym : y ∈ addresses t) + (bm : ∀ z, beta = some z → z ∈ addresses t) (rt : root t = some x) : + Represents (reconnected h x y beta cs side other) (parent cs) t ∧ + Context (reconnected h x y beta cs side other) (root t) cs := by + have hn := nd + simp only [List.nodup_append] at hn + constructor + · apply represents_congr localRep + intro z hz + exact write_other _ _ _ _ z (by + intro heq; have := parent_mem heq; grind) + · rw [rt] + apply context_reconnect (p := some y) ?_ hn.2.1 + apply context_congr ctx + intro z hz + have xz : x ≠ z := by grind + have yz : y ≠ z := by grind + have bz : beta ≠ some z := by intro heq; have := bm z heq; grind + simp [pivot_other _ _ _ _ _ _ _ _ xz yz, bz] + +end RotationBST.RealWorld.Linked diff --git a/RotationBST/Models/RealWorld/Linked/Refinement.lean b/RotationBST/Models/RealWorld/Linked/Refinement.lean new file mode 100644 index 0000000..fb72101 --- /dev/null +++ b/RotationBST/Models/RealWorld/Linked/Refinement.lean @@ -0,0 +1,162 @@ +module + +public import RotationBST.Models.RealWorld.Linked.Preservation +public import RotationBST.Models.Labelled.Cursor.Map.Basic + +@[expose] public section +namespace RotationBST.RealWorld.Linked +open Cslib.PointerMachine (Pointer) +variable {w e regs : Nat} + +theorem effect_in_context (s : State w e regs) (side other : Fin 3) (x y : Nat) + (rx ry : Record w e regs) (cs : List (LabelledCursor.Frame (Label w e))) + (cur : s.ptr 0 = some x) (hx : s.heap[x]? = some rx) (hy : s.heap[y]? = some ry) + (px : rx.ptr 2 = some y) (py : ry.ptr 2 = parent cs) + (ctx : Context s.heap (some y) cs) + (apart : ∀ z ∈ outside cs, z ≠ x ∧ z ≠ y ∧ rx.ptr other ≠ some z) : + let t := run (rotate side other) 18 (start s) + t.heap = reconnected s.heap x y (rx.ptr other) cs side other ∧ + t.ptr 0 = some x ∧ t.ptr 1 = if parent cs = none then some x else s.ptr 1 := by + cases cs with + | nil => simpa [reconnected, parent, write] using + rotate_root_effect s side other x y rx ry cur hx hy px py + | cons f cs => + cases f with + | left g r => + have sep := apart g.1 (by simp [outside]) + have hh := rotate_inner_effect s side other x y g.1 rx ry + (node (some y) (root r) (parent cs) g) cur hx hy ctx.1 px py sep.1 sep.2.1 sep.2.2 + simpa [reconnected, parent, contextSide, node] using hh + | right l g => + have sep := apart g.1 (by simp [outside]) + have ne : root l ≠ some y := by + intro heq + have mem := root_mem heq + have := apart y (by simp [outside, mem]) + simp at this + have hh := rotate_inner_effect s side other x y g.1 rx ry + (node (root l) (some y) (parent cs) g) cur hx hy ctx.1 px py sep.1 sep.2.1 sep.2.2 + simpa [reconnected, parent, contextSide, node, ne] using hh + +theorem root_plug_congr (cs : List (LabelledCursor.Frame (Label w e))) + {s t : Tree w e} (eq : root s = root t) : + root (LabelledCursor.plug cs s) = root (LabelledCursor.plug cs t) := by + induction cs generalizing s t with + | nil => exact eq + | cons f cs ih => cases f <;> exact ih rfl + +theorem root_after_rotation (cs : List (LabelledCursor.Frame (Label w e))) + (a b c : Tree w e) (x y : Label w e) : + root (LabelledCursor.plug cs (.node a x (.node b y c))) = + if parent cs = none then some x.1 else + root (LabelledCursor.plug cs (.node (.node a x b) y c)) := by + cases cs with + | nil => rfl + | cons f cs => cases f <;> exact root_plug_congr cs rfl + +theorem keys_inorder (t : Tree w e) : + (keys t).inorder = t.inorder.map (fun x => (x.2 0).toNat) := by + induction t <;> simp_all [keys, LabelledTree.inorder] + +set_option maxHeartbeats 800000 in +theorem rotateLeftChild {s : State w e regs} {a b c : Tree w e} {x y : Label w e} + {cs : List (LabelledCursor.Frame (Label w e))} + (h : Realizes s ⟨.node a x b, .left y c :: cs⟩) : + Realizes (run (rotate 0 1) 18 (start s)) ⟨.node a x (.node b y c), cs⟩ := by + have nd : (addresses a ++ x.1 :: addresses b ++ y.1 :: addresses c ++ outside cs).Nodup := by + have := (nodup_plug (.left y c :: cs) (.node a x b)).mp h.distinct + simpa [outside, List.append_assoc] using this + have hn := nd + simp only [List.nodup_append, List.nodup_cons, List.mem_append, List.mem_cons] at hn + have apart : ∀ z ∈ outside cs, z ≠ x.1 ∧ z ≠ y.1 ∧ root b ≠ some z := by + intro z hz + refine ⟨by grind, by grind, ?_⟩ + intro heq; have := root_mem heq; grind + have eff := effect_in_context s 0 1 x.1 y.1 + (node (root a) (root b) (some y.1) x) + (node (some x.1) (root c) (parent cs) y) cs h.cursor h.focus.1 h.context.1 + (by simp [node]) (by simp [node]) h.context.2.2 (by simpa [node] using apart) + have localRep := pivot_left h.focus h.context.1 h.context.2.1 + (List.Nodup.of_append_left nd) + have nd' : (addresses (.node a x (.node b y c)) ++ outside cs).Nodup := by + simpa [List.append_assoc] using nd + obtain ⟨rep, ctx⟩ := reconnect localRep h.context.2.2 nd' + (by simp) (by simp) (fun z hz => by have := root_mem hz; simp [this]) rfl + have trace : LabelledCursor.perform .rotateLeftChild + ⟨.node a x b, .left y c :: cs⟩ = some ⟨.node a x (.node b y c), cs⟩ := rfl + have inorder := LabelledCursor.perform_inorder trace + have ad : addresses (LabelledCursor.plug cs (.node a x (.node b y c))) = + addresses (LabelledCursor.plug (.left y c :: cs) (.node a x b)) := by + exact congrArg (List.map Prod.fst) inorder.symm + have len : (run (rotate 0 1) 18 (start s)).heap.length = s.heap.length := by + rw [eff.1] + simp [reconnected, pivot] + obtain ⟨time, _, exec⟩ := rotate_time s 0 1 + refine ⟨exec.valid h.valid, ?_, ?_, ?_, ?_, ?_, eff.2.1, ?_, by simp⟩ + · rw [eff.1]; exact rep + · rw [eff.1]; exact ctx + · change (addresses (LabelledCursor.plug cs _)).Nodup + rw [ad]; exact h.distinct + · intro z; rw [len]; simpa only [LabelledCursor.Config.tree, ad] using h.covers z + · rw [Representation.ordered_iff, keys_inorder, ← inorder] + simpa only [keys_inorder] using (Representation.ordered_iff _).mp h.ordered + · rw [eff.2.2, h.rootReg] + exact (root_after_rotation cs a b c x y).symm + +theorem root_after_rotation_right (cs : List (LabelledCursor.Frame (Label w e))) + (a b c : Tree w e) (x y : Label w e) : + root (LabelledCursor.plug cs (.node (.node a y b) x c)) = + if parent cs = none then some x.1 else + root (LabelledCursor.plug cs (.node a y (.node b x c))) := by + cases cs with + | nil => rfl + | cons f cs => cases f <;> exact root_plug_congr cs rfl + +set_option maxHeartbeats 800000 in +theorem rotateRightChild {s : State w e regs} {a b c : Tree w e} {x y : Label w e} + {cs : List (LabelledCursor.Frame (Label w e))} + (h : Realizes s ⟨.node b x c, .right a y :: cs⟩) : + Realizes (run (rotate 1 0) 18 (start s)) ⟨.node (.node a y b) x c, cs⟩ := by + have nd : (addresses a ++ y.1 :: addresses b ++ x.1 :: addresses c ++ outside cs).Nodup := by + have := (nodup_plug (.right a y :: cs) (.node b x c)).mp h.distinct + simp only [outside, addresses_node, List.nodup_append, List.nodup_cons, + List.mem_append, List.mem_cons] at this ⊢ + grind + have hn := nd + simp only [List.nodup_append, List.nodup_cons, List.mem_append, List.mem_cons] at hn + have apart : ∀ z ∈ outside cs, z ≠ x.1 ∧ z ≠ y.1 ∧ root b ≠ some z := by + intro z hz + refine ⟨by grind, by grind, ?_⟩ + intro heq; have := root_mem heq; grind + have eff := effect_in_context s 1 0 x.1 y.1 + (node (root b) (root c) (some y.1) x) + (node (root a) (some x.1) (parent cs) y) cs h.cursor h.focus.1 h.context.1 + (by simp [node]) (by simp [node]) h.context.2.2 (by simpa [node] using apart) + have localRep := pivot_right h.focus h.context.1 h.context.2.1 + (List.Nodup.of_append_left nd) + have nd' : (addresses (.node (.node a y b) x c) ++ outside cs).Nodup := by + simpa [List.append_assoc] using nd + obtain ⟨rep, ctx⟩ := reconnect localRep h.context.2.2 nd' + (by simp) (by simp) (fun z hz => by have := root_mem hz; simp [this]) rfl + have trace : LabelledCursor.perform .rotateRightChild + ⟨.node b x c, .right a y :: cs⟩ = some ⟨.node (.node a y b) x c, cs⟩ := rfl + have inorder := LabelledCursor.perform_inorder trace + have ad : addresses (LabelledCursor.plug cs (.node (.node a y b) x c)) = + addresses (LabelledCursor.plug (.right a y :: cs) (.node b x c)) := by + exact congrArg (List.map Prod.fst) inorder.symm + have len : (run (rotate 1 0) 18 (start s)).heap.length = s.heap.length := by + rw [eff.1] + simp [reconnected, pivot] + obtain ⟨time, _, exec⟩ := rotate_time s 1 0 + refine ⟨exec.valid h.valid, ?_, ?_, ?_, ?_, ?_, eff.2.1, ?_, by simp⟩ + · rw [eff.1]; exact rep + · rw [eff.1]; exact ctx + · change (addresses (LabelledCursor.plug cs _)).Nodup + rw [ad]; exact h.distinct + · intro z; rw [len]; simpa only [LabelledCursor.Config.tree, ad] using h.covers z + · rw [Representation.ordered_iff, keys_inorder, ← inorder] + simpa only [keys_inorder] using (Representation.ordered_iff _).mp h.ordered + · rw [eff.2.2, h.rootReg] + exact (root_after_rotation_right cs a b c x y).symm + +end RotationBST.RealWorld.Linked diff --git a/RotationBST/Models/RealWorld/Linked/Rotation.lean b/RotationBST/Models/RealWorld/Linked/Rotation.lean new file mode 100644 index 0000000..02e6d97 --- /dev/null +++ b/RotationBST/Models/RealWorld/Linked/Rotation.lean @@ -0,0 +1,100 @@ +module + +public import RotationBST.Models.RealWorld.Linked.Heap +import Mathlib.Tactic.FinCases + +@[expose] public section +namespace RotationBST.RealWorld.Linked +open Cslib.PointerMachine (Pointer Instr step) +variable {w e regs : Nat} + +def write (h : List (Record w e regs)) (p : Pointer) (f : Fin 3) (v : Pointer) := + match p with + | none => h + | some a => h.modify a (fun r => { r with ptr := Function.update r.ptr f v }) + +@[simp] theorem write_length (h : List (Record w e regs)) (p : Pointer) (f : Fin 3) (v : Pointer) : + (write h p f v).length = h.length := by + cases p <;> simp [write] + +@[simp] theorem write_get (h : List (Record w e regs)) (p : Pointer) (f : Fin 3) + (v : Pointer) (z : Nat) : + (write h p f v)[z]? = (h[z]?).map (fun r => + if p = some z then { r with ptr := Function.update r.ptr f v } else r) := by + cases p <;> simp [write, List.getElem?_modify] + +/-- The five field writes common to both rotation directions. -/ +def pivot (h : List (Record w e regs)) (x y : Nat) (beta g : Pointer) (side other : Fin 3) := + write (write (write (write (write h (some y) side beta) beta 2 (some y)) + (some x) other (some y)) (some y) 2 (some x)) (some x) 2 g + +set_option maxRecDepth 8192 in +set_option maxHeartbeats 2000000 in +theorem rotate_root_effect (s : State w e regs) (side other : Fin 3) (x y : Nat) + (rx ry : Record w e regs) (cur : s.ptr 0 = some x) + (hx : s.heap[x]? = some rx) (hy : s.heap[y]? = some ry) + (px : rx.ptr 2 = some y) (py : ry.ptr 2 = none) : + let t := run (rotate side other) 18 (start s) + t.heap = pivot s.heap x y (rx.ptr other) none side other ∧ + t.ptr 0 = some x ∧ t.ptr 1 = some x := by + cases hb : rx.ptr other <;> + simp [run, step, rotate, start, Instr.effect, Instr.next, + Cslib.PointerMachine.State.deref, Cslib.PointerMachine.State.setPtr, + Cslib.PointerMachine.State.modify, cur, hx, hy, px, py, pivot, write, hb] + +set_option maxRecDepth 8192 in +set_option maxHeartbeats 2000000 in +theorem rotate_inner_effect (s : State w e regs) (side other : Fin 3) (x y g : Nat) + (rx ry rg : Record w e regs) (cur : s.ptr 0 = some x) + (hx : s.heap[x]? = some rx) (hy : s.heap[y]? = some ry) + (hg : s.heap[g]? = some rg) (px : rx.ptr 2 = some y) (py : ry.ptr 2 = some g) + (gx : g ≠ x) (gy : g ≠ y) (gb : rx.ptr other ≠ some g) : + let t := run (rotate side other) 18 (start s) + t.heap = write (pivot s.heap x y (rx.ptr other) (some g) side other) (some g) + (if rg.ptr 0 = some y then 0 else 1) (some x) ∧ + t.ptr 0 = some x ∧ t.ptr 1 = s.ptr 1 := by + cases hb : rx.ptr other <;> + simp [hb] at gb <;> + simp [run, step, rotate, start, Instr.effect, Instr.next, + Cslib.PointerMachine.State.deref, Cslib.PointerMachine.State.setPtr, + Cslib.PointerMachine.State.modify, cur, hx, hy, hg, px, py, pivot, write, + hb, Ne.symm gx, Ne.symm gy, gb] + all_goals split_ifs <;> simp_all + +theorem write_other (h : List (Record w e regs)) (p v : Pointer) (f : Fin 3) (z : Nat) + (ne : p ≠ some z) : (write h p f v)[z]? = h[z]? := by simp [ne] + +theorem pivot_other (h : List (Record w e regs)) (x y z : Nat) (beta g : Pointer) + (side other : Fin 3) (hx : x ≠ z) (hy : y ≠ z) : + (pivot h x y beta g side other)[z]? = + (h[z]?).map (fun r => if beta = some z then + { r with ptr := Function.update r.ptr 2 (some y) } else r) := by + simp [pivot, hx, hy, Function.comp_def] + +theorem context_reconnect {h : List (Record w e regs)} {cs : List (LabelledCursor.Frame (Label w e))} + {p q : Pointer} (rep : Context h p cs) (nd : (outside cs).Nodup) : + Context (write h (parent cs) (contextSide cs) q) q cs := by + cases cs with + | nil => trivial + | cons f cs => + cases f with + | left x r => + simp only [outside, List.nodup_cons, List.nodup_append] at nd + refine ⟨?_, represents_congr rep.2.1 ?_, context_congr rep.2.2 ?_⟩ + · simp [parent, contextSide, rep.1, node] + funext i; fin_cases i <;> simp + · intro z hz + exact write_other h _ _ _ z (by simp [parent]; grind) + · intro z hz + exact write_other h _ _ _ z (by simp [parent]; grind) + | right l x => + simp only [outside, List.nodup_cons, List.nodup_append] at nd + refine ⟨?_, represents_congr rep.2.1 ?_, context_congr rep.2.2 ?_⟩ + · simp [parent, contextSide, rep.1, node] + funext i; fin_cases i <;> simp + · intro z hz + exact write_other h _ _ _ z (by simp [parent]; grind) + · intro z hz + exact write_other h _ _ _ z (by simp [parent]; grind) + +end RotationBST.RealWorld.Linked diff --git a/RotationBST/Models/RealWorld/Linked/Simulation.lean b/RotationBST/Models/RealWorld/Linked/Simulation.lean new file mode 100644 index 0000000..27eb0fa --- /dev/null +++ b/RotationBST/Models/RealWorld/Linked/Simulation.lean @@ -0,0 +1,44 @@ +module + +public import RotationBST.Models.RealWorld.Linked.Refinement + +@[expose] public section +namespace RotationBST.RealWorld.Linked +variable {w e regs : Nat} + +theorem same_storage {s t : State w e regs} {c d : Cursor w e} + (hs : Realizes s c) (ht : Realizes t d) (same : c.tree.inorder = d.tree.inorder) : + t.heap.length = s.heap.length := by + have cov : ∀ a, a < s.heap.length ↔ a < t.heap.length := by + intro a + rw [hs.covers, ht.covers] + simp only [addresses, same] + have := cov s.heap.length + have := cov t.heap.length + omega + +/-- Every legal primitive has a concrete upstream program. The bound includes +halt, and no records are allocated. Dispatch between primitive programs is +not represented by this theorem; compiling a controller is a separate step. -/ +theorem primitive {s : State w e regs} {c d : Cursor w e} {op : Multifinger.Opcode} + (h : Realizes s c) (legal : LabelledCursor.perform op c = some d) : + ∃ t time, time ≤ 19 ∧ Cslib.PointerMachine.Executes (program op) (start s) t time ∧ + Realizes t d ∧ t.heap.length = s.heap.length := by + have same := LabelledCursor.perform_inorder legal + suffices result : ∃ t time, time ≤ 19 ∧ + Cslib.PointerMachine.Executes (program op) (start s) t time ∧ Realizes t d by + obtain ⟨t, time, bound, exec, rep⟩ := result + exact ⟨t, time, bound, exec, rep, same_storage h rep same⟩ + unfold LabelledCursor.perform at legal + split at legal <;> simp_all only [Option.some.injEq, reduceCtorEq] + all_goals subst d + · exact ⟨moved s 0, 2, by decide, move_executes s 0, downLeft h⟩ + · exact ⟨moved s 1, 2, by decide, move_executes s 1, downRight h⟩ + · exact ⟨moved s 2, 2, by decide, move_executes s 2, upLeft h⟩ + · exact ⟨moved s 2, 2, by decide, move_executes s 2, upRight h⟩ + · obtain ⟨time, bound, exec⟩ := rotate_time s 0 1 + exact ⟨_, time, bound, exec, rotateLeftChild h⟩ + · obtain ⟨time, bound, exec⟩ := rotate_time s 1 0 + exact ⟨_, time, bound, exec, rotateRightChild h⟩ + +end RotationBST.RealWorld.Linked diff --git a/RotationBST/Models/RealWorld/PointerMachine/Abstract.lean b/RotationBST/Models/RealWorld/PointerMachine/Abstract.lean new file mode 100644 index 0000000..77add67 --- /dev/null +++ b/RotationBST/Models/RealWorld/PointerMachine/Abstract.lean @@ -0,0 +1,55 @@ +module + +import RotationBST.Audit.Check +public import RotationBST.Models.RealWorld.PointerMachine.AbstractBridge + +@[expose] public section +namespace RotationBST.RealWorld.PointerMachine.Results + +variable {w e : Nat} + +/-- Completed request prefixes uniquely determine the actual machine state and time. -/ +theorem causal {p : Protocol w e} {s t u : State w e} + {xs : List (BitVec w)} {a b : Nat} + (h : Execution p s xs t a) (k : Execution p s xs u b) : t = u ∧ a = b := + execution_unique h k + +/-- A child-pointer load is one charged upstream instruction. -/ +theorem navigation_time (s : State w e) (side : Fin 2) (pc : s.pc = 0) : + Cslib.PointerMachine.Runs [down side, .halt] s (effects [down side] s) 1 := + down_runs s side pc + +/-- Navigation reaches the represented left subtree without changing its storage. -/ +theorem navigation {s : State w e} {l r : Tree w} {x : Nat × BitVec w} + (h : Represents s.heap (.node l x r)) (cursor : s.ptr 0 = some x.1) : + (effects [down 0] s).ptr 0 = root l ∧ + Represents (effects [down 0] s).heap l := down_left_refines h cursor + +/-- A root right rotation takes five upstream instructions before halt. -/ +theorem rotation_time (s : State w e) (pc : s.pc = 0) : + Cslib.PointerMachine.Runs (rotateRight ++ [.halt]) s (effects rotateRight s) 5 := + rotateRight_runs s pc + +/-- A root rotation preserves the ordered BST, its exact node storage, and validity. -/ +theorem rotation {s : State w e} {a b c : Tree w} {x y : Nat × BitVec w} + (h : Boundary s (.node (.node a x b) y c)) (pc : s.pc = 0) : + Boundary (effects rotateRight s) (.node a x (.node b y c)) ∧ + (effects rotateRight s).heap.length = s.heap.length := rotateRight_boundary h pc + +/-- The same change is down-left followed by the existing child rotation. -/ +theorem rotation_bst (a b c : Tree w) (x y : Nat × BitVec w) : + (LabelledCursor.perform .downLeft ⟨.node (.node a x b) y c, []⟩).bind + (LabelledCursor.perform .rotateLeftChild) = + some ⟨.node a x (.node b y c), []⟩ := rotateRight_cursor a b c x y + +end RotationBST.RealWorld.PointerMachine.Results + +/-- info: abstract audit passed for `RotationBST.RealWorld.PointerMachine.Results`: 6 root declarations -/ +#guard_msgs in +#check_bst_abstract RotationBST.RealWorld.PointerMachine.Results allowing [ + RotationBST.Models.RealWorld.PointerMachine.Definitions.Abstract, + RotationBST.Models.Labelled.Cursor.Definitions.Abstract, + RotationBST.Models.Multifinger.Program.Definitions.Abstract, + RotationBST.Models.Rotation.Abstract, + RotationBST.Models.Labelled.Ordering.Definitions.Abstract, + CslibFrontier.Computability.PointerMachine.Defs] diff --git a/RotationBST/Models/RealWorld/PointerMachine/AbstractBridge.lean b/RotationBST/Models/RealWorld/PointerMachine/AbstractBridge.lean new file mode 100644 index 0000000..e5086a2 --- /dev/null +++ b/RotationBST/Models/RealWorld/PointerMachine/AbstractBridge.lean @@ -0,0 +1,3 @@ +module + +public import RotationBST.Models.RealWorld.PointerMachine.Rotation diff --git a/RotationBST/Models/RealWorld/PointerMachine/Definitions/Abstract.lean b/RotationBST/Models/RealWorld/PointerMachine/Definitions/Abstract.lean new file mode 100644 index 0000000..aec8767 --- /dev/null +++ b/RotationBST/Models/RealWorld/PointerMachine/Definitions/Abstract.lean @@ -0,0 +1,112 @@ +module + +public import CslibFrontier.Computability.PointerMachine.Basic +public import RotationBST.Models.Labelled.Cursor.Abstract +public import RotationBST.Models.Labelled.Ordering.Abstract + +@[expose] public section +namespace RotationBST.RealWorld.PointerMachine + + +/-- The scalar instruction vocabulary is independent of word width. -/ +inductive WordOp where + | literal (n : Nat) | add | sub + +inductive WordTest where + | eq | lt + +/-- Modular words, with no conversion from a word to a pointer. -/ +abbrev words (w : Nat) : Cslib.PointerMachine.Model where + Value := BitVec w + undefined := 0 + Op := WordOp + Test := WordTest + evalOp + | .literal n, _, _ => BitVec.ofNat w n + | .add, x, y => x + y + | .sub, x, y => x - y + evalTest + | .eq, x, y => decide (x = y) + | .lt, x, y => decide (x.toNat < y.toNat) + +/-- Three pointer registers (cursor and two temporaries), two child fields, +one key field and `extra` metadata words. This initial representation has no +parent links: upward navigation needs a later representation extension. -/ +abbrev layout (extra : Nat) : Cslib.PointerMachine.Layout := ⟨3, 2, 2, extra + 1⟩ + +abbrev State (w extra : Nat) := Cslib.PointerMachine.State (words w) (layout extra) +abbrev Record (w extra : Nat) := Cslib.PointerMachine.Record (words w) (layout extra) +abbrev Instruction (w extra : Nat) := Cslib.PointerMachine.Instr (words w) (layout extra) +abbrev Tree (w : Nat) := LabelledTree (Nat × BitVec w) + +/-- Addresses in this specification are ghost labels, never scalar machine data. -/ +def root {w : Nat} : Tree w → Cslib.PointerMachine.Pointer + | .nil => none + | .node _ x _ => some x.1 + +def addresses {w : Nat} (t : Tree w) : List Nat := t.inorder.map Prod.fst + +def keys {w : Nat} : Tree w → LabelledTree Nat + | .nil => .nil + | .node l x r => .node (keys l) x.2.toNat (keys r) + +/-- Recursive representation in an actual upstream heap. Metadata is unrestricted. -/ +def Represents {w e : Nat} (heap : List (Record w e)) : Tree w → Prop + | .nil => True + | .node l x r => + (∃ record, heap[x.1]? = some record ∧ record.ptr 0 = root l ∧ + record.ptr 1 = root r ∧ record.data 0 = x.2) ∧ + Represents heap l ∧ Represents heap r + +/-- At a boundary all allocated records are exactly the distinct tree nodes. +There is no separate unaccounted work heap. -/ +structure Boundary {w e : Nat} (s : State w e) (t : Tree w) : Prop where + valid : s.Valid + represents : Represents s.heap t + distinct : (addresses t).Nodup + covers : ∀ a, a < s.heap.length ↔ a ∈ addresses t + ordered : (keys t).Ordered + cursor : s.ptr 0 = root t + +/-- Accepting the next key changes only its designated register and the entry +label. A suspended computation and all retained history must reside in `s`. -/ +def accept {w e : Nat} (entry : Nat) (key : BitVec w) (s : State w e) : State w e := + { s.setData 0 key with pc := entry } + +/-- Fixed code and a restart label. Halting is the request boundary. -/ +structure Protocol (w e : Nat) where + code : List (Instruction w e) + entry : Nat + + +/-- A response includes an actual visit along the execution, and counts the +halting instruction. The next key is unavailable until this response ends. -/ +def Responds {w e : Nat} (p : Protocol w e) (s : State w e) (key : BitVec w) + (t : State w e) (time : Nat) : Prop := + p.code[s.pc]? = some .halt ∧ + Cslib.PointerMachine.Executes p.code (accept p.entry key s) t time ∧ + ∃ u a b, Cslib.PointerMachine.Runs p.code (accept p.entry key s) u a ∧ + Cslib.PointerMachine.Runs p.code u t b ∧ (∃ record, u.deref 0 = some record ∧ record.data 0 = key) ∧ time = a + b + 1 + +/-- Histories are proof objects; they are not passed to the machine. -/ +inductive Execution {w e : Nat} (p : Protocol w e) : + State w e → List (BitVec w) → State w e → Nat → Prop where + | nil (s) : Execution p s [] s 0 + | cons {s t u key rest a b} : Responds p s key t a → + Execution p t rest u b → Execution p s (key :: rest) u (a + b) + +/-- Downward navigation is exactly one pointer load. -/ +def down {w e : Nat} (side : Fin 2) : Instruction w e := .loadPtr 0 side 0 + +/-- Root right rotation: load the left child and its right subtree, rewire +both child links, then put the new root in the cursor. No allocation. -/ +def rotateRight {w e : Nat} : List (Instruction w e) := + [.loadPtr 1 0 0, .loadPtr 2 1 1, .storePtr 0 0 2, .storePtr 1 1 0, .movePtr 0 1] + +/-- Straight-line effects, used only to name the endpoints of these programs. +The execution theorem separately establishes the actual charged `Cslib.PointerMachine.Runs`. -/ +def effects {w e : Nat} : List (Instruction w e) → State w e → State w e + | [], s => s + | i :: rest, s => effects rest { i.effect s with pc := s.pc + 1 } + +end RotationBST.RealWorld.PointerMachine diff --git a/RotationBST/Models/RealWorld/PointerMachine/Proofs.lean b/RotationBST/Models/RealWorld/PointerMachine/Proofs.lean new file mode 100644 index 0000000..8abc66f --- /dev/null +++ b/RotationBST/Models/RealWorld/PointerMachine/Proofs.lean @@ -0,0 +1,93 @@ +module + +public import RotationBST.Models.RealWorld.PointerMachine.Definitions.Abstract + +@[expose] public section +namespace RotationBST.RealWorld.PointerMachine +open Cslib.PointerMachine (Instr Runs Executes) + +variable {w e : Nat} + +theorem response_unique {p : Protocol w e} {s t u : State w e} + {key : BitVec w} {a b : Nat} + (h : Responds p s key t a) (k : Responds p s key u b) : t = u ∧ a = b := + h.2.1.unique k.2.1 + +theorem execution_unique {p : Protocol w e} {s t u : State w e} + {xs : List (BitVec w)} {a b : Nat} + (h : Execution p s xs t a) (k : Execution p s xs u b) : t = u ∧ a = b := by + induction h generalizing u b with + | nil => cases k; exact ⟨rfl, rfl⟩ + | cons h rest ih => + cases k with + | cons k more => + obtain ⟨rfl, rfl⟩ := response_unique h k + obtain ⟨rfl, rfl⟩ := ih more + exact ⟨rfl, rfl⟩ + +theorem execution_append {p : Protocol w e} {s t u : State w e} + {xs ys : List (BitVec w)} {a b : Nat} + (h : Execution p s xs t a) (k : Execution p t ys u b) : + Execution p s (xs ++ ys) u (a + b) := by + induction h with + | nil => simpa using k + | cons h _ ih => simpa [Nat.add_assoc] using Execution.cons h (ih k) + +/-- Following either child uses one actual instruction and leaves the heap unchanged. -/ +theorem down_effect (s : State w e) (side : Fin 2) (record : Record w e) + (h : s.deref 0 = some record) : + (down side).effect s = s.setPtr 0 (record.ptr side) := by + simp [down, Instr.effect, h] + +theorem down_runs (s : State w e) (side : Fin 2) (hpc : s.pc = 0) : + Runs [down side, .halt] s (effects [down side] s) 1 := by + apply Relation.RelatesInSteps.single + simp [Cslib.PointerMachine.step, hpc, effects, down, Instr.next] + +/-- Both subtree representation witnesses are retained by navigation. -/ +theorem down_left_refines {s : State w e} {l r : Tree w} {x : Nat × BitVec w} + (h : Represents s.heap (.node l x r)) (cursor : s.ptr 0 = some x.1) : + (effects [down 0] s).ptr 0 = root l ∧ + Represents (effects [down 0] s).heap l := by + obtain ⟨⟨record, hr, hl, _, _⟩, hleft, _⟩ := h + have hd : s.deref 0 = some record := by + simp [Cslib.PointerMachine.State.deref, cursor, hr] + simp [effects, down_effect s 0 record hd, Cslib.PointerMachine.State.setPtr, hl, hleft] + +/-- Replacing records outside a represented subtree preserves its representation. -/ +theorem represents_frame {h k : List (Record w e)} {t : Tree w} + (rep : Represents h t) (agree : ∀ a ∈ addresses t, k[a]? = h[a]?) : + Represents k t := by + induction t with + | nil => trivial + | node l x r il ir => + obtain ⟨⟨record, hr, hl, hh, hk⟩, rl, rr⟩ := rep + have mem : addresses (.node l x r) = addresses l ++ x.1 :: addresses r := by + simp [addresses, LabelledTree.inorder] + refine ⟨⟨record, ?_, hl, hh, hk⟩, il rl ?_, ir rr ?_⟩ + · rw [agree x.1 (by simp [mem]), hr] + · intro a ha; exact agree a (by simp [mem, ha]) + · intro a ha; exact agree a (by simp [mem, ha]) + +/-- The straight-line rotation executes five instructions; halt is a sixth. -/ +theorem rotateRight_runs (s : State w e) (hpc : s.pc = 0) : + Runs (rotateRight ++ [.halt]) s (effects rotateRight s) 5 := by + let s1 := { (Instr.loadPtr 1 0 0).effect s with pc := s.pc + 1 } + let s2 := { (Instr.loadPtr 2 1 1).effect s1 with pc := s1.pc + 1 } + let s3 := { (Instr.storePtr 0 0 2).effect s2 with pc := s2.pc + 1 } + let s4 := { (Instr.storePtr 1 1 0).effect s3 with pc := s3.pc + 1 } + let s5 := { (Instr.movePtr 0 1).effect s4 with pc := s4.pc + 1 } + have h1 : Cslib.PointerMachine.step (rotateRight ++ [.halt]) s = some s1 := by + simp [Cslib.PointerMachine.step, rotateRight, hpc, Instr.next, s1] + have h2 : Cslib.PointerMachine.step (rotateRight ++ [.halt]) s1 = some s2 := by + simp [Cslib.PointerMachine.step, rotateRight, s1, s2, hpc, Instr.next] + have h3 : Cslib.PointerMachine.step (rotateRight ++ [.halt]) s2 = some s3 := by + simp [Cslib.PointerMachine.step, rotateRight, s1, s2, s3, hpc, Instr.next] + have h4 : Cslib.PointerMachine.step (rotateRight ++ [.halt]) s3 = some s4 := by + simp [Cslib.PointerMachine.step, rotateRight, s1, s2, s3, s4, hpc, Instr.next] + have h5 : Cslib.PointerMachine.step (rotateRight ++ [.halt]) s4 = some s5 := by + simp [Cslib.PointerMachine.step, rotateRight, s1, s2, s3, s4, s5, hpc, Instr.next] + have run1 : Runs (rotateRight ++ [.halt]) s s1 1 := .single h1 + exact ((run1.tail _ _ _ _ h2).tail _ _ _ _ h3).tail _ _ _ _ h4 |>.tail _ _ _ _ h5 + +end RotationBST.RealWorld.PointerMachine diff --git a/RotationBST/Models/RealWorld/PointerMachine/Rotation.lean b/RotationBST/Models/RealWorld/PointerMachine/Rotation.lean new file mode 100644 index 0000000..4163a4a --- /dev/null +++ b/RotationBST/Models/RealWorld/PointerMachine/Rotation.lean @@ -0,0 +1,94 @@ +module + +public import RotationBST.Models.RealWorld.PointerMachine.Proofs + +@[expose] public section +namespace RotationBST.RealWorld.PointerMachine +open Cslib.PointerMachine (Instr) +variable {w e : Nat} + +/-- The two writes made by the right-rotation program. -/ +def rewired (heap : List (Record w e)) (x y : Nat) (beta : Cslib.PointerMachine.Pointer) := + (heap.modify y (fun r => { r with ptr := Function.update r.ptr 0 beta })).modify x + (fun r => { r with ptr := Function.update r.ptr 1 (some y) }) + +theorem rotation_effect (s : State w e) (x y : Nat) (rx ry : Record w e) + (cur : s.ptr 0 = some y) (hy : s.heap[y]? = some ry) + (hx : s.heap[x]? = some rx) (left : ry.ptr 0 = some x) : + (effects rotateRight s).heap = rewired s.heap x y (rx.ptr 1) ∧ + (effects rotateRight s).ptr 0 = some x := by + simp [effects, rotateRight, Instr.effect, Cslib.PointerMachine.State.deref, + Cslib.PointerMachine.State.setPtr, Cslib.PointerMachine.State.modify, + cur, hy, hx, left, rewired] + +theorem rewired_other (heap : List (Record w e)) (x y z : Nat) + (beta : Cslib.PointerMachine.Pointer) (hx : z ≠ x) (hy : z ≠ y) : + (rewired heap x y beta)[z]? = heap[z]? := by + simp [rewired, Ne.symm hx, Ne.symm hy] + +/-- Rotation preserves arbitrary represented subtrees away from the two pivots. -/ +theorem rewired_frame {heap : List (Record w e)} {t : Tree w} {x y : Nat} + {beta : Cslib.PointerMachine.Pointer} (h : Represents heap t) + (apart : ∀ z ∈ addresses t, z ≠ x ∧ z ≠ y) : + Represents (rewired heap x y beta) t := + represents_frame h (fun z hz => rewired_other heap x y z beta (apart z hz).1 (apart z hz).2) + +/-- Full recursive representation after a root rotation. Address separation is +explicit here; a valid tree with distinct addresses supplies it. -/ +theorem rotateRight_represents {s : State w e} {a b c : Tree w} {x y : Nat × BitVec w} + (rep : Represents s.heap (.node (.node a x b) y c)) + (cur : s.ptr 0 = some y.1) (different : x.1 ≠ y.1) + (apart : ∀ z ∈ addresses a ++ addresses b ++ addresses c, z ≠ x.1 ∧ z ≠ y.1) : + Represents (effects rotateRight s).heap (.node a x (.node b y c)) ∧ + (effects rotateRight s).ptr 0 = some x.1 := by + obtain ⟨⟨ry, hy, ly, ryright, ky⟩, ⟨⟨rx, hx, lx, rxright, kx⟩, ra, rb⟩, rc⟩ := rep + have eff := rotation_effect s x.1 y.1 rx ry cur hy hx ly + rw [eff.1] + refine ⟨⟨?_, ?_, ?_⟩, eff.2⟩ + · refine ⟨{ rx with ptr := Function.update rx.ptr 1 (some y.1) }, ?_, ?_, ?_, kx⟩ + · simp [rewired, Ne.symm different, hx] + · simpa using lx + · rfl + · exact rewired_frame ra (fun z hz => apart z (by simp [hz])) + · refine ⟨?_, ?_, ?_⟩ + · refine ⟨{ ry with ptr := Function.update ry.ptr 0 (rx.ptr 1) }, ?_, ?_, ryright, ky⟩ + · simp [rewired, different, hy] + · simpa using rxright + · exact rewired_frame rb (fun z hz => apart z (by simp [hz])) + · exact rewired_frame rc (fun z hz => apart z (by simp [hz])) + +/-- The represented change is precisely the existing down-left then rotation +operation. There is no new notion of tree rotation hidden in the machine layer. -/ +theorem rotateRight_cursor (a b c : Tree w) (x y : Nat × BitVec w) : + (LabelledCursor.perform .downLeft ⟨.node (.node a x b) y c, []⟩).bind + (LabelledCursor.perform .rotateLeftChild) = + some ⟨.node a x (.node b y c), []⟩ := rfl + +/-- The entire BST boundary invariant survives the program, with no new records. -/ +theorem rotateRight_boundary {s : State w e} {a b c : Tree w} {x y : Nat × BitVec w} + (h : Boundary s (.node (.node a x b) y c)) (hpc : s.pc = 0) : + Boundary (effects rotateRight s) (.node a x (.node b y c)) ∧ + (effects rotateRight s).heap.length = s.heap.length := by + have nd := h.distinct + simp only [addresses, LabelledTree.inorder, List.map_append, List.map_cons, + List.append_assoc, List.nodup_append, List.nodup_cons, + List.mem_append, List.mem_cons, List.mem_map] at nd + have different : x.1 ≠ y.1 := by grind + have apart : ∀ z ∈ addresses a ++ addresses b ++ addresses c, z ≠ x.1 ∧ z ≠ y.1 := by + simp only [addresses, List.mem_append, List.mem_map] + grind + obtain ⟨rep, cur⟩ := rotateRight_represents h.represents h.cursor different apart + obtain ⟨⟨ry, hy, ly, _, _⟩, ⟨⟨rx, hx, _, _, _⟩, _, _⟩, _⟩ := h.represents + have length : (effects rotateRight s).heap.length = s.heap.length := by + rw [(rotation_effect s x.1 y.1 rx ry h.cursor hy hx ly).1] + simp [rewired] + have addr : addresses (.node a x (.node b y c)) = addresses (.node (.node a x b) y c) := by + simp [addresses, LabelledTree.inorder, List.append_assoc] + refine ⟨⟨(rotateRight_runs s hpc).valid h.valid, rep, ?_, ?_, ?_, cur⟩, length⟩ + · rw [addr]; exact h.distinct + · intro z; rw [length, addr]; exact h.covers z + · rw [Representation.ordered_iff] + simpa [keys, LabelledTree.inorder, List.append_assoc] using + (Representation.ordered_iff _).mp h.ordered + +end RotationBST.RealWorld.PointerMachine diff --git a/RotationBST/Models/RealWorld/Proofs.lean b/RotationBST/Models/RealWorld/Proofs.lean new file mode 100644 index 0000000..d2d4663 --- /dev/null +++ b/RotationBST/Models/RealWorld/Proofs.lean @@ -0,0 +1,149 @@ +module + +public import RotationBST.Models.RealWorld.Definitions.Abstract +import Mathlib.Tactic + +@[expose] public section +namespace RotationBST.RealWorld + +/-- Erasing scalar work leaves either no tree change or one legal BST step. -/ +theorem eval_physical {w f r l : Nat} {i : Instruction f r l} + {s t : State w f r l} {out : Option Multifinger.Opcode} + (h : eval i s = some (t, out)) : + Pointer.Trace s.cursor.erase t.cursor.erase out.toList.length := by + cases i with + | literal | copy | add | sub | branch | query => + simp only [eval, Option.pure_def, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + exact .refl + | load | key => + simp only [eval, Option.bind_eq_bind, Option.bind_eq_some_iff, + Option.pure_def, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨node, _, rfl, rfl⟩ := h + exact .refl + | store => + simp only [eval, Option.bind_eq_bind, Option.bind_eq_some_iff, + Option.pure_def, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨node, _, cursor, written, rfl, rfl⟩ := h + change Pointer.Trace s.cursor.erase cursor.erase 0 + rw [LabelledCursor.Results.write_erase written] + exact .refl + | bst => + simp only [eval, Option.bind_eq_bind, Option.bind_eq_some_iff, + Option.pure_def, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨cursor, moved, rfl, rfl⟩ := h + exact .step (LabelledCursor.Results.perform_physical moved) .refl + | mark => + simp only [eval, Option.bind_eq_bind, Option.bind_eq_some_iff] at h + obtain ⟨node, _, h⟩ := h + split at h + · simp only [Option.pure_def, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + exact .refl + · contradiction + | finish => + simp only [eval] at h + split at h + · simp only [Option.pure_def, Option.some.injEq, Prod.mk.injEq] at h + obtain ⟨rfl, rfl⟩ := h + exact .refl + · contradiction + + theorem tick_physical {w f r l : Nat} {p : Machine f r l} + {s t : State w f r l} {out : Option Multifinger.Opcode} + (h : tick p s = some (t, out)) : + Pointer.Trace s.cursor.erase t.cursor.erase out.toList.length := by + unfold tick at h + cases hp : s.pc with + | none => simp [hp] at h + | some pc => exact eval_physical (by simpa [hp] using h) + + theorem trace_append {s t u : Pointer.Config} {a b : Nat} + (h : Pointer.Trace s t a) (k : Pointer.Trace t u b) : Pointer.Trace s u (a + b) := by + induction h with + | refl => simpa using k + | step step _ ih => simpa [Nat.add_assoc, Nat.add_comm, Nat.add_left_comm] using Pointer.Trace.step step (ih k) + + theorem run_physical {w f r l : Nat} {p : Machine f r l} + {s t : State w f r l} {time cost : Nat} (h : Run p s t time cost) : + Pointer.Trace s.cursor.erase t.cursor.erase cost := by + induction h with + | nil => exact .refl + | cons step _ ih => + simpa [Nat.add_comm] using trace_append (tick_physical step) ih + + theorem cost_le_time {w f r l : Nat} {p : Machine f r l} + {s t : State w f r l} {time cost : Nat} (h : Run p s t time cost) : cost ≤ time := by + induction h with + | nil => omega + | @cons s t u time cost out step rest ih => cases out <;> simp_all; omega + + theorem transition_deterministic {w f r l : Nat} (p : Machine f r l) + {s t u : State w f r l} {event : Event w} + (h : (lts p).Tr s event t) (k : (lts p).Tr s event u) : t = u := by + cases event <;> simp only [lts] at h k + · exact Option.some.inj (h.symm.trans k) + · exact congrArg Prod.fst (Option.some.inj (h.symm.trans k)) + + theorem boundary_stuck {w f r l : Nat} (p : Machine f r l) + (s : State w f r l) (h : s.pc = none) : tick p s = none := by + simp [tick, h] + +/-- Two completed runs from the same state agree, including both costs. -/ + theorem completed_unique {w f r l : Nat} {p : Machine f r l} + {s t : State w f r l} {time cost : Nat} (h : Run p s t time cost) + (halt : t.pc = none) : ∀ {u a b}, Run p s u a b → u.pc = none → + t = u ∧ time = a ∧ cost = b := by + induction h with + | nil => + intro u a b other stop + cases other with + | nil => exact ⟨rfl, rfl, rfl⟩ + | cons step rest => simp [boundary_stuck _ _ halt] at step + | @cons s v t time cost out step rest ih => + intro u a b other stop + cases other with + | nil => simp [boundary_stuck _ _ stop] at step + | cons step' rest' => + have eq := Option.some.inj (step.symm.trans step') + cases eq + obtain ⟨ht, ha, hb⟩ := ih halt rest' stop + exact ⟨ht, by omega, by omega⟩ + + theorem response_unique {w f r l : Nat} {p : Machine f r l} + {s t u : State w f r l} {x : BitVec w} {a b c d : Nat} + (h : Responds p s x t a b) (k : Responds p s x u c d) : + t = u ∧ a = c ∧ b = d := by + obtain ⟨start, hs, run, halt⟩ := h + obtain ⟨start', hs', run', halt'⟩ := k + have eq := Option.some.inj (hs.symm.trans hs') + subst start' + exact completed_unique run halt run' halt' + +/-- Causality: a completed request prefix has a unique retained state and costs. +Any continuation must therefore start from that same state. -/ + theorem execution_unique {w f r l : Nat} {p : Machine f r l} + {s t : State w f r l} {xs : List (BitVec w)} {a b : Nat} + (h : Execution p s xs t a b) : ∀ {u c d}, Execution p s xs u c d → + t = u ∧ a = c ∧ b = d := by + induction h with + | nil => intro u c d k; cases k; exact ⟨rfl, rfl, rfl⟩ + | cons response rest ih => + intro u c d k + cases k with + | cons response' rest' => + obtain ⟨eq, ha, hb⟩ := response_unique response response' + subst eq + obtain ⟨ht, hc, hd⟩ := ih rest' + exact ⟨ht, by omega, by omega⟩ + + theorem execution_append {w f r l : Nat} {p : Machine f r l} + {s t u : State w f r l} {xs ys : List (BitVec w)} {a b c d : Nat} + (h : Execution p s xs t a b) (k : Execution p t ys u c d) : + Execution p s (xs ++ ys) u (a + c) (b + d) := by + induction h with + | nil => simpa using k + | cons response rest ih => + simpa [Nat.add_assoc] using Execution.cons response (ih k) + +end RotationBST.RealWorld diff --git a/RotationBSTTests.lean b/RotationBSTTests.lean index fb80476..6d0cd02 100644 --- a/RotationBSTTests.lean +++ b/RotationBSTTests.lean @@ -1,5 +1,10 @@ module +import RotationBSTTests.RealWorld +import RotationBSTTests.PointerMachineBST +import RotationBSTTests.LinkedBST +import RotationBSTTests.CompiledBST + import RotationBSTTests.TangoBottomUp import RotationBSTTests.UniformCombination import RotationBSTTests.CombinationCharges diff --git a/RotationBSTTests/CompiledBST.lean b/RotationBSTTests/CompiledBST.lean new file mode 100644 index 0000000..20e4538 --- /dev/null +++ b/RotationBSTTests/CompiledBST.lean @@ -0,0 +1,148 @@ +module + +public import RotationBST.Models.RealWorld.Compiler.Abstract +import Mathlib.Tactic.FinCases + +@[expose] public section +namespace RotationBSTTests.CompiledBST +open RotationBST RealWorld +open RealWorld.Compiler + +set_option maxRecDepth 100000 +set_option maxHeartbeats 4000000 + +/-- Search a three-node tree, mark the visit, exercise all scalar and metadata +instructions, return to the root, and finish. The same code serves every request. -/ +def controller : Machine 1 3 18 where + entry := 0 + code pc := match pc.val with + | 0 => .query 0 1 + | 1 => .key 1 2 + | 2 => .branch 0 1 3 4 + | 3 => .bst .downLeft 6 + | 4 => .branch 1 0 5 6 + | 5 => .bst .downRight 6 + | 6 => .mark 7 + | 7 => .literal 2 1 8 + | 8 => .store 0 2 9 + | 9 => .load 2 0 10 + | 10 => .add 2 2 2 11 + | 11 => .sub 2 2 2 12 + | 12 => .copy 2 0 13 + | 13 => .branch 0 1 14 15 + | 14 => .bst .upLeft 17 + | 15 => .branch 1 0 16 17 + | 16 => .bst .upRight 17 + | _ => .finish + +def label (addr key : Nat) : Linked.Label 8 1 := + (addr, fun i => if i = 0 then BitVec.ofNat 8 key else 0) + +def cursor : Linked.Cursor 8 1 := + ⟨.node (.node .nil (label 1 1) .nil) (label 0 2) (.node .nil (label 2 3) .nil), []⟩ + +def initial : Target 8 1 3 := + ⟨boundary 18, fun r => if r = 0 ∨ r = 1 then some 0 else none, fun _ => 0, + [Linked.node (some 1) (some 2) none (label 0 2), + Linked.node none none (some 0) (label 1 1), + Linked.node none none (some 0) (label 2 3)]⟩ + +def sourceInitial : RealWorld.State 8 1 3 18 := + ⟨cursor.map decode, fun _ => 0, 0, false, none⟩ + +/-- The integration fixture satisfies the full source/target invariant. -/ +theorem initial_image : Image sourceInitial initial := by + refine ⟨cursor, ?_, rfl, ?_, rfl, ?_, rfl⟩ + · constructor + · constructor + · intro r a ha + fin_cases r <;> simp [initial] at ha <;> subst a <;> decide + · intro rec mem f a ha + simp only [initial, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl <;> + fin_cases f <;> simp [Linked.node] at ha <;> subst a <;> decide + · simp [initial, cursor, Linked.Represents, Linked.root, Linked.parent, label] + · trivial + · decide + · intro a + simp [initial, cursor, Linked.addresses, LabelledCursor.Config.tree, + LabelledCursor.plug, LabelledTree.inorder, label] + omega + · simp [cursor, Linked.keys, LabelledCursor.Config.tree, LabelledCursor.plug, + LabelledTree.Ordered, LabelledTree.inorder, label] + · rfl + · rfl + · simp [cursor] + · intro i; rfl + · decide + +def serve (key : BitVec 8) (s : Target 8 1 3) : Target 8 1 3 := + match Compiler.accept (l := 18) key s with + | none => s + | some input => Linked.run (compile controller) 100 input + +def first := serve 1 initial +def second := serve 3 first + +example : first.pc = boundary 18 ∧ first.ptr 0 = some 0 := by decide +example : (first.heap[1]).data 1 = 1 := by decide +example : second.pc = boundary 18 ∧ second.ptr 0 = some 0 := by decide +example : (second.heap[2]).data 1 = 1 ∧ (second.heap[1]).data 1 = 1 := by decide +example : second.data (queryReg 3) = 3 ∧ second.data (userReg (2 : Fin 3)) = 3 := by decide +example : second.heap.length = initial.heap.length := by decide +example : (compile (w := 8) controller).length = 436 := by decide + +/-- Real charged execution for both requests, without restarting or changing code. -/ +example : ∃ time, Compiler.Responds controller initial 1 first time := by + let input := (Compiler.accept (l := 18) 1 initial).getD initial + have acc : Compiler.accept (l := 18) 1 initial = some input := by rfl + have halted : (compile (w := 8) controller)[(Linked.run (compile controller) 100 input).pc]? = + some .halt := by rfl + obtain ⟨time, _, run⟩ := Linked.run_executes (compile controller) 100 input halted + exact ⟨time, input, acc, run⟩ + +example : ∃ time, Compiler.Responds controller first 3 second time := by + let input := (Compiler.accept (l := 18) 3 first).getD first + have acc : Compiler.accept (l := 18) 3 first = some input := by rfl + have halted : (compile (w := 8) controller)[(Linked.run (compile controller) 100 input).pc]? = + some .halt := by rfl + obtain ⟨time, _, run⟩ := Linked.run_executes (compile controller) 100 input halted + exact ⟨time, input, acc, run⟩ + +-- An unmarked finish cannot successfully halt, even after a preceding visit. +def unmarked : Machine 1 3 1 := ⟨fun _ => .finish, 0⟩ +def unmarkedInput : Target 8 1 3 := + { initial.setData (seenReg 3) 1 with pc := entry 1 } +example : (Linked.run (compile unmarked) 12 unmarkedInput).pc = trap 1 := by decide + +-- A failed mark goes to the nonhalting trap. +def wrongMark : Machine 1 3 2 := ⟨fun pc => if pc = 0 then .mark 1 else .finish, 0⟩ +def wrongInput : Target 8 1 3 := { initial.setData (queryReg 3) 7 with pc := entry 2 } +example : (Linked.run (compile wrongMark) 12 wrongInput).pc = trap 2 := by decide + +-- Rotation blocks are relocated away from address zero, and their final +-- halt is replaced by a charged continuation to mark and finish. +def rotating (right : Bool) : Machine 1 3 4 where + entry := 0 + code pc := match pc.val with + | 0 => .literal 0 7 1 + | 1 => .bst (if right then .rotateRightChild else .rotateLeftChild) 2 + | 2 => .mark 3 + | _ => .finish + +def rotationInput (right : Bool) : Target 8 1 3 := + ⟨entry 4, fun r => if r = 0 then some 1 else if r = 1 then some 0 else none, + fun i => if i = queryReg 3 then (if right then 3 else 1) else 0, + [Linked.node (if right then none else some 1) (if right then some 1 else none) + none (label 0 2), Linked.node none none (some 0) (label 1 (if right then 3 else 1))]⟩ + +def rotated (right : Bool) := Linked.run (compile (rotating right)) 50 (rotationInput right) +example : (rotated false).pc = boundary 4 ∧ (rotated false).ptr 1 = some 1 := by decide +example : (rotated true).pc = boundary 4 ∧ (rotated true).ptr 1 = some 1 := by decide +example : ((rotated false).heap[0]).ptr 2 = some 1 := by decide +example : ((rotated true).heap[1]).ptr 2 = none := by decide +example : (rotated true).data (userReg (0 : Fin 3)) = 7 := by decide + +#print axioms RotationBST.RealWorld.Compiler.execution_simulation +#print axioms RotationBST.RealWorld.Compiler.storage_preserved +end RotationBSTTests.CompiledBST diff --git a/RotationBSTTests/LinkedBST.lean b/RotationBSTTests/LinkedBST.lean new file mode 100644 index 0000000..898b724 --- /dev/null +++ b/RotationBSTTests/LinkedBST.lean @@ -0,0 +1,99 @@ +module + +public import RotationBST.Models.RealWorld.Linked.Abstract +import Mathlib.Tactic.FinCases + +@[expose] public section +namespace RotationBSTTests.LinkedBST +open RotationBST RealWorld.Linked + +def label (addr key : Nat) : Label 8 1 := + (addr, fun f => BitVec.ofNat 8 (if f = 0 then key else 10 * key)) + +def leaf (addr key : Nat) : Tree 8 1 := .node .nil (label addr key) .nil + +def tree : Tree 8 1 := + .node (.node (.node (leaf 3 1) (label 2 2) (leaf 4 3)) (label 1 4) (leaf 5 6)) + (label 0 8) (leaf 6 10) + +def cursor : Cursor 8 1 := + ⟨.node (leaf 3 1) (label 2 2) (leaf 4 3), + [.left (label 1 4) (leaf 5 6), .left (label 0 8) (leaf 6 10)]⟩ + +def initial : State 8 1 2 := + ⟨0, fun r => if r = 0 then some 2 else if r = 1 then some 0 else none, fun _ => 0, + [node (some 1) (some 6) none (label 0 8), + node (some 2) (some 5) (some 0) (label 1 4), + node (some 3) (some 4) (some 1) (label 2 2), + node none none (some 2) (label 3 1), + node none none (some 2) (label 4 3), + node none none (some 1) (label 5 6), + node none none (some 0) (label 6 10)]⟩ + +example : Realizes initial cursor := by + constructor + · constructor + · intro r a ha + fin_cases r <;> simp [initial] at ha <;> subst a <;> decide + · intro rec mem f a ha + simp only [initial, List.mem_cons, List.not_mem_nil, or_false] at mem + rcases mem with rfl | rfl | rfl | rfl | rfl | rfl | rfl <;> + fin_cases f <;> simp [node] at ha <;> subst a <;> decide + · simp [initial, cursor, Represents, parent, leaf, root, label] + · simp [initial, cursor, Context, Represents, parent, leaf, root, label] + · decide + · intro a + simp [initial, cursor, LabelledCursor.Config.tree, LabelledCursor.plug, + addresses, LabelledTree.inorder, leaf, label] + omega + · simp [cursor, LabelledCursor.Config.tree, LabelledCursor.plug, keys, + LabelledTree.Ordered, LabelledTree.inorder, leaf, label] + · rfl + · rfl + · simp [cursor] + +def rotated := run (program .rotateLeftChild) 18 (start initial) + +-- Non-root rotation with a nonempty transferred subtree. +example : rotated.ptr 0 = some 2 ∧ rotated.ptr 1 = some 0 := by decide +example : (rotated.heap[0]).ptr 0 = some 2 := by decide +example : (rotated.heap[1]).ptr 0 = some 4 ∧ (rotated.heap[1]).ptr 2 = some 2 := by decide +example : (rotated.heap[4]).ptr 2 = some 1 := by decide +example : (rotated.heap[2]).ptr 1 = some 1 ∧ (rotated.heap[2]).ptr 2 = some 0 := by decide +example : rotated.heap.map (fun r => r.data 1) = initial.heap.map (fun r => r.data 1) := by decide + +-- All four navigation opcodes follow the intended physical link. +example : (run (program .downLeft) 1 (start initial)).ptr 0 = some 3 := by decide +example : (run (program .downRight) 1 (start initial)).ptr 0 = some 4 := by decide +example : (run (program .upLeft) 1 (start initial)).ptr 0 = some 1 := by decide +example : (run (program .upRight) 1 (start (run (program .downRight) 1 (start initial)))).ptr 0 = some 2 := by decide + +-- Right-child promotion, reconnecting through the grandparent's right link. +def rightInitial : State 8 1 2 := + ⟨0, fun r => if r = 0 then some 3 else if r = 1 then some 0 else none, fun _ => 0, + [node none (some 1) none (label 0 0), + node (some 2) (some 3) (some 0) (label 1 2), + node none none (some 1) (label 2 1), + node (some 4) none (some 1) (label 3 4), + node none none (some 3) (label 4 3)]⟩ + +def rightRotated := run (program .rotateRightChild) 18 (start rightInitial) +example : (rightRotated.heap[0]).ptr 1 = some 3 := by decide +example : (rightRotated.heap[1]).ptr 1 = some 4 := by decide +example : (rightRotated.heap[4]).ptr 2 = some 1 := by decide +example : (rightRotated.heap[3]).ptr 0 = some 1 ∧ (rightRotated.heap[3]).ptr 2 = some 0 := by decide +example : rightRotated.ptr 1 = some 0 := by decide + +-- Rotating a child of the root repairs the root register and null parent. +def rootInitial (right : Bool) : State 8 1 2 := + ⟨0, fun r => if r = 0 then some 1 else if r = 1 then some 0 else none, fun _ => 0, + [node (if right then none else some 1) (if right then some 1 else none) none (label 0 2), + node none none (some 0) (label 1 (if right then 3 else 1))]⟩ + +example : (run (program .rotateLeftChild) 18 (rootInitial false)).ptr 1 = some 1 := by decide +example : (run (program .rotateRightChild) 18 (rootInitial true)).ptr 1 = some 1 := by decide +example : ((run (program .rotateLeftChild) 18 (rootInitial false)).heap[1]).ptr 2 = none := by decide +example : ((run (program .rotateRightChild) 18 (rootInitial true)).heap[1]).ptr 2 = none := by decide + +#print axioms RotationBST.RealWorld.Linked.Results.primitive +end RotationBSTTests.LinkedBST diff --git a/RotationBSTTests/PointerMachineBST.lean b/RotationBSTTests/PointerMachineBST.lean new file mode 100644 index 0000000..61dd219 --- /dev/null +++ b/RotationBSTTests/PointerMachineBST.lean @@ -0,0 +1,38 @@ +module + +public import RotationBST.Models.RealWorld.PointerMachine.Abstract + +@[expose] public section +namespace RotationBSTTests.PointerMachineBST +open RotationBST.RealWorld.PointerMachine + +-- Root 4 has left child 2, whose right child 3 is transferred by rotation. +-- Every record also has a metadata word which must survive the two writes. +def record (key tag : Nat) (l r : Option Nat) : Record 8 1 := + ⟨fun f => if f = 0 then l else r, + fun f => BitVec.ofNat 8 (if f = 0 then key else tag)⟩ + +def initial : State 8 1 := + ⟨0, fun _ => some 0, fun _ => 0, + [record 4 40 (some 1) none, record 2 20 none (some 2), record 3 30 none none]⟩ + +def finalState := effects rotateRight initial + +example : finalState.ptr 0 = some 1 := by decide +example : (finalState.heap[0]).ptr 0 = some 2 := by decide +example : (finalState.heap[1]).ptr 1 = some 0 := by decide +example : (finalState.heap[2]).ptr 0 = none := by decide +example : finalState.heap.map (fun r => r.data 1) = [40, 20, 30] := by decide +example : finalState.heap.length = initial.heap.length := by decide +example : Cslib.PointerMachine.Executes (rotateRight ++ [.halt]) initial finalState 6 := by + refine ⟨5, Results.rotation_time initial rfl, ?_, rfl⟩ + rfl + +-- Input injection preserves the heap and pointer registers; arithmetic is modular. +example : (accept 7 9 initial).heap = initial.heap := rfl +example : (accept 7 9 initial).ptr = initial.ptr := rfl +example : (words 8).evalOp .add 255 1 = 0 := by decide + +#print axioms RotationBST.RealWorld.PointerMachine.Results.rotation +#print axioms RotationBST.RealWorld.PointerMachine.Results.causal +end RotationBSTTests.PointerMachineBST diff --git a/RotationBSTTests/RealWorld.lean b/RotationBSTTests/RealWorld.lean new file mode 100644 index 0000000..052e845 --- /dev/null +++ b/RotationBSTTests/RealWorld.lean @@ -0,0 +1,38 @@ +module + +import RotationBST.Models.RealWorld.Abstract + +open RotationBST RotationBST.RealWorld + +private def program : Machine 1 2 2 where + code i := if i.val = 0 then .mark 1 else .finish + entry := 0 + +private def boundary : State 4 1 2 2 where + cursor := ⟨.node .nil ⟨3, fun _ => 0⟩ .nil, []⟩ + regs := fun _ => 0 + request := 0 + seen := false + pc := none + +private def active : State 4 1 2 2 := { boundary with request := 3, pc := some 0 } + +example : accept program 3 boundary = some active := rfl +example : accept program 2 active = none := rfl +example : tick program active = some ({ active with seen := true, pc := some 1 }, none) := rfl +example : eval (.mark 1) { active with request := 2 } = none := rfl +example : eval .finish active = none := rfl +example : eval (.bst .upLeft 1) active = none := rfl +example : eval (.add 0 0 1 1) { active with regs := fun _ => 15 } = + some ({ active with regs := Function.update (fun _ : Fin 2 => (15 : BitVec 4)) 0 14, pc := some 1 }, none) := rfl +example : eval (.store 0 1 1) active = some ({ active with pc := some 1 }, none) := by + simp [eval, active, boundary, LabelledCursor.Config.read, LabelledCursor.Config.write] + +/-- The known-key singleton program takes two scalar steps and no BST steps. -/ +example : Responds program boundary 3 { active with seen := true, pc := none } 2 0 := by + refine ⟨active, rfl, ?_, rfl⟩ + apply Run.cons (t := { active with seen := true, pc := some 1 }) (out := none) (by rfl) + exact Run.cons (out := none) (by rfl) Run.nil + +example : accept program 2 { active with seen := true, pc := none } = + some { active with request := 2, seen := false, pc := some 0 } := rfl diff --git a/book/src/book.json b/book/src/book.json index 0b7a804..73a491c 100644 --- a/book/src/book.json +++ b/book/src/book.json @@ -25,6 +25,7 @@ { "slug": "online", "file": "models/online.md", "title": "Online algorithms and cost" }, { "slug": "dictionary", "file": "models/dictionary.md", "title": "Insertions and deletions" }, { "slug": "pointer", "file": "models/pointer.md", "title": "The pointer machine" }, + { "slug": "real-world", "file": "models/real-world.md", "title": "Real-world BST implementations" }, { "slug": "regions", "file": "models/regions.md", "title": "Touched regions" }, { "slug": "geometry", "file": "models/geometry.md", "title": "The geometric view" }, { "slug": "fingers", "file": "models/fingers.md", "title": "Many fingers" }, diff --git a/book/src/chapters/front/preface.md b/book/src/chapters/front/preface.md index 16c9eb6..6a231dc 100644 --- a/book/src/chapters/front/preface.md +++ b/book/src/chapters/front/preface.md @@ -75,3 +75,5 @@ The book has five parts, and each opens with an introduction that surveys it. ::: note Sources The main sources are the splay tree paper [@sleator1985]; move-to-root [@allen1978]; Wilber's lower bounds [@wilber1989]; the greedy algorithm [@lucas1988; @munro2000]; Tango trees [@demaine2007]; the geometric view, GreedyASS and the online simulation [@demaine2009]; the comparison of BST models in Derryberry's thesis [@derryberry2009]; the lazy finger [@bose2016]; the weighted dynamic finger [@iacono2016]; the multi-finger simulation, ComboBST, tree buffers and snapshots [@demaine2013]; pop-tarts, heavy-path simulation and deamortization [@bose2012]; and the potential used in the scanning proof [@kakimura2026]. The [bibliography](bibliography.html) lists every work cited, and each part ends with bibliographic notes on who proved what, and when. ::: + +[Real-world BST implementations](real-world.html) separates bounded-memory, charged computation from the abstract online models. diff --git a/book/src/chapters/models/part-models.md b/book/src/chapters/models/part-models.md index 766b627..d225f88 100644 --- a/book/src/chapters/models/part-models.md +++ b/book/src/chapters/models/part-models.md @@ -44,3 +44,7 @@ The table lists every correspondence, with $m$ requests, $n$ keys, $R$ rotations | online geometric algorithm | online BST algorithm | $R \le 6018\,(\text{points} + n)$ | any initial tree | [[Geometric.Equivalence.Results.online_bst\|online_bst]] | Two consequences shape the rest of the book. Bounds can be stated in whichever model is most convenient and moved to the others at a constant cost: [Part II](part-bounds.html) states its sequence bounds for rotation-model algorithms, and Wilber's lower bound in [Chapter 11](wilber.html) is proved on point sets. And an algorithm can be designed in whichever model is most convenient: splaying ([Chapter 13](splay.html)) is a rotation algorithm, GreedyASS ([Chapter 16](greedy.html)) is a geometric one, and Tango ([Chapter 19](tango.html)) maintains a tree whose edges are marked by preferred paths. + +## Implementations with bounded workspace + +[Real-world BST implementations](real-world.html) adds finite control, fixed-width registers and node metadata, and charged scalar computation. It distinguishes a full-prefix online rule from a bounded-memory implementation of that rule. Its projection theorem recovers legal pointer traces; termination and proportional runtime remain algorithm-specific proof obligations. diff --git a/book/src/chapters/models/real-world.md b/book/src/chapters/models/real-world.md new file mode 100644 index 0000000..fb2e558 --- /dev/null +++ b/book/src/chapters/models/real-world.md @@ -0,0 +1,218 @@ +# Real-world BST implementations + +An online BST algorithm may use the entire request prefix when selecting its next operations. The interface in [Online algorithms](online.html) permits this explicitly: `Algorithm.step` receives the history. Only BST operations are charged. That mathematical model is useful for competitive analysis, but it does not bound the memory or computation used to select those operations. + +Bose, Collette, Fagerberg and Langerman distinguish this from a real-world implementation in the opening model discussion of *De-amortizing Binary Search Trees* [-@bose2012]. Such an implementation uses a pointer machine, a constant number of words per node, constant global workspace, and time proportional to its BST operations. Theorem 7 asks that the transformation preserve these additional properties. + +## A finite-control word machine + +`RealWorld.Machine` specifies a fixed finite instruction table. Its parameters are the number of metadata words per node, scalar registers, and code locations. These are fixed independently of the tree size, input sequence, and word width. Constants in instructions are fixed natural literals interpreted modulo the word size. Instructions contain no arbitrary Lean callbacks. + +`RealWorld.State` contains the labelled tree with its persistent finger, the scalar registers, the current request, a visited flag, and the program counter. Each node has an immutable key and a fixed vector of mutable words. Words are `BitVec width`; addition and subtraction wrap modulo $2^{\mathit{width}}$. A comparison is unsigned. `WordSize` requires enough bits to represent keys and addresses and an $O(\log(n+1))$ upper bound, uniformly in $n$. + +The instruction set includes register constants, copies, arithmetic, conditional branches, reading the current request and current node's key, loading and storing metadata at the finger, and the six existing pointer moves and rotations. An explicit `mark` instruction succeeds only when the finger's stored key equals the current request. A response can finish only after that mark. There is no direct access to another node's metadata by an arbitrary integer address. The RAM-like arithmetic is on the fixed register file; tree access remains local to the finger. + +Every instruction costs one machine step. Only a pointer move or rotation also costs one BST operation. Invalid moves and failed checks have no successful successor; termination and successful service must be proved for an algorithm. + +The semantic cursor uses a zipper to describe a linked tree and its finger. This is a mathematical representation, not a charged runtime stack. The storage convention is three links, a key and the metadata words per node, plus the fixed registers, root/finger/query words and a flag. Finite control is separate. The concrete representation and compiler below implement this semantic machine on a pointer machine. This does not assert that arbitrary Lean evaluation has the same runtime. + +@decl RealWorld.Node RealWorld.Instruction RealWorld.Machine RealWorld.State RealWorld.eval RealWorld.tick + +## Online input and resumable state + +`accept` supplies one new key only when the machine is at a response boundary. It resets the visited flag and starts at the fixed entry location. The machine has no input-history field and cannot read future requests. It may retain information about earlier requests only in the bounded registers and node metadata. Its complete state also describes everything needed to resume an interrupted computation. + +`Responds` describes one completed access. `Execution` chains completed accesses; its request list and execution witnesses are specification data, inaccessible to instructions. The uniqueness theorem says that a completed prefix determines a unique state and both costs. The append theorem composes prefixes with continuations. Together these give the retained-state formulation of online causality. + +@decl RealWorld.accept RealWorld.lts RealWorld.Run RealWorld.Responds RealWorld.Execution + +## What must an implementation prove? + +`RealWorld.Implementation` packages a uniform program, a logarithmic word-width family, initial states satisfying `Initial`, and the total-service and runtime certificates. Its constants are outside the quantification over tree sizes. Initialization runtime remains a separate obligation. + +There are separate obligations: + +- Initialize a correctly ordered tree with the intended keys, charging setup separately. +- Prove `Total`: every existing key can be served after every completed valid history. +- Prove `EfficientFrom`: on states reachable from initialization, machine time per completed request is at most a fixed constant times its BST operations plus one. The request unit handles a key already under the finger. +- Use fixed code, field and register counts, and a word-width family satisfying `WordSize`. +- For a pointer-machine implementation, prove that the stored representation realizes these machine instructions and respects the same local-access discipline. + +The physical-trace theorem removes scalar and metadata instructions and yields a legal trace in the existing pointer model, with exactly the recorded BST cost. It does not identify stored keys with inorder ranks for an arbitrary malformed input: that requires the ordered-key initialization invariant. + +This is a model and a set of proof obligations, not a proof of Theorem 7. Applying this model to the pop-tart construction still requires a controller implementing this interface and a proof of proportional machine time. + +@decl RealWorld.Initial RealWorld.Total RealWorld.EfficientFrom RealWorld.WordSize RealWorld.Implementation RealWorld.storageWords + +## CSLib + +The semantic model above uses CSLib's `Cslib.LTS`. A second layer now connects +BST representations to the general Tarjan-style pointer machine from +[CSLib Frontier PR #5420](https://github.com/cslib-community/cslib-frontier/pull/5420), +pinned at commit `86efa56d47a44812fab049080fba87d7635db63b`. It uses that +library's instructions, heaps and charged execution directly. The existing +CSLib pin is retained; this adds a pinned Frontier dependency. + +## Concrete pointer-machine representation + +`RealWorld.PointerMachine.words` supplies modular words, literal/add/subtract +operations, and equality/order tests. Pointers occupy separate fields and +registers and cannot be obtained by arithmetic. The current layout has three +pointer registers, two scalar registers, two child links per record, one key, +and a fixed number of metadata words. Addresses in the labelled specification +tree are ghost labels, not scalar values exposed to the program. + +`Represents` relates an actual heap to a labelled tree. `Boundary` additionally +requires distinct node addresses, an ordered key tree, valid pointers, the +root under the cursor, and exact coverage of the allocated heap by the tree. +Consequently, no separate work heap is hidden in this boundary invariant. + +@decl RealWorld.PointerMachine.words RealWorld.PointerMachine.layout RealWorld.PointerMachine.Represents RealWorld.PointerMachine.Boundary + +The concrete online protocol accepts one key in a designated register and +restarts at a fixed entry label, preserving all other state. `Responds` +requires a halted starting state, a charged execution to halt, and a witnessed +visit to a record holding the requested key during that execution. `Execution` +chains responses. The history and visit witnesses are specification objects, +not extra runtime storage. Prefix determinism follows from the upstream +machine's deterministic execution. + +@decl RealWorld.PointerMachine.Protocol RealWorld.PointerMachine.accept RealWorld.PointerMachine.Responds RealWorld.PointerMachine.Execution RealWorld.PointerMachine.Results.causal + +A child navigation is one pointer-load instruction. A root right rotation is +five instructions: load the left child, load its right subtree, replace the +old root's left link, replace the child's right link, and move the cursor to +the new root. A standalone program additionally charges one instruction for +halt. The rotation theorem preserves the complete boundary invariant and +exact heap length, for arbitrary subtrees and metadata. Its structural change +is exactly the existing down-left followed by rotate-left-child operations. + +@decl RealWorld.PointerMachine.down RealWorld.PointerMachine.rotateRight RealWorld.PointerMachine.Results.navigation_time RealWorld.PointerMachine.Results.navigation RealWorld.PointerMachine.Results.rotation_time RealWorld.PointerMachine.Results.rotation RealWorld.PointerMachine.Results.rotation_bst + +The two-child representation above remains a small introductory example. +The following representation adds the parent links needed for all six +primitives. + +## Parent-linked trees and all six primitives + +`RealWorld.Linked.layout` has seven pointer registers: cursor, root, parent, +grandparent, middle subtree, null, and a comparison temporary. It has a fixed scalar register file and three pointer fields per record (left, right, parent), +plus the key and a fixed number of metadata words. These counts are independent +of tree size and access history. The programs use only pointer instructions; +they do not compute numeric addresses. + +`Realizes` relates an actual machine state to a labelled cursor anywhere in +the BST. Its recursive focus and context predicates check both directions of +every tree edge, including the null parent of the root. It also checks pointer +validity, the root register, distinct addresses, ordered keys, and exact +coverage of the heap by the tree. Labels retain every data field, so preserving +the represented labels preserves metadata as well as keys. The context is a +proof-only zipper; it is not a runtime stack. + +@decl RealWorld.Linked.layout RealWorld.Linked.node RealWorld.Linked.Represents RealWorld.Linked.Context RealWorld.Linked.Realizes + +The two downward moves load the corresponding child field. Both upward moves +load the parent field; their abstract legality distinguishes the left and right +cases. Each navigation executes one load followed by halt, for two charged +instructions. + +Each rotation promotes the cursor above its parent while leaving the cursor +on the promoted node. The program repairs the transferred middle subtree's +parent link, both pivot nodes, and the grandparent's appropriate child link. +When there is no grandparent it updates the root register instead. Stores +through a null middle-subtree pointer have no effect, as specified by the +upstream machine. Both directions use fixed code and terminate within nineteen +charged instructions, including halt; this is a conservative uniform bound. + +@decl RealWorld.Linked.move RealWorld.Linked.rotate RealWorld.Linked.program RealWorld.Linked.start + +The primitive simulation theorem states that **every legal one-step operation +of the existing labelled-cursor model has a concrete pointer-machine execution** +within that bound. The resulting state realizes exactly the resulting cursor, +and the heap has exactly the same number of records. The theorem covers every +cursor depth, both grandparent child positions, root rotations, empty and +nonempty middle subtrees, and arbitrary metadata. + +@decl RealWorld.Linked.Results.primitive + +Regressions include a fully verified seven-node starting representation, +non-root rotations in both directions with nonempty middle subtrees, root +register repair, parent links, and metadata preservation. + +## Compiling the complete controller + +`RealWorld.Compiler.compile` translates the entire finite `RealWorld.Machine` +into **one pointer-machine program**. It supports every source instruction: +constants, copies, addition and subtraction, comparisons, key and query reads, +metadata loads and stores, all six BST primitives, visit marking and finish. +Each source instruction occupies a block of twenty-four code slots. Internal +branches in a BST primitive are relocated; its final halt becomes a charged +jump to the next source instruction. There is no free per-operation restart +or external instruction-selection oracle. + +The target has seven pointer registers and $r+4$ scalar registers: the source +registers plus current request, visited flag, key temporary and zero temporary. +It retains the same tree records, with three links, the key and $f$ metadata +words each. The program has exactly $24l+4$ slots for a source with $l$ labels, +independently of the number of nodes and requests. Padding and failed checks +lead to a nonhalting trap; the program has one successful halt. + +@decl RealWorld.Compiler.Target RealWorld.Compiler.block RealWorld.Compiler.relocate RealWorld.Compiler.compile RealWorld.Compiler.Results.code_size + +Input is accepted only at that successful halt. The external input operation +replaces the designated request register and enters the request-entry routine. +Resetting the visited flag and jumping to the source entry are two charged +instructions. Marking a visit reads the current node's key and compares it +with the request. Finish checks the stored visited flag before reaching halt. +Registers and tree storage persist between requests. + +@decl RealWorld.Compiler.accept RealWorld.Compiler.Responds RealWorld.Compiler.Execution + +`Image` is the full source/target invariant. It combines the parent-linked +representation with equality of user registers and request, encoding of the +visited flag, and translation of the program counter. Addresses and execution +histories occur only in the specification. The theorem assumes a represented +nonempty tree and a positive word width; the latter distinguishes the stored +zero and one used for the visited flag. + +@decl RealWorld.Compiler.decode RealWorld.Compiler.Image + +For a successful source request taking $T$ semantic machine steps, the same +compiled program completes the request in at most $19T+3$ pointer-machine +instructions. The three extra instructions account for request entry and +final halt. For a sequence of $m$ requests with total source time $T$, the +bound is $19T+3m$. The target endpoint represents the exact source endpoint, +including its cursor and metadata. Concrete successful responses have unique +endpoints and exact instruction counts. + +@decl RealWorld.Compiler.Results.response RealWorld.Compiler.Results.execution RealWorld.Compiler.Results.deterministic + +Consequently, a source certificate $T\le C(k+1)$, where $k$ is its BST work, +transfers to target time at most $(19C+3)(k+1)$. The compiler does not establish +that source certificate by itself. Separately, every compiled execution, +including prefixes and trap loops, preserves the exact record count: compiled +code contains no allocation instruction. + +@decl RealWorld.Compiler.Results.proportional_time RealWorld.Compiler.Results.storage + +The regression controller serves two different keys using the same compiled +program, exercises scalar arithmetic and metadata access, and returns to the +root between requests. Additional cases check both relocated rotation +directions and confirm that an unmarked finish or a mismatched mark cannot +reach the successful halt in those examples. Its initial source/target image +is proved explicitly; the examples are evaluated by Lean's kernel. + +## Remaining implementation obligations + +The compiler gives a forward simulation of successful source executions from +a supplied source/target image. It does not construct or charge an initial +heap, handle an empty-tree image, or prove termination for arbitrary source +controllers. Initialization, the source word-size discipline, total service, +and source proportional-time certificates remain obligations of each +algorithm. Intermediate field writes during a rotation need not represent a +complete tree; the simulation invariant holds at source-instruction boundaries. + +Theorem 7 and the ComboBST implementation-preservation clauses still require +concrete finite controllers for their constructions and the corresponding +algorithm-specific storage and runtime proofs. The compiler now supplies the +machine-level connection for those controllers. diff --git a/docs/organization.md b/docs/organization.md index c7712e7..c3cc33e 100644 --- a/docs/organization.md +++ b/docs/organization.md @@ -736,3 +736,70 @@ results: the bottom-up policy's bound `run + m ≤ 42n + F(R + m)` `2n` reset (`Policy.rotation_algorithm`). Regression examples: `RotationBSTTests/TangoLinear.lean`. The book chapter `algorithms/tango-linear.md` still composes the two by hand. + +## Real-world implementation model + +`Models/RealWorld/Abstract.lean` exposes a finite-control register-and-pointer +machine, its CSLib LTS, and physical-trace and prefix-causality theorems. +`Definitions/Abstract.lean` fixes the primitive instruction set, word-size +policy, storage convention, and separate total-service and proportional-time +obligations. The book introduces it in Models, after the pointer machine. +The compiler below supplies concrete pointer-machine lowering. The paper-level +transformation theorems remain separate work; no existing finite-word component +is automatically certified in this model. + + +### Concrete pointer-machine foundation + +`Models/RealWorld/PointerMachine/Definitions/Abstract.lean` defines bounded-word +instances of the pinned CSLib Frontier pointer machine, heap/tree representation, +exact-node boundary invariants, and incremental request semantics. `Proofs.lean` +contains prefix determinism, navigation, and instruction-count proofs; +`Rotation.lean` proves root right rotation preserves the complete boundary. +`Abstract.lean` exposes the audited results. Regression examples live in +`RotationBSTTests/PointerMachineBST.lean`. + +This introductory concrete layout has two child fields and no parent links. +The parent-linked layer below supplies upward navigation, both rotation +directions and non-root reconnection. The compiler then lowers complete semantic +controllers; the paper-level implementation theorems remain open. + + +### Parent-linked primitive simulation + +`Models/RealWorld/Linked/Definitions/Abstract.lean` extends the concrete machine +with three link fields, a root register, and a complete representation at an +arbitrary labelled cursor. `Navigation.lean` proves all four moves; +`Execution.lean` supplies bounded upstream execution; `Heap.lean`, +`Rotation.lean`, `Preservation.lean`, and `Refinement.lean` prove both rotations +through arbitrary ancestor contexts. `Simulation.lean` assembles the six cases. +The audited entry point is `Linked.Results.primitive` in `Abstract.lean`. +Every primitive preserves the full representation and exact node count, with +a bound of nineteen instructions including halt. The original two-child layer +remains an introductory example rather than being silently strengthened. + +`RotationBSTTests/LinkedBST.lean` checks a non-vacuous full representation, +all navigation opcodes, non-root left/right rotations with transferred +subtrees, root register repair, and metadata preservation. The compiler layer +below supplies complete controller compilation, including charged dispatch and +online interaction. + + +### Complete finite-controller compiler + +`Models/RealWorld/Compiler/Definitions/Abstract.lean` defines the single-program +compiler, address-labelled source/target image, and concrete request protocol. +`Relocation` and `Code` certify block placement; `Representation`, `Metadata`, +`Scalar`, `Primitive`, `Branch`, `Boundaries`, and `Step` prove all instruction +cases; `Online` composes ticks into requests and sequences. `Space` proves +exact record-count preservation and transfers proportional-time constants. +The audited results are in `Compiler/Abstract.lean`. + +Linked primitives now permit any fixed scalar-register count, allowing the +compiler to use the source register file plus four private scalar registers. +The pointer registers and link fields are unchanged. The compiled program has +24 slots per source instruction plus four protocol slots. Successful requests +cost at most 19 times source machine time plus three, including entry and halt. +Theorems assume positive word width and an initial image with a nonempty tree; +initial-heap construction and its cost remain separate. Regression tests are +in `RotationBSTTests/CompiledBST.lean`. diff --git a/lake-manifest.json b/lake-manifest.json index 59dd857..f8a517f 100644 --- a/lake-manifest.json +++ b/lake-manifest.json @@ -1,7 +1,17 @@ {"version": "1.3.0", "packagesDir": ".lake/packages", "packages": - [{"url": "https://github.com/leanprover/cslib", + [{"url": "https://github.com/cslib-community/cslib-frontier", + "type": "git", + "subDir": null, + "scope": "", + "rev": "86efa56d47a44812fab049080fba87d7635db63b", + "name": "«cslib-frontier»", + "manifestFile": "lake-manifest.json", + "inputRev": "86efa56d47a44812fab049080fba87d7635db63b", + "inherited": false, + "configFile": "lakefile.toml"}, + {"url": "https://github.com/leanprover/cslib", "type": "git", "subDir": null, "scope": "", diff --git a/lakefile.toml b/lakefile.toml index 2a10499..44e377e 100644 --- a/lakefile.toml +++ b/lakefile.toml @@ -10,6 +10,11 @@ name = "cslib" git = "https://github.com/leanprover/cslib" rev = "254e30e6d4299c51323aaeaf5f51a4763b375d4a" +[[require]] +name = "cslib-frontier" +git = "https://github.com/cslib-community/cslib-frontier" +rev = "86efa56d47a44812fab049080fba87d7635db63b" + [[lean_lib]] name = "RotationBST"